def getRigBuildData(self): """Returns the Guide data used by the Rig Component to define the layout of the final rig.. Return: The JSON rig data object. """ data = super(FKChainComponentGuide, self).getRigBuildData() numJoints = self.numJoints.getValue() # Calculate Xfos fw = Vec3(0, 0, 1) boneXfos = [] boneLengths = [] for i in xrange(numJoints): boneVec = self.jointCtrls[i + 1].xfo.tr.subtract( self.jointCtrls[i].xfo.tr) boneLengths.append(boneVec.length()) bone1Normal = fw.cross(boneVec).unit() bone1ZAxis = boneVec.cross(bone1Normal).unit() xfo = Xfo() xfo.setFromVectors(boneVec.unit(), bone1Normal, bone1ZAxis, self.jointCtrls[i].xfo.tr) boneXfos.append(xfo) data['boneXfos'] = boneXfos data['endXfo'] = self.jointCtrls[-1].xfo data['boneLengths'] = boneLengths return data
def __init__(self, name='limb', parent=None, *args, **kwargs): Profiler.getInstance().push("Construct StretchyLimb Guide Component:" + name) super(StretchyLimbComponentGuide, self).__init__(name, parent, *args, **kwargs) # ========= # Controls # ======== guideSettingsAttrGrp = AttributeGroup("GuideSettings", parent=self) # Guide Controls self.upperCtl = Control('upper', parent=self.ctrlCmpGrp, shape="sphere") self.lowerCtl = Control('lower', parent=self.ctrlCmpGrp, shape="sphere") self.endCtl = Control('end', parent=self.ctrlCmpGrp, shape="sphere") self.default_data = { "name": name, "location": "L", "upperXfo": Xfo(Vec3(0.9811, 9.769, -0.4572)), "lowerXfo": Xfo(Vec3(1.4488, 5.4418, -0.5348)), "endXfo": Xfo(Vec3(1.841, 1.1516, -1.237)) } self.loadData(self.default_data) Profiler.getInstance().pop()
def computeOffset(self): """Invokes the constraint and computes the offset Returns: xfo: The offset to be used for the constraint. """ if self._constrainee is None: return Xfo() if len(self._constrainers) == 0: return Xfo() if not self.getMaintainOffset(): return Xfo() cls = self.__class__.__name__ ks.loadExtension('KrakenForCanvas') rtVal = ks.rtVal('KrakenForCanvas::Kraken%s' % cls) rtVal.offset = ks.rtVal('Mat44', Mat44()) for c in self._constrainers: rtVal.addConstrainer('', ks.rtVal('Xfo', c.globalXfo).toMat44('Mat44')) return Xfo( rtVal.computeOffset( "Xfo", ks.rtVal('Xfo', self._constrainee.xfo).toMat44('Mat44')))
def getRigBuildData(self): """Returns the Guide data used by the Rig Component to define the layout of the final rig.. Return: The JSON rig data object. """ data = super(ClavicleComponentGuide, self).getRigBuildData() # Values claviclePosition = self.clavicleCtrl.xfo.tr clavicleUpV = self.clavicleUpVCtrl.xfo.tr clavicleEndPosition = self.clavicleEndCtrl.xfo.tr # Calculate Clavicle Xfo rootToEnd = clavicleEndPosition.subtract(claviclePosition).unit() rootToUpV = clavicleUpV.subtract(claviclePosition).unit() bone1ZAxis = rootToUpV.cross(rootToEnd).unit() bone1Normal = bone1ZAxis.cross(rootToEnd).unit() clavicleXfo = Xfo() clavicleXfo.setFromVectors(rootToEnd, bone1Normal, bone1ZAxis, claviclePosition) clavicleLen = claviclePosition.subtract(clavicleEndPosition).length() data['clavicleXfo'] = clavicleXfo data['clavicleLen'] = clavicleLen return data
def __init__(self, name='leg', parent=None, data=None): Profiler.getInstance().push("Construct Leg Guide Component:" + name) super(LegComponentGuide, self).__init__(name, parent) # ========= # Controls # ======== guideSettingsAttrGrp = AttributeGroup("GuideSettings", parent=self) # Guide Controls self.femurCtrl = Control('femur', parent=self.ctrlCmpGrp, shape="sphere") self.kneeCtrl = Control('knee', parent=self.ctrlCmpGrp, shape="sphere") self.ankleCtrl = Control('ankle', parent=self.ctrlCmpGrp, shape="sphere") self.toeCtrl = Control('toe', parent=self.ctrlCmpGrp, shape="sphere") self.toeTipCtrl = Control('toeTip', parent=self.ctrlCmpGrp, shape="sphere") if data is None: data = { "name": name, "location": "L", "femurXfo": Xfo(Vec3(0.9811, 9.769, -0.4572)), "kneeXfo": Xfo(Vec3(1.4488, 5.4418, -0.5348)), "ankleXfo": Xfo(Vec3(1.841, 1.1516, -1.237)), "toeXfo": Xfo(Vec3(1.85, 0.4, 0.25)), "toeTipXfo": Xfo(Vec3(1.85, 0.4, 1.5)) } self.loadData(data) Profiler.getInstance().pop()
def __init__(self, name='clavicle', parent=None, data=None): Profiler.getInstance().push("Construct Clavicle Guide Component:" + name) super(ClavicleComponentGuide, self).__init__(name, parent) # ========= # Controls # ========= # Guide Controls guideSettingsAttrGrp = AttributeGroup("GuideSettings", parent=self) self.clavicleCtrl = Control('clavicle', parent=self.ctrlCmpGrp, shape="sphere") self.clavicleUpVCtrl = Control('clavicleUpV', parent=self.ctrlCmpGrp, shape="triangle") self.clavicleUpVCtrl.setColor('red') self.clavicleEndCtrl = Control('clavicleEnd', parent=self.ctrlCmpGrp, shape="sphere") if data is None: data = { "name": name, "location": "L", "clavicleXfo": Xfo(Vec3(0.1322, 15.403, -0.5723)), "clavicleUpVXfo": Xfo(Vec3(0.0, 1.0, 0.0)), "clavicleEndXfo": Xfo(Vec3(2.27, 15.295, -0.753)) } self.loadData(data) Profiler.getInstance().pop()
def setTransform(self, kSceneItem): """Translates the transform to Maya transform. Args: kSceneItem -- Object: object to set the transform on. Return: bool: True if successful. """ nodeAndPort = self.rigGraph.getNodeAndPortSI(kSceneItem, asInput=False) if not nodeAndPort: return False (node, port) = nodeAndPort constructorNode = self.rigGraph.getNodeSI(kSceneItem, title='constructor') if node != constructorNode: self.rigGraph.setPortDefaultValue(constructorNode, "xfo", Xfo()) parentXfo = Xfo(self.rigGraph.computeCurrentPortValue(node, port)) invXfo = parentXfo.inverse() localXfo = invXfo.multiply(kSceneItem.xfo) self.rigGraph.setPortDefaultValue(constructorNode, "xfo", localXfo) return True self.rigGraph.setPortDefaultValue(constructorNode, "xfo", kSceneItem.xfo) return True
def getRigBuildData(self): """Returns the Guide data used by the Rig Component to define the layout of the final rig.. Return: The JSON rig data object. """ data = super(FKChainComponentGuide, self).getRigBuildData() numJoints = self.numJoints.getValue() # Calculate Xfos fw = Vec3(0, 0, 1) boneXfos = [] boneLengths = [] for i in xrange(numJoints): boneVec = self.jointCtrls[i + 1].xfo.tr.subtract(self.jointCtrls[i].xfo.tr) boneLengths.append(boneVec.length()) bone1Normal = fw.cross(boneVec).unit() bone1ZAxis = boneVec.cross(bone1Normal).unit() xfo = Xfo() xfo.setFromVectors(boneVec.unit(), bone1Normal, bone1ZAxis, self.jointCtrls[i].xfo.tr) boneXfos.append(xfo) data['boneXfos'] = boneXfos data['endXfo'] = self.jointCtrls[-1].xfo data['boneLengths'] = boneLengths return data
def getRigBuildData(self): """Returns the Guide data used by the Rig Component to define the layout of the final rig. Return: The JSON rig data object. """ data = super(NeckComponentGuide, self).getRigBuildData() # values neckEndPosition = self.neckCtrl.xfo.tr neckPosition = self.neckEndCtrl.xfo.tr neckUpV = Vec3(0.0, 0.0, -1.0) # Calculate Neck Xfo rootToEnd = neckEndPosition.subtract(neckPosition).unit() rootToUpV = neckUpV.subtract(neckPosition).unit() bone1ZAxis = rootToUpV.cross(rootToEnd).unit() bone1Normal = bone1ZAxis.cross(rootToEnd).unit() neckXfo = Xfo() neckXfo.setFromVectors(rootToEnd, bone1Normal, bone1ZAxis, neckPosition) data['neckXfo'] = neckXfo return data
def __init__(self, name='head', parent=None, *args, **kwargs): Profiler.getInstance().push("Construct Head Guide Component:" + name) super(HeadComponentGuide, self).__init__(name, parent, *args, **kwargs) # ========= # Controls # ========= guideSettingsAttrGrp = AttributeGroup("GuideSettings", parent=self) sphereCtrl = Control('sphere', shape='sphere') sphereCtrl.scalePoints(Vec3(0.375, 0.375, 0.375)) self.headCtrl = Control('head', parent=self.ctrlCmpGrp, shape='square') self.headCtrl.rotatePoints(90, 0, 0) self.headCtrl.translatePoints(Vec3(0.0, 0.5, 0.0)) self.headCtrl.scalePoints(Vec3(1.8, 2.0, 2.0)) self.eyeLeftCtrl = Control('eyeLeft', parent=self.headCtrl, shape='arrow_thin') self.eyeLeftCtrl.translatePoints(Vec3(0, 0, 0.5)) self.eyeLeftCtrl.rotatePoints(0, 90, 0) self.eyeLeftCtrl.appendCurveData(sphereCtrl.getCurveData()) self.eyeRightCtrl = Control('eyeRight', parent=self.headCtrl, shape='arrow_thin') self.eyeRightCtrl.translatePoints(Vec3(0, 0, 0.5)) self.eyeRightCtrl.rotatePoints(0, 90, 0) self.eyeRightCtrl.appendCurveData(sphereCtrl.getCurveData()) self.jawCtrl = Control('jaw', parent=self.headCtrl, shape='square') self.jawCtrl.rotatePoints(90, 0, 0) self.jawCtrl.rotatePoints(0, 90, 0) self.jawCtrl.translatePoints(Vec3(0.0, -0.5, 0.5)) self.jawCtrl.scalePoints(Vec3(1.0, 0.8, 1.5)) self.jawCtrl.setColor('orange') eyeXAlignOri = Quat() eyeXAlignOri.setFromAxisAndAngle(Vec3(0, 1, 0), Math_degToRad(-90)) self.default_data = { "name": name, "location": "M", "headXfo": Xfo(Vec3(0.0, 17.5, -0.5)), "headCrvData": self.headCtrl.getCurveData(), "eyeLeftXfo": Xfo(tr=Vec3(0.375, 18.5, 0.5), ori=eyeXAlignOri), "eyeLeftCrvData": self.eyeLeftCtrl.getCurveData(), "eyeRightXfo": Xfo(tr=Vec3(-0.375, 18.5, 0.5), ori=eyeXAlignOri), "eyeRightCrvData": self.eyeRightCtrl.getCurveData(), "jawXfo": Xfo(Vec3(0.0, 17.875, -0.275)), "jawCrvData": self.jawCtrl.getCurveData() } self.loadData(self.default_data) Profiler.getInstance().pop()
def getRigBuildData(self): """Returns the Guide data used by the Rig Component to define the layout of the final rig.. Return: The JSON rig data object. """ data = super(StretchyLimbComponentGuide, self).getRigBuildData() # Values startPos = self.upperCtl.xfo.tr midPos = self.lowerCtl.xfo.tr endPos = self.endCtl.xfo.tr # Calculate Upper Xfo startToEnd = endPos.subtract(startPos).unit() startToMid = midPos.subtract(startPos).unit() bone1Normal = startToEnd.cross(startToMid).unit() bone1ZAxis = startToMid.cross(bone1Normal).unit() upperXfo = Xfo() upperXfo.setFromVectors(startToMid, bone1Normal, bone1ZAxis, startPos) # Calculate Lower Xfo midToEnd = endPos.subtract(midPos).unit() midToStart = startPos.subtract(midPos).unit() bone2Normal = midToStart.cross(midToEnd).unit() bone2ZAxis = midToEnd.cross(bone2Normal).unit() lowerXfo = Xfo() lowerXfo.setFromVectors(midToEnd, bone2Normal, bone2ZAxis, midPos) upperLen = startPos.subtract(midPos).length() lowerLen = endPos.subtract(midPos).length() handleXfo = Xfo() handleXfo.tr = endPos endXfo = Xfo() endXfo.tr = endPos # endXfo.ori = lowerXfo.ori upVXfo = xfoFromDirAndUpV(startPos, endPos, midPos) upVXfo.tr = midPos upVXfo.tr = upVXfo.transformVector(Vec3(0, 0, 5)) data['upperXfo'] = upperXfo data['lowerXfo'] = lowerXfo data['endXfo'] = endXfo data['handleXfo'] = handleXfo data['upVXfo'] = upVXfo data['upperLen'] = upperLen data['lowerLen'] = lowerLen return data
def __init__(self, name='leg', parent=None, *args, **kwargs): Profiler.getInstance().push("Construct Leg Guide Component:" + name) super(LegComponentGuide, self).__init__(name, parent, *args, **kwargs) # ========= # Controls # ========= guideSettingsAttrGrp = AttributeGroup("GuideSettings", parent=self) # Guide Controls self.femurCtrl = Control('femur', parent=self.ctrlCmpGrp, shape="sphere") self.kneeCtrl = Control('knee', parent=self.ctrlCmpGrp, shape="sphere") self.ankleCtrl = Control('ankle', parent=self.ctrlCmpGrp, shape="sphere") armGuideSettingsAttrGrp = AttributeGroup("DisplayInfo_ArmSettings", parent=self.femurCtrl) self.armGuideDebugAttr = BoolAttribute('drawDebug', value=True, parent=armGuideSettingsAttrGrp) self.guideOpHost = Transform('guideOpHost', self.ctrlCmpGrp) # Guide Operator self.legGuideKLOp = KLOperator('guide', 'TwoBoneIKGuideSolver', 'Kraken') self.addOperator(self.legGuideKLOp) # Add Att Inputs self.legGuideKLOp.setInput('drawDebug', self.armGuideDebugAttr) self.legGuideKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Source Inputs self.legGuideKLOp.setInput('root', self.femurCtrl) self.legGuideKLOp.setInput('mid', self.kneeCtrl) self.legGuideKLOp.setInput('end', self.ankleCtrl) # Add Target Outputs self.legGuideKLOp.setOutput('guideOpHost', self.guideOpHost) self.default_data = { "name": name, "location": "L", "createIKHandle": False, "femurXfo": Xfo(Vec3(1.0, 9.75, -0.5)), "kneeXfo": Xfo(Vec3(1.5, 5.5, -0.5)), "ankleXfo": Xfo(Vec3(1.75, 1.15, -1.25)) } self.loadData(self.default_data) Profiler.getInstance().pop()
def calculateUpVXfo(self, boneXfos, endXfo): """Calculates the transform for the UpV control. Args: boneXfos (list): Bone transforms. endXfo (Xfo): Transform for the end of the chain. Returns: Xfo: Up Vector transform. """ # Calculate FW toFirst = boneXfos[1].tr.subtract(boneXfos[0].tr).unit() toTip = endXfo.tr.subtract(boneXfos[0].tr).unit() fw = toTip.cross(toFirst).unit() chainNormal = fw.cross(toTip).unit() chainZAxis = toTip.cross(chainNormal).unit() chainXfo = Xfo() chainXfo.setFromVectors(toTip.unit(), chainNormal, chainZAxis, boneXfos[0].tr) rootToTip = endXfo.tr.subtract(boneXfos[0].tr).length() upVXfo = Xfo() upVXfo.tr = chainXfo.transformVector( Vec3(rootToTip / 2.0, rootToTip / 2.0, 0.0)) return upVXfo
def __mirrorData(jsonData, plane): if isinstance(jsonData, Vec3): return jsonData if isinstance(jsonData, Quat): newQuat = Quat(jsonData) newQuat.mirror(plane) return newQuat elif isinstance(jsonData, Xfo): newXfo = Xfo(jsonData) if plane == 0: newXfo.tr.x = -newXfo.tr.x elif plane == 1: newXfo.tr.y = -newXfo.tr.y elif plane == 2: newXfo.tr.z = -newXfo.tr.z newXfo.ori.mirror(plane) return newXfo elif type(jsonData) is list: newList = [] for item in jsonData: newList.append(__mirrorData(item, plane)) return newList elif type(jsonData) is dict: newDict = {} for key, value in jsonData.iteritems(): newDict[key] = __mirrorData(value, plane) return newDict return jsonData
def addFinger(self, name, data): fingerCtrls = [] fingerJoints = [] parentCtrl = self.handCtrl for i, joint in enumerate(data): if i == 0: jointName = name + 'Meta' else: jointName = name + str(i).zfill(2) jointXfo = joint.get('xfo', Xfo()) jointCrvData = joint.get('curveData') # Create Controls newJointCtrlSpace = CtrlSpace(jointName, parent=parentCtrl) newJointCtrl = Control(jointName, parent=newJointCtrlSpace, shape='square') newJointCtrl.lockScale(True, True, True) newJointCtrl.lockTranslation(True, True, True) if jointCrvData is not None: newJointCtrl.setCurveData(jointCrvData) fingerCtrls.append(newJointCtrl) # Create Deformers jointDef = Joint(jointName, parent=self.defCmpGrp) fingerJoints.append(jointDef) # Create Constraints # Set Xfos newJointCtrlSpace.xfo = jointXfo newJointCtrl.xfo = jointXfo parentCtrl = newJointCtrl # ================= # Create Operators # ================= # Add Deformer KL Op deformersToCtrlsKLOp = KLOperator(name + 'DeformerKLOp', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(deformersToCtrlsKLOp) # Add Att Inputs deformersToCtrlsKLOp.setInput('drawDebug', self.drawDebugInputAttr) deformersToCtrlsKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs deformersToCtrlsKLOp.setInput('constrainers', fingerCtrls) # Add Xfo Outputs deformersToCtrlsKLOp.setOutput('constrainees', fingerJoints) return deformersToCtrlsKLOp
def compute(self): """invokes the constraint and returns the resulting transform Returns: xfo: The result of the constraint in global space. """ if self._constrainee is None: return None if len(self._constrainers) == 0: return None if self.getMaintainOffset(): return self._constrainee.xfo cls = self.__class__.__name__ ks.loadExtension('KrakenForCanvas') rtVal = ks.rtVal('KrakenForCanvas::Kraken%s' % cls) for c in self._constrainers: rtVal.addConstrainer('', ks.rtVal('Xfo', c.globalXfo).toMat44('Mat44')) # Using globalXfo here would cause a recursion return Xfo( rtVal.compute( "Xfo", ks.rtVal('Xfo', self._constrainee.xfo).toMat44('Mat44')))
def __init__(self, name='head', parent=None): Profiler.getInstance().push("Construct Head Guide Component:" + name) super(FabriceHeadGuide, self).__init__(name, parent) # ========= # Controls # ========= guideSettingsAttrGrp = AttributeGroup("GuideSettings", parent=self) self.headCtrl = Control('head', parent=self.ctrlCmpGrp, shape="circle") self.headCtrl.rotatePoints(90.0, 0.0, 0.0) self.headCtrl.scalePoints(Vec3(3.5, 3.5, 3.5)) self.jawCtrl = Control('jaw', parent=self.ctrlCmpGrp, shape="cube") self.jawCtrl.alignOnZAxis() self.jawCtrl.scalePoints(Vec3(2.0, 0.5, 2.0)) self.jawCtrl.alignOnYAxis(negative=True) self.jawCtrl.setColor('orange') data = { "name": name, "location": "M", "headXfo": Xfo(Vec3(0.0, 1.67, 1.75)), "headCtrlCrvData": self.headCtrl.getCurveData(), "jawPosition": Vec3(0.0, 1.2787, 2.0078), "jawCtrlCrvData": self.jawCtrl.getCurveData(), } self.loadData(data) Profiler.getInstance().pop()
def __init__(self, name, parent=None, flags=None, metaData=None): super(Object3D, self).__init__(name, parent=parent, metaData=metaData) self._children = [] self._flags = {} self._attributeGroups = [] self._constraints = [] self._xfo = Xfo() self._ro = RotationOrder() self._color = None self._implicitAttrGrp = AttributeGroup("implicitAttrGrp", self) self._visibility = BoolAttribute('visibility', True, self._implicitAttrGrp) self._shapeVisibility = BoolAttribute('ShapeVisibility', True, self._implicitAttrGrp) if parent is not None: parent.addChild(self) if flags is not None: assert type( flags ) is str, "Flags argument must be a comma separated string." for flag in flags.replace(' ', '').split(','): if not re.match("[\w]*$", flag): msg = "{} '{}' {} ({}: {}) {}\n".format( "Invalid flag", flag, "set on", self.getName(), self.getPath(), ". Alphanumeric and underscores only!") logger.warn(msg) continue self.setFlag(flag)
def placeFingers(self): spacing = 0.25 length = spacing * (len(self.fingers.keys()) - 1) mid = length / 2.0 startOffset = length - mid for i, finger in enumerate(self.fingers.keys()): parentCtrl = self.handCtrl numJoints = self.numJointsAttr.getValue() if finger == "thumb": numJoints = 3 for y in xrange(numJoints + 1): if y == 1: xOffset = 0.375 else: xOffset = 0.25 if y == 0: offsetVec = Vec3(xOffset, 0, startOffset - (i * spacing)) else: offsetVec = Vec3(xOffset, 0, 0) fingerPos = parentCtrl.xfo.transformVector(offsetVec) fingerXfo = Xfo(tr=fingerPos, ori=self.handCtrl.xfo.ori) self.fingers[finger][y].xfo = fingerXfo parentCtrl = self.fingers[finger][y]
def __init__(self, name='clavicle', parent=None): Profiler.getInstance().push("Construct Clavicle Guide Component:" + name) super(FabriceClavicleGuide, self).__init__(name, parent) # ========= # Controls # ========= # Guide Controls guideSettingsAttrGrp = AttributeGroup("GuideSettings", parent=self) self.clavicleCtrl = Control('clavicle', parent=self.ctrlCmpGrp, shape="cube") self.clavicleCtrl.alignOnXAxis() self.clavicleCtrl.scalePoints(Vec3(1.0, 0.25, 0.25)) data = { "name": name, "location": "L", "clavicleXfo": Xfo(Vec3(0.1322, 15.403, -0.5723)), 'clavicleCtrlCrvData': self.clavicleCtrl.getCurveData() } self.loadData(data) Profiler.getInstance().pop()
def generateGuideXfos(self, numSprings): """Generates the positions for the guide controls based on the number of joints. Args: numSprings (int): Number of joints to generate a transform for. Returns: list: Guide control positions. """ guideXfos = [] j = 0 for i in xrange(numSprings): springXfo = Xfo() springXfo.tr.x = i % 5 * 2 springXfo.tr.z = j * 2 if i % 5 == 4: j += 1 guideXfos.append(springXfo) return guideXfos
def getRigBuildData(self): """Returns the Guide data used by the Rig Component to define the layout of the final rig.. Return: The JSON rig data object. """ data = super(HandComponentGuide, self).getRigBuildData() data['handXfo'] = self.handCtrl.xfo fingerData = {} for finger in self.fingers.keys(): fingerData[finger] = [] for i, joint in enumerate(self.fingers[finger]): if i == len(self.fingers[finger]) - 1: continue # Calculate Xfo boneVec = self.fingers[finger][ i + 1].xfo.tr - self.fingers[finger][i].xfo.tr bone1Normal = self.fingers[finger][i].xfo.ori.getZaxis().cross( boneVec).unit() bone1ZAxis = boneVec.cross(bone1Normal).unit() jointXfo = Xfo() jointXfo.setFromVectors(boneVec.unit(), bone1Normal, bone1ZAxis, self.fingers[finger][i].xfo.tr) jointData = { 'curveData': self.fingers[finger][i].shapeCtrl.getCurveData(), 'length': self.fingers[finger][i].xfo.tr.distanceTo( self.fingers[finger][i + 1].xfo.tr), 'xfo': jointXfo } fingerData[finger].append(jointData) data['fingerData'] = fingerData return data
def evaluate(self): """invokes the constraint causing the output value to be computed. Return: Boolean, True if successful. """ if self.getMaintainOffset() is False: newXfo = Xfo() newXfo.ori.set(Vec3(), 0.0) for constrainer in self.getConstrainers(): newXfo.tr = newXfo.tr.add(constrainer.xfo.tr) newXfo.ori = newXfo.ori.add(constrainer.xfo.ori) newXfo.ori.setUnit() self.getConstrainee().xfo = newXfo return True
def evaluate(self): """invokes the constraint causing the output value to be computed. Returns: bool: True if successful. """ if self.getMaintainOffset() is False: newXfo = Xfo(); newXfo.ori.set(Vec3(), 0.0) for constrainer in self.getConstrainers(): newXfo.tr = newXfo.tr.add(constrainer.xfo.tr) newXfo.ori = newXfo.ori.add(constrainer.xfo.ori) newXfo.ori.setUnit() self.getConstrainee().xfo = newXfo return True
def __init__(self, name='hand', parent=None, *args, **kwargs): Profiler.getInstance().push("Construct Hand Guide Component:" + name) super(HandComponentGuide, self).__init__(name, parent, *args, **kwargs) # ========= # Controls # ========= # Guide Controls self.guideSettingsAttrGrp = AttributeGroup("GuideSettings", parent=self) self.digitNamesAttr = StringAttribute( 'digitNames', value="thumb,index,middle,ring,pinky", parent=self.guideSettingsAttrGrp) self.digitNamesAttr.setValueChangeCallback(self.updateFingers) self.numJointsAttr = IntegerAttribute('numJoints', value=4, minValue=2, maxValue=20, parent=self.guideSettingsAttrGrp) self.numJointsAttr.setValueChangeCallback(self.resizeDigits) self.fingers = OrderedDict() self.handCtrl = Control('hand', parent=self.ctrlCmpGrp, shape="square") self.handCtrl.rotatePoints(0.0, 0.0, 90.0) self.handCtrl.scalePoints(Vec3(1.0, 0.75, 1.0)) self.handCtrl.setColor('yellow') self.handGuideSettingsAttrGrp = AttributeGroup("Settings", parent=self.handCtrl) self.ctrlShapeToggle = BoolAttribute( 'ctrlShape_vis', value=False, parent=self.handGuideSettingsAttrGrp) self.handDebugInputAttr = BoolAttribute( 'drawDebug', value=False, parent=self.handGuideSettingsAttrGrp) self.drawDebugInputAttr.connect(self.handDebugInputAttr) self.guideCtrlHrcGrp = HierarchyGroup('controlShapes', parent=self.ctrlCmpGrp) self.default_data = { "name": name, "location": "L", "handXfo": Xfo(Vec3(7.1886, 12.2819, 0.4906)), "digitNames": self.digitNamesAttr.getValue(), "numJoints": self.numJointsAttr.getValue(), "fingers": self.fingers } self.loadData(self.default_data) Profiler.getInstance().pop()
def calculateUpVXfo(self, boneXfos, endXfo): """Calculates the transform for the UpV control. Args: boneXfos (list): Bone transforms. endXfo (Xfo): Transform for the end of the chain. Returns: Xfo: Up Vector transform. """ # Calculate FW toFirst = boneXfos[1].tr.subtract(boneXfos[0].tr).unit() toTip = endXfo.tr.subtract(boneXfos[0].tr).unit() fw = toTip.cross(toFirst).unit() chainNormal = fw.cross(toTip).unit() chainZAxis = toTip.cross(chainNormal).unit() chainXfo = Xfo() chainXfo.setFromVectors(toTip.unit(), chainNormal, chainZAxis, boneXfos[0].tr) rootToTip = endXfo.tr.subtract(boneXfos[0].tr).length() upVXfo = Xfo() upVXfo.tr = chainXfo.transformVector(Vec3(rootToTip / 2.0, rootToTip / 2.0, 0.0)) return upVXfo
def getRigBuildData(self): """Returns the Guide data used by the Rig Component to define the layout of the final rig.. Return: The JSON rig data object. """ data = super(FKCollisionComponentGuide, self).getRigBuildData() numJoints = self.numJoints.getValue() # Calculate Xfos boneXfos = [] boneLengths = [] for i in xrange(numJoints): boneVec = self.jointCtrls[i + 1].xfo.tr.subtract( self.jointCtrls[i].xfo.tr) boneLengths.append(boneVec.length()) xfo = Xfo() q = Quat() q.setFromDirectionAndUpvector( boneVec.unit(), self.jointCtrls[i].xfo.ori.getYaxis()) qDir = Quat().setFromAxisAndAngle(Vec3(0, 1, 0), Math_degToRad(-90)) xfo.ori = q * qDir xfo.tr = self.jointCtrls[i].xfo.tr boneXfos.append(xfo) data['jointXfos'] = [x.xfo for x in self.jointCtrls] data['boneXfos'] = boneXfos data['endXfo'] = self.jointCtrls[-1].xfo data['boneLengths'] = boneLengths return data
def getRigBuildData(self): """Returns the Guide data used by the Rig Component to define the layout of the final rig.. Return: The JSON rig data object. """ data = super(HandComponentGuide, self).getRigBuildData() data['handXfo'] = self.handCtrl.xfo fingerData = {} for finger in self.fingers.keys(): fingerData[finger] = [] for i, joint in enumerate(self.fingers[finger]): if i == len(self.fingers[finger]) - 1: continue # Calculate Xfo boneVec = self.fingers[finger][i + 1].xfo.tr - self.fingers[finger][i].xfo.tr bone1Normal = self.fingers[finger][i].xfo.ori.getZaxis().cross(boneVec).unit() bone1ZAxis = boneVec.cross(bone1Normal).unit() jointXfo = Xfo() jointXfo.setFromVectors(boneVec.unit(), bone1Normal, bone1ZAxis, self.fingers[finger][i].xfo.tr) jointData = { 'curveData': self.fingers[finger][i].shapeCtrl.getCurveData(), 'length': self.fingers[finger][i].xfo.tr.distanceTo(self.fingers[finger][i + 1].xfo.tr), 'xfo': jointXfo } fingerData[finger].append(jointData) data['fingerData'] = fingerData return data
def __init__(self, name, parent=None): super(Object3D, self).__init__(name, parent) self._component = None self._children = [] self._flags = {} self._attributeGroups = [] self._constraints = [] self._xfo = Xfo() self._ro = RotationOrder() self._color = None self._visibility = True self._shapeVisibility = True if parent is not None: parent.addChild(self)
def getRigBuildData(self): """Returns the Guide data used by the Rig Component to define the layout of the final rig.. Return: The JSON rig data object. """ data = super(InsectLegComponentGuide, self).getRigBuildData() numJoints = self.numJoints.getValue() # Calculate FW toFirst = self.jointCtrls[0].xfo.tr.subtract(self.jointCtrls[1].xfo.tr).unit() toTip = self.jointCtrls[0].xfo.tr.subtract(self.jointCtrls[-1].xfo.tr).unit() fw = toTip.cross(toFirst).unit() # Calculate Xfos boneXfos = [] boneLengths = [] for i in xrange(numJoints): boneVec = self.jointCtrls[i + 1].xfo.tr.subtract(self.jointCtrls[i].xfo.tr) boneLengths.append(boneVec.length()) bone1Normal = fw.cross(boneVec).unit() bone1ZAxis = boneVec.cross(bone1Normal).unit() xfo = Xfo() xfo.setFromVectors(boneVec.unit(), bone1Normal, bone1ZAxis, self.jointCtrls[i].xfo.tr) boneXfos.append(xfo) data["boneXfos"] = boneXfos data["endXfo"] = self.jointCtrls[-1].xfo data["boneLengths"] = boneLengths return data
def generateGuideXfos(self, numJoints): """Generates the positions for the guide controls based on the number of joints. Args: numJoints (int): Number of joints to generate a transform for. Returns: list: Guide control positions. """ guideXfos = [] for i in xrange(numJoints + 1): guideXfos.append(Xfo(tr=Vec3(0, 0, i))) return guideXfos
def __init__(self, name, parent=None): super(Object3D, self).__init__(name, parent) self._children = [] self._flags = {} self._attributeGroups = [] self._constraints = [] self._xfo = Xfo() self._ro = RotationOrder() self._color = None self._implicitAttrGrp = AttributeGroup("implicitAttrGrp", self) self._visibility = BoolAttribute('visibility', True, self._implicitAttrGrp) self._shapeVisibility = BoolAttribute('ShapeVisibility', True, self._implicitAttrGrp) if parent is not None: parent.addChild(self)
def __init__(self, name, parent=None): super(SceneItem, self).__init__() self.name = name self.parent = None self.component = None self.children = [] self.flags = {} self.attributeGroups = [] self.constraints = [] self.xfo = Xfo() self.color = None self.visibility = True self.shapeVisibility = True if parent is not None: parent.addChild(self) defaultAttrGroup = AttributeGroup("") self.addAttributeGroup(defaultAttrGroup)
def updateNumJointControls(self, numJoints): """Load a saved guide representation from persisted data. Arguments: numJoints -- object, The number of joints inthe chain. Return: True if successful. """ if numJoints == 0: raise IndexError("'numJoints' must be > 0") if numJoints + 1 > len(self.jointCtrls): for i in xrange(len(self.jointCtrls), numJoints + 1): if i == 0: ctrlParent = self.ctrlCmpGrp else: ctrlParent = self.jointCtrls[i - 1] newCtrl = Control('chain' + str(i + 1).zfill(2), parent=ctrlParent, shape="sphere") newCtrl.scalePoints(Vec3(0.25, 0.25, 0.25)) # Generate thew new ctrl off the end of the existing one. newCtrl.xfo = self.jointCtrls[i - 1].xfo.multiply( Xfo(Vec3(10.0, 0.0, 0.0))) self.jointCtrls.append(newCtrl) elif numJoints + 1 < len(self.jointCtrls): numExtraCtrls = len(self.jointCtrls) - (numJoints + 1) for i in xrange(numExtraCtrls): extraCtrl = self.jointCtrls.pop() extraCtrl.getParent().removeChild(extraCtrl) # Reset the control positions based on new number of joints jointPositions = self.generateGuidePositions(numJoints) for i in xrange(len(self.jointCtrls)): self.jointCtrls[i].xfo.tr = jointPositions[i] return True
def __init__(self, name='InsectLeg', parent=None): Profiler.getInstance().push("Construct InsectLeg Guide Component:" + name) super(InsectLegComponentGuide, self).__init__(name, parent) # ========= # Controls # ========= guideSettingsAttrGrp = AttributeGroup("GuideSettings", parent=self) self.numJoints = IntegerAttribute('numJoints', value=5, minValue=2, maxValue=20, parent=guideSettingsAttrGrp) self.numJoints.setValueChangeCallback(self.updateNumLegControls) self.jointCtrls = [] numJoints = self.numJoints.getValue() jointPositions = self.generateGuidePositions(numJoints) for i in xrange(numJoints): self.jointCtrls.append( Control('leg' + str(i + 1).zfill(2), parent=self.ctrlCmpGrp, shape="sphere")) jointXfos = [] for i in xrange(numJoints): jointXfos.append(Xfo(jointPositions[i])) data = { "location": "L", "jointPositions": jointXfos, "numJoints": self.numJoints.getValue() } self.loadData(data) Profiler.getInstance().pop()
def loadData(self, data=None): """Load a saved guide representation from persisted data. Arguments: data -- object, The JSON data object. Return: True if successful. """ super(HandComponentRig, self).loadData(data) # Data fingerData = data.get('fingerData') handXfo = data.get('handXfo', Xfo()) self.handCtrlSpace.xfo = handXfo self.handCtrl.xfo = handXfo fingerOps = [] for finger in fingerData.keys(): fingerOp = self.addFinger(finger, fingerData[finger]) fingerOps.append(fingerOp) # ============ # Set IO Xfos # ============ self.armEndInputTgt.xfo = handXfo self.handOutputTgt.xfo = handXfo # Eval Constraints self.armEndInputConstraint.evaluate() self.handOutputConstraint.evaluate() self.handDefConstraint.evaluate() # Eval Operators for op in fingerOps: op.evaluate()
def getRigBuildData(self): data = super(mjEyelidComponentGuide, self).getRigBuildData() eyeballPosition = self.eyeballCtrl.xfo.tr eyeballOriXfo = Xfo() eyeballOriXfo.tr = eyeballPosition eyeballOriOffset = Quat(Vec3(0.0, 0.894, 0.0), -0.448) if self.getLocation() == "R": eyeballOriXfo.ori.subtract(eyeballOriOffset) data['eyeballXfo'] = eyeballOriXfo eyelidUpVOffset = Vec3(0.0, 0.2, 0.0) eyelidUpVXfo = Xfo() eyelidUpVXfo.tr = eyeballPosition.add(eyelidUpVOffset) data['eyelidUpVXfo'] = eyelidUpVXfo data['lidMedialXfo'] = self.lidMedialCtrl.xfo data['lidLateralXfo'] = self.lidLateralCtrl.xfo data['lidUpXfo'] = self.lidUpCtrl.xfo data['lidUpMedialXfo'] = self.lidUpMedialCtrl.xfo data['lidUpLateralXfo'] = self.lidUpLateralCtrl.xfo data['lidLowXfo'] = self.lidLowCtrl.xfo data['lidLowMedialXfo'] = self.lidLowMedialCtrl.xfo data['lidLowLateralXfo'] = self.lidLowLateralCtrl.xfo data['numUpDeformers'] = self.numUpDeformersAttr.getValue() data['numLowDeformers'] = self.numLowDeformersAttr.getValue() data['lidUpMedialBlink'] = self.upMedialFactorAttr.getValue() data['lidUpLateralBlink'] = self.upLateralFactorAttr.getValue() data['lidLowMedialBlink'] = self.lowMedialFactorAttr.getValue() data['lidLowLateralBlink'] = self.lowLateralFactorAttr.getValue() return data
def __init__(self, name, parent=None, location='M'): super(FootComponent, self).__init__(name, parent, location) # ========= # Controls # ========= # Setup component attributes defaultAttrGroup = self.getAttributeGroupByIndex(0) defaultAttrGroup.addAttribute(BoolAttribute("toggleDebugging", True)) # Default values if location == 'R': ctrlColor = "red" footPosition = Vec3(-7.1886, 12.2819, 0.4906) footUpV = Vec3(-1.7454, 0.1922, -1.7397) footEndPosition = Vec3(-2.0939, 0.4288, 0.0944) else: ctrlColor = "greenBright" footPosition = Vec3(7.1886, 12.2819, 0.4906) footUpV = Vec3(1.7454, 0.1922, -1.7397) footEndPosition = Vec3(2.0939, 0.4288, 0.0944) # Calculate Clavicle Xfo rootToEnd = footEndPosition.subtract(footPosition).unit() rootToUpV = footUpV.subtract(footPosition).unit() bone1ZAxis = rootToEnd.cross(rootToUpV).unit() bone1Normal = rootToEnd.cross(bone1ZAxis).unit() footXfo = Xfo() if location == "R": footQuat = Quat(Vec3(0.5695, -0.6377, 0.4190), 0.3053) footPos = Vec3(-1.841, 1.1516, -1.237) else: footQuat = Quat(Vec3(0.6377, -0.5695, 0.3053), 0.4190) footPos = Vec3(1.841, 1.1516, -1.237) footXfo.rot = footQuat.clone() footXfo.tr.copy(footPos) # Add Controls footCtrlSrtBuffer = SrtBuffer('foot', parent=self) footCtrlSrtBuffer.xfo.copy(footXfo) footCtrl = CubeControl('foot', parent=footCtrlSrtBuffer) footCtrl.alignOnXAxis() footCtrl.scalePoints(Vec3(2.5, 1.5, 0.75)) footCtrl.xfo.copy(footCtrlSrtBuffer.xfo) footCtrl.setColor(ctrlColor) # Rig Ref objects footRefSrt = Locator('footRef', parent=self) footRefSrt.xfo.copy(footCtrlSrtBuffer.xfo) # Add Component Params to IK control footDebugInputAttr = BoolAttribute('debug', True) footLinkToWorldInputAttr = FloatAttribute('linkToWorld', 1.0, 0.0, 1.0) footSettingsAttrGrp = AttributeGroup("DisplayInfo_HandSettings") footCtrl.addAttributeGroup(footSettingsAttrGrp) footSettingsAttrGrp.addAttribute(footDebugInputAttr) footSettingsAttrGrp.addAttribute(footLinkToWorldInputAttr) # ========== # Deformers # ========== container = self.getParent().getParent() deformersLayer = container.getChildByName('deformers') footDef = Joint('foot') footDef.setComponent(self) deformersLayer.addChild(footDef) # ===================== # Create Component I/O # ===================== # Setup Component Xfo I/O's legEndXfoInput = Locator('legEndXfo') legEndXfoInput.xfo.copy(footCtrlSrtBuffer.xfo) legEndPosInput = Locator('legEndPos') legEndPosInput.xfo.copy(footCtrlSrtBuffer.xfo) footEndOutput = Locator('handEnd') footEndOutput.xfo.copy(footCtrlSrtBuffer.xfo) footOutput = Locator('hand') footOutput.xfo.copy(footCtrlSrtBuffer.xfo) # Setup componnent Attribute I/O's debugInputAttr = BoolAttribute('debug', True) rightSideInputAttr = BoolAttribute('rightSide', location is 'R') linkToWorldInputAttr = FloatAttribute('linkToWorld', 0.0, 0.0, 1.0) # Connect attrs to control attrs debugInputAttr.connect(footDebugInputAttr) linkToWorldInputAttr.connect(footLinkToWorldInputAttr) # ============== # Constrain I/O # ============== # Constraint inputs # Constraint outputs handConstraint = PoseConstraint('_'.join([footOutput.getName(), 'To', footCtrl.getName()])) handConstraint.addConstrainer(footCtrl) footOutput.addConstraint(handConstraint) handEndConstraint = PoseConstraint('_'.join([footEndOutput.getName(), 'To', footCtrl.getName()])) handEndConstraint.addConstrainer(footCtrl) footEndOutput.addConstraint(handEndConstraint) # ================== # Add Component I/O # ================== # Add Xfo I/O's self.addInput(legEndXfoInput) self.addInput(legEndPosInput) self.addOutput(footOutput) self.addOutput(footEndOutput) # Add Attribute I/O's self.addInput(debugInputAttr) self.addInput(rightSideInputAttr) self.addInput(linkToWorldInputAttr)
def __init__(self, name, parent=None, location='M'): super(HandComponent, self).__init__(name, parent, location) # ========= # Controls # ========= # Setup component attributes defaultAttrGroup = self.getAttributeGroupByIndex(0) defaultAttrGroup.addAttribute(BoolAttribute("toggleDebugging", True)) # Default values if location == 'R': ctrlColor = "red" handPosition = Vec3(-7.1886, 12.2819, 0.4906) handUpV = Vec3(-7.7463, 13.1746, 0.4477) handEndPosition = Vec3(-7.945, 11.8321, 0.9655) else: ctrlColor = "greenBright" handPosition = Vec3(7.1886, 12.2819, 0.4906) handUpV = Vec3(7.7463, 13.1746, 0.4477) handEndPosition = Vec3(7.945, 11.8321, 0.9655) # Calculate Clavicle Xfo rootToEnd = handEndPosition.subtract(handPosition).unit() rootToUpV = handUpV.subtract(handPosition).unit() bone1ZAxis = rootToEnd.cross(rootToUpV).unit() bone1Normal = rootToEnd.cross(bone1ZAxis).unit() handXfo = Xfo() if location == "R": handQuat = Quat(Vec3(-0.2301, -0.0865, -0.9331), 0.2623) handPos = Vec3(-7.1886, 12.2819, 0.4906) else: handQuat = Quat(Vec3(-0.0865, -0.2301, -0.2623), 0.9331) handPos = Vec3(7.1886, 12.2819, 0.4906) handXfo.rot = handQuat.clone() handXfo.tr.copy(handPos) # Add Controls handCtrlSrtBuffer = SrtBuffer('hand', parent=self) handCtrlSrtBuffer.xfo.copy(handXfo) handCtrl = CubeControl('hand', parent=handCtrlSrtBuffer) handCtrl.alignOnXAxis() handCtrl.scalePoints(Vec3(2.0, 0.75, 1.25)) handCtrl.xfo.copy(handCtrlSrtBuffer.xfo) handCtrl.setColor(ctrlColor) # Rig Ref objects handRefSrt = Locator('handRef', parent=self) handRefSrt.xfo.copy(handCtrlSrtBuffer.xfo) # Add Component Params to IK control handDebugInputAttr = BoolAttribute('debug', True) handLinkToWorldInputAttr = FloatAttribute('linkToWorld', 0.0, 0.0, 1.0) handSettingsAttrGrp = AttributeGroup("DisplayInfo_HandSettings") handCtrl.addAttributeGroup(handSettingsAttrGrp) handSettingsAttrGrp.addAttribute(handDebugInputAttr) handSettingsAttrGrp.addAttribute(handLinkToWorldInputAttr) # ========== # Deformers # ========== container = self.getParent().getParent() deformersLayer = container.getChildByName('deformers') handDef = Joint('hand') handDef.setComponent(self) deformersLayer.addChild(handDef) # ===================== # Create Component I/O # ===================== # Setup Component Xfo I/O's armEndXfoInput = Locator('armEndXfo') armEndXfoInput.xfo.copy(handCtrlSrtBuffer.xfo) armEndPosInput = Locator('armEndPos') armEndPosInput.xfo.copy(handCtrlSrtBuffer.xfo) handEndOutput = Locator('handEnd') handEndOutput.xfo.copy(handCtrlSrtBuffer.xfo) handOutput = Locator('hand') handOutput.xfo.copy(handCtrlSrtBuffer.xfo) # Setup componnent Attribute I/O's debugInputAttr = BoolAttribute('debug', True) rightSideInputAttr = BoolAttribute('rightSide', location is 'R') linkToWorldInputAttr = FloatAttribute('linkToWorld', 0.0, 0.0, 1.0) # Connect attrs to control attrs debugInputAttr.connect(handDebugInputAttr) linkToWorldInputAttr.connect(handLinkToWorldInputAttr) # ============== # Constrain I/O # ============== # Constraint inputs # Constraint outputs handConstraint = PoseConstraint('_'.join([handOutput.getName(), 'To', handCtrl.getName()])) handConstraint.addConstrainer(handCtrl) handOutput.addConstraint(handConstraint) handEndConstraint = PoseConstraint('_'.join([handEndOutput.getName(), 'To', handCtrl.getName()])) handEndConstraint.addConstrainer(handCtrl) handEndOutput.addConstraint(handEndConstraint) # ================== # Add Component I/O # ================== # Add Xfo I/O's self.addInput(armEndXfoInput) self.addInput(armEndPosInput) self.addOutput(handOutput) self.addOutput(handEndOutput) # Add Attribute I/O's self.addInput(debugInputAttr) self.addInput(rightSideInputAttr) self.addInput(linkToWorldInputAttr)
def __init__(self, name, parent=None, location='M'): super(ClavicleComponent, self).__init__(name, parent, location) # ========= # Controls # ========= # Setup component attributes defaultAttrGroup = self.getAttributeGroupByIndex(0) defaultAttrGroup.addAttribute(BoolAttribute("toggleDebugging", True)) # Default values if location == 'R': ctrlColor = "red" claviclePosition = Vec3(-0.1322, 15.403, -0.5723) clavicleUpV = Vec3() clavicleUpV.copy(claviclePosition) clavicleUpV = clavicleUpV.add(Vec3(0.0, 1.0, 0.0)).unit() clavicleEndPosition = Vec3(-2.27, 15.295, -0.753) else: ctrlColor = "greenBright" claviclePosition = Vec3(0.1322, 15.403, -0.5723) clavicleUpV = Vec3() clavicleUpV.copy(claviclePosition) clavicleUpV = clavicleUpV.add(Vec3(0.0, 1.0, 0.0)).unit() clavicleEndPosition = Vec3(2.27, 15.295, -0.753) # Calculate Clavicle Xfo rootToEnd = clavicleEndPosition.subtract(claviclePosition).unit() rootToUpV = clavicleUpV.subtract(claviclePosition).unit() bone1ZAxis = rootToUpV.cross(rootToEnd).unit() bone1Normal = bone1ZAxis.cross(rootToEnd).unit() clavicleXfo = Xfo() clavicleXfo.setFromVectors(rootToEnd, bone1Normal, bone1ZAxis, claviclePosition) # Add Controls clavicleCtrl = CubeControl('clavicle', parent=self) clavicleCtrl.alignOnXAxis() clavicleLen = claviclePosition.subtract(clavicleEndPosition).length() clavicleCtrl.scalePoints(Vec3(clavicleLen, 0.75, 0.75)) if location == "R": clavicleCtrl.translatePoints(Vec3(0.0, 0.0, -1.0)) else: clavicleCtrl.translatePoints(Vec3(0.0, 0.0, 1.0)) clavicleCtrl.xfo.copy(clavicleXfo) clavicleCtrl.setColor(ctrlColor) clavicleCtrlSrtBuffer = SrtBuffer('clavicle', parent=self) clavicleCtrlSrtBuffer.xfo.copy(clavicleCtrl.xfo) clavicleCtrlSrtBuffer.addChild(clavicleCtrl) # ========== # Deformers # ========== container = self.getParent().getParent() deformersLayer = container.getChildByName('deformers') clavicleDef = Joint('clavicle') clavicleDef.setComponent(self) deformersLayer.addChild(clavicleDef) # ===================== # Create Component I/O # ===================== # Setup Component Xfo I/O's spineEndInput = Locator('spineEnd') spineEndInput.xfo.copy(clavicleXfo) clavicleEndOutput = Locator('clavicleEnd') clavicleEndOutput.xfo.copy(clavicleXfo) clavicleOutput = Locator('clavicle') clavicleOutput.xfo.copy(clavicleXfo) # Setup componnent Attribute I/O's debugInputAttr = BoolAttribute('debug', True) rightSideInputAttr = BoolAttribute('rightSide', location is 'R') armFollowBodyOutputAttr = FloatAttribute('followBody', 0.0, 0.0, 1.0) # ============== # Constrain I/O # ============== # Constraint inputs clavicleInputConstraint = PoseConstraint('_'.join([clavicleCtrl.getName(), 'To', spineEndInput.getName()])) clavicleInputConstraint.setMaintainOffset(True) clavicleInputConstraint.addConstrainer(spineEndInput) clavicleCtrlSrtBuffer.addConstraint(clavicleInputConstraint) # Constraint outputs clavicleConstraint = PoseConstraint('_'.join([clavicleOutput.getName(), 'To', clavicleCtrl.getName()])) clavicleConstraint.addConstrainer(clavicleCtrl) clavicleOutput.addConstraint(clavicleConstraint) clavicleEndConstraint = PoseConstraint('_'.join([clavicleEndOutput.getName(), 'To', clavicleCtrl.getName()])) clavicleEndConstraint.addConstrainer(clavicleCtrl) clavicleEndOutput.addConstraint(clavicleEndConstraint) # ================== # Add Component I/O # ================== # Add Xfo I/O's self.addInput(spineEndInput) self.addOutput(clavicleEndOutput) self.addOutput(clavicleOutput) # Add Attribute I/O's self.addInput(debugInputAttr) self.addInput(rightSideInputAttr) self.addOutput(armFollowBodyOutputAttr)
def __init__(self, name, parent=None, location='M'): super(NeckComponent, self).__init__(name, parent, location) # Setup component attributes defaultAttrGroup = self.getAttributeGroupByIndex(0) defaultAttrGroup.addAttribute(BoolAttribute("toggleDebugging", True)) # Default values neckPosition = Vec3(0.0, 16.5572, -0.6915) neckUpV = Vec3() neckUpV.copy(neckPosition) neckUpV = neckUpV.add(Vec3(0.0, 0.0, -1.0)).unit() neckEndPosition = Vec3(0.0, 17.4756, -0.421) # Calculate Clavicle Xfo rootToEnd = neckEndPosition.subtract(neckPosition).unit() rootToUpV = neckUpV.subtract(neckPosition).unit() bone1ZAxis = rootToUpV.cross(rootToEnd).unit() bone1Normal = bone1ZAxis.cross(rootToEnd).unit() neckXfo = Xfo() neckXfo.setFromVectors(rootToEnd, bone1Normal, bone1ZAxis, neckPosition) # Add Guide Controls neckCtrlSrtBuffer = SrtBuffer('neck', parent=self) neckCtrlSrtBuffer.xfo.copy(neckXfo) neckCtrl = PinControl('neck', parent=neckCtrlSrtBuffer) neckCtrl.scalePoints(Vec3(1.25, 1.25, 1.25)) neckCtrl.translatePoints(Vec3(0, 0, -0.5)) neckCtrl.rotatePoints(90, 0, 90) neckCtrl.xfo.copy(neckXfo) neckCtrl.setColor("orange") # ========== # Deformers # ========== container = self.getParent().getParent() deformersLayer = container.getChildByName('deformers') neckDef = Joint('neck', parent=deformersLayer) neckDef.setComponent(self) # ===================== # Create Component I/O # ===================== # Setup Component Xfo I/O's neckEndInput = Locator('neckBase') neckEndInput.xfo.copy(neckXfo) neckEndOutput = Locator('neckEnd') neckEndOutput.xfo.copy(neckXfo) neckOutput = Locator('neck') neckOutput.xfo.copy(neckXfo) # Setup componnent Attribute I/O's debugInputAttr = BoolAttribute('debug', True) rightSideInputAttr = BoolAttribute('rightSide', location is 'R') # ============== # Constrain I/O # ============== # Constraint inputs clavicleInputConstraint = PoseConstraint('_'.join([neckCtrl.getName(), 'To', neckEndInput.getName()])) clavicleInputConstraint.setMaintainOffset(True) clavicleInputConstraint.addConstrainer(neckEndInput) neckCtrlSrtBuffer.addConstraint(clavicleInputConstraint) # Constraint outputs neckEndConstraint = PoseConstraint('_'.join([neckEndOutput.getName(), 'To', neckCtrl.getName()])) neckEndConstraint.addConstrainer(neckCtrl) neckEndOutput.addConstraint(neckEndConstraint) # ================== # Add Component I/O # ================== # Add Xfo I/O's self.addInput(neckEndInput) self.addOutput(neckEndOutput) self.addOutput(neckOutput) # Add Attribute I/O's self.addInput(debugInputAttr) self.addInput(rightSideInputAttr)
def __init__(self, name, parent=None, location='M'): super(ArmComponent, self).__init__(name, parent, location) # ========= # Controls # ========= # Setup component attributes defaultAttrGroup = self.getAttributeGroupByIndex(0) defaultAttrGroup.addAttribute(BoolAttribute("toggleDebugging", True)) # Default values if self.getLocation() == "R": ctrlColor = "red" bicepPosition = Vec3(-2.27, 15.295, -0.753) forearmPosition = Vec3(-5.039, 13.56, -0.859) wristPosition = Vec3(-7.1886, 12.2819, 0.4906) else: ctrlColor = "greenBright" bicepPosition = Vec3(2.27, 15.295, -0.753) forearmPosition = Vec3(5.039, 13.56, -0.859) wristPosition = Vec3(7.1886, 12.2819, 0.4906) # Calculate Bicep Xfo rootToWrist = wristPosition.subtract(bicepPosition).unit() rootToElbow = forearmPosition.subtract(bicepPosition).unit() bone1Normal = rootToWrist.cross(rootToElbow).unit() bone1ZAxis = rootToElbow.cross(bone1Normal).unit() bicepXfo = Xfo() bicepXfo.setFromVectors(rootToElbow, bone1Normal, bone1ZAxis, bicepPosition) # Calculate Forearm Xfo elbowToWrist = wristPosition.subtract(forearmPosition).unit() elbowToRoot = bicepPosition.subtract(forearmPosition).unit() bone2Normal = elbowToRoot.cross(elbowToWrist).unit() bone2ZAxis = elbowToWrist.cross(bone2Normal).unit() forearmXfo = Xfo() forearmXfo.setFromVectors(elbowToWrist, bone2Normal, bone2ZAxis, forearmPosition) # Bicep bicepFKCtrl = CubeControl('bicepFK') bicepFKCtrl.alignOnXAxis() bicepLen = bicepPosition.subtract(forearmPosition).length() bicepFKCtrl.scalePoints(Vec3(bicepLen, 1.75, 1.75)) bicepFKCtrl.setColor(ctrlColor) bicepFKCtrl.xfo.copy(bicepXfo) bicepFKCtrlSrtBuffer = SrtBuffer('bicepFK') self.addChild(bicepFKCtrlSrtBuffer) bicepFKCtrlSrtBuffer.xfo.copy(bicepFKCtrl.xfo) bicepFKCtrlSrtBuffer.addChild(bicepFKCtrl) # Forearm forearmFKCtrl = CubeControl('forearmFK') forearmFKCtrl.alignOnXAxis() forearmLen = forearmPosition.subtract(wristPosition).length() forearmFKCtrl.scalePoints(Vec3(forearmLen, 1.5, 1.5)) forearmFKCtrl.setColor(ctrlColor) forearmFKCtrl.xfo.copy(forearmXfo) forearmFKCtrlSrtBuffer = SrtBuffer('forearmFK') bicepFKCtrl.addChild(forearmFKCtrlSrtBuffer) forearmFKCtrlSrtBuffer.xfo.copy(forearmFKCtrl.xfo) forearmFKCtrlSrtBuffer.addChild(forearmFKCtrl) # Arm IK armIKCtrlSrtBuffer = SrtBuffer('IK', parent=self) armIKCtrlSrtBuffer.xfo.tr.copy(wristPosition) armIKCtrl = PinControl('IK', parent=armIKCtrlSrtBuffer) armIKCtrl.xfo.copy(armIKCtrlSrtBuffer.xfo) armIKCtrl.setColor(ctrlColor) if self.getLocation() == "R": armIKCtrl.rotatePoints(0, 90, 0) else: armIKCtrl.rotatePoints(0, -90, 0) # Add Component Params to IK control armDebugInputAttr = BoolAttribute('debug', True) armBone1LenInputAttr = FloatAttribute('bone1Len', bicepLen, 0.0, 100.0) armBone2LenInputAttr = FloatAttribute('bone2Len', forearmLen, 0.0, 100.0) armFkikInputAttr = FloatAttribute('fkik', 0.0, 0.0, 1.0) armSoftIKInputAttr = BoolAttribute('softIK', True) armSoftDistInputAttr = FloatAttribute('softDist', 0.0, 0.0, 1.0) armStretchInputAttr = BoolAttribute('stretch', True) armStretchBlendInputAttr = FloatAttribute('stretchBlend', 0.0, 0.0, 1.0) armSettingsAttrGrp = AttributeGroup("DisplayInfo_ArmSettings") armIKCtrl.addAttributeGroup(armSettingsAttrGrp) armSettingsAttrGrp.addAttribute(armDebugInputAttr) armSettingsAttrGrp.addAttribute(armBone1LenInputAttr) armSettingsAttrGrp.addAttribute(armBone2LenInputAttr) armSettingsAttrGrp.addAttribute(armFkikInputAttr) armSettingsAttrGrp.addAttribute(armSoftIKInputAttr) armSettingsAttrGrp.addAttribute(armSoftDistInputAttr) armSettingsAttrGrp.addAttribute(armStretchInputAttr) armSettingsAttrGrp.addAttribute(armStretchBlendInputAttr) # UpV upVXfo = xfoFromDirAndUpV(bicepPosition, wristPosition, forearmPosition) upVXfo.tr.copy(forearmPosition) upVOffset = Vec3(0, 0, 5) upVOffset = upVXfo.transformVector(upVOffset) armUpVCtrl = TriangleControl('UpV') armUpVCtrl.xfo.tr.copy(upVOffset) armUpVCtrl.alignOnZAxis() armUpVCtrl.rotatePoints(180, 0, 0) armUpVCtrl.setColor(ctrlColor) armUpVCtrlSrtBuffer = SrtBuffer('UpV') self.addChild(armUpVCtrlSrtBuffer) armUpVCtrlSrtBuffer.xfo.tr.copy(upVOffset) armUpVCtrlSrtBuffer.addChild(armUpVCtrl) # ========== # Deformers # ========== container = self.getParent().getParent() deformersLayer = container.getChildByName('deformers') bicepDef = Joint('bicep') bicepDef.setComponent(self) forearmDef = Joint('forearm') forearmDef.setComponent(self) wristDef = Joint('wrist') wristDef.setComponent(self) deformersLayer.addChild(bicepDef) deformersLayer.addChild(forearmDef) deformersLayer.addChild(wristDef) # ===================== # Create Component I/O # ===================== # Setup component Xfo I/O's clavicleEndInput = Locator('clavicleEnd') clavicleEndInput.xfo.copy(bicepXfo) bicepOutput = Locator('bicep') bicepOutput.xfo.copy(bicepXfo) forearmOutput = Locator('forearm') forearmOutput.xfo.copy(forearmXfo) armEndXfo = Xfo() armEndXfo.rot = forearmXfo.rot.clone() armEndXfo.tr.copy(wristPosition) armEndXfoOutput = Locator('armEndXfo') armEndXfoOutput.xfo.copy(armEndXfo) armEndPosOutput = Locator('armEndPos') armEndPosOutput.xfo.copy(armEndXfo) # Setup componnent Attribute I/O's debugInputAttr = BoolAttribute('debug', True) bone1LenInputAttr = FloatAttribute('bone1Len', bicepLen, 0.0, 100.0) bone2LenInputAttr = FloatAttribute('bone2Len', forearmLen, 0.0, 100.0) fkikInputAttr = FloatAttribute('fkik', 0.0, 0.0, 1.0) softIKInputAttr = BoolAttribute('softIK', True) softDistInputAttr = FloatAttribute('softDist', 0.5, 0.0, 1.0) stretchInputAttr = BoolAttribute('stretch', True) stretchBlendInputAttr = FloatAttribute('stretchBlend', 0.0, 0.0, 1.0) rightSideInputAttr = BoolAttribute('rightSide', location is 'R') # Connect attrs to control attrs debugInputAttr.connect(armDebugInputAttr) bone1LenInputAttr.connect(armBone1LenInputAttr) bone2LenInputAttr.connect(armBone2LenInputAttr) fkikInputAttr.connect(armFkikInputAttr) softIKInputAttr.connect(armSoftIKInputAttr) softDistInputAttr.connect(armSoftDistInputAttr) stretchInputAttr.connect(armStretchInputAttr) stretchBlendInputAttr.connect(armStretchBlendInputAttr) # ============== # Constrain I/O # ============== # Constraint inputs armRootInputConstraint = PoseConstraint('_'.join([armIKCtrl.getName(), 'To', clavicleEndInput.getName()])) armRootInputConstraint.setMaintainOffset(True) armRootInputConstraint.addConstrainer(clavicleEndInput) bicepFKCtrlSrtBuffer.addConstraint(armRootInputConstraint) # Constraint outputs # ================== # Add Component I/O # ================== # Add Xfo I/O's self.addInput(clavicleEndInput) self.addOutput(bicepOutput) self.addOutput(forearmOutput) self.addOutput(armEndXfoOutput) self.addOutput(armEndPosOutput) # Add Attribute I/O's self.addInput(debugInputAttr) self.addInput(bone1LenInputAttr) self.addInput(bone2LenInputAttr) self.addInput(fkikInputAttr) self.addInput(softIKInputAttr) self.addInput(softDistInputAttr) self.addInput(stretchInputAttr) self.addInput(stretchBlendInputAttr) self.addInput(rightSideInputAttr)
def __init__(self, name='mjEyelid', parent=None): Profiler.getInstance().push("Construct Eyelid Guide Component:" + name) super(mjEyelidComponentGuide, self).__init__(name, parent) # ========= # Attributes // Create Attributes Controls. # ========= guideUpSettingsAttrGrp = AttributeGroup("Eyelid Up", parent=self) guideLowSettingsAttrGrp = AttributeGroup("Eyelid Low", parent=self) self.numUpDeformersAttr = IntegerAttribute( 'Num Deformers', value=10, minValue=1, maxValue=50, parent=guideUpSettingsAttrGrp) self.upMedialFactorAttr = ScalarAttribute( 'Medial Blink Factor', value=0.25, minValue=0, maxValue=1, parent=guideUpSettingsAttrGrp) self.upLateralFactorAttr = ScalarAttribute( 'Lateral Blink Factor', value=0.65, minValue=0, maxValue=1, parent=guideUpSettingsAttrGrp) self.numLowDeformersAttr = IntegerAttribute( 'Num Deformers', value=10, minValue=1, maxValue=50, parent=guideLowSettingsAttrGrp) self.lowMedialFactorAttr = ScalarAttribute( 'Medial Blink Factor', value=0.25, minValue=0, maxValue=1, parent=guideLowSettingsAttrGrp) self.lowLateralFactorAttr = ScalarAttribute( 'Lateral Blink Factor', value=0.65, minValue=0, maxValue=1, parent=guideLowSettingsAttrGrp) self.numUpDeformersAttr.setValueChangeCallback( self.updateNumUpDeformers) self.numLowDeformersAttr.setValueChangeCallback( self.updateNumLowDeformers) # ========= # Controls // Create the Guide Controls, Name them, give them a shape, a color and scale it. # ========= self.eyeballCtrl = Control('eyeball', parent=self.ctrlCmpGrp, shape="sphere") self.eyeballCtrl.scalePoints(Vec3(0.35, 0.35, 0.35)) self.eyeballCtrl.setColor("red") self.lidMedialCtrl = Control('lidMedial', parent=self.eyeballCtrl, shape="sphere") self.lidMedialCtrl.scalePoints(Vec3(0.025, 0.025, 0.025)) self.lidMedialCtrl.setColor("peach") self.lidLateralCtrl = Control('lidLateral', parent=self.eyeballCtrl, shape="sphere") self.lidLateralCtrl.scalePoints(Vec3(0.025, 0.025, 0.025)) self.lidLateralCtrl.setColor("peach") self.lidUpCtrl = Control('lidUp', parent=self.eyeballCtrl, shape="sphere") self.lidUpCtrl.scalePoints(Vec3(0.025, 0.025, 0.025)) self.lidUpCtrl.setColor("peach") self.lidUpMedialCtrl = Control('lidUpMedial', parent=self.eyeballCtrl, shape="sphere") self.lidUpMedialCtrl.scalePoints(Vec3(0.025, 0.025, 0.025)) self.lidUpMedialCtrl.setColor("peach") self.lidUpLateralCtrl = Control('lidUpLateral', parent=self.eyeballCtrl, shape="sphere") self.lidUpLateralCtrl.scalePoints(Vec3(0.025, 0.025, 0.025)) self.lidUpLateralCtrl.setColor("peach") self.lidLowCtrl = Control('lidLow', parent=self.eyeballCtrl, shape="sphere") self.lidLowCtrl.scalePoints(Vec3(0.025, 0.025, 0.025)) self.lidLowCtrl.setColor("peach") self.lidLowMedialCtrl = Control('lidLowMedial', parent=self.eyeballCtrl, shape="sphere") self.lidLowMedialCtrl.scalePoints(Vec3(0.025, 0.025, 0.025)) self.lidLowMedialCtrl.setColor("peach") self.lidLowLateralCtrl = Control('lidLowLateral', parent=self.eyeballCtrl, shape="sphere") self.lidLowLateralCtrl.scalePoints(Vec3(0.025, 0.025, 0.025)) self.lidLowLateralCtrl.setColor("peach") # =============== # Add Debug Splice Ops # =============== # Add Lid Up Canvas Op self.debugLidUpCanvasOp = CanvasOperator( 'Debug_Canvas_Eyelid_Up_Op', 'MJCG.Solvers.mjEyelidDebugSolver') self.addOperator(self.debugLidUpCanvasOp) # Add Attributes Inputs self.debugLidUpCanvasOp.setInput('drawDebug', self.drawDebugInputAttr) self.debugLidUpCanvasOp.setInput('rigScale', self.rigScaleInputAttr) self.debugLidUpCanvasOp.setInput('Deformer_Count', self.numUpDeformersInputAttr) # Add Xfo Inputs self.debugLidUpCanvasOp.setInput('Eye_Center', self.eyeballCtrl) self.debugLidUpCanvasOp.setInput('Lid_Medial', self.lidMedialCtrl) self.debugLidUpCanvasOp.setInput('Lid_MedialCen', self.lidUpMedialCtrl) self.debugLidUpCanvasOp.setInput('Lid_Center_Ref', self.lidUpCtrl) self.debugLidUpCanvasOp.setInput('Lid_Center_Ctrl', self.lidUpCtrl) self.debugLidUpCanvasOp.setInput('Lid_LateralCen', self.lidUpLateralCtrl) self.debugLidUpCanvasOp.setInput('Lid_Lateral', self.lidLateralCtrl) # Add Xfo Outputs self.debugLidUpCanvasOp.setOutput('result', self.eyelidUpOutput.getTarget()) # Add Lid Low Canvas Op self.debugLidLowCanvasOp = CanvasOperator( 'Debug_Canvas_Eyelid_Low_Op', 'MJCG.Solvers.mjEyelidDebugSolver') self.addOperator(self.debugLidLowCanvasOp) # Add Attributes Inputs self.debugLidLowCanvasOp.setInput('drawDebug', self.drawDebugInputAttr) self.debugLidLowCanvasOp.setInput('rigScale', self.rigScaleInputAttr) self.debugLidLowCanvasOp.setInput('Deformer_Count', self.numLowDeformersInputAttr) # Add Xfo Inputs self.debugLidLowCanvasOp.setInput('Eye_Center', self.eyeballCtrl) self.debugLidLowCanvasOp.setInput('Lid_Medial', self.lidMedialCtrl) self.debugLidLowCanvasOp.setInput('Lid_MedialCen', self.lidLowMedialCtrl) self.debugLidLowCanvasOp.setInput('Lid_Center_Ref', self.lidLowCtrl) self.debugLidLowCanvasOp.setInput('Lid_Center_Ctrl', self.lidLowCtrl) self.debugLidLowCanvasOp.setInput('Lid_LateralCen', self.lidLowLateralCtrl) self.debugLidLowCanvasOp.setInput('Lid_Lateral', self.lidLateralCtrl) # Add Xfo Outputs self.debugLidLowCanvasOp.setOutput('result', self.eyelidLowOutput.getTarget()) # ========= # Position Data // Get the Guide Controls Position data, else set them at their initial position. # ========= self.default_data = { "name": name, "location": "L", "eyeballXfo": Xfo(Vec3(0.322, 15.500, 0.390)), "lidMedialXfo": Xfo(Vec3(0.168, 15.445, 0.520)), "lidLateralXfo": Xfo(Vec3(0.465, 15.47, 0.465)), "lidUpXfo": Xfo(Vec3(0.322, 15.585, 0.605)), "lidUpMedialXfo": Xfo(Vec3(0.203, 15.515, 0.525)), "lidUpLateralXfo": Xfo(Vec3(0.432, 15.55, 0.538)), "lidLowXfo": Xfo(Vec3(0.322, 15.434, 0.6)), "lidLowMedialXfo": Xfo(Vec3(0.24, 15.45, 0.513)), "lidLowLateralXfo": Xfo(Vec3(0.413, 15.44, 0.525)), "lidUpMedialBlink": self.upMedialFactorAttr.getValue(), "lidUpLateralBlink": self.upLateralFactorAttr.getValue(), "lidLowMedialBlink": self.lowMedialFactorAttr.getValue(), "lidLowLateralBlink": self.lowLateralFactorAttr.getValue(), "numUpDeformers": self.numUpDeformersAttr.getValue(), "numLowDeformers": self.numLowDeformersAttr.getValue(), } self.loadData(self.default_data) Profiler.getInstance().pop()
def getRigBuildData(self): """Returns the Guide data used by the Rig Component to define the layout of the final rig.. Return: The JSON rig data object. """ data = super(ArmComponentGuide, self).getRigBuildData() # values bicepPosition = self.bicepCtrl.xfo.tr forearmPosition = self.forearmCtrl.xfo.tr wristPosition = self.wristCtrl.xfo.tr # Calculate Bicep Xfo rootToWrist = wristPosition.subtract(bicepPosition).unit() rootToElbow = forearmPosition.subtract(bicepPosition).unit() bone1Normal = rootToWrist.cross(rootToElbow).unit() bone1ZAxis = rootToElbow.cross(bone1Normal).unit() bicepXfo = Xfo() bicepXfo.setFromVectors(rootToElbow, bone1Normal, bone1ZAxis, bicepPosition) # Calculate Forearm Xfo elbowToWrist = wristPosition.subtract(forearmPosition).unit() elbowToRoot = bicepPosition.subtract(forearmPosition).unit() bone2Normal = elbowToRoot.cross(elbowToWrist).unit() bone2ZAxis = elbowToWrist.cross(bone2Normal).unit() forearmXfo = Xfo() forearmXfo.setFromVectors(elbowToWrist, bone2Normal, bone2ZAxis, forearmPosition) handXfo = Xfo() handXfo.tr = self.handCtrl.xfo.tr handXfo.ori = self.handCtrl.xfo.ori bicepLen = bicepPosition.subtract(forearmPosition).length() forearmLen = forearmPosition.subtract(wristPosition).length() armEndXfo = Xfo() armEndXfo.tr = wristPosition armEndXfo.ori = forearmXfo.ori upVXfo = xfoFromDirAndUpV(bicepPosition, wristPosition, forearmPosition) upVXfo.tr = forearmPosition upVXfo.tr = upVXfo.transformVector(Vec3(0, 0, 5)) data["bicepXfo"] = bicepXfo data["forearmXfo"] = forearmXfo data["handXfo"] = handXfo data["armEndXfo"] = armEndXfo data["upVXfo"] = upVXfo data["forearmLen"] = forearmLen data["bicepLen"] = bicepLen return data
class SceneItem(object): """Kraken base object type for any 3D object.""" __kType__ = "SceneItem" def __init__(self, name, parent=None): super(SceneItem, self).__init__() self.name = name self.parent = None self.component = None self.children = [] self.flags = {} self.attributeGroups = [] self.constraints = [] self.xfo = Xfo() self.color = None self.visibility = True self.shapeVisibility = True if parent is not None: parent.addChild(self) defaultAttrGroup = AttributeGroup("") self.addAttributeGroup(defaultAttrGroup) # ============= # Name methods # ============= def getName(self): """Returns the name of the object as a string. Return: String of the object's name. """ return self.name def getFullName(self): """Returns the full hierarchical path to this object. Return: String, full name of the object. """ if self.parent is not None: return self.parent.getFullName() + '.' + self.getName() return self.getName() def getBuildName(self): """Returns the name used when building the node in the target application. Return: String, build name of the object. """ if self.component is not None: return self.component.getComponentName() + '_' + self.getName() return self.getName() # =============== # Parent Methods # =============== def getParent(self): """Returns the parent of the object as an object. Return: Parent of this object. """ return self.parent def setParent(self, parent): """Sets the parent attribute of this object. Arguments: parent -- Object, object that is the parent of this one. Return: True if successful. """ self.parent = parent return True # =============== # Hierarchy Methods # =============== def getLayer(self): """Returns the Layer of the object as an object. Return: Layer of this object. """ layer = self while (layer.__class__.__name__ != 'Layer'): layer = layer.parent return layer def getContainer(self): """Returns the Layer of the object as an object. Return: Layer of this object. """ container = self while (container.__class__.__name__ != 'Container'): container = container.parent return container # ================== # Component Methods # ================== def getComponent(self): """Returns the component of the object as an object. Return: Component of this object. """ return self.component def setComponent(self, component): """Sets the component attribute of this object. Arguments: component -- Object, object that is the component of this one. Return: True if successful. """ self.component = component return True # ============== # Child Methods # ============== def checkChildIndex(self, index): """Checks the supplied index is valid. Arguments: index -- Integer, child index to check. """ if index > len(self.children): raise IndexError("'" + str(index) + "' is out of the range of the 'children' array.") return True def addChild(self, child): """Adds a child to this object. Arguments: child -- Object, object that will be a child of this object. Return: True if successful. """ # TODO: WE NEED UNIQUE NAMES BUT WE HAVE A RESTRICTION CURRENTLY WHEN TWO OBJECTS OF DIFFERENT TYPES # NEED THE SAME NAME. i.e.: 'bicep' control and 'bicep' srtBuffer # if child.getName() in [x.getName() for x in self.children]: # raise IndexError("Child with name '" + child.getName() + "'' already exists as a child.") if child.getParent() is not None: parent = child.getParent() if child in parent.children: parent.children.remove(child) self.children.append(child) child.setParent(self) # Assign the child the same component. if self.component is not None: child.setComponent(self.component) return True def removeChildByIndex(self, index): """Removes a child from this object by index. Arguments: index -- Integer, index of child to remove. Return: True if successful. """ if self.checkChildIndex(index) is not True: return False del self.children[index] return True def removeChildByName(self, name): """Removes a child from this object by name. Arguments: name -- String, name of child to remove. Return: True if successful. """ removeIndex = None for i, eachChild in enumerate(self.children): if eachChild.getName() == name: removeIndex = i if removeIndex is None: raise ValueError("'" + name + "' is not a valid child of this object.") self.removeChildByIndex(removeIndex) return True def getNumChildren(self): """Returns the number of children this object has. Return: Integer, number of children of this object. """ return len(self.children) def getChildByIndex(self, index): """Returns the child object at specified index. Arguments: index -- Integer, index of the child to find. Return: Child object at specified index. """ if self.checkChildIndex(index) is not True: return False return self.children[index] def getChildByName(self, name): """Returns the child object with the specified name. Return: Object if found. None if not found. """ for eachChild in self.children: if eachChild.getName() == name: return eachChild return None def getChildrenByType(self, childType): """Returns all children that are of the specified type. Arguments: childType -- Class, type of children to find. Return: Array of child objects of the specified type. None if no objects of specified type are found. """ childrenOfType = [] for eachChild in self.children: if type(eachChild) is childType: childrenOfType.append(eachChild) return childrenOfType def findChild(self, name, targetObj=None): """Finds a child by recursively searching the hierarhcy for a child with the given name. Arguments: name -- String, name of the child to find. targetObj -- Object, object to search under. Used for recursive searching. Return: Object, child if found. """ foundChild = None if targetObj == None: targetObj = self # Build children for i in xrange(targetObj.getNumChildren()): child = targetObj.getChildByIndex(i) if child.getName() == name: foundChild = child else: foundChild = self.findChild(name, child) if foundChild is not None: break return foundChild def findChildrenByType(self, objectType, targetObj=None): """Finds a child by recursively searching the hierarhcy for a child with the given name. Arguments: objectType -- Class, type of children to find. targetObj -- Object, object to search under. Used for recursive searching. Return: List, children of the searched type if found. """ childrenOfType = [] self._findChildByType(objectType, childrenOfType) return childrenOfType def _findChildByType(self, objectType, foundArray, targetObj=None): """Protected find child by type method. Arguments: objectType -- Class, type of children to find. foundArray -- List, list of found children to append to. targetObj -- Object, object to search under. Used for recursive searching. Return: True if successful. """ if targetObj == None: targetObj = self # Build children for i in xrange(targetObj.getNumChildren()): child = targetObj.getChildByIndex(i) if type(child) is objectType: foundArray.append(child) newFoundChildren = self._findChildByType(objectType, foundArray, child) return # ============= # Flag Methods # ============= def setFlag(self, name): """Sets the flag of the specified name. Return: True if successful. """ self.flags[name] = True return True def testFlag(self, name): """Tests if the specified flag is set. Arguments: name -- String, name of the flag to test. Return: True if flag is set, false otherwise. """ if name in self.flags: return True return False def clearFlag(self, name): """Clears the flag of the specified name. Arguments: name -- String, name of the flag to clear. Return: True if successful. """ if name in self.flags: del self.flags[name] return True return False # ======================== # Attribute Group Methods # ======================== def checkAttributeGroupIndex(self, index): """Checks the supplied index is valid. Arguments: index -- Integer, attribute index to check. Return: True if successful. """ if index > len(self.attributeGroups): raise IndexError("'" + str(index) + "' is out of the range of 'attributeGroups' array.") return True def addAttributeGroup(self, attributeGroup): """Adds an attributeGroup to this object. Arguments: attributeGroup -- Object, Attribute Group object to add to this object. Return: True if successful. """ if attributeGroup.getName() in [x.getName() for x in self.attributeGroups]: raise IndexError("Child with " + attributeGroup.getName() + " already exists as a attributeGroup.") self.attributeGroups.append(attributeGroup) attributeGroup.setParent(self) return True def removeAttributeGroupByIndex(self, index): """Removes attribute at specified index. Arguments: index -- Integer, index of attribute to remove. Return: True if successful. """ if self.checkAttributeGroupIndex(index) is not True: return False del self.attributeGroups[index] return True def removeAttributeGroupByName(self, name): """Removes the attribute with the specified name. Arguments: name -- String, name of the attribute to remove. Return: True if successful. """ removeIndex = None for i, eachAttributeGroup in enumerate(self.attributeGroups): if eachAttributeGroup.getName() == name: removeIndex = i if removeIndex is None: return False self.removeAttributeGroupByIndex(removeIndex) return True def getNumAttributeGroups(self): """Returns the number of attributeGroups as an integer. Return: Integer of the number of attributeGroups on this object. """ return len(self.attributeGroups) def getAttributeGroupByIndex(self, index): """Returns the attribute at the specified index. Arguments: index -- Integer, index of the attribute to return. Return: AttributeGroup at the specified index. False if not a valid index. """ if self.checkAttributeGroupIndex(index) is not True: return False return self.attributeGroups[index] def getAttributeGroupByName(self, name): """Return the attribute group with the specified name. Arguments: name -- String, name of the attribute group to return. Return: Attribute with the specified name. None if not found. """ for eachAttributeGroup in self.attributeGroups: if eachAttributeGroup.getName() == name: return eachAttributeGroup return None # =================== # Constraint Methods # =================== def checkConstraintIndex(self, index): """Checks the supplied index is valid. Arguments: index -- Integer, constraint index to check. Return: True if successful. """ if index > len(self.constraints): raise IndexError("'" + str(index) + "' is out of the range of 'constraints' array.") return True def addConstraint(self, constraint): """Adds an constraint to this object. Arguments: constraint -- Object, Constraint object to add to this object. Return: True if successful. """ if constraint.getName() in [x.getName() for x in self.constraints]: raise IndexError("Constraint with name '" + constraint.getName() + "'' already exists as a constraint.") self.constraints.append(constraint) constraint.setParent(self) constraint.setConstrainee(self) return True def removeConstraintByIndex(self, index): """Removes constraint at specified index. Arguments: index -- Integer, index of constraint to remove. Return: True if successful. """ if self.checkConstraintIndex(index) is not True: return False del self.constraints[index] return True def removeConstraintByName(self, name): """Removes the constraint with the specified name. Arguments: name -- String, name of the constraint to remove. Return: True if successful. """ removeIndex = None for i, eachConstraint in enumerate(self.constraints): if eachConstraint.getName() == name: removeIndex = i if removeIndex is None: return False self.removeConstraintByIndex(removeIndex) return True def getNumConstraints(self): """Returns the number of constraints as an integer. Return: Integer of the number of constraints on this object. """ return len(self.constraints) def getConstraintByIndex(self, index): """Returns the constraint at the specified index. Arguments: index -- Integer, index of the constraint to return. Return: Constraint at the specified index. False if not a valid index. """ if self.checkConstraintIndex(index) is not True: return False return self.constraints[index] def getConstraintByName(self, name): """Return the constraint group with the specified name. Arguments: name -- String, name of the constraint group to return. Return: Attribute with the specified name. None if not found. """ for eachConstraint in self.constraints: if eachConstraint.getName() == name: return eachConstraint return None # ============== # kType Methods # ============== def getKType(self): """Returns the kType of this object. Return: True if successful. """ return self.__kType__ # =================== # Visibility Methods # =================== def getVisibility(self): """Returns the visibility status of the scene item. Return: Boolean, visible or not. """ return self.visibility def setVisibility(self, value): """Sets the visibility of the scene object. Arguments: value -- Boolean, value of the visibility of the object. Return: True if successful. """ self.visibility = value return True def getShapeVisibility(self): """Returns the shape visibility status of the scene item. Return: Boolean, visible or not. """ return self.shapeVisibility def setShapeVisibility(self, value): """Sets the shape visibility of the scene object. Arguments: value -- Boolean, value of the visibility of the object. Return: True if successful. """ self.shapeVisibility = value return True # ================ # Display Methods # ================ def setColor(self, color): """Sets the color of this object. Arguments: color -- String, name of the color you wish to set. Return: True if successful. """ self.color = color return True def getColor(self): """Returns the color of the object. Return: String, color of the object. """ return self.color # ================== # Transform Methods # ================== def lockAttribute(self, attributeName): pass def unlockAttribute(self, attributeName): pass def hideAttribute(self, attributeName): pass def unhideAttribute(self, attributeName): pass # ==================== # Persistence Methods # ==================== def jsonEncode(self, saver): """Returns the data for this object encoded as a JSON hierarchy. Arguments: Return: A JSON structure containing the data for this SceneItem. """ classHierarchy = [] for cls in type.mro(type(self)): if cls == object: break; classHierarchy.append(cls.__name__) jsonData = { '__typeHierarchy__': classHierarchy, 'name': self.name, 'parent': None, 'children': [], 'flags': self.flags, 'attributeGroups': [], 'constraints': [], 'xfo': self.xfo.jsonEncode(), 'color': self.color, 'visibility': self.visibility, 'shapeVisibility': self.shapeVisibility, } if self.parent is not None: jsonData['parent'] = self.parent.getName() if self.color is not None: jsonData['color'] = saver.encodeValue(self.color) for child in self.children: jsonData['children'].append(child.jsonEncode(saver)) for attrGroup in self.attributeGroups: jsonData['attributeGroups'].append(attrGroup.jsonEncode(saver)) for constr in self.constraints: jsonData['constraints'].append(constr.jsonEncode(saver)) return jsonData def jsonDecode(self, loader, jsonData): """Returns the color of the object. Return: True if decoding was successful """ self.parent = loader.getParentItem() self.flags = jsonData['flags'] self.xfo = loader.decodeValue(jsonData['xfo']) if 'color' in jsonData and jsonData['color'] is not None: self.color = loader.decodeValue(jsonData['color']) self.visibility = jsonData['visibility'] self.shapeVisibility = jsonData['shapeVisibility'] for child in jsonData['children']: self.addChild(loader.construct(child)) for attrGroup in jsonData['attributeGroups']: # There is one default attribute group assigned to each scene item. # Load data into the existing item instead of constructing a new one. if attrGroup['name'] == '': loader.registerItem(self.attributeGroups[0]) self.attributeGroups[0].jsonDecode(loader, attrGroup) else: self.addAttributeGroup(loader.construct(attrGroup)) for constr in jsonData['constraints']: self.addConstraint(loader.construct(constr)) return True
def getRigBuildData(self): """Returns the Guide data used by the Rig Component to define the layout of the final rig.. Return: The JSON rig data object. """ data = super(LegComponentGuide, self).getRigBuildData() # Values femurPosition = self.femurCtrl.xfo.tr kneePosition = self.kneeCtrl.xfo.tr anklePosition = self.ankleCtrl.xfo.tr toePosition = self.toeCtrl.xfo.tr toeTipPosition = self.toeTipCtrl.xfo.tr # Calculate Bicep Xfo rootToWrist = anklePosition.subtract(femurPosition).unit() rootToKnee = kneePosition.subtract(femurPosition).unit() bone1Normal = rootToWrist.cross(rootToKnee).unit() bone1ZAxis = rootToKnee.cross(bone1Normal).unit() femurXfo = Xfo() femurXfo.setFromVectors(rootToKnee, bone1Normal, bone1ZAxis, femurPosition) # Calculate Forearm Xfo elbowToWrist = anklePosition.subtract(kneePosition).unit() elbowToRoot = femurPosition.subtract(kneePosition).unit() bone2Normal = elbowToRoot.cross(elbowToWrist).unit() bone2ZAxis = elbowToWrist.cross(bone2Normal).unit() kneeXfo = Xfo() kneeXfo.setFromVectors(elbowToWrist, bone2Normal, bone2ZAxis, kneePosition) femurLen = femurPosition.subtract(kneePosition).length() shinLen = kneePosition.subtract(anklePosition).length() handleXfo = Xfo() handleXfo.tr = anklePosition ankleXfo = Xfo() ankleXfo.tr = anklePosition # ankleXfo.ori = kneeXfo.ori toeXfo = Xfo() toeXfo.tr = toePosition # toeXfo.ori = kneeXfo.ori upVXfo = xfoFromDirAndUpV(femurPosition, anklePosition, kneePosition) upVXfo.tr = kneePosition upVXfo.tr = upVXfo.transformVector(Vec3(0, 0, 5)) data['femurXfo'] = femurXfo data['kneeXfo'] = kneeXfo data['handleXfo'] = handleXfo data['ankleXfo'] = ankleXfo data['toeXfo'] = toeXfo data['upVXfo'] = upVXfo data['femurLen'] = femurLen data['shinLen'] = shinLen return data