import pymel.core as pm jnt = pm.PyNode('Joint2') sel = pm.ls(sl=1)[0] his = pm.listHistory(sel) Skin = pm.ls(his, type='skinCluster')[0] jnts = pm.skinCluster(Skin, q=1, inf=1) vtxCnt = pm.polyEvaluate(sel, v=1) pm.select(cl=1) pm.skinCluster(Skin, siv=jnt, e=1) vtx = pm.ls(sl=1, fl=1) pos = pm.xform(jnt, q=1, ws=1, t=1) cl = pm.cluster(n=jnt + 'CL') cl[1].origin.set(pos) cl[1].rotatePivot.set(pos) cl[1].scalePivot.set(pos) clSet = pm.listConnections(cl[0], t='objectSet') for i in vtx: skinData = pm.skinPercent(Skin, i, q=1, t=jnt, v=1) pm.percent(cl[0], i, v=skinData) print skinData
if not os.path.exists(OUTPUT_PATH): os.makedirs(OUTPUT_PATH) output = os.path.join(OUTPUT_PATH,"%s.py"%name) with open(output,'w',encoding="utf-8") as f: f.write(output_file) # NOTE 输出 __init__.py 文件 output = os.path.join(OUTPUT_PATH, "__init__.py" ) with open(output, 'w', encoding="utf-8") as f: f.write(init_file) if __name__ == "__main__": main() from maya import cmds cmds.about(api=1,bd=1) cmds.polyCube(q=1) cmds.spaceLoca from maya import OpenMaya OpenMaya.MSelectionList() import pymel.core as pm pm.PyNode() pm.space
def save_previs_to_shots(self, take_name): """exports previs to animation shots """ self.pre_publish_previs() shot_tasks = self.scene_shot_tasks shot_nodes = self.shot_list shots_to_export = [] for shot_node in shot_nodes: for shot_task in shot_tasks: for task in shot_task.tasks: if task.type == self.anim_type: shot_number = shot_task.name.split('_')[-1] if shot_node.getShotName() == shot_number: shots_to_export.append( [shot_node, task, shot_number]) from anima.env import mayaEnv from stalker import Version from anima.ui.progress_dialog import ProgressDialogManager pdm = ProgressDialogManager() pdm.close() m_env = mayaEnv.Maya() versions = [] description = 'Auto Created By Shot Exporter' # create versions to save and show in pop-up window for shot_info in shots_to_export: version = Version(task=shot_info[1], description=description, take_name=take_name, created_by=self.logged_in_user) versions.append(version) if len(versions) != len(shots_to_export): from stalker.db.session import DBSession DBSession.rollback() raise RuntimeError( 'Something is critically wrong. Contact Mehmet ERER.') # pop-up a window to show everything will be saved properly before actually doing it message = 'Shots will be Saved as Below:\r\n' message += '\r' index = 0 for shot_info in shots_to_export: v = versions[index] message += 'shot[ %s ] -> %s\n' % (shot_info[2], v) index += 1 dialog = pm.confirmDialog( title='Important Warning', message=message, button=['OK, Start Saving Shots', 'STOP, wrong paths!']) if dialog == 'OK, Start Saving Shots': pass else: from stalker.db.session import DBSession DBSession.rollback() raise RuntimeError('Process Interrupted by User.') previs_version = self.current_version errored_shots = [] ind = 0 caller = pdm.register( len(shots_to_export), 'Batch Saving Previs Shot Nodes to Animation Shot Tasks...') from anima.env.mayaEnv import toolbox from stalker.db.session import DBSession for shot_info in shots_to_export: shot_task = versions[ind].task.parent try: # open previs version m_env.open(previs_version, force=True, reference_depth=3, skip_update_check=True) # clear scene except_this_shot = pm.PyNode(shot_info[0].name()) self.clear_scene(except_this_shot) # set frame range before save anima.env.mayaEnv.animation.Animation.set_range_from_shot() # update shot.cut_in and shot.cut_out info cut_in = pm.playbackOptions(q=1, min=1) cut_out = pm.playbackOptions(q=1, max=1) shot_task.cut_in = int(cut_in) shot_task.cut_out = int(cut_out) # save it m_env.save_as(versions[ind]) except: errored_shots.append(shot_info[2]) else: # store information to database DBSession.add(shot_task) DBSession.add(versions[ind]) DBSession.commit() ind += 1 caller.step() if errored_shots: message = 'Shots could not be saved:\r\n' message += '\r' for shot in errored_shots: message += '[ %s ]\n' % shot pm.confirmDialog(title='Error', message=message, button='OK') DBSession.rollback() raise RuntimeError( 'Some Shots could not be saved. Contact Mehmet ERER.') # leave it as empty new file pm.newFile(force=True) message = 'Previs to Shots\r\n' message += '\r' message += 'Completed Succesfully.\r\n' pm.confirmDialog(title='Info', message=message, button='OK')
def ReleaseCmd(myface, pinMode, leave_curve = False) : # - - - - - カーブを作成 - - - - - - - - - - - - - - - global cvList cv = [ [i[0],i[1],i[2]] for i in cvList] print cv curvename = myface.projection_curve_name if pm.objExists(curvename) : c = pm.PyNode(curvename) pm.delete(c) #pm.rename( c, "projectionCurve_backup") #pm.hide(c) # なぜかここでエラー? cur = pm.curve(p = cv, n=curvename) # バックアップ用にもう一つ作成 if leave_curve == True : pm.curve(p = cv, n=curvename) cur = pm.PyNode(curvename) # それぞれのパーツごとにカーブを保存 # multiple.py で使用 name = curvename + "_" + myface.context_parts if pm.objExists(name) : c = pm.PyNode(name) pm.delete(c) pm.curve(p = cv, n=name ) #except : # print "ERROR カーブを作成できません" global locus_temp locus_temp = [ om2.MPoint(0.0,0.0,0.0), om2.MPoint(0.0,0.0,0.0), om2.MPoint(0.0,0.0,0.0) ] #[makeSphere(i, 0.05) for i in curPosList] myface.curve = cur if pm.objExists("show_mysketch") : pm.delete(pm.PyNode("show_mysketch")) # 可視カーブを結合 lst = [] for i in pm.ls(type = u'transform') : if "temp_locus_plane" in i.name() : lst.append(i) #pm.delete(i) pm.polyCBoolOp(lst, n = "show_mysketch") # ラインを削除 tools.deltemp() # シェーダを削除 #pm.delete(pm.PyNode("projection_line_shader")) #do_dmp() # カーブを見えるように show_sketch_from_name_head( myface ) pass
def addJnt(obj=False, parent=False, noReplace=False, grp=None, jntName=None, *args): """Create one joint for each selected object. Args: obj (bool or dagNode, optional): The object to drive the new joint. If False will use the current selection. parent (bool or dagNode, optional): The parent for the joint. If False will try to parent to jnt_org. If jnt_org doesn't exist will parent the joint under the obj noReplace (bool, optional): If True will add the extension "_jnt" to the new joint name grp (pyNode or None, optional): The set to add the new joint. If none will use "rig_deformers_grp" *args: Maya's dummy Returns: pyNode: The New created joint. """ if not obj: oSel = pm.selected() else: oSel = [obj] for obj in oSel: if not parent: try: oParent = pm.PyNode("jnt_org") except TypeError: oParent = obj else: oParent = parent if not jntName: if noReplace: jntName = "_".join(obj.name().split("_")) + "_jnt" else: jntName = "_".join(obj.name().split("_")[:-1]) + "_jnt" jnt = pm.createNode("joint", n=jntName) if grp: grp.add(jnt) else: try: defSet = pm.PyNode("rig_deformers_grp") pm.sets(defSet, add=jnt) except TypeError: pm.sets(n="rig_deformers_grp") defSet = pm.PyNode("rig_deformers_grp") pm.sets(defSet, add=jnt) oParent.addChild(jnt) jnt.setAttr("jointOrient", 0, 0, 0) try: applyop.gear_matrix_cns(obj, jnt) except RuntimeError: for axis in ["tx", "ty", "tz", "rx", "ry", "rz"]: jnt.attr(axis).set(0.0) return jnt
import pymel.core as pm from maya.api.OpenMaya import MTransformationMatrix, MGlobal, MSelectionList, MFnDagNode, MMatrix, MFnTransform, MFnMatrixAttribute import maya.api.OpenMaya as om dgn = MFnDagNode() mobj = om.MObject() m_dagPath = om.MDagPath() mattr = MFnMatrixAttribute() sel = MGlobal.getActiveSelectionList() # selection srcDagpath = sel.getDependNode(0) # first node srctransform_node = MFnTransform(srcDagpath) # MFnTransform srcBaseMtx = srctransform_node.transformation().asMatrix() # matrix srcName = (dgn.setObject(sel.getDagPath(0))).name() #dagname srcPym = pm.PyNode(srcName) #dagPynode tgtDagpath = sel.getDependNode(1) # first node tgttransform_node = MFnTransform(tgtDagpath) # MFnTransform tgtBaseMtx = tgttransform_node.transformation().asMatrix() # matrix tgtName = (dgn.setObject(sel.getDagPath(1))).name() #dagname tgtPym = pm.PyNode(tgtName) #dagPynode srcBattr = mattr.create("srcBaseMtx", "mm") #createAttr srctransform_node.addAttribute(srcBattr) #addAttr srcPym.srcBaseMtx.set(srcBaseMtx) #setAttronPym tgtBAttr = mattr.create("tgtBaseMtx", "mm") #createAttr srctransform_node.addAttribute(tgtBAttr) #addAttr srcPym.tgtBaseMtx.set(tgtBaseMtx) #setAttronPym
def test_listNodes(self): self.assertEqual( set(pm.Namespace('FOO').listNodes()), set([ pm.PyNode('FOO:sphere1'), pm.PyNode('FOO:sphere1Shape'), pm.PyNode('FOO:sphere2'), pm.PyNode('FOO:sphere2Shape'), ])) if self.recurseAvailable: self.assertEqual( set(pm.Namespace('FOO').listNodes(recursive=False)), set([ pm.PyNode('FOO:sphere1'), pm.PyNode('FOO:sphere1Shape'), pm.PyNode('FOO:sphere2'), pm.PyNode('FOO:sphere2Shape'), ])) self.assertEqual( set(pm.Namespace('FOO').listNodes(recursive=True)), set([ pm.PyNode('FOO:sphere1'), pm.PyNode('FOO:sphere1Shape'), pm.PyNode('FOO:sphere2'), pm.PyNode('FOO:sphere2Shape'), pm.PyNode('FOO:BAR:sphere1'), pm.PyNode('FOO:BAR:sphere1Shape'), ]))
def build(self): ################################################################################################################ # root self.rigSystem = drRoot.DrRig(ctrlSize=5.0) ################################################################################################################ # spine self.spineSystem = drSpine.DrSpine( name='spine', start=pmc.PyNode('hip_GD'), end=pmc.PyNode('chest_GD'), rtHip=pmc.PyNode('rt_hip_GD'), lfHip=pmc.PyNode('lf_hip_GD'), rtShldr=pmc.PyNode('rt_shldr_GD'), lfShldr=pmc.PyNode('lf_shldr_GD'), ) p = systemUtils.plug(self.spineSystem.bodyZero_grp, self.rigSystem.rootSystem.sockets['03'], name='spine') p.setParent(self.spineSystem.plugs_grp) # Head self.headSystem = drHead.DrHead(name='head', start=pmc.PyNode('head_GD')) p = systemUtils.plug(self.headSystem.headZero_grp, self.spineSystem.sockets['chest'], plugType='point', name='head') p.setParent(self.headSystem.plugs_grp) p = systemUtils.multiPlug(self.headSystem.headZero_grp, targetList=[ self.rigSystem.rootSystem.sockets['03'], self.spineSystem.sockets['body'], self.spineSystem.sockets['chest'] ], targetNames=['root', 'body', 'chest'], settingsNode=self.headSystem.head_ctrl, plugType='orient', name='head') p.setParent(self.headSystem.plugs_grp) ################################################################################################################ # neck self.neckSystem = drTwistySegment.DrTwistySegmentSimple( name='neck', start=pmc.PyNode('neck_GD'), end=pmc.PyNode('head_GD'), numSegs=3, axis='y', upAxis='x', worldUpAxis='x') p = systemUtils.plug(self.neckSystem.start_grp, self.spineSystem.sockets['chest'], name='neckStart') p.setParent(self.neckSystem.plugs_grp) p = systemUtils.plug(self.neckSystem.end_grp, self.headSystem.sockets['ctrl'], name='neckEnd') p.setParent(self.neckSystem.plugs_grp) self.spineSystem.main_grp.chest_twist.connect( self.neckSystem.twist_pma.input1D[1]) self.headSystem.main_grp.twist.connect( self.neckSystem.twist_pma.input1D[0]) ################################################################################################################ # right arm self.rtArmSystem = drArm.DrArm(name='rt_arm', joints=[ pmc.PyNode('rt_shldr_GD'), pmc.PyNode('rt_elbow_GD'), pmc.PyNode('rt_wrist_GD'), pmc.PyNode('rt_wrist_end_GD') ], numTwistSegs=7, leg=0, flipTwist=0) # connect to body p = systemUtils.plug(self.rtArmSystem.fkCtrls_grp, self.spineSystem.sockets['rt_shldr'], plugType='parent', name='shldr') p.setParent(self.rtArmSystem.plugs_grp) p = systemUtils.multiPlug(self.rtArmSystem.fkCtrlsConst_grp, targetList=[ self.rigSystem.rootSystem.sockets['03'], self.spineSystem.sockets['body'], self.spineSystem.sockets['chest'] ], targetNames=['root', 'body', 'chest'], settingsNode=self.rtArmSystem.fkTopCtrl, plugType='orient', name='rt_arm_shldr') p.setParent(self.rtArmSystem.plugs_grp) # spaceswitch for ikCtrl p = systemUtils.multiPlug( self.rtArmSystem.ikCtrls_grp, targetList=[ self.rigSystem.rootSystem.sockets['03'], self.spineSystem.sockets['body'], self.spineSystem.sockets['chest'], self.headSystem.sockets['ctrl'] ], targetNames=['root', 'body', 'chest', 'head'], settingsNode=self.rtArmSystem.ikCtrl, plugType='parent', name='rt_arm_ikCtrl') p.setParent(self.rtArmSystem.plugs_grp) # spaceswitch for polevector p = systemUtils.multiPlug(self.rtArmSystem.pvZero, targetList=[ self.rigSystem.rootSystem.sockets['03'], self.spineSystem.sockets['body'], self.spineSystem.sockets['chest'], self.rtArmSystem.sockets['poleVectorAim'] ], targetNames=['root', 'body', 'chest', 'arm'], settingsNode=self.rtArmSystem.pvCtrl, plugType='parent', name='rt_arm_poleVectorCtrl') p.setParent(self.rtArmSystem.plugs_grp) ################################################################################################################ # left arm self.lfArmSystem = drArm.DrArm(name='lf_arm', joints=[ pmc.PyNode('lf_shldr_GD'), pmc.PyNode('lf_elbow_GD'), pmc.PyNode('lf_wrist_GD'), pmc.PyNode('lf_wrist_end_GD') ], numTwistSegs=7, leg=0, flipTwist=1, colour='blue') # connect to body p = systemUtils.plug(self.lfArmSystem.fkCtrls_grp, self.spineSystem.sockets['lf_shldr'], plugType='parent', name='shldr') p.setParent(self.lfArmSystem.plugs_grp) p = systemUtils.multiPlug(self.lfArmSystem.fkCtrlsConst_grp, targetList=[ self.rigSystem.rootSystem.sockets['03'], self.spineSystem.sockets['body'], self.spineSystem.sockets['chest'] ], targetNames=['root', 'body', 'chest'], settingsNode=self.lfArmSystem.fkTopCtrl, plugType='orient', name='lf_arm_shldr') p.setParent(self.lfArmSystem.plugs_grp) # spaceswitch for ikCtrl p = systemUtils.multiPlug( self.lfArmSystem.ikCtrls_grp, targetList=[ self.rigSystem.rootSystem.sockets['03'], self.spineSystem.sockets['body'], self.spineSystem.sockets['chest'], self.headSystem.sockets['ctrl'] ], targetNames=['root', 'body', 'chest', 'head'], settingsNode=self.lfArmSystem.ikCtrl, plugType='parent', name='lf_arm_ikCtrl') p.setParent(self.lfArmSystem.plugs_grp) # spaceswitch for polevector p = systemUtils.multiPlug(self.lfArmSystem.pvZero, targetList=[ self.rigSystem.rootSystem.sockets['03'], self.spineSystem.sockets['body'], self.spineSystem.sockets['chest'], self.lfArmSystem.sockets['poleVectorAim'] ], targetNames=['root', 'body', 'chest', 'arm'], settingsNode=self.lfArmSystem.pvCtrl, plugType='parent', name='lf_arm_poleVectorCtrl') p.setParent(self.lfArmSystem.plugs_grp) ################################################################################################################ # right leg self.rtLegSystem = drArm.DrArm(name='rt_leg', joints=[ pmc.PyNode('rt_hip_GD'), pmc.PyNode('rt_knee_GD'), pmc.PyNode('rt_ankle_GD'), pmc.PyNode('rt_ankle_end_GD') ], numTwistSegs=7, upAxis='z', flipTwist=0, leg=0) # connect to body p = systemUtils.plug(self.rtLegSystem.fkCtrls_grp, self.spineSystem.sockets['rt_hip'], plugType='parent', name='rt_leg_hip') p.setParent(self.rtLegSystem.plugs_grp) # spaceswitch for ikCtrl p = systemUtils.multiPlug(self.rtLegSystem.ikCtrls_grp, targetList=[ self.rigSystem.rootSystem.sockets['03'], self.spineSystem.sockets['hips'] ], targetNames=['root', 'hip'], settingsNode=self.rtLegSystem.ikCtrl, plugType='parent', name='rt_leg_ikCtrl') p.setParent(self.rtLegSystem.plugs_grp) # spaceswitch for polevector p = systemUtils.multiPlug(self.rtLegSystem.pvZero, targetList=[ self.rigSystem.rootSystem.sockets['03'], self.spineSystem.sockets['hips'], self.rtLegSystem.sockets['poleVectorAim'] ], targetNames=['root', 'hip', 'foot'], settingsNode=self.rtLegSystem.pvCtrl, plugType='parent', name='rt_leg_poleVectorCtrl') p.setParent(self.rtLegSystem.plugs_grp) ################################################################################################################ # left leg self.lfLegSystem = drArm.DrArm(name='lf_leg', joints=[ pmc.PyNode('lf_hip_GD'), pmc.PyNode('lf_knee_GD'), pmc.PyNode('lf_ankle_GD'), pmc.PyNode('lf_ankle_end_GD') ], numTwistSegs=7, upAxis='z', leg=0, flipTwist=1, colour='blue') # connect to body p = systemUtils.plug(self.lfLegSystem.fkCtrls_grp, self.spineSystem.sockets['lf_hip'], plugType='parent', name='hip') p.setParent(self.lfLegSystem.plugs_grp) # spaceswitch for ikCtrl p = systemUtils.multiPlug(self.lfLegSystem.ikCtrls_grp, targetList=[ self.rigSystem.rootSystem.sockets['03'], self.spineSystem.sockets['hips'] ], targetNames=['root', 'hip'], settingsNode=self.lfLegSystem.ikCtrl, plugType='parent', name='lf_leg_ikCtrl') p.setParent(self.lfLegSystem.plugs_grp) # spaceswitch for polevector p = systemUtils.multiPlug(self.lfLegSystem.pvZero, targetList=[ self.rigSystem.rootSystem.sockets['03'], self.spineSystem.sockets['hips'], self.lfLegSystem.sockets['poleVectorAim'] ], targetNames=['root', 'hip', 'foot'], settingsNode=self.lfLegSystem.pvCtrl, plugType='parent', name='lf_leg_poleVectorCtrl') p.setParent(self.lfLegSystem.plugs_grp) ################################################################################################################ # right foot self.rtFootSystem = drHoof.DrHoof( name='rt_foot', ankle=pmc.PyNode('rt_ankle_GD'), toe=pmc.PyNode('rt_toe_GD'), heel=pmc.PyNode('rt_heel_GD'), inner=pmc.PyNode('rt_inner_GD'), outer=pmc.PyNode('rt_outer_GD'), settingsNode=self.rtLegSystem.ikCtrl, blendAttr=self.rtLegSystem.settingsCtrl.ik_fk_blend) # connect to body p = systemUtils.plug(self.rtFootSystem.ikConstGrp, self.rtLegSystem.sockets['ikCtrl'], name='rt_ikFoot') p.setParent(self.rtFootSystem.plugs_grp) p = systemUtils.plug(self.rtFootSystem.fkConstGrp, self.rtLegSystem.sockets['fkCtrl'], name='rt_fkFoot') p.setParent(self.rtFootSystem.plugs_grp) # attach ik leg to foot p = systemUtils.plug(self.rtLegSystem.ctrl_loc, self.rtFootSystem.sockets['ankle'], name='rt_leg_ikFoot') p.setParent(self.rtLegSystem.plugs_grp) ################################################################################################################ # left foot self.lfFootSystem = drHoof.DrHoof( name='lf_foot', ankle=pmc.PyNode('lf_ankle_GD'), toe=pmc.PyNode('lf_toe_GD'), heel=pmc.PyNode('lf_heel_GD'), inner=pmc.PyNode('lf_inner_GD'), outer=pmc.PyNode('lf_outer_GD'), settingsNode=self.lfLegSystem.ikCtrl, blendAttr=self.lfLegSystem.settingsCtrl.ik_fk_blend) # connect to body p = systemUtils.plug(self.lfFootSystem.ikConstGrp, self.lfLegSystem.sockets['ikCtrl'], name='lf_ikFoot') p.setParent(self.lfFootSystem.plugs_grp) p = systemUtils.plug(self.lfFootSystem.fkConstGrp, self.lfLegSystem.sockets['fkCtrl'], name='lf_fkFoot') p.setParent(self.lfFootSystem.plugs_grp) # attach ik leg to foot p = systemUtils.plug(self.lfLegSystem.ctrl_loc, self.lfFootSystem.sockets['ankle'], name='lf_leg_ikFoot') p.setParent(self.lfLegSystem.plugs_grp) ################################################################################################################ # right hand self.rtHandSystem = drHoof.DrHoof( name='rt_hand', ankle=pmc.PyNode('rt_wrist_GD'), toe=pmc.PyNode('rt_hand_toe_GD'), heel=pmc.PyNode('rt_hand_heel_GD'), inner=pmc.PyNode('rt_hand_inner_GD'), outer=pmc.PyNode('rt_hand_outer_GD'), settingsNode=self.rtArmSystem.ikCtrl, blendAttr=self.rtArmSystem.settingsCtrl.ik_fk_blend) # connect to body p = systemUtils.plug(self.rtHandSystem.ikConstGrp, self.rtArmSystem.sockets['ikCtrl'], name='rt_ikHand') p.setParent(self.rtHandSystem.plugs_grp) p = systemUtils.plug(self.rtHandSystem.fkConstGrp, self.rtArmSystem.sockets['fkCtrl'], name='rt_fkHand') p.setParent(self.rtHandSystem.plugs_grp) # attach ik leg to foot p = systemUtils.plug(self.rtArmSystem.ctrl_loc, self.rtHandSystem.sockets['ankle'], name='rt_arm_ikHand') p.setParent(self.rtArmSystem.plugs_grp) ################################################################################################################ # left hand self.lfHandSystem = drHoof.DrHoof( name='lf_hand', ankle=pmc.PyNode('lf_wrist_GD'), toe=pmc.PyNode('lf_hand_toe_GD'), heel=pmc.PyNode('lf_hand_heel_GD'), inner=pmc.PyNode('lf_hand_inner_GD'), outer=pmc.PyNode('lf_hand_outer_GD'), settingsNode=self.lfArmSystem.ikCtrl, blendAttr=self.lfArmSystem.settingsCtrl.ik_fk_blend) # connect to body p = systemUtils.plug(self.lfHandSystem.ikConstGrp, self.lfArmSystem.sockets['ikCtrl'], name='lf_ikHand') p.setParent(self.lfHandSystem.plugs_grp) p = systemUtils.plug(self.lfHandSystem.fkConstGrp, self.lfArmSystem.sockets['fkCtrl'], name='lf_fkHand') p.setParent(self.lfHandSystem.plugs_grp) # attach ik leg to foot p = systemUtils.plug(self.lfArmSystem.ctrl_loc, self.lfHandSystem.sockets['ankle'], name='lf_arm_ikHand') p.setParent(self.lfArmSystem.plugs_grp) ################################################################################################################ # Parent to rig_grp and connect globalscales of all systems for system in [ self.spineSystem, self.headSystem, self.neckSystem, self.rtArmSystem, self.lfArmSystem, self.rtLegSystem, self.lfLegSystem, self.rtFootSystem, self.lfFootSystem, self.rtHandSystem, self.lfHandSystem ]: system.main_grp.setParent(self.rigSystem.rig_grp) self.rigSystem.rootSystem.main_grp.globalScale.connect( system.main_grp.globalScale) ################################################################################################################ # Publish joints publishJoints(self.rigSystem, [ self.spineSystem, self.headSystem, self.neckSystem, self.rtArmSystem, self.lfArmSystem, self.rtLegSystem, self.lfLegSystem, self.rtFootSystem, self.lfFootSystem, self.rtHandSystem, self.lfHandSystem ])
def _edit_all_off(): """Set all crank layer edit off """ for lyr in list_crank_layer_nodes(): edit_layer_off(pm.PyNode(lyr))
for x, object in enumerate(selection): if x % deleteEachNumber == 0: pm.delete(object) else: pass #select cv on Curve TESTED import pymel.core as pm cvPick = 3 #TODO import the value from user selection = pm.selected() cvList = [] for curveTransform in selection: curve = curveTransform.getChildren()[0] tempHolder = pm.PyNode(curve.name() + '.cv[' + str(cvPick) + ']') cvList.append(tempHolder) pm.select(cvList) #set pivot on curve root TESTED import pymel.core as pm selection = pm.selected() for curve in selection: root = pm.PyNode(curve.name() + '.cv[0]') rootPosition = pm.xform(root, q=True, t=True, ws=True) pm.xform(curve, rp=rootPosition, sp=rootPosition) print 'done' #reverse curve TESTED import pymel.core as pm pm.reverseCurve()
self.TipName = naming.TipName(name=name, base='%s%s' % (name.base, system), suffix="1") else: name = startJoint self.TipName = naming.TipName(name=name, base='%s%s' % (name.nodeBase.get(), system), suffix="1") self.topName = naming.TipName(name=name, descriptor='rig', index='A', suffix='1') self.sysName = '%s%s' % (self.TipName.base, self.TipName.side) #add attrs if not pm.objExists(self.topName.name): self.rigGrp = pm.group(em=True) naming.TipName(self.rigGrp, name=self.topName) pm.delete(pm.parentConstraint(mainEye, self.rigGrp)) self.rigGrp.setParent(self.socketJoint) else: self.rigGrp = pm.PyNode(self.topName.name) self.rigGrp.unlockAndShow(attribute.STANDARD_ATTRIBUTES) self.createMainNodes() self.createFollowNodes() self.constraintSystem() self.addAttrsToRig() self.setDefaultValues() self.createMainSystemNodes() if self.eyeArea == 'eye' or self.eyeArea == 'membrane': self.connectMainSystemAttrs_Rot() self.createOffsetSystem_Rot() else: self.connectMainSystemAttrs_Trans() self.createOffsetSystem_Trans()
def get_opposite_control(node): target_name = mgear.core.string.convertRLName(node.name()) target = None if pc.objExists(target_name): target = pc.PyNode(target_name) return target
def ghostSliderForMouth(ghostControls, intTra, surface, sliderParent): """Modify the ghost control behaviour to slide on top of a surface Args: ghostControls (dagNode): The ghost control surface (Surface): The NURBS surface sliderParent (dagNode): The parent for the slider. """ if not isinstance(ghostControls, list): ghostControls = [ghostControls] def conn(ctl, driver, ghost): for attr in ["translate", "scale", "rotate"]: try: pm.connectAttr("{}.{}".format(ctl, attr), "{}.{}".format(driver, attr)) pm.disconnectAttr("{}.{}".format(ctl, attr), "{}.{}".format(ghost, attr)) except RuntimeError: pass def connCenter(ctl, driver, ghost): # mul_node1 = pm.createNode("multMatrix") # mul_node2 = pm.createNode("multMatrix") down, _, up = ymt_util.findPathAtoB(ctl, driver) mult = pm.createNode("multMatrix") for i, d in enumerate(down): d.attr("matrix") >> mult.attr("matrixIn[{}]".format(i)) for j, u in enumerate(up[:-1]): u.attr("inverseMatrix") >> mult.attr( "matrixIn[{}]".format(i + j + 1)) decomp = pm.createNode("decomposeMatrix") dm_node = node.createDecomposeMatrixNode(mult.attr("matrixSum")) for attr in ["translate", "scale", "rotate"]: pm.connectAttr("{}.output{}".format(dm_node, attr.capitalize()), "{}.{}".format(driver, attr)) pm.disconnectAttr("{}.{}".format(ctl, attr), "{}.{}".format(ghost, attr)) surfaceShape = surface.getShape() sliders = [] for i, ctlGhost in enumerate(ghostControls): ctl = pm.listConnections(ctlGhost, t="transform")[-1] t = ctl.getMatrix(worldSpace=True) gDriver = primitive.addTransform(surface.getParent(), "{}_slideDriver".format(ctl.name()), t) if 0 == i: connCenter(ctl, gDriver, ctlGhost) else: conn(ctl, gDriver, ctlGhost) oParent = ctlGhost.getParent() npoName = "_".join(ctlGhost.name().split("_")[:-1]) + "_npo" oTra = pm.PyNode( pm.createNode("transform", n=npoName, p=oParent, ss=True)) oTra.setTransformation(ctlGhost.getMatrix()) pm.parent(ctlGhost, oTra) slider = primitive.addTransform(sliderParent, ctl.name() + "_slideDriven", t) sliders.append(slider) # connexion if 0 == i: dm_node = node.createDecomposeMatrixNode(gDriver.attr("matrix")) else: mul_node = pm.createNode("multMatrix") i = 0 parent = ctl while parent != sliderParent: parent.attr("matrix") >> mul_node.attr( "matrixIn[{}]".format(i)) parent = parent.getParent() i += 1 if 10 < i: logger.error("maximum recursion") break dm_node = node.createDecomposeMatrixNode( mul_node.attr("matrixSum")) cps_node = pm.createNode("closestPointOnSurface") dm_node.attr("outputTranslate") >> cps_node.attr("inPosition") surfaceShape.attr("local") >> cps_node.attr("inputSurface") cps_node.attr("position") >> slider.attr("translate") pm.normalConstraint(surfaceShape, slider, aimVector=[0, 0, 1], upVector=[0, 1, 0], worldUpType="objectrotation", worldUpVector=[0, 1, 0], worldUpObject=gDriver) pm.parent(ctlGhost.getParent(), slider) ymt_util.setKeyableAttributesDontLockVisibility(slider, []) for slider in sliders[1:]: _visi_off_lock(slider)
def _createSoftTweakControls(name, parent=None, t=datatypes.Matrix(), grps=None, size=0.5): root_name = "{}_{}".format(name, "softTweak_root") namespace = None try: # simple check if exist a tweak with the same name exist = pm.PyNode(root_name) if exist: pm.displayError("the tweak: {} already exist. Please use a " "unique name.".format(name)) return False, False except pm.MayaNodeError: if parent: try: p = pm.PyNode(parent) namespace = p.namespace() except pm.MayaNodeError: pm.displayWarning("{} is not a valid parent or doesn't " "exist".format(parent)) p = None else: p = None root = primitive.addTransform(p, root_name, t) attribute.addAttribute(root, "iconSize", "float", size, keyable=False) baseCtl = icon.create(parent=root, name="{}_{}".format(name, "baseSoftTweak_ctl"), m=t, color=[1, 0.622, 0], icon="square", d=size, w=size) tweakCtl = icon.create(parent=baseCtl, name="{}_{}".format(name, "softTweak_ctl"), m=t, color=[0.89, 0.0, 0.143], icon="diamond", w=size * .8) attribute.addAttribute(tweakCtl, "falloff", "float", size) if grps: if not isinstance(grps, list): grps = [grps] for grp in grps: try: # try if exist oGrp = pm.PyNode(grp) except pm.MayaNodeError: # create a new grp if does't exist if len(grp.split("_")) >= 3: # check name convention name = grp else: name = "rig_{}_grp".format(grp) # namespace basic handling # NOTE: Doesn't support more than one namespace stacked if namespace and len(name.split(":")) < 2: name = namespace + name oGrp = pm.sets(n=name, em=True) pm.sets(oGrp, add=[baseCtl, tweakCtl]) if t: root.setMatrix(t, worldSpace=True) return baseCtl, tweakCtl
def importNHairCache(hairSystemNode=None, filePath=None): """ Attach nHair cache. :param hairSystemNode: `PyNode` hair system node to attach the cache to :param filePath: `string` nCache .xml file path :return: """ selection = pm.ls(sl=True, type=["transform", "hairSystem"]) if not hairSystemNode: if selection: if selection[0].nodeType() == "hairSystem": hairSystemNode = selection[0] else: shapeNode = selection[0].getShape() if shapeNode and shapeNode.nodeType() == "hairSystem": hairSystemNode = shapeNode if not hairSystemNode: print "Please select/input a hairSystem node to import cache files." return False if not filePath: filePath = pm.fileDialog2(fileFilter="*.xml", dialogStyle=2, fileMode=1) if not filePath: return False else: filePath = filePath[0] baseDirectory = os.path.split(filePath)[0] cacheName = os.path.splitext(os.path.basename(filePath))[0] # check if is already connected to a cache if hairSystemNode.playFromCache.isConnected(): replaceCache = pm.confirmDialog( title="Replace Cache", message="{0} is already connected to a cache, " "do you want to replace the current one?".format( hairSystemNode.name()), button=["Yes", "No"], defaultButton="Yes", cancelButton="No", dismissString="No") if replaceCache == "No": return False else: oldCache = hairSystemNode.playFromCache.connections( type="cacheFile")[0] pm.delete(oldCache) channelNames = getChannelNames(filePath) print channelNames cacheNodeName = pm.cacheFile(af=True, f=cacheName, dir=baseDirectory, cnm=channelNames, ia=[ "{0}.hairCounts".format(hairSystemNode), "{0}.vertexCounts".format(hairSystemNode), "{0}.positions".format(hairSystemNode) ]) pm.PyNode(cacheNodeName).inRange.connect(hairSystemNode.playFromCache, f=True) pm.select(cacheNodeName) return True
def createRivetTweak(mesh, edgePair, name, parent=None, parentJnt=None, ctlParent=None, color=[0, 0, 0], size=.04, defSet=None, ctlSet=None, side=None, gearMulMatrix=True): """Create a tweak joint attached to the mesh using a rivet Args: mesh (mesh): The object to add the tweak edgePair (pari list): The edge pairt to create the rivet name (str): The name for the tweak parent (None or dagNode, optional): The parent for the tweak parentJnt (None or dagNode, optional): The parent for the joints ctlParent (None or dagNode, optional): The parent for the tweak control color (list, optional): The color for the control size (float, optional): Size of the control defSet (None or set, optional): Deformer set to add the joints ctlSet (None or set, optional): the set to add the controls side (None, str): String to set the side. Valid values are L, R or C. If the side is not set or the value is not valid, the side will be set automatically based on the world position gearMulMatrix (bool, optional): If False will use Maya default multiply matrix node Returns: PyNode: The tweak control """ blendShape = blendShapes.getBlendShape(mesh) inputMesh = blendShape.listConnections(sh=True, t="shape", d=False)[0] oRivet = rivet.rivet() base = oRivet.create(inputMesh, edgePair[0], edgePair[1], parent) # get side if not side or side not in ["L", "R", "C"]: if base.getTranslation(space='world')[0] < -0.01: side = "R" elif base.getTranslation(space='world')[0] > 0.01: side = "L" else: side = "C" nameSide = name + "_tweak_" + side pm.rename(base, nameSide) if not ctlParent: ctlParent = base ctl_parent_tag = None else: ctl_parent_tag = ctlParent # Joints NPO npo = pm.PyNode( pm.createNode("transform", n=nameSide + "_npo", p=ctlParent, ss=True)) pm.pointConstraint(base, npo, mo=False) # create joints if not parentJnt: parentJnt = npo matrix_cnx = False else: # need extra connection to ensure is moving with th npo, even is # not child of npo matrix_cnx = True jointBase = primitive.addJoint(parentJnt, nameSide + "_jnt_lvl") joint = primitive.addJoint(jointBase, nameSide + "_jnt") # reset axis and invert behaviour for axis in "XYZ": pm.setAttr(jointBase + ".jointOrient" + axis, 0) pm.setAttr(npo + ".translate" + axis, 0) # pm.setAttr(jointBase + ".translate" + axis, 0) pp = npo.getParent() pm.parent(npo, w=True) for axis in "xyz": npo.attr("r" + axis).set(0) if side == "R": npo.attr("ry").set(180) npo.attr("sz").set(-1) pm.parent(npo, pp) dm_node = None if matrix_cnx: mulmat_node = applyop.gear_mulmatrix_op( npo + ".worldMatrix", jointBase + ".parentInverseMatrix") dm_node = node.createDecomposeMatrixNode(mulmat_node + ".output") m = mulmat_node.attr('output').get() pm.connectAttr(dm_node + ".outputTranslate", jointBase + ".t") pm.connectAttr(dm_node + ".outputRotate", jointBase + ".r") # invert negative scaling in Joints. We only inver Z axis, so is # the only axis that we are checking print dm_node.attr("outputScaleZ").get() if dm_node.attr("outputScaleZ").get() < 0: mul_nod_invert = node.createMulNode(dm_node.attr("outputScaleZ"), -1) out_val = mul_nod_invert.attr("outputX") else: out_val = dm_node.attr("outputScaleZ") pm.connectAttr(dm_node.attr("outputScaleX"), jointBase + ".sx") pm.connectAttr(dm_node.attr("outputScaleY"), jointBase + ".sy") pm.connectAttr(out_val, jointBase + ".sz") pm.connectAttr(dm_node + ".outputShear", jointBase + ".shear") # Segment scale compensate Off to avoid issues with the global # scale jointBase.setAttr("segmentScaleCompensate", 0) joint.setAttr("segmentScaleCompensate", 0) jointBase.setAttr("jointOrient", 0, 0, 0) # setting the joint orient compensation in order to have clean # rotation channels jointBase.attr("jointOrientX").set(jointBase.attr("rx").get()) jointBase.attr("jointOrientY").set(jointBase.attr("ry").get()) jointBase.attr("jointOrientZ").set(jointBase.attr("rz").get()) im = m.inverse() if gearMulMatrix: mul_nod = applyop.gear_mulmatrix_op(mulmat_node.attr('output'), im, jointBase, 'r') dm_node2 = mul_nod.output.listConnections()[0] else: mul_nod = node.createMultMatrixNode(mulmat_node.attr('matrixSum'), im, jointBase, 'r') dm_node2 = mul_nod.matrixSum.listConnections()[0] if dm_node.attr("outputScaleZ").get() < 0: negateTransformConnection(dm_node2.outputRotate, jointBase.rotate) else: resetJntLocalSRT(jointBase) # hidding joint base by changing the draw mode pm.setAttr(jointBase + ".drawStyle", 2) if not defSet: try: defSet = pm.PyNode("rig_deformers_grp") except TypeError: pm.sets(n="rig_deformers_grp", empty=True) defSet = pm.PyNode("rig_deformers_grp") pm.sets(defSet, add=joint) controlType = "sphere" o_icon = icon.create(npo, nameSide + "_ctl", datatypes.Matrix(), color, controlType, w=size) transform.resetTransform(o_icon) if dm_node and dm_node.attr("outputScaleZ").get() < 0: pm.connectAttr(o_icon.scale, joint.scale) negateTransformConnection(o_icon.rotate, joint.rotate) negateTransformConnection(o_icon.translate, joint.translate, [1, 1, -1]) else: for t in [".translate", ".scale", ".rotate"]: pm.connectAttr(o_icon + t, joint + t) # create the attributes to handlde mirror and symetrical pose attribute.addAttribute(o_icon, "invTx", "bool", 0, keyable=False, niceName="Invert Mirror TX") attribute.addAttribute(o_icon, "invTy", "bool", 0, keyable=False, niceName="Invert Mirror TY") attribute.addAttribute(o_icon, "invTz", "bool", 0, keyable=False, niceName="Invert Mirror TZ") attribute.addAttribute(o_icon, "invRx", "bool", 0, keyable=False, niceName="Invert Mirror RX") attribute.addAttribute(o_icon, "invRy", "bool", 0, keyable=False, niceName="Invert Mirror RY") attribute.addAttribute(o_icon, "invRz", "bool", 0, keyable=False, niceName="Invert Mirror RZ") attribute.addAttribute(o_icon, "invSx", "bool", 0, keyable=False, niceName="Invert Mirror SX") attribute.addAttribute(o_icon, "invSy", "bool", 0, keyable=False, niceName="Invert Mirror SY") attribute.addAttribute(o_icon, "invSz", "bool", 0, keyable=False, niceName="Invert Mirror SZ") # magic of doritos connection pre_bind_matrix_connect(mesh, joint, jointBase) # add control tag node.add_controller_tag(o_icon, ctl_parent_tag) if not ctlSet: try: ctlSet = pm.PyNode("rig_controllers_grp") except TypeError: pm.sets(n="rig_controllers_grp", empty=True) ctlSet = pm.PyNode("rig_controllers_grp") pm.sets(ctlSet, add=o_icon) return o_icon
def _read_bvh(self, e=False): # Safe close is needed for End Site part to keep from setting new parent. safeClose = False # Once motion is active, animate. motion = False # Clear channels before appending self._channels = [] # Scale the entire rig and animation rigScale = mc.floatField(self._scaleField, q=True, value=True) frame = mc.intField(self._frameField, q=True, value=True) rotOrder = mc.optionMenu(self._rotationOrder, q=True, select=True) - 1 with open(self._filename) as f: # Check to see if the file is valid (sort of) if not f.next().startswith("HIERARCHY"): mc.error("No valid .bvh file selected.") return False if self._rootNode is None: # Create a group for the rig, easier to scale. (Freeze transform when ungrouping please..) mocapName = os.path.basename(self._filename) grp = pm.group(em=True, name="_mocap_%s_grp" % mocapName) grp.scale.set(rigScale, rigScale, rigScale) # The group is now the 'root' myParent = TinyDAG(str(grp), None) else: myParent = TinyDAG(str(self._rootNode), None) self._clear_animation() for line in f: line = line.replace(" ", " ") # force spaces if not motion: # root joint if line.startswith("ROOT"): # Set the Hip joint as root if self._rootNode: myParent = TinyDAG(str(self._rootNode), None) else: myParent = TinyDAG(line[5:].rstrip(), myParent) if "JOINT" in line: jnt = line.split(" ") # Create the joint myParent = TinyDAG(jnt[-1].rstrip(), myParent) if "End Site" in line: # Finish up a hierarchy and ignore a closing bracket safeClose = True if "}" in line: # Ignore when safeClose is on if safeClose: safeClose = False continue # Go up one level if myParent is not None: myParent = myParent.pObj if myParent is not None: mc.select(myParent._fullPath()) if "CHANNELS" in line: chan = line.strip().split(" ") if self._debug: print chan # Append the channels that are animated for i in range(int(chan[1])): self._channels.append("%s.%s" % (myParent._fullPath(), translationDict[chan[2 + i]])) if "OFFSET" in line: offset = line.strip().split(" ") if self._debug: print offset jntName = str(myParent) # When End Site is reached, name it "_tip" if safeClose: jntName += "_tip" # skip if exists if mc.objExists(myParent._fullPath()): jnt = pm.PyNode(myParent._fullPath()) jnt.rotateOrder.set(rotOrder) jnt.translate.set([float(offset[1]), float(offset[2]), float(offset[3])]) continue # Build the joint and set its properties jnt = pm.joint(name=jntName, p=(0, 0, 0)) jnt.translate.set([float(offset[1]), float(offset[2]), float(offset[3])]) jnt.rotateOrder.set(rotOrder) if "MOTION" in line: # Animate! motion = True if self._debug: if myParent is not None: print "parent: %s" % myParent._fullPath() else: # We don't really need to use Framecount and time(since Python handles file reads nicely) if "Frame" not in line: data = line.split(" ") if len(data) > 0: if data[0] == "": data.pop(0) if self._debug: print "Animating.." print "Data size: %d" % len(data) print "Channels size: %d" % len(self._channels) # Set the values to channels for x in range(0, len(data) - 1): if self._debug: print "Set Attribute: %s %f" % (self._channels[x], float(data[x])) mc.setKeyframe(self._channels[x], time=frame, value=float(data[x])) frame = frame + 1
def createRivetTweakLayer(layerMesh, bst, edgePairList, name, parent=None, parentJnt=None, ctlParent=None, color=[0, 0, 0], size=.04, defSet=None, ctlSet=None, side=None, mirror=False, mParent=None, mParentJnt=None, mCtlParent=None, mColor=None, gearMulMatrix=True, static_jnt=None): """Create a rivet tweak layer setup Args: layerMesh (mesh): The tweak layer mesh bst (mesh): The mesh blendshape target edgePairList (list of list): The edge pair list of list name (str): The name for the tweak parent (None or dagNode, optional): The parent for the tweak parentJnt (None or dagNode, optional): The parent for the joints ctlParent (None or dagNode, optional): The parent for the tweak control color (list, optional): The color for the control size (float, optional): Size of the control defSet (None or set, optional): Deformer set to add the joints ctlSet (None or set, optional): the set to add the controls side (None, str): String to set the side. Valid values are L, R or C. If the side is not set or the value is not valid, the side will be set automatically based on the world position mirror (bool, optional): Create the mirror tweak on X axis symmetry mParent (None, optional): Mirror tweak parent, if None will use parent arg mParentJnt (None, optional): Mirror parent joint, if None will use parentJnt arg mCtlParent (None, optional): Mirror ctl parent, if None will use ctlParent arg mColor (None, optional): Mirror controls color, if None will color arg gearMulMatrix (bool, optional): If False will use Maya default multiply matrix node static_jnt (dagNode, optional): Static joint for the setup """ # Apply blendshape from blendshapes layer mesh blendShapes.connectWithBlendshape(layerMesh, bst) # create static joint if not static_jnt: if pm.objExists('static_jnt') is not True: static_jnt = primitive.addJoint(parent, "static_jnt", m=datatypes.Matrix(), vis=True) else: static_jnt = pm.PyNode("static_jnt") # apply initial skincluster pm.skinCluster(static_jnt, layerMesh, tsb=True, nw=2, n='%s_skinCluster' % layerMesh.name()) # create doritos if not mParent: mParent = parent if not mCtlParent: mCtlParent = ctlParent if not mColor: mColor = color if not mParentJnt: mParentJnt = parentJnt createRivetTweakFromList(layerMesh, edgePairList, name, parent=parent, parentJnt=parentJnt, ctlParent=ctlParent, color=color, size=size, defSet=defSet, ctlSet=ctlSet, side=side, mirror=mirror, mParent=mParent, mParentJnt=mParentJnt, mCtlParent=mCtlParent, mColor=mColor, gearMulMatrix=gearMulMatrix)
def test_import(self): ref = self.sphereRef1 sphere = 'sphere1:pSphere1' self.assertTrue(pm.PyNode(sphere).isReferenced()) ref.importContents() self.assertFalse(pm.PyNode(sphere).isReferenced())
def cacheScene(task, code): ver = 0 collection = database.getCollection('shot') shotMData = database.getItemMData(task=task, code=code, itemType='shot') if 'caches' not in shotMData: shotMData['caches'] = copy.deepcopy(shotMData['components']) for item in shotMData['caches'].itervalues(): item['ver'] = 0 item['type'] = 'cache' item['assembleMode'] = 'cache' item['cacheVer'] = 0 item['name'] = '' itemComponents = shotMData['components'] itemCaches = shotMData['caches'] geoGroups = pm.ls('geo_group', r=True) choosen = pm.layoutDialog(ui=lambda: cachePrompt(geoGroups)) if 'Abort' in choosen: return path = database.getPath(shotMData, dirLocation='cacheLocation', ext='') cachePath = os.path.join(*path) if not os.path.exists(cachePath): os.makedirs(cachePath) choosenGeoGroups = [pm.PyNode(x) for x in choosen.split(',')] for geoGroup in choosenGeoGroups: # get all geometry on geo_group geosShape = geoGroup.getChildren(allDescendents=True, type='geometryShape') geos = [x.getParent() for x in geosShape] jobGeos = '' for geo in geos: if '|' in geo: logger.error('Naming problem on geo %s' % geo) else: jobGeos = jobGeos + ' -root ' + geo # make path and name for alembic file ns = geoGroup.namespace()[:-1] cacheMData = itemCaches[ns] # get the data for this component # get version and increment cacheMData['cacheVer'] += 1 ver = cacheMData['cacheVer'] # get cache publish path cacheName = database.templateName(cacheMData) + '_' + ns cacheFileName = str('v%03d_' % ver) + cacheName cacheFullPath = os.path.join(cachePath, cacheFileName) jobFile = " -file " + cacheFullPath + ".abc " # get scene frame range ini = str(int(pm.playbackOptions(q=True, min=True))) fim = str(int(pm.playbackOptions(q=True, max=True))) jobFrameRange = ' -frameRange ' + ini + ' ' + fim # set parameters for alembic cache jobAttr = ' -attr translateX -attr translateY -attr translateZ -attr rotateX ' \ '-attr rotateY -attr rotateZ -attr scaleX -attr scaleY -attr scaleZ -attr visibility' jobOptions = " -worldSpace -uv -writeVisibility" # build cache arguments jobArg = jobFrameRange + jobOptions + jobAttr + jobGeos + jobFile # do caching pm.AbcExport(j=jobArg) collection.find_one_and_update({ 'task': task, 'code': code }, {'$set': shotMData}) logger.info('Cache Ver: %s')
def dragCmd(ref) : print "***dragCmd***" span = 0.5 # CVを打つ基準の距離 dragPosition = cmds.draggerContext( ctx, query=True, dragPoint=True) post2 = om2.MPoint(dragPosition) global post global cvList distance = post - post2 if distance.length() > span : #print "\n", distance.length(),"-------------------------" # 衝突判定 dagPath = tools.getDagPath(ref.name()) camName = tools.getCamFromModelPanel() cam = pm.PyNode(camName) #print "Try to make cv / camera is [",camName, "]" projection = tools.laytomesh( dagPath, # 衝突検知対象のオブジェクトのパス post2, # om2.MPoint クラスのオブジェクト / 移動対象 cam # カメラのトランスフォームノード ) #projection = om2.MPoint(0,0,0) cvList.append(projection) #cvList.append( om2.MPoint(0,0,0) ) post = post2 # - - - 可視カーブ - - - - - - - - - - - - - length = 0.5 thickness = 0.1 cam_pos_temp = pm.getAttr(cam.translate) cam_pos = om2.MPoint(cam_pos_temp[0],cam_pos_temp[1],cam_pos_temp[2]) source = projection # om2.MVector vec = source - cam_pos new_point = cam_pos + (length * vec) #tools.makeSphere(new_point, 0.1) global locus_temp locus = new_point - locus_temp[0] normal = (locus ^ vec).normal() if locus_temp[0] != om2.MPoint([0.0,0.0,0.0]): new_point_d = new_point+(thickness*normal) new_point_u = new_point-(thickness*normal) plane = tools.makePlane([ locus_temp[1], new_point_u, new_point_d, locus_temp[2] ], "temp_locus_plane") # シェーダをセット print "set shader" global shadingEngine pm.sets(shadingEngine, e = 1, forceElement = plane) print "fin" else : new_point_d = new_point new_point_u = new_point locus_temp = [ new_point, new_point_u, new_point_d ] #pm.refresh(f = 1) # - - - - - - - - - - - - - #button = cmds.draggerContext( ctx, query=True, button=True) #modifier = cmds.draggerContext( ctx, query=True, modifier=True) #print ("Drag: " + str(dragPosition) + " Button is " + str(button) + " Modifier is " + modifier + "\n") message = str(dragPosition[0]) + ", " + str(dragPosition[1]) + "aaaaaaaaaaaa" cmds.draggerContext( ctx, edit=True, drawString=message) pm.refresh()
def __init__(self, nodeName): BaseTemplate.__init__(self, nodeName) self.thisNode = None self.node = pm.PyNode(self.nodeName) self.buildBody(nodeName) log.debug("AEappleSeedNodeTemplate")
def test() : curvedayo = pm.PyNode(pm.curve( p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9)] ))
def __init__(self, attr, value=None, optional=False): self.attr = pm.PyNode(attr) self.optional = optional super(SetAndRestoreAttr, self).__init__(value)
def addBlendedJoint(oSel=None, compScale=True, blend=.5, name=None, select=True, *args): """Create and gimmick blended joint Create a joint that rotate 50% of the selected joint. This operation is done using a pairBlend node. Args: oSel (None or joint, optional): If None will use the selected joints. compScale (bool, optional): Set the compScale option of the blended joint. Default is True. blend (float, optional): blend rotation value name (None, optional): Name for the blended o_node *args: Maya's dummy Returns: list: blended joints list """ if not oSel: oSel = pm.selected() elif not isinstance(oSel, list): oSel = [oSel] jnt_list = [] for x in oSel: if isinstance(x, pm.nodetypes.Joint): parent = x.getParent() if name: bname = 'blend_' + name else: bname = 'blend_' + x.name() jnt = pm.createNode('joint', n=bname, p=x) jnt_list.append(jnt) jnt.attr('radius').set(1.5) pm.parent(jnt, parent) o_node = pm.createNode("pairBlend") o_node.attr("rotInterpolation").set(1) pm.setAttr(o_node + ".weight", blend) pm.connectAttr(x + ".translate", o_node + ".inTranslate1") pm.connectAttr(x + ".translate", o_node + ".inTranslate2") pm.connectAttr(x + ".rotate", o_node + ".inRotate1") pm.connectAttr(o_node + ".outRotateX", jnt + ".rotateX") pm.connectAttr(o_node + ".outRotateY", jnt + ".rotateY") pm.connectAttr(o_node + ".outRotateZ", jnt + ".rotateZ") pm.connectAttr(o_node + ".outTranslateX", jnt + ".translateX") pm.connectAttr(o_node + ".outTranslateY", jnt + ".translateY") pm.connectAttr(o_node + ".outTranslateZ", jnt + ".translateZ") pm.connectAttr(x + ".scale", jnt + ".scale") jnt.attr("overrideEnabled").set(1) jnt.attr("overrideColor").set(17) jnt.attr("segmentScaleCompensate").set(compScale) try: defSet = pm.PyNode("rig_deformers_grp") except TypeError: pm.sets(n="rig_deformers_grp") defSet = pm.PyNode("rig_deformers_grp") pm.sets(defSet, add=jnt) else: pm.displayWarning("Blended Joint can't be added to: %s. Because " "is not ot type Joint" % x.name()) if jnt_list and select: pm.select(jnt_list) return jnt_list
""" """ 1. Basic example transform parent / child association """ from itertools import izip import pymel.core as pm # 1. PyMEL + list comprehension transforms = ['joint1', 'joint2', 'joint3', 'joint4'] # convert strings to PyNodes transforms = [pm.PyNode(transform) for transform in transforms] # create list of parents parents = [transform.getParent() for transform in transforms] for parent, child in izip(parents, transforms): print('%s > %s' % (parent, child)) # None > joint1 # joint1 > joint2 # joint2 > joint3 # joint3 > joint4 # 2. Strings + list slicing transforms = ['joint1', 'joint2', 'joint3', 'joint4'] for parent, child in izip(transforms[:-1], transforms[1:]): print('%s > %s' % (parent, child)) # joint1 > joint2 # joint2 > joint3
def __plugin_unloader(plugin_name): if not pm.pluginInfo(plugin_name, q=1, loaded=1): logprint('unloading %s!' % plugin_name) pm.unloadPlugin(plugin_name) logprint('%s unloaded!' % plugin_name) # set the optionVar that enables hidden mentalray shaders if pymel.versions.current() <= pymel.versions.v2012: pm.optionVar['MIP_SHD_EXPOSE'] = 1 pm.runtime.SavePreferences() # Change the default camera to Alexa try: persp = pm.PyNode("persp") perspShape = persp.getShape() perspShape.horizontalFilmAperture.set(23.76 / 25.4) perspShape.verticalFilmAperture.set(13.365 / 25.4) except pm.MayaNodeError: pass # set ui to PySide2 for maya2017 if pymel.versions.current() > 201651: logprint('setting QtLib to PySide2 inside userSetup.py') from anima import ui ui.SET_PYSIDE2() logprint('successfully set QtLib to PySide2 inside userSetup.py') else:
def importSkin(filePath=None, *args): if not filePath: startDir = pm.workspace(q=True, rootDirectory=True) filePath = pm.fileDialog2(dialogStyle=2, fileMode=1, startingDirectory=startDir, fileFilter='mGear Skin (*%s)' % FILE_EXT) if not filePath: return if not isinstance(filePath, basestring): filePath = filePath[0] # Read in the file fh = open(filePath, 'rb') dataPack = pickle.load(fh) fh.close() for data in dataPack["objDDic"]: try: skinCluster = False objName = data["objName"] objNode = pm.PyNode(objName) try: meshVertices = pm.polyEvaluate(objNode, vertex=True) importedVertices = len(data['blendWeights']) if meshVertices != importedVertices: pm.displayWarning('Vertex counts do not match. %d != %d' % (meshVertices, importedVertices)) continue except Exception: pass if getSkinCluster(objNode): skinCluster = getSkinCluster(objNode) else: try: joints = data['weights'].keys() skinCluster = pm.skinCluster(joints, objNode, tsb=True, nw=2, n=data['skinClsName']) except Exception: notFound = data['weights'].keys() sceneJoints = set( [pm.PyNode(x).name() for x in pm.ls(type='joint')]) for j in notFound: if j in sceneJoints: notFound.remove(j) pm.displayWarning("Object: " + objName + " Skiped. Can't " "found corresponding deformer for the " "following joints: " + str(notFound)) continue if skinCluster: setData(skinCluster, data) print 'Imported skin for: %s' % objName except Exception: pm.displayWarning("Object: " + objName + " Skiped. Can NOT be " "found in the scene")
def setRes(): # setup RESOLUTION rgRes = pm.PyNode('defaultResolution') rgRes.width.set(1998) rgRes.height.set(1080) rgRes.deviceAspectRatio.set(1.85) rgRes.pixelAspect.set(1)
def an_exp_cc(filterAttr='alembic', exStp=1, ref_mode=True, doCache=True): """ modify date : 2019 07 01 aim at current pipeline ,provide procedure to maya batch tools to proceess animation file output alembic cache AbcExport -j "-frameRange 1000 1100 -ro -uvWrite -worldSpace -writeVisibility -dataFormat ogawa -root |basGrp|cube|pCube1 -root |basGrp|ball|pSphere1 -root |basGrp|pPlane1 -file E:/work/JMWC/cache/alembic/aaassss.abc"; AbcImport -mode replace "E:/work/JMWC/cache/alembic/aaassss.abc"; AbcImport -mode import -setToStartFrame -connect "SMMXW_ch001001TyrannosaurusRex_h_msAnim:FKBS_ch002001TyrannosaurusRex_zhijia SMMXW_ch001001TyrannosaurusRex_h_msAnim:FKBS_ch002001TyrannosaurusRex_yachi SMMXW_ch001001TyrannosaurusRex_h_msAnim:FKBS_ch002001TyrannosaurusRex_shetou SMMXW_ch001001TyrannosaurusRex_h_msAnim:ch002001TyrannosaurusRex_eye_L_01 SMMXW_ch001001TyrannosaurusRex_h_msAnim:ch002001TyrannosaurusRex_eye_L_02 SMMXW_ch001001TyrannosaurusRex_h_msAnim:ch002001TyrannosaurusRex_eye_L_03 SMMXW_ch001001TyrannosaurusRex_h_msAnim:ch002001TyrannosaurusRex_eye_R_01 SMMXW_ch001001TyrannosaurusRex_h_msAnim:ch002001TyrannosaurusRex_eye_R_02 SMMXW_ch001001TyrannosaurusRex_h_msAnim:ch002001TyrannosaurusRex_eye_R_03 SMMXW_ch001001TyrannosaurusRex_h_msAnim:ch002001TyrannosaurusRex_eye_L_01_new SMMXW_ch001001TyrannosaurusRex_h_msAnim:ch002001TyrannosaurusRex_eye_L_02_new SMMXW_ch001001TyrannosaurusRex_h_msAnim:ch002001TyrannosaurusRex_eye_L_03_new SMMXW_ch001001TyrannosaurusRex_h_msAnim:ch002001TyrannosaurusRex_eye_R_01_new SMMXW_ch001001TyrannosaurusRex_h_msAnim:ch002001TyrannosaurusRex_eye_R_02_new SMMXW_ch001001TyrannosaurusRex_h_msAnim:ch002001TyrannosaurusRex_eye_R_03_new SMMXW_ch001001TyrannosaurusRex_h_msAnim:FKBS_ch002001TyrannosaurusRex_body SMMXW_ch001001TyrannosaurusRex_h_msAnim:FKBS_ch002001TyrannosaurusRex_kouqiang SMMXW_ch001001TyrannosaurusRex_h_msAnim:FKBS_ch002001TyrannosaurusRex_body_new SMMXW_ch001001TyrannosaurusRex_h_msAnim:face_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:face_base_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:jaw_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:freq_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:neck_dw_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:neck_up_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:sine_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:face_sec_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:L_eye1_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:L_eye2_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:L_eye3_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:R_eye1_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:R_eye2_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:R_eye3_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:face_sec_loc_geo SMMXW_ch001001TyrannosaurusRex_h_msAnim:new_body_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:body_mus_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:body_all_old_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:body_all_bs SMMXW_ch001001TyrannosaurusRex_h_msAnim:Facial_BG_Plane" -createIfNotFound "E:/work/JMWC/cache/alembic/SMMXW_sc09_sh01_ch001001TyrannosaurusRex.abc"; """ # shotType = 2 # 默认值是2 ,镜头按场次镜头来划分,备用于切分为3的 模式 # exStp = 1 # filterAttr = 'alembic' # filterAttr = None #parse shot information # parse shot information STORDATE = {} scInfo = Ppl_scInfo.Ppl_scInfo() k4m = Kits4maya.Kits4maya() if not mc.pluginInfo('KLJZ_dts.py', q=True, l=True): mc.loadPlugin( "//octvision.com/cg/Tech/maya_sixteen/Plugins/KLJZ_dts.py") if not pm.pluginInfo('AbcExport', q=True, l=True): pm.loadPlugin('AbcExport') if not pm.pluginInfo('AbcImport', q=True, l=True): pm.loadPlugin('AbcImport') error_msg = {} shot_nm_bs = scInfo.scbsnm shot_dir = scInfo.cwd_local shot_nm_repr_lst = [scInfo.proj, scInfo.ID, scInfo.descr ] if scInfo.descr else [scInfo.proj, scInfo.ID] shot_nm_repr = '_'.join(shot_nm_repr_lst) # wsps_cc_dir = pm.workspace(en='cache') # wsps_sc_dir = pm.workspace(en='scenes') wsps_sc_dir = shot_dir wsps_cc_dir = "{}/cache".format(scInfo.projPath_loc) exp_abc_dir = '{}/alembic/'.format(wsps_cc_dir) exp_mb_dir = "{}/mayabatchOPT/{}/".format(wsps_sc_dir, scInfo.scbsnmStrip) if not os.path.isdir(exp_mb_dir): os.makedirs(exp_mb_dir) st_frm = int(pm.playbackOptions(q=True, min=True)) end_frm = int(pm.playbackOptions(q=True, max=True)) # for each reference proc_grps = pm.selected() if not ref_mode else pm.listReferences() # oneRef = proc_grps[-1] if not proc_grps: proc_grps = get_chprGrp(scInfo.proj) ref_mode = False if not proc_grps: pm.error(u"程序没有找到需要做缓存的角色或道具组,请检查角色或者道具组的namespace是否正确。") for oneRef in proc_grps: ref_nsp = oneRef.namespace().strip( ':') if not ref_mode else oneRef.namespace oneRef_top = None if ref_mode: oneRef_top = oneRef.nodes()[0] else: lngnmSpl = oneRef.longName().split('|') n = -1 for m in range(len(lngnmSpl)): if re.search(ref_nsp, lngnmSpl[m]): n = m break oneRef_top = pm.PyNode('|'.join(lngnmSpl[:n + 1])) # ref_f_bsnm = os.path.basename(ref_f) # ref_f_nmspl = ref_f_bsnm.split('_') ref_f_nmspl = ref_nsp.split('_') ref_type = re.search('\w{2}', ref_f_nmspl[1]).group() if ref_type not in ['ch', 'pr']: continue reprChar = re.search("[^\d]+[\d]*$", ref_f_nmspl[1], re.I).group() ref_No = '' if re.search('\d+$', ref_nsp): ref_No = re.search('\d+$', ref_nsp).group() ref_repr_Char4cc = "{}{}".format(ref_f_nmspl[1], ref_No) ref_repr_Char4mb = "{}{}".format(reprChar, ref_No) exp_abc_nm = "{}{}_{}.abc".format(exp_abc_dir, shot_nm_repr, ref_repr_Char4cc) exp_mb_nm = "{}{}_{}_cc.mb".format(exp_mb_dir, shot_nm_repr, ref_repr_Char4mb) need2cc = None if filterAttr: if ref_mode: need2cc = [ e_nd.getParent().longName() for e_nd in oneRef.nodes() if e_nd.type() in [u'mesh'] and e_nd.getParent().hasAttr(filterAttr) ] if not need2cc: need2cc = [ e_nd.getParent().longName() for e_nd in oneRef.nodes() if e_nd.type() in [u'mesh'] and not e_nd.isIntermediate() ] else: need2cc = [ e_nd.getParent().longName() for e_nd in oneRef_top.listRelatives( c=True, type='mesh', ad=True, ni=True) if e_nd.getParent().hasAttr(filterAttr) ] if not need2cc: need2cc = [ e_nd.getParent().longName() for e_nd in oneRef_top.listRelatives( c=True, type='mesh', ni=True, ad=True) ] else: if ref_mode: need2cc = [ e_nd.getParent().longName() for e_nd in oneRef.nodes() if e_nd.type() in [u'mesh'] and not e_nd.isIntermediate() ] else: need2cc = [ e_nd.getParent().longName() for e_nd in oneRef_top.listRelatives( c=True, type='mesh', ni=True, ad=True) ] need2cc.sort() pm.select(need2cc, r=True) # add by zhangben 2019 06 21 老鼠项目,要导出毛发部分 yetiGrp = None if scInfo.proj in ['SLD']: if findNodeByName(oneRef, 'yeti'): yetiGrp = findNodeByName(oneRef, 'yeti') need2cc_str = "-root {}".format(' -root '.join(need2cc)) j_str = "-frameRange {} {} -step {} -uvWrite -writeVisibility -worldSpace {} -f {} -pythonPerFrameCallBack \"print(\\\"...Writing Cache...\\\")\"".format( st_frm, end_frm, exStp, need2cc_str, exp_abc_nm) if doCache: try: mc.AbcExport(j=j_str) print(">>>Cache Generated on disk---{}".format(exp_abc_nm)) except BaseException, e: error_msg[oneRef_top.nodeName()] = e.message else: print(">>>Unnecessary Need To Generate Alembic Cache!!!!!!") if ref_mode: oneRef.importContents() pm.select(need2cc) pm.delete(ch=True) if scInfo.proj in ["SLD"]: for ea_trn_nm in need2cc: ea_trn = pm.PyNode(ea_trn_nm) ea_mesh = ea_trn.getShape() if ea_mesh.listConnections(type="pgYetiGroom"): continue ea_con_sg = ea_mesh.shadingGroups() k4m.power_disconect(ea_mesh, ea_con_sg) chkGrp = [] for n in oneRef_top.getChildren(): for m in need2cc: if n.hasChild(m): chkGrp.append(n) break for eaGrp in chkGrp: if re.search('yeti', eaGrp.name(), re.I): continue allTrns = [ j for j in eaGrp.getChildren(ad=True, type='transform') if j.nodeType() == 'transform' ] for k in allTrns: if k.listConnections(s=True, d=False, type='constraint'): cons_asTarg = k.listConnections(c=True, p=True, s=True, d=False, type='constraint') for ea_c in cons_asTarg: attrName = ea_c[0].attrName() try: ea_c[1] // ea_c[0] if attrName in ['csx', 'csy', 'csz']: eaGrp.attr(attrName).set(1) else: eaGrp.attr(attrName).set(0) except Exception, e: error_msg[ ">>>Break Constraint occurs Error on node {}". format(eaGrp.name())] = e.message