def setController(self, node=None):
		# If controller already set, just add to that one. Otherwise assume a switch and delete old connections first
		if not node is None:
			# TODO
			# Remove connections from previous (use category?)
			if self.controller:
				if self.dev: print '\n'
				self.deleteControllerAttributes()


			self.controller = node
			self.updateRigNode()


		if not hasAttr(self.controller, 'spaceSwitchRigNode'):
			addAttr(self.controller, ct=self.attrCategory, ln='spaceSwitchRigNode', at='message', k=self.dev)
		if not isConnected(self.rigNode.message, self.controller.spaceSwitchRigNode):
			self.rigNode.message.connect(self.controller.spaceSwitchRigNode)

		# if not hasAttr(self.controller, 'controlVis'):
		# 	addAttr(self.controller, ct=self.attrCategory, ln='controlVis', at='short', min=0, max=1, k=1, dv=self.dev)
		# self.controller.controlVis.connect(self.rigNode.controlVis)
		
		# if not hasAttr(self.controller, 'indicVis'):
		# 	addAttr(self.controller, ct=self.attrCategory, ln='indicVis', at='short', min=0, max=1, k=1, dv=self.dev)
		# self.controller.indicVis.connect(self.rigNode.indicVis)

		
		# enumName = addAttr(self.enumAttrA, q=1, enumName=1)
		enumName = self.enumAttrA.getEnums()
		enumAttrAName = self.enumAttrA.longName()
		enumAttrBName = self.enumAttrB.longName()

		if not hasAttr(self.controller, enumAttrAName):
			utils.cbSep(self.controller, ct=self.attrCategory)
			addAttr(self.controller, ct=self.attrCategory, ln=enumAttrAName, at='enum', enumName='0:1', k=1)
		self.controller.attr(enumAttrAName).setEnums(enumName)

		if not hasAttr(self.controller, enumAttrBName):
			addAttr(self.controller, ct=self.attrCategory, ln=enumAttrBName, at='enum', enumName='0:1', dv=1, k=1)
		self.controller.attr(enumAttrBName).setEnums(enumName)


		blendAttrName =self.blendAttr.longName()
		if not hasAttr(self.controller, blendAttrName):
			addAttr(self.controller, ct=self.attrCategory, ln=blendAttrName, min=0, max=1, dv=self.dev, k=1)
		

		self.controllerEnumAttrA = self.controller.attr(enumAttrAName)
		self.controllerEnumAttrB = self.controller.attr(enumAttrBName)
		self.controllerBlendAttr = self.controller.attr(blendAttrName)
		
		if not isConnected(self.controllerEnumAttrA, self.enumAttrA):
			self.controllerEnumAttrA.connect(self.enumAttrA)
		if not isConnected(self.controllerEnumAttrB, self.enumAttrB):
			self.controllerEnumAttrB.connect(self.enumAttrB)
		if not isConnected(self.controllerBlendAttr, self.blendAttr):
			self.controllerBlendAttr.connect(self.blendAttr)
示例#2
0
def boxRig():
	'''creates a useful control for blendshapes, with attributes for adjusting size and result values built in.'''
	rigGroup = createNode('transform', n=names.get('rigGroup', 'rnm_rigGroup'))
	rb.cbSep(rigGroup)
	addAttr(rigGroup, ln='boxVis', at='short', min=0, max=1, dv=1)
	rigGroup.boxVis.set(cb=1)

	compAttrs = [
	'minBounds',
	'maxBounds',
	'newMinBounds',
	'newMaxBounds',
	'outputPos',
	'outputNeg'
	]

	for attribute in compAttrs:
		rb.cbSep(rigGroup)
		addAttr(rigGroup, ln=attribute, at='compound', numberOfChildren=3, k=1)
		addAttr(rigGroup, ln='%sX' % attribute, at='float', p=attribute, k=1)
		addAttr(rigGroup, ln='%sY' % attribute, at='float', p=attribute, k=1)
		addAttr(rigGroup, ln='%sZ' % attribute, at='float', p=attribute, k=1)
示例#3
0
    def __init__(self, fitNode):
        self.dev = True
        try:
            # Initialize rigNode
            # Error Check:

            # Convert string input to PyNode if neccessary
            if isinstance(fitNode, str):
                fitNode = ls(fitNode)[0]

            if fitNode.rigType.get() != 'lips':
                raise Exception('Incorrect rig type: %s' %
                                fitNode.rigType.get())

            jointsList = fitNode.jointsList.get()

            buildRig.rig.__init__(self, fitNode)

            # Move rigGroup
            xform(self.rigGroup, ws=1, m=xform(jointsList[0], q=1, ws=1, m=1))

            # fitNode attributes

            inbetweenJoints = 2
            if hasAttr(self.fitNode, 'inbetweenJoints'):
                inbetweenJoints = self.fitNode.inbetweenJoints.get()
            numJointsList = [int(inbetweenJoints + 1), int(inbetweenJoints)]

            shapes = fitNode.shapes.get()

            # Mirroring
            mirror = False
            # if self.fitNode.side.get() == 2:
            # 	mirror=True
            # else:
            # 	mirror=False

            # if self.fitNode.mirror.get() is False:
            # 	mirror=False

            # Per joint mirroring
            mirrorList = []
            for jnt in jointsList:
                if jnt.autoMirror.get() is False:
                    mirrorList.append(False)
                elif jnt.side.get() == 2:
                    mirrorList.append(True)
                else:
                    mirrorList.append(False)

            self.crvs = []
            # Naming
            self.globalName = fitNode.globalName.get()

            self.subNames = []
            # for node in jointsList:
            # self.subNames.append(node.nodeName())
            subAttrs = listAttr(self.fitNode, st='subName*')
            for subAttr in subAttrs:
                self.subNames.append(self.fitNode.attr(subAttr).get())
            print 'subnames:'
            print self.subNames

            self.naming(0)
            self.names = utils.constructNames(self.namesDict)

            # ========================= RigNode Attributes =========================
            self.rigNode.rigType.set('lips', l=1)

            utils.cbSep(self.rigNode)

            addAttr(self.rigNode,
                    ct='publish',
                    ln='tangentCtrlsVis',
                    min=0,
                    max=1,
                    dv=0,
                    at='short',
                    k=1)
            setAttr(self.rigNode.tangentCtrlsVis, k=0, cb=1)

            addAttr(self.rigNode,
                    ct='publish',
                    ln='offsetsCtrlsVis',
                    min=0,
                    max=1,
                    dv=0,
                    at='short',
                    k=1)
            setAttr(self.rigNode.offsetsCtrlsVis, k=0, cb=1)

            utils.cbSep(self.rigNode)
            addAttr(self.rigNode,
                    ln='upAxis',
                    at='enum',
                    enumName='Y=1:Z=2',
                    dv=1,
                    k=1)

            addAttr(self.rigNode,
                    ln='tangentsDistanceScaling',
                    softMinValue=0,
                    softMaxValue=1,
                    dv=0.5,
                    k=1)

            # ========================= Vis Mults =========================
            # allVis Mults

            debugVisMult = createNode('multDoubleLinear',
                                      n=self.names.get('debugVisMult',
                                                       'rnm_debugVisMult'))
            self.debugVis = debugVisMult.o
            self.rigNode.allVis >> debugVisMult.i1
            self.rigNode.debugVis >> debugVisMult.i2
            self.step(debugVisMult, 'debugVisMult')

            tangentVisMult = createNode('multDoubleLinear',
                                        n=self.names.get(
                                            'tangentVisMult',
                                            'rnm_tangentVisMult'))
            self.tangentVis = tangentVisMult.o
            self.rigNode.allVis >> tangentVisMult.i1
            self.rigNode.tangentCtrlsVis >> tangentVisMult.i2
            self.step(tangentVisMult, 'tangentVisMult')

            offsetsVisMult = createNode('multDoubleLinear',
                                        n=self.names.get(
                                            'offsetsVisMult',
                                            'rnm_offsetsVisMult'))
            self.offsetsVis = offsetsVisMult.o
            self.rigNode.allVis >> offsetsVisMult.i1
            self.rigNode.offsetsCtrlsVis >> offsetsVisMult.i2
            self.step(offsetsVisMult, 'offsetsVisMult')

            # ========================= World Group =========================
            worldGroup = createNode('transform',
                                    n=self.names.get('worldGroup',
                                                     'rnm_worldGroup'),
                                    p=self.rigGroup)
            self.worldGroup = worldGroup
            self.step(worldGroup, 'worldGroup')
            worldGroup.inheritsTransform.set(0)
            xform(worldGroup, rp=[0, 0, 0], ro=[0, 0, 0], ws=1)

            controlGroup = createNode('transform',
                                      n=self.names.get('controlGroup',
                                                       'rnm_controlGroup'),
                                      p=self.rigGroup)
            self.step(controlGroup, 'controlGroup')

            self.lipCtrls = []
            # For each joint, create a control
            for i, jnt in enumerate(jointsList):

                lipCtrl = self.createControlHeirarchy(
                    transformSnap=jnt,
                    selectionPriority=0,
                    mirrorStart=mirrorList[i],
                    mirror=mirrorList[i],
                    name=self.names.get('lipCtrl', 'rnm_lipCtrl'),
                    shape=shapes[i],
                    par=controlGroup,
                    ctrlParent=controlGroup,
                    jntBuf=False)

                self.lipCtrls.append(lipCtrl)

            baseLipJnt, leftLipJnt, topLipJnt, rightLipJnt, botLipJnt = jointsList  # TODO: determine in some other way?
            baseLipCtrl, leftLipCtrl, topLipCtrl, rightLipCtrl, botLipCtrl = self.lipCtrls  # TODO: determine in some other way?

            #=========================== Bezier Setup =================================

            jointGroupings = [[leftLipJnt, topLipJnt, rightLipJnt],
                              [leftLipJnt, botLipJnt, rightLipJnt]]
            ctrlGroupings = [[leftLipCtrl, topLipCtrl, rightLipCtrl],
                             [leftLipCtrl, botLipCtrl, rightLipCtrl]]
            bezierRigGroups = []
            crvs = []
            for i in range(2):
                bezierRigGroup = self.buildBezierSetup(
                    transforms=jointGroupings[i],
                    ctrlTransforms=ctrlGroupings[i],
                    follow=False,
                    twist=True,
                    bias=False,
                    twistAxisChoice=0,
                    doNeutralize=True,
                    mirror=False,
                    bezChain=True,  # ?
                )
                self.rigNode.tangentsDistanceScaling.connect(
                    bezierRigGroup.tangentsDistanceScaling)
                bezierRigGroups.append(bezierRigGroup)
                crvs.append(bezierRigGroup.curve.get())

                for ctrl in self.bendCtrls:
                    ctrl.neutralize.set(1)
                    ctrl.magnitude.set(1)

            print crvs
            # =========================== CurvePath =================================
            # create a result curve based on the postion on both curve inputs

            # blendCurve0 = duplicate(crvs[0], n=self.names.get('blendCurve0', 'rnm_blendCurve0'), rc=True)
            # self.step(blendCurve0, 'blendCurve0')

            # curveBS = blendShape(crvs[1], crvs[0])

            # raise

            # =========================== CurvePath Rig =================================
            crvPathRigs = []
            for i in range(2):

                crvPathRig = self.buildCurvePartitionsSetup(
                    crvs[i],
                    partitionParams=bezierRigGroups[i].uValues.get(),
                    numJointsList=numJointsList,
                    mirror=False,
                    createOffsetControls=True,
                    rotationStyle='curve',
                    twist=True)
                crvPathRigs.append(crvPathRig)
                results = crvPathRig.results.get()
                self.offsetsVis.connect(crvPathRig.v)
                for j in range(3):
                    bezierRigGroups[i].attr('uValues%s' % j).connect(
                        crvPathRig.attr('partitionParameter%s' % j))

                print 'LEN'
                print len(self.twistAdds)
                print len(self.bendCtrls)
                for i in range(len(self.bendCtrls)):
                    print '\n%s' % i
                    # addAttr(self.bendCtrls[i], ln='twist', k=1)

                    rangeStart = True if i == 0 else False
                    rangeEnd = True if i == (len(self.bendCtrls) -
                                             1) else False

                    if not rangeEnd:
                        self.bendCtrls[i].twist.connect(
                            self.twistAdds[i].input2D[0].getChildren()[0])
                    if not rangeStart:
                        self.bendCtrls[i].twist.connect(
                            self.twistAdds[i - 1].input2D[0].getChildren()[1])

                    if not rangeEnd:
                        self.socket(self.bendCtrls[i]).twist.connect(
                            self.twistAdds[i].input2D[1].getChildren()[0])
                    if not rangeStart:
                        self.socket(self.bendCtrls[i]).twist.connect(
                            self.twistAdds[i - 1].input2D[1].getChildren()[1])

                for i, res in enumerate(results):

                    # Create a bind joint for each result transform (special naming for midJoints)

                    self.naming(n=i)
                    self.names = utils.constructNames(self.namesDict)

                    if mirror:
                        res.scaleZ.set(-1)
                        res.rotateZ.set(180)

                    bind = createNode('joint',
                                      n=self.names.get('bind', 'rnm_bind'),
                                      p=res)
                    self.step(bind, 'bind')
                    # xform(bind, ws=1, ro=xform(jointsList[0], q=1, ws=1, ro=1))
                    self.bindList.append(bind)
                    bind.rotate.set(0, 0, 0)
                    bind.jointOrient.set(0, 0, 0)
                    # bind.attr('type').set(18)
                    # bind.otherType.set('%s' % i)
                    # bind.drawLabel.set(1)
                    bind.hide()

        #=========================== Finalize =================================
        finally:
            try:
                self.setController(bezierRigGroups[0], self.rigGroup)
                self.setController(bezierRigGroups[1], self.rigGroup)
                self.setController(crvPathRig, self.rigGroup)
            except:
                pass
            try:
                self.constructSelectionList(selectionName='bendCtrls',
                                            selectionList=self.bendCtrls)
                self.constructSelectionList(selectionName='tangentCtrls',
                                            selectionList=self.tangentCtrls)
                self.constructSelectionList(selectionName='offsetCtrls',
                                            selectionList=self.offsetCtrls)
                self.constructSelectionList(selectionName='frozenNodes',
                                            selectionList=self.freezeList)
            except:
                pass

            self.finalize()
