def create_rig(crv=None, emitters=10, up_vec=(0, 0, -1), s=(0, 0, -1), start=1, end=50): crv = pm.PyNode(crv) name = crv.name() cont_name = name + '_fluidContainer' emitter_name = name + '_emitter' rig_grp_name = name + '_rigGrp' up_loc_name = name + '_upLoc' up_vec = dt.Vector(up_vec) s = dt.Vector(s) pos = get_pos(crv=crv, param=0) rig_grp = pm.group(em=1, name=rig_grp_name) em_grp = pm.group(em=1, name=emitter_name + 'Grp') pm.move(em_grp, pos) cont_grp = pm.group(em=1, name=cont_name) cont = create_fluid_container(name=cont_name, prnt=cont_grp) pm.move(cont_grp, pos) emittersList = [] em_pos = pos for i in range(emitters): em = create_emitter(container=cont, name=(emitter_name + '_%s' % i), pos=em_pos) em_pos += s pm.parent(em, em_grp) emittersList.append(em) up_loc = pm.spaceLocator(p=pos, name=up_loc_name) pm.move(up_loc, (pos + up_vec * -3000)) pm.parent(up_loc, rig_grp) pm.pathAnimation(em_grp, stu=start, etu=end, c=crv, wut='object', wuo=up_loc) pm.parent(em_grp, rig_grp) pm.parent(rig_grp, cont)
def addJointsToCurve(self, *args): self.jointsList = [] self.jointsListGRP = [] try: numOfJoints = pm.intField(self.loadNumJoints, q = True, v = True) self.selectedCurve = pm.ls(sl = True)[0] incr = float((numOfJoints - 1)) incr = 1/incr #calculate incrementation print incr incrTemp = 0.0 for i in range(numOfJoints): pm.select(clear = True) j = pm.joint(radius = 0.25, n = self.selectedCurve + "Joint") self.jointsList.append(j) jGRP = pm.group(j, n = j + "GRP") self.jointsListGRP.append(jGRP) #attach to motion path motionPath = pm.pathAnimation(jGRP, self.selectedCurve, fractionMode = True, follow = True ) pm.setAttr(motionPath +".u", incrTemp) pm.cutKey(motionPath) incrTemp += incr print incrTemp if incrTemp >= 1.0: incrTemp = 1.0 facialAnimations.allJoints.append(self.jointsList) self.curvesGRP = pm.group(self.jointsListGRP, n = self.selectedCurve + "_Face_jointsGRP") except: pass print "Curve not selected"
def hookOnCurve(mode=1, tangent=False): sel = pm.ls(sl=True) crv = sel[-1] sampleNPoC = pm.createNode('nearestPointOnCurve') sampleGrpA = pm.group(empty=True) crv.worldSpace[0] >> sampleNPoC.inputCurve sampleGrpA.translate >> sampleNPoC.inPosition for obj in sel[:-1]: wp = pm.xform(obj, t=True, ws=True, q=True) pm.xform(sampleGrpA, t=wp, ws=True) hookPar = sampleNPoC.parameter.get() if mode == 1: hookPoci = pm.createNode('pointOnCurveInfo') crv.worldSpace[0] >> hookPoci.inputCurve hookPoci.position >> obj.translate hookPoci.parameter.set(hookPar) if tangent: pm.tangentConstraint(crv, obj, aimVector=(-1, 0, 0), upVector=(0, 1, 0), worldUpType="vector", worldUpVector=(0, 1, 0)) elif mode == 2: mpathName = pm.pathAnimation(obj, c=crv) mpath = pm.PyNode(mpathName) deleteConnection(mpath.uValue) mpath.uValue.set(hookPar) pm.delete(sampleNPoC, sampleGrpA)
def setToCurve(target, objectData, position=0): #pathAnimationを指定.fractionMode=Trueにすることで0~1にu値を正規化 motionPathName=pm.pathAnimation(objectData, curve=target, fractionMode=True) #文字列をstr型で使いたいためAsciiコードに変換 ascPathName = motionPathName.encode('ascii') pm.setAttr(ascPathName+".uValue", position) pm.disconnectAttr(ascPathName+".uValue")
def recalculatePosition(currentPositions, newNumberPositions, degree=2): """ For a given set of position create a curve and return fewer/more a set of position that follow on that arc. @param currentPositions: Current list of cv position @param newNumberPositions: How many CV points do me require @param degree: What degree should be on the created curve @return: list of new cv positions """ if len(currentPositions) < 4: crv = createCurve(currentPositions, 1) else: crv = createCurve(currentPositions, degree) newPositions = [] pm.cycleCheck(e=False) for posOnCurve in libMath.spread(0, 1, newNumberPositions - 1): pm.select(clear=True) tempDag = pm.joint() mp = pm.PyNode( pm.pathAnimation(tempDag, fractionMode=True, follow=False, curve=crv)) pm.delete(mp.listConnections(type="animCurve")) mp.uValue.set(posOnCurve) newPositions.append(libUtilities.get_world_space_pos(tempDag)) pm.delete([mp, tempDag]) pm.delete(crv) return newPositions
def recalculatePosition(currentPositions, newNumberPositions, degree=2): """ For a given set of position create a curve and return fewer/more a set of position that follow on that arc. @param currentPositions: Current list of cv position @param newNumberPositions: How many CV points do me require @param degree: What degree should be on the created curve @return: list of new cv positions """ if len(currentPositions) < 4: crv = createCurve(currentPositions, 1) else: crv = createCurve(currentPositions, degree) newPositions = [] pm.cycleCheck(e=False) for posOnCurve in libMath.spread(0, 1, newNumberPositions - 1): pm.select(clear=True) tempDag = pm.joint() mp = pm.PyNode(pm.pathAnimation(tempDag, fractionMode=True, follow=False, curve=crv )) pm.delete(mp.listConnections(type="animCurve")) mp.uValue.set(posOnCurve) newPositions.append(libUtilities.get_world_space_pos(tempDag)) pm.delete([mp, tempDag]) pm.delete(crv) return newPositions
def createMotionPath(self, object, curve, uValue, fractionMode=False): motionPath = pm.pathAnimation(object, curve, follow=1) PyMotionPath = pm.PyNode(motionPath) animNode = pm.listConnections(motionPath, t='animCurve') pm.delete(animNode) PyMotionPath.fractionMode.set(fractionMode) PyMotionPath.uValue.set(uValue) return PyMotionPath
def duplicateAlongPath(self, *args): ''' ------------------------------------------ position along curve ------------------------------------------ ''' inputX = pm.intField(self.widgets['numberOfDuplicates'], q=True, v=True) GOD_object = pm.ls(sl=True)[0] curve = pm.textFieldButtonGrp(self.widgets['curvePath'], q=True, tx=True) pathLength = pm.arclen(curve, ch=False) randomON = pm.checkBox(self.widgets['RandomPathDistance'], q=True, v=True) n = 0 pathIncrement = 1.0 / inputX for increment in range(inputX): object = pm.duplicate(GOD_object, rc=True) objGroup = pm.group(object) motionPath = pm.pathAnimation(objGroup, fm=True, f=True, fa='x', ua='y', wut='scene', c=curve) pm.delete(pm.listConnections(motionPath + '.uValue')) value = rand.uniform(n, (n + pathIncrement)) if randomON == True: pm.setAttr(motionPath + '.uValue', value) randomRotate = rand.randint(0, 360) randomScale = rand.uniform( (pm.floatField(self.widgets['randomizeScaleMINPath'], q=True, v=True)), (pm.floatField(self.widgets['randomizeScaleMAXPath'], q=True, v=True))) print object pm.setAttr(object[0] + '.ry', randomRotate) pm.setAttr(object[0] + '.sx', randomScale) pm.setAttr(object[0] + '.sy', randomScale) pm.setAttr(object[0] + '.sz', randomScale) else: pm.setAttr(motionPath + '.uValue', n) n = n + pathIncrement pm.parent(objGroup, 'ROOT_enviroment_01')
def controlShapeAdaptive(controlList, geoList, ctrlSmooth=6, scaleConstant=1.5, rebuildCV=32): adaptiveShapeBuildGrp = pm.group(n='daptiveShapeBuild_GRP', em=True) geoList = pm.ls(geoList) dupliGeo = pm.duplicate(geoList) geoCombined = pm.polyUnite(dupliGeo, ch=False, name='tmpAdaptiveRef_GEO')[0] pm.parent(geoCombined, adaptiveShapeBuildGrp) ctrlList = pm.ls(controlList) for ctrl in ctrlList: ctrlShapeBuildGrp = pm.group(n=ctrl.name() + '_GRP', em=True, p=adaptiveShapeBuildGrp) dupliCtrl = pm.duplicate(ctrl, n='tmpCtrl')[0] pm.delete(pm.ls(dupliCtrl, dagObjects=True, exactType='transform')[1:]) pm.rebuildCurve(dupliCtrl, ch=False, s=rebuildCV) pm.parent(dupliCtrl, ctrlShapeBuildGrp) # extrusion extrudeCircle = pm.circle(r=0.1, ch=0)[0] pm.parent(extrudeCircle, ctrlShapeBuildGrp) motionPathNode = \ pm.ls(pm.pathAnimation(extrudeCircle, curve=dupliCtrl, fractionMode=True, follow=True, followAxis='z', upAxis='y', worldUpType='vector', worldUpVector=[0, 1, 0], inverseUp=False, inverseFront=False, bank=False))[0] pm.disconnectAttr(extrudeCircle.tx) pm.disconnectAttr(extrudeCircle.ty) pm.disconnectAttr(extrudeCircle.tz) pm.disconnectAttr(extrudeCircle.rx) pm.disconnectAttr(extrudeCircle.ry) pm.disconnectAttr(extrudeCircle.rz) pm.disconnectAttr(motionPathNode.u) pm.delete(motionPathNode) extrudedSurface = \ pm.extrude(extrudeCircle, dupliCtrl, ch=False, rn=False, po=0, et=2, ucp=0, fpt=1, upn=0, rotation=0, scale=1, rsp=1)[0] pm.parent(extrudedSurface, ctrlShapeBuildGrp) nurbsToPoly = pm.nurbsToPoly(extrudedSurface, ch=False, polygonType=1, chr=0.9) pm.parent(nurbsToPoly, ctrlShapeBuildGrp) # add deformer wrapNode = deform.wrapDeformer(dupliCtrl, nurbsToPoly) shrinkWrapNode = deform.shrinkWrapDeformer(nurbsToPoly, geoCombined) shrinkWrapNode.projection.set(4) shrinkWrapNode.targetSmoothLevel.set(ctrlSmooth) # delete history common.deleteHistory(nurbsToPoly) common.deleteHistory(dupliCtrl) pm.scale(dupliCtrl.cv[:], [scaleConstant, scaleConstant, scaleConstant]) copyShape(dupliCtrl, ctrl) pm.delete(adaptiveShapeBuildGrp)
def distribute(self, increment, bbox=False, *args, **kwargs): if not (self.curves and self.transformMesh): logger.info('No curves were saved, please excecute .saveObjects() before') return for curve in self.curves: currentCurvePos = 0.0 if increment >= curve.length(): logger.info('Increment value is higher than %s length' % curve) continue curveGrp = pm.createNode('transform', n='%sGrp' % curve) self.curveGroups.add(curveGrp) while currentCurvePos < 1.0: random.shuffle(self.transformMesh) # random items logger.debug('currentCurvePos value is: %s' % currentCurvePos) if bbox: currentCurvePos += self.boundingBoxObject(self.transformMesh[0])/curve.length() # validateChecks if currentCurvePos > 1: logger.debug('currentCurvePos value is bigger than 1: %s : %s' % (curve, currentCurvePos)) break if currentCurvePos <= 0: logger.warning('currentCurvePos is not incrementing its value: %s' % currentCurvePos) break # create duplicate obj trnfMesh = pm.duplicate(self.transformMesh[0])[0] logger.debug('trnsMesh is type: %s' % type(trnfMesh)) # group object and parent it in its respective curveGrp trnfGrp = pm.createNode('transform', n='%sOffset' % trnfMesh) motionPath = pm.PyNode(pm.pathAnimation(trnfGrp, c=curve, follow=True, followAxis='x', upAxis='y', fractionMode=True)) motionPath.setUStart(currentCurvePos) pm.parent(trnfGrp, curveGrp) # pm.disconnectAttr('%s_uValue.output' % motionPath, motionPath.uValue) pm.delete('%s_uValue' % str(motionPath)) # pos group and set transforms to zero pm.parent(trnfMesh, trnfGrp) trnfMesh.setTranslation((0,0,0), space='object') trnfMesh.setRotation((0,0,0)) self.randomizerItem(trnfMesh, *args, **kwargs) currentCurvePos += increment / curve.length() # this syntax type doesn't work on Int if bbox: currentCurvePos += self.boundingBoxObject(self.transformMesh[0]) / curve.length() # validateChecks if currentCurvePos > 1: logger.debug('currentCurvePos value is bigger than 1: %s : %s' % (curve, currentCurvePos)) break if currentCurvePos <= 0: logger.warning('currentCurvePos is not incrementing its value: %s' % currentCurvePos) break
def bdMultiMotionPath(crvPath, objects,interval=2,speed=20): numObjects = len(objects) startTime = pm.playbackOptions(q=1,minTime=1) endTime = pm.playbackOptions(q=1,maxTime=1) allMotionPath = [] for i in range(numObjects): #motionPath = pm.pathAnimation(objects[i],c=crvPath,n=objects[i].name() + '_mp',stu = i*interval , etu = i*interval + speed,follow = 1, followAxis = 'x', upAxis = 'y',fractionMode =1) pm.currentTime(0) motionPath = pm.pathAnimation(objects[i],c=crvPath,n=objects[i].name() + '_mp',follow = 1, followAxis = 'x', upAxis = 'y',fractionMode =1) allMotionPath.append(motionPath) pm.setAttr(motionPath + '.worldUpType',1) bdSetStartMp(allMotionPath) startCycleFrame = i*interval + speed + 2
def bdBuildMotionPathRbn(self): self.mpCrv = pm.ls(sl=1)[0] if self.mpType == 'closed': startU = self.bdFindStart() self.mpLength = pm.arclen(self.mpCrv) print self.mpLength # oriCrv = self.bdGetOriCrv(self.mpCrv) # bdGetUPos(oriCrv) allCtrlGrp = pm.group(name=self.mpCrv.name().replace('crv', 'loc_grp'), empty=1) allCtrlGrp.setScalePivot(self.mpCrv.boundingBox().center()) allCtrlGrp.setRotatePivot(self.mpCrv.boundingBox().center()) for i in range(0, self.numLocs, 1): ctrl = pm.circle( n=self.mpCrv.name().replace('crv', 'ctrl_' + str(i)))[0] ctrl.ry.set(90) ctrl.setScale([0.2, 0.2, 0.2]) ctrl.overrideEnabled.set(1) ctrl.overrideColor.set(18) pm.makeIdentity(ctrl, a=1) ctrlGrp = pm.group(name=ctrl.name() + '_grp') if self.mpType == 'closed': self.bdFindStart() if self.mpType == 'closed': uPos = startU + i / (self.numLocs * 1.0) else: uPos = startU + i / (self.numLocs - 1.0) if uPos > 1: uPos = uPos - 1 print uPos mp = pm.pathAnimation(ctrlGrp, c=self.mpCrv.name(), su=uPos, follow=1, followAxis='x', upAxis='y', worldUpType="vector") uAnimCrv = pm.listConnections('%s.uValue' % mp) pm.delete(uAnimCrv) pm.select(cl=1) jnt = pm.joint(n=ctrl.name().replace('ctrl', 'JNT')) pm.select(cl=1) pm.parent(jnt, ctrl) for axis in ['X', 'Y', 'Z']: jnt.attr('translate' + axis).set(0) pm.parent(ctrlGrp, allCtrlGrp)
def build(self): #build Trv self.guideTrv = pm.joint(p = [0,0,0],n = nameUtils.getUniqueName(self.side,self.baseName,'trv')) moPathName = nameUtils.getUniqueName(self.side,self.baseName,'MOP') moPathNode = pm.pathAnimation(self.guideCc,self.guideTrv,fractionMode = 1,follow = 1,followAxis = 'x',upAxis = 'y',worldUpType = 'vector', worldUpVector = [0,1,0],inverseUp = 0,inverseFront = 0,bank = 0,startTimeU = 1,endTimeU = 24,n = moPathName) pm.delete(moPathNode + '.uValue') # pm.disconnectAttr(moPathNode + '_uValue.output',moPathNode + '.uValue') #set Trv Loc: self.trvPosList = [] for num in range(0,self.segment): trvDis = num * (1 / float(self.segment-1)) pm.setAttr(moPathNode + '.uValue',trvDis) trvPos = self.guideTrv.getTranslation(space = 'world') self.trvPosList.append(trvPos) #set loc #set loc grp for i,p in enumerate(self.trvPosList): trvName = nameUtils.getUniqueName(self.side,self.baseName + 'Fk','gud') loc = pm.spaceLocator(n = trvName) loc.t.set(p) self.fkGuides.append(loc) loc.setParent(self.guideGrp) tempGuides = list(self.fkGuides) tempGuides.reverse() #set loc grp for i in range(len(tempGuides)): if i != (len(tempGuides) - 1): pm.parent(tempGuides[i],tempGuides[i + 1]) name = nameUtils.getUniqueName(self.side,self.baseName + '_Gud','grp') self.guideGrp = pm.group(em = 1,n = name) self.guideCc.setParent(self.guideGrp) self.fkGuides[0].setParent(self.guideGrp) self.guideTrv.setParent(self.guideGrp) self.guideGrp.v.set(0) self.__bodyCtrl() self.__fkJj() self.__ikJj() self.__squashStretch() self.__combine()
def bdMultiMotionPath(crvPath, objects, interval=2, speed=20): numObjects = len(objects) startTime = pm.playbackOptions(q=1, minTime=1) endTime = pm.playbackOptions(q=1, maxTime=1) allMotionPath = [] for i in range(numObjects): #motionPath = pm.pathAnimation(objects[i],c=crvPath,n=objects[i].name() + '_mp',stu = i*interval , etu = i*interval + speed,follow = 1, followAxis = 'x', upAxis = 'y',fractionMode =1) pm.currentTime(0) motionPath = pm.pathAnimation(objects[i], c=crvPath, n=objects[i].name() + '_mp', follow=1, followAxis='x', upAxis='y', fractionMode=1) allMotionPath.append(motionPath) pm.setAttr(motionPath + '.worldUpType', 1) bdSetStartMp(allMotionPath) startCycleFrame = i * interval + speed + 2
def buildPath(self): # After the user is done adding positions, they wil call the buildPath() method # it creates a curve with the list of positions as points. myPath = pm.curve(d=1, p=self.Points) # Now we'll constrain the car's root to the path and create a motion path animation motionPath = pm.pathAnimation(self.root, fractionMode=False, c=myPath, followAxis='z', upAxis='y', startTimeU=self.Times[0], endTimeU=self.Times[-1]) # go through all the positions and set keys in the motion path for k in self.Times: # reminder to self: k is the value, and not the index of the list # I will ask Python what is the index of that value and store it in a variable... n = self.Times.index(k) pm.setKeyframe( motionPath + '.uValue', v=n, t=k ) # 'n' is the Uvalue position that the motionPath should be keyed at
def bdBuildMotionPathRbn(self): self.mpCrv = pm.ls(sl=1)[0] if self.mpType == 'closed': startU = self.bdFindStart() self.mpLength = pm.arclen(self.mpCrv) print self.mpLength #oriCrv = self.bdGetOriCrv(self.mpCrv) #bdGetUPos(oriCrv) allCtrlGrp = pm.group(name = self.mpCrv.name().replace('crv','loc_grp'),empty=1) allCtrlGrp.setScalePivot(self.mpCrv.boundingBox().center()) allCtrlGrp.setRotatePivot(self.mpCrv.boundingBox().center()) for i in range(0,self.numLocs,1): ctrl = pm.circle(n=self.mpCrv.name().replace('crv','ctrl_' + str(i)))[0] ctrl.ry.set(90) ctrl.setScale([0.2,0.2,0.2]) ctrl.overrideEnabled.set(1) ctrl.overrideColor.set(18) pm.makeIdentity(ctrl,a=1) ctrlGrp = pm.group(name = ctrl.name() + '_grp') if self.mpType == 'closed': self.bdFindStart() if self.mpType == 'closed': uPos = startU + i/(self.numLocs*1.0) else: uPos = startU + i/(self.numLocs-1.0) if uPos > 1: uPos = uPos - 1 print uPos mp = pm.pathAnimation(ctrlGrp,c = self.mpCrv.name(),su = uPos,follow = 1,followAxis = 'x', upAxis='y',worldUpType="vector") uAnimCrv = pm.listConnections('%s.uValue'%mp) pm.delete(uAnimCrv) pm.select(cl=1) jnt = pm.joint(n=ctrl.name().replace('ctrl','JNT')) pm.select(cl=1) pm.parent(jnt,ctrl) for axis in ['X','Y','Z']: jnt.attr('translate'+axis).set(0) pm.parent(ctrlGrp,allCtrlGrp)
def setupCurve(self, cv, pointsNumber, sphereSize=0.1, offsetActive=False, locSize=0.1, jointRadius=0.1, follow=False): cvName = str(cv.name()).replace('_CRV', '') locatorList = [] for p in range(0, pointsNumber): # place locator locator = pm.spaceLocator(n=cvName + str(p + 1) + '_LOC') locator.localScaleX.set(locSize) locator.localScaleY.set(locSize) locator.localScaleZ.set(locSize) motionPath = pm.ls(pm.pathAnimation(locator, c=cv, f=follow))[0] self.deleteConnection(motionPath.u) motionPath.uValue.set(self.spacing * p) locatorList.append(locator) # place joint if offsetActive: jointOffset = pm.joint(n=cvName + 'Offset' + str(p + 1) + '_JNT', r=jointRadius) jointOffset.radius.set(jointRadius) pm.delete(pm.pointConstraint(locator, jointOffset)) joint = pm.joint(n=cvName + str(p + 1) + '_JNT', r=jointRadius) joint.radius.set(jointRadius) if not offsetActive: pm.delete(pm.pointConstraint(locator, joint)) # sphereObj = pm.sphere(r=sphereSize, axis=(0, 1, 0)) # sphereShape = pm.listRelatives(sphereObj, children=True, shapes=True) # pm.parent(sphereShape, joint, r=True, s=True) # pm.delete(sphereObj) locGrp = pm.group(locatorList, n=cvName + 'Loc_GRP', p=self.rigmodule.partsNoTransGrp) return locatorList
def generateFollowPlane(self, *args): startTime = pm.playbackOptions(q=1, min=1) endTime = pm.playbackOptions(q=1, max=1) sel_list = pm.ls(sl=1, ni=1, type="transform") if not sel_list: pm.confirmDialog(message='请选择物体', button=['确定']) return for sel in sel_list: # snapshot = pm.snapshot(sel,st=startTime,et=endTime)[1] snapshot = pm.createNode("snapshot") sel.selectHandle.connect(snapshot.localPosition) sel.worldMatrix[0].connect(snapshot.inputMatrix) snapshot.startTime.set(startTime) snapshot.endTime.set(endTime) snapshot.increment.set(1) anim_curve = pm.curve(n=sel + "_follow_curve", d=3, p=snapshot.pts.get()) pm.delete(snapshot) curve_length = pm.arclen(anim_curve, ch=0) plane, plane_node = pm.polyPlane(n=sel + "_follow_plane", sx=20, sy=3, w=curve_length, h=20) plane_grp = pm.group(plane, n=plane + "_grp") # NOTE 创建运动路径跟随 motion_path = pm.pathAnimation( plane_grp, anim_curve, fractionMode=1, follow=1, followAxis="x", upAxis="y", worldUpType="vector", worldUpVector=(0, 1, 0), inverseUp=0, inverseFront=0, bank=0, startTimeU=startTime, endTimeU=endTime, ) motion_path = pm.PyNode(motion_path) flow_node, ffd_node, lattice_node, ffd_base = pm.flow(plane_grp, dv=(100, 2, 2)) # NOTE 设置外部影响 ffd_node.outsideLattice.set(1) ffd_node.local.set(1) plane_node.width.set(50) lattice_node.v.set(0) ffd_base.v.set(0) # NOTE 设置 Parametric Length 匹配位置 motion_path.fractionMode.set(0) # NOTE 设置为 normal 朝向确保不会翻转 motion_path.worldUpType.set(4) animCurve = motion_path.listConnections(type="animCurve")[0] # NOTE 关键帧设置为线性 animCurve.setTangentTypes(range(animCurve.numKeys()), inTangentType="linear", outTangentType="linear") # NOTE 打组 pm.group(lattice_node, ffd_base, plane_grp, anim_curve, n=sel + "_follow_grp") pm.select(plane)
def squash_stretch_IK(*args): list_loc = pm.ls(sl=True) list_loc_number = len(list_loc) if pm.objExists('IK_spline_stretch_squash_bind_grp'): print 'group already exist' else: pm.group(em=True, n='IK_spline_stretch_squash_bind_grp', w=True) if pm.objExists('IK_spline_stretch_squash_IK_handle_grp'): print 'group already exist' else: pm.group(em=True, n='IK_spline_stretch_squash_IK_handle_grp', w=True) if pm.objExists('IK_spline_stretch_squash_curve_grp'): print 'group already exist' else: pm.group(em=True, n='IK_spline_stretch_squash_curve_grp', w=True) if pm.objExists('IK_spline_stretch_squash_loc_grp'): print 'group already exist' else: pm.group(em=True, n='IK_spline_stretch_squash_loc_grp', w=True) if pm.objExists('IK_spline_stretch_squash_joint_ctrl_grp'): print 'group already exist' else: pm.group(em=True, n='IK_spline_stretch_squash_joint_ctrl_grp', w=True) ''' Retreiving data entry ''' intFieldData_num_joint = pm.intField(intFieldEntry_num_joint, editable=True, query=True, value=True) textFieldData_ik_spline_name = pm.textField(textFieldEntry_ik_spline_name, editable=True, query=True, text=True) for loc_seq in range(1, list_loc_number + 1): if loc_seq == list_loc_number: print(list_loc[list_loc_number - 1]), 'is the final locator' pm.delete(list_loc[list_loc_number - 1]) break elif (intFieldData_num_joint % 2) > 0: print 'Input joint number is odd number' break else: if pm.objExists('{0}_{1}_IK_spline_loc_grp'.format( textFieldData_ik_spline_name, loc_seq)): print 'Naming error - system with same name exist' break else: pm.group(em=True, n='{0}_{1}_IK_spline_loc_grp'.format( textFieldData_ik_spline_name, loc_seq), w=True) pm.parent( '{0}_{1}_IK_spline_loc_grp'.format( textFieldData_ik_spline_name, loc_seq), 'IK_spline_stretch_squash_loc_grp') loc_first = list_loc[loc_seq - 1] loc_second = list_loc[loc_seq] loc_first_X = pm.getAttr(loc_first.translateX) loc_first_Y = pm.getAttr(loc_first.translateY) loc_first_Z = pm.getAttr(loc_first.translateZ) loc_second_X = pm.getAttr(loc_second.translateX) loc_second_Y = pm.getAttr(loc_second.translateY) loc_second_Z = pm.getAttr(loc_second.translateZ) loc_mid_tranX = loc_first_X + ((loc_second_X - loc_first_X) / 2) loc_mid_tranY = loc_first_Y + ((loc_second_Y - loc_first_Y) / 2) loc_mid_tranZ = loc_first_Z + ((loc_second_Z - loc_first_Z) / 2) loc_mid = pm.spaceLocator(n='{0}_{1}_02_trans_loc'.format( textFieldData_ik_spline_name, loc_seq)) pm.setAttr('{0}.tx'.format(loc_mid), (loc_mid_tranX)) pm.setAttr('{0}.ty'.format(loc_mid), (loc_mid_tranY)) pm.setAttr('{0}.tz'.format(loc_mid), (loc_mid_tranZ)) if loc_seq == 1: pm.rename( loc_first, '{0}_{1}_01_trans_loc'.format(textFieldData_ik_spline_name, loc_seq)) pm.rename( loc_second, '{0}_{1}_01_trans_loc'.format(textFieldData_ik_spline_name, loc_seq + 1)) else: pm.rename( loc_second, '{0}_{1}_01_trans_loc'.format(textFieldData_ik_spline_name, loc_seq + 1)) curve_path = pm.curve(d=1, p=[(loc_first_X, loc_first_Y, loc_first_Z), (loc_mid_tranX, loc_mid_tranY, loc_mid_tranZ), (loc_second_X, loc_second_Y, loc_second_Z) ]) ''' Method on reconstruct curve and rename ''' pm.rebuildCurve(curve_path, ch=1, rpo=1, rt=0, end=1, kr=0, kcp=0, kep=1, kt=0, s=intFieldData_num_joint, d=3, tol=0.0001) name_curve = pm.rename( curve_path, '{0}_{1}_ik_spline_curve'.format(textFieldData_ik_spline_name, loc_seq)) pre_joint = '' root_joint = '' for i in range(0, intFieldData_num_joint): user_default_unit = pm.currentUnit(query=True, linear=True) pm.currentUnit(linear='cm') pm.select(cl=True) new_joint = pm.joint() mot_path = pm.pathAnimation(new_joint, c=curve_path, fm=True) pm.cutKey(mot_path + '.u') pm.setAttr(mot_path + '.u', i * (1.0 / (intFieldData_num_joint - 1))) pm.delete('{0}.{1}'.format(new_joint, 'tx'), icn=True) pm.delete('{0}.{1}'.format(new_joint, 'ty'), icn=True) pm.delete('{0}.{1}'.format(new_joint, 'tz'), icn=True) pm.currentUnit(linear='{0}'.format(user_default_unit)) renaming_item = pm.ls(sl=True) if i == 0: pre_joint = new_joint root_joint = new_joint pm.rename( renaming_item, '{0}_{1}_{2:02d}_IK_spline_bind'.format( textFieldData_ik_spline_name, loc_seq, i + 1)) continue elif i == intFieldData_num_joint - 1: pm.rename( renaming_item, '{0}_{1}_{2:02d}_IK_spline_waste'.format( textFieldData_ik_spline_name, loc_seq, i + 1)) else: pm.rename( renaming_item, '{0}_{1}_{2:02d}_IK_spline_bind'.format( textFieldData_ik_spline_name, loc_seq, i + 1)) pm.parent(new_joint, pre_joint) pre_joint = new_joint pm.joint(root_joint, e=True, zso=True, oj='xyz', ch=True, sao='yup') stretch_squash_ik_handle = pm.ikHandle( sol='ikSplineSolver', pcv=False, ccv=False, c=curve_path, roc=True, ns=2, sj=('{0}_{1}_01_IK_spline_bind'.format( textFieldData_ik_spline_name, loc_seq)), ee=('{0}_{1}_{2:02d}_IK_spline_bind'.format( textFieldData_ik_spline_name, loc_seq, intFieldData_num_joint - 1)), n='{0}_{1}_IK_spline'.format(textFieldData_ik_spline_name, loc_seq)) pre_joint = '' root_joint = '' for i in range(0, 3): user_default_unit = pm.currentUnit(query=True, linear=True) pm.currentUnit(linear='cm') pm.select(cl=True) new_joint = pm.joint() mot_path = pm.pathAnimation(new_joint, c=curve_path, fm=True) pm.cutKey(mot_path + '.u') pm.setAttr(mot_path + '.u', i * (1.0 / 2)) pm.delete('{0}.{1}'.format(new_joint, 'tx'), icn=True) pm.delete('{0}.{1}'.format(new_joint, 'ty'), icn=True) pm.delete('{0}.{1}'.format(new_joint, 'tz'), icn=True) pm.currentUnit(linear='{0}'.format(user_default_unit)) renaming_item = pm.ls(sl=True) if i == 0: pre_joint = new_joint root_joint = new_joint pm.rename( renaming_item, '{0}_{1}_{2:02d}_IK_spline_joint_ctrl'.format( textFieldData_ik_spline_name, loc_seq, i + 1)) else: pm.rename( renaming_item, '{0}_{1}_{2:02d}_IK_spline_joint_ctrl'.format( textFieldData_ik_spline_name, loc_seq, i + 1)) for n in renaming_item: pm.group(em=True, name='empty') pm.parent('empty', n) pm.setAttr('empty.translateX', 0) pm.setAttr('empty.translateY', 0) pm.setAttr('empty.translateZ', 0) pm.setAttr('empty.rotateX', 0) pm.setAttr('empty.rotateY', 0) pm.setAttr('empty.rotateZ', 0) pm.parent('empty', world=True) pm.parent(n, 'empty') for n in renaming_item: newname = n.split('_') number_name = len(newname) new_name_first = newname[0] + '_' for i in range(0, number_name): if i > number_name - 3 or i == number_name - 3: new_name = new_name_first print 'naming error' break else: if i < number_name - 3: new_name_second = newname[i + 1] + '_' new_name = new_name_first + new_name_second new_name_first = new_name else: break pm.rename('empty', new_name + 'joint_ctrl_pad') stretch_squash_joint_ctrl_grp = pm.group( '{0}_{1}_01_IK_spline_joint_ctrl_pad'.format( textFieldData_ik_spline_name, loc_seq), '{0}_{1}_02_IK_spline_joint_ctrl_pad'.format( textFieldData_ik_spline_name, loc_seq), '{0}_{1}_03_IK_spline_joint_ctrl_pad'.format( textFieldData_ik_spline_name, loc_seq), n='{0}_{1}_IK_spline_joint_ctrl_grp'.format( textFieldData_ik_spline_name, loc_seq)) loc_first_rot = pm.duplicate(loc_first, n='{0}_{1}_01_rot_loc'.format( textFieldData_ik_spline_name, loc_seq)) loc_mid_rot = pm.duplicate(loc_mid, n='{0}_{1}_02_rot_loc'.format( textFieldData_ik_spline_name, loc_seq)) loc_second_trans = pm.duplicate(loc_second, n='{0}_{1}_03_trans_loc'.format( textFieldData_ik_spline_name, loc_seq)) loc_second_rot = pm.duplicate(loc_second, n='{0}_{1}_03_rot_loc'.format( textFieldData_ik_spline_name, loc_seq)) pm.parent(loc_first_rot, loc_first) pm.parent(loc_mid_rot, loc_mid) pm.parent(loc_second_rot, loc_second_trans[0]) pm.select(loc_first, loc_mid, loc_second_trans[0]) list_loc_trans = pm.ls(sl=True) number_loc_trans = len(list_loc_trans) for n in list_loc_trans: pm.group(em=True, name='empty') pm.parent('empty', n) pm.setAttr('empty.translateX', 0) pm.setAttr('empty.translateY', 0) pm.setAttr('empty.translateZ', 0) pm.setAttr('empty.rotateX', 0) pm.setAttr('empty.rotateY', 0) pm.setAttr('empty.rotateZ', 0) pm.parent('empty', world=True) pm.parent(n, 'empty') newname = n.split('_') number_name = len(newname) new_name_first = newname[0] + '_' for i in range(0, number_name): if i > number_name - 1 or i == number_name - 1: new_name = new_name_first print 'naming error' break else: if i < number_name - 1: new_name_second = newname[i + 1] + '_' new_name = new_name_first + new_name_second new_name_first = new_name else: break pm.rename('empty', new_name + 'pad') pm.parent( '{0}_{1}_01_trans_loc_pad'.format(textFieldData_ik_spline_name, loc_seq), '{0}_{1}_02_trans_loc_pad'.format(textFieldData_ik_spline_name, loc_seq), '{0}_{1}_03_trans_loc_pad'.format(textFieldData_ik_spline_name, loc_seq), '{0}_{1}_IK_spline_loc_grp'.format( textFieldData_ik_spline_name, loc_seq)) pm.aimConstraint(loc_first, loc_mid_rot) pm.aimConstraint(loc_mid, loc_first_rot) pm.aimConstraint(loc_mid, loc_second_rot) pm.pointConstraint(loc_first, loc_second_trans[0], (loc_mid + '_pad')) pm.pointConstraint(loc_first, '{0}_{1}_01_IK_spline_joint_ctrl'.format( textFieldData_ik_spline_name, loc_seq), mo=True) pm.pointConstraint(loc_mid, '{0}_{1}_02_IK_spline_joint_ctrl'.format( textFieldData_ik_spline_name, loc_seq), mo=True) pm.pointConstraint(loc_second_trans[0], '{0}_{1}_03_IK_spline_joint_ctrl'.format( textFieldData_ik_spline_name, loc_seq), mo=True) pm.orientConstraint(loc_first_rot, '{0}_{1}_01_IK_spline_joint_ctrl'.format( textFieldData_ik_spline_name, loc_seq), mo=True) pm.orientConstraint(loc_mid_rot, '{0}_{1}_02_IK_spline_joint_ctrl'.format( textFieldData_ik_spline_name, loc_seq), mo=True) pm.orientConstraint(loc_second_rot, '{0}_{1}_03_IK_spline_joint_ctrl'.format( textFieldData_ik_spline_name, loc_seq), mo=True) curve_length_node = pm.createNode('curveInfo', n='{0}curve_length_{1}'.format( new_name, loc_seq)) pm.connectAttr('{0}.worldSpace[0]'.format(curve_path), '{0}.inputCurve'.format(curve_length_node)) curve_arc_length = pm.getAttr( '{0}.arcLength'.format(curve_length_node)) ratio_curve_stretch = pm.createNode( 'multiplyDivide', n='{0}ratio_curve_stretch_{1}'.format(new_name, loc_seq)) pm.setAttr('{0}.operation'.format(ratio_curve_stretch), 2) pm.connectAttr('{0}.arcLength'.format(curve_length_node), '{0}.input1X'.format(ratio_curve_stretch)) pm.setAttr('{0}.input2X'.format(ratio_curve_stretch), curve_arc_length) ratio_curve_squash = pm.createNode( 'multiplyDivide', n='{0}ratio_curve_squash_{1}'.format(new_name, loc_seq)) pm.setAttr('{0}.operation'.format(ratio_curve_squash), 2) pm.connectAttr('{0}.arcLength'.format(curve_length_node), '{0}.input2X'.format(ratio_curve_squash)) pm.setAttr('{0}.input1X'.format(ratio_curve_squash), curve_arc_length) exp_squash = pm.createNode('multiplyDivide', n='{0}exp_squash_{1}'.format( new_name, loc_seq)) pm.setAttr('{0}.operation'.format(exp_squash), 2) pm.setAttr('{0}.input2X'.format(exp_squash), intFieldData_num_joint - 1) for number_joint in range(0, intFieldData_num_joint - 1): pm.connectAttr( '{0}.outputX'.format(ratio_curve_stretch), '{0}_{1}_{2:02d}_IK_spline_bind.scaleX'.format( textFieldData_ik_spline_name, loc_seq, number_joint + 1)) exp_squash_plus = pm.createNode( 'plusMinusAverage', n='{0}exp_squash_plus_0{1}_{2}'.format( new_name, number_joint + 1, loc_seq)) pm.setAttr('{0}.input1D[0]'.format(exp_squash_plus), 1) if number_joint < (intFieldData_num_joint / 2): pm.setAttr('{0}.operation'.format(exp_squash_plus), 1) else: pm.setAttr('{0}.operation'.format(exp_squash_plus), 2) if number_joint == 0: print 'do nothing' elif number_joint > 0: pm.connectAttr('{0}.outputX'.format(exp_squash), '{0}.input1D[1]'.format(exp_squash_plus)) pm.connectAttr( '{0}exp_squash_plus_0{1}_{2}.output1D'.format( new_name, number_joint, loc_seq), '{0}.input1D[0]'.format(exp_squash_plus)) power_curve_squash = pm.createNode( 'multiplyDivide', n='{0}power_curve_squash_0{1}_{2}'.format( new_name, number_joint + 1, loc_seq)) pm.setAttr('{0}.operation'.format(power_curve_squash), 3) pm.connectAttr('{0}.outputX'.format(ratio_curve_squash), '{0}.input1X'.format(power_curve_squash)) pm.connectAttr('{0}.output1D'.format(exp_squash_plus), '{0}.input2X'.format(power_curve_squash)) pm.connectAttr( '{0}.outputX'.format(power_curve_squash), '{0}_{1}_{2:02d}_IK_spline_bind.scaleY'.format( textFieldData_ik_spline_name, loc_seq, number_joint + 1)) pm.connectAttr( '{0}.outputX'.format(power_curve_squash), '{0}_{1}_{2:02d}_IK_spline_bind.scaleZ'.format( textFieldData_ik_spline_name, loc_seq, number_joint + 1)) pm.skinCluster( '{0}_{1}_01_IK_spline_joint_ctrl'.format( textFieldData_ik_spline_name, loc_seq), '{0}_{1}_02_IK_spline_joint_ctrl'.format( textFieldData_ik_spline_name, loc_seq), '{0}_{1}_03_IK_spline_joint_ctrl'.format( textFieldData_ik_spline_name, loc_seq), '{0}_{1}_ik_spline_curve'.format(textFieldData_ik_spline_name, loc_seq)) pm.parent(curve_path, 'IK_spline_stretch_squash_curve_grp') pm.parent( '{0}_{1}_01_IK_spline_bind'.format( textFieldData_ik_spline_name, loc_seq), 'IK_spline_stretch_squash_bind_grp') pm.parent( '{0}_{1}_IK_spline'.format(textFieldData_ik_spline_name, loc_seq), 'IK_spline_stretch_squash_IK_handle_grp') pm.parent(stretch_squash_joint_ctrl_grp, 'IK_spline_stretch_squash_joint_ctrl_grp')
def makeHairMesh(name="HairMesh#", mat="", cSet="hairCrease", reverse=False, lengthDivs=7, widthDivs=4, Segments=4, width=1, curveDel=False, cShape='triangle'): '''Create a Hair Tube From Select Curve line or Edge or IsoPram''' sel = pm.selected() if not sel: print "Select some Curves or Edges or isopram" return if type(sel[0]) == pm.general.MeshEdge: pm.runtime.CreateCurveFromPoly() pathTransform = pm.selected()[0] elif type(sel[0]) == pm.general.NurbsSurfaceIsoparm: pm.runtime.DuplicateCurve() pathTransform = pm.selected()[0] pathTransform = [ t for t in pm.selected() if type(t) == pm.nodetypes.Transform ] pm.select(pathTransform, r=1) pathShape = pm.listRelatives(shapes=True) if type(pathShape[0]) == pm.nodetypes.NurbsCurve: minscale = [0.001, 0.001, 0.001] pathCurve = [(i, pathShape[pathTransform.index(i)]) for i in pathTransform] if pm.objExists("HairBaseProfileCurve"): profileCurve = pm.ls("HairBaseProfileCurve")[0] #print profileCurve.listRelatives()[0].listConnections()[0] profileCurve.listRelatives()[0].listConnections()[0].setRadius( width) pm.showHidden(profileCurve, a=1) else: shapeType = { 'circle': (3, 8), 'triangle': (1, 3), 'square': (1, 4) } profileCurve = pm.circle(c=(0, 0, 0), nr=(0, 1, 0), sw=360, r=width, d=shapeType[cShape][0], ut=0, tol=5.77201e-008, s=shapeType[cShape][1], ch=1, name="HairBaseProfileCurve") for a in [('overrideEnabled', 1), ('overrideRGBColors', 1), ('overrideColorRGB', (0.2, 0.5, 0.2))]: profileCurve[0].getShape().attr(a[0]).set(a[1]) pm.select(d=1) for crv in pathCurve: print crv pm.rebuildCurve(crv[0], kep=1) if reverse: pm.reverseCurve(crv[0]) #profileInstance = instance(profileCurve,n="pCrv_instance"+string(pathCurve.index(crv))) if pm.objExists("HairCtrlGroup"): hairOncsGroup = pm.ls("HairCtrlGroup")[0] else: hairOncsGroup = pm.group(name="HairCtrlGroup") #pm.parent(hairOncGroup,crv[0]) mPath = pm.pathAnimation(profileCurve, crv[0], fa='y', ua='x', stu=1, etu=Segments * 10, b=1) HairProfile = [] hairOncGroup = pm.group(name="HairCtrls#") pm.parent(hairOncGroup, hairOncsGroup, r=1) for u in range(Segments + 1): pm.currentTime(u * 10) profileInstance = pm.duplicate(profileCurve, n=(crv[0] + "HairProFileCrv_" + str(u)), rr=1)[0] pm.parent(profileInstance, hairOncGroup, r=1) HairProfile.append(profileInstance) if u == 0 or u == Segments: pm.scale(profileInstance, minscale, a=1, os=1) HairMesh = createHairMesh(HairProfile, name=name, cSet=cSet, mat=mat, lengthDivs=lengthDivs, widthDivs=widthDivs) pm.rename(hairOncGroup, hairOncGroup.name() + HairMesh[0].name()) pm.delete(profileCurve, mp=1) pm.delete(profileCurve) pm.xform(hairOncsGroup, ws=1, piv=pm.xform(hairOncsGroup.getChildren()[-1], q=1, ws=1, piv=1)[:3]) if curveDel: pm.delete(pathTransform, hi=1)
def makeTreads(*args): try: if ('world_object_up' ): # if locator exists from a previous attempt, delete it pm.delete('world_object_up') pm.spaceLocator(name='world_object_up') pm.addAttr(ln="Tread_Cycle", at='double', dv=0, hidden=False, k=True) pm.select(clear=True) pm.parentConstraint('treadCurve', 'world_object_up') except: pm.spaceLocator(name='world_object_up') # or else just create it pm.addAttr(ln="Tread_Cycle", at='double', dv=0, hidden=False, k=True) pm.select(clear=True) pm.parentConstraint('treadCurve', 'world_object_up') try: for j in treadJnts: # if motionPaths exist from a previous attempt, delete them if ('motionPath' + str(treadJnts.index(j) + 1)): pm.delete('motionPath' + str(treadJnts.index(j) + 1)) except: pass # get the Max Value of the curve, so the treads loop properly curveMaxValue = pm.getAttr('treadCurve.maxValue') print curveMaxValue # this loop will go through each joint in the treadJnts list for i in treadJnts: # for the first joint, which has index '0' if treadJnts.index(str(i)) == 0: # select the first joint and then the curve pm.select(clear=True) pm.select(i) pm.select('treadCurve', add=True) # constrain the first joint to the curve using motion path animation pm.pathAnimation(fractionMode=False, follow=True, followAxis='y', upAxis='z', worldUpType='object', worldUpObject='world_object_up', inverseUp=True, inverseFront=False, bank=False) # delete useless nodes we're not gonna need pm.delete('addDoubleLinear1', 'addDoubleLinear2', 'addDoubleLinear3', 'motionPath1_uValue') # connect motionPath allCoordinates node into the joint's translates pm.connectAttr('motionPath1.allCoordinates', str(i) + '.translate', force=True) # set driven keys for the anim curve driving the joints around the curve pm.setAttr('world_object_up.Tread_Cycle', 0) pm.setAttr('motionPath1.uValue', 0) pm.setDrivenKeyframe('motionPath1.uValue', currentDriver='world_object_up.Tread_Cycle') pm.setAttr('world_object_up.Tread_Cycle', curveMaxValue) pm.setAttr('motionPath1.uValue', curveMaxValue) pm.setDrivenKeyframe('motionPath1.uValue', currentDriver='world_object_up.Tread_Cycle') pm.selectKey('motionPath1.uValue') pm.keyTangent(itt='linear', ott='linear') # make them linear and cycle pm.setInfinity(pri='cycle', poi='cycle') pm.select(clear=True) pm.rename( 'motionPath1_uValue', 'setDrivenKeys_anim_1' ) # rename it to something with number at the end, easier to work with if it's duplicated # for the rest of the joints: else: # constrain the joint to the curve using motion path animation pm.select(clear=True) pm.select(i) pm.select('treadCurve', add=True) pm.pathAnimation(fractionMode=False, follow=True, followAxis='y', upAxis='z', worldUpType='object', worldUpObject='world_object_up', inverseUp=True, inverseFront=False, bank=False) pm.select(clear=True) # delete useless nodes we're not gonna need pm.delete('addDoubleLinear1', 'addDoubleLinear2', 'addDoubleLinear3', 'motionPath' + str(treadJnts.index(i) + 1) + '_uValue') # connect motionPath allCoordinates node into joint's translates pm.connectAttr('motionPath' + str(treadJnts.index(i) + 1) + '.allCoordinates', str(i) + '.translate', force=True) pm.select(clear=True) # duplicate the previous set driven keys anim curve pm.select('setDrivenKeys_anim_' + str(treadJnts.index(i))) pm.duplicate() pm.select(clear=True) # connect the new duplicated setDrivenKeys anim's output into the joint's motionPath's uValue pm.connectAttr('setDrivenKeys_anim_' + str(treadJnts.index(i) + 1) + '.output', 'motionPath' + str(treadJnts.index(i) + 1) + '.uValue', force=True) # connect the animation curve to the Tread Cycle attribute pm.connectAttr('world_object_up.Tread_Cycle', 'setDrivenKeys_anim_' + str(treadJnts.index(i) + 1) + '.input', force=True) # shift the animation curve to the side so the treads won't be on top of each other and move accordingly pm.select('setDrivenKeys_anim_' + str(treadJnts.index(i) + 1)) pm.selectKey() num = spaceInput.getValue1() # get the spacing the user wants pm.keyframe(option='over', relative=True, floatChange=(num)) pm.select(clear=True)
import pymel.core as pm for cls in pm.selected(): loc = pm.duplicate('temp', name = cls.name().replace("_cluster", "_control"))[0] pm.delete(pm.pointConstraint(cls, loc)) adj = pm.group(empty=True, name="adj_%s" %loc.name()) pm.delete(pm.parentConstraint(loc, adj)) #pm.parent(cls, loc) loc.translate >> cls.translate loc.rotate >> cls.rotate loc.scale >> cls.scale pm.parent(loc, adj) for obj in pm.selected(): pm.pathAnimation(obj, c='motion_path_guide_curve', fractionMode=True, follow=True , followAxis='z' ,upAxis='y', worldUpType="vector", worldUpVector=[0,1,0], inverseUp=False, inverseFront=False, bank=False, startTimeU=1, endTimeU=100) for i in range(0,5): motionPathNode = pm.PyNode('motionPath%d'%(i+1)) motionPathNode.uValue.set(i*0.0002) for i in range(1,21): ref = pm.PyNode("temp_%02d"%i) ctrl = pm.PyNode("motion_path_guide_control_%02d"%i) pm.delete(pm.pointConstraint(ref, ctrl, mo=False)) for cls in pm.selected(): ctrl = pm.PyNode(cls.name().replace("_cluster", "_control")) ctrl.translate >> cls.translate ctrl.rotate >> cls.rotate
def createJointsOnCurve(steps): selectedCurve = pm.ls(sl=True) for t in range(0,steps): newJoint = pm.joint(p=(0,0,0)) pm.pathAnimation(newJoint, c=selectedCurve[0], su=(2/steps)*t)
def motionPath_setup(self): pos = [] self._MODEL.getJoints = [ pm.joint(rad=self._MODEL.radius) for x in range(self._MODEL.interval) ] for _joint in self._MODEL.getJoints: pm.parent(_joint, w=True) adb.makeroot_func(_joint) double_linears_nodes = [] _motionPathNode = pm.pathAnimation(self._MODEL.curve, _joint.getParent(), upAxis='y', fractionMode=True, worldUpType="vector", inverseUp=False, inverseFront=False, follow=True, bank=False, followAxis='x', worldUpVector=(0, 1, 0)) ## Delete double Linear nodes for axis in 'xyz': double_linear = pm.listConnections( _motionPathNode + '.{}Coordinate'.format(axis))[0] double_linears_nodes.append(double_linear) pm.delete(double_linears_nodes) for axis in 'xyz': pm.cycleCheck(e=1) pm.connectAttr('{}.{}Coordinate'.format(_motionPathNode, axis), '{}.t{}'.format(_joint.getParent(), axis), f=1) self._MODEL.motionPaths.append(_motionPathNode) # New interval value for the Function Nintervalls = self._MODEL.interval - 1 for i in range(0, Nintervalls): factor = 1 / float((Nintervalls)) oPos = factor * i pos.append(oPos) pos.append(1) for oPosition, oMotionPath in zip(pos, self._MODEL.motionPaths): pm.PyNode(oMotionPath).uValue.set(oPosition) _dup = pm.duplicate(self._MODEL.getJoints[-1]) # delete animation for path in self._MODEL.motionPaths: pm.cutKey(path) for joint in self._MODEL.getJoints: joint.jointOrient.set(0, 0, 0) joint.translate.set(0, 0, 0) pm.select(None) # Cleaning the scene pm.delete(_dup)
def node_base(self, *nodes, **kwargs): super(MotionPath, self).node_base(*nodes, **kwargs) """ creates a motion path on the provided nodes and attaches them to a curve you can control the up vector, and make it one object, or a list of objects one for each Node List :param nodes: list of nodes that will constraint to the path :param curve: curve that will have the nodes :param UpVectorType: type of UpVector, can be object, array, anything else will be assumed as scene :param UpVectorArray: the array of objects that will be the upVector :param upVectorObject: the object that will be upVector :return: """ motion_path_list = [] if 'curve' in kwargs.keys(): self.curve = dataValidators.as_pymel_nodes(kwargs.pop('curve')) name = kwargs.pop('name', 'motionPath') followAxis = kwargs.pop('followAxis', config.axis_order[0]) upAxis = kwargs.pop('upAxis', config.axis_order[1]) kwargs['followAxis'] = followAxis kwargs['upAxis'] = upAxis UpVectorType = kwargs.pop('UpVectorType', 'world') UpVectorArray = kwargs.pop('UpVectorArray', None) upVectorObject = kwargs.pop('upVectorObject', None) if self.curve: len_node_list = len(nodes) spans = pm.getAttr(self.curve + ".spans") min_value = pm.getAttr(self.curve + ".minValue") max_value = pm.getAttr(self.curve + ".maxValue") form = pm.getAttr(self.curve + ".form") step = 0.0 if len_node_list > 1: if form == 0 or form == 1: step = (max_value - min_value) / (len_node_list - 1) else: step = (max_value - min_value) / len_node_list else: step = 0 node_count = 0 for each_node in nodes: if UpVectorType == 'object': motion_path_node = pm.pathAnimation( each_node, c=self.curve, follow=True, worldUpObject=upVectorObject, worldUpType="objectrotation", **kwargs) elif UpVectorType == 'array': motion_path_node = pm.pathAnimation( each_node, c=self.curve, follow=True, worldUpObject=UpVectorArray[node_count], worldUpType="object", **kwargs) else: motion_path_node = pm.pathAnimation(each_node, c=self.curve, follow=True, worldUpType="scene", **kwargs) motion_path_node = dataValidators.as_pymel_nodes( motion_path_node) motion_path_list.append(motion_path_node) list_add_double_linear = each_node.listConnections( type='addDoubleLinear', source=False) pm.delete(list_add_double_linear) motion_path_node.xCoordinate >> each_node.translateX motion_path_node.yCoordinate >> each_node.translateY motion_path_node.zCoordinate >> each_node.translateZ connection = pm.listConnections(motion_path_node.uValue) if connection: pm.delete(connection) motion_path_node.uValue.set(step * node_count) # pm.setKeyframe(motionPath, v=(step * nodeCount), at="uValue") self.name_convention.rename_name_in_format( str(motion_path_node), name=name) node_count += 1 value = pm.currentTime(q=True) pm.currentTime(value + 1, e=True) pm.currentTime(value, e=True) if len(motion_path_list) == 1: return motion_path_list[0] return motion_path_list
def run(): # channel lists tAttr = ['translateX', 'translateY', 'translateZ'] rAttr = ['rotateX', 'rotateY', 'rotateZ'] sAttr = ['scaleX', 'scaleY', 'scaleZ'] selection = pm.ls(selection=True) if not selection: cmds.error('Select desired object first') return selectedNode = selection[0] bbox_xMin, bbox_yMin, bbox_zMin, bbox_xMax, bbox_yMax, bbox_zMax = pm.exactWorldBoundingBox(selectedNode) center_x = (bbox_xMax + bbox_xMin) / 2.0 center_y = (bbox_yMax + bbox_yMin) / 2.0 center_z = (bbox_zMax + bbox_zMin) / 2.0 obj_width = max(abs(bbox_xMax - bbox_xMin), abs(bbox_zMax - bbox_zMin)) obj_height = abs(bbox_yMax - bbox_yMin) nurbCircleNode, makeNurbCircleNode = pm.circle(name='camera_path1', normalX=0, normalY=1, normalZ=0) revolvingCamGroupNode = pm.group(name='revolvingCam_group1', empty=True) aimLocator = pm.spaceLocator(name='aim_locator1') cameraParentLocator = pm.spaceLocator(name='camera_parent_locator1') cameraLocator = pm.spaceLocator(name='camera_locator1') revolvingCameraXformNode, revolvingCameraShapeNode = pm.camera(name='revolving_camera1') filmFitType = revolvingCameraShapeNode.getAttr('filmFit') camHFOV, camVFOV = getRenderFOVs(revolvingCameraShapeNode, filmFitType) circleScale = max(getDistanceFromWidth(obj_width, camHFOV), getDistanceFromHeight(obj_height, camVFOV)) nurbCircleNode.setScale(scale=(circleScale,circleScale,circleScale)) pm.makeIdentity(nurbCircleNode, apply=True) pm.move(0.0, 0.0, -10.0, aimLocator, absolute=True) pm.parent(nurbCircleNode, revolvingCamGroupNode) pm.parent(aimLocator, nurbCircleNode) pm.parent(cameraParentLocator, revolvingCamGroupNode) pm.parent(cameraLocator, cameraParentLocator) pm.parent(revolvingCameraXformNode, cameraLocator) nurbCircleNode.addAttr('revolutions', attributeType='double', defaultValue=1.0) nurbCircleNode.setAttr('revolutions', channelBox=True) for attr in list(tAttr+rAttr+sAttr): revolvingCamGroupNode.attr(attr).lock() aimConstraint = pm.aimConstraint(aimLocator, cameraLocator, aimVector=(0.0,0.0,-1.0)) pm.move(0.0, 0.0, 0.0, aimLocator, absolute=True) motionPathNodeName = pm.pathAnimation(cameraParentLocator, curve=nurbCircleNode, name='camera_motion_path1', fractionMode=True, follow=True, followAxis='x', upAxis='y', worldUpType='vector', worldUpVector=[0.0,1.0,0.0], inverseUp=False, inverseFront=False, bank=False, startTimeU=pm.playbackOptions(query=True, minTime=True), endTimeU=pm.playbackOptions(query=True, maxTime=True)) motionPathNode = pm.ls(motionPathNodeName)[0] motionPathAnimCurveNode = motionPathNode.listConnections(source=True, destination=False, connections=False, type=pm.nodetypes.AnimCurveTL)[0] motionPathAnimCurveNode.setPreInfinityType(infinityType='cycle') motionPathAnimCurveNode.setPostInfinityType(infinityType='cycle') expressionString = 'global proc setRevolutionSpeed()\n\n' \ '{{\n\n' \ 'float $endFrame = `playbackOptions -query -maxTime`;\n' \ 'float $result = $endFrame / `getAttr {circleNode}.revolutions`;\n' \ 'print $result;\n' \ 'keyframe -option over -index 1 -absolute -timeChange $result {animCurveNode} ;\n\n' \ 'print "\\n";\n\n' \ '}}\n\n' \ 'scriptJob -attributeChange "{circleNode}.revolutions" "setRevolutionSpeed()";'.format(circleNode=nurbCircleNode.fullPath(), animCurveNode=motionPathAnimCurveNode.__str__()) expressionNode = pm.expression(name='revolutionExpression1', string=expressionString, object=nurbCircleNode, alwaysEvaluate=True, unitConversion='all') pm.move(center_x, center_y, center_z, nurbCircleNode, absolute=True)
def joint_on_curve(self): if self.jnt_checkbx.checkState( ) == QtCore.Qt.Unchecked and self.curve_checkbx.checkState( ) == QtCore.Qt.Unchecked: curveSel = pm.selected()[0] self.RadiusJnt = float(self.slider_jnt_rad_LineEdit.text()) self.Naming = self.name_LineEdit.text() self.interval = int(self.slider_int_LineEdit.text()) self.curve = pm.selected() self.all_jnts = [] self.all_motionPath = [] self.Pos = [] for i in range(int(self.interval)): _joint = pm.joint(rad=self.RadiusJnt, n=str(self.Naming)) pm.parent(_joint, w=True) self.all_jnts.append(_joint) _motionPathNode = pm.pathAnimation(self.curve, _joint, upAxis='y', fractionMode=True, worldUpType="vector", inverseUp=False, inverseFront=False, follow=True, bank=False, followAxis='x', worldUpVector=(0, 1, 0)) self.all_motionPath.append(_motionPathNode) # New interval value for the Function Nintervalls = int(self.interval) - 1 for i in range(0, Nintervalls): factor = 1 / float((Nintervalls)) oPos = factor * i self.Pos.append(oPos) self.Pos.append(1) for oPosition, oMotionPath in zip(self.Pos, self.all_motionPath): pm.PyNode(oMotionPath).uValue.set(oPosition) _dup = pm.duplicate(self.all_jnts[-1]) # delete animation for path in self.all_motionPath: _motion_uvalue_node = [ x for x in pm.listConnections(path + '.uValue', s=1) ] pm.delete(_motion_uvalue_node) pm.select(None) # Cleaning the scene pm.delete(_dup) pm.delete(self.all_motionPath) for joint in self.all_jnts: joint.jointOrientX.set(0) joint.jointOrientY.set(0) joint.jointOrientZ.set(0) joint.rx.set(0) joint.ry.set(0) joint.rz.set(0) if self.jnt_checkbx.checkState( ) == QtCore.Qt.Checked and self.curve_checkbx.checkState( ) == QtCore.Qt.Unchecked: curveSel = pm.selected()[0] self.RadiusJnt = float(self.slider_jnt_rad_LineEdit.text()) self.Naming = self.name_LineEdit.text() self.interval = int(self.slider_int_LineEdit.text()) self.curve = pm.selected() self.all_jnts = [] self.all_motionPath = [] self.Pos = [] for i in range(int(self.interval)): _joint = pm.joint(rad=self.RadiusJnt, n=str(self.Naming)) pm.parent(_joint, w=True) self.all_jnts.append(_joint) _motionPathNode = pm.pathAnimation(self.curve, _joint, upAxis='y', fractionMode=True, worldUpType="vector", inverseUp=False, inverseFront=False, follow=True, bank=False, followAxis='x', worldUpVector=(0, 1, 0)) self.all_motionPath.append(_motionPathNode) # New interval value for the Function Nintervalls = int(self.interval) - 1 for i in range(0, Nintervalls): factor = 1 / float((Nintervalls)) oPos = factor * i self.Pos.append(oPos) self.Pos.append(1) for oPosition, oMotionPath in zip(self.Pos, self.all_motionPath): pm.PyNode(oMotionPath).uValue.set(oPosition) _dup = pm.duplicate(self.all_jnts[-1]) # delete animation for path in self.all_motionPath: _motion_uvalue_node = [ x for x in pm.listConnections(path + '.uValue', s=1) ] pm.delete(_motion_uvalue_node) pm.select(None) # Cleaning the scene pm.delete(_dup) pm.delete(self.all_motionPath) # OPTIONAL if we want the joints to be chained pm.select(self.all_jnts[:]) for oParent, oChild in zip(pm.selected()[0:-1], pm.selected()[1:]): pm.parent(oChild, None) pm.parent(oChild, oParent) if self.jnt_checkbx.checkState( ) == QtCore.Qt.Unchecked and self.curve_checkbx.checkState( ) == QtCore.Qt.Checked: curveSel = pm.selected()[0] self.RadiusJnt = float(self.slider_jnt_rad_LineEdit.text()) self.Naming = self.name_LineEdit.text() self.interval = int(self.slider_int_LineEdit.text()) self.curve = pm.selected() self.all_jnts = [] self.all_motionPath = [] self.Pos = [] for i in range(int(self.interval)): _joint = pm.joint(rad=self.RadiusJnt, n=str(self.Naming)) pm.parent(_joint, w=True) self.all_jnts.append(_joint) _motionPathNode = pm.pathAnimation(self.curve, _joint, upAxis='y', fractionMode=True, worldUpType="vector", inverseUp=False, inverseFront=False, follow=True, bank=False, followAxis='x', worldUpVector=(0, 1, 0)) self.all_motionPath.append(_motionPathNode) # New interval value for the Function Nintervalls = int(self.interval) - 1 for i in range(0, Nintervalls): factor = 1 / float((Nintervalls)) oPos = factor * i self.Pos.append(oPos) self.Pos.append(1) for oPosition, oMotionPath in zip(self.Pos, self.all_motionPath): pm.PyNode(oMotionPath).uValue.set(oPosition) _dup = pm.duplicate(self.all_jnts[-1]) # delete animation for path in self.all_motionPath: _motion_uvalue_node = [ x for x in pm.listConnections(path + '.uValue', s=1) ] pm.delete(_motion_uvalue_node) pm.select(None) # Cleaning the scene pm.delete(_dup) pm.delete(self.all_motionPath) pm.delete(curveSel) for joint in self.all_jnts: joint.jointOrientX.set(0) joint.jointOrientY.set(0) joint.jointOrientZ.set(0) joint.rx.set(0) joint.ry.set(0) joint.rz.set(0) if self.jnt_checkbx.checkState( ) == QtCore.Qt.Checked and self.curve_checkbx.checkState( ) == QtCore.Qt.Checked: curveSel = pm.selected()[0] self.RadiusJnt = float(self.slider_jnt_rad_LineEdit.text()) self.Naming = self.name_LineEdit.text() self.interval = int(self.slider_int_LineEdit.text()) self.curve = pm.selected() self.all_jnts = [] self.all_motionPath = [] self.Pos = [] for i in range(int(self.interval)): _joint = pm.joint(rad=self.RadiusJnt, n=str(self.Naming)) pm.parent(_joint, w=True) self.all_jnts.append(_joint) _motionPathNode = pm.pathAnimation(self.curve, _joint, upAxis='y', fractionMode=True, worldUpType="vector", inverseUp=False, inverseFront=False, follow=True, bank=False, followAxis='x', worldUpVector=(0, 1, 0)) self.all_motionPath.append(_motionPathNode) # New interval value for the Function Nintervalls = int(self.interval) - 1 for i in range(0, Nintervalls): factor = 1 / float((Nintervalls)) oPos = factor * i self.Pos.append(oPos) self.Pos.append(1) for oPosition, oMotionPath in zip(self.Pos, self.all_motionPath): pm.PyNode(oMotionPath).uValue.set(oPosition) _dup = pm.duplicate(self.all_jnts[-1]) # delete animation for path in self.all_motionPath: _motion_uvalue_node = [ x for x in pm.listConnections(path + '.uValue', s=1) ] pm.delete(_motion_uvalue_node) pm.select(None) # Cleaning the scene pm.delete(_dup) pm.delete(self.all_motionPath) pm.delete(curveSel) # OPTIONAL if we want the joints to be chained pm.select(self.all_jnts[:]) for oParent, oChild in zip(pm.selected()[0:-1], pm.selected()[1:]): pm.parent(oChild, None) pm.parent(oChild, oParent)
def keep_motion_path(self): curveSel = pm.selected()[0] self.RadiusJnt = float(self.slider_jnt_rad_LineEdit.text()) self.Naming = self.name_LineEdit.text() self.interval = int(self.slider_int_LineEdit.text()) self.curve = pm.selected() self.all_jnts = [] self.all_motionPath = [] self.Pos = [] for i in range(int(self.interval)): _joint = pm.joint(rad=self.RadiusJnt, n=str(self.Naming)) pm.parent(_joint, w=True) adb.makeroot_func(_joint) self.all_jnts.append(_joint) double_linears_nodes = [] _motionPathNode = pm.pathAnimation(self.curve, _joint.getParent(), upAxis='y', fractionMode=True, worldUpType="vector", inverseUp=False, inverseFront=False, follow=True, bank=False, followAxis='x', worldUpVector=(0, 1, 0)) ## Delete double Linear nodes for axis in 'xyz': double_linear = pm.listConnections( _motionPathNode + '.{}Coordinate'.format(axis))[0] double_linears_nodes.append(double_linear) pm.delete(double_linears_nodes) for axis in 'xyz': # pm.cycleCheck(e=0) pm.connectAttr('{}.{}Coordinate'.format(_motionPathNode, axis), '{}.t{}'.format(_joint.getParent(), axis), f=1) self.all_motionPath.append(_motionPathNode) # New interval value for the Function Nintervalls = int(self.interval) - 1 for i in range(0, Nintervalls): factor = 1 / float((Nintervalls)) oPos = factor * i self.Pos.append(oPos) self.Pos.append(1) for oPosition, oMotionPath in zip(self.Pos, self.all_motionPath): pm.PyNode(oMotionPath).uValue.set(oPosition) _dup = pm.duplicate(self.all_jnts[-1]) # delete animation for path in self.all_motionPath: _motion_uvalue_node = [ x for x in pm.listConnections(path + '.uValue', s=1) ] pm.delete(_motion_uvalue_node) pm.select(None) # Cleaning the scene pm.delete(_dup)