def match(self, *args): characterContainer = self.characterNamespaceOnly + ":character_container" blueprintContainer = self.blueprintNamespace + ":module_container" moduleContainer = self.blueprintNamespace + ":" + self.moduleNamespace +":module_container" containers = [characterContainer, blueprintContainer, moduleContainer] for c in containers: cmds.lockNode(c, lock=False, lockUnpublished=False) ikJointsAll = utils.findJointChain(self.blueprintNamespace + ":" + self.moduleNamespace + ":joints_grp") blueprintJointsAll = utils.findJointChain(self.blueprintNamespace + ":blueprint_joints_grp") ikJoints = [ikJointsAll[1], ikJointsAll[2], ikJointsAll[3]] blueprintJoints = [blueprintJointsAll[1], blueprintJointsAll[2], blueprintJointsAll[3]] ikHandleControl = self.blueprintNamespace + ":" + self.moduleNamespace + ":ikHandleControl" if cmds.objExists(ikHandleControl): cmds.setAttr(ikHandleControl+".stretchiness", 1) endPos = cmds.xform(blueprintJoints[2], q=True, worldSpace=True, translation=True) cmds.xform(ikHandleControl, worldSpace=True, absolute=True, translation=endPos) twistControl = self.blueprintNamespace + ":" + self.moduleNamespace + ":twistControl" utils.matchTwistAngle(twistControl+".rotateZ", ikJoints, blueprintJoints) for c in containers: cmds.lockNode(c, lock=True, lockUnpublished=True)
def changeNumberOfJoints(self, *args): self.blueprint_UI_instance.deleteScriptJob() joints = self.getJoints() numJoints = len(joints) newNumJoints = cmds.intField(self.numberOfJointsField, q=True, value=True) startPos = cmds.xform(self.getTranslationControl(joints[0]), q=True, ws=True, t=True) endPos = cmds.xform(self.getTranslationControl(joints[numJoints-1]), q=True, ws=True, t=True) hookObject = self.findHookObjectForLock() rotationOrder = cmds.getAttr(joints[0] + ".rotateOrder") sao_local = cmds.getAttr(self.moduleNamespace+":module_grp.sao_local") sao_world = cmds.getAttr(self.moduleNamespace+":module_grp.sao_world") self.delete() newInstance = Spline(self.userSpecifiedName, hookObject, newNumJoints, startPos, endPos) newInstance.install() # We have to refer to the new instance stored in memory newJoints = newInstance.getJoints() cmds.setAttr(newJoints[0]+".rotateOrder", rotationOrder) cmds.setAttr(newInstance.moduleNamespace+":module_grp.sao_local", sao_local) cmds.setAttr(newInstance.moduleNamespace+":module_grp.sao_world", sao_world) self.blueprint_UI_instance.createScriptJob() cmds.select(newInstance.moduleNamespace+":module_transform", replace=True)
def set_knee_IK(): # メッセージ cmds.inViewMessage(amg="<hl>「指のコントローラー設置」</hl>を押してください。", pos="midCenter", fade=True, fit=1, fst=4000, fts=20) # 座標取得 positionR = cmds.xform("Knee_R", q=True, ws=True, t=True) locatorNameR = "Knee_R_Locator" # ロケーター設置 cmds.spaceLocator(p=(positionR[0], positionR[1], positionR[2] + 3.8), n=locatorNameR) knee_ik_add("Hip_R", "Ankle_R", "Knee_R_Effector", positionR, locatorNameR) # 座標取得 positionL = cmds.xform("Knee_L", q=True, ws=True, t=True) locatorNameL = "Knee_L_Locator" # ロケーター設置 cmds.spaceLocator(p=(positionL[0], positionL[1], positionL[2] + 3.8), n=locatorNameL) knee_ik_add("Hip_L", "Ankle_L", "Knee_L_Effector", positionL, locatorNameL) # つま先のIK実行 toe_ik_add("Ankle_R", "MiddleToe2_R", "Ankle_R_Effector") toe_ik_add("Ankle_L", "MiddleToe2_L", "Ankle_L_Effector") # 足のコントローラー、 座標取得 toePositionR = cmds.xform("MiddleToe1_R", q=True, ws=True, t=True) toePositionL = cmds.xform("MiddleToe1_L", q=True, ws=True, t=True) foot_controller("foot_R_controller", toePositionR[0]) foot_controller("foot_L_controller", toePositionL[0]) # コントローラー内にエフェクター移動 cmds.parent("Ankle_L_Effector", "foot_L_controller") cmds.parent("Knee_L_Effector", "foot_L_controller") cmds.parent("Ankle_R_Effector", "foot_R_controller") cmds.parent("Knee_R_Effector", "foot_R_controller") # 親子関係移動 cmds.parent("Knee_R_Locator", "Knee_L_Locator", "foot_R_controller", "foot_L_controller", "main_controller")
def rotateToOrient (joint): ''' Transfer the euler rotate values to the joint orientation :param joint: Joint(s) you want to do the transfer for :type joint: *str* or *list* ''' sArrJoints = [joint]#common.toList(joint) for j in sArrJoints: if cmds.objectType(j)=='joint': doit=True for attr in ['rx','ry','rz','jox','joy','joz','ro']: #don't exists, lock,or connected if cmds.getAttr(j+'.'+attr,l=True) or cmds.listConnections('%s.%s' % (j,attr), destination = False, plugs = True): doit=False if doit: roo = cmds.xform(j,q=True,roo=True)#get rotation order cmds.xform(j, p=True, roo='xyz' )#set rotation order to default (joint orient only works with xyz rotation order) orientToRotate(j)#transfer current joint orient to rotate ori = cmds.getAttr(j+'.r')[0] cmds.setAttr(j+'.jo',ori[0],ori[1],ori[2]) cmds.setAttr(j+'.r',0,0,0) cmds.xform(j, p=True, roo=roo )#set back the initial rotation order else: print ('//Warning: "' + j + '" is locked or connected, unable to set rotation')
def unparent(shape): ''' Unparent shape nodes from a source parent @param shape: Shape or transform to unparent shapes from @type shape: str ''' # Checks if not mc.objExists(shape): raise Exception('Object "'+shape+'" does not exist!!') # Get shapes if mc.ls(shape,type='transform'): transform = shape shapes = mc.listRelatives(shape,s=True,pa=True) else: transform = mc.listRelatives(shape,p=True,pa=True)[0] shapes = [shape] # Create shape holder shapeHolder = transform+'Shapes' if not mc.objExists(shapeHolder): shapeHolder = mc.createNode('transform',n=shapeHolder) targetXform = mc.xform(transform,q=True,ws=True,m=True) mc.xform(shapeHolder,ws=True,m=targetXform) # Unparent shapes for shape in shapes: mc.parent(shape,shapeHolder,s=True,r=True) # Return Result return shapeHolder
def huddleExec(*args): """from first selection, will use vector math (basic addition/subtraction) to move the next selected objects closer or farther from first selection based on slider values (as a percentage)""" factor = cmds.floatSliderGrp(widgets["slider"], q=True, v=True) sel = cmds.ls(sl=True, type="transform") center = sel[0] objs = sel[1:] centerPos = cmds.xform(center, q=True, ws=True, rp=True) centerVec = om.MVector(centerPos[0], centerPos[1], centerPos[2]) # print (centerVec[0], centerVec[1], centerVec[2]) for obj in objs: # get location objPos = cmds.xform(obj, ws=True, q=True, rp=True) objVec = om.MVector(objPos[0], objPos[1], objPos[2]) # print (objVec[0], objVec[1], objVec[2]) #find difference vector between obj and center diffVec = objVec-centerVec #scale that vector scaledVec = diffVec * factor #add that vector to the center vec newVec = scaledVec + centerVec #apply it to the position of the obj cmds.xform(obj, ws=True, t=(newVec[0], newVec[1], newVec[2]))
def main(): mm.eval('selectCurveCV("all");') sel = mc.ls(sl=1, fl=1) grpname = (sel[0].split('.')) grpname = grpname[0]+"_grp" grp = mc.group(em=1, n=grpname) for i in sel: iname = i.replace('[', '') iname = iname.replace(']','') iname = iname.replace('.','_') locname = iname+"_loc" clusname = iname+"_clus" mc.select(i, r=1) print "here" cluster = mc.cluster(n=clusname) location = mc.xform(cluster, q=1, ws=1, sp=1) print location locator = mc.spaceLocator(n=locname, p=(location[0], location[1], location[2])) mc.xform(locator, cp=1) set_vis = clusname+"Handle.visibility" mc.setAttr(set_vis, 0) mc.parent(cluster, locator) mc.parent(locator, grp) shape = mc.listRelatives(locator) mc.setAttr((shape[0]+".overrideEnabled"),1) mc.setAttr((shape[0]+".overrideColor"),17)
def _mirror_setFollowDefault(self): for target in self.__followTargets: if target.find( 'Collar' ) != -1: otherTarget = target.replace( 'Collar_L', 'Arm_L_PoleV' ).replace( 'Collar_R', 'Arm_R_PoleV' ) mtxList = cmds.getAttr( otherTarget+'.wm' ) elif target.find( 'Leg' ) != -1: poleVTarget = target.replace( 'Switch_CTL', 'PoleV_CTL' ) poleVMtxList = cmds.getAttr( poleVTarget+'.wm' ) mtxList = cmds.getAttr( target.replace( 'Switch', 'IK' ) +'.wm' ) else: mtxList = cmds.getAttr( target.replace( 'Switch', 'IK' ) +'.wm' ) udAttrs = cmds.listAttr( target, ud=1 ) for attr in udAttrs: if attr.find( 'Follow' ) != -1: case1 = target.find( 'Arm' ) != -1 and attr == 'collarFollow' case2 = target.find( 'Leg' ) != -1 and attr == 'hipFollow' case3 = attr == 'neckFollow' if case1 or case2 or case3: cmds.setAttr( target+'.'+attr, 10 ) else: cmds.setAttr( target+'.'+attr, 0 ) if target.find( 'Switch' ) != -1: target = target.replace( 'Switch', 'IK' ) elif target.find( 'Collar' ) != -1: target = target.replace( 'Collar_L', 'Arm_L_PoleV' ).replace( 'Collar_R', 'Arm_R_PoleV' ) cmds.xform( target, ws=1, matrix = mtxList ) if cmds.nodeType( target ) == 'joint': rigbase.setRotate_keepJointOrient(mtxList, target) if target.find( 'Leg' ) != -1: cmds.xform( poleVTarget, ws=1, matrix = poleVMtxList )
def _mirror_setFollowValues(self): for target in self.__followTargets: if target.find( 'Collar' ) != -1: otherTarget = target.replace( 'Collar_L', 'Arm_L_PoleV' ).replace( 'Collar_R', 'Arm_R_PoleV' ) mtxList = cmds.getAttr( otherTarget+'.wm' ) elif target.find( 'Leg' ) != -1: poleVTarget = target.replace( 'Switch_CTL', 'PoleV_CTL' ) poleVMtxList = cmds.getAttr( poleVTarget+'.wm' ) mtxList = cmds.getAttr( target.replace( 'Switch', 'IK' )+'.wm' ) else: mtxList = cmds.getAttr( target.replace( 'Switch', 'IK' )+'.wm' ) index = self.__followTargets.index( target ) udAttrs = cmds.listAttr( target, ud=1 ) for attr in udAttrs: if attr.find( 'Follow' ) != -1: cmds.setAttr( target+'.'+attr, self.__followValues[index].pop(0) ) if target.find( 'Switch' ) != -1: target = target.replace( 'Switch', 'IK' ) elif target.find( 'Collar' ) != -1: target = target.replace( 'Collar_L', 'Arm_L_PoleV' ).replace( 'Collar_R', 'Arm_R_PoleV' ) cmds.xform( target, ws=1, matrix = mtxList ) if cmds.nodeType( target ) == 'joint': rigbase.setRotate_keepJointOrient( mtxList, target ) if target.find( 'Leg' ) != -1: cmds.xform( poleVTarget, ws=1, matrix = poleVMtxList )
def returnLinearDirection(rootObj,aimObj): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Returns a linear direction ARGUMENTS: rootObj(string) aimObj(string) RETURNS: direction(string) - 'x,y,z,-x,-y,-z' >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ #make locators in case we're using something like joints axis = {0:'x',1:'y',2:'z'} rootPos = mc.xform (rootObj,q=True, ws=True, rp=True) aimPos = mc.xform (aimObj,q=True, ws=True, rp=True) rawDifferenceList = [(aimPos[0]-rootPos[0]),(aimPos[1]-rootPos[1]),(aimPos[2]-rootPos[2])] absDifferenceList = [abs(rawDifferenceList[0]),abs(rawDifferenceList[1]),abs(rawDifferenceList[2])] biggestNumberIndex = absDifferenceList.index(max(absDifferenceList)) direction = axis.get(biggestNumberIndex) if rawDifferenceList[biggestNumberIndex] < 0: return ('%s%s' %('-',direction)) else: return (direction)
def makeGem(size): #import gem if not cmds.objExists('gem'): cmds.file("gem.ma", i=True) cmds.select('gem') cmds.xform(s=(size,size,size))
def updateRot(indAnt, vel, curTri, newTri, comPos, nextLeft, extForceFrame): """Update the rotation of the character """ if np.linalg.norm(extForceFrame) != 0: diff = np.average(newTri, axis=0) - np.average(curTri, axis=0) else: diff = np.average(newTri, axis=0) - comPos velNorm = np.linalg.norm(vel) diffNorm = np.linalg.norm(diff) newVel = velNorm*diff/diffNorm # normal is normalised triN = triangleNorm(curTri, nextLeft) velOnNormal = np.dot(newVel, triN)*triN velOnTri = newVel - velOnNormal # scale matrix for the ant model scaleMatrix = np.matrix([[0.4, 0, 0, 0], [0, 0.4, 0, 0], [0, 0, 0.4, 0], [0, 0, 0, 1]]) rotMat = up.constructRotMat(triN, velOnTri, full=True) mat = np.asarray(rotMat*scaleMatrix).flatten() cmds.xform("antRig"+str(indAnt), m=mat) cmds.setKeyframe('antRig'+str(indAnt), at='rotate') return newVel
def _createAimLocator(self, position = [0,0,0], color = None): #create aim locator and move into position aimLocator = \ cmds.spaceLocator(n = '%s_aim_%s' % (self.name(), common.LOCATOR))[0] aimZero = \ cmds.createNode('transform', n = aimLocator.replace(common.LOCATOR, common.ZERO)) cmds.parent(aimLocator, aimZero) cmds.xform(aimZero, ws = True, t = position) #create display line between aim locator and start joint displayLine = control.displayLine(self.startJoint, aimLocator) cmds.parent(displayLine, self.guidesGrp) #set color on aim control common.setColor(aimLocator, color) #parent locator to zero group cmds.parent(aimZero, self.masterGuide) return aimLocator
def match(self, *args): characterContainer = self.characterNamespaceOnly + ':character_container' blueprintContainer = self.blueprintNamespace + ':module_container' moduleContainer = self.blueprintNamespace + ':' + self.moduleNamespace + ':module_container' containers = [characterContainer, blueprintContainer, moduleContainer] for c in containers: cmds.lockNode(c, lock=False, lockUnpublished=False) joints = utils.findJointChain(self.blueprintNamespace+':' + self.moduleNamespace+':joints_grp') blueprintJoints = utils.findJointChain(self.blueprintNamespace+':blueprint_joints_grp') ikHandleControl = self.blueprintNamespace + ':' + self.moduleNamespace + ':ikHandleControl' cmds.setAttr(ikHandleControl + '.stretchiness',1) endPos = cmds.xform(blueprintJoints[len(blueprintJoints)-1], q=1, worldSpace=True, translation=True) cmds.xform(ikHandleControl, worldSpace=True, absolute=True, translation=endPos) joints.pop(0) blueprintJoints.pop(0) utils.matchTwistAngle(ikHandleControl + '.twist', joints, blueprintJoints) for c in containers: cmds.lockNode(c, lock=True, lockUnpublished=True)
def surfaceFromNodes(nodes, name='jntsSrf', upAxis=0, doubleEndPoints=False): """ Create a 2-degree nurbs surface from the position of a list of node (generally, the IK controls) @param nodes: controls that will dictate the CV positions @type nodes: list of strings @param name: the name of the surface @type name: str @param upAxis: the direction of the width of the surface @type upAxis: int representing x(0), y(1) or z(2) """ inPos = [0,0,0] outPos = [0,0,0] inPos[upAxis] = -1 outPos[upAxis] = 1 crv1 = curveFromNodes(nodes, doubleEndPoints=doubleEndPoints) crv2 = curveFromNodes(nodes, doubleEndPoints=doubleEndPoints) MC.xform(crv1, t=outPos) MC.xform(crv2, t=inPos) srf = MC.loft(crv1, crv2, u=1, c=0, ch=0, ar=1, d=1, ss=1, rn=0, po=0, rsn=True)[0] srf = MC.rename(srf, name) MC.delete(crv1, crv2) return srf
def createIKCtrlsOnJnts(ikCrv, parentCtrl, size=1): ikCVNum = ll.getCurveCVCount(ikCrv) prev=parentCtrl for i in range(1, ikCVNum): clus = mc.cluster('%s.cv[%d]'%(ikCrv, i), n=parentCtrl.replace('masterctrl','ikClus%d')%i) cvPos = mc.xform('%s.cv[%d]'%(ikCrv, i), q=1, ws=1, t=1) mc.select(parentCtrl) meval('wireShape("plus")') ikCtrl = mc.rename(masterCtrl.replace('masterctrl','ikCtrl%d'%i)) mc.xform(ikCtrl, t=cvPos, ws=1) mc.scale(size, size, size, ikCtrl, ocp=1) mc.makeIdentity(ikCtrl, a=1, s=1) mc.parent(ikCtrl, parentCtrl) lsZeroOut(ikCtrl) ctrlPR = lsZeroOut(ikCtrl, 'PR') mc.addAttr(ikCtrl, ln='SPACE', at='bool', k=1) mc.setAttr(ikCtrl+'.SPACE', l=1) mc.addAttr(ikCtrl, ln='parent', at='float', dv=0, min=0, max=1, k=1) mc.addAttr(ikCtrl, ln='master', at='float', dv=1, min=0, max=1, k=1) mc.addAttr(ikCtrl, ln='world', at='float', dv=0, min=0, max=1, k=1) mc.parentConstraint(ikCtrl, clus) cons = mc.parentConstraint(prev, parentCtrl, ctrlPR, mo=1)[0] wal = mc.parentConstraint(cons, q=1, wal=1) if len(wal) > 1: mc.connectAttr(ikCtrl+'.parent', '%s.%s'%(cons, wal[0]), f=1) mc.connectAttr(ikCtrl+'.master', '%s.%s'%(cons, wal[1]), f=1) prev=ikCtrl
def _createParentMaster(obj, translation=True, rotation=True): '''Crea i gruppi necessari per utilizzare il parent master.''' # creo il parent handle e lo snap group dell'oggetto (aventi stesso pivot) # un file referenziato genera eccezione if cmds.referenceQuery(obj, inr=True) and (not ALLOW_REFERENCE_ROOT or cmds.listRelatives(obj, p=True)): sys.stdout.write('Read-only hierarchy detected\n') msg = 'Are you working with referenced files?\n\nZVPM can\'t group "%s" because it\'s in a read-only hierarchy.\n\n\nDo the following:\n\n- Open the referenced file.\n- Select this object, right-click on "Attach objects" button and "Create parent groups".\n- Save the file.' % obj cmds.confirmDialog(title='Referenced file - ZV Parent Master', message=msg) return False piv = cmds.xform(obj, q=True, rp=True, ws=True) cmds.group(obj, n=_getSnapGroup(obj)) cmds.xform(_getSnapGroup(obj), piv=piv, ws=True) ph = cmds.group(_getSnapGroup(obj), n=_getParentHandle(obj)) cmds.xform(_getParentHandle(obj), piv=piv, ws=True) # locca gli attributi non diponibili e quelli non richiesti ts = set(['tx', 'ty', 'tz']) rs = set(['rx', 'ry', 'rz']) availAttrs = set(cmds.listAttr(obj, k=True, u=True, sn=True) or []) attrsToLock = (ts | rs) - availAttrs if not translation: attrsToLock |= ts if not rotation: attrsToLock |= rs for attr in attrsToLock: cmds.setAttr('%s.%s' % (ph, attr), lock=True) return True
def freezeCenterPivot(): """ freeze transfoms, delete history and center pivot """ cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0) cmds.delete(ch=True) cmds.xform(cp=True)
def ttmAlign(self,debugflag=False): if debugflag: print "%së¥%sTransform •ë ¬." % (self.objs[1],self.objs[0]) RefTm=cmds.xform(self.objs[0],query=True,ws=True,matrix=True) TargetTm=cmds.xform(self.objs[1],query=True,ws=True,matrix=True) Tflags =self.isChecked(ATranslate) RefSRCTm = om.MMatrix() RefSRCTm.setToIdentity() TargetSRCTm = om.MMatrix() TargetSRCTm.setToIdentity() om.MScriptUtil.createMatrixFromList( RefTm, RefSRCTm) om.MScriptUtil.createMatrixFromList( TargetTm, TargetSRCTm) x=self.Ori_RefTm[12] y=self.Ori_RefTm[13] z=self.Ori_RefTm[14] if Tflags[0]: x=TargetSRCTm(0,12) if Tflags[1]: y=TargetSRCTm(0,13) if Tflags[2]: z=TargetSRCTm(0,14) outTm=[RefTm[0],RefTm[1],RefTm[2],0,RefTm[4],RefTm[5],RefTm[6],0,RefTm[8],RefTm[9],RefTm[10],0,x,y,z,1] cmds.xform(self.objs[0],ws=True,m=outTm) self.Result_TM=outTm
def alignComponentsBetweenAnchors(anchorA, anchorB, components, axis=("X", "Y", "Z")): """ Aligns given Components between the two anchors. :param anchorA: Anchor a. :type anchorA: str :param anchorB: Anchor b. :type anchorB: str :param components: Components to align. :type components: list :param axis: Collapse axis. :type axis: tuple """ vertices = cmds.ls(cmds.polyListComponentConversion(components, toVertex=True), fl=True) pointA = cmds.xform(anchorA, q=True, t=True, ws=True) pointB = cmds.xform(anchorB, q=True, t=True, ws=True) vectorA = normalize([pointB_ - pointA_ for pointA_, pointB_ in zip(pointA, pointB)]) for vertex in vertices: pointC = cmds.xform(vertex, q=True, ws=True, t=True) vectorB = [pointC_ - pointA_ for pointA_, pointC_ in zip(pointA, pointC)] mVectorA = getMVector(vectorA) mVectorB = getMVector(vectorB) dot = mVectorB * mVectorA mVectorA *= dot offset = mVectorB - mVectorA xValue = "X" in axis and - offset.x or 0 yValue = "Y" in axis and - offset.y or 0 zValue = "Z" in axis and - offset.z or 0 cmds.xform(vertex, ws=True, r=True, t=(xValue, yValue, zValue))
def curveBetweenNodes(start=None, end=None, name=''): ''' Makes a degree 3 nurbs curve with 4 cvs between two nodes ''' # Validation of args startPos, endPos = None, None if not start or not end and len( cmds.ls( sl=True ) ) == 2: startPos = cmds.xform( cmds.ls( sl=True )[0], translation=True, query=True, ws=True ) endPos = cmds.xform( cmds.ls( sl=True )[1], translation=True, query=True, ws=True ) else: if type( start ) == type( 'hello' ) or type( start ) == type( u'hello' ): startPos = cmds.xform( str(start), translation=True, query=True, ws=True ) else: startPos = start if type( end ) == type( 'hello' ) or type( end ) == type( u'hello' ): endPos = cmds.xform( str(end), translation=True, query=True, ws=True ) else: endPos = end if not startPos or not endPos: return common.showDialog( 'Argument Error', 'Cannot determine start and end points' ) points = common.pointsAlongVector(start=startPos, end=endPos, divisions=3) # create the curve crv = cmds.curve(p=points, k=[0,0,0,1,1,1], name='%s_crv' % name) return crv
def rebuild(self): ''' Rebuild the lattice deformer from the recorded deformerData ''' # Rebuild deformer ffd = mc.lattice(self.getMemberList(),n=self.deformerName) lattice = ffd[0] latticeShape = ffd[1] latticeBase = ffd[2] # Set Deformer Attributes mc.setAttr(lattice+'.local',self.local) mc.setAttr(lattice+'.outsideLattice',self.outside) mc.setAttr(lattice+'.outsideFalloffDist',self.falloff) mc.setAttr(lattice+'.usePartialResolution',self.resolution) mc.setAttr(lattice+'.partialResolution',self.partialResolution) mc.setAttr(lattice+'.freezeGeometry',self.freeze) mc.setAttr(lattice+'.localInfluenceS',self.localInfluenceS) mc.setAttr(lattice+'.localInfluenceT',self.localInfluenceT) mc.setAttr(lattice+'.localInfluenceU',self.localInfluenceU) # Set Lattice Shape Attributes mc.setAttr(latticeShape+'.sDivisions',self.sDivisions) mc.setAttr(latticeShape+'.tDivisions',self.tDivisions) mc.setAttr(latticeShape+'.uDivisions',self.uDivisions) # Restore World Transform Data mc.xform(lattice,ws=True,m=self.latticeXform) mc.xform(latticeBase,ws=True,m=self.baseXform) # Return result return lattice
def setRestCurve( startCurves ): restCurves = [] index = 0 for startCurve in startCurves: follicle = cmds.listConnections( startCurve+'.wm', type='follicle', shapes=1 )[0] if cmds.listConnections( follicle+'.restPosition', s=1, d=0 ): continue startShape = cmds.listConnections( follicle+'.startPosition', s=1, d=0, shapes=1 )[0] rebuildCurve= cmds.listConnections( startShape+'.create', type='rebuildCurve' )[0] crvShape = cmds.createNode( 'nurbsCurve' ) cmds.connectAttr( rebuildCurve+'.outputCurve', crvShape+'.create' ) cmds.connectAttr( crvShape+'.worldSpace', follicle+'.restPosition' ) cmds.setAttr( crvShape+'.io', 1 ) crv = cmds.listRelatives( crvShape, p=1 )[0] crv = cmds.rename( crv, 'restCurve_%03d' % index ) startMtx = cmds.getAttr( crv+'.wm' ) cmds.xform( crv, ws=1, matrix= startMtx ) restCurves.append( crv ) index += 1 cmds.group( restCurves, n='restCurveGrps' )
def apply( self, nodes=None, applySettings=None, worldSpace=False ): if nodes is None: nodes = self._nodeAttrDict.iterkeys() for node in nodes: if node in self._nodeAttrDict: for attr, value in self._nodeAttrDict[ node ].iteritems(): attrpath = '%s.%s' % (node, attr) if objExists( attrpath ): setAttr( attrpath, value ) if worldSpace: if node in self._nodeWorldDict: if cmd.objectType( node, isAType='transform' ): pos, rot, rotateOrder = self._nodeWorldDict[node] move( pos[0], pos[1], pos[2], node, ws=True, a=True, rpr=True ) roAttrpath = '%s.ro' % node initialRotateOrder = getAttr( roAttrpath ) rotateOrderMatches = initialRotateOrder == rotateOrder if rotateOrderMatches: rotate( rot[0], rot[1], rot[2], node, ws=True, a=True ) else: setAttr( roAttrpath, rotateOrder ) rotate( rot[0], rot[1], rot[2], node, ws=True, a=True ) xform( node, ro=constants.ROTATE_ORDER_STRS[ initialRotateOrder ], p=True )
def bakeManualRotateDelta( src, ctrl, presetStr ): ''' When you need to apply motion from a skeleton that is completely different from a skeleton driven by the rig you're working with (transferring motion from old assets to newer assets for example) you can manually align the control to the joint and then use this function to generate offset rotations and bake a post trace cmd. ''' srcInvMat = Matrix( getAttr( '%s.worldInverseMatrix' % src ) ) ctrlMat = Matrix( getAttr( '%s.worldMatrix' % ctrl ) ) #generate the offset matrix as mat_o = ctrlMat * srcInvMat #now figure out the euler rotations for the offset ro = getAttr( '%s.ro' % ctrl ) rotDelta = constants.MATRIX_ROTATION_ORDER_CONVERSIONS_TO[ ro ]( mat_o, True ) #now get the positional delta posDelta = Vector( xform( src, q=True, ws=True, rp=True ) ) - Vector( xform( ctrl, q=True, ws=True, rp=True ) ) posDelta *= -1 ctrlParentInvMat = Matrix( getAttr( '%s.parentInverseMatrix' % ctrl ) ) posDelta = posDelta * ctrlParentInvMat #construct a list to use for the format str formatArgs = tuple( rotDelta ) + tuple( posDelta ) #build the post trace cmd str PostTraceNode( ctrl ).setCmd( presetStr % formatArgs ) return rotDelta
def mmMirrorJoint( *args ): sels= cmds.ls( sl=1 ) for sel in sels: srcStr = '' trgStr = '' if sel.find( '_L_' ) != -1: other = sel.replace( '_L_', '_R_' ) srcStr = '_L_' trgStr = '_R_' elif sel.find( '_R_' ) != -1: other = sel.replace( '_R_', '_L_' ) srcStr = '_R_' trgStr = '_L_' else: continue if not cmds.objExists( other ): cmds.mirrorJoint( sel, mirrorYZ=1, mirrorBehavior=1, searchReplace=["_L_", "_R_"] ) else: mtxTop = cmds.getAttr( sel+'.wm' ) mtxTop[1] *= -1; mtxTop[ 2] *= -1 mtxTop[5] *= -1; mtxTop[ 6] *= -1 mtxTop[9] *= -1; mtxTop[10] *= -1 mtxTop[12] *= -1 cmds.xform( other, ws=1, matrix=mtxTop ) children = cmds.listRelatives( sel, c=1, ad=1 ) for child in children: mtx = cmds.getAttr( child+'.m' ) mtx[12] *= -1; mtx[13] *= -1; mtx[14] *= -1 otherChild = child.replace( srcStr, trgStr ) cmds.xform( otherChild, matrix=mtx )
def mmInsertJoint( *args ): def normalize(vector_value): length = math.sqrt(vector_value[0]**2 + vector_value[1]**2 + vector_value[2]**2) x = vector_value[0]/length y = vector_value[1]/length z = vector_value[2]/length result = [x, y, z] return result num_joints =input(10) num_joints = num_joints+1 joint_list = cmds.ls(sl=True) for r in joint_list: first_joint_trans = cmds.xform(r, q=True, ws=True, t=True) first_joint_ori = cmds.xform(r, q=True, ws=True, ro=True) end_joint = cmds.listRelatives(r, f=True, c=True) end_joint_rename=cmds.rename(end_joint[0], "end_to_delete______yeah") end_joint_trans = cmds.xform(end_joint_rename, q=True, ws=True, t=True) end_joint_ori = cmds.xform(end_joint_rename, q=True, ws=True, ro=True) between_vector = [-(first_joint_trans[0]-end_joint_trans[0]),-(first_joint_trans[1]-end_joint_trans[1]),-(first_joint_trans[2]-end_joint_trans[2])] vector_length = mel.eval(("mag(<<"+str(between_vector[0])+","+str(between_vector[1])+","+str(between_vector[2])+">>)")) vector_normalize = normalize(between_vector) for i in range(num_joints): vector_to_add = [(vector_normalize[0]*((vector_length/num_joints)*((num_joints-float(i))))),(vector_normalize[1]*((vector_length/num_joints)*((num_joints-float(i))))),(vector_normalize[2]*((vector_length/num_joints)*((num_joints-float(i)))))] inset_joint = cmds.insertJoint(r) cmds.joint(inset_joint, e=True, co=True, o=(0,0,0), p=((first_joint_trans[0]+vector_to_add[0]), (first_joint_trans[1]+vector_to_add[1]), (first_joint_trans[2]+vector_to_add[2]))) cmds.delete(end_joint_rename)
def buildGuideSpline(self): cPoints = [] for marker in self.totalMarkerList: markerPos = cmds.xform(marker.getName(), t=True, q=True, ws=True) cPoints.append(markerPos) nameStart = nameBase(self.totalMarkerList[0].getName(), self.searchString, "loc", "cv") guideSplineName = nameStart + "ribbonGuideSpline" self.guideSpline = cmds.curve(editPoint = cPoints, degree=3, name=guideSplineName) #Need to add Naming Convention here self.tempGuideParts.append(self.guideSpline) for i, marker in enumerate(self.totalMarkerList): locPos = cmds.xform(marker.getName(), t=True, q=True, ws=True) newPara = cmds.closestPointOnCurve(self.guideSpline, ip=locPos, paramU=True) newParaVal = cmds.getAttr(newPara + ".paramU") cmds.delete(newPara) # print "new ParaVal : ", newParaVal ##Now Create a new Locator and add it to the precise parameter position nameStart = nameRebuild(marker.getName(), self.searchString, "loc", "loc",nameAddition = "tempRibbonGuide") newAlignedLoc = cmds.spaceLocator(name = nameStart) # guideSplineName = nameStart + "ribbonGuideSpline" #Need naming convention self.tempGuideParts.append(newAlignedLoc[0]) mPath = cmds.pathAnimation(newAlignedLoc, follow=True, c=self.guideSpline) uAnimNode = cmds.listConnections(mPath + ".uValue", source=True) cmds.delete(uAnimNode) cmds.setAttr(mPath + ".uValue", newParaVal) self.totalMarkerList[i].setAlignedMarker(newAlignedLoc[0]) self.totalMarkerList[i].setUParameter(newParaVal)
def ui_on_BTN_create_clicked(self, *args): cube = m.polyCube(ch=False)[0] xPosUI = self.ui_FLTFLDGRP_xPos.getValue()[0] xNegUI = self.ui_FLTFLDGRP_xNeg.getValue()[0] yPosUI = self.ui_FLTFLDGRP_yPos.getValue()[0] yNegUI = self.ui_FLTFLDGRP_yNeg.getValue()[0] zPosUI = self.ui_FLTFLDGRP_zPos.getValue()[0] zNegUI = self.ui_FLTFLDGRP_zNeg.getValue()[0] xPos = max(xPosUI, xNegUI) xNeg = min(xPosUI, xNegUI) yPos = max(yPosUI, yNegUI) yNeg = min(yPosUI, yNegUI) zPos = max(zPosUI, zNegUI) zNeg = min(zPosUI, zNegUI) m.move(xPos, cube + faceMapping['xPos'], worldSpaceDistance=True, x=True) m.move(xNeg, cube + faceMapping['xNeg'], worldSpaceDistance=True, x=True) m.move(yPos, cube + faceMapping['yPos'], worldSpaceDistance=True, y=True) m.move(yNeg, cube + faceMapping['yNeg'], worldSpaceDistance=True, y=True) m.move(zPos, cube + faceMapping['zPos'], worldSpaceDistance=True, z=True) m.move(zNeg, cube + faceMapping['zNeg'], worldSpaceDistance=True, z=True) m.xform(cube, cp=True) m.rename(cube, BBOX_NAME)
def extractGeo(obj): ''' Extract the selected faces. ''' # Grab elements from the textScrollList. orgSelected = cmds.textScrollList("mecFEXTSL", q=True, ai=True) curSel = obj faces = [] for sel in orgSelected: temp = sel.split(".") #print( curSel[0] + "." + temp[-1] ) faces.append( curSel + "." + temp[-1] ) cmds.select(faces, r=True) mel.eval('doMenuComponentSelection("%s", "facet")' %curSel) cmds.ExtractFace() extSel = cmds.ls(sl=True) cmds.delete(extSel[0]) cmds.delete(ch=1) # Grab transform values from the interface. tx = cmds.floatField("mecFEXTX", q=True, v=True) ty = cmds.floatField("mecFEXTY", q=True, v=True) tz = cmds.floatField("mecFEXTZ", q=True, v=True) # Center Pivot and move the geometry cmds.xform(extSel[1], cp=True) cmds.xform(extSel[1], t=[tx,ty,tz])
def centerPivot(self, item): cmds.xform(item, centerPivots=True)
import maya.cmds as mc ikfkSwitch = mc.getAttr('Switch.IK_FK') if ikfkSwitch == 1: mc.select('FK3_joint') wp= mc.xform(q=True,ws=True,t=True) wr= mc.xform(q=True,ws=True,ro=True) mc.select('IKhand') mc.xform(ws=True,t=(wp[0],wp[1],wp[2])) mc.xform(ws=True,ro=(wr[0],wr[1],wr[2])) mc.select('fakePole') fpt=mc.xform(q=True,ws=True,t=True) fpr=mc.xform(q=True,ws=True,ro=True) mc.select('Pole') mc.xform(ws=True,t=(fpt[0],fpt[1],fpt[2])) mc.xform(ws=True,ro=(fpr[0],fpr[1],fpr[2])) ikfkSwitch = mc.getAttr('Switch.IK_FK') if ikfkSwitch == 1 : mc.select('FK3_joint') wp= mc.xform(q=True,ws=True,t=True) wr= mc.xform(q=True,ws=True,ro=True) mc.select('IKhand') mc.xform(ws=True,t=(wp[0],wp[1],wp[2])) mc.xform(ws=True,ro=(wr[0],wr[1],wr[2])) mc.select('fakePole')
import maya.cmds as cmds # cube[transform, object] cube = cmds.polyCube() print(cube) # Query the width cube_width = cmds.polyCube(cube[1], query=True, width=True) # Create a sph based in the width's cube sph = cmds.polySphere(radius=cube_width / 2) # Transforming objets # Move, Rotate, Scale cmds.move(1, 0, 0, cube[0], localSpace=True) cmds.rotate(0, 45, 0, cube[0], relative=True) cmds.scale(2, 2, 3, cube[0]) # xform - Obtenemos atributos de transformación cube_t = cmds.xform(cube[0], query=True, translation=True) cmds.xform(sph[0], translation=cube_t) cube_bb = cmds.xform(cube[0], query=True, bb=True) print cube_bb
def softModDeformerDo(*args): """creates and sets up the softmod deformer setup""" check = cmds.checkBoxGrp(widgets["checkCBG"], q=True, v1=True) increment = cmds.checkBoxGrp(widgets["incrCBG"], q=True, v1=True) toParent = cmds.checkBoxGrp(widgets["parentCBG"], q=True, v1=True) #get deformer name defName = cmds.textFieldGrp(widgets["smdTFG"], tx=True, q=True) scaleFactor = cmds.floatFieldGrp(widgets["scaleFFG"], q=True, v1=True) if not (cmds.objExists(defName)): # choose a vert (for example) vertsRaw = cmds.ls(sl=True, fl=True) if vertsRaw == []: cmds.warning("Must select at least one vertex") else: if (cmds.checkBoxGrp(widgets["firstVertCBG"], q=True, v1=True)): vertex = [vertsRaw[0]] else: vertex = vertsRaw obj = vertex[0].partition(".")[0] #get vert position then select the geo positions = [] for vert in vertex: positions.append(cmds.pointPosition(vert)) numVerts = len(positions) x,y,z = 0,0,0 for i in range(numVerts): x += positions[i][0] y += positions[i][1] z += positions[i][2] vertPos = [(x/numVerts), (y/numVerts), (z/numVerts)] #check if there are other deformers on the obj if check: deformers = [] deformers = getDeformers(obj) if deformers: cmds.confirmDialog( title='Deformer Alert!', message='Found some deformers on %s.\nYou may want to put the softmod\n early in the input list'%obj, button=['OK'], defaultButton='OK', cancelButton='OK', dismissString='OK' ) cmds.select(obj) # create a soft mod at vert position (avg) softMod = defName softModOrig = cmds.softMod(relative=False, falloffCenter = vertPos, falloffRadius=5.0, n=softMod)[0] cmds.rename(softModOrig, softMod) softModXform = cmds.listConnections(softModOrig, type="transform")[0] # create a control at the position of the softmod control = defName + "_CTRL" cmds.curve(n=control, d=1, p=[[0.0, 1.0, 0.0], [-0.382683, 0.92388000000000003, 0.0], [-0.70710700000000004, 0.70710700000000004, 0.0], [-0.92388000000000003, 0.382683, 0.0], [-1.0, 0.0, 0.0], [-0.92388000000000003, -0.382683, 0.0], [-0.70710700000000004, -0.70710700000000004, 0.0], [-0.382683, -0.92388000000000003, 0.0], [0.0, -1.0, 0.0], [0.382683, -0.92388000000000003, 0.0], [0.70710700000000004, -0.70710700000000004, 0.0], [0.92388000000000003, -0.382683, 0.0], [1.0, 0.0, 0.0], [0.92388000000000003, 0.382683, 0.0], [0.70710700000000004, 0.70710700000000004, 0.0], [0.382683, 0.92388000000000003, 0.0], [0.0, 1.0, 0.0], [0.0, 0.92388000000000003, 0.382683], [0.0, 0.70710700000000004, 0.70710700000000004], [0.0, 0.382683, 0.92388000000000003], [0.0, 0.0, 1.0], [0.0, -0.382683, 0.92388000000000003], [0.0, -0.70710700000000004, 0.70710700000000004], [0.0, -0.92388000000000003, 0.382683], [0.0, -1.0, 0.0], [0.0, -0.92388000000000003, -0.382683], [0.0, -0.70710700000000004, -0.70710700000000004], [0.0, -0.382683, -0.92388000000000003], [0.0, 0.0, -1.0], [0.0, 0.382683, -0.92388000000000003], [0.0, 0.70710700000000004, -0.70710700000000004], [0.0, 0.92388000000000003, -0.382683], [0.0, 1.0, 0.0], [-0.382683, 0.92388000000000003, 0.0], [-0.70710700000000004, 0.70710700000000004, 0.0], [-0.92388000000000003, 0.382683, 0.0], [-1.0, 0.0, 0.0], [-0.92388000000000003, 0.0, 0.382683], [-0.70710700000000004, 0.0, 0.70710700000000004], [-0.382683, 0.0, 0.92388000000000003], [0.0, 0.0, 1.0], [0.382683, 0.0, 0.92388000000000003], [0.70710700000000004, 0.0, 0.70710700000000004], [0.92388000000000003, 0.0, 0.382683], [1.0, 0.0, 0.0], [0.92388000000000003, 0.0, -0.382683], [0.70710700000000004, 0.0, -0.70710700000000004], [0.382683, 0.0, -0.92388000000000003], [0.0, 0.0, -1.0], [-0.382683, 0.0, -0.92388000000000003], [-0.70710700000000004, 0.0, -0.70710700000000004], [-0.92388000000000003, 0.0, -0.382683], [-1.0, 0.0, 0.0]]) cmds.select(cl=True) #TO-DO----------------pull this out into separate function?? Args would be object and color shapes = cmds.listRelatives(control, shapes=True) for shape in shapes: cmds.setAttr("%s.overrideEnabled"%shape, 1) cmds.setAttr("%s.overrideColor"%shape, 14) controlGrp = cmds.group(control, n="%s_GRP"%control) cmds.xform(controlGrp, ws=True, t=vertPos) # connect the pos, rot, scale of the control to the softModHandle cmds.connectAttr("%s.translate"%control, "%s.translate"%softModXform) cmds.connectAttr("%s.rotate"%control, "%s.rotate"%softModXform) cmds.connectAttr("%s.scale"%control, "%s.scale"%softModXform) cmds.addAttr(control, ln="__XTRA__", at="enum", k=True) cmds.setAttr("%s.__XTRA__"%control, l=True) # cmds.addAttr(control, ln="centerCtrlVis", at="bool", min=0, max=1, k=True, dv=0) cmds.addAttr(control, ln="envelope", at="float", min=0, max=1, k=True, dv=1) cmds.addAttr(control, ln="falloff", at="float", min=0, max=100, k=True, dv=5) # cmds.addAttr(control, ln="centerX", at="float", dv=0, k=True) # cmds.addAttr(control, ln="centerY", at="float", dv=0, k=True) # cmds.addAttr(control, ln="centerZ", at="float", dv=0, k=True) # connect that attr to the softmod falloff radius cmds.connectAttr("%s.envelope"%control, "%s.envelope"%softMod) cmds.connectAttr("%s.falloff"%control, "%s.falloffRadius"%softMod) # inherit transforms on softModHandle are "off" cmds.setAttr("%s.inheritsTransform"%softModXform, 0) # centerName = defName + "_center_CTRL" # #create secondary (area of influence) control here # centerCtrl = cmds.curve(n=centerName, d=1, p=[[-1.137096, -1.137096, 1.137096], [-1.137096, 1.137096, 1.137096], [1.137096, 1.137096, 1.137096], [1.137096, -1.137096, 1.137096], [-1.137096, -1.137096, 1.137096], [-1.137096, -1.137096, -1.137096], [-1.137096, 1.137096, -1.137096], [-1.137096, 1.137096, 1.137096], [1.137096, 1.137096, 1.137096], [1.137096, 1.137096, -1.137096], [1.137096, -1.137096, -1.137096], [1.137096, -1.137096, 1.137096], [1.137096, -1.137096, -1.137096], [-1.137096, -1.137096, -1.137096], [-1.137096, 1.137096, -1.137096], [1.137096, 1.137096, -1.137096]]) # centerCtrlSh = cmds.listRelatives(centerCtrl, s=True) # for shape in centerCtrlSh: # #turn on overrides # cmds.setAttr("%s.overrideEnabled"%shape, 1) # cmds.connectAttr("%s.centerCtrlVis"%control, "%s.overrideVisibility"%shape) # cmds.setAttr("%s.overrideColor"%shape, 13) # centerGrp = cmds.group(centerCtrl, n="%s_GRP"%centerName) # #turn off scale and rotation for the center control # cmds.setAttr("%s.rotate"%centerCtrl, k=False, l=True) # cmds.setAttr("%s.scale"%centerCtrl, k=False, l=True) # cmds.setAttr("%s.visibility"%centerCtrl, k=False, l=True) # #move the group to the location # cmds.xform(centerGrp, ws=True, t=vertPos) # plusName = defName + "_plus" # plusNode = cmds.shadingNode("plusMinusAverage", asUtility=True, n=plusName) # cmds.connectAttr("%s.translate"%centerGrp, "%s.input3D[0]"%plusNode, f=True) # cmds.connectAttr("%s.translate"%centerCtrl, "%s.input3D[1]"%plusNode, f=True) # cmds.connectAttr("%s.output3D"%plusNode, "%s.falloffCenter"%softMod, f=True) #hide the softmod cmds.setAttr("%s.visibility"%softModXform, 0) #group the group and the softmod xform # defGroup = cmds.group(softModXform, controlGrp, n=(defName + "_deform_GRP")) defGroup = cmds.group(empty=True, n=(defName + "_deform_GRP")) cmds.xform(defGroup, ws=True, t=vertPos) cmds.parent(softModXform, controlGrp, defGroup) #parent the softmod under the centerCtrl # cmds.parent(defGroup, centerCtrl) #parent that group under the obj? if toParent: cmds.parent(defGroup, obj) # #connect group translate to plus node # plusName = defName + "_plus" # plusNode = cmds.shadingNode("plusMinusAverage", asUtility=True, n=plusName) # cmds.connectAttr("%s.translate"%defGroup, "%s.input3D[0]"%plusNode) # #connect to falloff center # cmds.connectAttr("%s.centerX"%control, "%s.input3D[1].input3Dx"%plusNode) # cmds.connectAttr("%s.centerY"%control, "%s.input3D[1].input3Dy"%plusNode) # cmds.connectAttr("%s.centerZ"%control, "%s.input3D[1].input3Dz"%plusNode) # cmds.connectAttr("%s.output3D"%plusNode, "%s.falloffCenter"%softMod) #scale the controls scaleCtrl([control], scaleFactor) #increment name if increment == 1: print "trying to rename" split = defName.rpartition("_") end = split[2] isInt = integerTest(end) if isInt: newNum = int(end) + 1 newName = "%s%s%02d"%(split[0], split[1], newNum) cmds.textFieldGrp(widgets["smdTFG"], tx=newName, e=True) else: newName = "%s_01"%defName cmds.textFieldGrp(widgets["smdTFG"], tx=newName, e=True) #select the control to wrap up cmds.select(control) else: cmds.warning("An object of this name, %s, already exists! Choose a new name!"%defName)
def softSelectDef(*args): """calls on getSoftSelection() to get the weights of the softSelect and then puts it all under a cluster and a control""" ssDefName = cmds.textFieldGrp(widgets["ssdTFG"], q=True, tx=True) if not cmds.objExists("%s_CLS"%ssDefName): ssScale = cmds.floatFieldGrp(widgets["ssScaleFFG"], q=True, v1=True) ssIncrement = cmds.checkBoxGrp(widgets["ssIncrCBG"], q=True, v1=True) ssCheck = cmds.checkBoxGrp(widgets["ssCheckCBG"], q=True, v1=True) ssParent = cmds.checkBoxGrp(widgets["ssParentCBG"], q=True, v1=True) ssCPOM = cmds.checkBoxGrp(widgets["ssCPOMCBG"], q=True, v1=True) #this gets the verts selected and their respective weights in the soft selection elements,weights = getSoftSelection() #get transform and mesh xform = elements[0].partition(".")[0] #maybe here I should check for "orig", etc and exclude them? mesh = cmds.listRelatives(xform, f=True, s=True)[0] #check if there are other deformers on the obj if ssCheck: deformers = [] deformers = getDeformers(xform) if deformers: cmds.confirmDialog( title='Deformer Alert!', message='Found some deformers on %s.\nYou may want to put the softmod\n early in the input list'%xform, button=['OK'], defaultButton='OK', cancelButton='OK', dismissString='OK' ) #select each of the points from the list and create a cluster cmds.select(cl=True) for elem in elements: cmds.select(elem, add=True) clus = cmds.cluster(relative=True, name="%s_CLS"%ssDefName) for i in range(len(elements)): element = elements[i] value = weights[i] #percent -v 0.5 thisCluster pSphere1.vtx[241] ; cmds.percent(clus[0], element, v=value, ) #get cluster position clusPos = cmds.xform(clus[1], ws=True, q=True, rp=True) if ssCPOM: #create closest point on mesh (surface?) node cpomNode = cmds.shadingNode("closestPointOnMesh", asUtility=True, n="%s_CPOM"%ssDefName) #-------------------- #inputs and outputs for "closestPointOnMesh": #inputs: #"mesh"->"inputMesh" (mesh node of transform) #"clusPos"->"inPosition" #"worldMatrix"(transform of object)->"inputMatrix" #outputs: #"position"->surfacepoint in space #"u"->parameter u #"v"->parameter v #"normal"->normal vector #--------------------- #connect up object to cpom cmds.connectAttr("%s.outMesh"%mesh, "%s.inMesh"%cpomNode) cmds.setAttr("%s.inPosition"%cpomNode, clusPos[0], clusPos[1], clusPos[2]) cmds.connectAttr("%s.worldMatrix"%mesh, "%s.inputMatrix"%cpomNode) cpomPos = cmds.getAttr("%s.position"%cpomNode)[0] #delete cpom node cmds.delete(cpomNode) else: cpomPos = avgElementPos(elements) #TO-DO----------------see if you can't orient things to the verts (maybe only with cpom?) #now create a control control = "%s_CTRL"%ssDefName cmds.curve(n=control, d=1, p=[[0.0, 1.0, 0.0], [-0.382683, 0.92388000000000003, 0.0], [-0.70710700000000004, 0.70710700000000004, 0.0], [-0.92388000000000003, 0.382683, 0.0], [-1.0, 0.0, 0.0], [-0.92388000000000003, -0.382683, 0.0], [-0.70710700000000004, -0.70710700000000004, 0.0], [-0.382683, -0.92388000000000003, 0.0], [0.0, -1.0, 0.0], [0.382683, -0.92388000000000003, 0.0], [0.70710700000000004, -0.70710700000000004, 0.0], [0.92388000000000003, -0.382683, 0.0], [1.0, 0.0, 0.0], [0.92388000000000003, 0.382683, 0.0], [0.70710700000000004, 0.70710700000000004, 0.0], [0.382683, 0.92388000000000003, 0.0], [0.0, 1.0, 0.0], [0.0, 0.92388000000000003, 0.382683], [0.0, 0.70710700000000004, 0.70710700000000004], [0.0, 0.382683, 0.92388000000000003], [0.0, 0.0, 1.0], [0.0, -0.382683, 0.92388000000000003], [0.0, -0.70710700000000004, 0.70710700000000004], [0.0, -0.92388000000000003, 0.382683], [0.0, -1.0, 0.0], [0.0, -0.92388000000000003, -0.382683], [0.0, -0.70710700000000004, -0.70710700000000004], [0.0, -0.382683, -0.92388000000000003], [0.0, 0.0, -1.0], [0.0, 0.382683, -0.92388000000000003], [0.0, 0.70710700000000004, -0.70710700000000004], [0.0, 0.92388000000000003, -0.382683], [0.0, 1.0, 0.0], [-0.382683, 0.92388000000000003, 0.0], [-0.70710700000000004, 0.70710700000000004, 0.0], [-0.92388000000000003, 0.382683, 0.0], [-1.0, 0.0, 0.0], [-0.92388000000000003, 0.0, 0.382683], [-0.70710700000000004, 0.0, 0.70710700000000004], [-0.382683, 0.0, 0.92388000000000003], [0.0, 0.0, 1.0], [0.382683, 0.0, 0.92388000000000003], [0.70710700000000004, 0.0, 0.70710700000000004], [0.92388000000000003, 0.0, 0.382683], [1.0, 0.0, 0.0], [0.92388000000000003, 0.0, -0.382683], [0.70710700000000004, 0.0, -0.70710700000000004], [0.382683, 0.0, -0.92388000000000003], [0.0, 0.0, -1.0], [-0.382683, 0.0, -0.92388000000000003], [-0.70710700000000004, 0.0, -0.70710700000000004], [-0.92388000000000003, 0.0, -0.382683], [-1.0, 0.0, 0.0]]) cmds.select(cl=True) #scale the control scaleCtrl([control], ssScale) shapes = cmds.listRelatives(control, shapes=True) for shape in shapes: cmds.setAttr("%s.overrideEnabled"%shape, 1) cmds.setAttr("%s.overrideColor"%shape, 14) controlGrp = cmds.group(control, n="%s_GRP"%control) #put the control at the cpomPos cmds.xform(controlGrp, ws=True, t=(cpomPos[0],cpomPos[1],cpomPos[2])) clusHandShape = cmds.listRelatives(clus[1], s=True) # #move the cluster control to the control space (weighted node) cmds.cluster(clus[0], e=True, bs=1, wn=(control, control)) cmds.setAttr("%s.originX"%clusHandShape[0], 0.0) cmds.setAttr("%s.originY"%clusHandShape[0], 0.0) cmds.setAttr("%s.originZ"%clusHandShape[0], 0.0) cmds.delete(clus[1]) cmds.setAttr("%s.visibility"%clusHandShape[0], 0) if ssParent: cmds.parent(controlGrp, xform) cmds.select(control, r=True) if ssIncrement == 1: print "trying to rename" split = ssDefName.rpartition("_") end = split[2] isInt = integerTest(end) if isInt: newNum = int(end) + 1 newName = "%s%s%02d"%(split[0], split[1], newNum) cmds.textFieldGrp(widgets["ssdTFG"], tx=newName, e=True) else: newName = "%s_01"%ssDefName cmds.textFieldGrp(widgets["ssdTFG"], tx=newName, e=True) else: cmds.warning("An object/cluster of that name already exists! Please choose another name!")
def text_curves(self, name_text='Name', font='Arial', color=16): #BASED ON OLD ONE in RDM Tools V1 (Sorry for the spanish i just copy paste it) #Im deleting one node so if theres one already in the scene i dont want to delete it if cmds.objExists('makeTextCurves1'): cmds.rename('makeTextCurves1', 'makeTextCurves1LOL') #Lets Create some curves Texto = '_' + name_text Color = color LetrasDobles = [] Text = cmds.textCurves(n=Texto, t=Texto, o=True, f=font) Lista = cmds.listRelatives(Text, ad=True) #print Lista Shape = Lista[1] #print Shape cmds.delete('makeTextCurves1') for Curva in Lista: if cmds.objectType(str(Curva), isType='nurbsCurve'): #print Curva #Get Parents curvaPapa = cmds.listRelatives(Curva, p=True) #print 'Curva papa ' + str(curvaPapa) curvaAbuelo = cmds.listRelatives(curvaPapa, p=True) #print 'curva Abuelo '+(curvaAbuelo[0]) #letters like e and o have 2 curves instead of 1 DobleCurva = cmds.listRelatives(curvaAbuelo) if len(DobleCurva) == 2: #print 'DobleCurva ' + str(DobleCurva) LetrasDobles.append(Curva) else: #parent to first shape if not Shape == curvaPapa[0]: cmds.makeIdentity(curvaAbuelo, a=True, t=True, r=True) cmds.parent(Curva, Shape, r=True, s=True) #Colores cmds.setAttr(Curva + '.overrideEnabled', 1) cmds.setAttr(Curva + '.overrideColor', Color) #Do stuff for the Double Letters #print LetrasDobles for dl in LetrasDobles: dlPapa = cmds.listRelatives(dl, p=True) dlAbuelo = cmds.listRelatives(dlPapa, p=True) cmds.makeIdentity(dlAbuelo, a=True, t=True, r=True) cmds.parent(dl, Shape, r=True, s=True) cmds.setAttr(dl + '.overrideEnabled', 1) cmds.setAttr(dl + '.overrideColor', Color) #Organizing cmds.parent(Shape, w=True) cmds.rename(Shape, Texto + str(nc['ctrl'])) cmds.delete(Text[0]) cmds.delete(Texto + str(nc['ctrl'] + 'Shape')) cmds.move(-0.5, 0, 0, r=True) cmds.xform(cp=True) cmds.rename(name_text + nc['curve']) return name_text + nc['curve']
def flattenVertex(self): mousePos = cmds.autoPlace(um=True) sl = cmds.ls(selection=True, flatten=True) ######################################################################################################## x = [] y = [] z = [] ######################################################################################################## for i in sl: location = cmds.xform(i, query=True, translation=True, worldSpace=True) x.append(location[0]) y.append(location[1]) z.append(location[2]) avgX = sum(x) / len(x) avgY = sum(y) / len(y) avgZ = sum(z) / len(z) xyzPos = [avgX, avgY, avgZ] message = ['X', 'Y', 'Z'] largestValue = mousePos[0] - xyzPos[0] positionToUse = 0 for i in range(len(mousePos)): if mousePos[i] == 0: pass else: temp = abs(mousePos[i]) - abs(xyzPos[0]) if temp > largestValue: largestValue = temp positionToUse = i if mousePos[positionToUse] - xyzPos[positionToUse] > 0: direction = '+' elif mousePos[positionToUse] - xyzPos[positionToUse] < 0: direction = '-' ######################################################################################################## if direction == '+': if positionToUse == 0: for i in range(len(sl)): cmds.xform(sl[i], translation=[max(x), y[i], z[i]], worldSpace=True) if positionToUse == 1: for i in range(len(sl)): cmds.xform(sl[i], translation=[x[i], max(y), z[i]], worldSpace=True) if positionToUse == 2: for i in range(len(sl)): cmds.xform(sl[i], translation=[x[i], y[i], max(z)], worldSpace=True) if direction == '-': if positionToUse == 0: for i in range(len(sl)): cmds.xform(sl[i], translation=[min(x), y[i], z[i]], worldSpace=True) if positionToUse == 1: for i in range(len(sl)): cmds.xform(sl[i], translation=[x[i], min(y), z[i]], worldSpace=True) if positionToUse == 2: for i in range(len(sl)): cmds.xform(sl[i], translation=[x[i], y[i], min(z)], worldSpace=True) ######################################################################################################## cmds.headsUpMessage('FLATTENED IN THE ' + direction + ' ' + message[positionToUse], verticalOffset=100, horizontalOffset=200)
def main(): #################################################################### #初期設定 #################################################################### In = cmds.playbackOptions(q=True,min=True) Out = cmds.playbackOptions(q=True,max=True) oSel = cmds.ls(sl=True,tr=True) oSel_str = map(str,oSel) oSel_Joint = ",".join(oSel_str) oSel_Array = oSel_Joint.split(",") bakeSet = [] deleteSet = [] Finsel = [] if len(oSel)>0: for i in oSel_Array: Artr_Check = cmds.attributeQuery('TargetModel', node=i, exists=1) if Artr_Check ==False: posX_Flag = int("0") posY_Flag = int("0") posZ_Flag = int("0") rotX_Flag = int("0") rotY_Flag = int("0") rotZ_Flag = int("0") sclX_Flag = int("0") sclY_Flag = int("0") sclZ_Flag = int("0") posX = cmds.selectKey(i,at="translateX") posY = cmds.selectKey(i,at="translateY") posZ = cmds.selectKey(i,at="translateZ") rotX = cmds.selectKey(i,at="rotateX") rotY = cmds.selectKey(i,at="rotateY") rotZ = cmds.selectKey(i,at="rotateZ") sclX = cmds.selectKey(i,at="scaleX") sclY = cmds.selectKey(i,at="scaleY") sclZ = cmds.selectKey(i,at="scaleZ") #################################################################### #アトリビュート確認 #################################################################### posX_Flag += Flag_Check(posX,posX_Flag) posY_Flag += Flag_Check(posY,posY_Flag) posZ_Flag += Flag_Check(posZ,posZ_Flag) rotX_Flag += Flag_Check(rotX,rotX_Flag) rotY_Flag += Flag_Check(rotY,rotY_Flag) rotZ_Flag += Flag_Check(rotZ,rotZ_Flag) sclX_Flag += Flag_Check(sclX,sclX_Flag) sclY_Flag += Flag_Check(sclY,sclY_Flag) sclZ_Flag += Flag_Check(sclZ,sclZ_Flag) Rename_Point = 0 Rename_Orient = 0 Rename_Scale = 0 #################################################################### #選択にコンスト #################################################################### if posX_Flag+posY_Flag+posZ_Flag+rotX_Flag+rotY_Flag+rotZ_Flag+sclX_Flag+sclY_Flag+sclZ_Flag == 0: makeWindow(i) else: Sel_FullPath = Path(i) Sel_Long = Sel_FullPath.fullPathName() Cone = cmds.curve(d = 1, p = [[-8.6754635314381261, -11.371846236362176, 8.721448300231371], [-0.19018254083754044, 12.628153763637824, 0.23616730963078481], [-0.19018254083754044, -11.371846236362176, 12.236166355956469], [-8.6754635314381261, -11.371846236362176, 8.721448300231371], [-0.19018254083754044, -11.371846236362176, 0.23616730963078481], [-0.19018254083754044, -11.371846236362176, 12.236166355956469], [-0.19018254083754044, 12.628153763637824, 0.23616730963078481], [8.2950984497630458, -11.371846236362176, 8.721448300231371], [-0.19018254083754044, -11.371846236362176, 12.236166355956469], [-0.19018254083754044, -11.371846236362176, 0.23616730963078481], [8.2950984497630458, -11.371846236362176, 8.721448300231371], [-0.19018254083754044, 12.628153763637824, 0.23616730963078481], [11.80981745916246, -11.371846236362176, 0.23616730963078481], [8.2950984497630458, -11.371846236362176, 8.721448300231371], [-0.19018254083754044, -11.371846236362176, 0.23616730963078481], [11.80981745916246, -11.371846236362176, 0.23616730963078481], [-0.19018254083754044, 12.628153763637824, 0.23616730963078481], [8.2950984497630458, -11.371846236362176, -8.2491136809698009], [11.80981745916246, -11.371846236362176, 0.23616730963078481], [-0.19018254083754044, -11.371846236362176, 0.23616730963078481], [8.2950984497630458, -11.371846236362176, -8.2491136809698009], [-0.19018254083754044, 12.628153763637824, 0.23616730963078481], [-0.19018254083754044, -11.371846236362176, -11.763830783020582], [8.2950984497630458, -11.371846236362176, -8.2491136809698009], [-0.19018254083754044, -11.371846236362176, 0.23616730963078481], [-0.19018254083754044, -11.371846236362176, -11.763830783020582], [-0.19018254083754044, 12.628153763637824, 0.23616730963078481], [-8.6754635314381261, -11.371846236362176, -8.2491136809698009], [-0.19018254083754044, -11.371846236362176, 0.23616730963078481], [-0.19018254083754044, -11.371846236362176, -11.763830783020582], [-8.6754635314381261, -11.371846236362176, -8.2491136809698009], [-0.19018254083754044, 12.628153763637824, 0.23616730963078481], [-12.190180633488907, -11.371846236362176, 0.23616730963078481], [-8.6754635314381261, -11.371846236362176, -8.2491136809698009], [-0.19018254083754044, -11.371846236362176, 0.23616730963078481], [-12.190180633488907, -11.371846236362176, 0.23616730963078481], [-0.19018254083754044, 12.628153763637824, 0.23616730963078481], [-8.6754635314381261, -11.371846236362176, 8.721448300231371], [-12.190180633488907, -11.371846236362176, 0.23616730963078481], [-0.19018254083754044, -11.371846236362176, 0.23616730963078481], [-8.6754635314381261, -11.371846236362176, 8.721448300231371]]) cmds.addAttr(Cone,sn="TM", ln="TargetModel", dt="string" ) cmds.setAttr(Cone+'.TargetModel',Sel_Long,type='string') if posX_Flag+posY_Flag+posZ_Flag > 2: Point_Const = cmds.pointConstraint(i,Cone) Rename_Point = 1 if rotX_Flag+rotY_Flag+rotZ_Flag > 2: Orient_Const = cmds.orientConstraint(i,Cone) Rename_Orient = 1 if sclX_Flag+sclY_Flag+sclZ_Flag > 2: Scale_Const = cmds.scaleConstraint(i,Cone) Rename_Scale = 1 Name_Set = '' if Rename_Scale ==1: Name_Set = Name_Set + 'S' if Rename_Orient ==1: Name_Set = Name_Set + 'R' if Rename_Point ==1: Name_Set = Name_Set + 'T' ReName = cmds.rename(Cone,"Global_"+i+"_"+Name_Set) At_list = [] #################################################################### #ベイク設定 #################################################################### Bake_list = Channel_Check(ReName,posX,rotX,sclX,At_list) Connections = cmds.listRelatives(ReName,c=True,typ="constraint") #################################################################### #ベイク関数 #################################################################### RunBake(Bake_list,In,Out,Connections) #################################################################### #再コンスト #################################################################### if Rename_Scale == 1 : cmds.cutKey( i, attribute='scaleX', option="keys" ) cmds.cutKey( i, attribute='scaleY', option="keys" ) cmds.cutKey( i, attribute='scaleZ', option="keys" ) cmds.scaleConstraint(ReName,i) if Rename_Orient == 1 : cmds.orientConstraint(ReName,i) if Rename_Point == 1 : cmds.pointConstraint(ReName,i) Sel_Pos = cmds.xform(i,worldSpace=True,q=True,translation=True) cmds.xform(ReName, translation=Sel_Pos,worldSpace=True,absolute=True ) cmds.setAttr(ReName+".overrideEnabled",1) cmds.setAttr(ReName+".overrideColor",6) Finsel.append(ReName) else: target = cmds.getAttr ( '%s.TargetModel' % i ) bakeSet.append(target) deleteSet.append(i) ########################################################### #グローバルを一括ペースト ########################################################### if len(bakeSet)>0: At_list = [] for i in bakeSet: posX = cmds.selectKey(i,at="translateX") posY = cmds.selectKey(i,at="translateY") posZ = cmds.selectKey(i,at="translateZ") rotX = cmds.selectKey(i,at="rotateX") rotY = cmds.selectKey(i,at="rotateY") rotZ = cmds.selectKey(i,at="rotateZ") sclX = cmds.selectKey(i,at="scaleX") sclY = cmds.selectKey(i,at="scaleY") sclZ = cmds.selectKey(i,at="scaleZ") Bake_list = Channel_Check(i,posX,rotX,sclX,At_list) #Bakeしてワールドコントローラーを削除 RunBake(Bake_list,In,Out,deleteSet) else: cmds.confirmDialog(message = u'1つ以上選択して実行して下さい。',b= u'~終了~') if len(Finsel)>0: cmds.select(Finsel)
def nwCreateghOstCam(): makeCam = cmds.camera(name='ghostCam') mel.eval('cameraMakeNode 2 "";') cmds.select(makeCam[0]) # set new pivots for realistic panning. cmds.xform(rp=[0, -.4, 0.3], sp=[0, -.4, 0.3]) cmds.select(makeCam[0] + '_aim') cmds.xform(rp=[0, -.4, 0], sp=[0, -.4, 0]) # make ctrl and connect attributes. cmds.setAttr(makeCam[0] + '_group' + '.worldUpType', 4) camCtrl = cmds.circle(n=("'" + makeCam[0] + "'" + 'Ctrl'), c=(0, 0, 0), nr=(0, 1, 0), sw=360, r=8) cmds.setAttr(camCtrl[0] + '.rx', l=True, k=False) cmds.setAttr(camCtrl[0] + '.ry', k=False) cmds.setAttr(camCtrl[0] + '.rz', k=False) cmds.setAttr(camCtrl[0] + '.sx', l=True, k=False) cmds.setAttr(camCtrl[0] + '.sy', l=True, k=False) cmds.setAttr(camCtrl[0] + '.sz', l=True, k=False) cmds.setAttr(camCtrl[0] + '.visibility', l=True, k=False) # add new ctrl attributes cmds.addAttr(ln='cameraScale', k=True) cmds.setAttr(camCtrl[0] + '.cameraScale', 1) cmds.addAttr(ln='cameraTruck', at="enum", en="Rotation") cmds.setAttr(camCtrl[0] + '.cameraTruck', channelBox=1) cmds.addAttr(ln='orbitY', k=True, at='doubleAngle') cmds.addAttr(ln='orbitX', k=True, at='doubleAngle') cmds.addAttr(ln='orbitZ', k=True, at='doubleAngle') cmds.addAttr(ln='sideTracking', at="enum", en="and Zoom") cmds.setAttr(camCtrl[0] + '.sideTracking', channelBox=1) cmds.addAttr(ln='trackZoom', k=True) cmds.addAttr(ln='trackY', k=True) cmds.addAttr(ln='trackX', k=True) cmds.setAttr(camCtrl[0] + '.trackZoom', 8) cmds.addAttr(ln='cameraLens', at="enum", en="Pan/Tilt") cmds.setAttr(camCtrl[0] + '.cameraLens', channelBox=1) cmds.addAttr(ln='panY', k=True, at='doubleAngle') cmds.addAttr(ln='panX', k=True, at='doubleAngle') cmds.addAttr(ln='tilt', k=True, at='doubleAngle') cmds.addAttr(ln='lens', at="enum", en="Settings") cmds.setAttr(camCtrl[0] + '.lens', channelBox=1) cmds.addAttr(ln='lensZoom', k=True) cmds.setAttr(camCtrl[0] + '.lensZoom', 35) cmds.parent(makeCam[0] + '_group', camCtrl[0]) # connect new ctrl attributes cmds.connectAttr(camCtrl[0] + '.cameraScale', makeCam[0] + '.sx') cmds.connectAttr(camCtrl[0] + '.cameraScale', makeCam[0] + '.sy') cmds.connectAttr(camCtrl[0] + '.cameraScale', makeCam[0] + '.sz') cmds.connectAttr(camCtrl[0] + '.trackZoom', makeCam[0] + '.tz') cmds.connectAttr(camCtrl[0] + '.trackX', makeCam[0] + '_group' + '.tx') cmds.connectAttr(camCtrl[0] + '.trackY', makeCam[0] + '_group' + '.ty') cmds.setAttr(makeCam[0] + '_aim.tz', 0) cmds.connectAttr(camCtrl[0] + '.orbitY', makeCam[0] + '_group' + '.rx') cmds.connectAttr(camCtrl[0] + '.orbitX', camCtrl[0] + '.ry') cmds.connectAttr(camCtrl[0] + '.orbitZ', camCtrl[0] + '.rz') cmds.connectAttr(camCtrl[0] + '.panY', makeCam[0] + '_group' + '.offsetX') cmds.connectAttr(camCtrl[0] + '.panX', makeCam[0] + '_group' + '.offsetY') cmds.connectAttr(camCtrl[0] + '.tilt', makeCam[0] + '_group' + '.offsetZ') cmds.connectAttr(camCtrl[0] + '.lensZoom', makeCam[1] + '.focalLength') # lock the aim cmds.setAttr(makeCam[0] + '_aim.t', l=True) cmds.setAttr(makeCam[0] + '_aim.s', l=True) cmds.setAttr(makeCam[0] + '_aim.r', l=True) cmds.setAttr(makeCam[0] + '_aim.visibility', 0, l=True) # create and connect new aim for visual feedback. aimLoc = cmds.spaceLocator(n=makeCam[0] + "_aimLoc") cmds.parent(aimLoc, makeCam[0] + '_group') cmds.setAttr(aimLoc[0] + '.displayRotatePivot', 1) cmds.setAttr(aimLoc[0] + 'Shape.visibility', 0) cmds.setAttr(aimLoc[0] + '.visibility', l=True, k=False) cmds.setAttr(aimLoc[0] + '.tx', l=True, k=False) cmds.setAttr(aimLoc[0] + '.ty', l=True, k=False) cmds.setAttr(aimLoc[0] + '.tz', l=True, k=False) cmds.setAttr(aimLoc[0] + '.sx', l=True, k=False) cmds.setAttr(aimLoc[0] + '.sy', l=True, k=False) cmds.setAttr(aimLoc[0] + '.sz', l=True, k=False) cmds.setAttr(aimLoc[0] + '.rx', l=True, k=False) cmds.setAttr(aimLoc[0] + '.ry', l=True, k=False) cmds.setAttr(aimLoc[0] + '.rz', l=True, k=False) cmds.select(camCtrl)
import maya.cmds as cmds # Create a variable that contains a list of selected objects object_selected = cmds.ls(sl=True) # for each object selected... for each in object_selected: # create a variable that it gives me the transformation of selected object. # query = True it's like setAttr # matrix = True --> ask about the object's transformation father = cmds.listRelatives(each, parent=True) object = cmds.xform(each, query=True, matrix=True, worldSpace=True) # Create a null, with the object's name follow of a sufix and store in a variable grp_ori = cmds.group(em=True, name='ori_' + each + '_n_00') # Put the same object's matrix in the grp_group cmds.xform(grp_ori, matrix=object, worldSpace=True) grp_off = cmds.group(em=True, name='off_' + each + '_n_00') cmds.xform(grp_off, matrix=object, worldSpace=True) grp_lvu = cmds.group(em=True, name='lvu_' + each + '_n_00') cmds.xform(grp_lvu, matrix=object, worldSpace=True) grp_lvd = cmds.group(em=True, name='lvd_' + each + '_n_00') cmds.xform(grp_lvd, matrix=object, worldSpace=True) cmds.parent(grp_off, grp_ori)
def move_center2selection(): if not cmds.ls(sl=True): return if cmds.selectMode(q=True, co=True): selection = cmds.ls(sl=True) selMode = "component" # カーブもとっておく cv_selection = cmds.ls(sl=True, type="double3", fl=True) verticies = cmds.polyListComponentConversion(selection, tv=True) if verticies: verticies = cmds.filterExpand(verticies, sm=31) + cv_selection else: verticies = cv_selection # print verticies center = [0, 0, 0] for i in range(3): center[i] = sum( [cmds.pointPosition(vtx, w=True)[i] for vtx in verticies]) / len(verticies) # print center elif cmds.selectMode(q=True, o=True): selMode = "object" # スムース直後だとうまくオブジェクト選択にならないときがあるのでいったんコンポーネントを経由 cmds.selectMode(co=True) cmds.selectMode(o=True) selection = cmds.ls(sl=True, l=True, tr=True) childeNodes = common.search_polygon_mesh(selection, serchChildeNode=True, fullPath=True, nurbs=True) # print childeNodes selection = list(set(selection + childeNodes)) preLock = {} for sel in selection: preLock[sel] = cmds.getAttr(sel + ".translateX", lock=True) for ax in ["X", "Y", "Z"]: cmds.setAttr(sel + ".translate" + ax, lock=False) if selMode == "object": # 正しいバウンディングボックスを得るために複製、ベイク、取得、削除する duplicate_mesh = cmds.duplicate(selection, rc=True) # 子の名前を固有にしてエラー回避rc=True cmds.bakePartialHistory(duplicate_mesh, ppt=True) bBox = cmds.exactWorldBoundingBox(duplicate_mesh, ignoreInvisible=False) center = [(bBox[i] + bBox[i + 3]) / 2 for i in range(3)] cmds.delete(duplicate_mesh) for sel in selection: if np_flag: sel_pos = np.array(cmds.xform(sel, q=True, t=True, ws=True)) offset = sel_pos - np.array(center) # offset *= 2 else: sel_pos = cmds.xform(sel, q=True, t=True, ws=True) offset = [p - c for p, c in zip(sel_pos, center)] dummy = common.TemporaryReparent().main(mode="create") # モジュールでダミーの親作成 common.TemporaryReparent().main(sel, dummyParent=dummy, mode="cut") cmds.xform(sel, t=center, ws=True) # カーブもとっておく cv_selection = cmds.ls(sel + ".cv[*]", fl=True) # print cv_selection verticies = cmds.polyListComponentConversion(sel, tv=True) if verticies: verticies = cmds.filterExpand(verticies, sm=31) + cv_selection else: verticies = cv_selection # print verticies # print offset cmds.xform(verticies, t=offset, r=True, ws=True) cmds.xform(sel + ".scalePivot", t=center, ws=True) cmds.xform(sel + ".rotatePivot", t=center, ws=True) if preLock[sel]: for ax in ["X", "Y", "Z"]: cmds.setAttr(sel + ".translate" + ax, lock=True) # cmds.xform(sel+'.scalePivot', t=[0, 0, 0], os=True) # cmds.xform(sel+'.rotatePivot', t=[0, 0, 0], os=True) common.TemporaryReparent().main(sel, dummyParent=dummy, mode="parent") common.TemporaryReparent().main(sel, dummyParent=dummy, mode="delete") freeze.main(mesh=selection) cmds.select(selection, r=True)
import maya.cmds as cmds selection_list = cmds.ls(orderedSelection = True) # Finding which groups these locators belongs to. So we can create the cones under the same group first_loc = selection_list[0] loc_parent_grp = cmds.listRelatives( first_loc, p=True )[0] # Making cone group and making it child of the locator group cone_grp = cmds.group(em = True, name = '%s_cone' % loc_parent_grp, parent = loc_parent_grp) for obj in selection_list: # Making a cone and adding that under the cone_group cone_new = cmds.polyCone(r = 1, h = 3.3, name = '%s_%s' % (obj, 'Cone') ) cmds.parent( '%s_%s' % (obj, 'Cone'), cone_grp) # Bringing the pivot of the cone in to its own tip cone_vtx = cmds.ls('%s_%s.vtx[*]' % (obj, 'Cone'), fl=True) cone_tip = cone_vtx[-1] vtx_pos = cmds.xform(cone_tip, ws = 1, q = 1, t = 1) cmds.move( vtx_pos[0], vtx_pos[1], vtx_pos[2], ['%s_%s.scalePivot' % (obj, 'Cone'), '%s_%s.rotatePivot' % (obj, 'Cone')], relative=True ) cmds.rotate(0,0,180) cmds.pointConstraint(obj, cone_new) cmds.select(clear = True)
def freeze_transform(mode="", c_comp=False): from . import sisidebar_sub selections = cmds.ls(sl=True, l=True, tr=True) # 下からのマルチ選択でも正しく上からフリーズできるように階層深さでソート sel_depth = [[sel, check_depth(sel)] for sel in selections] sel_depth = sorted(sel_depth, key=lambda a: a[1]) for sel in sel_depth: sel = sel[0] dummy = common.TemporaryReparent().main(mode="create") srt_dummy = common.TemporaryReparent().main(mode="create") # common.TemporaryReparent().main(sel, dummyParent=dummy, mode='cut') if not c_comp: set_maching(nodes=srt_dummy, mode="all", pre_sel=selections) matching_obj = srt_dummy trs_matching(node=sel, sel_org=False) common.TemporaryReparent().main( sel, dummyParent=dummy, srtDummyParent=srt_dummy, mode="custom_cut", preSelection=selections, ) attr_lock_flag_list = check_attr_locked(sel) try: if mode == "all": cmds.makeIdentity(sel, n=0, s=1, r=1, jointOrient=1, t=1, apply=True, pn=1) cmds.xform(srt_dummy, t=[0, 0, 0]) cmds.xform(srt_dummy, ro=[0, 0, 0]) cmds.xform(srt_dummy, s=[1, 1, 1]) if mode == "trans": cmds.makeIdentity(sel, n=0, s=0, r=0, jointOrient=0, t=1, apply=True, pn=1) cmds.xform(srt_dummy, t=[0, 0, 0]) if mode == "rot": cmds.makeIdentity(sel, n=0, s=0, r=1, jointOrient=0, t=0, apply=True, pn=1) cmds.xform(srt_dummy, ro=[0, 0, 0]) if mode == "scale": cmds.makeIdentity(sel, n=0, s=1, r=0, jointOrient=0, t=0, apply=True, pn=1) cmds.xform(srt_dummy, s=[1, 1, 1]) if mode == "joint": if cmds.nodeType(sel) == "joint": cmds.makeIdentity( sel, n=0, s=0, r=0, jointOrient=1, t=0, apply=True, pn=1, ) cmds.xform(srt_dummy, ro=[0, 0, 0]) if mode == "trans" or mode == "all": cmds.xform(sel + ".scalePivot", t=[0, 0, 0], os=True) cmds.xform(sel + ".rotatePivot", t=[0, 0, 0], os=True) except Exception as e: print(e.message) cmds.inViewMessage(amg=e.message, pos="midCenterTop", fade=True, ta=0.75, a=0.5) set_attr_locked(sel, attr_lock_flag_list) common.TemporaryReparent().main(sel, dummyParent=dummy, mode="parent") common.TemporaryReparent().main(sel, dummyParent=srt_dummy, mode="parent") common.TemporaryReparent().main(dummyParent=dummy, mode="delete") common.TemporaryReparent().main(dummyParent=srt_dummy, mode="delete") # ダミー親削除 cmds.select(selections, r=True) sisidebar_sub.get_matrix()
def setPivotToManip_apply(): # get trans transX = cmds.checkBox('nwSAK_modWorldSpaceAniTransXCB', q=True, v=True) transY = cmds.checkBox('nwSAK_modWorldSpaceAniTransYCB', q=True, v=True) transZ = cmds.checkBox('nwSAK_modWorldSpaceAniTransZCB', q=True, v=True) # get rotate rotateX = cmds.checkBox('nwSAK_modWorldSpaceAniRotateXCB', q=True, v=True) rotateY = cmds.checkBox('nwSAK_modWorldSpaceAniRotateYCB', q=True, v=True) rotateZ = cmds.checkBox('nwSAK_modWorldSpaceAniRotateZCB', q=True, v=True) # get scale scaleX = cmds.checkBox('nwSAK_modWorldSpaceAniScaleXCB', q=True, v=True) scaleY = cmds.checkBox('nwSAK_modWorldSpaceAniScaleYCB', q=True, v=True) scaleZ = cmds.checkBox('nwSAK_modWorldSpaceAniScaleZCB', q=True, v=True) # get selected sel = cmds.ls(sl=True, type='transform') manipPos = cmds.floatFieldGrp('nwSAK_manipPivotAni', q=True, v=True) targetTrans = cmds.floatFieldGrp('nwSAK_transPivotsAni', q=True, v=True) targetRot = cmds.floatFieldGrp('nwSAK_rotPivotsAni', q=True, v=True) targetScale = cmds.floatFieldGrp('nwSAK_scalePivotsAni', q=True, v=True) types = cmds.radioButtonGrp('nwSAK_animovTypeSelect', q=True, sl=True) if sel: if manipPos: if (types == 1): # cycle for stuff in sel: # get select trans selTrans = cmds.xform(stuff, q=True, ws=True, t=True) selRot = cmds.xform(stuff, q=True, ws=True, ro=True) selScale = cmds.xform(stuff, q=True, r=True, s=True) # set/reset array trans = [] rotate = [] scale = [] ### check for trans if (transX == 1): trans.append(targetTrans[0]) else: trans.append(selTrans[0]) if (transY == 1): trans.append(targetTrans[1]) else: trans.append(selTrans[1]) if (transZ == 1): trans.append(targetTrans[2]) else: trans.append(selTrans[2]) ### check for rot if (rotateX == 1): rotate.append(targetRot[0]) else: rotate.append(selRot[0]) if (rotateY == 1): rotate.append(targetRot[1]) else: rotate.append(selRot[1]) if (rotateZ == 1): rotate.append(targetRot[2]) else: rotate.append(selRot[2]) ### check for scl if (scaleX == 1): scale.append(targetScale[0]) else: scale.append(selScale[0]) if (scaleY == 1): scale.append(targetScale[1]) else: scale.append(selScale[1]) if (scaleZ == 1): scale.append(targetScale[2]) else: scale.append(selScale[2]) cmds.xform(stuff, ws=True, t=trans, ro=rotate) cmds.xform(stuff, r=True, s=scale) nmGUI_func.nmGUI_runCheck( 'complete', 'Selected transforms set to captured') else: # do pivot for obj in sel: cmds.xform(worldSpace=True, pivots=manipPos) # line nmGUI_func.nmGUI_runCheck( 'complete', 'Pivot(s) set to captured pivot position') # line else: nmGUI_func.nmGUI_runCheck('error', 'No captured target transforms/pivot') # line else: nmGUI_func.nmGUI_runCheck('error', 'Select a target to set transforms/pivot')
def edo_addMultiplyFrame(frameList): #frameList=['bbb_CTRL_rtdn','vvv_CTRL_fourAxisup'] frameStr = edo_frameListToFrameStr(frameList).replace( 'fourAxis', 'fourAxis_') curve = cmds.curve(d=1, p=[(-1, 1, 0), (-1, -1, 0), (1, -1, 0), (1, 1, 0), (-1, 1, 0)], k=[0, 1, 2, 3, 4]) cmds.rename(curve, frameStr) cmds.createNode('locator', n=frameStr.replace('_CTRL_', '_LOC_'), p=frameStr) cmds.setAttr(frameStr.replace('_CTRL_', '_LOC_') + '.v', 0) ex = '//' + frameStr + '_EXPRESSION\n' ex += (frameStr + '.multiplyValue=\n') cmds.addAttr(frameStr, ln='connectCurveVis', at='bool') cmds.setAttr(frameStr + '.connectCurveVis', e=1, k=1) cmds.setAttr(frameStr + '.connectCurveVis', 1) cmds.addAttr(frameStr, ln='multiplyValue', at='double') cmds.setAttr(frameStr + '.multiplyValue', e=1, k=1) cmds.addAttr(frameStr, ln='multiplyReverseValue', at='double') cmds.setAttr(frameStr + '.multiplyReverseValue', e=1, k=1) pl = [] for fl in frameList: #fl=frameList[1] print fl fl = fl.replace('fourAxis', 'fourAxis_') fattr = fl.replace('_CTRL_', '_FRAME.') loc = fl.replace('_CTRL_', '_LOC_') cmds.addAttr(frameStr, ln=fattr.replace('.', '__'), at='double') cmds.setAttr(frameStr + '.' + fattr.replace('.', '__'), e=1, k=1) cmds.connectAttr(fattr, frameStr + '.' + fattr.replace('.', '__'), f=1) ex += frameStr + '.' + fattr.replace('.', '__') + '*\n' cmds.curve(d=1, p=[(-1, 0, 0), (1, 0, 0)], k=[0, 1], n=fl + '___' + frameStr + '_connectCurve') cmds.parent(fl + '___' + frameStr + '_connectCurve', frameStr) cmds.setAttr(fl + '___' + frameStr + '_connectCurve.inheritsTransform', 0) cmds.setAttr(fl + '___' + frameStr + '_connectCurve.overrideEnabled', 1) cmds.setAttr( fl + '___' + frameStr + '_connectCurve.overrideDisplayType', 2) cmds.connectAttr( frameStr.replace('_CTRL_', '_LOC_') + '.worldPosition', fl + '___' + frameStr + '_connectCurve.controlPoints[0]', f=1) cmds.connectAttr(loc + '.worldPosition', fl + '___' + frameStr + '_connectCurve.controlPoints[1]', f=1) cmds.connectAttr(frameStr + '.connectCurveVis', fl + '___' + frameStr + '_connectCurve.v', f=1) pl += [cmds.xform(fl.replace('fourAxis_', 'fourAxis'), q=1, ws=1, t=1)] p = edo_arrayPositions(pl) cmds.xform(frameStr, ws=1, t=p) if cmds.objExists(frameStr + '_EXPRESSION'): cmds.delete(frameStr + '_EXPRESSION') ex = ex[:-2] + '\n;\n' ex += (frameStr + '.multiplyReverseValue=1-' + frameStr + '.multiplyValue;\n') cmds.expression(n=frameStr + '_EXPRESSION', s=ex) cmds.select(frameStr, r=1)
def reset_pivot_pos(nodes): if not nodes: nodes = cmds.ls(sl=True, tr=True, l=True) for s in nodes: cmds.xform(s + ".scalePivot", t=[0, 0, 0], os=True) cmds.xform(s + ".rotatePivot", t=[0, 0, 0], os=True)
def initialize(self, poses, rest_pose, num_bones, iterations, mayaMesh=None, jointList=None): bones = [] num_verts = rest_pose.shape[0] # shape mean array scale num_poses = poses.shape[0] bone_transforms = np.empty( (num_bones, num_poses, 4, 3)) # [(R, T) for for each pose] for each bone # 3rd dim has 3 rows for R and 1 row for T # Use k-means to assign bones to vertices whitened = whiten(rest_pose) codebook, _ = kmeans(whitened, num_bones) rest_pose_corrected = np.empty( (num_bones, num_verts, 3)) # Rest pose - mean of vertices attached to each bone # confirm mode if mayaMesh: #rigid Skin vert_assignments, bones = self.manual_codebook(mayaMesh, jointList) boneArray = [] for i in bones: boneArray.append(cmds.xform(i, q=1, t=1, ws=1)) self.rest_bones_t = np.array(boneArray) #rest_bones_t = np.empty((num_bones , 3)) for bone in range(num_bones): #rest_bones_t[bone] = np.mean(rest_pose[vert_assignments == bone] , axis = 0) self.rest_bones_t[bone] = np.array(boneArray[bone]) rest_pose_corrected[bone] = rest_pose - self.rest_bones_t[bone] for pose in range(num_poses): bone_transforms[bone, pose] = self.kabsch( rest_pose_corrected[bone, vert_assignments == bone], poses[pose, vert_assignments == bone]) else: # Compute initial random bone transformations vert_assignments, _ = vq( whitened, codebook) # Bone assignment for each vertex (|num_verts| x 1) self.rest_bones_t = np.empty( (num_bones, 3)) # Translations for bones at rest pose for bone in range(num_bones): self.rest_bones_t[bone] = np.mean( rest_pose[vert_assignments == bone], axis=0) rest_pose_corrected[bone] = rest_pose - self.rest_bones_t[bone] for pose in range(num_poses): bone_transforms[bone, pose] = self.kabsch( rest_pose_corrected[bone, vert_assignments == bone], poses[pose, vert_assignments == bone]) for it in range(iterations): # Re-assign bones to vertices using smallest reconstruction error from all poses constructed = np.empty( (num_bones, num_poses, num_verts, 3)) # |num_bones| x |num_poses| x |num_verts| x 3 for bone in range(num_bones): Rp = bone_transforms[bone, :, :3, :].dot( (rest_pose - self.rest_bones_t[bone]).T).transpose( (0, 2, 1)) # |num_poses| x |num_verts| x 3 # R * p + T constructed[bone] = Rp + bone_transforms[bone, :, np.newaxis, 3, :] errs = np.linalg.norm(constructed - poses, axis=(1, 3)) # position value average vert_assignments = np.argmin(errs, axis=0) # For each bone, for each pose, compute new transform using kabsch for bone in range(num_bones): self.rest_bones_t[bone] = np.mean( rest_pose[vert_assignments == bone], axis=0) rest_pose_corrected[bone] = rest_pose - self.rest_bones_t[bone] for pose in range(num_poses): P = rest_pose_corrected[bone, vert_assignments == bone] Q = poses[pose, vert_assignments == bone] if (P.size == 0 or Q.size == 0): print 'Skip Iteration' else: bone_transforms[bone, pose] = self.kabsch(P, Q) # jointList is correct Index Joint return bone_transforms, self.rest_bones_t, bones
def reset_transform(mode="", c_comp=False, reset_pivot=True): # print 'comp mode :', c_comp from . import sisidebar_sub if cmds.selectMode(q=True, co=True): return selections = cmds.ls(sl=True, l=True) # 子供のノード退避用ダミーペアレントを用意 dummy = common.TemporaryReparent().main(mode="create") for sel in selections: if c_comp: common.TemporaryReparent().main(sel, dummyParent=dummy, mode="cut") if mode == "all": cmds.xform(sel, t=[0, 0, 0]) cmds.xform(sel, ro=[0, 0, 0]) cmds.xform(sel, s=[1, 1, 1]) if mode == "trans": cmds.xform(sel, t=[0, 0, 0]) if mode == "rot": cmds.xform(sel, ro=[0, 0, 0]) if mode == "scale": cmds.xform(sel, s=[1, 1, 1]) if mode == "trans" or mode == "all": if reset_pivot: cmds.xform(sel + ".scalePivot", t=[0, 0, 0], os=True) cmds.xform(sel + ".rotatePivot", t=[0, 0, 0], os=True) if c_comp: common.TemporaryReparent().main(sel, dummyParent=dummy, mode="parent") common.TemporaryReparent().main(dummyParent=dummy, mode="delete") # ダミー親削除 cmds.select(selections, r=True) sisidebar_sub.get_matrix()
def getCubePos(cubeTrans): coords = cmds.xform(cubeTrans, q=True, t=True, os=True) return roundCoords(coords)
def flipAxis(self, pose, W, rest_pose, poses, rest_bones_t, mesh, finalBone): rotation = [] trans = [] for bone in range(len(finalBone)): rotation = self.euler_angles_from_rotation_matrix( self.boneTransform[bone][pose][:3, :]) trans = self.boneTransform[bone][pose][3, :] cmds.xform(finalBone[bone], ws=1, t=trans, ro=rotation) #flip axis def confirmFunc(): num_bones = W.shape[1] num_poses = poses.shape[0] num_verts = W.shape[0] p_corrected = rest_pose[ np. newaxis, :, :] - rest_bones_t[:, np. newaxis, :] # |num_bones| x |num_verts| x 3 constructions = np.empty( (num_bones, num_poses, num_verts, 3)) # |num_bones| x |num_poses| x |num_verts| x 3 for bone_ in range(num_bones): # When you are a vectorizing GOD constructions[bone_] = np.einsum( 'ijk,lk->ilj', self.boneTransform[bone_, :, :3, :], p_corrected[bone_]) # |num_poses| x |num_verts| x 3 constructions += self.boneTransform[:, :, np.newaxis, 3, :] # |num_bones| x |num_poses| x |num_verts| x 3 constructions *= ( W.T)[:, np.newaxis, :, np.newaxis] # |num_bones| x |num_poses| x |num_verts| x 3 errors = poses - np.sum(constructions, axis=0) # |num_poses| x |num_verts| x 3 return errors #W,rest_pose,poses,rest_bones_t errors = confirmFunc() err = np.mean(np.linalg.norm(errors, axis=2)) print np.linalg.norm(errors[pose], axis=-1) print np.argmax(np.linalg.norm(errors[pose], axis=-1)) while err > 0.1: print err for bone, na in enumerate(finalBone): largest_vert_errs = np.argmax( np.linalg.norm(errors[pose], axis=-1)) print largest_vert_errs dist_ = [] #find bone for i in range(len(finalBone)): trans = cmds.xform(finalBone[i], q=1, t=1) lveXform = cmds.xform(mesh + '.vtx[%s]' % largest_vert_errs, q=1, t=1) dist_.append( math.sqrt( sum([(a - b)**2 for a, b in zip(trans, lveXform)]))) ind_ = np.argmin(dist_) if ind_ == bone: print na print self.boneTransform[ind_][pose][:3, :] self.boneTransform[bone][pose][1, 1] *= -1 self.boneTransform[bone][pose][1, 0] *= -1 rotation = self.euler_angles_from_rotation_matrix( self.boneTransform[bone][pose][:3, :]) trans = self.boneTransform[bone][pose][3, :] cmds.xform(na, ws=1, t=trans, ro=rotation) errors = confirmFunc() err = np.mean(np.linalg.norm(errors, axis=2)) print err return rotation, trans
def _createDelta(self, combo, target, tVal): """ Part of the combo extraction process. Combo shapes are fixit shapes added on top of any sliders. This means that the actual combo-shape by itself will not look good by itself, and that's bad for artist interaction. So we must create a setup to take the final sculpted shape, and subtract the any direct slider deformations to get the actual "combo shape" as a delta It is this delta shape that is then plugged into the system """ # get floaters # As floaters can appear anywhere along any combo, they must # always be evaluated in isolation. For this reason, we will # always disconnect all floaters floatShapes = [i.thing for i in self.simplex.getFloatingShapes()] # get my shapes myShapes = [i.thing for i in combo.prog.getShapes()] with disconnected(self.op) as sliderCnx: with disconnected(floatShapes): with disconnected(myShapes): # zero all slider vals on the op for a in sliderCnx.itervalues(): cmds.setAttr(a, 0.0) # pull out the rest shape orig = cmds.duplicate(self.mesh, name="Orig")[0] # set the combo values sliderVals = [] for pair in combo.pairs: cmds.setAttr(sliderCnx[pair.slider.thing], pair.value * tVal) deltaObj = cmds.duplicate(self.mesh, name="{0}_Delta".format( combo.name))[0] cmds.xform(deltaObj, relative=True, translation=[10, 0, -10]) cmds.setAttr("{0}.visibility".format(deltaObj), False) bs = cmds.blendShape(deltaObj, name="tempDelta_BS")[0] base = cmds.duplicate(deltaObj, name="Base")[0] cmds.blendShape(bs, edit=True, target=(deltaObj, 0, target, 1.0)) cmds.blendShape(bs, edit=True, target=(deltaObj, 1, base, 1.0)) cmds.blendShape(bs, edit=True, target=(deltaObj, 2, orig, 1.0)) cmds.setAttr("{0}.{1}".format(bs, target), 1.0) cmds.setAttr("{0}.{1}".format(bs, base), 1.0) cmds.setAttr("{0}.{1}".format(bs, orig), 1.0) cmds.delete(base) cmds.delete(orig) return deltaObj
def shapeMirror(shape_list, position, axis, search, replace): if not isinstance(shape_list, (list, tuple, set)): shape_list = [shape_list] with OptimiseContext(): for shape in shape_list: if not mc.listRelatives(shape, shapes=True, type='nurbsCurve'): log.warning('Current version only supports nurbs curve.') continue orig_pos = mc.xform(shape, q=True, ws=True, rp=True) orig_rot = mc.xform(shape, q=True, ws=True, ro=True) mc.move(0, 0, 0, shape, ws=True) mc.rotate(0, 0, 0, shape, ws=True) curve_target = mc.duplicate(shape, returnRootsOnly=True)[0] for i in range(mc.getAttr(shape + '.spans')): pos = mc.xform((shape + '.cv[%s]' % i), q=True, ws=True, t=True) pos[axis] *= -1 mc.move(pos[0], pos[1], pos[2], curve_target + '.cv[%s]' % i, ws=True) mc.move(orig_pos[0], orig_pos[1], orig_pos[2], shape, ws=True) mc.rotate(orig_rot[0], orig_rot[1], orig_rot[2], shape, ws=True) if mc.listRelatives(shape, parent=True): mc.parent(curve_target, world=True) if position == 2: mc.move(orig_pos[0], orig_pos[1], orig_pos[2], curve_target, ws=True) mc.rotate(orig_rot[0], orig_rot[1], orig_rot[2], curve_target, ws=True) elif position == 3: mirrored_pos = list(orig_pos) mirrored_pos[axis] *= -1 mc.move(mirrored_pos[0], mirrored_pos[1], mirrored_pos[2], curve_target, ws=True) if mc.checkBox('ld_mCurve_colour_cBox', q=True, value=True) == 1: if mc.getAttr( mc.listRelatives(shape, shapes=True)[0] + '.overrideEnabled'): colour_object = mc.listRelatives( curve_target, shapes=True)[0] + '.overrideColor' else: colour_object = curve_target + '.overrideColor' value = mc.colorIndexSliderGrp( 'ld_mCurve_colour_cISGrp', q=True, value=True) - 1 mc.setAttr(colour_object, value) mc.rename(curve_target, shape.replace(search, replace))
def SK_followToAuto(obj, num): pos = rig.xform(obj, q=True, t=True, ws=True) rig.setAttr(obj + '.follow', num) rig.xform(obj, t=pos, ws=True)
cmds.setKeyframe(ctrls_FK_base + ".rotate") cmds.setKeyframe(ctrls_FK_mid + ".rotate") cmds.setKeyframe(ctrls_FK_tip + ".rotate") cmds.setKeyframe(ctrl_IK_FK_switch + ".IK_FK") #Goes back to the key frame this procccesses started on. cmds.currentTime(time, edit=True) cmds.setKeyframe(ctrl_IK + ".rotate") cmds.setKeyframe(ctrl_IK + ".translate") cmds.setKeyframe(ctrl_IK_pole + ".translate") cmds.setKeyframe(ctrl_IK_FK_switch + ".IK_FK") #Looks at the rotation position od the skinning joints for the arn in world space and stores them in variables baseRot = cmds.xform(jnt_base, q=True, ws=True, ro=True) midRot = cmds.xform(jnt_mid, q=True, ws=True, ro=True) twristRot = cmds.xform(ctrl_IK, q=True, ws=True, ro=True) #switches the arm from IK mode to FK mode. cmds.setAttr(ctrl_IK_FK_switch + ".IK_FK", 0) if "left" in ctrl_IK_FK_switch: #Set the FK controls to the rotate in world space we got from the skinning joints. cmds.xform(ctrls_FK_base, ws=True, ro=(baseRot[0], baseRot[1], baseRot[2])) cmds.xform(ctrls_FK_mid, ws=True, ro=(midRot[0], midRot[1], midRot[2])) cmds.xform(ctrls_FK_tip,
def create_ik_setup(): selected_list = cmds.ls(selection=True) cmds.parent(world=True) dup_selected_list = cmds.duplicate(selected_list[1:], parentOnly=True) cmds.parent(selected_list[3], selected_list[2]) cmds.parent(selected_list[2], selected_list[1]) cmds.parent(selected_list[1], selected_list[0]) count = 1 renamed_list = [] for item in dup_selected_list: new_item = cmds.rename(item, selected_list[count] + '_ik') renamed_list.append(new_item) count = count + 1 cmds.parent(renamed_list[2], renamed_list[1]) cmds.parent(renamed_list[1], renamed_list[0]) cmds.parent(renamed_list[0], selected_list[0]) cmds.select(renamed_list[0]) cmds.hide(cmds.ls(selection=True)) get_ctrl_name=[] name_split = selected_list[3].split('_') new_name = name_split[:2] new_name = '_'.join(new_name) get_ctrl_name.append(new_name) #ik ctrl ik_ctrl = cmds.circle(r=2, nr=(1, 0, 0), n=get_ctrl_name[0] + '_ctrl') cmds.matchTransform(ik_ctrl, renamed_list[2]) zro_group = cmds.group(em=True, n=ik_ctrl[0] + '_zro') cmds.matchTransform(zro_group, ik_ctrl) cmds.parent(ik_ctrl, zro_group) cmds.orientConstraint(ik_ctrl[0], renamed_list[2], mo=True) cmds.setAttr(ik_ctrl[0] + '.scaleX', lock=True, keyable=False) cmds.setAttr(ik_ctrl[0] + '.scaleY', lock=True, keyable=False) cmds.setAttr(ik_ctrl[0] + '.scaleZ', lock=True, keyable=False) #PV setup start = cmds.xform(renamed_list[0], q=1, ws=1, t=1) mid = cmds.xform(renamed_list[1], q=1, ws=1, t=1) end = cmds.xform(renamed_list[2], q=1, ws=1, t=1) startV = OpenMaya.MVector(start[0], start[1], start[2]) midV = OpenMaya.MVector(mid[0], mid[1], mid[2]) endV = OpenMaya.MVector(end[0], end[1], end[2]) startEnd = endV - startV startMid = midV - startV dotP = startMid * startEnd proj = float(dotP) / float(startEnd.length()) startEndN = startEnd.normal() projV = startEndN * proj arrowV = startMid - projV arrowV*= 50 finalV = arrowV + midV cross1 = startEnd ^ startMid cross1.normalize() cross2 = cross1 ^ arrowV cross2.normalize() arrowV.normalize() matrixV = [arrowV.x, arrowV.y, arrowV.z, 0, cross1.x, cross1.y, cross1.z, 0, cross2.x, cross2.y, cross2.z, 0, 0, 0, 0, 1] matrixM = OpenMaya.MMatrix() OpenMaya.MScriptUtil.createMatrixFromList(matrixV, matrixM) matrixFn = OpenMaya.MTransformationMatrix(matrixM) rot = matrixFn.eulerRotation() pv_ctrl = cmds.circle(r=1.5, nr=(0, 0, 1), n= get_ctrl_name[0] + '_pv_ctrl') cmds.xform(pv_ctrl[0], ws=1, t=(finalV.x, finalV.y, finalV.z)) cmds.xform(pv_ctrl[0], ws=1, rotation=((rot.x/math.pi*180.0), (rot.y/math.pi*180.0), (rot.z/math.pi*180.0))) cmds.setAttr(pv_ctrl[0] + '.rotateX', lock=True, keyable=False) cmds.setAttr(pv_ctrl[0] + '.rotateY', lock=True, keyable=False) cmds.setAttr(pv_ctrl[0] + '.rotateZ', lock=True, keyable=False) cmds.setAttr(pv_ctrl[0] + '.scaleX', lock=True, keyable=False) cmds.setAttr(pv_ctrl[0] + '.scaleY', lock=True, keyable=False) cmds.setAttr(pv_ctrl[0] + '.scaleZ', lock=True, keyable=False) zro_group = cmds.group(em=True, n=pv_ctrl[0] + '_zro') cmds.matchTransform(zro_group, pv_ctrl) cmds.parent(pv_ctrl, zro_group) ikh = cmds.ikHandle( sj=renamed_list[0], ee=renamed_list[2], n= get_ctrl_name[0] + '_ikHandle') cmds.parent(get_ctrl_name[0] + '_ikHandle', ik_ctrl) cmds.poleVectorConstraint(pv_ctrl[0], get_ctrl_name[0] + '_ikHandle') cmds.select(ikh) cmds.hide(cmds.ls(selection=True))
def ikFkMatch(namespace, ikfk_attr, ui_host, fks, ik, upv, ik_rot=None, key=None): """Switch IK/FK with matching functionality This function is meant to work with 2 joint limbs. i.e: human legs or arms Args: namespace (str): Rig name space ikfk_attr (str): Blend ik fk attribute name ui_host (str): Ui host name fks ([str]): List of fk controls names ik (str): Ik control name upv (str): Up vector control name ikRot (None, str): optional. Name of the Ik Rotation control key (None, bool): optional. Whether we do an snap with animation """ # returns a pymel node on the given name def _get_node(name): # type: (str) -> pm.nodetypes.Transform name = anim_utils.stripNamespace(name) if namespace: node = anim_utils.getNode(":".join([namespace, name])) else: node = anim_utils.getNode(name) if not node: mgear.log("Can't find object : {0}".format(name), mgear.sev_error) return node # returns matching node def _get_mth(name): # type: (str) -> pm.nodetypes.Transform tmp = name.split("_") tmp[-1] = "mth" query = "_".join(tmp) n = _get_node(query) if not n: mgear.log( "Can't find mth object : {0} for {1}".format(query, name), mgear.sev_comment) return _get_node(name) else: return n # get things ready fk_ctrls = [_get_node(x) for x in fks] fk_goals = [_get_mth(x) for x in fks] ik_ctrl = _get_node(ik) ik_goal = _get_mth(ik) upv_ctrl = _get_node(upv) if ik_rot: ik_rot_node = _get_node(ik_rot) ik_rot_goal = _get_mth(ik_rot) ui_node = _get_node(ui_host) o_attr = ui_node.attr(ikfk_attr) switch_to_fk = (o_attr.get() == 1.0) switch_to_ik = (not switch_to_fk) is_leg = ("leg" in ikfk_attr) # sets keyframes before snapping if key: _all_controls = [] _all_controls.extend(fk_ctrls) _all_controls.extend([ik_ctrl, upv_ctrl, ui_node]) if ik_rot: _all_controls.extend([ik_rot_node]) [ cmds.setKeyframe("{}".format(elem), time=(cmds.currentTime(query=True) - 1.0)) for elem in _all_controls ] # if is IKw then snap FK if switch_to_fk: world_matrices = [] for src, _ in zip(fk_goals, fk_ctrls): world_matrices.append(src.getMatrix(worldSpace=True)) o_attr.set(0.0) for mat, dst in zip(world_matrices, fk_ctrls): dst.setMatrix(mat, worldSpace=True) for mat, dst in zip(world_matrices, fk_ctrls): dst.setMatrix(mat, worldSpace=True) # if is FKw then sanp IK elif switch_to_ik: shoulder_mat = fk_goals[0].getMatrix(worldSpace=True) ik_mat = ik_goal.getMatrix(worldSpace=True) # transform.matchWorldTransform(ik_goal, ik_ctrl) if ik_rot: rot_mat = ik_rot_goal.getMatrix(worldSpace=True) # transform.matchWorldTransform(ik_rot_goal, ik_rot_node) if is_leg: upv_mat = fk_goals[1].getMatrix(worldSpace=True) else: upv_mat = fk_goals[2].getMatrix(worldSpace=True) o_attr.set(1.0) ik_ctrl.setMatrix(ik_mat, worldSpace=True) if ik_rot: ik_rot_node.setMatrix(rot_mat, worldSpace=True) upv_ctrl.setMatrix(upv_mat, worldSpace=True) # for _ in range(10): # fk_ctrls[0].setMatrix(shoulder_mat, worldSpace=True) _m = [] for row in shoulder_mat: for elem in row: _m.append(elem) for _ in range(20): cmds.xform(fk_ctrls[0].name(), ws=True, matrix=_m) # transform.matchWorldTransform(fk_goals[1], upv_ctrl) # calculates new pole vector position if is_leg: start_end = (fk_goals[-1].getTranslation(space="world") - fk_goals[0].getTranslation(space="world")) start_mid = (fk_goals[1].getTranslation(space="world") - fk_goals[0].getTranslation(space="world")) else: start_end = (fk_goals[-1].getTranslation(space="world") - fk_goals[1].getTranslation(space="world")) start_mid = (fk_goals[2].getTranslation(space="world") - fk_goals[1].getTranslation(space="world")) dot_p = start_mid * start_end proj = float(dot_p) / float(start_end.length()) proj_vector = start_end.normal() * proj arrow_vector = (start_mid - proj_vector) * 1.5 arrow_vector *= start_end.normal().length() if is_leg: final_vector = (arrow_vector + fk_goals[1].getTranslation(space="world")) else: final_vector = (arrow_vector + fk_goals[2].getTranslation(space="world")) upv_ctrl.setTranslation(final_vector, space="world") # sets blend attribute new value # o_attr.set(1.0) roll_att = ui_node.attr(ikfk_attr.replace("blend", "roll")) roll_att.set(0.0) ik_ctrl.setMatrix(ik_mat, worldSpace=True) if ik_rot: ik_rot_node.setMatrix(rot_mat, worldSpace=True) # upv_ctrl.setMatrix(upv_mat, worldSpace=True) for _ in range(20): cmds.xform(fk_ctrls[0].name(), ws=True, matrix=_m) # sets keyframes if key: [ cmds.setKeyframe("{}".format(elem), time=(cmds.currentTime(query=True))) for elem in _all_controls ] if is_leg: prefix = "_".join(ik.split("_")[0:2]).replace("leg", "foot") leg_tip_con = ["heel_ctl", "bk0_ctl", "tip_ctl", "roll_ctl"] for tip in leg_tip_con: node = _get_node("{}_{}".format(prefix, tip)) if not node: continue attribute.reset_SRT([ node, ])
def attachToMesh(mesh, transform, faceId=-1, useClosestPoint=False, orient=False, normAxis='x', tangentAxis='y', prefix=''): ''' Attach a transform to a specified mesh object @param mesh: Mesh to attach to @type mesh: str @param transform: Transform object to attach to surface @type transform: str @param faceId: Attach transform to this mesh face @type faceId: int @param useClosestPoint: Use the closest point on the mesh instead of the specified face @type useClosestPoint: bool @param orient: Orient transform object to mesh face normal @type orient: bool @param normAxis: Transform axis that will be aimed along the face normal @type normAxis: str @param tangentAxis: Transform axis that will be aligned with the face tangent @type tangentAxis: str @param prefix: Name prefix string for all builder created nodes @type prefix: str ''' # Create axis value dictionary axis = { 'x': (1, 0, 0), 'y': (0, 1, 0), 'z': (0, 0, 1), '-x': (-1, 0, 0), '-y': (0, -1, 0), '-z': (0, 0, -1) } # Check mesh if not glTools.utils.mesh.isMesh(mesh): raise Exception('Object ' + mesh + ' is not a valid mesh!!') # Check transform if not mc.objExists(transform): raise Exception('Object ' + transform + ' does not exist!!') if not glTools.utils.transform.isTransform(transform): raise Exception('Object ' + transform + ' is not a valid transform!!') pos = mc.xform(transform, q=True, ws=True, rp=True) # Check prefix if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(transform) # Create int pointer for mesh iter classes indexUtil = OpenMaya.MScriptUtil() indexUtil.createFromInt(0) indexUtilPtr = indexUtil.asIntPtr() # Check closest face if useClosestPoint: faceId = glTools.utils.mesh.closestFace(mesh, pos) # Get MItMeshPolygon faceIter = glTools.utils.mesh.getMeshFaceIter(mesh) # Get face faceIter.setIndex(faceId, indexUtilPtr) # Get face edge list edgeIntList = OpenMaya.MIntArray() faceIter.getEdges(edgeIntList) edgeList = list(edgeIntList) # Get opposing edges edgeIter = glTools.utils.mesh.getMeshEdgeIter(mesh) edge1 = edgeList[0] edgeIter.setIndex(edge1, indexUtilPtr) edgePos = edgeIter.center(OpenMaya.MSpace.kWorld) # Find furthest edge edge2 = -1 dist = 0.0 for i in edgeList[1:]: edgeIter.setIndex(i, indexUtilPtr) eDist = edgePos.distanceTo(edgeIter.center(OpenMaya.MSpace.kWorld)) if eDist > dist: edge2 = i dist = eDist # Check opposing edge if not (edge2 + 1): raise Exception('Unable to determine opposing face edges!!') # Create mesh edge loft edge1_cme = prefix + '_edge01_curveFromMeshEdge' edge1_cme = mc.createNode('curveFromMeshEdge', n=edge1_cme) mc.connectAttr(mesh + '.worldMesh[0]', edge1_cme + '.inputMesh', f=True) mc.setAttr(edge1_cme + '.edgeIndex[0]', edge1) edge2_cme = prefix + '_edge02_curveFromMeshEdge' edge2_cme = mc.createNode('curveFromMeshEdge', n=edge2_cme) mc.connectAttr(mesh + '.worldMesh[0]', edge2_cme + '.inputMesh', f=True) mc.setAttr(edge2_cme + '.edgeIndex[0]', edge2) mesh_lft = prefix + '_loft' mesh_lft = mc.createNode('loft', n=mesh_lft) mc.connectAttr(edge1_cme + '.outputCurve', mesh_lft + '.inputCurve[0]', f=True) mc.connectAttr(edge2_cme + '.outputCurve', mesh_lft + '.inputCurve[1]', f=True) mc.setAttr(mesh_lft + '.degree', 1) # Create temporary surface tempSrf = mc.createNode('nurbsSurface') mc.connectAttr(mesh_lft + '.outputSurface', tempSrf + '.create') tempSrf = mc.listRelatives(tempSrf, p=True)[0] # Attach to lofted surface surfAttach = attachToSurface(surface=tempSrf, transform=transform, useClosestPoint=True, orient=orient, uAxis=tangentAxis, vAxis=normAxis, prefix=prefix) # Set aim constraint offset to orient to normal offsetVal = -90.0 if len(tangentAxis) == 2: offsetVal = 90.0 offsetAx = str.upper(tangentAxis[-1]) mc.setAttr(surfAttach[2] + '.offset' + offsetAx, offsetVal) # Bypass temporary nurbsSurface node mc.connectAttr(mesh_lft + '.outputSurface', surfAttach[0] + '.inputSurface', f=True) # Delete temporary surface mc.delete(tempSrf) # Return result return (surfAttach[0], surfAttach[1], surfAttach[2], mesh_lft, edge1_cme, edge2_cme)
def _matchSourceBlendshapesToTarget(source, target): if not cmds.objExists(source) or not cmds.objExists(target): return sourceInputTargets = [] bs = getConnectedInputBlendshapeNode(source) if bs: sourceInputTargets = cmds.listConnections(bs + '.inputTarget') cmds.delete(source, ch=1) # Reset source transformation. cmds.setAttr(source + '.tx', 0) cmds.setAttr(source + '.ty', 0) cmds.setAttr(source + '.tz', 0) # Temporally disable target deformation otherwise we cannot match the source and target correctly. for node in cmds.listHistory(target): if cmds.nodeType(node) == 'skinCluster' or cmds.nodeType( node) == 'blendShape': cmds.setAttr(node + '.envelope', 0.0) sourcePos = getMeshVertexPosition(source + '.vtx[0]') targetPos = getMeshVertexPosition(target + '.vtx[0]') dx = targetPos[0] - sourcePos[0] dy = targetPos[1] - sourcePos[1] dz = targetPos[2] - sourcePos[2] cmds.setAttr(source + '.tx', dx) cmds.setAttr(source + '.ty', dy) cmds.setAttr(source + '.tz', dz) cmds.makeIdentity(source, apply=True, t=1, r=1, s=1, n=0, pn=1) # Update all the source input targets to match our target mesh and freeze them. for sourceInputTarget in sourceInputTargets: cmds.setAttr(sourceInputTarget + '.tx', dx) cmds.setAttr(sourceInputTarget + '.ty', dy) cmds.setAttr(sourceInputTarget + '.tz', dz) cmds.makeIdentity(sourceInputTarget, apply=True, t=1, r=1, s=1, n=0, pn=1) # Recreate blendshape node. cmds.blendShape(sourceInputTargets, source) # Restore target deformation. for node in cmds.listHistory(target): if cmds.nodeType(node) == 'skinCluster' or cmds.nodeType( node) == 'blendShape': cmds.setAttr(node + '.envelope', 1.0) # Match the positions of vertices of source to target sourceVertsNum = cmds.polyEvaluate(source, v=True) targetVertsNum = cmds.polyEvaluate(target, v=True) pivotOffset = [0, 0, 0] if (sourceVertsNum == targetVertsNum): for i in range(sourceVertsNum): resTar = getMeshVertexPosition(target + '.vtx[%s]' % i) resSrc = getMeshVertexPosition(source + '.vtx[%s]' % i) srcPT = [ round(resSrc[0], 5), round(resSrc[1], 5), round(resSrc[2], 5) ] tarPT = [ round(resTar[0], 5), round(resTar[1], 5), round(resTar[2], 5) ] pivotOffset[0] = pivotOffset[0] + tarPT[0] - srcPT[0] pivotOffset[1] = pivotOffset[1] + tarPT[1] - srcPT[1] pivotOffset[2] = pivotOffset[2] + tarPT[2] - srcPT[2] cmds.xform(source + '.vtx[%s]' % i, t=tarPT, ws=True) sourcePiv = cmds.xform(source, piv=True, q=True, ws=True) sourcePiv[0] = sourcePiv[0] + pivotOffset[0] / sourceVertsNum sourcePiv[1] = sourcePiv[1] + pivotOffset[1] / sourceVertsNum sourcePiv[2] = sourcePiv[2] + pivotOffset[2] / sourceVertsNum cmds.xform(source, ws=True, piv=(sourcePiv[0], sourcePiv[1], sourcePiv[2]))
def attachToCurve(curve, transform, uValue=0.0, useClosestPoint=False, orient=False, tangentAxis='x', upAxis='y', upVector=(0, 1, 0), upType='none', upObject='', uAttr='uParam', prefix=''): ''' Constrain a transform to a specified curve. @param curve: Curve to attach transform to @type curve: str @param transform: Transform to attach to curve @type transform: str @param uValue: U parameter of the point on curve to attach to @type uValue: float @param useClosestPoint: Use the closest point on the curve instead of the specified uValue @type useClosestPoint: bool @param orient: Orient transform object to curve tangent @type orient: bool @param tangentAxis: Constrained transform tangent aim axis @type tangentAxis: str @param upAxis: Constrained transform up vector axis @type upAxis: str @param upVector: Vector to use as for the constraint upVector @type upVector: tuple/list @param upType: Constraint upVector calculation method. Valid values - none, scene, vector, object, objectUp. @type upType: string @param upObject: Object whose local space will be used to calculate the orient upVector @type upObject: str @param uAttr: Attribute name on the constrained transform that will be connected to the target curve U parameter. @type uAttr: str @param prefix: Name prefix for created nodes @type prefix: str ''' # =========================== # - Build Data Dictionaries - # =========================== # Build axis dictionary axisDict = { 'x': (1, 0, 0), 'y': (0, 1, 0), 'z': (0, 0, 1), '-x': (-1, 0, 0), '-y': (0, -1, 0), '-z': (0, 0, -1) } # Build upType dictionary upTypeDict = { 'scene': 0, 'object': 1, 'objectUp': 2, 'vector': 3, 'none': 4 } # ========== # - Checks - # ========== # Check curve if not glTools.utils.curve.isCurve(curve): raise Exception('Object ' + curve + ' is not a valid curve!!') # Check curve shape curveShape = '' if mc.objectType(curve) == 'transform': curveShape = mc.listRelatives(curve, s=1, ni=1)[0] else: curveShape = curve curve = mc.listRelatives(curve, p=1)[0] # Check uValue minu = mc.getAttr(curve + '.minValue') maxu = mc.getAttr(curve + '.maxValue') if not useClosestPoint: if uValue < minu or uValue > maxu: raise Exception('U paramater ' + str(uValue) + ' is not within the parameter range for ' + curve + '!!') # Check object if not mc.objExists(transform): raise Exception('Object ' + transform + ' does not exist!!') if not glTools.utils.transform.isTransform(transform): raise Exception('Object ' + transform + ' is not a valid transform!!') # Check constraint axis' if not axisDict.has_key(tangentAxis): raise Exception('Invalid tangent axis "' + tangentAxis + '"!') if not axisDict.has_key(upAxis): raise Exception('Invalid up axis "' + upAxis + '"!') # Check constraint upType if not upTypeDict.has_key(upType): raise Exception('Invalid upVector type "' + upType + '"!') # Check worldUp object if upObject: if not mc.objExists(upObject): raise Exception('WorldUp object ' + upObject + ' does not exist!!') if not glTools.utils.transform.isTransform(upObject): raise Exception('WorldUp object ' + upObject + ' is not a valid transform!!') # Check prefix if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(transform) # =================== # - Attach to Curve - # =================== # Get closest curve point if useClosestPoint: uPos = mc.xform(transform, q=True, ws=True, rp=True) uValue = glTools.utils.curve.closestPoint(curve, uPos) # Add U parameter attribute if not mc.objExists(transform + '.' + uAttr): mc.addAttr(transform, ln=uAttr, at='float', min=minu, max=maxu, dv=uValue, k=True) else: try: mc.setAttr(transform + '.' + uAttr, uValue) except: print('Unable to set existing attr "' + transform + '.' + uAttr + '" to specified value (' + str(uValue) + ')!') # Create pointOnCurveInfo node poc = prefix + '_pointOnCurveInfo' poc = mc.createNode('pointOnCurveInfo', n=poc) # Attach pointOnCurveInfo node mc.connectAttr(curve + '.worldSpace[0]', poc + '.inputCurve', f=True) mc.connectAttr(transform + '.' + uAttr, poc + '.parameter', f=True) # Create pointConstraint node pntCon = mc.createNode('pointConstraint', n=prefix + '_pointConstraint') # Attach pointConstraint node mc.connectAttr(poc + '.position', pntCon + '.target[0].targetTranslate', f=True) mc.connectAttr(transform + '.parentInverseMatrix[0]', pntCon + '.constraintParentInverseMatrix', f=True) mc.connectAttr(transform + '.rotatePivot', pntCon + '.constraintRotatePivot', f=True) mc.connectAttr(transform + '.rotatePivotTranslate', pntCon + '.constraintRotateTranslate', f=True) # Attach to constrained transform mc.connectAttr(pntCon + '.constraintTranslateX', transform + '.tx', f=True) mc.connectAttr(pntCon + '.constraintTranslateY', transform + '.ty', f=True) mc.connectAttr(pntCon + '.constraintTranslateZ', transform + '.tz', f=True) # Parent constraint node mc.parent(pntCon, transform) # ========== # - Orient - # ========== aimCon = '' if orient: # Create aimConstraint node aimCon = prefix + 'aimConstraint' aimCon = mc.createNode('aimConstraint', n=aimCon) # Attach aimConstraint node mc.connectAttr(poc + '.tangent', aimCon + '.target[0].targetTranslate', f=True) mc.setAttr(aimCon + '.aimVector', *axisDict[tangentAxis]) mc.setAttr(aimCon + '.upVector', *axisDict[upAxis]) mc.setAttr(aimCon + '.worldUpVector', *upVector) mc.setAttr(aimCon + '.worldUpType', upTypeDict[upType]) if upObject: mc.connectAttr(upObject + '.worldMatrix[0]', aimCon + '.worldUpMatrix', f=True) # Attach to constrained transform mc.connectAttr(aimCon + '.constraintRotateX', transform + '.rx', f=True) mc.connectAttr(aimCon + '.constraintRotateY', transform + '.ry', f=True) mc.connectAttr(aimCon + '.constraintRotateZ', transform + '.rz', f=True) # Parent constraint node mc.parent(aimCon, transform) # Return result return [poc, pntCon, aimCon]
def attachToSurface(surface, transform, uValue=0.0, vValue=0.0, useClosestPoint=False, orient=False, uAxis='x', vAxis='y', uAttr='uCoord', vAttr='vCoord', alignTo='u', prefix=''): ''' Constrain a transform to a specified surface. @param surface: Nurbs surface to attach to @type surface: str @param transform: Transform object to attach to surface @type transform: str @param uValue: U parameter of the point on surface to attach to @type uValue: float @param vValue: V parameter of the point on surface to attach to @type vValue: float @param useClosestPoint: Use the closest point on the surface instead of the specified uv parameter @type useClosestPoint: bool @param orient: Orient transform object to surface tangents @type orient: bool @param uAxis: Transform axis that will be aligned to the surface U direction @type uAxis: str @param vAxis: Transform axis that will be aligned to the surface V direction @type vAxis: str @param uAttr: Attribute name that will control the target uCoordinate for the constraint @type uAttr: str @param vAttr: Attribute name that will control the target vCoordinate for the constraint @type vAttr: str @param alignTo: Select which tangent direction the constrained transform will align to @type alignTo: str @param prefix: Name prefix string for all builder created nodes @type prefix: str ''' # Create axis value dictionary axis = { 'x': (1, 0, 0), 'y': (0, 1, 0), 'z': (0, 0, 1), '-x': (-1, 0, 0), '-y': (0, -1, 0), '-z': (0, 0, -1) } # Check surface if not glTools.utils.surface.isSurface(surface): raise Exception('Surface ' + surface + ' is not a valid nurbsSurface!!') # Check surface shape surfaceShape = '' if mc.objectType(surface) == 'transform': surfaceShape = mc.listRelatives(surface, s=1, ni=1)[0] else: surfaceShape = surface surface = mc.listRelatives(surface, p=1)[0] # Check uValue minu = mc.getAttr(surface + '.minValueU') maxu = mc.getAttr(surface + '.maxValueU') minv = mc.getAttr(surface + '.minValueV') maxv = mc.getAttr(surface + '.maxValueV') if not useClosestPoint: if uValue < minu or uValue > maxu: raise Exception('U paramater ' + str(uValue) + ' is not within the parameter range for ' + surface + '!!') if vValue < minv or vValue > maxv: raise Exception('V paramater ' + str(vValue) + ' is not within the parameter range for ' + surface + '!!') # Check transform if not mc.objExists(transform): raise Exception('Object ' + transform + ' does not exist!!') if not glTools.utils.transform.isTransform(transform): raise Exception('Object ' + transform + ' is not a valid transform!!') # Check closest point if useClosestPoint: uv = glTools.utils.surface.closestPoint( surface, mc.xform(transform, q=True, ws=True, rp=True)) uValue = uv[0] vValue = uv[1] # Check prefix if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(transform) # Attach to surface # == # Add parameter attributes if not mc.objExists(transform + '.' + uAttr): mc.addAttr(transform, ln=uAttr, at='float', min=minu, max=maxu, dv=uValue, k=True) if not mc.objExists(transform + '.' + vAttr): mc.addAttr(transform, ln=vAttr, at='float', min=minv, max=maxv, dv=vValue, k=True) # Create pointOnSurfaceInfo node pos = mc.createNode('pointOnSurfaceInfo', n=prefix + '_pointOnSurfaceInfo') # Attach pointOnSurfaceInfo node mc.connectAttr(surface + '.worldSpace[0]', pos + '.inputSurface', f=True) mc.connectAttr(transform + '.' + uAttr, pos + '.parameterU', f=True) mc.connectAttr(transform + '.' + vAttr, pos + '.parameterV', f=True) # Create pointConstraint node pntCon = mc.createNode('pointConstraint', n=prefix + '_pointConstraint') # Attach pointConstraint node mc.connectAttr(pos + '.position', pntCon + '.target[0].targetTranslate', f=True) mc.connectAttr(transform + '.parentInverseMatrix[0]', pntCon + '.constraintParentInverseMatrix', f=True) mc.connectAttr(transform + '.rotatePivot', pntCon + '.constraintRotatePivot', f=True) mc.connectAttr(transform + '.rotatePivotTranslate', pntCon + '.constraintRotateTranslate', f=True) mc.connectAttr(pntCon + '.constraintTranslateX', transform + '.tx', f=True) mc.connectAttr(pntCon + '.constraintTranslateY', transform + '.ty', f=True) mc.connectAttr(pntCon + '.constraintTranslateZ', transform + '.tz', f=True) mc.parent(pntCon, transform) # Orient aimCon = '' if orient: # Get axis vaules uAx = axis[uAxis] vAx = axis[vAxis] # Create aimConstraint node aimCon = mc.createNode('aimConstraint', n=prefix + '_aimConstraint') # Attach aimConstraint node if alignTo == 'u': mc.connectAttr(pos + '.tangentU', aimCon + '.target[0].targetTranslate', f=True) mc.connectAttr(pos + '.tangentV', aimCon + '.worldUpVector', f=True) mc.setAttr(aimCon + '.aimVector', uAx[0], uAx[1], uAx[2]) mc.setAttr(aimCon + '.upVector', vAx[0], vAx[1], vAx[2]) else: mc.connectAttr(pos + '.tangentV', aimCon + '.target[0].targetTranslate', f=True) mc.connectAttr(pos + '.tangentU', aimCon + '.worldUpVector', f=True) mc.setAttr(aimCon + '.aimVector', vAx[0], vAx[1], vAx[2]) mc.setAttr(aimCon + '.upVector', uAx[0], uAx[1], uAx[2]) mc.connectAttr(aimCon + '.constraintRotateX', transform + '.rx', f=True) mc.connectAttr(aimCon + '.constraintRotateY', transform + '.ry', f=True) mc.connectAttr(aimCon + '.constraintRotateZ', transform + '.rz', f=True) mc.parent(aimCon, transform) # Return result return [pos, pntCon, aimCon]