示例#4
0
	def __init__(self, fitNode=None, rigNode=None):

		if fitNode is None and rigNode is None:
			raise Exception('No data specified.')

		elif fitNode is None:
			self.rigNode = rigNode
			# Put any attributes needed for initialized rigs here

		else:
			try:
				# Initialize rigNode
				# Error Check:
				
				# Convert string input to PyNode if neccessary
				if isinstance(fitNode, str):
					fitNode = ls(fitNode)[0]

				if fitNode.rigType.get() != 'bezierIK':
					raise Exception('Incorrect rig type: %s' % fitNode.rigType.get())

				self.crvs = []

				buildRig.rig.__init__(self, fitNode)



				# fitNode attributes
				doFK = False
				doOffsetFK = False # end joint orient failure
				doParametric = True
				doSplineIK = False
				# 
				doStretchLimit = False
				# 
				doVolume = False

				doStretchLimit = self.fitNode.stretchLimits.get()

				style = self.fitNode.style.get(asString=True)
				if style == 'FK Only':
					doSplineIK = False
					doParametric = False
				elif style == 'IK Only':
					doFK = False
					if doStretchLimit:
						doSplineIK = True
				elif style == 'IK to FK' or style == ' IK to FK':
					doFK = True
					doOffsetFK = True
					if doStretchLimit:
						doSplineIK = True
				else:
					doFK=True
					doSplineIK = True
					doParametric = True

				# if doFK:
				# 	raise Exception(style)


				if not all([doParametric, doSplineIK]):
					doStretchLimit = False
				if not doFK:
					doOffsetFK = False

				jointsList = 	self.fitNode.jointsList.get()
				numJoints = 	self.fitNode.resultPoints.get()+1
				pointInput = 	self.fitNode.outputJoints.inputs()[:self.fitNode.resultPoints.get()+2]

				fkShapes = 		self.fitNode.fkShapes.get()
				ikShapes = 		[self.fitNode.startShape.get(), self.fitNode.endShape.get()]

				tan1 =			self.fitNode.tangent1.get()
				tan2 =			self.fitNode.tangent2.get()

				orientation = self.fitNode.orientation.get(asString=True)

				bindEnd = False

				doBind = 		self.fitNode.bind.get()

				if not doBind:
					bindEnd = False


				# Mirroring
				if self.fitNode.side.get() == 2:
					mirror=True
				else:
					mirror=False

				if self.fitNode.mirror.get() is False:
					mirror=False

				# Move rigGroup
				xform(self.rigGroup, ws=1, m=xform(jointsList[0], q=1, ws=1, m=1))

				# Naming
				self.globalName = self.fitNode.globalName.get()
				self.subNames = []
				subAttrs = listAttr(self.fitNode, st='subName*')
				for subAttr in subAttrs:
					self.subNames.append(self.fitNode.attr(subAttr).get())

				# NAMING
				self.naming(0)
				self.names = utils.constructNames(self.namesDict)



				# ========================= RigNode Attributes =========================
				self.rigNode.rigType.set('bezier', l=1)

				
				utils.cbSep(self.rigNode)

				if doFK and not doOffsetFK:
					addAttr(self.rigNode, ct='publish', k=1, dv=0, min=0, max=1, ln='fkIk', nn='FK/IK')
					utils.cbSep(self.rigNode, ct='publish')
					addAttr(self.rigNode, ct='publish', ln='autoVis', nn='FK/IK Auto Vis', at='short', min=0, max=1, dv=1)
					setAttr(self.rigNode.autoVis, keyable=False, channelBox=True)
				if doFK:
					addAttr(self.rigNode, ct='publish', ln='fkVis', nn='FK Vis', at='short', min=0, max=1, dv=1)
					setAttr(self.rigNode.fkVis, keyable=False, channelBox=True)
				
				addAttr(self.rigNode, ct='publish', ln='ikVis', nn='IK Vis', at='short', min=0, max=1, dv=1)
				setAttr(self.rigNode.ikVis, keyable=False, channelBox=True)
				

			
				if doParametric or doSplineIK:
					addAttr(self.rigNode, ct='publish', ln='offsetCtrlsVis', at='short', min=0, max=1, dv=0, k=1)
					setAttr(self.rigNode.offsetCtrlsVis, keyable=False, channelBox=True)

				utils.cbSep(self.rigNode, ct='publish')
				# addAttr(self.rigNode, ln='bendCtrlsVis', nn='Bend Ctrl Vis', at='short', min=0, max=1, dv=1, k=1)
				# setAttr(self.rigNode.bendCtrlsVis, k=0, cb=1)

				addAttr(self.rigNode, ct='publish', ln='tangentCtrlsVis', min=0, max=1, dv=0, at='short', k=1)
				setAttr(self.rigNode.tangentCtrlsVis, k=0, cb=1)

				addAttr(self.rigNode, ln='tangentsDistanceScaling', softMinValue=0, softMaxValue=1, dv=0.5, k=1)
				
				# addAttr(self.rigNode, ln='neutralizeAll', min=0, max=1, dv=1, k=1)

				if doStretchLimit:
					utils.cbSep(self.rigNode, ct='publish')
					addAttr(self.rigNode, ct='publish', ln='stretch', softMinValue=0, softMaxValue=1, dv=1, k=1)
					addAttr(self.rigNode, ct='publish', ln='squash', softMinValue=0, softMaxValue=1, dv=1, k=1)
					addAttr(self.rigNode, ct='publish', ln='restLength', min=0.01, dv=1, k=1)
					# addAttr(self.rigNode, ln='currentNormalizedLength', dv=0)
					# self.rigNode.currentNormalizedLength.set(k=0, cb=1)
				if doVolume:
					utils.cbSep(self.rigNode, ct='publish')
					addAttr(self.rigNode, ct='publish', ln='volume', min=0, max=1, dv=0.5, keyable=True)
				
				if not hasAttr(self.rigNode, 'upAxis'):
					utils.cbSep(self.rigNode)
					addAttr(self.rigNode,ln='upAxis', at='enum', enumName='Y=1:Z=2', dv=1, k=1)

				# ========================= Vis Mults =========================
				# allVis Mults
				ikVisMult = createNode('multDoubleLinear', n=self.names.get('ikVisMult', 'rnm_ikVisMult'))
				self.rigNode.allVis >> ikVisMult.i1
				self.rigNode.ikVis >> ikVisMult.i2
				self.step(ikVisMult, 'ikVisMult')
				self.ikVis = ikVisMult.o

				if doFK:
					fkVisMult = createNode('multDoubleLinear', n=self.names.get('fkVisMult', 'rnm_fkVisMult'))
					self.rigNode.allVis >> fkVisMult.i1
					self.rigNode.fkVis >> fkVisMult.i2
					self.step(fkVisMult, 'fkVisMult')
					self.fkVis = fkVisMult.o

				debugVisMult = createNode('multDoubleLinear', n=self.names.get('debugVisMult', 'rnm_debugVisMult'))
				self.debugVis = debugVisMult.o
				self.rigNode.allVis >> debugVisMult.i1
				self.rigNode.debugVis >> debugVisMult.i2
				self.step(debugVisMult, 'debugVisMult')

				if doFK and not doOffsetFK:
					#=================== FK/IK Autovis Setup =========================
					self.sectionTag = 'fkIkAutoVis'

					fkIkAutoMult = createNode('multDoubleLinear', n=self.names.get('fkIkAutoMult', 'rnm_fkIkAutoMult'))
					self.rigNode.allVis >> fkIkAutoMult.i1
					self.rigNode.autoVis >> fkIkAutoMult.i2
					self.step(fkIkAutoMult, 'fkIkAutoMult')

					fkCond = createNode('condition', n=self.names.get('fkCond', 'rnm_fkCond'))
					fkCond.operation.set(4)
					fkCond.secondTerm.set(0.9)
					fkCond.colorIfTrue.set(1,1,1)
					fkCond.colorIfFalse.set(0,0,0)
					connectAttr(self.rigNode.fkIk, fkCond.firstTerm)
					self.step(fkCond, 'fkCond')

					ikCond = createNode('condition', n=self.names.get('ikCond', 'rnm_ikCond'))
					fkCond.operation.set(4)
					fkCond.secondTerm.set(0.9)
					fkCond.colorIfTrue.set(1,1,1)
					fkCond.colorIfFalse.set(0,0,0)
					connectAttr(self.rigNode.fkIk, ikCond.firstTerm)
					self.step(ikCond, 'ikCond')

					fkAutoCond = createNode('condition', n=self.names.get('fkAutoCond', 'rnm_fkAutoCond'))
					self.fkVis = fkAutoCond.outColorR
					fkAutoCond.operation.set(0)
					fkAutoCond.secondTerm.set(1)
					connectAttr(fkIkAutoMult.o, fkAutoCond.firstTerm)
					connectAttr(fkCond.outColorR, fkAutoCond.colorIfTrueR)
					connectAttr(fkVisMult.o, fkAutoCond.colorIfFalseR)
					connectAttr(fkVisMult.o, fkAutoCond.colorIfFalseG)
					self.step(fkAutoCond, 'fkAutoCond')

					ikAutoCond = createNode('condition', n=self.names.get('ikAutoCond', 'rnm_ikAutoCond'))
					self.ikVis = ikAutoCond.outColorR
					ikAutoCond.operation.set(0)
					ikAutoCond.secondTerm.set(1)
					connectAttr(fkIkAutoMult.o, ikAutoCond.firstTerm)
					connectAttr(ikCond.outColorR, ikAutoCond.colorIfTrueR)
					connectAttr(ikVisMult.o, ikAutoCond.colorIfFalseR)
					connectAttr(ikVisMult.o, ikAutoCond.colorIfFalseG)
					self.step(ikAutoCond, 'ikAutoCond')

				# ========================= World Group =========================
				worldGroup = createNode('transform', n=self.names.get('worldGroup', 'rnm_worldGroup'), p=self.rigGroup)
				self.worldGroup = worldGroup
				self.ikVis.connect(self.worldGroup.v)

				self.step(worldGroup, 'worldGroup')
				worldGroup.inheritsTransform.set(0)
				xform(worldGroup, rp=[0,0,0], ro=[0,0,0], ws=1)


				#=========================== FK Setup =================================
				# if doFK:
				# 	fkGroup = self.buildFkSetup(shapes=[fkShapes[0]], transforms=[jointsList[0]], mirror=mirror)
					# for fkCtrl in self.fkCtrls:
					# 	fkCtrl.message.connect(self.rigNode.fkCtrl)

				#==========================================================================
				#=========================== Bezier Setup =================================
				bezierTransforms = []
				if str(orientation) == 'world':
					for trans in range(2):
						bezierTransforms.append(createNode('transform', p=[jointsList[0], jointsList[-1]][trans]))
						xform(bezierTransforms[trans], ro=[0,0,0], ws=1)

				twistAxisChoice = 0 # Get from fitNode
				if self.fitNode.orientation.get(asString=1) == 'world':
					twistAxisChoice = self.fitNode.orientChoice.get() # Get from fitNode
				
				bezierRigGroup = self.buildBezierSetup(
					transforms=[jointsList[0], jointsList[-1]],
					ctrlTransforms=bezierTransforms if bezierTransforms else None,
					defaultTangents=[[None, tan1], [tan2, None]],
					shapes=ikShapes,
					follow=False,
					twist=True,
					bias=False,
					twistAxisChoice=twistAxisChoice,
					mirror=mirror,
					# doStrength=True
					)
				self.ikVis.connect(bezierRigGroup.v)
				bezierRigGroup.controlsVis.set(1)

				if str(orientation) == 'world':
					delete(bezierTransforms)
				
				# Chest orientation
				endOriCtrlSS = buildRig.spaceSwitch(
					constraintType='orient',
					controller = self.bendCtrls[1],
					constrained= self.bendCtrls[1].const.get(),
					prefix = self.names.get('endOriCtrlSS', 'rnm_endOriCtrlSS'),
					p=self.rigGroup,
					# p=self.ssGroup,
					targets=[self.rigsGroup, self.bendCtrls[1].buf.get()],
					labels=['World', 'Parent'],
					offsets=True,
					)
				endOriCtrlSS.setDefaultBlend(1)


				self.rigNode.tangentsDistanceScaling.connect(bezierRigGroup.tangentsDistanceScaling)
				# if doFK:
				# 	self.matrixConstraint(self.fkCtrls[-1], bezierRigGroup, r=1, s=1)

				displaySmoothness(self.crvs[0], pointsWire=16)
				
				if doParametric:
					# Motion path groups
					crvPathRig = self.buildCurvePartitionsSetup(
						self.crvs[0], 
						nameVars='0',
						partitionParams=[0, 1],
						numJointsList=[numJoints],
						mirror=mirror,
						createOffsetControls=(False if doStretchLimit else True),
						rotationStyle=(None if doStretchLimit else 'aim'),
						twist=(False if doStretchLimit else True),
						bindEnd=True
					)
					results = crvPathRig.results.get()


				if doSplineIK:
					ikSplineRig = self.buildIKSplineSetup(
						crv=self.crvs[0], 
						points=pointInput, 
						mirror=mirror, 
						selectionPriority=2,
					)
					results = ikSplineRig.results.get()

				

				# # =========================== Twist ===========================
				# #### Bend ctrls
				if doParametric and not doStretchLimit:
					self.bendCtrls[0].twist.connect(				self.twistAdds[0].input2D[0].getChildren()[0])
					self.socket(self.bendCtrls[0]).twist.connect(	self.twistAdds[0].input2D[1].getChildren()[0])

					self.bendCtrls[1].twist.connect(				self.twistAdds[0].input2D[0].getChildren()[1])
					self.socket(self.bendCtrls[1]).twist.connect(	self.twistAdds[0].input2D[1].getChildren()[1])

				if doSplineIK:
					self.bendCtrls[0].twist.connect(				self.twistAdds[0].input2D[0].getChildren()[0])
					self.socket(self.bendCtrls[0]).twist.connect(	self.twistAdds[0].input2D[1].getChildren()[0])

					self.bendCtrls[1].twist.connect(				self.twistAdds[0].input2D[0].getChildren()[1])
					self.socket(self.bendCtrls[1]).twist.connect(	self.twistAdds[0].input2D[1].getChildren()[1])


				# Squash and stretch limits
				if doStretchLimit:

					staticLocatorsGroup = createNode('transform', n=self.names.get('staticLocatorsGroup', 'rnm_staticLocatorsGroup'), p=ikSplineRig)
					self.step(staticLocatorsGroup, 'staticLocatorsGroup')

					bezLocs = []
					staticBezLocs = []
					i=0
					print '\n'
					print crvPathRig.results.get()
					print ikSplineRig.results.get()
					
					for bezPoint, ikJnt in zip(crvPathRig.results.get(), ikSplineRig.results.get()):
						
						# if i==4:
						# 	raise Exception('4')

						bezLoc2 = createNode('locator', n='%s_dist_LOC' % bezPoint, p=bezPoint)
						self.step(bezLoc2, 'bezLoc')
						bezLoc2.hide()
						bezLocs.append(bezLoc2)

						# 

						staticBezPoint = createNode('transform', n=self.names.get('staticBezPoint', 'rnm_staticBezPoint'), p=staticLocatorsGroup)
						self.step(staticBezPoint, 'staticBezPoint')
						utils.snap(bezPoint, staticBezPoint)

						staticBezLoc2 = createNode('locator', n='%s_dist_LOC' % staticBezPoint, p=staticBezPoint)
						self.step(staticBezLoc2, 'staticBezLoc')
						staticBezLoc2.hide()
						staticBezLocs.append(staticBezLoc2)

						if not i==0: # Skip 0
							# Distance
							bezLoc1 = bezLocs[i-1]
							staticBezLoc1 = staticBezLocs[i-1]

							bezDist = createNode('distanceBetween', n=self.names.get('bezDist', 'rnm_bezDist'))
							self.step(bezDist, 'bezDist')

							bezLoc1.worldPosition.connect(bezDist.point1)
							bezLoc2.worldPosition.connect(bezDist.point2)

							# Static distance
							staticBezDist = createNode('distanceBetween', n=self.names.get('staticBezDist', 'rnm_staticBezDist'))
							self.step(staticBezDist, 'staticBezDist')

							staticBezLoc1.worldPosition.connect(staticBezDist.point1)
							staticBezLoc2.worldPosition.connect(staticBezDist.point2)

							# # Mult static by rig input
							staticBezDistMult = createNode('multDoubleLinear', n=self.names.get('staticBezDistMult', 'rnm_staticBezDistMult'))
							self.step(staticBezDistMult, 'staticBezDistMult')
							staticBezDist.distance.connect(staticBezDistMult.i1)
							self.rigNode.restLength.connect(staticBezDistMult.i2)

							# Normalize
							normalizeDiv = createNode('multiplyDivide', n=self.names.get('normalizeDiv', 'rnm_normalizeDiv'))
							self.step(normalizeDiv, 'normalizeDiv')
							normalizeDiv.operation.set(2)

							bezDist.distance.connect(normalizeDiv.input1X)
							staticBezDistMult.output.connect(normalizeDiv.input2X)



							# Stretch
							stretchBlend = createNode( 'blendTwoAttr', n=self.names.get('stretchBlend', 'rnm_stretchBlend') )
							self.step(stretchBlend, 'stretchBlend')
							stretchBlend.i[0].set(1)
							normalizeDiv.outputX.connect(stretchBlend.i[1])
							self.rigNode.stretch.connect(stretchBlend.ab)


							# Squash
							squashBlend = createNode( 'blendTwoAttr', n=self.names.get('squashBlend', 'rnm_squashBlend') )
							self.step(squashBlend, 'squashBlend')
							squashBlend.i[0].set(1)
							normalizeDiv.outputX.connect(squashBlend.i[1])
							self.rigNode.squash.connect(squashBlend.ab)

	
							# Squash/Stretch combiner
							squashStretchCond = createNode( 'condition', n=self.names.get('stretchBlend', 'rnm_stretchBlend') )
							self.step(squashStretchCond, 'squashStretchCond')
							squashStretchCond.operation.set(2) # Greater Than
							normalizeDiv.outputX.connect(squashStretchCond.firstTerm)

							squashStretchCond.secondTerm.set(1)

							stretchBlend.o.connect(squashStretchCond.colorIfTrueR)
							squashBlend.o.connect(squashStretchCond.colorIfFalseR)


							restLengthMult = createNode('multDoubleLinear', n=self.names.get('restLengthMult', 'rnm_restLengthMult'))
							self.step(restLengthMult, 'restLengthMult')
							squashStretchCond.outColorR.connect(restLengthMult.i1)
							self.rigNode.restLength.connect(restLengthMult.i2)


							denormalizeMult = createNode('multDoubleLinear', n=self.names.get('denormalizeMult', 'rnm_denormalizeMult'))
							self.step(denormalizeMult, 'denormalizeMult')
							denormalizeMult.i1.set(bezDist.distance.get())
							restLengthMult.o.connect(denormalizeMult.i2)
							

							denormalizeMult.o.connect(ikJnt.tx)

							

						i=i+1

					results = ikSplineRig.results.get()


				if doFK:

					fkGroup = self.buildFkSetup(shapes=fkShapes, transforms=results, mirror=mirror)
					self.fkVis.connect(fkGroup.v)

					# FK Offset Option
					if doOffsetFK:
						boneIndic = utils.boneIndic(self.fkCtrls[-1], results[-1], blackGrey=1)[0]
						self.debugVis.connect(boneIndic.v)


						# Create an external result chain with edits (for bend control)
						# Regular ik spline won't allow changes to orientation within heirarchy, but heirarchy still needs to be preserved to allow
						# edits to fk offset controls (no constraints)
						splineHierarchy = []
						for i, point in enumerate(results):
							self.naming(n=i)
							self.names = utils.constructNames(self.namesDict)

							splineRetarget = createNode( 'transform', n=self.names.get('splineRetarget', 'rnm_splineRetarget'), p=splineHierarchy[i-1] if i else ikSplineRig )
							print splineRetarget
							self.step(splineRetarget, 'splineRetarget')
							splineHierarchy.append(splineRetarget)

							if i==0:
								self.matrixConstraint(point, splineRetarget, t=1, s=1, offset=False)
								self.matrixConstraint(self.bendCtrls[0], splineRetarget, t=0, r=1, offset=False)
								splineRetarget.t.connect(self.fkCtrls[i].buf.get().t)
								splineRetarget.r.connect(self.fkCtrls[i].buf.get().r)
								splineRetarget.s.connect(self.fkCtrls[i].buf.get().s)


							elif point == results[-1] :
								self.matrixConstraint(point, splineRetarget, t=1, s=1, offset=False)
								self.matrixConstraint(self.bendCtrls[-1], splineRetarget, t=0, r=1, offset=False)
								# endSS = buildRig.simpleSpaceSwitch(
								# 	constraintType='orient',
								# 	controller=self.fkCtrls[i],
								# 	constrained=self.fkCtrls[i],
								# 	prefix = self.names.get('endSS', 'rnm_endSS'),
								# 	targets=[point, self.bendCtrls[-1]],
								# 	labels=['Default', 'IK'],
								# 	offsets=True,
								# )
								splineRetarget.t.connect(self.fkCtrls[i].buf.get().t)
								splineRetarget.r.connect(self.fkCtrls[i].buf.get().r)
								splineRetarget.s.connect(self.fkCtrls[i].buf.get().s)
							else:
								self.matrixConstraint(point, splineRetarget, t=1, r=1, s=1, offset=False)


								# FK chain driven by IK rig
								splineRetarget.t.connect(self.fkCtrls[i].buf.get().t)
								splineRetarget.r.connect(self.fkCtrls[i].buf.get().r)
								splineRetarget.s.connect(self.fkCtrls[i].buf.get().s)

						results = self.fkCtrls



					# FK/IK Switch Option
					else:
						fkIkGroup =  createNode('transform', n=self.names.get('fkIkGroup', 'rnm_fkIkGroup'), p=self.rigGroup)
						self.step(fkIkGroup, 'fkIkGroup')
					
						switchGroup = createNode('transform', n=self.names.get('switchGroup','rnm_switchGroup'), p=fkIkGroup)
						self.step(switchGroup, 'switchGroup')
						self.publishList.append(switchGroup)
						# ENTRANCE
						fkEntrance = createNode('transform', n=self.names.get('fkEntrance', 'rnm_fkEntrance'), p=fkIkGroup)
						self.step(fkEntrance, 'fkEntrance')
						utils.snap(self.fkCtrls[0], fkEntrance)
						self.matrixConstraint(self.fkCtrls[0], fkEntrance, t=1, r=0, s=0)

						ikEntrance = createNode('transform', n=self.names.get('ikEntrance', 'rnm_ikEntrance'), p=fkIkGroup)
						self.step(ikEntrance, 'ikEntrance')
						utils.snap(results[0], ikEntrance)
						self.matrixConstraint(results[0], ikEntrance, t=1, r=0, s=0)
						self.matrixConstraint(self.bendCtrls[0], ikEntrance, t=0, r=1, s=1, offset=True)

						rigEntrance = createNode('transform', n=self.names.get('rigEntrance', 'rnm_rigEntrance'), p=fkIkGroup)
						self.step(rigEntrance, 'rigEntrance')
						utils.snap(results[0], rigEntrance)

						rigEntranceScaleBlend = createNode('blendColors', n=self.names.get('rigEntranceScaleBlend', 'rnm_rigEntranceScaleBlend'))
						self.step(rigEntranceScaleBlend, 'rigEntranceScaleBlend')
						fkEntrance.scale.connect(rigEntranceScaleBlend.color1)
						ikEntrance.scale.connect(rigEntranceScaleBlend.color2)
						self.rigNode.fkIk.connect(rigEntranceScaleBlend.blender)
						rigEntranceScaleBlend.output.connect(rigEntrance.scale)
						
						fkIkStartSS = buildRig.simpleSpaceSwitch(
							constraintType='parent',
							constrained= rigEntrance,
							prefix = self.names.get('fkIkStartSS', 'rnm_fkIkStartSS'),
							targets=[fkEntrance, ikEntrance],
							labels=['FK', 'IK'],
							offsets=True,
						)
						self.rigNode.fkIk.connect(fkIkStartSS.blendAttr)

						self.matrixConstraint(ikEntrance, rigEntrance, t=0, r=0, s=1)

						# EXIT
						fkExit = createNode('transform', n=self.names.get('fkExit', 'rnm_fkExit'), p=fkIkGroup)
						self.step(fkExit, 'fkExit')
						utils.snap(self.fkCtrls[-1], fkExit)
						self.matrixConstraint(self.fkCtrls[-1], fkExit, t=1, r=1, s=0)

						ikExit = createNode('transform', n=self.names.get('ikExit', 'rnm_ikExit'), p=fkIkGroup)
						self.step(ikExit, 'ikExit')
						utils.snap(results[-1], ikExit)
						self.matrixConstraint(results[-1], ikExit, t=1, r=0, s=0)
						self.matrixConstraint(self.bendCtrls[-1], ikExit, t=0, r=1, s=1, offset=True)

						rigExit = createNode('transform', n=self.names.get('rigExit', 'rnm_rigExit'), p=fkIkGroup)
						self.step(rigExit, 'rigExit')
						utils.snap(results[0], rigExit)

						fkIkEndSS = buildRig.simpleSpaceSwitch(
							constraintType='parent',
							constrained= rigExit,
							prefix = self.names.get('fkIkEndSS', 'rnm_fkIkEndSS'),
							targets=[fkExit, ikExit],
							labels=['FK', 'IK'],
							offsets=True,
						)
						self.rigNode.fkIk.connect(fkIkEndSS.blendAttr)


						rigExitScaleBlend = createNode('blendColors', n=self.names.get('rigExitScaleBlend', 'rnm_rigExitScaleBlend'))
						self.step(rigExitScaleBlend, 'rigExitScaleBlend')
						fkExit.scale.connect(rigExitScaleBlend.color1)
						ikExit.scale.connect(rigExitScaleBlend.color2)
						self.rigNode.fkIk.connect(rigExitScaleBlend.blender)
						rigExitScaleBlend.output.connect(rigExit.scale)


						# Points
						switches = []
						for i, point in enumerate(results):
							self.naming(n=i)
							self.names = utils.constructNames(self.namesDict)
							# result transforms
							switch = createNode('transform', n=self.names.get('switch', 'rnm_switch'), p=switchGroup)
							utils.snap(point, switch)
							self.step(switch, 'switch')
							switches.append(switch)

							fkIkSwitchSS = buildRig.simpleSpaceSwitch(
								constrained= switch,
								controller=self.rigNode.fkIk,
								targets=[self.fkCtrls[i], results[i]],
								labels=['FK', 'IK'],
								prefix = self.names.get('fkIkSwitchSS', 'rnm_fkIkSwitchSS'),
								constraintType='parent',
								offsets=True,
							)
							# self.rigNode.fkIk.connect(fkIkSwitchSS.rigNode.parentSpaceBlend)
				

					offsetResults = []
					# Offset controls
					for i, point in enumerate(results):
						ctrlParent = None
						if doOffsetFK:
							ctrlParent = self.fkCtrls[i]
						else:
							ctrlParent = offsetResults[i-1] if i else switchGroup

						self.naming(n=i)
						self.names = utils.constructNames(self.namesDict)
						par = self.fkCtrls[i] if doOffsetFK else switches[i]
						offsetCtrl = self.createControlHeirarchy(
							name=self.names.get('offsetCtrl', 'rnm_offsetCtrl'), 
							transformSnap=self.fkCtrls[i],
							selectionPriority=2,
							ctrlParent=ctrlParent,
							outlinerColor = (0,0,0),
							par=par)

						offsetResults.append(offsetCtrl)
						self.rigNode.offsetCtrlsVis.connect(offsetCtrl.buf.get().v)

					results = offsetResults



				results = self.buildScaleLengthSetup(scaleInputs=self.bendCtrls, distanceInputs=[results[0], results[1]], nodes=results, settingsNode=self.rigNode)

				rigEntranceBuf = createNode('transform', n=self.names.get('rigEntranceBuf', 'rnm_rigEntranceBuf'), p=self.rigGroup)
				self.step(rigEntranceBuf, 'rigEntranceBuf')
				utils.snap(results[0], rigEntranceBuf)
				# if style == 'IK Only' or style == 'IK to FK':
				if style == 'IK Only':
					self.matrixConstraint(self.bendCtrls[0], rigEntranceBuf, t=0, r=1, s=0, offset=False)
					self.matrixConstraint(results[0].getParent(), rigEntranceBuf, t=1, r=0, s=1, offset=False)
				else:
					self.matrixConstraint(results[0].getParent(), rigEntranceBuf, t=1, r=1, s=1, offset=False)

				rigEntrance = createNode('transform', n=self.names.get('rigEntrance', 'rnm_rigEntrance'), p=rigEntranceBuf)
				self.step(rigEntrance, 'rigEntrance')
				self.bendCtrls[0].twist.connect(rigEntrance.rx)

				rigExitBuf = createNode('transform', n=self.names.get('rigExitBuf', 'rnm_rigExitBuf'), p=self.rigGroup)
				self.step(rigExitBuf, 'rigExitBuf')
				utils.snap(results[0], rigExitBuf)

				if style == 'IK Only':
					self.matrixConstraint(self.bendCtrls[-1], rigExitBuf, t=0, r=1, s=0, offset=False)
					self.matrixConstraint(results[-1].getParent(), rigExitBuf, t=1, r=0, s=1, offset=False)
				else:
					self.matrixConstraint(results[-1].getParent(), rigExitBuf, t=1, r=1, s=1, offset=False)

				rigExit = createNode('transform', n=self.names.get('rigExit', 'rnm_rigExit'), p=rigExitBuf)
				self.step(rigExit, 'rigExit')
				self.bendCtrls[-1].twist.connect(rigExit.rx)

				results.insert(0, rigEntrance)
				results.append(rigExit)

				# results = []
				print 'Results:'
				print results
				for i, point in enumerate(results):

					self.naming(n=i)
					self.names = utils.constructNames(self.namesDict)


					if mirror:
						point = self.socket(point)
					# 	ctrl.rotateY.set(-180)
					# 	ctrl.scaleX.set(-1)

					point.message.connect(self.rigNode.socketList, na=1)
					# self.socketList.append(point)
					if doBind:
						bind = createNode('joint', n=self.names.get('bind', 'rnm_bind'), p=point)
						self.bindList.append(bind)
						self.step(bind, 'bind')
						bind.hide()

				# rigExit = createNode('transform', n=self.names.get('rigExit', 'rnm_rigExit'), p=self.rigGroup)
				# self.step(rigExit, 'rigExit')
				# self.socket(rigExit).message.connect(self.rigNode.socketList, na=1)
				# utils.snap(point, rigExit)
				# self.matrixConstraint(point, rigExit, t=1, r=1, s=1, offset=True)

				# if bindEnd:
				# 	# # rig exit bind
				# 	rigExitBind = createNode( 'joint', n=self.names.get( 'rigExitBind', 'rnm_rigExitBind'), p=rigExit )
				# 	self.step(rigExitBind, 'rigExitBind')
				# 	self.bindList.append(rigExitBind)
				# 	rigExitBind.hide()


				#=========================== Finalize =================================

			except:
				raise

			finally:
				# try:
				# 	for bendCtrl in self.bendCtrls:
				# 		attrs = bendCtrl.s.getChildren()
				# 		for a in attrs:
				# 			a.set(l=1, k=0)
				# except:
				# 	pass
				# try:
				# 	self.setController(fkGroup, self.rigGroup)
				# 	self.setController(bezierRigGroup, self.rigGroup)
				# except:
				# 	pass
				try:
					self.constructSelectionList(selectionName='bendCtrls', selectionList=self.bendCtrls)
					self.constructSelectionList(selectionName='tangentCtrls', selectionList=self.tangentCtrls)
					self.constructSelectionList(selectionName='offsetCtrls', selectionList=self.offsetCtrls)
					self.constructSelectionList(selectionName='frozenNodes', selectionList=self.freezeList)
				except:
					pass

				self.finalize()
