def asMFnIkJoint(self): self.__assertDagNode() if self.getApiTypeStr() != 'kJoint': raise riggingToolsError.RiggingToolsError, 'This method can be used only for DagNodeWrappers that "contains" a dagNode of type kJoint, but the wrapped dagNode is of type %s' %self.getApiTypeStr() path = OpenMaya.MDagPath() self.asMFnDagNode().getPath(path) tran = OpenMayaAnim.MFnIkJoint(path) return tran
def bdMain(): dagPath = om.MDagPath() mObj = om.MObject() selection = om.MSelectionList() status = om.MGlobal.getActiveSelectionList(selection) try: status = selection.getDependNode(0,mObj) except: sys.stderr.write('Nothing is selected, you need to select the IK handle') return if mObj.hasFn(om.MFn.kIkHandle): ikHandleFn = oma.MFnIkHandle(mObj) startJointPath = om.MDagPath() ikHandleFn.getStartJoint(startJointPath) startJointTransformNode = startJointPath.transform() startJointTransformFn = om.MFnTransform(startJointTransformNode) print startJointTransformFn.name() rotateOrientation = startJointTransformFn.rotateOrientation(om.MSpace.kTransform) rotateOrientationEuler = rotateOrientation .asEulerRotation() print 'Rotation axis', math.degrees(rotateOrientationEuler.x), math.degrees(rotateOrientationEuler.y), math.degrees(rotateOrientationEuler.z) matrix = om.MTransformationMatrix(startJointTransformFn.transformationMatrix()) rotOrderAxis = matrix.rotationOrder() print rotOrderAxis quatRotation = om.MQuaternion() startJointTransformFn.getRotation(quatRotation) eulerRotation = quatRotation.asEulerRotation() print 'Local Rotation ', math.degrees(eulerRotation.x), math.degrees(eulerRotation.y), math.degrees(eulerRotation.z) translation = matrix.getTranslation(om.MSpace.kWorld) print 'World transation', translation.x, translation.y, translation.z ikJoint = oma.MFnIkJoint(startJointTransformNode) jointOrient = om.MEulerRotation() quatJointOrient = om.MQuaternion() ikJoint.getRotation(quatJointOrient) ikJoint.getOrientation(jointOrient) print 'Joint orientation', math.degrees(jointOrient.x) , math.degrees(jointOrient.y), math.degrees(jointOrient.z) globalRot = om.MQuaternion() globalRot = rotateOrientation * quatRotation * quatJointOrient globalRotEuler = globalRot.asEulerRotation() print 'World orientation', math.degrees(globalRot.x) , math.degrees(globalRot.y), math.degrees(globalRot.z) print bdGetChainLength(ikJoint)
def redoIt(self): ''' Create and manipulate the nodes to form the joint chain. ''' # Perform the operations enqueued within our reference to MDagModifier. self.dagModifier.doIt() # ======================================= # JOINT MANIPULATION # ======================================= # We can now use the function sets on the newly created DAG objects. jointFn = OpenMayaAnim.MFnIkJoint() for i in range(1, len(self.jointObjects)): jointFn.setObject(self.jointObjects[i]) # We set the orientation for our joint to be 'jointOrientation' degrees, to form an arc. # We use MFnIkJoint.setOrientation() instead of MFnTransform.setRotation() to let the # inverse-kinematic handle maintain the curvature. global jointOrientation rotationAngle = OpenMaya.MAngle(jointOrientation, OpenMaya.MAngle.kDegrees) jointFn.setOrientation( OpenMaya.MEulerRotation(rotationAngle.asRadians(), 0, 0, OpenMaya.MEulerRotation.kXYZ)) # We translate the joint by 'jointDistance' units along its parent's y axis. global jointDistance translationVector = OpenMaya.MVector(0, jointDistance, 0) jointFn.setTranslation(translationVector, OpenMaya.MSpace.kTransform) # ======================================= # IK HANDLE MANIPULATION # ======================================= # We will use the MEL command 'ikHandle' to create the handle which will move our joint chain. This command # will be enqueued in our reference to the MDagModifier so that it can be undone in our call to MDagModifier.undoIt(). # Obtain the DAG path of the first joint. startJointDagPath = OpenMaya.MDagPath() jointFn.setObject(self.jointObjects[0]) jointFn.getPath(startJointDagPath) # Obtain the DAG path of the effector. effectorDagPath = OpenMaya.MDagPath() effectorFn = OpenMayaAnim.MFnIkEffector(self.effectorObj) effectorFn.getPath(effectorDagPath) # Enqueue the following MEL command with the DAG paths of the start joint and the end effector. self.dagModifier.commandToExecute('ikHandle -sj ' + startJointDagPath.fullPathName() + ' -ee ' + effectorDagPath.fullPathName()) # We call MDagModifier.doIt() to effectively execute the MEL command and create the ikHandle. self.dagModifier.doIt()
def importSkeletonNode(skeleton): if skeleton is None: return (None, None) bones = skeleton.Bones() handles = [None] * len(bones) paths = [None] * len(bones) jointTransform = OpenMaya.MFnTransform() jointNode = jointTransform.create() jointTransform.setName("Joints") for i, bone in enumerate(bones): newBone = OpenMayaAnim.MFnIkJoint() newBone.create(jointNode) newBone.setName(bone.Name()) handles[i] = newBone for i, bone in enumerate(bones): if bone.ParentIndex() > -1: cmds.parent(handles[i].fullPathName(), handles[bone.ParentIndex()].fullPathName()) for i, bone in enumerate(bones): scaleUtility = OpenMaya.MScriptUtil() newBone = handles[i] paths[i] = newBone.fullPathName() if bone.SegmentScaleCompensate() is not None: segmentScale = bone.SegmentScaleCompensate() cmds.setAttr("%s.segmentScaleCompensate" % paths[1], segmentScale) if bone.LocalPosition() is not None: localPos = bone.LocalPosition() localRot = bone.LocalRotation() newBone.setTranslation( OpenMaya.MVector(localPos[0], localPos[1], localPos[2]), OpenMaya.MSpace.kTransform) newBone.setOrientation( OpenMaya.MQuaternion(localRot[0], localRot[1], localRot[2], localRot[3])) if bone.Scale() is not None: scale = bone.Scale() scaleUtility.createFromList([scale[0], scale[1], scale[2]], 3) newBone.setScale(scaleUtility.asDoublePtr()) return (handles, paths)
def loadMatrixCache(cacheFile, agent='', targetNS=''): """ """ # Initialize Frame No. frame = 0 # Check NS if targetNS: targetNS += ':' # Open File f = open(cacheFile, 'r') lines = f.readlines() # Load Cache for line in lines: # Get Frame if line.startswith('# frame'): frame = line.split(' ')[-1] print frame continue # Get Matrix seg = line.split(' ')[0] mat = ast.literal_eval(line.replace(seg + ' ', '')) matrix = buildMatrix(mat) # Check Agent if agent and seg == 'Agent': seg = agent # =================== # - Get Translation - # =================== pos = OpenMaya.MTransformationMatrix(matrix).getTranslation( OpenMaya.MSpace.kTransform) t = [pos[0], pos[1], pos[2]] # ================ # - Get Rotation - # ================ # Factor in Joint Orientation if cmds.objectType(seg) == 'joint': segObj = glTools.utils.base.getMObject(seg) segFn = OpenMayaAnim.MFnIkJoint(segObj) segOri = OpenMaya.MQuaternion() segFn.getOrientation(segOri) matrix *= segOri.asMatrix().inverse() # Get Rotation rot = OpenMaya.MTransformationMatrix(matrix).eulerRotation() rad = mel.eval('rad_to_deg(1)') r = [rot.x * rad, rot.y * rad, rot.z * rad] # ================= # - Set Keyframes - # ================= cmds.setKeyframe(targetNS + seg, at='tx', v=t[0], t=float(frame)) cmds.setKeyframe(targetNS + seg, at='ty', v=t[1], t=float(frame)) cmds.setKeyframe(targetNS + seg, at='tz', v=t[2], t=float(frame)) cmds.setKeyframe(targetNS + seg, at='rx', v=r[0], t=float(frame)) cmds.setKeyframe(targetNS + seg, at='ry', v=r[1], t=float(frame)) cmds.setKeyframe(targetNS + seg, at='rz', v=r[2], t=float(frame)) # ============== # - Close File - # ============== f.close()
import sys import math mObj = om.MObject() dagPath = om.MDagPath() selection = om.MSelectionList() om.MGlobal.getActiveSelectionList(selection) try: status = selection.getDependNode(0,mObj) selection.getDagPath(0,dagPath) except: sys.stderr.write('Nothing is selected, you need to select the IK handle') jointFn = oma.MFnIkJoint(mObj) jointPath = om.MDagPath() print jointFn.name(), dagPath.fullPathName() inclusiveMatrix = om.MMatrix(dagPath.inclusiveMatrix()) transformMatrix = om.MTransformationMatrix(dagPath.inclusiveMatrix()) quatRotation = om.MQuaternion() quatRotation = transformMatrix.rotation() eulerRotation = quatRotation.asEulerRotation() print 'Global Rotation ', math.degrees(eulerRotation.x), math.degrees(eulerRotation.y), math.degrees(eulerRotation.z) ''' for i in range(0,4):
def LoadPSKFile(filePath): """ Loads PSK Data into Maya """ # Load PSK File pskfile = psk.UnrealPSK(filePath) mObj = OpenMaya.MFnSingleIndexedComponent().create( OpenMaya.MFn.kMeshVertComponent) # Maya Arrays/Data weightIndices = OpenMaya.MIntArray() # Create Joints joints = [] mjoints = [] mtransform = OpenMaya.MFnTransform() bone_group = mtransform.create() mtransform.setName("PSKJoints") for i, joint in enumerate(pskfile.bones): mbone = OpenMayaAnim.MFnIkJoint() if i == 0: bone = mbone.create(bone_group) else: bone = mbone.create(joints[joint.parent]) mbone.setName(joint.name) mbone.setOrientation( OpenMaya.MQuaternion(-joint.rotation[0], -joint.rotation[1], -joint.rotation[2], joint.rotation[3])) mbone.setTranslation( OpenMaya.MVector(joint.offset[0], joint.offset[1], joint.offset[2]), OpenMaya.MSpace.kTransform) joints.append(bone) mjoints.append(mbone) weightIndices.append(i) # Create Maya Arrays weightVals = OpenMaya.MDoubleArray( len(pskfile.wedges) * weightIndices.length()) vertexArray = OpenMaya.MFloatPointArray() polygonCounts = OpenMaya.MIntArray(len(pskfile.faces), 3) polygonConnects = OpenMaya.MIntArray() uArray = OpenMaya.MFloatArray() vArray = OpenMaya.MFloatArray() # Material Faces materialPolys = {} materials = {} # Materials # Add Materials for i, material in enumerate(pskfile.materials): shader = cmds.shadingNode("lambert", name=material.name, asShader=True) materials[i] = shader materialPolys[i] = [] # Add Vertex Data weight = 0 for i, wedge in enumerate(pskfile.wedges): vertexArray.append(pskfile.vertices[wedge.point].offset[0], pskfile.vertices[wedge.point].offset[1], pskfile.vertices[wedge.point].offset[2]) uArray.append(wedge.uv[0]) vArray.append(1 - wedge.uv[1]) weights = pskfile.weights[wedge.point] for j in range(weightIndices.length()): weightVals[weight] = weights[j] weight += 1 # Add Face Data fid = 0 for i, face in enumerate(pskfile.faces): polygonConnects.append(face.wedges[0]) polygonConnects.append(face.wedges[2]) polygonConnects.append(face.wedges[1]) materialPolys[face.material_index].append(i) # Create Maya Mesh mesh = OpenMaya.MFnMesh() transform = mesh.create(vertexArray.length(), len(pskfile.faces), vertexArray, polygonCounts, polygonConnects) # Assign UVs mesh.setUVs(uArray, vArray) mesh.assignUVs(polygonCounts, polygonConnects) # Create Groups and assign Material/s mtransform = OpenMaya.MFnTransform() bone_group = mtransform.create() mtransform.setName("PSKMeshes") dagPath = OpenMaya.MDagPath() OpenMaya.MDagPath.getAPathTo(transform, dagPath) newPath = cmds.parent(dagPath.fullPathName(), "PSKMeshes") newPath = cmds.rename(newPath, "PSKMesh") cmds.select(newPath) # TODO: Improve on face Materials, currently in all # cases I've found material faces to run in a series # but I'm unsure if they can be spread out and might throw this off for index in materialPolys: cmds.select(newPath + ".f[%i:%i]" % (materialPolys[index][0], materialPolys[index][-1]), r=True) cmds.hyperShade(assign=materials[index]) cmds.select(clear=True) for joint in mjoints: cmds.select(joint.partialPathName(), add=True) cmds.select(newPath, add=True) # Set Weights cluster = cmds.skinCluster(tsb=True) selList = OpenMaya.MSelectionList() selList.add(cluster[0]) clusterNode = OpenMaya.MObject() selList.getDependNode(0, clusterNode) skin = OpenMayaAnim.MFnSkinCluster(clusterNode) cmds.select(clear=True) skin.setWeights(dagPath, mObj, weightIndices, weightVals)
def splinePreSolve(self, solvernode): # '\n initiate all the members of the class.\n including :\n handleFn , handlePath , effectorFn , startJointFn ,\n startJointPrefAngle , .\n the reason why I put the initial codes here is fail to load the plugin ,\n when I put these codes in the __init__() function .\n ' solvernode.setRotatePlane(0) solvernode.setSingleChainOnly(1) solvernode.setPositionOnly(0) handleGroup = solvernode.handleGroup() handle = handleGroup.handle(0) self.handlePath = OpenMaya.MDagPath() self.handlePath.getAPathTo(handle, self.handlePath) self.handleFn = OpenMayaAnim.MFnIkHandle(self.handlePath) if not self.handleFn.hasAttribute('str'): fnAttr = OpenMaya.MFnNumericAttribute() attr = fnAttr.create('stretchRatio', 'str', OpenMaya.MFnNumericData.kDouble, self.stretchRatio) fnAttr.setKeyable(1) fnAttr.setWritable(1) fnAttr.setMin(0) fnAttr.setMax(1) fnAttr.setHidden(0) fnAttr.setStorable(1) fnAttr.setReadable(1) self.handleFn.addAttribute( attr, OpenMaya.MFnDependencyNode.kLocalDynamicAttr) else: strPlug = self.handleFn.findPlug('str') self.stretchRatio = strPlug.asDouble() effectorPath = OpenMaya.MDagPath() self.handleFn.getEffector(effectorPath) self.effectorFn = OpenMayaAnim.MFnIkEffector(effectorPath) startJointPath = OpenMaya.MDagPath() self.handleFn.getStartJoint(startJointPath) self.startJointFn = OpenMayaAnim.MFnIkJoint(startJointPath) self.joints = [] currJoint = '' inCurvePlug = self.handleFn.findPlug('inCurve') curveHandle = inCurvePlug.asMDataHandle() inputCurveObject = curveHandle.asNurbsCurveTransformed() self.curveFn = OpenMaya.MFnNurbsCurve(inputCurveObject) #get joints while True: effectorPath.pop() j = OpenMayaAnim.MFnIkJoint(effectorPath) self.joints.append(j) currJoint = effectorPath if currJoint == startJointPath: break self.joints = list(reversed(self.joints)) #get lengths for v, j in enumerate(self.joints): pBaseJoint = j.rotatePivot(OpenMaya.MSpace.kWorld) if v == len(self.joints) - 1: pEndJoint = self.effectorFn.rotatePivot(OpenMaya.MSpace.kWorld) else: #get position of next joint pEndJoint = self.joints[v + 1].rotatePivot( OpenMaya.MSpace.kWorld) jVec = OpenMaya.MVector(pBaseJoint[0] - pEndJoint[0], pBaseJoint[1] - pEndJoint[1], pBaseJoint[2] - pEndJoint[2]) self.jointsVectors.append(jVec) self.initLength.append(jVec.length())
def create(s_type, s_name, mo_parent=None, s_namespace=None, i_restriction=0): """ !@Brief Create node. @type s_type: str / unicode @param s_type: Node type. @type s_name: str / unicode @param s_name: Node name. @type mo_parent: OpenMaya.MObject @param mo_parent: Parent object for dagNode. @type s_namespace: str / unicode @param s_namespace: With given namespace. @type i_restriction: int @param i_restriction: ObjectSet restriction. @rtype: OpenMaya.MObject @return: """ if isinstance(s_name, (str, unicode)) is False: raise TypeError("Argument must be a string not {0}".format(type(s_name))) if mo_parent is not None: if isinstance(mo_parent, OpenMaya.MObject) is False: raise Exception("Parent given is invalid. Parent must be an MObject not {0}".format(type(mo_parent))) if mo_parent.isNull() is True: raise Exception("Parent given object is null.") if mo_parent.hasFn(OpenMaya.MFn.kWorld) is True: mo_parent = None if mo_parent is not None and mo_parent.hasFn(OpenMaya.MFn.kTransform) is False: raise Exception("Parent is invalid. Parent node must be a transform not {0}".format(mo_parent.apiTypeStr())) # Set specific namespace if s_namespace is not None and s_namespace != "": s_namespace = apiUtils.set_namespace(s_namespace) # Create Node mdg_mod = OpenMaya.MDGModifier() if s_type == 'transform': if mo_parent is None: mo_node = OpenMaya.MFnTransform().create() else: mo_node = OpenMaya.MFnTransform().create(mo_parent) elif s_type == 'joint': if mo_parent is None: mo_node = OpenMayaAnim.MFnIkJoint().create() else: mo_node = OpenMayaAnim.MFnIkJoint().create(mo_parent) elif s_type == 'objectSet': mo_node = OpenMaya.MFnSet().create(OpenMaya.MSelectionList(), i_restriction) else: mo_node = OpenMaya.MFnDependencyNode().create(s_type) if mo_parent is not None and mo_node.hasFn(OpenMaya.MFn.kTransform): mfn_parent = OpenMaya.MFnDagNode(mo_parent) mfn_parent.addChild(mo_node) mdg_mod.renameNode(mo_node, s_name) mdg_mod.doIt() del mdg_mod # Restore current namespace if s_namespace is not None and s_namespace != "": apiUtils.set_namespace(s_namespace) return mo_node