示例#5
0
def coneAngleReader(base,
                    target,
                    prefix=None,
                    suffix=None,
                    targetOffset=1.0,
                    coneAxis=(0, 0, -1),
                    forwardAxis=(1, 0, 0),
                    coneAngle=90):
    nodeList = []
    freezeList = []

    dev = 1
    if prefix is None:
        prefix = target.shortName()
    names = {
        'axisGroup': '%s_angleReader_GRP' % (prefix),
        'baseVecProd': '%s_base_VP' % (prefix),
        'targetVecProd': '%s_target_VP' % (prefix),
        'angle': '%s_ANGBETW' % (prefix),
        'mult': '%s_MULT' % (prefix),
        'div': '%s_DIV' % (prefix),
        'cond': '%s_COND' % (prefix),
        'rev': '%s_REV' % (prefix),
        'coneBuf': '%s_cone_BUF' % (prefix),
        'previewCone': '%s_previewCone_GEO' % (prefix),
        'radExpression': '%s_rad_EXPR' % (prefix),
        'heightExpression': '%s_height_EXPR' % (prefix),
        'transYExpression': '%s_transY_EXPR' % (prefix)
    }
    if dev: print names

    axisGroup = createNode('transform',
                           n=names.get('axisGroup', 'rnm_axisGroup'),
                           p=base)
    nodeList.append(axisGroup)
    pointConstraint(target, axisGroup)

    if dev: print axisGroup

    baseVecProd = createNode('vectorProduct',
                             n=names.get('baseVecProd', 'rnm_baseVecProd'))
    nodeList.append(baseVecProd)
    axisGroup.worldMatrix.connect(baseVecProd.matrix)
    baseVecProd.operation.set(3)
    baseVecProd.normalizeOutput.set(1)
    baseVecProd.input1.set(coneAxis)
    if dev: print baseVecProd

    targetVecProd = createNode('vectorProduct',
                               n=names.get('targetVecProd',
                                           'rnm_targetVecProd'))
    nodeList.append(targetVecProd)
    target.worldMatrix.connect(targetVecProd.matrix)
    targetVecProd.operation.set(3)
    targetVecProd.normalizeOutput.set(1)
    targetVecProd.input1.set(forwardAxis)
    if dev: print targetVecProd

    #reader custom attributes
    if not hasAttr(target,
                   'coneAngle%s' % suffix.capitalize()) and not hasAttr(
                       target, 'value%s' % suffix.capitalize()):
        rb.cbSep(target)

    if not hasAttr(axisGroup, 'coneAngle%s' % suffix.capitalize()):
        addAttr(axisGroup,
                ln='coneAngle%s' % suffix.capitalize(),
                at='double',
                min=1,
                max=359,
                dv=coneAngle,
                k=True)
    if not hasAttr(axisGroup, 'value%s' % suffix.capitalize()):
        addAttr(axisGroup, ln='value%s' % suffix.capitalize(), k=1)
        axisGroup.attr('value%s' % suffix.capitalize()).set(k=0, cb=1)
    coneAngleAttr = axisGroup.attr('coneAngle%s' % suffix.capitalize())
    coneValueAttr = axisGroup.attr('value%s' % suffix.capitalize())

    # Angle between
    angle = createNode('angleBetween', n=names.get('angle', 'rnm_angle'))
    nodeList.append(angle)
    baseVecProd.output >> angle.vector1
    targetVecProd.output >> angle.vector2
    if dev: print angle

    # Multiply
    mult = createNode('multDoubleLinear', n=names.get('mult', 'rnm_mult'))
    nodeList.append(mult)
    coneAngleAttr >> mult.input1
    mult.i2.set(0.5)
    if dev: print mult

    div = createNode('multiplyDivide', n=names.get('div', 'rnm_div'))
    nodeList.append(div)
    angle.angle >> div.input1X
    mult.o >> div.input2X
    div.operation.set(2)
    if dev: print div

    cond = createNode('condition', n=names.get('cond', 'rnm_cond'))
    nodeList.append(cond)
    div.outputX >> cond.firstTerm
    div.outputX >> cond.colorIfTrueR
    cond.secondTerm.set(1.0)
    cond.operation.set(4)
    if dev: print cond

    # reverse
    rev = createNode('reverse', n=names.get('rev', 'rnm_rev'))
    nodeList.append(rev)
    cond.outColor >> rev.input
    rev.outputX >> coneValueAttr
    if dev: print rev

    # Cone preview
    coneBuf = createNode('transform',
                         n=names.get('coneBuf', 'rnm_coneBuf'),
                         p=axisGroup)
    nodeList.append(coneBuf)
    if dev: print coneBuf

    coneHeight = 1.0
    previewConeTransform, previewCone = polyCone(n=names.get(
        'previewCone', 'rnm_previewCone'),
                                                 r=1,
                                                 h=coneHeight,
                                                 sx=12,
                                                 sy=1,
                                                 sz=0,
                                                 ax=(0, -1, 0),
                                                 rcp=0,
                                                 cuv=3,
                                                 ch=1)
    nodeList.append(previewConeTransform)
    nodeList.append(previewCone)
    previewConeTransform.overrideEnabled.set(1)
    previewConeTransform.overrideDisplayType.set(2)
    previewConeTransform.overrideShading.set(0)
    parent(previewConeTransform, coneBuf)
    previewConeTransform.translate.set([0, 0, 0])
    previewConeTransform.rotate.set([0, 0, 0])
    previewCone.createUVs.set(0)
    if dev: print previewConeTransform
    if dev: print previewCone

    coneOri = createNode('transform', p=target)
    coneOri.translate.set(coneAxis)
    if dev: print coneOri

    aim = aimConstraint(coneOri,
                        coneBuf,
                        aimVector=[0, 1, 0],
                        upVector=[0, 1, 0],
                        worldUpVector=forwardAxis,
                        worldUpObject=target,
                        worldUpType='objectRotation')
    delete(aim)
    delete(coneOri)

    # Expressions
    radExpression = expression(
        s='%s=sind(%s*0.5)' % (previewCone.radius, coneAngleAttr),
        o=previewCone,
        ae=1,
        uc='all',
        name=names.get('radExpression', 'rnm_radExpression'))
    heightExpression = expression(
        s='%s=cosd(%s*0.5)' % (previewCone.height, coneAngleAttr),
        o=previewCone,
        ae=1,
        uc='all',
        name=names.get('heightExpression', 'rnm_heightExpression'))
    transYExpression = expression(
        s='%s=(%s/2)' % (previewConeTransform.translateY, previewCone.height),
        o=previewCone,
        ae=1,
        uc='all',
        name=names.get('transYExpression', 'rnm_transYExpression'))
    if dev: print radExpression
    if dev: print heightExpression
    if dev: print transYExpression

    nodeList.extend([radExpression, heightExpression, transYExpression])

    # Finalize
    rb.messageConnect(axisGroup, 'rigNodes', nodeList, 'angleReader')
    if len(freezeList):
        if not dev:
            rb.lockAndHide(
                freezeList,
                ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'])
            col.setOutlinerRGB(freezeList, [0.36, 0.58, 0.64])

    select(target)
示例#6
0
    def __init__(self, fitNode=None, rigNode=None):

        if fitNode is None and rigNode is None:
            raise Exception('No data specified.')

        elif fitNode is None:
            self.rigNode = rigNode
            # Put any attributes needed for initialized rigs here

        else:
            try:
                jointsList = fitNode.jointsList.get()
                # Initialize rigNode
                # Error Check:

                # Convert string input to PyNode if neccessary
                if isinstance(fitNode, str):
                    fitNode = ls(fitNode)[0]

                if fitNode.rigType.get() != 'aimIK':
                    raise Exception('Incorrect rig type: %s' %
                                    fitNode.rigType.get())

                if fitNode.hasAttr('inbetweenJoints'):
                    inbetweenJoints = fitNode.inbetweenJoints.get()
                else:
                    inbetweenJoints = 0

                self.crvs = []

                buildRig.rig.__init__(self, fitNode)

                jointsList = fitNode.jointsList.get()
                orientControlsList = [
                    fitNode.startOriCtrl.get(),
                    fitNode.endOriCtrl.get()
                ]
                # Move rigGroup
                xform(self.rigGroup,
                      ws=1,
                      m=xform(jointsList[0], q=1, ws=1, m=1))
                # fitNode attributes

                bindEnd = self.fitNode.bindEnd.get()
                doFK = self.fitNode.fkEnable.get()
                ikEndInherit = self.fitNode.ikEndInherit.get()
                doStretch = self.fitNode.doStretch.get()
                doTwist = self.fitNode.doTwist.get()
                doVolume = self.fitNode.doVolume.get()
                doScaling = self.fitNode.doScaling.get()
                twistAxis = 0

                if doFK:
                    fkShape = (self.fitNode.fkShape.get()
                               if self.fitNode.fkVis.get() else None)
                else:
                    fkShape = None

                ikShapes = [(self.fitNode.startShape.get()
                             if self.fitNode.ikVisStart.get() else None),
                            self.fitNode.endShape.get()
                            if self.fitNode.ikVisEnd.get() else None]

                doIkStartCtrl = self.fitNode.ikVisStart.get()
                doIkEndCtrl = self.fitNode.ikVisEnd.get()

                twistAxisChoice = 0
                # up = None:
                up = self.fitNode.up.get()

                # Mirroring
                if self.fitNode.side.get() == 2:
                    mirror = True
                else:
                    mirror = False

                # Naming
                self.globalName = self.fitNode.globalName.get()
                self.subNames = []
                subAttrs = listAttr(self.fitNode, st='subName*')
                for subAttr in subAttrs:
                    self.subNames.append(self.fitNode.attr(subAttr).get())
                # print 'subnames:'
                # print self.subNames

                self.naming()
                self.names = utils.constructNames(self.namesDict)
                # ========================= RigNode Attributes =========================
                self.rigNode.rigType.set('aimIK', l=1)

                utils.cbSep(self.rigNode)
                if doFK:
                    addAttr(self.rigNode,
                            ct='publish',
                            ln='fkVis',
                            nn='FK Vis',
                            at='short',
                            min=0,
                            max=1,
                            dv=1)
                    setAttr(self.rigNode.fkVis, keyable=False, channelBox=True)

                addAttr(self.rigNode,
                        ct='publish',
                        ln='ikVis',
                        nn='IK Vis',
                        at='short',
                        min=0,
                        max=1,
                        dv=1)
                setAttr(self.rigNode.ikVis, keyable=False, channelBox=True)

                addAttr(self.rigNode,
                        ct='publish',
                        ln='offsetCtrlsVis',
                        min=0,
                        max=1,
                        dv=0,
                        keyable=1)
                self.rigNode.offsetCtrlsVis.set(k=0, cb=1)

                if doStretch:
                    addAttr(self.rigNode,
                            ct='publish',
                            ln='squash',
                            min=0,
                            max=1,
                            dv=1,
                            keyable=1)
                    addAttr(self.rigNode,
                            ct='publish',
                            ln='stretch',
                            min=0,
                            max=1,
                            dv=1,
                            keyable=1)

                    utils.cbSep(self.rigNode, ct='publish')
                    addAttr(self.rigNode,
                            ct='publish',
                            ln='restLength',
                            min=0.01,
                            dv=1,
                            keyable=1)
                    addAttr(self.rigNode,
                            ct='publish',
                            ln='currentNormalizedLength',
                            min=0,
                            dv=1,
                            keyable=1)

                utils.cbSep(self.rigNode, ct='publish')
                addAttr(self.rigNode,
                        ln='upAxis',
                        at='enum',
                        enumName='Y=1:Z=2',
                        dv=2,
                        k=1)

                addAttr(self.rigNode,
                        ln='iKCtrlStart',
                        nn='IK Ctrl Start',
                        at='message')
                addAttr(self.rigNode,
                        ln='iKCtrlEnd',
                        nn='IK Ctrl End',
                        at='message')
                addAttr(self.rigNode,
                        ln='fkCtrl',
                        nn='FK Ctrl Start',
                        at='message')

                # ========================= Vis Mults =========================
                # allVis Mults
                if doFK:
                    fkVisMult = createNode('multDoubleLinear',
                                           n=self.names.get(
                                               'fkVisMult', 'rnm_fkVisMult'))
                    self.rigNode.allVis >> fkVisMult.i1
                    self.rigNode.fkVis >> fkVisMult.i2
                    self.step(fkVisMult, 'fkVisMult')
                    self.fkVis = fkVisMult.o

                ikVisMult = createNode('multDoubleLinear',
                                       n=self.names.get(
                                           'ikVisMult', 'rnm_ikVisMult'))
                self.rigNode.allVis >> ikVisMult.i1
                self.rigNode.ikVis >> ikVisMult.i2
                self.step(ikVisMult, 'ikVisMult')
                self.ikVis = ikVisMult.o

                # offsetVisMult = createNode('multDoubleLinear', n=self.names.get('offsetVisMult', 'rnm_offsetVisMult'))
                # self.rigNode.allVis >> offsetVisMult.i1
                # self.rigNode.ikVis >> offsetVisMult.i2
                # self.step(offsetVisMult, 'offsetVisMult')
                # self.offsetVis = offsetVisMult.o

                debugVisMult = createNode('multDoubleLinear',
                                          n=self.names.get(
                                              'debugVisMult',
                                              'rnm_debugVisMult'))
                self.debugVis = debugVisMult.o
                self.rigNode.allVis >> debugVisMult.i1
                self.rigNode.debugVis >> debugVisMult.i2
                self.step(debugVisMult, 'debugVisMult')

                # ========================= World Group =========================
                # worldGroup = createNode('transform', n=self.names.get('worldGroup', 'rnm_worldGroup'), p=self.rigGroup)
                # self.worldGroup = worldGroup
                # self.step(worldGroup, 'worldGroup')
                # worldGroup.inheritsTransform.set(0)
                # xform(worldGroup, rp=[0,0,0], ro=[0,0,0], ws=1)
                #

                self.ssGroup = createNode('transform',
                                          n=self.names.get(
                                              'ssGroup', 'rnm_ssGroup'),
                                          p=self.rigGroup)
                self.step(self.ssGroup, 'ssGroup')

                # =========================== FK Setup =================================

                if doFK:
                    fkGroup = self.buildFkSetup(shapes=[fkShape],
                                                transforms=[jointsList[0]],
                                                mirror=mirror)
                    self.fkVis.connect(fkGroup.v)
                    for fkCtrl in self.fkCtrls:

                        if self.dev:
                            print '\n\n'
                            print '%s' % self.rigsGroup
                            print '%s' % fkCtrl.buf.get()
                        fkCtrl.message.connect(self.rigNode.fkCtrl)
                        fkOriCtrlSS = buildRig.spaceSwitch(
                            constraintType='orient',
                            controller=fkCtrl,
                            constrained=fkCtrl.const.get(),
                            prefix=self.names.get('fkOriCtrlSS',
                                                  'rnm_fkOriCtrlSS'),
                            # p=self.rigGroup,
                            p=self.ssGroup,
                            targets=[self.rigsGroup,
                                     fkCtrl.buf.get()],
                            labels=['World', 'Parent'],
                            offsets=True,
                        )
                        fkOriCtrlSS.setDefaultBlend(1)

                # =========================== Aim Ik Setup =================================

                aimIKGroup = self.buildAimIkSetup(
                    source=orientControlsList[0],
                    dest=orientControlsList[1],
                    worldUpLocation=up,
                    inbetweenJoints=inbetweenJoints,
                    controller=self.rigNode,
                    sourceShape=ikShapes[0],
                    destShape=ikShapes[1],
                    registerControls=[bool(doIkStartCtrl),
                                      bool(doIkEndCtrl)],
                    stretch=doStretch,
                    twist=doTwist,
                    volume=doVolume,
                    scaling=doScaling,
                    twistAxisChoice=twistAxisChoice)
                self.ikVis.connect(aimIKGroup.v)

                aimIKGroup.results.get()[0].message.connect(
                    self.rigNode.socketList, na=1)
                aimIKGroup.results.get()[1].message.connect(
                    self.rigNode.socketList, na=1)

                # if doIkStartCtrl:
                # 	startOriCtrlSS = buildRig.spaceSwitch(
                # 		constraintType='orient',
                # 		controller = self.aimCtrls[0],
                # 		constrained= self.aimCtrls[0].const.get(),
                # 		prefix = self.names.get('startOriCtrlSS', 'rnm_startOriCtrlSS'),
                # 		p=self.ssGroup,
                # 		targets=[self.rigsGroup, self.aimCtrls[0].buf.get()],
                # 		labels=['World', 'Parent'],
                # 		offsets=True,
                # 	)
                # 	startOriCtrlSS.setDefaultBlend(1)

                # if doIkEndCtrl:
                # 	endOriCtrlSS = buildRig.spaceSwitch(
                # 		constraintType='orient',
                # 		controller = self.aimCtrls[1],
                # 		constrained= self.aimCtrls[1].const.get(),
                # 		prefix = self.names.get('endOriCtrlSS', 'rnm_endOriCtrlSS'),
                # 		p=self.ssGroup,
                # 		# p=self.ssGroup,
                # 		targets=[self.rigsGroup, self.aimCtrls[1].buf.get()],
                # 		labels=['World', 'Parent'],
                # 		offsets=True,
                # 	)
                # 	endOriCtrlSS.setDefaultBlend(1)

                self.aimCtrls[0].message.connect(self.rigNode.iKCtrlStart)
                self.aimCtrls[1].message.connect(self.rigNode.iKCtrlEnd)

                if doFK:
                    self.matrixConstraint(self.socket(fkCtrl),
                                          aimIKGroup,
                                          r=1,
                                          s=1,
                                          offset=False)

                for i, trans in enumerate(aimIKGroup.results.get()):
                    # If end is not being bound, skip last
                    if not bindEnd:
                        if trans is aimIKGroup.results.get()[-1]:
                            break

                    # Create a bind joint for each result transform (special naming for midJoints)
                    if inbetweenJoints:
                        n = i
                    else:
                        n = 0
                    self.naming(i=i, n=n)
                    self.names = utils.constructNames(self.namesDict)

                    bind = createNode('joint',
                                      n=self.names.get('bind', 'rnm_bind'),
                                      p=trans)
                    self.step(bind, 'bind')
                    xform(bind, ws=1, ro=xform(jointsList[0], q=1, ws=1, ro=1))
                    self.bindList.append(bind)
                    bind.hide()

                # Create an exit node
                self.rigExit = createNode('transform',
                                          n=self.names.get(
                                              'rigExit', 'rnm_rigExit'),
                                          p=self.rigGroup)

                # End result for translation, end control for rotation and scale
                # T
                self.matrixConstraint(self.socket(
                    aimIKGroup.results.get()[-1]),
                                      self.rigExit,
                                      t=1,
                                      offset=False)
                # R (snap offset from jointsList)
                utils.snap(jointsList[-1], self.socket(self.aimCtrls[1]))
                self.matrixConstraint(self.socket(self.aimCtrls[1]),
                                      self.rigExit,
                                      t=0,
                                      r=1,
                                      s=1,
                                      offset=False)
                self.step(self.rigExit, 'rigExit')

                self.rigExit.message.connect(self.rigNode.socketList, na=1)

                self.naming(i=2)
                self.names = utils.constructNames(self.namesDict)

                doFootRoll = False
                if hasAttr(self.fitNode, 'subNode'):
                    if self.fitNode.subNode.get():
                        if self.fitNode.subNode.get().rigType.get(
                        ) == 'footRoll':
                            if self.fitNode.subNode.get().build.get():
                                if self.dev:
                                    print 'FOOTROLL:'
                                    print self.fitNode.subNode.get()
                                doFootRoll = True

                if not doFootRoll:
                    if bindEnd:
                        # No need for exit bind if there's a rigExtension (expand to include hand rig when it's done)
                        rigExitBind = createNode('joint',
                                                 n=self.names.get(
                                                     'rigExitBind',
                                                     'rnm_rigExitBind'),
                                                 p=self.rigExit)
                        self.step(rigExitBind, 'rigExitBind')
                        self.bindList.append(rigExitBind)
                        rigExitBind.hide()

                else:
                    # self.buildFootRollSetup(self.fitNode.subNode.get()) AIMIK
                    pass

            #=========================== Finalize =================================
            finally:
                try:
                    if doFK:
                        for fkCtrl in self.fkCtrls:
                            self.socket(fkCtrl).message.connect(
                                self.rigNode.socketList, na=1)
                except:
                    pass
                try:
                    if doFK:
                        self.setController(fkRigGroup, self.rigGroup)
                    self.setController(aimIKGroup, self.rigGroup)
                except:
                    pass

                try:
                    if doFK:
                        self.constructSelectionList(selectionName='fkCtrls',
                                                    selectionList=self.fkCtrls)

                    self.constructSelectionList(selectionName='aimCtrls',
                                                selectionList=self.aimCtrls)
                    self.constructSelectionList(selectionName='frozenNodes',
                                                selectionList=self.freezeList)
                except:
                    pass

                self.finalize()
示例#7
0
    def __init__(self, fitNode=None, rigNode=None):

        if fitNode is None and rigNode is None:
            raise Exception('No data specified.')

        elif fitNode is None:
            self.rigNode = rigNode
            # Put any attributes needed for initialized rigs here

        else:

            jointsList = fitNode.jointsList.get()
            # Initialize rigNode
            # Error Check:

            # Convert string input to PyNode if neccessary
            if isinstance(fitNode, str):
                fitNode = ls(fitNode)[0]

            if fitNode.rigType.get() != 'chain':
                raise Exception('Incorrect rig type: %s' %
                                fitNode.rigType.get())

            self.crvs = []

            buildRig.rig.__init__(self, fitNode)

            jointsList = fitNode.jointsList.get()
            # Move rigGroup
            xform(self.rigGroup, ws=1, m=xform(jointsList[0], q=1, ws=1, m=1))
            # fitNode attributes

            fkShapes = self.fitNode.fkShapes.get()
            ikShapes = self.fitNode.ikShapes.get()

            doCloseLoop = False
            if hasAttr(self.fitNode, 'closeLoop'):
                doCloseLoop = bool(self.fitNode.closeLoop.get())

            doFK = True
            if hasAttr(self.fitNode, 'doFK'):
                doFK = bool(self.fitNode.doFK.get())

            doBend = True
            if hasAttr(self.fitNode, 'doBend'):
                doBend = bool(self.fitNode.doBend.get())

            autoTwist = True
            if hasAttr(self.fitNode, 'autoTwist'):
                autoTwist = bool(self.fitNode.autoTwist.get())

            doOffsets = True
            if hasAttr(self.fitNode, 'offsets'):
                doOffsets = bool(self.fitNode.offsets.get())

            fkTwist = True
            if hasAttr(self.fitNode, 'fkTwist'):
                fkTwist = bool(self.fitNode.fkTwist.get())

            if not doFK:
                fkTwist = False

            doBias = False
            if hasAttr(self.fitNode, 'doBias'):
                doBias = bool(self.fitNode.doBias.get())

            inbetweenJoints = 4
            if hasAttr(self.fitNode, 'inbetweenJoints'):
                inbetweenJoints = self.fitNode.inbetweenJoints.get()

            rotationStyle = 'aim'
            if hasAttr(self.fitNode, 'rotationStyle'):
                rotationStyle = self.fitNode.rotationStyle.get(asString=True)

            doNeutralize = 'aim'
            if hasAttr(self.fitNode, 'doNeutralize'):
                doNeutralize = bool(self.fitNode.doNeutralize.get())

            twistAxis = 0

            numJointsList = []
            for i in range(len(jointsList)):
                if not i == 0:
                    if i == len(jointsList):
                        numJointsList.append(inbetweenJoints + 1)
                    else:
                        numJointsList.append(inbetweenJoints)

            # Mirroring
            if self.fitNode.side.get() == 2:
                mirror = True
            else:
                mirror = False

            if self.fitNode.mirror.get() is False:
                mirror = False

            # Per joint mirroring
            mirrorList = []
            for jnt in jointsList:
                if jnt.autoMirror.get() is False:
                    mirrorList.append(False)
                elif jnt.side.get() == 2:
                    mirrorList.append(True)
                else:
                    mirrorList.append(False)

            print 'mirrorList:'
            print mirrorList

            # Naming
            self.globalName = self.fitNode.globalName.get()
            self.subNames = []
            subAttrs = listAttr(self.fitNode, st='subName*')
            for subAttr in subAttrs:
                self.subNames.append(self.fitNode.attr(subAttr).get())
            # print 'subnames:'
            # print self.subNames

            self.naming(0)
            self.names = utils.constructNames(self.namesDict)

            try:
                # ========================= RigNode Attributes =========================
                self.rigNode.rigType.set('bezier', l=1)

                utils.cbSep(self.rigNode)
                # addAttr(self.rigNode, ln='ikVis', nn='IK Vis', at='short', min=0, max=1, dv=1)
                # setAttr(self.rigNode.ikVis, keyable=False, channelBox=True)

                if doBend:
                    utils.cbSep(self.rigNode)
                    addAttr(self.rigNode,
                            ct='publish',
                            ln='bendCtrlsVis',
                            nn='Bend Ctrl Vis',
                            at='short',
                            min=0,
                            max=1,
                            dv=1,
                            k=1)
                    setAttr(self.rigNode.bendCtrlsVis, k=0, cb=1)

                    addAttr(self.rigNode,
                            ct='publish',
                            ln='tangentCtrlsVis',
                            min=0,
                            max=1,
                            dv=0,
                            at='short',
                            k=1)
                    setAttr(self.rigNode.tangentCtrlsVis, k=0, cb=1)

                    addAttr(self.rigNode,
                            ct='publish',
                            ln='offsetsCtrlsVis',
                            min=0,
                            max=1,
                            dv=0,
                            at='short',
                            k=1)
                    setAttr(self.rigNode.offsetsCtrlsVis, k=0, cb=1)

                    if not hasAttr(self.rigNode, 'upAxis'):
                        utils.cbSep(self.rigNode)
                        addAttr(self.rigNode,
                                ln='upAxis',
                                at='enum',
                                enumName='Y=1:Z=2',
                                dv=1,
                                k=1)

                    addAttr(self.rigNode,
                            ln='tangentsDistanceScaling',
                            softMinValue=0,
                            softMaxValue=1,
                            dv=0.5,
                            k=1)
                # ========================= Vis Mults =========================
                # allVis Mults
                # ikVisMult = createNode('multDoubleLinear', n=self.names.get('ikVisMult', 'rnm_ikVisMult'))
                # self.rigNode.allVis >> ikVisMult.i1
                # self.rigNode.ikVis >> ikVisMult.i2
                # self.step(ikVisMult, 'ikVisMult')

                bendVisMult = createNode('multDoubleLinear',
                                         n=self.names.get(
                                             'bendVisMult', 'rnm_bendVisMult'))
                self.bendVis = bendVisMult.o
                self.rigNode.allVis >> bendVisMult.i1
                self.rigNode.bendCtrlsVis >> bendVisMult.i2
                self.step(bendVisMult, 'bendVisMult')

                debugVisMult = createNode('multDoubleLinear',
                                          n=self.names.get(
                                              'debugVisMult',
                                              'rnm_debugVisMult'))
                self.debugVis = debugVisMult.o
                self.rigNode.allVis >> debugVisMult.i1
                self.rigNode.debugVis >> debugVisMult.i2
                self.step(debugVisMult, 'debugVisMult')

                tangentVisMult = createNode('multDoubleLinear',
                                            n=self.names.get(
                                                'tangentVisMult',
                                                'rnm_tangentVisMult'))
                self.tangentVis = tangentVisMult.o
                self.rigNode.allVis >> tangentVisMult.i1
                self.rigNode.tangentCtrlsVis >> tangentVisMult.i2
                self.step(tangentVisMult, 'tangentVisMult')

                offsetsVisMult = createNode('multDoubleLinear',
                                            n=self.names.get(
                                                'offsetsVisMult',
                                                'rnm_offsetsVisMult'))
                self.offsetsVis = offsetsVisMult.o
                self.rigNode.allVis >> offsetsVisMult.i1
                self.rigNode.offsetsCtrlsVis >> offsetsVisMult.i2
                self.step(offsetsVisMult, 'offsetsVisMult')

                # ========================= World Group =========================
                worldGroup = createNode('transform',
                                        n=self.names.get(
                                            'worldGroup', 'rnm_worldGroup'),
                                        p=self.rigGroup)
                self.worldGroup = worldGroup
                self.step(worldGroup, 'worldGroup')
                worldGroup.inheritsTransform.set(0)
                xform(worldGroup, rp=[0, 0, 0], ro=[0, 0, 0], ws=1)

                # =========================== FK Setup =================================
                if doFK:
                    fkGroup = self.buildFkSetup(shapes=fkShapes,
                                                transforms=jointsList,
                                                mirror=mirror)

                if doOffsets:
                    offsetGroup = createNode('transform',
                                             n=self.names.get(
                                                 'offsetGroup',
                                                 'rnm_offsetGroup'),
                                             p=self.rigGroup)
                    self.step(offsetGroup, 'offsetGroup')

                    self.offsetCtrls = []
                    for i, jnt in enumerate(jointsList):

                        par = self.fkCtrls[i] if doFK else offsetGroup

                        ctrlPar = None
                        if i:
                            ctrlPar = self.offsetCtrls[i - 1]
                        if doFK:
                            ctrlpar = self.fkCtrls[i]

                        offsetCtrl = self.createControlHeirarchy(
                            name=self.names.get('offsetCtrl',
                                                'rnm_offsetCtrl'),
                            transformSnap=jnt,
                            selectionPriority=0,
                            shape=ikShapes[i],
                            ctrlParent=ctrlPar,
                            outlinerColor=(0, 0, 0),
                            par=par)

                        self.offsetCtrls.append(offsetCtrl)

                    # for fkCtrl in self.fkCtrls:
                    # fkCtrl.message.connect(self.rigNode.fkCtrls, )

                #=========================== Bezier Setup =================================

                transforms = jointsList
                if doFK:
                    transforms = self.fkCtrls
                if doOffsets:
                    transforms = self.offsetCtrls

                bezierRigGroup = self.buildBezierSetup(
                    transforms=transforms,
                    ctrlTransforms=transforms,
                    shapes=fkShapes,
                    follow=True if doFK or doOffsets else False,
                    twist=autoTwist,
                    bias=doBias,
                    twistAxisChoice=0,
                    doNeutralize=doNeutralize,
                    mirror=mirrorList,
                    bezChain=doFK,
                    closeLoop=doCloseLoop)
                self.bendVis.connect(bezierRigGroup.controlsVis)

                self.rigNode.tangentsDistanceScaling.connect(
                    bezierRigGroup.tangentsDistanceScaling)

                for ctrl in self.bendCtrls:
                    if doNeutralize:
                        ctrl.neutralize.set(1)
                    ctrl.magnitude.set(1)

                #=========================== Bend Setup =================================
                # bendRigGroup = self.buildMidBendCurveSetup(transforms=self.fkCtrls, follow=True, shapes=ikShapes, controller=self.rigNode, mirror=mirror)

                # if self.dev: print 'Control uValues: %s' % (bezierRigGroup.uValues.get())

                crvPathRig = self.buildCurvePartitionsSetup(
                    self.crvs[0],
                    partitionParams=bezierRigGroup.uValues.get(),
                    constraintTargets=(self.fkCtrls[:-1] if doFK else None),
                    numJointsList=numJointsList,
                    mirror=mirror,
                    createOffsetControls=True,
                    rotationStyle=rotationStyle,
                    twist=True)

                results = crvPathRig.results.get()
                self.offsetsVis.connect(crvPathRig.v)

                for i in range(len(self.bendCtrls)):
                    # addAttr(crvPathRig, ln='partitionParameters', multi=True, numberOfChildren=3, k=1)
                    if self.dev:
                        print bezierRigGroup
                        print bezierRigGroup.attr('uValues%s' % i)
                        print bezierRigGroup.attr('uValues%s' % i).get()
                        print crvPathRig
                        print crvPathRig.attr('partitionParameter%s' % i)
                        print crvPathRig.attr('partitionParameter%s' % i).get()
                        print '\n'
                    bezierRigGroup.attr('uValues%s' % i).connect(
                        crvPathRig.attr('partitionParameter%s' % i))

                twistSettingsList = []
                if fkTwist:
                    for i in range(len(jointsList)):
                        twistSettings = self.socket(self.fkCtrls[i])
                        buildRig.twistExtractorMatrix(
                            self.fkCtrls[i], (self.fkCtrls[i].buf.get()),
                            settingsNode=twistSettings)
                        twistSettings.mult.set(-1)
                        twistSettingsList.append(twistSettings)

                for i in range(len(self.bendCtrls)):
                    # addAttr(self.bendCtrls[i], ln='twist', k=1)

                    rangeStart = True if i == 0 else False
                    rangeEnd = True if i == (len(self.bendCtrls) -
                                             1) else False

                    if not rangeEnd:
                        self.bendCtrls[i].twist.connect(
                            self.twistAdds[i].input2D[0].getChildren()[0])
                    if not rangeStart:
                        self.bendCtrls[i].twist.connect(
                            self.twistAdds[i - 1].input2D[0].getChildren()[1])

                    if autoTwist:
                        if not rangeEnd:
                            self.socket(self.bendCtrls[i]).twist.connect(
                                self.twistAdds[i].input2D[1].getChildren()[0])
                        if not rangeStart:
                            self.socket(self.bendCtrls[i]).twist.connect(
                                self.twistAdds[i -
                                               1].input2D[1].getChildren()[1])

                if fkTwist:
                    for i in range(len(self.fkCtrls)):
                        rangeEnd = True if i == (len(self.bendCtrls) -
                                                 1) else False
                        if not rangeEnd:
                            (twistSettingsList[i].twist.connect(
                                self.twistAdds[i].input2D[2].getChildren()[0]))

                # if scaling:
                nodes0 = crvPathRig.results.get(
                )[:len(crvPathRig.results.get()) / 2]
                nodes1 = crvPathRig.results.get(
                )[len(crvPathRig.results.get()) / 2:]
                scaleLengthGroup0 = self.buildScaleLengthSetup(
                    scaleInputs=bezierRigGroup.ctrls.get()[:2],
                    nodes=nodes0,
                    settingsNode=self.rigNode)
                scaleLengthGroup1 = self.buildScaleLengthSetup(
                    scaleInputs=bezierRigGroup.ctrls.get()[1:],
                    nodes=nodes1,
                    settingsNode=self.rigNode)
                print scaleLengthGroup0
                print scaleLengthGroup1
                results = scaleLengthGroup0 + scaleLengthGroup1

                for i, res in enumerate(results):

                    # Create a bind joint for each result transform (special naming for midJoints)

                    self.naming(n=i)
                    self.names = utils.constructNames(self.namesDict)

                    res.message.connect(self.rigNode.socketList, na=1)

                    if mirror:
                        res.scaleZ.set(-1)
                        res.rotateZ.set(180)

                    bind = createNode('joint',
                                      n=self.names.get('bind', 'rnm_bind'),
                                      p=res)
                    self.step(bind, 'bind')
                    # xform(bind, ws=1, ro=xform(jointsList[0], q=1, ws=1, ro=1))
                    self.bindList.append(bind)
                    bind.rotate.set(0, 0, 0)
                    bind.jointOrient.set(0, 0, 0)
                    # bind.attr('type').set(18)
                    # bind.otherType.set('%s' % i)
                    # bind.drawLabel.set(1)
                    bind.hide()

            #=========================== Finalize =================================
            finally:
                try:
                    self.setController(fkGroup, self.rigGroup)
                    self.setController(bezierRigGroup, self.rigGroup)
                    self.setController(crvPathRig, self.rigGroup)
                except:
                    pass
                try:
                    self.constructSelectionList(selectionName='bendCtrls',
                                                selectionList=self.bendCtrls)
                    self.constructSelectionList(
                        selectionName='tangentCtrls',
                        selectionList=self.tangentCtrls)
                    self.constructSelectionList(selectionName='offsetCtrls',
                                                selectionList=self.offsetCtrls)
                    self.constructSelectionList(selectionName='frozenNodes',
                                                selectionList=self.freezeList)
                except:
                    pass

                self.finalize()
示例#8
0
    def __init__(self, fitNode=None, rigNode=None):

        if fitNode is None and rigNode is None:
            raise Exception('No data specified.')

        elif fitNode is None:
            self.rigNode = rigNode
            # Put any attributes needed for initialized rigs here

        else:

            jointsList = fitNode.jointsList.get()
            # Initialize rigNode
            # Error Check:

            # Convert string input to PyNode if neccessary
            if isinstance(fitNode, str):
                fitNode = ls(fitNode)[0]

            if fitNode.rigType.get() != 'chain':
                raise Exception('Incorrect rig type: %s' %
                                fitNode.rigType.get())

            self.crvs = []

            buildRig.rig.__init__(self, fitNode)

            jointsList = fitNode.jointsList.get()
            # Move rigGroup
            xform(self.rigGroup, ws=1, m=xform(jointsList[0], q=1, ws=1, m=1))
            # fitNode attributes

            fkShapes = self.fitNode.fkShapes.get()
            endShapes = self.fitNode.ikShapes.get()
            # midShapes  = 	self.fitNode.midShapes.get()

            numJointsList = []
            for i in range(len(jointsList)):
                if not i == 0:
                    if i == len(jointsList):
                        numJointsList.append(3)
                    else:
                        numJointsList.append(2)

            # Mirroring
            if self.fitNode.side.get() == 2:
                mirror = True
            else:
                mirror = False

            if self.fitNode.mirror.get() is False:
                mirror = False

            doBend = True
            doFK = False
            oneCurve = False
            autoTwist = True

            # Naming
            self.globalName = self.fitNode.globalName.get()
            self.subNames = []
            subAttrs = listAttr(self.fitNode, st='subName*')
            for subAttr in subAttrs:
                self.subNames.append(self.fitNode.attr(subAttr).get())
            # print 'subnames:'
            # print self.subNames

            self.naming(0)
            self.names = utils.constructNames(self.namesDict)

            try:
                # ========================= RigNode Attributes =========================
                self.rigNode.rigType.set('midBendChain', l=1)

                if self.doFK:
                    utils.cbSep(self.rigNode)
                    addAttr(self.rigNode,
                            ln='fkVis',
                            nn='FK Vis',
                            at='short',
                            min=0,
                            max=1,
                            dv=1)
                    setAttr(self.rigNode.fkVis, keyable=False, channelBox=True)

                addAttr(self.rigNode,
                        ct='publish',
                        ln='offsetCtrlsVis',
                        at='short',
                        min=0,
                        max=1,
                        dv=0,
                        k=1)
                setAttr(self.rigNode.offsetCtrlsVis, k=0, cb=1)
                utils.cbSep(self.rigNode)
                addAttr(self.rigNode,
                        ct='publish',
                        ln='bendCtrlsVis',
                        nn='Bend Ctrl Vis',
                        at='short',
                        min=0,
                        max=1,
                        dv=1,
                        k=1)
                setAttr(self.rigNode.bendCtrlsVis, k=0, cb=1)

                if not hasAttr(self.rigNode, 'upAxis'):
                    utils.cbSep(self.rigNode)
                    addAttr(self.rigNode,
                            ln='upAxis',
                            at='enum',
                            enumName='Y=1:Z=2',
                            dv=1,
                            k=1)

                # ========================= Vis Mults =========================
                # allVis Mults
                if self.doFK:
                    fkVisMult = createNode('multDoubleLinear',
                                           n=self.names.get(
                                               'fkVisMult', 'rnm_fkVisMult'))
                    self.fkCtrlsVis = fkVisMult.o
                    self.rigNode.allVis >> fkVisMult.i1
                    self.rigNode.fkVis >> fkVisMult.i2
                    self.step(fkVisMult, 'fkVisMult')

                bendVisMult = createNode('multDoubleLinear',
                                         n=self.names.get(
                                             'bendVisMult', 'rnm_bendVisMult'))
                self.bendCtrlsVis = bendVisMult.o
                self.rigNode.allVis >> bendVisMult.i1
                self.rigNode.bendCtrlsVis >> bendVisMult.i2
                self.step(bendVisMult, 'bendVisMult')

                offsetVisMult = createNode('multDoubleLinear',
                                           n=self.names.get(
                                               'offsetVisMult',
                                               'rnm_ikVisMult'))
                self.offsetCtrlsVis = offsetVisMult.o
                self.rigNode.allVis >> offsetVisMult.i1
                self.rigNode.offsetCtrlsVis >> offsetVisMult.i2
                self.step(offsetVisMult, 'offsetVisMult')

                debugVisMult = createNode('multDoubleLinear',
                                          n=self.names.get(
                                              'debugVisMult',
                                              'rnm_debugVisMult'))
                self.debugVis = debugVisMult.o
                self.rigNode.allVis >> debugVisMult.i1
                self.rigNode.debugVis >> debugVisMult.i2
                self.step(debugVisMult, 'debugVisMult')

                # ========================= World Group =========================
                worldGroup = createNode('transform',
                                        n=self.names.get(
                                            'worldGroup', 'rnm_worldGroup'),
                                        p=self.rigGroup)
                self.worldGroup = worldGroup
                self.step(worldGroup, 'worldGroup')
                worldGroup.inheritsTransform.set(0)
                xform(worldGroup, rp=[0, 0, 0], ro=[0, 0, 0], ws=1)

                # =========================== FK Setup =================================
                if self.doFK:
                    fkGroup = self.buildFkSetup(shapes=fkShapes,
                                                transforms=jointsList,
                                                mirror=mirror)
                    self.fkCtrlsVis.connect(fkGroup.v)
                    self.fkCtrls = fkGroup.results.get()

                # for fkCtrl in self.fkCtrls:
                # fkCtrl.message.connect(self.rigNode.fkCtrls, )

                #=========================== Bend Setup =================================
                bendRigGroup = self.buildMidBendCurveSetup(
                    transforms=(self.fkCtrls if self.doFK else jointsList),
                    follow=(True if self.doFK else False),
                    shapes=endShapes,
                    controller=self.rigNode,
                    mirror=mirror)
                # print numJointsList
                # print bendRigGroup.uValues.get()

                crvPathRig = self.buildCurvePartitionsSetup(
                    self.crvs[0],
                    constraintTargets=(self.fkCtrls[:-1]
                                       if self.doFK else self.bendCtrls[:-1]),
                    partitionParams=bendRigGroup.uValues.get(),
                    numJointsList=numJointsList,
                    mirror=mirror,
                    createOffsetControls=True,
                    rotationStyle='aim',
                    twist=True)

                results = crvPathRig.results.get()
                self.offsetCtrlsVis.connect(crvPathRig.v)

                for i in range(len(jointsList)):
                    # addAttr(crvPathRig, ln='partitionParameters', multi=True, numberOfChildren=3, k=1)
                    print bendRigGroup
                    print bendRigGroup.attr('uValues%s' % i)
                    print bendRigGroup.attr('uValues%s' % i).get()
                    print crvPathRig
                    print crvPathRig.attr('partitionParameter%s' % i)
                    print crvPathRig.attr('partitionParameter%s' % i).get()
                    print '\n'
                    bendRigGroup.attr('uValues%s' % i).connect(
                        crvPathRig.attr('partitionParameter%s' % i))

                twistSettingsList = []
                if autoTwist:
                    for i in range(len(self.bendCtrls)):
                        twistSettings = self.socket(self.bendCtrls[i])
                        twistExtractorMatrix(
                            self.bendCtrls[i],
                            (self.fkCtrls[0].buf.get()
                             if self.doFK else self.bendCtrls[i].buf.get()),
                            settingsNode=twistSettings)
                        twistSettingsList.append(twistSettings)

                for i in range(len(self.bendCtrls)):
                    print '\n%s' % i
                    addAttr(self.bendCtrls[i], ln='twist', k=1)

                    rangeStart = True if i == 0 else False
                    rangeEnd = True if i == (len(self.bendCtrls) -
                                             1) else False

                    if not rangeEnd:
                        self.bendCtrls[i].twist.connect(
                            self.twistAdds[i].input2D[0].getChildren()[0])
                    if not rangeStart:
                        self.bendCtrls[i].twist.connect(
                            self.twistAdds[i - 1].input2D[0].getChildren()[1])

                    if autoTwist:
                        if not rangeEnd:
                            twistSettingsList[i].twist.connect(
                                self.twistAdds[i].input2D[1].getChildren()[0])
                        if not rangeStart:
                            twistSettingsList[i].twist.connect(
                                self.twistAdds[i -
                                               1].input2D[1].getChildren()[1])

                # self.bendCtrls[i-1].percentage.connect(offsetsGroup.startPoint)
                # self.bendCtrls[i-1].twist.connect(offsetsGroup.startTwist)
                # self.bendCtrls[i].percentage.connect(offsetsGroup.endPoint)
                # self.bendCtrls[i].twist.connect(offsetsGroup.endTwist)

                for i, res in enumerate(results):
                    # Create a bind joint for each result transform (special naming for midJoints)
                    self.naming(n=i)
                    self.names = utils.constructNames(self.namesDict)

                    bind = createNode('joint',
                                      n=self.names.get('bind', 'rnm_bind'),
                                      p=res)
                    self.step(bind, 'bind')
                    xform(bind, ws=1, ro=xform(jointsList[0], q=1, ws=1, ro=1))
                    self.bindList.append(bind)
                    # bind.attr('type').set(18)
                    # bind.otherType.set('%s' % i)
                    # bind.drawLabel.set(1)
                    bind.hide()

            #=========================== Finalize =================================
            finally:

                self.setController(fkRigGroup, self.rigGroup)
                self.setController(bezierRigGroup, self.rigGroup)
                self.setController(crvPathRig, self.rigGroup)
                try:
                    self.constructSelectionList(selectionName='bendCtrls',
                                                selectionList=self.bendCtrls)
                    self.constructSelectionList(
                        selectionName='tangentCtrls',
                        selectionList=self.tangentCtrls)
                    self.constructSelectionList(selectionName='offsetCtrls',
                                                selectionList=self.offsetCtrls)
                    self.constructSelectionList(selectionName='frozenNodes',
                                                selectionList=self.freezeList)
                except:
                    pass

                self.finalize()
示例#9
0
    def __init__(self, fitNode, crv, pointInput):
        with UndoChunk():

            # Initialize rigNode
            # Error Check:

            # Convert string input to PyNode if neccessary
            # if isinstance(fitNode, str):
            # 	fitNode = ls(fitNode)[0]

            # if fitNode.rigType.get() != 'bezierIK':
            # 	raise Exception('Incorrect rig type: %s' % fitNode.rigType.get())

            self.crv = crv

            buildRig.rig.__init__(self, fitNode)

            # Move rigGroup
            # xform(self.rigGroup, ws=1, m=xform(jointsList[0], q=1, ws=1, m=1))

            # Naming
            self.globalName = self.fitNode.globalName.get()
            self.subNames = []
            subAttrs = listAttr(self.fitNode, st='subName*')
            for subAttr in subAttrs:
                self.subNames.append(self.fitNode.attr(subAttr).get())

            doParametric = True
            doSplineIK = True

            # NAMING
            self.naming(0)
            self.names = utils.constructNames(self.namesDict)

            # ========================= RigNode Attributes =========================
            self.rigNode.rigType.set('curveDrivenIK', l=1)

            utils.cbSep(self.rigNode)

            addAttr(self.rigNode,
                    ct='publish',
                    ln='offsetCtrlsVis',
                    at='short',
                    min=0,
                    max=1,
                    dv=0,
                    k=1)
            setAttr(self.rigNode.offsetCtrlsVis,
                    keyable=False,
                    channelBox=True)

            utils.cbSep(self.rigNode, ct='publish')
            # addAttr(self.rigNode, ln='bendCtrlsVis', nn='Bend Ctrl Vis', at='short', min=0, max=1, dv=1, k=1)
            # setAttr(self.rigNode.bendCtrlsVis, k=0, cb=1)

            # addAttr(self.rigNode, ln='neutralizeAll', min=0, max=1, dv=1, k=1)

            utils.cbSep(self.rigNode, ct='publish')
            addAttr(self.rigNode,
                    ct='publish',
                    ln='stretch',
                    softMinValue=0,
                    softMaxValue=1,
                    dv=1,
                    k=1)
            addAttr(self.rigNode,
                    ct='publish',
                    ln='squash',
                    softMinValue=0,
                    softMaxValue=1,
                    dv=1,
                    k=1)
            addAttr(self.rigNode,
                    ct='publish',
                    ln='restLength',
                    min=0.01,
                    dv=1,
                    k=1)
            # addAttr(self.rigNode, ln='currentNormalizedLength', dv=0)
            # self.rigNode.currentNormalizedLength.set(k=0, cb=1)

            if not hasAttr(self.rigNode, 'upAxis'):
                utils.cbSep(self.rigNode)
                addAttr(self.rigNode,
                        ln='upAxis',
                        at='enum',
                        enumName='Y=1:Z=2',
                        dv=1,
                        k=1)

            debugVisMult = createNode('multDoubleLinear',
                                      n=self.names.get('debugVisMult',
                                                       'rnm_debugVisMult'))
            self.debugVis = debugVisMult.o
            self.rigNode.allVis >> debugVisMult.i1
            self.rigNode.debugVis >> debugVisMult.i2
            self.step(debugVisMult, 'debugVisMult')

            # ========================= World Group =========================
            worldGroup = createNode('transform',
                                    n=self.names.get('worldGroup',
                                                     'rnm_worldGroup'),
                                    p=self.rigGroup)
            self.worldGroup = worldGroup

            self.step(worldGroup, 'worldGroup')
            worldGroup.inheritsTransform.set(0)
            xform(worldGroup, rp=[0, 0, 0], ro=[0, 0, 0], ws=1)

            try:

                # if doFK:
                # 	self.matrixConstraint(self.fkCtrls[-1], bezierRigGroup, r=1, s=1)

                displaySmoothness(self.crv, pointsWire=16)

                ikSplineRig = self.buildIKSplineSetup(
                    crv=self.crv,
                    points=pointInput,
                    selectionPriority=2,
                )

                results = ikSplineRig.results.get()

                # # # =========================== Twist ===========================
                # # #### Bend ctrls
                # if doParametric and not doStretchLimit:
                # 	self.bendCtrls[0].twist.connect(				self.twistAdds[0].input2D[0].getChildren()[0])
                # 	self.socket(self.bendCtrls[0]).twist.connect(	self.twistAdds[0].input2D[1].getChildren()[0])

                # 	self.bendCtrls[1].twist.connect(				self.twistAdds[0].input2D[0].getChildren()[1])
                # 	self.socket(self.bendCtrls[1]).twist.connect(	self.twistAdds[0].input2D[1].getChildren()[1])

                # if doSplineIK:
                # 	self.bendCtrls[0].twist.connect(				self.twistAdds[0].input2D[0].getChildren()[0])
                # 	self.socket(self.bendCtrls[0]).twist.connect(	self.twistAdds[0].input2D[1].getChildren()[0])

                # 	self.bendCtrls[1].twist.connect(				self.twistAdds[0].input2D[0].getChildren()[1])
                # 	self.socket(self.bendCtrls[1]).twist.connect(	self.twistAdds[0].input2D[1].getChildren()[1])

                # staticLocatorsGroup = createNode('transform', n=self.names.get('staticLocatorsGroup', 'rnm_staticLocatorsGroup'), p=ikSplineRig)
                # self.step(staticLocatorsGroup, 'staticLocatorsGroup')

                # bezLocs = []
                # staticBezLocs = []
                # i=0
                # print '\n'
                # print crvPathRig.results.get()
                # print ikSplineRig.results.get()

                # for bezPoint, ikJnt in zip(crvPathRig.results.get(), ikSplineRig.results.get()):

                # 	# if i==4:
                # 	# 	raise Exception('4')

                # 	bezLoc2 = createNode('locator', n='%s_dist_LOC' % bezPoint, p=bezPoint)
                # 	self.step(bezLoc2, 'bezLoc')
                # 	bezLoc2.hide()
                # 	bezLocs.append(bezLoc2)

                # 	#

                # 	staticBezPoint = createNode('transform', n=self.names.get('staticBezPoint', 'rnm_staticBezPoint'), p=staticLocatorsGroup)
                # 	self.step(staticBezPoint, 'staticBezPoint')
                # 	utils.snap(bezPoint, staticBezPoint)

                # 	staticBezLoc2 = createNode('locator', n='%s_dist_LOC' % staticBezPoint, p=staticBezPoint)
                # 	self.step(staticBezLoc2, 'staticBezLoc')
                # 	staticBezLoc2.hide()
                # 	staticBezLocs.append(staticBezLoc2)

                # 	if not i==0: # Skip 0
                # 		# Distance
                # 		bezLoc1 = bezLocs[i-1]
                # 		staticBezLoc1 = staticBezLocs[i-1]

                # 		bezDist = createNode('distanceBetween', n=self.names.get('bezDist', 'rnm_bezDist'))
                # 		self.step(bezDist, 'bezDist')

                # 		bezLoc1.worldPosition.connect(bezDist.point1)
                # 		bezLoc2.worldPosition.connect(bezDist.point2)

                # 		# Static distance
                # 		staticBezDist = createNode('distanceBetween', n=self.names.get('staticBezDist', 'rnm_staticBezDist'))
                # 		self.step(staticBezDist, 'staticBezDist')

                # 		staticBezLoc1.worldPosition.connect(staticBezDist.point1)
                # 		staticBezLoc2.worldPosition.connect(staticBezDist.point2)

                # 		# # Mult static by rig input
                # 		staticBezDistMult = createNode('multDoubleLinear', n=self.names.get('staticBezDistMult', 'rnm_staticBezDistMult'))
                # 		self.step(staticBezDistMult, 'staticBezDistMult')
                # 		staticBezDist.distance.connect(staticBezDistMult.i1)
                # 		self.rigNode.restLength.connect(staticBezDistMult.i2)

                # 		# Normalize
                # 		normalizeDiv = createNode('multiplyDivide', n=self.names.get('normalizeDiv', 'rnm_normalizeDiv'))
                # 		self.step(normalizeDiv, 'normalizeDiv')
                # 		normalizeDiv.operation.set(2)

                # 		bezDist.distance.connect(normalizeDiv.input1X)
                # 		staticBezDistMult.output.connect(normalizeDiv.input2X)

                # 		# Stretch
                # 		stretchBlend = createNode( 'blendTwoAttr', n=self.names.get('stretchBlend', 'rnm_stretchBlend') )
                # 		self.step(stretchBlend, 'stretchBlend')
                # 		stretchBlend.i[0].set(1)
                # 		normalizeDiv.outputX.connect(stretchBlend.i[1])
                # 		self.rigNode.stretch.connect(stretchBlend.ab)

                # 		# Squash
                # 		squashBlend = createNode( 'blendTwoAttr', n=self.names.get('squashBlend', 'rnm_squashBlend') )
                # 		self.step(squashBlend, 'squashBlend')
                # 		squashBlend.i[0].set(1)
                # 		normalizeDiv.outputX.connect(squashBlend.i[1])
                # 		self.rigNode.squash.connect(squashBlend.ab)

                # 		# Squash/Stretch combiner
                # 		squashStretchCond = createNode( 'condition', n=self.names.get('stretchBlend', 'rnm_stretchBlend') )
                # 		self.step(squashStretchCond, 'squashStretchCond')
                # 		squashStretchCond.operation.set(2) # Greater Than
                # 		normalizeDiv.outputX.connect(squashStretchCond.firstTerm)

                # 		squashStretchCond.secondTerm.set(1)

                # 		stretchBlend.o.connect(squashStretchCond.colorIfTrueR)
                # 		squashBlend.o.connect(squashStretchCond.colorIfFalseR)

                # 		restLengthMult = createNode('multDoubleLinear', n=self.names.get('restLengthMult', 'rnm_restLengthMult'))
                # 		self.step(restLengthMult, 'restLengthMult')
                # 		squashStretchCond.outColorR.connect(restLengthMult.i1)
                # 		self.rigNode.restLength.connect(restLengthMult.i2)

                # 		denormalizeMult = createNode('multDoubleLinear', n=self.names.get('denormalizeMult', 'rnm_denormalizeMult'))
                # 		self.step(denormalizeMult, 'denormalizeMult')
                # 		denormalizeMult.i1.set(bezDist.distance.get())
                # 		restLengthMult.o.connect(denormalizeMult.i2)

                # 		denormalizeMult.o.connect(ikJnt.tx)

                # 	i=i+1

                # results = ikSplineRig.results.get()

                offsetResults = []
                # Offset controls
                for i, point in enumerate(results):
                    ctrlParent = None

                    ctrlParent = offsetResults[i - 1] if i else self.rigGroup

                    self.naming(n=i)
                    self.names = utils.constructNames(self.namesDict)
                    par = point
                    offsetCtrl = self.createControlHeirarchy(
                        name=self.names.get('offsetCtrl', 'rnm_offsetCtrl'),
                        transformSnap=point,
                        selectionPriority=2,
                        ctrlParent=ctrlParent,
                        outlinerColor=(0, 0, 0),
                        par=par)

                    offsetResults.append(offsetCtrl)
                    self.rigNode.offsetCtrlsVis.connect(offsetCtrl.buf.get().v)

                results = offsetResults

                # results = self.buildScaleLengthSetup(scaleInputs=self.bendCtrls, distanceInputs=[results[0], results[1]], nodes=results, settingsNode=self.rigNode)

                # results = []
                print 'Results:'
                print results
                for i, point in enumerate(results):

                    self.naming(n=i)
                    self.names = utils.constructNames(self.namesDict)

                    point.message.connect(self.rigNode.socketList, na=1)
                    # self.socketList.append(point)

                    bind = createNode('joint',
                                      n=self.names.get('bind', 'rnm_bind'),
                                      p=point)
                    self.bindList.append(bind)
                    self.step(bind, 'bind')
                    bind.hide()

                # crvPathRig = self.buildParametricCurveRigSetup(
                # 	self.crv,
                # 	numJoints=1,
                # 	stretch=False
                # 	)
                # results = crvPathRig.results.get()

                # rigExit = createNode('transform', n=self.names.get('rigExit', 'rnm_rigExit'), p=self.rigGroup)
                # self.step(rigExit, 'rigExit')
                # self.socket(rigExit).message.connect(self.rigNode.socketList, na=1)
                # utils.snap(point, rigExit)
                # self.matrixConstraint(point, rigExit, t=1, r=1, s=1, offset=True)

                # if bindEnd:
                # 	# # rig exit bind
                # 	rigExitBind = createNode( 'joint', n=self.names.get( 'rigExitBind', 'rnm_rigExitBind'), p=rigExit )
                # 	self.step(rigExitBind, 'rigExitBind')
                # 	self.bindList.append(rigExitBind)
                # 	rigExitBind.hide()

                #=========================== Finalize =================================

            except:
                raise

            finally:
                # try:
                # 	for bendCtrl in self.bendCtrls:
                # 		attrs = bendCtrl.s.getChildren()
                # 		for a in attrs:
                # 			a.set(l=1, k=0)
                # except:
                # 	pass
                # try:
                # 	self.setController(fkGroup, self.rigGroup)
                # 	self.setController(bezierRigGroup, self.rigGroup)
                # except:
                # 	pass
                try:
                    # self.constructSelectionList(selectionName='bendCtrls', selectionList=self.bendCtrls)
                    # self.constructSelectionList(selectionName='tangentCtrls', selectionList=self.tangentCtrls)
                    self.constructSelectionList(selectionName='offsetCtrls',
                                                selectionList=self.offsetCtrls)
                    self.constructSelectionList(selectionName='frozenNodes',
                                                selectionList=self.freezeList)
                except:
                    pass

                self.finalize()
示例#10
0
    def __init__(self, fitNode=None, rigNode=None):

        if fitNode is None and rigNode is None:
            raise Exception('No data specified.')

        elif fitNode is None:
            self.rigNode = rigNode
            # Put any attributes needed for initialized rigs here

        else:
            try:
                # Initialize rigNode
                # Error Check:

                # Convert string input to PyNode if neccessary
                if isinstance(fitNode, str):
                    fitNode = ls(fitNode)[0]

                if fitNode.rigType.get() != 'chain':
                    raise Exception('Incorrect rig type: %s' %
                                    fitNode.rigType.get())

                self.offsetCtrls = []
                # self.crvs = []

                buildRig.rig.__init__(self, fitNode)

                # fitNode attributes

                jointsList = self.fitNode.jointsList.get()
                fkShapes = self.fitNode.fkShapes.get()
                ikShapes = self.fitNode.ikShapes.get()
                doIK = self.fitNode.offsets.get()

                multiChain = 0
                if hasAttr(self.fitNode, 'multiChain'):
                    multiChain = self.fitNode.multiChain.get()

                doHierarchy = True
                if hasAttr(self.fitNode, 'doHierarchy'):
                    doHierarchy = self.fitNode.doHierarchy.get()

                # if doHierarchy:
                # organize jointsList
                # Move rigGroup
                xform(self.rigGroup,
                      ws=1,
                      m=xform(jointsList[0], q=1, ws=1, m=1))

                # Mirroring
                if self.fitNode.side.get() == 2:
                    mirror = True
                else:
                    mirror = False

                # Per joint mirroring
                mirrorList = []
                for jnt in jointsList:
                    if jnt.autoMirror.get() is False:
                        mirrorList.append(False)
                    elif jnt.side.get() == 2:
                        mirrorList.append(True)
                    else:
                        mirrorList.append(False)
                if self.dev:
                    print 'mirrorList:'
                    print mirrorList

                if hasAttr(self.fitNode, 'bind'):
                    doBind = self.fitNode.bind.get()
                else:
                    doBind = True

                if hasAttr(self.fitNode, 'doFK'):
                    doFK = self.fitNode.doFK.get()
                else:
                    doFK = True

                # Make sure one of the options are on by default
                if not doFK and not doIK:
                    doFK = True

                if hasAttr(self.fitNode, 'doEntranceBind'):
                    doEntranceBind = bool(self.fitNode.doEntranceBind.get())
                else:
                    doEntranceBind = True

                # raise Exception('end test.')
                # Naming
                self.globalName = self.fitNode.globalName.get()
                self.subNames = []
                subAttrs = listAttr(self.fitNode, st='subName*')
                for subAttr in subAttrs:
                    self.subNames.append(self.fitNode.attr(subAttr).get())
                # print 'subnames:'
                # print self.subNames

                self.naming()
                self.names = utils.constructNames(self.namesDict)

                # ========================= RigNode Attributes =========================
                self.rigNode.rigType.set('chain', l=1)
                if doFK or doIK:
                    utils.cbSep(self.rigNode)
                if doFK:
                    addAttr(self.rigNode,
                            ct='publish',
                            ln='fkVis',
                            nn='FK Vis',
                            at='short',
                            min=0,
                            max=1,
                            dv=1)
                    setAttr(self.rigNode.fkVis, keyable=False, channelBox=True)
                if doIK:
                    addAttr(self.rigNode,
                            ct='publish',
                            ln='ikVis',
                            nn='IK Vis',
                            at='short',
                            min=0,
                            max=1,
                            dv=1)
                    setAttr(self.rigNode.ikVis, keyable=False, channelBox=True)

                # ========================= Vis Mults =========================
                # allVis Mults
                if doFK:
                    fkVisMult = createNode('multDoubleLinear',
                                           n=self.names.get(
                                               'fkVisMult', 'rnm_fkVisMult'))
                    self.rigNode.allVis >> fkVisMult.i1
                    self.rigNode.fkVis >> fkVisMult.i2
                    self.step(fkVisMult, 'fkVisMult')

                if doIK:
                    ikVisMult = createNode('multDoubleLinear',
                                           n=self.names.get(
                                               'ikVisMult', 'rnm_ikVisMult'))
                    self.rigNode.allVis >> ikVisMult.i1
                    self.rigNode.ikVis >> ikVisMult.i2
                    self.ikVis = ikVisMult.o
                    self.step(ikVisMult, 'ikVisMult')

                # debugVisMult = createNode('multDoubleLinear', n=self.names.get('debugVisMult', 'rnm_debugVisMult'))
                # self.debugVis = debugVisMult.o
                # self.rigNode.allVis >> debugVisMult.i1
                # self.rigNode.debugVis >> debugVisMult.i2
                # self.step(debugVisMult, 'debugVisMult')

                # ========================= World Group =========================
                # worldGroup = createNode('transform', n=self.names.get('worldGroup', 'rnm_worldGroup'), p=self.rigGroup)
                # self.worldGroup = worldGroup
                # self.step(worldGroup, 'worldGroup')
                # worldGroup.inheritsTransform.set(0)
                # xform(worldGroup, rp=[0,0,0], ro=[0,0,0], ws=1)

                #=========================== FK Setup =================================

                if doHierarchy:
                    print '\nJointsList:'
                    print jointsList
                    # We're going to form a hierarchy of controls based on a 'clump' of joints input as a list

                    # Reorder joints list so that we create controls top-down
                    heirScore = {}
                    for item in jointsList:
                        heirScore[item] = (len(item.getAllParents()))

                    import operator
                    sortedHeir = sorted(heirScore.items(),
                                        key=operator.itemgetter(1))

                    jointsList2 = []
                    for s in sortedHeir:
                        jointsList2.append(s[0])

                    print '\nJointsList2:'
                    print jointsList2

                    # Map controls to each joint
                    ctrlMapping = {}
                    for i, jnt in enumerate(jointsList2):

                        ind = jointsList.index(jnt)
                        self.naming(i=ind)
                        self.names = utils.constructNames(self.namesDict)

                        # Reach upward into each joint's parentage.  If no fit joints in list up to top, it's a root joint. otherwise, use first parent found
                        jntParent = jnt.getParent()
                        while not jntParent in jointsList2:
                            if jntParent is None:
                                break
                            jntParent = jntParent.getParent()

                        # If it found anything, get the control for that joint
                        if jntParent:
                            ctrlParent = ctrlMapping[jntParent]
                        else:
                            ctrlParent = None

                        if ctrlParent:
                            ctrl = self.createControlHeirarchy(
                                selectionPriority=0,
                                transformSnap=jnt,
                                mirrorStart=mirrorList[ind],
                                mirror=mirrorList[ind],
                                name=self.names.get('fkCtrl', 'rnm_fkCtrl'),
                                shape=fkShapes[ind],
                                par=ctrlParent,
                                ctrlParent=ctrlParent,
                                jntBuf=True)
                            # ctrl = createNode('transform', name=self.names.get('fkCtrl', 'rnm_fkCtrl'), p=ctrlParent)
                        else:
                            ctrl = self.createControlHeirarchy(
                                selectionPriority=0,
                                transformSnap=jnt,
                                mirrorStart=mirrorList[ind],
                                mirror=mirrorList[ind],
                                name=self.names.get('fkCtrl', 'rnm_fkCtrl'),
                                shape=fkShapes[ind],
                                par=self.rigGroup,
                                ctrlParent=self.rigGroup,
                                jntBuf=True)
                            # ctrl = createNode('transform', name=self.names.get('fkCtrl', 'rnm_fkCtrl'), p=self.rigGroup)

                        ctrlMapping[jnt] = ctrl

                        try:
                            self.fkCtrls.append(ctrl)
                        except AttributeError:
                            self.fkCtrls = []
                            self.fkCtrls.append(ctrl)

                        if ctrl.getShapes():
                            fkVisMult.o.connect(ctrl.getShapes()[0].v)
                        self.socket(ctrl).message.connect(
                            self.rigNode.socketList, na=1)

                    if self.dev:
                        print '\nctrlMapping:'
                        print ctrlMapping
                        for item, key in ctrlMapping.items():
                            print '%s\t-\t%s' % (item, key)

                else:
                    if doFK:
                        fkGroup = self.buildFkSetup(shapes=fkShapes,
                                                    transforms=jointsList,
                                                    mirror=mirror)
                        fkVisMult.o.connect(fkGroup.v)

                        if not doIK:
                            for fkCtrl in self.fkCtrls:
                                self.socket(fkCtrl).message.connect(
                                    self.rigNode.socketList, na=1)

                #=========================== Offset Setup =================================
                # Whether or not fk is created
                if doIK:
                    for i, jnt in enumerate(jointsList):
                        self.naming(i=i)
                        self.names = utils.constructNames(self.namesDict)

                        # If fk ctrls were created, parent them there
                        if doFK:
                            offsetCtrl = self.createControlHeirarchy(
                                selectionPriority=0,
                                mirror=mirror,
                                name=self.names.get('offsetCtrl',
                                                    'rnm_offsetCtrl'),
                                shape=ikShapes[i],
                                par=self.fkCtrls[i],
                                ctrlParent=self.fkCtrls[i],
                                jntBuf=False,
                                outlinerColor=(0, 0, 0))

                        # Else create offset controls on their own
                        else:
                            offsetCtrl = self.createControlHeirarchy(
                                selectionPriority=0,
                                mirror=mirror,
                                name=self.names.get('offsetCtrl',
                                                    'rnm_offsetCtrl'),
                                shape=ikShapes[i],
                                par=self.rigGroup,
                                ctrlParent=self.rigGroup,
                                jntBuf=False,
                                transformSnap=jnt)

                        self.offsetCtrls.append(offsetCtrl)
                        self.ctrlsList.append(offsetCtrl)

                        self.ikVis.connect(offsetCtrl.buf.get().v)

                        try:
                            self.ikCtrls.append(offsetCtrl)
                        except AttributeError:
                            self.ikCtrls = []
                            self.ikCtrls.append(offsetCtrl)

                        self.socket(offsetCtrl).message.connect(
                            self.rigNode.socketList, na=1)

                if doBind:
                    if doEntranceBind:
                        # Transform to handle distribution of mesh with root moved without rotation
                        rigEntranceGrp = createNode('transform',
                                                    n=self.names.get(
                                                        'rigEntranceGrp',
                                                        'rnm_rigEntranceGrp'),
                                                    p=self.rigGroup)
                        self.step(rigEntranceGrp, 'rigEntranceGrp')

                        # point constrain to start node
                        utils.snap(jointsList[0], rigEntranceGrp)
                        self.matrixConstraint(
                            self.ikCtrls[0] if doIK else self.fkCtrls[0],
                            rigEntranceGrp,
                            t=1)

                        rigEntrance = createNode('joint',
                                                 n=self.names.get(
                                                     'rigEntrance',
                                                     'rnm_rigEntrance'),
                                                 p=rigEntranceGrp)
                        self.step(rigEntrance, 'rigEntrance')
                        self.bindList.append(rigEntrance)
                        rigEntrance.hide()

                    for i, ctrl in enumerate(
                            self.ikCtrls if doIK else self.fkCtrls):
                        self.naming(i=i)
                        self.names = utils.constructNames(self.namesDict)

                        if mirror:
                            ctrl = self.socket(ctrl)
                        # 	ctrl.rotateY.set(-180)
                        # 	ctrl.scaleX.set(-1)

                        bind = createNode('joint',
                                          n=self.names.get('bind', 'rnm_bind'),
                                          p=ctrl)
                        self.bindList.append(bind)
                        self.step(bind, 'bind')
                        bind.hide()

            finally:

                #=========================== Finalize =================================

                try:
                    self.setController(fkRigGroup, self.rigGroup)
                except:
                    pass

                try:
                    self.constructSelectionList(selectionName='fkCtrls',
                                                selectionList=self.fkCtrls)
                    if doIK:
                        self.constructSelectionList(
                            selectionName='offsetCtrls',
                            selectionList=self.offsetCtrls)
                    self.constructSelectionList(selectionName='frozenNodes',
                                                selectionList=self.freezeList)
                except:
                    pass

                self.finalize()
示例#11
0
def matrixCollision(control=None, constrained=None, surface=None):
    # Creates a simple collision detector that orients object to surface

    # Create nodes if not supplied
    if control is None:
        control = createNode('transform', n='matrixCollisionControl')
    if constrained is None:
        constrained = createNode('transform', n='matrixCollisionConstrained')
    if surface is None:
        surface, surfaceCH = polyPlane(n='matrixCollisionSurface',
                                       sx=10,
                                       sy=10,
                                       w=10,
                                       h=10,
                                       constructionHistory=True,
                                       createUVs=0)
        print surface
    # Error checks

    base = control.getParent()
    if base is None:
        raise Exception('Control object has no parent.')

    # Convert to string to pynode if necessary
    if isinstance(control, str) or isinstance(control, unicode):
        if len(ls(control)) == 1:
            control = ls(control)[0]
        elif len(ls(control)) == 0:
            raise Exception('No object found with name: %s' % control)
        else:
            raise Exception('More than one object found with name: %s' %
                            control)

    if isinstance(constrained, str) or isinstance(constrained, unicode):
        if len(ls(constrained)) == 1:
            constrained = ls(constrained)[0]
        elif len(ls(constrained)) == 0:
            raise Exception('No object found with name: %s' % constrained)
        else:
            raise Exception('More than one object found with name: %s' %
                            constrained)

    if isinstance(surface, str) or isinstance(surface, unicode):
        if len(ls(surface)) == 1:
            surface = ls(surface)[0]
        elif len(ls(surface)) == 0:
            raise Exception('No object found with name: %s' % surface)
        else:
            raise Exception('More than one object found with name: %s' %
                            surface)

    # Test input types
    for i, testNode in enumerate([control, constrained]):
        if not isinstance(testNode, nt.Transform):
            raise Exception('Input arugument %s is not a transform: %s' %
                            (['control', 'constrained'][i], testNode))

    # Set surface to the actual transform if it's been input as the shape node
    if isinstance(surface, nt.Mesh):
        sufaceShape = surface
        surface = sufaceShape.getParent()
    else:
        if not isinstance(surface, nt.Transform):
            raise Exception('Input arugument surface is not a transform: %s' %
                            (surface))
        else:
            if not surface.getShapes():
                raise Exception('No shape found under surface input: %s' %
                                (surface))
            else:
                surfaceShape = None
                for shp in surface.getShapes():
                    if isinstance(shp, nt.Mesh):
                        surfaceShape = shp
                        break
                if not surfaceShape:
                    raise Exception(
                        ('No mesh found under surface input: %s' % (surface)))

    # Naming
    names = {
        'collisionPoint': 'collisionPoint',
        'twistComp': 'twistComp',
        'collPointDecmp': 'collPointDecmp',
        'closest': 'closest',
        'twistAdd': 'twistAdd',
        'axZ': 'axZ',
        'axX': 'axX',
        'fourByFour': 'fourByFour',
        'diffMat': 'diffMat',
        'diffDecmp': 'diffDecmp',
        'distRng': 'distRng',
        'offsetMat': 'offsetMat',
        'controlDecmp': 'controlDecmp',
        'offsetDecmp': 'offsetDecmp',
        'rotBlnd': 'rotBlnd',
        'transCond': 'transCond',
    }

    # Initialize Build

    # Collision Point under control to determine where to halt transform
    collisionPoint = createNode('transform',
                                n=names.get('collisionPoint'),
                                p=control)
    collisionPoint.displayHandle.set(1, k=1)

    utils.cbSep(collisionPoint)
    addAttr(collisionPoint, ln='collisionDistance', min=0, dv=1, k=1)

    collPointDecmp = createNode('decomposeMatrix',
                                n=names.get('collPointDecmp'))
    collisionPoint.worldMatrix.connect(collPointDecmp.inputMatrix)

    # Closest point
    closest = createNode('closestPointOnMesh', n=names.get('closest'))
    collPointDecmp.outputTranslate.connect(closest.inPosition)
    surfaceShape.outMesh.connect(closest.inMesh)
    surface.worldMatrix.connect(closest.inputMatrix)

    # use twist on axis to orient result transform
    buildRig.twistExtractorMatrix(points=[control],
                                  base=base,
                                  settingsNode=collisionPoint,
                                  twistAxisChoice=1)

    twistAdd = createNode('animBlendNodeAdditiveRotation',
                          n=names.get('twistAdd'))
    collisionPoint.twist.connect(twistAdd.inputAY)
    twistAdd.rotateOrder.set(1)
    twistAdd.rotationInterpolation.set(1)

    # Vector Product Z (convert closest point normal to standard matrix by getting double cross product)
    axZ = createNode('vectorProduct', n=names.get('axZ'))
    axZ.operation.set(2)  # Cross product
    axZ.input1.set(1, 0, 0)
    axZ.normalizeOutput.set(1)
    closest.normal.connect(axZ.input2)

    # Vector Product X (convert closest point normal to standard matrix by getting double cross product)
    axX = createNode('vectorProduct', n=names.get('axX'))
    axX.operation.set(2)  # Cross product
    axX.normalizeOutput.set(1)
    closest.normal.connect(axX.input1)
    axZ.output.connect(axX.input2)

    # Four by four matrix (Construct result of closest point to matrix)
    fourByFour = createNode('fourByFourMatrix', n=names.get('fourByFour'))
    axX.outputX.connect(fourByFour.in00)
    axX.outputY.connect(fourByFour.in01)
    axX.outputZ.connect(fourByFour.in02)

    closest.normalX.connect(fourByFour.in10)
    closest.normalY.connect(fourByFour.in11)
    closest.normalZ.connect(fourByFour.in12)

    axZ.outputX.connect(fourByFour.in20)
    axZ.outputY.connect(fourByFour.in21)
    axZ.outputZ.connect(fourByFour.in22)

    closest.positionX.connect(fourByFour.in30)
    closest.positionY.connect(fourByFour.in31)
    closest.positionZ.connect(fourByFour.in32)

    # Create a matrix to measure difference between collision point and closest point
    diffMat = createNode('multMatrix', n=names.get('diffMat'))
    fourByFour.output.connect(diffMat.matrixIn[0])
    collisionPoint.worldInverseMatrix.connect(diffMat.matrixIn[1])

    diffDecmp = createNode('decomposeMatrix', n=names.get('diffDecmp'))
    diffMat.matrixSum.connect(diffDecmp.inputMatrix)

    distRng = createNode('setRange', n=names.get('distRng'))
    diffDecmp.outputTranslateY.connect(distRng.valueX)
    distRng.minX.set(0)
    distRng.maxX.set(1)
    distRng.oldMinX.set(-1)
    distRng.oldMaxX.set(0)

    uc = createNode('unitConversion')
    uc.conversionFactor.set(-1)

    collisionPoint.collisionDistance.connect(uc.input)
    uc.output.connect(distRng.oldMinX)

    offsetMat = createNode('multMatrix', n=names.get('offsetMat'))
    diffMat.matrixSum.connect(offsetMat.matrixIn[0])
    control.worldMatrix.connect(offsetMat.matrixIn[1])

    controlDecmp = createNode('decomposeMatrix', n=names.get('controlDecmp'))
    control.worldMatrix.connect(controlDecmp.inputMatrix)

    offsetDecmp = createNode('decomposeMatrix', n=names.get('offsetDecmp'))
    offsetMat.matrixSum.connect(offsetDecmp.inputMatrix)

    offsetDecmp.outputRotate.connect(twistAdd.inputB)

    rotBlnd = createNode('pairBlend', n=names.get('rotBlnd'))
    rotBlnd.translateXMode.set(1)
    rotBlnd.translateYMode.set(1)
    rotBlnd.translateZMode.set(1)
    rotBlnd.rotInterpolation.set(1)
    distRng.outValueX.connect(rotBlnd.weight)

    twistAdd.o.connect(rotBlnd.inRotate2)

    controlDecmp.outputRotate.connect(rotBlnd.inRotate1)
    rotBlnd.outRotate.connect(constrained.rotate)

    transCond = createNode('condition', n=names.get('transCond'))
    diffDecmp.outputTranslateY.connect(transCond.firstTerm)
    transCond.secondTerm.set(0)
    transCond.operation.set(2)
    offsetDecmp.outputTranslate.connect(transCond.colorIfTrue)
    controlDecmp.outputTranslate.connect(transCond.colorIfFalse)
    transCond.outColor.connect(constrained.translate)

    # Freeze collision point control
    for attribute in [
            collisionPoint.tx, collisionPoint.tz, collisionPoint.rx,
            collisionPoint.ry, collisionPoint.rz, collisionPoint.sx,
            collisionPoint.sy, collisionPoint.sz
    ]:
        attribute.set(l=1, k=0)