def rigFace() : jntGrp = 'facialJnt_grp' if not mc.objExists(jntGrp) : mc.group(em = True, n = jntGrp) facePolyMap = {'L_brow_ply': 'L_brow_ctrl', 'L_baseEye_ply': 'L_baseEye_ctrl', 'L_eye_ply': 'L_eye_ctrl', 'R_brow_ply': 'R_brow_ctrl', 'R_baseEye_ply': 'R_baseEye_ctrl', 'R_eye_ply': 'R_eye_ctrl', 'nose_ply': 'noseface_ctrl', 'mouth_ply': 'mount_ctrl' } for each in facePolyMap : poly = each ctrl = facePolyMap[poly] if mc.objExists(poly) : movePivot(ctrl, poly) joint = mc.createNode('joint', n = poly.replace('_ply', '_jnt')) mc.delete(mc.pointConstraint(poly, joint)) mc.skinCluster(poly, joint, tsb = True) mc.parentConstraint(ctrl, joint) mc.scaleConstraint(ctrl, joint) mc.parent(joint, jntGrp)
def strandRemovedSlot(self, strand): """ Receives notification from the model when a strand is removed. Deletes the strand related mapping in mayaObjectManager, deletes all the Maya nodes, deletes all the decorators(live in the virtualHelixItem right now), deletes itself from the virtualHelixItem, and disconnects itself from the controller. """ mom = Mom() mID = mom.strandMayaID(strand) mom.removeIDMapping(mID, strand) # print "solidview.StrandItem.strandRemovedSlot %s" % mID transformName = "%s%s" % (mom.helixTransformName, mID) cylinderName = "%s%s" % (mom.helixNodeName, mID) meshName = "%s%s" % (mom.helixMeshName, mID) if cmds.objExists(transformName): cmds.delete(transformName) if cmds.objExists(cylinderName): cmds.delete(cylinderName) if cmds.objExists(meshName): cmds.delete(meshName) if mID in self._virtualHelixItem.StrandIDs(): self._virtualHelixItem.StrandIDs().remove(mID) self._virtualHelixItem.updateDecorators() self._virtualHelixItem.removeStrandItem(self) self._virtualHelixItem = None self._modelStrand = None self._controller.disconnectSignals() self._controller = None
def addScalePP(particle): """ Add a per particle vector(Array) attribute named "scalePP", to the specified particle object. An initial state attribute "scalePP0" will also be created. @param particle: The particle or nParticle object to add the attribute to @type particle: str """ # Check Particle if not cmds.objExists(particle): raise Exception('Particle "' + particle + '" does not exist!') if cmds.objectType(particle) == 'transform': particleShape = cmds.listRelatives(particle, s=True) if not particleShape: raise Exception('Unable to determine particle shape from transform "' + particle + '"!') else: particle = particleShape[0] if (cmds.objectType(particle) != 'particle') and (cmds.objectType(particle) != 'nParticle'): raise Exception('Object "' + particle + '" is not a valid particle or nParticle object!') # Add rotatePP attribute if not cmds.objExists(particle + '.scalePP0'): cmds.addAttr(particle, ln='scalePP0', dt='vectorArray') if not cmds.objExists(particle + '.scalePP'): cmds.addAttr(particle, ln='scalePP', dt='vectorArray') # Return Result return particle + '.scalePP'
def distributeAttrValue(targetList,targetAttr,rangeStart=0.0,rangeEnd=1.0,smoothStep=0.0): ''' Distribute a range of attribute values across list of target objects @param targetList: List of target objects to distribute the attribute values across @type targetList: list @param targetAttr: The target attribute that the distributed values will be applied to @type targetAttr: str @param rangeStart: The distribution range minimum value @type rangeStart: float @param rangeEnd: The distribution range maximum value @type rangeEnd: float @param smoothStep: Amount of value smoothing to apply to the distribution @type smoothStep: float ''' # Check target list for i in range(len(targetList)): if not mc.objExists(targetList[i]): raise UserInputError('Object "'+targetList[i]+'" does not exist!') if not mc.objExists(targetList[i]+'.'+targetAttr): raise UserInputError('Object "'+targetList[i]+'" has no ".'+targetAttr+'" attribute!') # Get value list vList = glTools.utils.mathUtils.distributeValue(len(targetList),1.0,rangeStart,rangeEnd) # Apply values to target list for i in range(len(targetList)): val = vList[i] if smoothStep: val = glTools.utils.mathUtils.smoothStep(val,rangeStart,rangeEnd,smoothStep) mc.setAttr(targetList[i]+'.'+targetAttr,val)
def unparent(shape): ''' Unparent shape nodes from a source parent @param shape: Shape or transform to unparent shapes from @type shape: str ''' # Checks if not mc.objExists(shape): raise Exception('Object "'+shape+'" does not exist!!') # Get shapes if mc.ls(shape,type='transform'): transform = shape shapes = mc.listRelatives(shape,s=True,pa=True) else: transform = mc.listRelatives(shape,p=True,pa=True)[0] shapes = [shape] # Create shape holder shapeHolder = transform+'Shapes' if not mc.objExists(shapeHolder): shapeHolder = mc.createNode('transform',n=shapeHolder) targetXform = mc.xform(transform,q=True,ws=True,m=True) mc.xform(shapeHolder,ws=True,m=targetXform) # Unparent shapes for shape in shapes: mc.parent(shape,shapeHolder,s=True,r=True) # Return Result return shapeHolder
def selectNode(): """ Select node from reference edits UI. """ # Get Selected Ref Node refNode = cmds.textScrollList('refEdits_refListTSL', q=True, si=True) if not refNode: return refNS = glTools.utils.reference.getNamespace(refNode[0]) + ':' # Get Selected Nodes nodeList = cmds.textScrollList('refEdits_nodeListTSL', q=True, si=True) if not nodeList: return # Select Nodes selNodes = [] for node in nodeList: # Check Node editNode = node if not cmds.objExists(node): node = node.split('|')[-1] if not cmds.objExists(node): node = refNS + node if not cmds.objExists(node): raise Exception('Reference edit node "' + editNode + '" not found!') # Append to Selection List selNodes.append(node) # Select Node if selNodes: cmds.select(selNodes)
def _publish_gpu_for_item(self, item, output, work_template, primary_publish_path, sg_task, comment, thumbnail_path, progress_cb): """ Export a gpu cache for the specified item and publish it to Shotgun. """ group_name = item["name"].strip("|") debug(app = None, method = '_publish_gpu_for_item', message = 'group_name: %s' % group_name, verbose = False) tank_type = output["tank_type"] publish_template = output["publish_template"] # get the current scene path and extract fields from it using the work template: scene_path = os.path.abspath(cmds.file(query=True, sn= True)) fields = work_template.get_fields(scene_path) publish_version = fields["version"] # update fields with the group name: fields["grp_name"] = group_name ## create the publish path by applying the fields with the publish template: publish_path = publish_template.apply_fields(fields) #'@asset_root/publish/gpu/{name}[_{grp_name}].v{version}.abc' gpuFileName = os.path.splitext(publish_path)[0].split('\\')[-1] fileDir = '/'.join(publish_path.split('\\')[0:-1]) debug(app = None, method = '_publish_gpu_for_item', message = 'gpuFileName: %s' % gpuFileName, verbose = False) ## Now fix the shaders shd.fixDGForGPU() if cmds.objExists('CORE_ARCHIVES_hrc'): cmds.setAttr('CORE_ARCHIVES_hrc.visiblity', 0) if cmds.objExists('ROOT_ARCHIVES_DNT_hrc'): cmds.setAttr('ROOT_ARCHIVES_DNT_hrc.visiblity', 0) ## build and execute the gpu cache export command for this item: try: print '=====================' print 'Exporting gpu now to %s\%s' % (fileDir, gpuFileName) #PUT THE FILE EXPORT COMMAND HERE cmds.select(clear = True) for geo in cmds.listRelatives(group_name, children = True): if 'geo_hrc' in geo: geoGroup = str(group_name) debug(app = None, method = '_publish_gpu_for_item', message = 'geoGroup: %s' % geoGroup, verbose = False) cmds.select(geoGroup) debug(app = None, method = '_publish_gpu_for_item', message = 'geoGroup: %s' % geoGroup, verbose = False) debug(app = None, method = '_publish_gpu_for_item', message = "gpuCache -startTime 1 -endTime 1 -optimize -optimizationThreshold 40000 -directory \"%s\" -fileName %s %s;" % (fileDir, gpuFileName, geoGroup), verbose = False) mel.eval("gpuCache -startTime 1 -endTime 1 -optimize -optimizationThreshold 40000 -directory \"%s\" -fileName %s %s;" % (fileDir, gpuFileName, geoGroup)) print 'Finished gpu export...' print '=====================' if cmds.objExists('dgSHD'): ## Now reconnect the FileIn nodes for key, var in filesDict.items(): cmds.connectAttr('%s.outColor' % key, '%s.color' % var) except Exception, e: raise TankError("Failed to export gpu cache file")
def orientJoints(s): """ Face joints in the correct direction. """ sel = cmds.ls(sl=True) err = cmds.undoInfo(openChunk=True) try: markers = s.markers joints = markers.keys() with ReSeat(joints): for j in joints: m = markers[j] if cmds.objExists(m.marker) and cmds.objExists(j): with Isolate(j): m.setJoint() try: cmds.makeIdentity( j, apply=True, r=True) # Freeze Rotations except RuntimeError: pass else: # User deleted marker / joint. Stop tracking. m.removeMarker() del markers[j] cmds.select(sel, r=True) except Exception as err: raise finally: cmds.undoInfo(closeChunk=True) if err: cmds.undo()
def matchUsing(transform, reference, target): """ Match the specified transform to a target transform, relative to a reference transform @param transform: Transform to set @type transform: str @param reference: Reference transform @type reference: str @param target: Target transform to match to @type target: str """ # Checks if not cmds.objExists(transform): raise Exception('Transform "' + transform + '" does not exist!') if not cmds.objExists(reference): raise Exception('Reference transform "' + target + '" does not exist!') if not cmds.objExists(target): raise Exception('Target transform "' + target + '" does not exist!') # Get Transform, Target and Reference Matrices trMat = getMatrix(transform) rfMat = getMatrix(reference) tgMat = getMatrix(target) # Calculate Transform Target resultMat = trMat * rfMat.inverse() * tgMat # Set Transform Matrix setFromMatrix(transform, resultMat)
def exportRig(self): """ will export SH and Geo found in the geo folder """ # rig and geo should not be referenced # find SH, delete constraints, parent to world # find geo folder parent to world # select SH and geo folder and export as fbx to fbx folder pymelLogger.debug( 'Starting rig export' ) export = 0 for rig in self.rootList: if cmds.objExists(rig): # check if geo folder also exists if cmds.objExists(self.geo): self._delConstraints(rig) cmds.parent(rig, w=1) cmds.parent(self.geo, w=1) cmds.select(rig,self.geo, r=1) #print rig, self.geo if self._fbxExport( 2 ): cmds.confirmDialog(m='FBX Rig Exported', button='Ok') pymelLogger.debug( 'Finished rig export' ) export = 1 break else: pymelLogger.error( 'No geo folder has been found' ) if export == 0 : pymelLogger.error( 'No Rig Exported. Note: Referenced Rigs Will Not Export' )
def doSyncInfo(self) : asset = entityInfo.info() rigGrps = ['Rig_Grp', 'Rig:Rig_Grp'] assetID = self.getAssetID() attrs = ['assetID', 'assetType', 'assetSubType', 'assetName', 'project'] values = [assetID, asset.type(), asset.subType(), asset.name(), asset.project()] geoGrps = ['Geo_Grp', 'Rig:Geo_Grp'] refPath = asset.getPath('ref') pipelineTools.assignGeoInfo() for rigGrp in rigGrps : if mc.objExists(rigGrp) : i = 0 for each in attrs : attr = '%s.%s' % (rigGrp, each) if mc.objExists(attr) : if not each == 'assetID' : mc.setAttr(attr, values[i], type = 'string') else : mc.setAttr(attr, values[i]) i += 1 for geoGrp in geoGrps : if mc.objExists(geoGrp) : mc.setAttr('%s.%s' % (geoGrp, 'id'), assetID) mc.setAttr('%s.%s' % (geoGrp, 'ref'), refPath, type = 'string') self.setStatus('Sync info', True) self.messageBox('Information', 'Sync Complete')
def __setup_final_meshes(self): #--- this method setups the final meshes if 'FINAL' in self.mesh: if cmds.objExists(self.mesh): self.final_mesh = self.mesh else: self.final_mesh = cmds.duplicate(self.mesh) cmds.parent(self.final_mesh, self.sf_final_meshes) final_name = cmds.rename(self.final_mesh, self.mesh) self.final_mesh = final_name else: if cmds.objExists(self.mesh + 'FINAL'): self.final_mesh = self.mesh + 'FINAL' else: self.final_mesh = cmds.duplicate(self.mesh) cmds.parent(self.final_mesh, self.sf_final_meshes) final_name = cmds.rename(self.final_mesh, self.mesh + 'FINAL') self.final_mesh = final_name if cmds.objExists(self.mesh + '_BSP'): #--- setup blendShape deformer self.final_bsp = self.mesh + '_BSP' cmds.setAttr(self.final_bsp + '.' + self.mesh, 1) cmds.setAttr(self.mesh + '.v', 0) else: if 'FINAL' in self.mesh: self.mesh = self.mesh.split('FINAL')[0] self.final_bsp = cmds.blendShape(self.mesh, self.final_mesh, name = self.mesh + '_BSP')[0] cmds.setAttr(self.final_bsp + '.' + self.mesh, 1) cmds.setAttr(self.mesh + '.v', 0)
def add(self,objectList): ''' Adds the channel state attr to all specified objects @param objectList: List of objects to add flags to @type objectList: list ''' # Add Channel State Attrs for obj in objectList: # Check obj if not mc.objExists(obj): raise Exception('Object "'+obj+'" does not exist!') if not glTools.utils.transform.isTransform(obj): raise Exception('Object "'+obj+'" is not a valid transform!') if mc.objExists(obj+'.channelState'): print ('Object "'+obj+'" already has a "channelState" attribute! Skipping...') # Add channelState attr #mc.addAttr(obj,ln='channelState',at='enum',en=':Keyable:NonKeyable:Locked:',m=1,dv=-1) mc.addAttr(obj,ln='channelState',at='enum',en=':Keyable:NonKeyable:Locked:',m=1) # Set channelState flag values for i in range(len(self.channel)): if mc.getAttr(obj+'.'+self.channel[i],l=1): # Set Locked State mc.setAttr(obj+'.channelState['+str(i)+']',2) elif not mc.getAttr(obj+'.'+self.channel[i],k=1): # Set NonKeyable State mc.setAttr(obj+'.channelState['+str(i)+']',1) else: # Set Keyable State mc.setAttr(obj+'.channelState['+str(i)+']',0) # Alias Attribute mc.aliasAttr(self.channel[i]+'_state',obj+'.channelState['+str(i)+']')
def __add_root_attributes(self): #--- globalScale if not cmds.objExists(self.root + ".globalScale"): cmds.addAttr(self.root, longName="globalScale", min=0, defaultValue=1, attributeType='float') cmds.setAttr(self.root + '.globalScale', edit=True, keyable=False, channelBox=True) #--- project if not cmds.objExists(self.root + ".project"): cmds.addAttr(self.root, longName="project", dataType='string') cmds.setAttr(self.root + '.project', self.assetInfo[0], type='string', lock=True) #--- assetType if not cmds.objExists(self.root + ".assetType"): cmds.addAttr(self.root, longName="assetType", dataType='string') cmds.setAttr(self.root + '.assetType', self.assetInfo[1], type='string', lock=True) #--- assetResolution if not cmds.objExists(self.root + ".assetResolution"): cmds.addAttr(self.root, longName="assetResolution", dataType='string') cmds.setAttr(self.root + '.assetResolution', self.assetInfo[2], type='string', lock=True) #--- assetName if not cmds.objExists(self.root + ".assetName"): cmds.addAttr(self.root, longName="assetName", dataType='string') cmds.setAttr(self.root + '.assetName', self.assetInfo[3], type='string', lock=True)
def processItems(self, sender = None, all = False, case = ''): cmds.undoInfo(openChunk = True) cmds.select(clear = True) if not all: for eachItem in self._getSelItems(): itemName = eachItem.text().replace(SEP, "|") if not cmds.objExists(itemName): itemName = itemName.split("|")[-1] or None if itemName: if case == 'select': cmds.select(itemName, add = True, ne = True) elif case == 'delete': cmds.delete(itemName) elif case == 'deleteCH': cmds.delete(itemName, ch = True) else: count = self.reportTree.count() items = [] for x in range(count): if "-----" not in self.reportTree.item(x).text(): itemName = self.reportTree.item(x).text().replace(SEP, "|") if not cmds.objExists(itemName): itemName = itemName.split("|")[-1] or None if itemName: items.extend([itemName]) if case == 'select': cmds.select(items, r = True, ne = True) elif case == 'delete': cmds.delete(items) elif case == 'deleteCH': cmds.delete(items, ch = True) cmds.undoInfo(closeChunk = True)
def _findRelativesByType(self, embeddedRoot, resList=['lo', 'md', 'hi', 'apos'], byType='shape', resExcludeList=[]): shapes = None searchResList = list(set(resList) - set(resExcludeList)) #print 'searchResList: %s'%searchResList if embeddedRoot != 'master': shapes = [] for res in searchResList: if cmds.objExists('%s|%s'%(embeddedRoot, res)): resShapes = cmds.listRelatives('%s|%s'%(embeddedRoot, res), ad=True, type=byType, f=True) if resShapes: shapes.extend(resShapes) if not shapes: shapes = None else: embeddedCodes = self._findEmbeddedAssets() index = embeddedCodes.index('master') embeddedCodes.pop(index) if cmds.objExists('|master'): children = cmds.listRelatives('|master') if children: shapes = [] for child in children: if child not in embeddedCodes: if child in searchResList: #print 'child:%s' % child if cmds.objExists('|master|%s'%child): childShapes = cmds.listRelatives('|master|%s'%child, ad=True, type=byType, f=True) if childShapes: shapes.extend(childShapes) if not shapes: shapes = None return shapes
def addOverrideTarget(geo, targetGeo, targetWeight=0): """ Add override blendShape target to the specified geometry. @param geo: The geometry to add an override blendShape target to. @type geo: str @param targetGeo: The override target geometry to add to the blendShape deformer. @type targetGeo: str @param targetWeight: The override target blend weight to apply. @type targetWeight: float """ # Checks if not cmds.objExists(geo): raise Exception('Base geometry "' + geo + '" does not exist!!') if not cmds.objExists(targetGeo): raise Exception('Target geometry "' + targetGeo + '" does not exist!!') # Get Override BlendShape blendShape = geo.split(":")[-1] + "_override_blendShape" if not cmds.objExists(blendShape): blendShape = geo + "_override_blendShape" if not cmds.objExists(blendShape): raise Exception('Override blendShape "' + blendShape + '" does not exist!!') # Add Target targetAttr = glTools.utils.blendShape.addTarget( blendShape=blendShape, target=targetGeo, base=geo, targetWeight=targetWeight, topologyCheck=False ) # Return Result return targetAttr
def updateOrigNamesFormat(self,objectList=[]): ''' Update a combined meshes origNames attribute to the newest format. @param objectList: list of mesh objects to update origNames attribute on. @type objectList: list ''' # Confirm list if type(objectList) == str: objectList = [objectList] # Iterate through object list for obj in objectList: # Check origNames attribute if not mc.objExists(obj+'.origNames'): raise Exception('Object '+obj+' does not have a "origNames" attribute!') if mc.addAttr(obj+'.origNames',q=True,multi=True): print(obj+'.origNames is already in the correct format.') continue # Extract original names list from old format origNamesList = [] index = 0 while True: if mc.objExists(obj+'.origNames.origNames_'+str(index)): origNamesList.append(mc.getAttr(obj+'.origNames.origNames_'+str(index))) index+=1 else: break # Re-create the origNames attribute in the new format mc.deleteAttr(obj+'.origNames') mc.addAttr(obj,ln='origNames',dt='string',multi=True) for i in range(len(origNamesList)): mc.setAttr( obj+'.origNames['+str(i)+']', origNamesList[i], type='string')
def combine(self, objs=[], new_name="", keepHistory=0): ''' Combines the geometry and stores the names. This is useful for speeding up the rigs and seperating in a predictible way. @param objs: Mesh objects to combine @type objs: list @param new_name: New name for the combined mesh @type new_name: str @param keepHistory: Maintain history after function has completed @type keepHistory: bool ''' # Check input arguments if not objs: raise Exception('Input list "objs" is not a valid list!') for obj in objs: if not mc.objExists(obj): raise Exception('Object '+obj+' does not exist!') if mc.objExists(new_name): raise Exception('An object of name '+new_name+' already exists! Please choose another name!') # Combine multiple mesh objects to a single mesh new_obj = mc.polyUnite(objs, n=new_name) mc.addAttr( new_obj[0], ln='origNames', dt='string', multi=True) # Recond original names list on new mesh transform for i in range(len(objs)): mc.setAttr( new_obj[0]+'.origNames['+str(i)+']', objs[i], type='string') # Delete history if not keepHistory : mc.delete(new_obj[1]) mc.delete(objs) return new_obj[0]
def test_createRig(self): scene = cwd + os.sep + "tests/scenes/test_createRig.ma" cmds.file(scene, o=True, f=True) self.rig.createRig( name="test", baseTransform="joint2", targetTransform="joint3", control="control", aim="y", up="z", wup="y" ) self.assertTrue(cmds.objExists("test_multiAxisRigGrp")) self.assertTrue(cmds.objExists("test_multiAxisRigGrpParentConst")) self.assertTrue(cmds.objExists("test_multiAxisRigPlane")) self.assertTrue(cmds.objExists("test_multiAxisRigPlanePointConst")) self.assertTrue(cmds.objExists("test_multiAxisRigLoc")) self.assertTrue(cmds.objExists("test_multiAxisRigCPOS")) self.assertTrue(cmds.objExists("test_multiAxisRigLocGeoConst")) self.assertTrue(cmds.objExists("test_multiAxisRigLocPointConst")) self.assertTrue(cmds.objExists("control.test_u")) self.assertTrue(cmds.objExists("control.test_v")) self.assertEqual(cmds.getAttr("control.test_u"), 0.5) self.assertEqual(cmds.getAttr("control.test_v"), 0.5) cmds.rotate(0, 90, 0, "joint2", a=True) self.assertEqual(cmds.getAttr("control.test_u"), 0) cmds.rotate(0, 0, 90, "joint2", a=True) self.assertEqual(cmds.getAttr("control.test_v"), 0) cmds.rotate(0, -90, 0, "joint2", a=True) self.assertEqual(cmds.getAttr("control.test_u"), 1) cmds.rotate(0, 0, -90, "joint2", a=True) self.assertEqual(cmds.getAttr("control.test_v"), 1)
def matchInternalPoseObjects(self, nodes=None, fromFilter=True): ''' This is a throw-away and only used in the UI to select for debugging! from a given poseFile return or select the internal stored objects ''' InternalNodes=[] if not fromFilter: #no filter, we just pass in the longName thats stored for key in self.poseDict.keys(): if cmds.objExists(self.poseDict[key]['longName']): InternalNodes.append(self.poseDict[key]['longName']) elif cmds.objExists(key): InternalNodes.append(key) elif cmds.objExists(r9Core.nodeNameStrip(key)): InternalNodes.append(r9Core.nodeNameStrip(key)) else: #use the internal Poses filter and then Match against scene nodes if self.settings.filterIsActive(): filterData=r9Core.FilterNode(nodes,self.settings).ProcessFilter() matchedPairs=self._matchNodesToPoseData(filterData) if matchedPairs: InternalNodes=[node for _,node in matchedPairs] if not InternalNodes: raise StandardError('No Matching Nodes found!!') return InternalNodes
def set(self,state,objectList=[]): ''' Set channel states based on channelState multi attribute @param state: The state to set object channels to @type state: int @param objList: List of objects to set channels states for @type objList: list ''' # Check objectList if type(objectList) == str: objectList = [objectList] if not objectList: objectList = mc.ls('*.channelState',o=True) # For each object in list for obj in objectList: # Get channel state values channelState = self.get(obj) if not len(channelState): continue if len(channelState) != 10: raise UserInputError('Attribute "'+obj+'.channelState" is not the expected length (10)!') if state: for i in range(len(self.channel)): if not channelState[i]: mc.setAttr(obj+'.'+self.channel[i],l=0,k=1) elif channelState[i] == 1: mc.setAttr(obj+'.'+self.channel[i],l=0,k=0) elif channelState[i] == 2: mc.setAttr(obj+'.'+self.channel[i],l=1,k=0) # radius if mc.objExists(obj+'.radius'): mc.setAttr(obj+'.radius',l=0,k=0) else: for attr in self.channel: mc.setAttr(obj+'.'+attr,l=0,k=1) if mc.objExists(obj+'.radius'): mc.setAttr(obj+'.radius',l=0,k=1)
def doAnimRig(self) : path = str(self.ui.path_lineEdit.text()) texturePath = '%s/textures' % path animRes = str(self.ui.animRes_comboBox.currentText()) facialCore.path = texturePath facialCore.animRes = animRes if mc.objExists(self.renderHeadName) : previewHead = mc.duplicate(self.renderHeadName, n = self.previewHeadName)[0] # render node ltNode = facialCore.makeAnimFacial(facialCore.renderLayerTextureName) # create lambert if not mc.objExists(self.animNode) : mtl = mc.shadingNode('lambert', asShader = True, n = self.animNode) # connect mc.connectAttr('%s.outColor' % ltNode, '%s.color' % mtl, f = True) # assign mc.select(previewHead) mc.hyperShade(assign = mtl) self.messageBox('Success', 'Set Anim Node Complete')
def setDeformerAttrConnections(self): ''' Set custom (non-standard) deformer attribute connections based on the stored deformer connection data. ''' # ==================================== # - Set Custom Attribute Connections - # ==================================== for attr in self._data['attrConnectionDict'].iterkeys(): # Define Deformer Attribute deformerAttr = self._data['name']+'.'+attr # Check connection destination if not mc.objExists(deformerAttr): print('Deformer attribute connection destination "'+deformerAttr+'" does not exist!('+self._data['name']+')') continue # Check connection destination settable state if not mc.getAttr(deformerAttr,se=True): print('Deformer attribute connection destination "'+deformerAttr+'" is not settable!('+self._data['name']+')') continue # Check connection source if not mc.objExists(self._data['attrConnectionDict'][attr]): print('Deformer attribute connection source "'+self._data['attrConnectionDict'][attr]+'" does not exist!('+self._data['name']+')') continue # Create Connection mc.connectAttr(self._data['attrConnectionDict'][attr],deformerAttr,f=True)
def doRenderRig(self) : path = str(self.ui.path_lineEdit.text()) texturePath = '%s/textures' % path renderRes = str(self.ui.renderRes_comboBox.currentText()) facialCore.path = texturePath facialCore.res = renderRes if mc.objExists(self.defaultHeadName) : # rename mc.rename(self.defaultHeadName, self.renderHeadName) # group group = mc.group(em = True, n = self.stillGroup) mc.parent(self.renderHeadName, group) # render node ltNode = facialCore.makeRenderFacial() # create lambert if not mc.objExists(self.renderNode) : vrayMtl = mc.shadingNode('VRayMtl', asShader = True, n = self.renderNode) # connect mc.connectAttr('%s.outColor' % ltNode, '%s.color' % vrayMtl, f = True) # assign mc.select(self.renderHeadName) mc.hyperShade(assign = vrayMtl) self.messageBox('Success', 'Set Render Node Complete') else : self.messageBox('Warning', '%s not Exists' % self.defaultHeadName)
def connectToTargetFromUI(): ''' ''' # Get UI Data blendShape = mc.textScrollList('bsMan_blendShapeTSL',q=True,si=True) if not blendShape: print('No blendShape node selected!') return base = mc.textScrollList('bsMan_baseGeomTSL',q=True,si=True) if not base: base = [''] target = mc.textScrollList('bsMan_targetsTSL',q=True,si=True) if not target: print('No blendShape target selected!') return targetGeo = mc.textFieldButtonGrp('bsMan_connectTargetTFB',q=True,text=True) targetWt = mc.floatSliderGrp('bsMan_connectTargetFSG',q=True,v=True) # Checks if not glTools.utils.blendShape.isBlendShape(blendShape[0]): raise Exception('BlendShape "'+blendShape[0]+'" does not exist!') if base[0] and not mc.objExists(base[0]): raise Exception('Base geometry "'+base[0]+'" does not exist!') if not mc.objExists(targetGeo): raise Exception('Target geometry "'+targetGeo+'" does not exist!') # Add BlendShape Target Inbetween glTools.utils.blendShape.connectToTarget( blendShape=blendShape[0], targetGeo=targetGeo, targetName=targetName[0], baseGeo=base[0], weight=1.0 ) # Reload reloadUI()
def bsManUpdateTargetsFromUI(): ''' ''' # Get UI Data blendShape = mc.textScrollList('bsMan_blendShapeTSL',q=True,si=True) if not blendShape: print('No blendShape node selected!') return base = mc.textScrollList('bsMan_baseGeomTSL',q=True,si=True) if not base: raise Exception('No base (old) geometry specified!') oldBase = base[0] newBase = mc.textFieldButtonGrp('bsMan_updateTargetTFB',q=True,text=True) targetList = mc.textScrollList('bsMan_targetsTSL',q=True,si=True) # Checks if not glTools.utils.blendShape.isBlendShape(blendShape[0]): raise Exception('BlendShape "'+blendShape[0]+'" does not exist!') if not mc.objExists(oldBase): raise Exception('Old base geometry "'+oldBase+'" does not exist!') if not mc.objExists(newBase): raise Exception('New base geometry "'+newBase+'" does not exist!') if not targetList: raise Exception('Empty target list!') # Get Target Geometry targetGeoList = [] for target in targetList: targetGeo = glTools.utils.blendShape.getTargetGeo(blendShape[0],target,baseGeo=oldBase) if not targetGeo: print('No target geometry found for target name"'+target+'"! Skipping') continue targetGeoList.append(targetGeo) # Update Targets glTools.tools.blendShape.updateTargets(oldBase,newBase,targetGeoList)
def on_actionStartMove_triggered(self, args=None): if args==None:return toMoveOBJ = str(self.MovedOBJLineEdit.text()) toKeepOBJ = str(self.KeepedOBJLineEdit.text()) if not mc.objExists(toMoveOBJ) or not mc.objExists(toKeepOBJ):return if toMoveOBJ == toKeepOBJ:return self.ConstraintDT = {} self.ConstraintLocators = [] for Jnt in (toKeepOBJ, toMoveOBJ): OldConstraintNode = [x for x in mc.listRelatives(Jnt, c=True, path=True) or [] if mc.nodeType(x).endswith('Constraint')] for OCSN in OldConstraintNode: ConstraintType = mc.nodeType(OCSN) ConstraintOBJ = eval('mc.%s("%s", q=True, tl=True)'%(ConstraintType, OCSN)) self.ConstraintDT.setdefault(Jnt, {})['type'] = ConstraintType self.ConstraintDT.setdefault(Jnt, {})['ConsOBJ'] = ConstraintOBJ mc.delete(OCSN) Loc = mc.spaceLocator(p=(0,0,0)) mc.delete(mc.parentConstraint(Jnt, Loc)) ConstraintNode = mc.parentConstraint(Loc[0], Jnt) self.ConstraintLocators.append(Loc[0]) self.ConstraintLocators.append(ConstraintNode[0])
def addTargetFromUI(): ''' ''' # Get UI Data blendShape = mc.textScrollList('bsMan_blendShapeTSL',q=True,si=True) if not blendShape: print('No blendShape node selected!') return base = mc.textScrollList('bsMan_baseGeomTSL',q=True,si=True) if not base: base = [''] targetGeo = mc.textFieldButtonGrp('bsMan_addTargetGeoTFB',q=True,text=True) targetName = mc.textFieldGrp('bsMan_addTargetNameTFG',q=True,text=True) # Checks if not glTools.utils.blendShape.isBlendShape(blendShape[0]): raise Exception('BlendShape "'+blendShape[0]+'" does not exist!') if base[0] and not mc.objExists(base[0]): raise Exception('Base geometry "'+base[0]+'" does not exist!') if not mc.objExists(targetGeo): raise Exception('Target geometry "'+targetGeo+'" does not exist!') # Add BlendShape Target glTools.utils.blendShape.addTarget( blendShape=blendShape[0], target=targetGeo, base=base[0], targetIndex=-1, targetAlias=targetName, targetWeight=0.0, topologyCheck=False ) # Reload reloadUI()
def assignShader(self): if not cmds.objExists(str(self.shaderToAssign)): if self.shaderToAssign.endswith("SG") and cmds.objExists(str(self.shaderToAssign)[:-2]): self.shaderToAssign = self.interface.createSG(str(self.shaderToAssign)[:-2]) else: return if not cmds.nodeType(self.shaderToAssign) == "shadingEngine": self.shaderToAssign = self.interface.createSG(str(self.shaderToAssign)) path = self.getPath() self.cache.assignShader(path, self.shaderToAssign) selectedItems = self.interface.hierarchyWidget.selectedItems() if len(selectedItems) > 1: for item in selectedItems: if item is not self: item.cache.assignShader(item.getPath(), self.shaderToAssign) self.interface.checkShaders(self.interface.getLayer(), item=self) self.interface.hierarchyWidget.resizeColumnToContents(1)
def _remove_unused_items(self, parent_item): for row in reversed(xrange(parent_item.rowCount())): child = parent_item.child(row) if not cmds.objExists(child.text()): parent_item.removeRow(row)
def visCtrl(*args): ''' Set up visibility control for the rig. ''' visCtrl = cmds.ls(sl=True)[0] # Check if attributes exists visAttrDic = { 'lodVis': ['enum', 'Low', 'Mid', 'High'], 'geometryVis': ['enum', 'Normal', 'Template', 'Reference'], 'extraControlVis': ['bool'], 'facialControlVis': ['bool'], 'floorContactCheckVis': ['bool'] } for visAttr in visAttrDic.keys(): if cmds.objExists('%s.%s' % (visCtrl, visAttr)): continue else: if visAttrDic[visAttr][0] == 'enum': joinStr = ':' cmds.addAttr(visCtrl, ln=visAttr, at=visAttrDic[visAttr][0], en=joinStr.join(visAttrDic[visAttr][1:])) cmds.setAttr('%s.%s' % (visCtrl, visAttr), channelBox=True) elif visAttrDic[visAttr][0] == 'bool': if visAttr == 'modelVis': cmds.addAttr(visCtrl, ln=visAttr, at=visAttrDic[visAttr][0], keyable=False) if cmds.objExists('lod01_GRP'): models = cmds.listRelatives('lod01_GRP') if models: for model in models: cmds.connectAttr('%s.%s' % (visCtrl, visAttr), '%s.visibility' % model, f=True) if cmds.objExists('lod02_GRP'): models = cmds.listRelatives('lod02_GRP') for model in models: cmds.connectAttr('%s.%s' % (visCtrl, visAttr), '%s.visibility' % model, f=True) else: models = cmds.listRelatives('lod03_GRP') for model in models: cmds.connectAttr('%s.%s' % (visCtrl, visAttr), '%s.visibility' % model, f=True) else: cmds.addAttr(visCtrl, ln=visAttr, at=visAttrDic[visAttr][0]) cmds.setAttr('%s.%s' % (visCtrl, visAttr), channelBox=True) # Connect attributes if not cmds.isConnected('%s.geometryVis' % visCtrl, 'geo_layer.displayType'): cmds.connectAttr('%s.geometryVis' % visCtrl, 'geo_layer.displayType', f=True) if cmds.objExists('facial_gui_grp'): if not cmds.isConnected('%s.facialControlVis' % visCtrl, 'facial_gui_grp.visibility'): cmds.connectAttr('%s.facialControlVis' % visCtrl, 'facial_gui_grp.visibility', f=True) if cmds.objExists('extra_ctrl_grp'): if not cmds.isConnected('%s.extraControlVis' % visCtrl, 'extra_ctrl_grp.visibility'): cmds.connectAttr('%s.extraControlVis' % visCtrl, 'extra_ctrl_grp.visibility', f=True) if cmds.objExists('floorContactCheck_geo'): if not cmds.isConnected('%s.floorContactCheckVis' % visCtrl, 'floorContactCheck_geo.visibility'): cmds.connectAttr('%s.floorContactCheckVis' % visCtrl, 'floorContactCheck_geo.visibility', f=True) # LOD visibility control setup if cmds.objExists('lod01_GRP'): mel.eval('CBdeleteConnection "lod01_GRP.visibility"') if cmds.objExists('lod02_GRP'): mel.eval('CBdeleteConnection "lod02_GRP.visibility"') if cmds.objExists('lod03_GRP'): mel.eval('CBdeleteConnection "lod03_GRP.visibility"') if cmds.objExists('lod02_GRP') and cmds.objExists('lod01_GRP'): cmds.setDrivenKeyframe('lod01_GRP.visibility', cd='%s.lodVis' % visCtrl, dv=0, v=1) cmds.setDrivenKeyframe('lod02_GRP.visibility', cd='%s.lodVis' % visCtrl, dv=0, v=0) cmds.setDrivenKeyframe('lod03_GRP.visibility', cd='%s.lodVis' % visCtrl, dv=0, v=0) cmds.setDrivenKeyframe('lod01_GRP.visibility', cd='%s.lodVis' % visCtrl, dv=1, v=0) cmds.setDrivenKeyframe('lod02_GRP.visibility', cd='%s.lodVis' % visCtrl, dv=1, v=1) cmds.setDrivenKeyframe('lod03_GRP.visibility', cd='%s.lodVis' % visCtrl, dv=1, v=0) cmds.setDrivenKeyframe('lod01_GRP.visibility', cd='%s.lodVis' % visCtrl, dv=2, v=0) cmds.setDrivenKeyframe('lod02_GRP.visibility', cd='%s.lodVis' % visCtrl, dv=2, v=0) cmds.setDrivenKeyframe('lod03_GRP.visibility', cd='%s.lodVis' % visCtrl, dv=2, v=1) elif cmds.objExists('lod02_GRP') and not cmds.objExists('lod01_GRP'): cmds.setDrivenKeyframe('lod02_GRP.visibility', cd='%s.lodVis' % visCtrl, dv=0, v=0) cmds.setDrivenKeyframe('lod03_GRP.visibility', cd='%s.lodVis' % visCtrl, dv=0, v=0) cmds.setDrivenKeyframe('lod02_GRP.visibility', cd='%s.lodVis' % visCtrl, dv=1, v=1) cmds.setDrivenKeyframe('lod03_GRP.visibility', cd='%s.lodVis' % visCtrl, dv=1, v=0) cmds.setDrivenKeyframe('lod02_GRP.visibility', cd='%s.lodVis' % visCtrl, dv=2, v=0) cmds.setDrivenKeyframe('lod03_GRP.visibility', cd='%s.lodVis' % visCtrl, dv=2, v=1) elif cmds.objExists('lod02_GRP') and not cmds.objExists('lod01_GRP'): pass # Dynamic control visibility setup if cmds.objExists('dyn_ctr_crv'): if cmds.objExists('dyn_ctr_crv.clothSolverOnOff') and cmds.objExists( 'dyn_ctr_crv.hairSolverOnOff'): dynExprStr = ''' // Expression for Dynamic Visibility // string $clothSolverState = dyn_ctr_crv.clothSolverOnOff; string $hairSolverState = dyn_ctr_crv.hairSolverOnOff; if (($hairSolverState == 1) || ($clothSolverState == 1)){ geometry.visibility = 0; Geometry.visibility = 0; } else if (($hairSolverState == 0) && ($clothSolverState == 0)){ geometry.visibility = 1; Geometry.visibility = 1; } ''' cmds.expression(s=dynExprStr, ae=True, uc='all', n='dynVis_expr') # Turn off smooth preview for low poly group. if cmds.objExists('lod02_GRP'): cmds.select("lod02_GRP", r=True) mel.eval('setDisplaySmoothness 1;') cmds.select(visCtrl, r=True)
def prepareForExportFBX(self, path, startFrame, endFrame, *args): sys.__stdout__.write("Preparing the File...\n") #get the characters in the scene characters = self.getCharacters() #get rotation interp options = cmds.optionVar(list=True) for op in options: if op == "rotationInterpolationDefault": interp = cmds.optionVar(q=op) cmds.optionVar(iv=("rotationInterpolationDefault", 3)) #Loop through each character in the scene, and export the fbx for that character cmds.progressBar(self.widgets["currentFileProgressBar"], edit=True, progress=40) #create increment ammount for progress bar increment = 50 / len(characters) step = increment / 5 #NEW: If use anim sequence info, get that info now if cmds.checkBox(self.widgets["useSequenceInfo"], q=True, v=True) == True: if cmds.objExists("ExportAnimationSettings"): sys.__stdout__.write("Using file anim sequence data" + "\n") sequeneces = cmds.listAttr("ExportAnimationSettings", string="sequence*") for seq in sequeneces: #get data data = cmds.getAttr("ExportAnimationSettings." + seq) dataList = data.split("::") name = dataList[0] start = dataList[1] end = dataList[2] fps = dataList[3] interp = dataList[4] sys.__stdout__.write("Export Sequence ------------->: " + str(name) + "\n") try: exportCharacter = dataList[5] except: if len(characters) > 1: characterString = "" for char in characters: characterString += str(char) + " or " result = cmds.promptDialog( title='No Character Data Found', message='Enter Name: ' + characterString, button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if result == 'OK': exportCharacter = cmds.promptDialog(query=True, text=True) else: exportCharacter = characters[0] if interp == "Independent Euler Angle": interp = 1 if interp == "Synchronized Euler Angle": interp = 2 if interp == "Quaternion Slerp": interp = 3 if cmds.checkBox(self.widgets["optionalPathCB"], q=True, v=True): customPath = cmds.textField( self.widgets["ExportPathtextField"], q=True, text=True) filename = os.path.basename(name) exportPath = os.path.join(customPath, filename) else: #directory = os.path.dirname(path) #filename = os.path.basename(name) #exportPath = os.path.join(directory, filename) exportPath = name sys.__stdout__.write(" Final Export Path: " + exportPath + "\n") pre_text = "--- Final Export Path: " self.logger.info(pre_text + exportPath, title=None) if os.path.exists(exportPath): self.logger.warning("OVERWRITTEN: " + exportPath, title=None) self._fbx_overwrites.append(exportPath) if exportPath in self._fbx_files: self.logger.error("DUPLICATE!!!: " + exportPath, title=None) self._duplicates.append(exportPath) self._fbx_files.append(exportPath) startFrame = int(start) endFrame = int(end) cmds.playbackOptions(min=startFrame, animationStartTime=startFrame) cmds.playbackOptions(max=endFrame, animationEndTime=endFrame) sys.__stdout__.write("Start Frame: " + str(startFrame) + "\n") sys.__stdout__.write("End Frame: " + str(endFrame) + "\n") #custom attrs to export import json if not cmds.objExists("ExportAnimationSettings.settings"): cmds.addAttr("ExportAnimationSettings", ln="settings", dt="string") jsonString = json.dumps( [False, False, False, "null", "null"]) cmds.setAttr("ExportAnimationSettings.settings", jsonString, type="string") settings = json.loads( cmds.getAttr("ExportAnimationSettings.settings")) #get blendshapes #sys.__stdout__.write(" get blendshapes..." + "\n") cmds.progressBar(self.widgets["currentFileProgressBar"], edit=True, step=step) self.getBlendshapes(step, exportCharacter, startFrame, endFrame) #duplicate the skeleton self.dupeAndBake(step, exportCharacter, startFrame, endFrame, settings[2], settings[4]) cmds.select("root", hi=True) skeletonvis = cmds.ls(sl=True) cmds.cutKey(cl=True, at="v") for jnt in skeletonvis: cmds.setAttr(jnt + ".v", 1) self.exportFBX(exportPath, interp) else: for character in characters: sys.__stdout__.write("Export Character ------------->: " + str(character) + "\n") #add character suffix to fbx path file exportPath = path.rpartition(".fbx")[0] exportPath = exportPath + "_" + character + ".fbx" #get blendshapes #sys.__stdout__.write(" get blendshapes..." + "\n") cmds.progressBar(self.widgets["currentFileProgressBar"], edit=True, step=step) self.getBlendshapes(step, character, startFrame, endFrame) #duplicate the skeleton self.dupeAndBake(step, character, startFrame, endFrame) sys.__stdout__.write("Start Frame: " + str(startFrame) + "\n") sys.__stdout__.write("End Frame: " + str(endFrame) + "\n") #check remove root animation checkbox. if true, delete keys off of root and zero out removeRoot = cmds.checkBox(self.widgets["removeRoot"], q=True, v=True) if removeRoot: cmds.select("root") cmds.cutKey() for attr in ["tx", "ty", "tz", "rx", "ry", "rz"]: cmds.setAttr("root." + attr, 0) self.logger.info(exportPath, title=None) if os.path.exists(exportPath): self.logger.warning("OVERWRITTEN: " + exportPath, title=None) self._fbx_overwrites.append(exportPath) if exportPath in self._fbx_files: self.logger.error("DUPLICATE!: " + exportPath, title=None) self._duplicates.append(exportPath) self._fbx_files.append(exportPath) self.exportFBX(exportPath, interp)
def getBlendshapes(self, step, character, startFrame, endFrame, *args): #get blendshapes allBlends = cmds.ls(type="blendShape") jmBlends = [ "calf_l_shapes", "calf_r_shapes", "head_shapes", "l_elbow_shapes", "r_elbow_shapes", "l_lowerarm_shapes", "r_lowerarm_shapes", "l_shoulder_shapes", "r_shoulder_shapes", "l_upperarm_shapes", "r_upperarm_shapes", "neck1_shapes", "neck2_shapes", "neck3_shapes", "pelvis_shapes", "spine1_shapes", "spine2_shapes", "spine3_shapes", "spine4_shapes", "spine5_shapes", "thigh_l_shapes", "thigh_r_shapes" ] blendshapes = [] morphList = [] if allBlends != None: for shape in allBlends: if shape.split(":")[-1] not in jmBlends: if shape.split(":")[0] == character: blendshapes.append(shape) #if our character has blendshapes, deal with those now cmds.progressBar(self.widgets["currentFileProgressBar"], edit=True, step=step) value = cmds.checkBox(self.widgets["exportMorphs"], q=True, v=True) if value: if blendshapes != None: if cmds.objExists("custom_export"): cmds.delete("custom_export") cube = cmds.polyCube(name="custom_export")[0] i = 1 if blendshapes != None: for shape in blendshapes: attrs = cmds.listAttr(shape, m=True, string="weight") for attr in attrs: morph = cmds.polyCube(name=attr)[0] morphList.append(morph) sys.__stdout__.write("Blendshape:" + morph + "\n") cmds.select(morphList, r=True) cmds.select(cube, add=True) cmds.blendShape(name="custom_export_shapes") cmds.select(clear=True) cmds.delete(morphList) if blendshapes != None: #transfer keys from original to new morph #disabling redraw try: if cmds.checkBox(self.widgets["disableRedraw"], q=True, v=True) == True: mel.eval("paneLayout -e -manage false $gMainPane") for x in range(startFrame, endFrame + 1): for shape in blendshapes: attrs = cmds.listAttr(shape, m=True, string="weight") #counter for index for attr in attrs: cmds.currentTime(x) value = cmds.getAttr(shape + "." + attr) cmds.setKeyframe("custom_export_shapes." + attr, t=(x), v=value) except Exception, e: logger.error(e, title='Crash in blendshape bake loop') finally:
def dupeAndBake(self, step, character, startFrame, endFrame, exportAttrs=False, attrsToExport=None, *args): #sys.__stdout__.write(" duplicate the skeleton" + "\n") cmds.progressBar(self.widgets["currentFileProgressBar"], edit=True, step=step) dupeSkeleton = cmds.duplicate(character + ":" + "root", un=False, ic=False) cmds.select(dupeSkeleton[0], hi=True) cmds.delete(constraints=True) newSelection = cmds.ls(sl=True) newSkeleton = [] for each in newSelection: newSkeleton.append(each) joints = [] for each in newSkeleton: if cmds.nodeType(each) != "joint": cmds.delete(each) else: joints.append(each) #constrain the dupe skeleton to the original skeleton constraints = [] #sys.__stdout__.write(" constrain dupe skeleton to original" + "\n") for joint in joints: #do some checks to make sure that this is valid parent = cmds.listRelatives(joint, parent=True) if parent != None: if parent[0] in joints: constraint = cmds.parentConstraint( character + ":" + parent[0] + "|" + character + ":" + joint, joint)[0] constraints.append(constraint) else: #root bone? if joint == "root": constraint = cmds.parentConstraint(character + ":" + joint, joint)[0] constraints.append(constraint) if exportAttrs == True: #sys.__stdout__.write(" exporting custom attr curves" + "\n") constraint = cmds.parentConstraint( character + ":" + joint, joint)[0] constraints.append(constraint) #remove all custom attrs allAttrs = cmds.listAttr("root", keyable=True) normalAttrs = [ "translateX", "translateY", "translateZ", "rotateX", "rotateY", "rotateZ", "scaleX", "scaleY", "scaleZ", "visibility" ] for attr in allAttrs: if attr not in normalAttrs: if cmds.objExists("root." + attr): cmds.deleteAttr("root", at=attr) for attr in attrsToExport: if cmds.objExists(character + ":root." + attr): #sys.__stdout__.write(" exporting attr curve : " + str(attr) + "\n") if not cmds.objExists("root." + attr): cmds.addAttr("root", ln=attr, keyable=True) #disabling redraw try: if cmds.checkBox( self.widgets["disableRedraw"], q=True, v=True) == True: mel.eval( "paneLayout -e -manage false $gMainPane" ) for i in range(startFrame, endFrame + 1): cmds.currentTime(i) value = cmds.getAttr(character + ":root." + attr) cmds.setAttr("root." + attr, value) cmds.setKeyframe("root." + attr, itt="linear", ott="linear") except Exception, e: logger.error( e, title='Crash in bake root attrs') finally: mel.eval( "paneLayout -e -manage true $gMainPane" ) cmds.refresh(force=True) cmds.selectKey("root." + attr) cmds.keyTangent(itt="linear", ott="linear")
class FBX_Batcher(): def __init__(self): # logging self.logger = epic_logger.EpicLogger() self.logger.terminal(on_top=True) # terminal self.start = time.time() #get access to our maya tools toolsPath = cmds.internalVar(usd=True) + "mayaTools.txt" if os.path.exists(toolsPath): f = open(toolsPath, 'r') self.mayaToolsDir = f.readline() f.close() self.widgets = {} if cmds.window("ART_RetargetTool_UI", exists=True): cmds.deleteUI("ART_RetargetTool_UI") self.widgets["window"] = cmds.window("ART_RetargetTool_UI", title="ART FBX Export Batcher", w=400, h=500, sizeable=False, mnb=False, mxb=False) #main layout self.widgets["layout"] = cmds.formLayout(w=400, h=500) #textField and browse button label = cmds.text(label="Directory to Batch:") self.widgets["textField"] = cmds.textField(w=300, text="") self.widgets["browse"] = cmds.button(w=70, label="Browse", c=self.browse) self.widgets["optionalPathCB"] = cmds.checkBox( l="Optional Batch Export Path", ann= "Check this if you want to export all of your files to a single location defined in the text field below." ) self.widgets["ExportPathtextField"] = cmds.textField( w=300, text="", ann= "Where do you want to export your files to? This is optional and only used if the checkbox above is on" ) self.widgets["ExportPathbrowse"] = cmds.button(w=70, label="Browse", c=self.ExportPathbrowse) cmds.formLayout(self.widgets["layout"], edit=True, af=[(label, "left", 10), (label, "top", 10)]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(self.widgets["textField"], "left", 10), (self.widgets["textField"], "top", 30)]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(self.widgets["browse"], "right", 10), (self.widgets["browse"], "top", 30)]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(self.widgets["optionalPathCB"], "left", 10), (self.widgets["optionalPathCB"], "top", 60)]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(self.widgets["ExportPathtextField"], "left", 10), (self.widgets["ExportPathtextField"], "top", 80)]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(self.widgets["ExportPathbrowse"], "right", 10), (self.widgets["ExportPathbrowse"], "top", 80)]) # CUSTOM FILE SCRIPT self.widgets["frame"] = cmds.frameLayout(w=380, h=100, bs="etchedIn", cll=False, label="Advanced", parent=self.widgets["layout"]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(self.widgets["frame"], "right", 10), (self.widgets["frame"], "top", 110)]) self.widgets["advancedForm"] = cmds.formLayout( w=380, h=100, parent=self.widgets["frame"]) label2 = cmds.text("Custom File Script:", parent=self.widgets["advancedForm"]) self.widgets["scriptField"] = cmds.textField( w=280, text="", parent=self.widgets["advancedForm"]) self.widgets["scriptBrowse"] = cmds.button( w=70, label="Browse", c=self.scriptBrowse, parent=self.widgets["advancedForm"]) cmds.formLayout(self.widgets["advancedForm"], edit=True, af=[(label2, "left", 10), (label2, "top", 10)]) cmds.formLayout(self.widgets["advancedForm"], edit=True, af=[(self.widgets["scriptField"], "left", 10), (self.widgets["scriptField"], "top", 30)]) cmds.formLayout(self.widgets["advancedForm"], edit=True, af=[(self.widgets["scriptBrowse"], "right", 10), (self.widgets["scriptBrowse"], "top", 30)]) # EXPORT AN FBX self.widgets["exportFBXCB"] = cmds.checkBox( label="Export an FBX?", v=True, parent=self.widgets["layout"]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(self.widgets["exportFBXCB"], "left", 16), (self.widgets["exportFBXCB"], "top", 200)]) # USE ANIM SEQ INFO self.widgets["useSequenceInfo"] = cmds.checkBox( label="Use Anim Sequence Info?", v=True, parent=self.widgets["layout"]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(self.widgets["useSequenceInfo"], "left", 16), (self.widgets["useSequenceInfo"], "top", 220)]) # EXPORT MORPHS self.widgets["exportMorphs"] = cmds.checkBox( label="Export Morphs?", v=True, parent=self.widgets["layout"]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(self.widgets["exportMorphs"], "left", 16), (self.widgets["exportMorphs"], "top", 240)]) # REMOVE ROOT ANIM self.widgets["removeRoot"] = cmds.checkBox( label="Remove root animation?", v=False, parent=self.widgets["layout"]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(self.widgets["removeRoot"], "left", 16), (self.widgets["removeRoot"], "top", 260)]) # DISABLE REDRAW self.widgets["disableRedraw"] = cmds.checkBox( label="Disable 3D viewport redraw", v=True, parent=self.widgets["layout"]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(self.widgets["disableRedraw"], "left", 16), (self.widgets["disableRedraw"], "top", 280)]) #process button self.widgets["process"] = cmds.button(w=380, h=50, label="BEGIN BATCH", c=self.process, parent=self.widgets["layout"]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(self.widgets["process"], "left", 10), (self.widgets["process"], "top", 330)]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(self.widgets["process"], "left", 10), (self.widgets["process"], "bottom", 360)]) #progress bar text = cmds.text(label="File Progress: ", parent=self.widgets["layout"]) self.widgets["currentFileProgressBar"] = cmds.progressBar( w=250, parent=self.widgets["layout"]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(text, "left", 10), (text, "top", 390)]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(self.widgets["currentFileProgressBar"], "left", 110), (self.widgets["currentFileProgressBar"], "top", 390)]) text2 = cmds.text(label="Total Progress: ", parent=self.widgets["layout"]) self.widgets["progressBar"] = cmds.progressBar( w=250, parent=self.widgets["layout"]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(text2, "left", 10), (text2, "top", 420)]) cmds.formLayout(self.widgets["layout"], edit=True, af=[(self.widgets["progressBar"], "left", 110), (self.widgets["progressBar"], "top", 420)]) #show window cmds.showWindow(self.widgets["window"]) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def browse(self, *args): try: directory = cmds.fileDialog2(dialogStyle=2, fm=3)[0] cmds.textField(self.widgets["textField"], edit=True, text=directory) except: pass def ExportPathbrowse(self, *args): try: directory = cmds.fileDialog2(dialogStyle=2, fm=3)[0] cmds.textField(self.widgets["ExportPathtextField"], edit=True, text=directory) except: pass # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def scriptBrowse(self, *args): try: directory = cmds.fileDialog2(dialogStyle=2, fm=1)[0] cmds.textField(self.widgets["scriptField"], edit=True, text=directory) except: pass # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def dupeAndBake(self, step, character, startFrame, endFrame, exportAttrs=False, attrsToExport=None, *args): #sys.__stdout__.write(" duplicate the skeleton" + "\n") cmds.progressBar(self.widgets["currentFileProgressBar"], edit=True, step=step) dupeSkeleton = cmds.duplicate(character + ":" + "root", un=False, ic=False) cmds.select(dupeSkeleton[0], hi=True) cmds.delete(constraints=True) newSelection = cmds.ls(sl=True) newSkeleton = [] for each in newSelection: newSkeleton.append(each) joints = [] for each in newSkeleton: if cmds.nodeType(each) != "joint": cmds.delete(each) else: joints.append(each) #constrain the dupe skeleton to the original skeleton constraints = [] #sys.__stdout__.write(" constrain dupe skeleton to original" + "\n") for joint in joints: #do some checks to make sure that this is valid parent = cmds.listRelatives(joint, parent=True) if parent != None: if parent[0] in joints: constraint = cmds.parentConstraint( character + ":" + parent[0] + "|" + character + ":" + joint, joint)[0] constraints.append(constraint) else: #root bone? if joint == "root": constraint = cmds.parentConstraint(character + ":" + joint, joint)[0] constraints.append(constraint) if exportAttrs == True: #sys.__stdout__.write(" exporting custom attr curves" + "\n") constraint = cmds.parentConstraint( character + ":" + joint, joint)[0] constraints.append(constraint) #remove all custom attrs allAttrs = cmds.listAttr("root", keyable=True) normalAttrs = [ "translateX", "translateY", "translateZ", "rotateX", "rotateY", "rotateZ", "scaleX", "scaleY", "scaleZ", "visibility" ] for attr in allAttrs: if attr not in normalAttrs: if cmds.objExists("root." + attr): cmds.deleteAttr("root", at=attr) for attr in attrsToExport: if cmds.objExists(character + ":root." + attr): #sys.__stdout__.write(" exporting attr curve : " + str(attr) + "\n") if not cmds.objExists("root." + attr): cmds.addAttr("root", ln=attr, keyable=True) #disabling redraw try: if cmds.checkBox( self.widgets["disableRedraw"], q=True, v=True) == True: mel.eval( "paneLayout -e -manage false $gMainPane" ) for i in range(startFrame, endFrame + 1): cmds.currentTime(i) value = cmds.getAttr(character + ":root." + attr) cmds.setAttr("root." + attr, value) cmds.setKeyframe("root." + attr, itt="linear", ott="linear") except Exception, e: logger.error( e, title='Crash in bake root attrs') finally: mel.eval( "paneLayout -e -manage true $gMainPane" ) cmds.refresh(force=True) cmds.selectKey("root." + attr) cmds.keyTangent(itt="linear", ott="linear") if exportAttrs == False: allAttrs = cmds.listAttr("root", keyable=True) normalAttrs = [ "translateX", "translateY", "translateZ", "rotateX", "rotateY", "rotateZ", "scaleX", "scaleY", "scaleZ", "visibility" ] for attr in allAttrs: if attr not in normalAttrs: if cmds.objExists("root." + attr): cmds.deleteAttr("root", at=attr)
def is_item_of_type(item, node_type): if not cmds.objExists(item.text()): return False return cmds.objectType(item.text()) == node_type
def isValid(self): ''' check if this cache is still valid''' return cmds.objExists(self.shape)
def applyMotionNodeConnections(self): spaceListGroup = [self.filterGroupNodeDic['fkSpace'], self.filterGroupNodeDic['ikSpace'], self.filterGroupNodeDic['outputSpace'], self.filterGroupNodeDic['controlFkSpace'], self.filterGroupNodeDic['controlIkSpace']] for node in self.filterGroupNodeDic['inputChildPlug'].iterkeys(): nodeLocal = util.fullPathName2Local(node) if nodeLocal[1].rfind('upleg') != -1: for spaceList in spaceListGroup: for spaceNode in spaceList: spaceNodeLocal = util.fullPathName2Local(spaceNode) if spaceNodeLocal[1].rfind('upleg') != -1: util.transformChannelBinding(node, spaceNode) elif nodeLocal[1].rfind('ball_twist') != -1: for controlIkSpace in self.filterGroupNodeDic['controlIkSpace']: controlIkSpaceLocal = util.fullPathName2Local(controlIkSpace) if controlIkSpaceLocal[1].rfind('Pole_Rot') != -1: cmds.orientConstraint(node, controlIkSpace) elif nodeLocal[1].rfind('foot_offset') != -1: footOffsetPlug = node ballJntOffsetPlug = '' tipJntOffsetPlug = '' uplegIkSpace = '' footIkSpace = '' ballIkSpaceLocal = '' tipIkSpaceLocal = '' controlIKSpaceLocalNodes = [] for controlIkSpace in self.filterGroupNodeDic['controlIkSpace']: controlIkSpaceLocal = util.fullPathName2Local(controlIkSpace) if controlIkSpaceLocal[1].rfind('space_local') != -1: controlIKSpaceLocalNodes.append(controlIkSpace) for spaceLocalNode in controlIKSpaceLocalNodes: spaceLocalNodeBaseStr = util.fullPathName2Local(spaceLocalNode) if spaceLocalNodeBaseStr[1].rfind('ball') != -1: ballIkSpaceLocal = spaceLocalNode elif spaceLocalNodeBaseStr[1].rfind('tip') != -1: tipIkSpaceLocal = spaceLocalNode for plugNode in self.filterGroupNodeDic['inputChildPlug'].iterkeys(): plugNodeLocal = util.fullPathName2Local(plugNode) if plugNodeLocal[1].rfind('ball_jnt') != -1: ballJntOffsetPlug = plugNode elif plugNodeLocal[1].rfind('tip_jnt') != -1: tipJntOffsetPlug = plugNode for controlIkSpace in self.filterGroupNodeDic['controlIkSpace']: controlIkSpaceLocalStr = util.fullPathName2Local(controlIkSpace) if controlIkSpaceLocalStr[1].rfind('upleg_con_ik') != -1: uplegIkSpace = controlIkSpace elif controlIkSpaceLocalStr[1].rfind('foot_con_ik') != -1 and controlIkSpaceLocalStr[1].rfind('local') == -1: footIkSpace = controlIkSpace matrixOps = util.localMatrixOp(self.moduleNameSpace, 'foot_Ik_Con_space') cmds.connectAttr(uplegIkSpace+'.worldInverseMatrix', matrixOps[0]+'.matrixIn[1]', f=True) cmds.connectAttr(footOffsetPlug+'.worldMatrix', matrixOps[0]+'.matrixIn[0]', f=True) util.decompChannelBinding(matrixOps[1], footIkSpace) matrixOps = util.localMatrixOp(self.moduleNameSpace, 'ball_ik_Con_space') cmds.connectAttr(footOffsetPlug+'.worldInverseMatrix', matrixOps[0]+'.matrixIn[1]', f=True) cmds.connectAttr(ballJntOffsetPlug+'.worldMatrix', matrixOps[0]+'.matrixIn[0]', f=True) util.decompChannelBinding(matrixOps[1], ballIkSpaceLocal) matrixOps = util.localMatrixOp(self.moduleNameSpace, 'tip_Ik_Con_space') cmds.connectAttr(footOffsetPlug+'.worldInverseMatrix', matrixOps[0]+'.matrixIn[1]', f=True) cmds.connectAttr(tipJntOffsetPlug+'.worldMatrix', matrixOps[0]+'.matrixIn[0]', f=True) util.decompChannelBinding(matrixOps[1], tipIkSpaceLocal) for controlFkCon in self.filterGroupNodeDic['controlFkCon']: controlFkConLocal = util.fullPathName2Local(controlFkCon) matchStr = controlFkConLocal[1].replace('_fk_Con', 'Jnt_fk') for fkJntNode in self.filterGroupNodeDic['fkJnt']: fkJntNodeLocal = util.fullPathName2Local(fkJntNode) if fkJntNodeLocal[1] == matchStr: cmds.connectAttr(controlFkCon+'.rotate', fkJntNode+'.rotate', f=True) filterDic = {'foot':'ball', 'ball':'tip'} sourceNode = '' targetNode = '' targetUpNode = '' for key, value in filterDic.iteritems(): for ikJnt in self.filterGroupNodeDic['ikJnt']: ikJntLocal = util.fullPathName2Local(ikJnt) if ikJntLocal[1].rfind(key) != -1: sourceNode = ikJnt for controlRef in self.filterGroupNodeDic['controlRef']: controlRefLocal = util.fullPathName2Local(controlRef) if controlRefLocal[1].rfind(value) != -1: if controlRefLocal[1].rfind('Handle') != -1: targetNode = controlRef elif controlRefLocal[1].rfind('Pole') != -1: targetUpNode = controlRef cmds.aimConstraint(targetNode, sourceNode, aim = [1,0,0], u= [0,1,0], wut='object', wuo=targetUpNode) for spaceIkNode in self.filterGroupNodeDic['ikSpace']: spaceIkNodeLocal = util.fullPathName2Local(spaceIkNode) if spaceIkNodeLocal[1].rfind('soft') != -1: sourceNode = spaceIkNode for controlIkNode in self.filterGroupNodeDic['controlIkCon']: controlIkNodeLocal = util.fullPathName2Local(controlIkNode) if controlIkNodeLocal[1].rfind('foot') != -1 and controlIkNodeLocal[1].rfind('local') != -1: targetNode = controlIkNode elif controlIkNodeLocal[1].rfind('leg') != -1 and controlIkNodeLocal[1].rfind('Pole') != -1: targetUpNode = controlIkNode cmds.aimConstraint(targetNode, sourceNode, aim = [1,0,0], u= [0,1,0], wut='object', wuo=targetUpNode) for blendNode in self.filterGroupNodeDic['outputBlend']: blendNodeLocal = util.fullPathName2Local(blendNode) blendNodeLocalPrefix = blendNodeLocal[1].split('_')[0] blendNodeOp = util.createOpNode(self.moduleNameSpace, 'blendColors', blendNodeLocalPrefix+'_blend_op') cmds.connectAttr(self.filterGroupNodeDic['fk2ikCon'].keys()[0]+'.fk2ik', blendNodeOp+'.blender', f=True) for ikJntNode in self.filterGroupNodeDic['ikJnt']: ikJntNodeLocal = util.fullPathName2Local(ikJntNode) if blendNodeLocalPrefix+'_ik' == ikJntNodeLocal[1]: cmds.connectAttr(ikJntNode+'.rotate', blendNodeOp+'.color1', f=True) for fkJntNode in self.filterGroupNodeDic['fkJnt']: fkJntNodeLocal = util.fullPathName2Local(fkJntNode) if blendNodeLocalPrefix+'_fk' == fkJntNodeLocal[1]: cmds.connectAttr(fkJntNode+'.rotate', blendNodeOp+'.color2', f=True) cmds.connectAttr(blendNodeOp+'.output', blendNode+'.rotate', f=True) ikConDisplayOp = util.createOpNode(self.moduleNameSpace, 'condition', 'ik_con_display_op') cmds.setAttr(ikConDisplayOp+'.operation', 0) cmds.setAttr(ikConDisplayOp+'.secondTerm', 1) cmds.setAttr(ikConDisplayOp+'.colorIfTrueR', 1) cmds.setAttr(ikConDisplayOp+'.colorIfFalseR', 0) fkConDisplayOp = util.createOpNode(self.moduleNameSpace, 'condition', 'fk_con_display_op') cmds.setAttr(fkConDisplayOp+'.operation', 0) cmds.setAttr(fkConDisplayOp+'.secondTerm', 0) cmds.setAttr(fkConDisplayOp+'.colorIfTrueR', 1) cmds.setAttr(fkConDisplayOp+'.colorIfFalseR', 0) cmds.connectAttr(self.filterGroupNodeDic['fk2ikCon'].keys()[0]+'.controlDisplay', ikConDisplayOp+'.firstTerm', f=True) cmds.connectAttr(self.filterGroupNodeDic['fk2ikCon'].keys()[0]+'.controlDisplay', fkConDisplayOp+'.firstTerm', f=True) for blendNode in self.filterGroupNodeDic['outputBlend']: blendNodeLocal = util.fullPathName2Local(blendNode) if blendNodeLocal[1].rfind('upleg') != -1: cmds.connectAttr(blendNode+'.rotate', self.filterGroupNodeDic['fk2ikSpace'].keys()[0]+'.rotate', f=True) placementList = ['Fk', 'Ik'] for typeStr in placementList: for placementNode in self.filterGroupNodeDic['control'+typeStr+'Placement'].iterkeys(): placementNodeLocal = util.fullPathName2Local(placementNode) if placementNodeLocal[1].rfind('upleg') != -1 and placementNodeLocal[1].rfind('fk2ik') == -1: if typeStr == placementList[0]: cmds.connectAttr(fkConDisplayOp+'.outColorR', placementNode+'.visibility', f=True) else: cmds.connectAttr(ikConDisplayOp+'.outColorR', placementNode+'.visibility', f=True) legPoleAutoAssetPath = self.pathInfo.assetDirPath + 'poleVectorPosAutoOpAsset' + '.' + self.file_extenstion_str legPoleAutoOpNode = '' legPoleAutoOpNodeNew = '' fileCheck = cmds.file( legPoleAutoAssetPath, query=True, exists=True ) if fileCheck: cmds.file( legPoleAutoAssetPath, i=True, mergeNamespacesOnClash=True ) containerNodes = cmds.ls(type='container', l=True) if containerNodes != None: for containerNode in containerNodes: localStr = containerNode.split(':')[-1] if localStr == 'poleVectorPosAutoOp': legPoleAutoOpNode = containerNode if cmds.objExists(legPoleAutoOpNode): legPoleAutoOpNodeNew = cmds.rename(legPoleAutoOpNode, legPoleAutoOpNode + '_' + self.component_val) uplegIkMotion = '' legPoleAuto = '' legPoleSideAuto = '' legPoleFntAuto = '' footIkConLocal = '' uplegIkMotionStr = '' legPoleAutoStr = '' legPoleSideAutoStr = '' legPoleFntAutoStr = '' footIkConLocalStr = '' for conPoleAutoNode in self.filterGroupNodeDic['controlPoleAuto']: conPoleAutoNodeLocal = util.fullPathName2Local(conPoleAutoNode) if conPoleAutoNodeLocal[1].rfind('Pole_Auto') != -1: legPoleAuto = conPoleAutoNode legPoleAutoStr = conPoleAutoNodeLocal[1] elif conPoleAutoNodeLocal[1].rfind('Side') != -1: legPoleSideAuto = conPoleAutoNode legPoleSideAutoStr = conPoleAutoNodeLocal[1] elif conPoleAutoNodeLocal[1].rfind('Fnt') != -1: legPoleFntAuto = conPoleAutoNode legPoleFntAutoStr = conPoleAutoNodeLocal[1] for motinoIkSpaceNode in self.filterGroupNodeDic['ikSpace']: motinoIkSpaceNodeLocal = util.fullPathName2Local(motinoIkSpaceNode) if motinoIkSpaceNodeLocal[1].rfind('upleg') != -1: uplegIkMotion = motinoIkSpaceNode uplegIkMotionStr = motinoIkSpaceNodeLocal[1] for conIkNode in self.filterGroupNodeDic['controlIkCon']: conIkNodeLocal = util.fullPathName2Local(conIkNode) if conIkNodeLocal[1] == 'foot_ik_Con_local': footIkConLocal = conIkNode footIkConLocalStr = conIkNodeLocal[1] uplegIkMotionDecompOp = util.createOpNode(self.moduleNameSpace, 'decomposeMatrix', uplegIkMotionStr+'_decomp') footIkConLocalDecompOp = util.createOpNode(self.moduleNameSpace, 'decomposeMatrix', footIkConLocalStr+'_decomp') legPoleSideAutoDecompOp = util.createOpNode(self.moduleNameSpace, 'decomposeMatrix', legPoleSideAutoStr+'_decomp') cmds.connectAttr(uplegIkMotion+'.worldMatrix', uplegIkMotionDecompOp +'.inputMatrix', f=True) cmds.connectAttr(footIkConLocal+'.worldMatrix', footIkConLocalDecompOp +'.inputMatrix', f=True) cmds.connectAttr(legPoleSideAuto+'.worldMatrix', legPoleSideAutoDecompOp +'.inputMatrix', f=True) cmds.connectAttr(uplegIkMotionDecompOp+'.outputTranslate', legPoleAutoOpNodeNew +'.Input_ikSpaceWorldPos', f=True) cmds.connectAttr(footIkConLocalDecompOp+'.outputTranslate', legPoleAutoOpNodeNew +'.Input_conSpaceWorldPos', f=True) cmds.connectAttr(legPoleSideAutoDecompOp+'.outputTranslate', legPoleAutoOpNodeNew +'.Input_ikSideWorldPos', f=True) legPoleSideAutoCompOp = util.createOpNode(self.moduleNameSpace, 'composeMatrix', legPoleSideAutoStr+'_comp') cmds.connectAttr(legPoleAutoOpNodeNew+'.Output_poleVectorWorldPos', legPoleSideAutoCompOp +'.inputTranslate', f=True) matrixOps = util.localMatrixOp(self.moduleNameSpace, legPoleSideAutoStr+'_comp') cmds.connectAttr(legPoleAuto+'.worldInverseMatrix', matrixOps[0]+'.matrixIn[1]', f=True) cmds.connectAttr(legPoleSideAutoCompOp +'.outputMatrix', matrixOps[0]+'.matrixIn[0]', f=True) util.decompChannelBinding(matrixOps[1], legPoleFntAuto, option=2) for conIkSpaceNode in self.filterGroupNodeDic['controlIkSpace']: conIkSpaceNodeLocal = util.fullPathName2Local(conIkSpaceNode) if conIkSpaceNodeLocal[1].rfind('Pole_Pos') != -1: cmds.pointConstraint(legPoleFntAuto, conIkSpaceNode) legFk2IkConNode = self.filterGroupNodeDic['fk2ikCon'].keys()[0] if self._side == 'L': legFk2IkConShapeNode = cmds.listRelatives(legFk2IkConNode, shapes=True, f=True)[0] spanNums = cmds.getAttr(legFk2IkConShapeNode+'.spans') spanNums = spanNums + 1 for i in range(0, spanNums): originalPos = cmds.getAttr(legFk2IkConShapeNode+".controlPoints["+ str(i)+"].zValue") cmds.setAttr(legFk2IkConShapeNode+".controlPoints["+ str(i)+"].zValue", originalPos * -1)
def execute(self, **kwargs): """ Main hook entry point :returns: A list of any items that were found to be published. Each item in the list should be a dictionary containing the following keys: { type: String This should match a scene_item_type defined in one of the outputs in the configuration and is used to determine the outputs that should be published for the item name: String Name to use for the item in the UI description: String Description of the item to use in the UI selected: Bool Initial selected state of item in the UI. Items are selected by default. required: Bool Required state of item in the UI. If True then item will not be deselectable. Items are not required by default. other_params: Dictionary Optional dictionary that will be passed to the pre-publish and publish hooks } """ items = [] # get the main scene: scene_name = cmds.file(query=True, sn=True) if not scene_name: raise TankError("Please Save your file before Publishing") scene_path = os.path.abspath(scene_name) name = os.path.basename(scene_path) # create the primary item - this will match the primary output 'scene_item_type': items.append({"type": "work_file", "name": name}) ### CLEANUP ################################################################################ ### NOW DO SCENE CRITICAL CHECKS LIKE DUPLICATE OBJECT NAMES ETC AND FAIL HARD IF THESE FAIL! ############################################################################################ ############################# ## INITAL HARD FAILS ## Do a quick check for geo_hrc and rig_hrc ## geo_hrc if not cmds.objExists('geo_hrc'): raise TankError( "Please Group all your geo under a geo_hrc group under the root node." ) ## rig_hrc ## UNCOMMENT FOR MDL STEP if cleanup.rigGroupCheck(): raise TankError( 'Rig group found!! Please use the RIG menus to publish rigs...' ) ## UNCOMMENT FOR RIG STEP # if not cleanup.rigGroupCheck(): # raise TankError('No rig group found!! Please make sure your animation controls are under rig_hrc.') ## Now check it's the right KIND of asset eg CHAR or PROP cleanup.assetCheckAndTag(type='BLD', customTag='staticBLD') ############################# ## SECONDARIES FOR PUBLISHING ## WE NEED TO FIND THE MAIN GROUP THAT HAS MESHES IN IT NOW AND PUSH THIS INTO THE ITEMS LIST FOR SECONDARY PUBLISHING ## Look for root level groups that have meshes as children: for grp in cmds.ls(assemblies=True, long=True): if cmds.ls(grp, dag=True, type="mesh"): # include this group as a 'mesh_group' type ### UNCOMMENT FOR PROP CHAR LND ASSETS # items.append({"type":"mesh_group", "name":grp}) ### UNCOMMENT FOR BLD MLD STEP if cleanup.BLDTransformCheck( grp ): ## Check for BLD step only to make sure the transforms are not frozen on the BLD grps items.append({"type": "mesh_group", "name": grp}) ############################# ## HARD FAILS ## Duplicate name check if not cleanup.duplicateNameCheck(): raise TankError( "Duplicate names found please fix before publishing.\nCheck the outliner for the duplicate name set." ) ## Incorrect Suffix check checkSceneGeo = cleanup._geoSuffixCheck(items) if not checkSceneGeo: raise TankError( "Incorrect Suffixes found! Fix suffixes before publishing.\nCheck the outliner for the duplicate name set." ) ## Incorrect root name if not utils.checkRoot_hrc_Naming(items): assetName = cmds.file(query=True, sn=True).split('/')[4] raise TankError( "YOUR ASSET IS NAMED INCORRECTLY! Remember it is CASE SENSITIVE!\nIt should be %s_hrc" % assetName) ############################# ## NOW PREP THE GEO FOR EXPORT!!! ## THESE CLEANUPS SHOULD NOT FAIL THEY SHOULD JUST BE PERFORMED ## UNCOMMENT FOR MDL STEP ## PEFORM MDL CLEANUP cleanup.cleanUp(items=items, checkShapes=True, history=True, pivots=True, freezeXFRM=True, smoothLvl=True, tagSmoothed=True, checkVerts=True, renderflags=True, deleteIntermediate=True, turnOffOpposite=True, instanceCheck=True, shaders=True) ## UNCOMMENT FOR RIG STEP ## PEFORM RIG CLEANUP # cleanup.cleanUp(items = items, checkShapes = False, history = False, pivots = False, freezeXFRM = False, smoothLvl = True, tagSmoothed = True, checkVerts = False, # renderflags = True, deleteIntermediate = False, turnOffOpposite = True, instanceCheck = False, shaders = True) ############################################################################# ## NOW MOVE ON TO PUBLISHING return items
def __init__(self): # Setup the scene the Turbine way utils.sceneSetup(self) self.previousBlueprintListEntry = None self.previousBlueprintModule = None self.previousAnimationModule = None baseIconsDir = os.environ["GEPPETTO"] + "/Icons/" self.selectedCharacter = self.findSelectedCharacter() if self.selectedCharacter == None: return self.characterName = self.selectedCharacter.partition("__")[2] self.windowName = self.characterName + "_window" self.UIElements = {} if cmds.window(self.windowName, exists=True): cmds.deleteUI(self.windowName) self.windowWidth = 420 self.windowHeight = 730 self.UIElements["window"] = cmds.window(self.windowName, width=self.windowWidth, height=self.windowHeight, title = "Animation UI: " + self.characterName, sizeable=False) self.UIElements["topColumnLayout"] = cmds.columnLayout(adj=True, rs=3) buttonWidth = 32 columnOffset = 5 buttonColumnWidth = buttonWidth + (2*columnOffset) textScrollWidth = (self.windowWidth - buttonColumnWidth - 8) /2 self.UIElements["listBoxRowLayout"] = cmds.rowLayout(nc=3, columnWidth3=[textScrollWidth, textScrollWidth, buttonColumnWidth], columnAttach=([1, "both", columnOffset], [2, "both", columnOffset], [3, "both", columnOffset])) self.UIElements["blueprintModule_textScroll"] = cmds.textScrollList(numberOfRows=12, allowMultiSelection=False, selectCommand=self.refreshAnimationModuleList) self.initialiseBlueprintModuleList() self.UIElements["animationModule_textScroll"] = cmds.textScrollList(numberOfRows=12, allowMultiSelection=False, selectCommand=self.setupModuleSpecificControls) self.UIElements["buttonColumnLayout"] = cmds.columnLayout() self.UIElements["pinButton"] = cmds.symbolCheckBox(onImage=baseIconsDir+"_pinned.bmp", offImage=baseIconsDir+"_unpinned.bmp", width=buttonWidth, height=buttonWidth, onCommand=self.deleteScriptJob, offCommand=self.setupScriptJob) if cmds.objExists(self.selectedCharacter+":non_blueprint_grp"): value = cmds.getAttr(self.selectedCharacter+":non_blueprint_grp.display") self.UIElements["nonBlueprintVisibility"] = cmds.symbolCheckBox(image=baseIconsDir+"_abxPicker.bmp", width=buttonWidth, height=buttonWidth, onCommand=self.toggleNonBlueprintVisibility, offCommand=self.toggleNonBlueprintVisibility) value = cmds.getAttr(self.selectedCharacter + ":character_grp.animationControlVisibility") self.UIElements["animControlVisibility"] = cmds.symbolCheckBox(image=baseIconsDir+"_visibility.bmp", width=buttonWidth, height=buttonWidth, onCommand=self.toggleAnimControlVisibility, offCommand=self.toggleAnimControlVisibility) self.UIElements["deleteModuleButton"] = cmds.symbolButton(image=baseIconsDir+"_shelf_delete.bmp", width=buttonWidth, height=buttonWidth, enable=False, c=self.deleteSelectedModule) self.UIElements["duplicateModuleButton"] = cmds.symbolButton(image=baseIconsDir+"_duplicate.bmp", width=buttonWidth, height=buttonWidth, enable=False, c=self.duplicateSelectedModule) cmds.setParent(self.UIElements["topColumnLayout"]) cmds.separator() # 159 > self.UIElements["activeModuleColumn"] = cmds.columnLayout(adj=True) self.setupActiveModuleControls() cmds.setParent(self.UIElements["topColumnLayout"]) cmds.separator() self.UIElements["matchingButton"] = cmds.button(label="Match Controls to Result", enable=False) cmds.separator() # < 159 # 175 > # Setup space switching UI self.UIElements["spaceSwitchingColumn"] = cmds.columnLayout(adj=True) self.setupSpaceSwitchingControls() cmds.setParent(self.UIElements["topColumnLayout"]) cmds.separator() # < 175 cmds.rowColumnLayout(nr=1, rowAttach=[1, "both", 0], rowHeight=[1, self.windowHeight-395]) self.UIElements["moduleSpecificControlsScroll"] = cmds.scrollLayout(hst=0) scrollWidth = cmds.scrollLayout(self.UIElements["moduleSpecificControlsScroll"], q=True, scrollAreaWidth=True) self.UIElements["moduleSpecificControlsColumn"] = cmds.columnLayout(columnWidth=scrollWidth, columnAttach=["both", 5]) self.refreshAnimationModuleList() self.setupScriptJob() # Shows a new window for each character. Tab these? cmds.showWindow (self.UIElements["window"]) self.selectionChanged()
def test(self): # Get input plugs for this operator from dictionary literal_input_plugs = TEST_DATA_ASSOCIATION[operator]["input_plugs"] # Convert these input strings into actual objects of "self" input_plugs = convert_literal_to_object(self, literal_input_plugs) # Get output plugs for this operator from dictionary literal_output_plugs = TEST_DATA_ASSOCIATION[operator]["output_plugs"] # Convert these output strings into actual objects of "self" output_plugs = convert_literal_to_object(self, literal_output_plugs) # Get NodeCalculator data for this operator node_data = noca.OPERATORS[operator] node_type = node_data.get("node", None) node_inputs = expand_array_attributes(node_data.get("inputs", None), input_plugs) node_outputs = node_data.get("outputs", None) node_operation = node_data.get("operation", None) # This assignment is necessary because closure argument can't be used directly. true_operator = operator try: noca_operator_func = getattr(noca.NcBaseClass, "__{}__".format(true_operator)) except AttributeError: noca_operator_func = getattr(noca.Op, true_operator) # Perform operation try: results = noca_operator_func(*input_plugs, return_all_outputs=True) except TypeError: results = noca_operator_func(*input_plugs) if not isinstance(results, (list, tuple)): results = [results] for output_plug, result in zip(output_plugs, results): output_plug.attrs = result # Check that result is an NcNode self.assertTrue(isinstance(result, noca.NcNode)) # Test that the created node is of the correct type self.assertEqual(cmds.nodeType(result.node), node_type) # Some Operators require a list as input-parameter. These flattened_input_plugs = flatten(input_plugs) for node_input, desired_input in zip(node_inputs, flattened_input_plugs): if isinstance(node_input, (tuple, list)): node_input = node_input[0] plug = "{}.{}".format(result.node, node_input) # Check the input plug actually exists self.assertTrue(cmds.objExists(plug)) # Usually the parent plug gets connected and should be compared. # However, some nodes have oddly parented attributes. In that case # don't get the parent attribute! if TEST_DATA_ASSOCIATION[operator].get("seek_input_parent", True): # Get a potential parent plug, which would have been connected instead. mplug = om_util.get_mplug_of_plug(plug) parent_plug = om_util.get_parent_mplug(mplug) if parent_plug: plug = parent_plug # Check the correct plug is connected into the input-plug input_connections = cmds.listConnections(plug, plugs=True, skipConversionNodes=True) self.assertEqual(input_connections, desired_input.plugs) # Test that the outputs are correct for node_output, desired_output in zip(node_outputs, output_plugs): output_is_multidimensional = False if len(node_output) > 1: output_is_multidimensional = True node_output = node_output[0] plug = "{}.{}".format(result.node, node_output) # Check the output plug actually exists self.assertTrue(cmds.objExists(plug)) if output_is_multidimensional: mplug = om_util.get_mplug_of_plug(plug) parent_plug = om_util.get_parent_mplug(mplug) if parent_plug: plug = parent_plug output_connections = cmds.listConnections(plug, plugs=True, skipConversionNodes=True) self.assertEqual(output_connections, desired_output.plugs) # Test if the operation of the created node is correctly set if node_operation: operation_attr_value = cmds.getAttr("{}.operation".format( result.node)) self.assertEqual(operation_attr_value, node_operation)
def findSymmetricalBlendshape(inputShape, pattern_R='R', pattern_r='r', pattern_L='L', pattern_l='l'): if not cmds.objExists(inputShape): cmds.warning('Input shape does not exist: ' + inputShape) return None shapeName = SEStringHelper.SE_RemoveSuffix(inputShape) suffix = SEStringHelper.getSuffix(inputShape) if suffix == None: cmds.warning('Suffix not found for input shape: ' + inputShape) return None if suffix == pattern_R or suffix == pattern_r: # Try to find left side shape and suffix pattern. shapeName_L = shapeName + '_' + pattern_L shapeName_l = shapeName + '_' + pattern_l symmetricalBS = None symmetricalPattern = None if cmds.objExists(shapeName_L): symmetricalBS = shapeName_L symmetricalPattern = pattern_L elif cmds.objExists(shapeName_l): symmetricalBS = shapeName_l symmetricalPattern = pattern_l else: cmds.warning( 'Symmetrical blend shape does not exist for input shape: ' + inputShape) return [symmetricalBS, symmetricalPattern, shapeName_L] elif suffix == pattern_L or suffix == pattern_l: # Try to find right side shape and suffix pattern. shapeName_R = shapeName + '_' + pattern_R shapeName_r = shapeName + '_' + pattern_r symmetricalBS = None symmetricalPattern = None if cmds.objExists(shapeName_R): symmetricalBS = shapeName_R symmetricalPattern = pattern_R elif cmds.objExists(shapeName_l): symmetricalBS = shapeName_r symmetricalPattern = pattern_r else: cmds.warning( 'Symmetrical blend shape does not exist for input shape: ' + inputShape) return [symmetricalBS, symmetricalPattern, shapeName_R] else: # Blendshape that matches symmetrical pattern not found. cmds.warning( 'Blendshape that matches symmetrical pattern not found for input shape: ' + inputShape) return None
def applyInitNodeConnections(self): initNodeFullName = cmds.ls(self.modulePathDic['init'], l=True)[0] initNodeParents = [] placementNodesList = [self.filterGroupNodeDic['inputPlacement'], self.filterGroupNodeDic['fkPlacement'], self.filterGroupNodeDic['ikPlacement'], self.filterGroupNodeDic['outputPlacement'], self.filterGroupNodeDic['controlPlacement']] uplegInitFull = '' for initNode, parentNode in self.filterGroupNodeDic['init'].iteritems(): initLocalNode = util.fullPathName2Local(initNode) matchStr = initLocalNode[1].replace('init', '') for placementNodes in placementNodesList: for placementNode in placementNodes: placementLocalNode = util.fullPathName2Local(placementNode) if placementLocalNode[1].rfind(matchStr) != -1: util.transformChannelBinding(initNode, placementNode) uplegInitFull = '' lolegInitFull = '' footInitFull = '' ballInitFull = '' tipInitFull = '' spaceInitFull = '' controlInitFull = '' for initNode, parentNode in self.filterGroupNodeDic['init'].iteritems(): initLocalNode = util.fullPathName2Local(initNode) partStr = initLocalNode[1].replace('_init', '') if initLocalNode[1].rfind('upleg') != -1: uplegInitFull = initNode elif initLocalNode[1].rfind('loleg') != -1: lolegInitFull = initNode elif initLocalNode[1].rfind('foot') != -1: footInitFull = initNode elif initLocalNode[1].rfind('ball') != -1: ballInitFull = initNode elif initLocalNode[1].rfind('tip') != -1: tipInitFull = initNode elif initLocalNode[1].rfind('space') != -1: spaceInitFull = initNode elif initLocalNode[1].rfind('control') != -1: controlInitFull = initNode jointListGroup = [self.filterGroupNodeDic['fkJnt'], self.filterGroupNodeDic['ikJnt'], self.filterGroupNodeDic['outputBlend']] for initNode, parentNode in self.filterGroupNodeDic['init'].iteritems(): initLocalNode = util.fullPathName2Local(initNode) partStr = initLocalNode[1].replace('_init', '') if initLocalNode[1].rfind('loleg') != -1: for controlFkSpace in self.filterGroupNodeDic['controlFkSpace']: controlLocalFkSpace = util.fullPathName2Local(controlFkSpace) if controlLocalFkSpace[1].rfind('loleg') != -1: matrixOps = util.localMatrixOp(self.moduleNameSpace, 'loleg_init') cmds.connectAttr(uplegInitFull+'.worldInverseMatrix', matrixOps[0]+'.matrixIn[1]', f=True) cmds.connectAttr(initNode+'.worldMatrix', matrixOps[0]+'.matrixIn[0]', f=True) util.decompChannelBinding(matrixOps[1], controlFkSpace) for jointList in jointListGroup: for jnt in jointList: jntLocal = util.fullPathName2Local(jnt) if jntLocal[1].rfind('loleg') != -1: cmds.connectAttr(matrixOps[1]+'.outputTranslate', jnt+'.translate') cmds.connectAttr(matrixOps[1]+'.outputRotate', jnt+'.jointOrient') elif initLocalNode[1].rfind('foot') != -1: for controlFkSpace in self.filterGroupNodeDic['controlFkSpace']: controlLocalFkSpace = util.fullPathName2Local(controlFkSpace) if controlLocalFkSpace[1].rfind('foot') != -1: matrixOps = util.localMatrixOp(self.moduleNameSpace, 'foot_init') cmds.connectAttr(lolegInitFull+'.worldInverseMatrix', matrixOps[0]+'.matrixIn[1]', f=True) cmds.connectAttr(initNode+'.worldMatrix', matrixOps[0]+'.matrixIn[0]', f=True) util.decompChannelBinding(matrixOps[1], controlFkSpace) for jointList in jointListGroup: for jnt in jointList: jntLocal = util.fullPathName2Local(jnt) if jntLocal[1].rfind('foot') != -1: cmds.connectAttr(matrixOps[1]+'.outputTranslate', jnt+'.translate') cmds.connectAttr(matrixOps[1]+'.outputRotate', jnt+'.jointOrient') elif initLocalNode[1].rfind('ball') != -1: for controlFkSpace in self.filterGroupNodeDic['controlFkSpace']: controlLocalFkSpace = util.fullPathName2Local(controlFkSpace) if controlLocalFkSpace[1].rfind('ball') != -1: matrixOps = util.localMatrixOp(self.moduleNameSpace, 'ball_init') cmds.connectAttr(footInitFull+'.worldInverseMatrix', matrixOps[0]+'.matrixIn[1]', f=True) cmds.connectAttr(initNode+'.worldMatrix', matrixOps[0]+'.matrixIn[0]', f=True) util.decompChannelBinding(matrixOps[1], controlFkSpace) for jointList in jointListGroup: for jnt in jointList: jntLocal = util.fullPathName2Local(jnt) if jntLocal[1].rfind('ball') != -1: cmds.connectAttr(matrixOps[1]+'.outputTranslate', jnt+'.translate') cmds.connectAttr(matrixOps[1]+'.outputRotate', jnt+'.jointOrient') elif initLocalNode[1].rfind('tip') != -1: for controlFkSpace in self.filterGroupNodeDic['controlFkSpace']: controlLocalFkSpace = util.fullPathName2Local(controlFkSpace) if controlLocalFkSpace[1].rfind('tip') != -1: matrixOps = util.localMatrixOp(self.moduleNameSpace, 'ball_init') cmds.connectAttr(ballInitFull+'.worldInverseMatrix', matrixOps[0]+'.matrixIn[1]', f=True) cmds.connectAttr(initNode+'.worldMatrix', matrixOps[0]+'.matrixIn[0]', f=True) util.decompChannelBinding(matrixOps[1], controlFkSpace) for jointList in jointListGroup: for jnt in jointList: jntLocal = util.fullPathName2Local(jnt) if jntLocal[1].rfind('tip') != -1: cmds.connectAttr(matrixOps[1]+'.outputTranslate', jnt+'.translate') cmds.connectAttr(matrixOps[1]+'.outputRotate', jnt+'.jointOrient') for fkSpaceNode in self.filterGroupNodeDic['fkSpace']: fkSpaceLocalNode = util.fullPathName2Local(fkSpaceNode) if fkSpaceLocalNode[1].rfind('foot') != -1: matrixOps = util.localMatrixOp(self.moduleNameSpace, 'foot_init') cmds.connectAttr(lolegInitFull+'.worldInverseMatrix', matrixOps[0]+'.matrixIn[1]', f=True) cmds.connectAttr(footInitFull+'.worldMatrix', matrixOps[0]+'.matrixIn[0]', f=True) util.decompChannelBinding(matrixOps[1], fkSpaceNode) # soft IK OP upleg2lolegDistanceOp = util.createOpNode(self.moduleNameSpace, 'distanceBetween', 'upleg2loleg_distasnce') loleg2footDistanceOp = util.createOpNode(self.moduleNameSpace, 'distanceBetween', 'loleg2foot_distasnce') legDistanceOp = util.createOpNode(self.moduleNameSpace, 'plusMinusAverage', 'leg_distance_sum') cmds.connectAttr(uplegInitFull+'.worldMatrix', upleg2lolegDistanceOp+'.inMatrix1', f=True) cmds.connectAttr(lolegInitFull+'.worldMatrix', upleg2lolegDistanceOp+'.inMatrix2', f=True) cmds.connectAttr(lolegInitFull+'.worldMatrix', loleg2footDistanceOp+'.inMatrix1', f=True) cmds.connectAttr(footInitFull+'.worldMatrix', loleg2footDistanceOp+'.inMatrix2', f=True) cmds.connectAttr(upleg2lolegDistanceOp+'.distance', legDistanceOp+'.input1D[0]', f=True) cmds.connectAttr(loleg2footDistanceOp+'.distance', legDistanceOp+'.input1D[1]', f=True) softIkAssetPath = self.pathInfo.assetDirPath + 'softIkOpAsset' + '.' + self.file_extenstion_str softIkOpNode = '' softIkOpNodeNew = '' fileCheck = cmds.file( softIkAssetPath, query=True, exists=True ) if fileCheck: cmds.file( softIkAssetPath, i=True, mergeNamespacesOnClash=True ) containerNodes = cmds.ls(type='container', l=True) if containerNodes != None: for containerNode in containerNodes: localStr = containerNode.split(':')[-1] if localStr == 'softIKOp': softIkOpNode = containerNode if cmds.objExists(softIkOpNode): softIkOpNodeNew = cmds.rename(softIkOpNode, softIkOpNode + '_' + self.component_val) cmds.connectAttr(legDistanceOp+'.output1D', softIkOpNodeNew+'.In_initLength', f=True) softIkNode = '' for ikSoftNode in self.filterGroupNodeDic['ikSoft']: ikSoftNodeLocal = util.fullPathName2Local(ikSoftNode) if ikSoftNodeLocal[1].rfind('space') == -1: softIkNode = ikSoftNode cmds.connectAttr(softIkOpNodeNew+'.Out_softDistance', softIkNode +'.translateX', f=True) legIkSpaceNode = '' for ikSpaceNode in self.filterGroupNodeDic['ikSpace']: ikSpaceLocalNode = util.fullPathName2Local(ikSpaceNode) if ikSpaceLocalNode[1].rfind('leg') != -1 and ikSpaceLocalNode[1].rfind('soft') == -1: legIkSpaceNode = ikSpaceNode footikConLocalNode = '' footikConNode = '' for ikConNode in self.filterGroupNodeDic['controlIkCon']: ikConLocalNode = util.fullPathName2Local(ikConNode) if ikConLocalNode[1].rfind('foot') != -1: if ikConLocalNode[1].rfind('local') != -1: footikConLocalNode = ikConNode else: footikConNode = ikConNode ikControlDistanceOp = util.createOpNode(self.moduleNameSpace, 'distanceBetween', 'ik_control_distasnce') cmds.connectAttr(legIkSpaceNode+'.worldMatrix', ikControlDistanceOp+'.inMatrix1', f=True) cmds.connectAttr(footikConLocalNode+'.worldMatrix', ikControlDistanceOp+'.inMatrix2', f=True) cmds.connectAttr(ikControlDistanceOp+'.distance', softIkOpNodeNew+'.In_motionLength', f=True) cmds.connectAttr(footikConNode+'.softIK', softIkOpNodeNew+'.In_softWeight', f=True) for initNode, parentNode in self.filterGroupNodeDic['init'].iteritems(): initNodeLocal = util.fullPathName2Local(initNode) partStr = initNodeLocal[1].replace('_init', '') if partStr in ['foot', 'ball', 'tip']: for ikSpace in self.filterGroupNodeDic['ikSpace']: ikLocalSpace = util.fullPathName2Local(ikSpace) if ikLocalSpace[1].rfind(partStr) != -1: matrixOps = util.localMatrixOp(self.moduleNameSpace, partStr+'_init') cmds.connectAttr(uplegInitFull+'.worldInverseMatrix', matrixOps[0]+'.matrixIn[1]', f=True) cmds.connectAttr(initNode+'.worldMatrix', matrixOps[0]+'.matrixIn[0]', f=True) util.decompChannelBinding(matrixOps[1], ikSpace) uplegInitDecompOp = util.createOpNode(self.moduleNameSpace, 'decomposeMatrix', 'upleg_init_decomp') cmds.connectAttr(uplegInitFull+'.worldMatrix', uplegInitDecompOp+'.inputMatrix') lolegInitDecompOp = util.createOpNode(self.moduleNameSpace, 'decomposeMatrix', 'loleg_init_decomp') cmds.connectAttr(lolegInitFull+'.worldMatrix', lolegInitDecompOp+'.inputMatrix') footInitDecompOp = util.createOpNode(self.moduleNameSpace, 'decomposeMatrix', 'foot_init_decomp') cmds.connectAttr(footInitFull+'.worldMatrix', footInitDecompOp+'.inputMatrix') footVecOp = util.createOpNode(self.moduleNameSpace, 'plusMinusAverage', 'footVec') cmds.setAttr(footVecOp+'.operation',2) cmds.connectAttr(uplegInitDecompOp+'.outputTranslate', footVecOp+'.input3D[0]') cmds.connectAttr(footInitDecompOp+'.outputTranslate', footVecOp+'.input3D[1]') #cmds.connectAttr(footInitDecompOp+'.outputTranslate', +'.translate') footVecMagOp = util.createOpNode(self.moduleNameSpace, 'distanceBetween', 'footVecMag') cmds.connectAttr(uplegInitDecompOp+'.outputTranslate', footVecMagOp+'.point1') cmds.connectAttr(footInitDecompOp+'.outputTranslate', footVecMagOp+'.point2') footVecUnitOp = util.createOpNode(self.moduleNameSpace, 'multiplyDivide', 'footVecUnit') cmds.setAttr(footVecUnitOp+'.operation',2) cmds.connectAttr(footVecOp+'.output3D', footVecUnitOp+'.input1') cmds.connectAttr(footVecMagOp+'.distance', footVecUnitOp+'.input2X') cmds.connectAttr(footVecMagOp+'.distance', footVecUnitOp+'.input2Y') cmds.connectAttr(footVecMagOp+'.distance', footVecUnitOp+'.input2Z') lolegVecOp = util.createOpNode(self.moduleNameSpace, 'plusMinusAverage', 'lolegVec') cmds.setAttr(lolegVecOp+'.operation',2) cmds.connectAttr(lolegInitDecompOp+'.outputTranslate', lolegVecOp+'.input3D[0]') cmds.connectAttr(footInitDecompOp+'.outputTranslate', lolegVecOp+'.input3D[1]') lolegVecMagOp = util.createOpNode(self.moduleNameSpace, 'distanceBetween', 'lolegVecMag') cmds.connectAttr(lolegInitDecompOp+'.outputTranslate', lolegVecMagOp+'.point1') cmds.connectAttr(footInitDecompOp+'.outputTranslate', lolegVecMagOp+'.point2') lolegVecUnitOp = util.createOpNode(self.moduleNameSpace, 'multiplyDivide', 'lolegVecUnit') cmds.setAttr(lolegVecUnitOp+'.operation',2) cmds.connectAttr(lolegVecOp+'.output3D', lolegVecUnitOp+'.input1') cmds.connectAttr(lolegVecMagOp+'.distance', lolegVecUnitOp+'.input2X') cmds.connectAttr(lolegVecMagOp+'.distance', lolegVecUnitOp+'.input2Y') cmds.connectAttr(lolegVecMagOp+'.distance', lolegVecUnitOp+'.input2Z') poleSideVecOp = util.createOpNode(self.moduleNameSpace, 'vectorProduct', 'poleSideVec') cmds.setAttr(poleSideVecOp+'.normalizeOutput', 1) cmds.setAttr(poleSideVecOp+'.operation',2) cmds.connectAttr(footVecUnitOp+'.output', poleSideVecOp+'.input1') cmds.connectAttr(lolegVecUnitOp+'.output', poleSideVecOp+'.input2') poleFntVecOp = util.createOpNode(self.moduleNameSpace, 'vectorProduct', 'poleFntVec') cmds.setAttr(poleFntVecOp+'.normalizeOutput', 1) cmds.setAttr(poleFntVecOp+'.operation',2) cmds.connectAttr(poleSideVecOp+'.output', poleFntVecOp+'.input1') cmds.connectAttr(footVecUnitOp+'.output', poleFntVecOp+'.input2') poleMatOp = util.createOpNode(self.moduleNameSpace, 'fourByFourMatrix', 'poleMat') # X axis cmds.connectAttr(poleSideVecOp+'.outputX', poleMatOp+'.in00') cmds.connectAttr(poleSideVecOp+'.outputY', poleMatOp+'.in01') cmds.connectAttr(poleSideVecOp+'.outputZ', poleMatOp+'.in02') # Y axis cmds.connectAttr(footVecUnitOp+'.outputX', poleMatOp+'.in10') cmds.connectAttr(footVecUnitOp+'.outputY', poleMatOp+'.in11') cmds.connectAttr(footVecUnitOp+'.outputZ', poleMatOp+'.in12') # Z axis cmds.connectAttr(poleFntVecOp+'.outputX', poleMatOp+'.in20') cmds.connectAttr(poleFntVecOp+'.outputY', poleMatOp+'.in21') cmds.connectAttr(poleFntVecOp+'.outputZ', poleMatOp+'.in22') # translate cmds.connectAttr(footInitDecompOp+'.outputTranslateX', poleMatOp+'.in30') cmds.connectAttr(footInitDecompOp+'.outputTranslateY', poleMatOp+'.in31') cmds.connectAttr(footInitDecompOp+'.outputTranslateZ', poleMatOp+'.in32') # decomp poleMatDecompOp = util.createOpNode(self.moduleNameSpace, 'decomposeMatrix', 'poleMat_decomp') cmds.connectAttr(poleMatOp+'.output', poleMatDecompOp+'.inputMatrix') cmds.connectAttr(poleMatDecompOp+'.outputTranslate', spaceInitFull+'.translate') cmds.connectAttr(poleMatDecompOp+'.outputRotate', spaceInitFull+'.rotate') matrixOps = util.localMatrixOp(self.moduleNameSpace, 'space_init') cmds.connectAttr(controlInitFull+'.worldInverseMatrix', matrixOps[0]+'.matrixIn[1]', f=True) cmds.connectAttr(spaceInitFull+'.worldMatrix', matrixOps[0]+'.matrixIn[0]', f=True) for controlPoleNode in self.filterGroupNodeDic['controlPoleAuto']: controlPoleNodeLocal = util.fullPathName2Local(controlPoleNode) if controlPoleNodeLocal[1].rfind('Pole_Auto') != -1: util.decompChannelBinding(matrixOps[1], controlPoleNode) return
def loadInfoWithScene(storeNode, attr): obj = "%s.%s" % (storeNode, attr) if cmds.objExists(obj): return cmds.getAttr(obj) else: return None
def addReference(rfn, reference): """ Add proxy to current reference. """ if cmds.nodeType(rfn) == "reference": rfn = rfn elif os.path.isfile(rfn): rfn = cmds.referenceQuery(rfn, rfn=True) else: print "%s is not reference" % rfn return None #Validate current reference. filename = cmds.referenceQuery(rfn, filename=True) namespace = cmds.file(filename, query=True, namespace=True) parents = cmds.referenceQuery(rfn, parent=True, referenceNode=True) if parents: print "%s has reference parents, please open first parent if you want to add new proxy reference for current reference." % rfn return None if cmds.file(filename, query=True, usingNamespaces=True) is False: print "%s is not using namespaces." % rfn return None #Validate target reference. if cmds.objExists(reference) and cmds.nodeType(reference) == "reference": parents = cmds.referenceQuery(reference, parent=True, referenceNode=True) if parents: print "%s has reference parents, please open first parent if you want to add new proxy reference for current reference." % reference return None elif os.path.isfile(reference): if not re.findall(".ma$|.mb$", reference): print "%s is not maya scene file." % reference return None else: print "%s is not valid reference." % reference return None #Get current reference proxy manager. pm = cmds.listConnections(rfn, type="proxyManager") if pm: pm = pm[0] else: name = cmds.referenceQuery(rfn, filename=True).split("/")[-1].split(".")[0] pm = cmds.createNode("proxyManager", name=name + "PM") cmds.connectAttr("%s.activeProxy" % pm, "%s.proxyList[0]" % pm) cmds.connectAttr("%s.proxyList[0]" % pm, "%s.proxyMsg" % rfn) cmds.connectAttr("%s.proxyMsg" % rfn, "%s.sharedEditsOwner" % pm) #Get empty proxy attribute. pmProxy = "{0}.proxyList[%s]".format(pm) pmIndex = 0 while pmIndex < 1000: if cmds.listConnections(pmProxy % pmIndex, type="reference"): pmIndex = pmIndex + 1 continue else: pmProxy = pmProxy % pmIndex break #Load new reference. if not cmds.objExists(reference) and os.path.isfile(reference): reference = cmds.file(reference, reference=True, mergeNamespacesOnClash=True, options="v=0;", namespace=namespace, loadReferenceDepth="none") reference = cmds.referenceQuery(reference, rfn=True) else: reference = reference if cmds.nodeType(reference) == "reference": cmds.connectAttr(pmProxy, "%s.proxyMsg" % reference) return reference else: print "%s is not reference." % reference return None
def option_doItYiJointLine(name,aimObj,jnt1,jnt2): p1 = option_getWorldPosition(jnt1) p2 = option_getWorldPosition(jnt2) j = option_createJoint_y(p1,p2,name) """ option_par(jnt1,j[0]) cmds.makeIdentity(j[0],apply=True,t=0,r=1,s=0,n=0,pn=1) """ ikHandle = cmds.ikHandle(n=name + "_ikHandle1",sj=j[0],ee=j[1])[0] ctrl = option_createCircle(name) option_par(j[1],ctrl[1]) cmds.parent(ikHandle,ctrl[0]) cmds.setAttr(ikHandle+".v",0) aimG = [cmds.group(n= (name + "_scaleAim_" + x + y),em=1) for x in ["A","B"] for y in ["1","2"] ] aimS = cmds.group(n= (name + "_scaleAim_G"),em=1) cmds.parent(aimG,aimS) option_par(j[0],aimG[0]) option_par(j[1],aimG[1]) option_par(j[0],aimG[2]) option_par(j[1],aimG[3]) g1 = cmds.group(n= name + "_YiIK_G",em=1) g2 = cmds.group(n= name + "_YiIK_Ro",em=1) g3 = cmds.group(n= name + "_AimUp",em=1) cmds.parent((g2,g3),g1) option_par(j[0],g1) y = getScaleValue(j[0],j[1],"t") cmds.setAttr(g3+".ty",y) cmds.parent(ctrl[1],g2) cmds.parent(aimS,g1) cmds.parent(j[0],g1) g4 = aimObj + "_del_Aim" g5 = aimObj + "_optionAim" if cmds.objExists(g5) == False: cmds.group(n= g4,em=1) cmds.group(n= g5,em=1) cmds.parent(g5,g4) option_par(aimObj,g4) if cmds.getAttr(aimObj+".tx") > 0: cmds.setAttr(g5+".tx",0.5) if cmds.getAttr(aimObj+".tx") < 0: cmds.setAttr(g5+".tx",-0.5) cmds.parent(g5,w=1) down = cmds.listRelatives(aimObj,c=1) if down != None: t = getScaleValue(aimObj,down[0]) [cmds.setAttr(g5+".t"+x,y) for x,y in zip(["x","y","z"],t) ] cmds.parentConstraint(aimObj,g5,mo=1,weight=1) if cmds.objExists("optionAim_G") == False: cmds.group(n="optionAim_G",em=1) l = cmds.listRelatives("optionAim_G",c=1) if l == None: l = [] if g5 not in l: cmds.parent(g5,"optionAim_G") if cmds.objExists(g4): cmds.delete(g4) cmds.aimConstraint(g5,g2,mo=1,weight=1,aimVector=(1,0,0) ,upVector=(0,1,0),worldUpType="object",worldUpObject=g3) cmds.parentConstraint(ctrl[0],aimG[1],mo=1,weight=1) cmds.parentConstraint(g5,aimG[3],mo=1,weight=1) db1 = option_addDisBet(name,i=1,input1=aimG[0],input2 = aimG[1]) cmds.connectAttr(db1+".distance",j[1]+".tx") db2 = option_addDisBet(name,i=2,input1=aimG[2],input2 = aimG[3]) mulName = cmds.createNode("multiplyDivide",n=(name +"_mul")) cmds.connectAttr(db2+".distance",mulName+".input1X") cmds.setAttr(mulName+".input2X",cmds.getAttr(mulName+".input1X")) cmds.setAttr(mulName+".operation",2) cmds.connectAttr(mulName+".outputX",g2+".sx") if not cmds.objExists("optionYiIK_G"): cmds.group(n="optionYiIK_G",em=1) cmds.parent(str(g1),"optionYiIK_G") else: cmds.parent(str(g1),"optionYiIK_G") return g1
def _matchSourceBlendshapesToTarget(source, target): if not cmds.objExists(source) or not cmds.objExists(target): return sourceInputTargets = [] bs = getConnectedInputBlendshapeNode(source) if bs: sourceInputTargets = cmds.listConnections(bs + '.inputTarget') cmds.delete(source, ch=1) # Reset source transformation. cmds.setAttr(source + '.tx', 0) cmds.setAttr(source + '.ty', 0) cmds.setAttr(source + '.tz', 0) # Temporally disable target deformation otherwise we cannot match the source and target correctly. for node in cmds.listHistory(target): if cmds.nodeType(node) == 'skinCluster' or cmds.nodeType( node) == 'blendShape': cmds.setAttr(node + '.envelope', 0.0) sourcePos = getMeshVertexPosition(source + '.vtx[0]') targetPos = getMeshVertexPosition(target + '.vtx[0]') dx = targetPos[0] - sourcePos[0] dy = targetPos[1] - sourcePos[1] dz = targetPos[2] - sourcePos[2] cmds.setAttr(source + '.tx', dx) cmds.setAttr(source + '.ty', dy) cmds.setAttr(source + '.tz', dz) cmds.makeIdentity(source, apply=True, t=1, r=1, s=1, n=0, pn=1) # Update all the source input targets to match our target mesh and freeze them. for sourceInputTarget in sourceInputTargets: cmds.setAttr(sourceInputTarget + '.tx', dx) cmds.setAttr(sourceInputTarget + '.ty', dy) cmds.setAttr(sourceInputTarget + '.tz', dz) cmds.makeIdentity(sourceInputTarget, apply=True, t=1, r=1, s=1, n=0, pn=1) # Recreate blendshape node. cmds.blendShape(sourceInputTargets, source) # Restore target deformation. for node in cmds.listHistory(target): if cmds.nodeType(node) == 'skinCluster' or cmds.nodeType( node) == 'blendShape': cmds.setAttr(node + '.envelope', 1.0) # Match the positions of vertices of source to target sourceVertsNum = cmds.polyEvaluate(source, v=True) targetVertsNum = cmds.polyEvaluate(target, v=True) pivotOffset = [0, 0, 0] if (sourceVertsNum == targetVertsNum): for i in range(sourceVertsNum): resTar = getMeshVertexPosition(target + '.vtx[%s]' % i) resSrc = getMeshVertexPosition(source + '.vtx[%s]' % i) srcPT = [ round(resSrc[0], 5), round(resSrc[1], 5), round(resSrc[2], 5) ] tarPT = [ round(resTar[0], 5), round(resTar[1], 5), round(resTar[2], 5) ] pivotOffset[0] = pivotOffset[0] + tarPT[0] - srcPT[0] pivotOffset[1] = pivotOffset[1] + tarPT[1] - srcPT[1] pivotOffset[2] = pivotOffset[2] + tarPT[2] - srcPT[2] cmds.xform(source + '.vtx[%s]' % i, t=tarPT, ws=True) sourcePiv = cmds.xform(source, piv=True, q=True, ws=True) sourcePiv[0] = sourcePiv[0] + pivotOffset[0] / sourceVertsNum sourcePiv[1] = sourcePiv[1] + pivotOffset[1] / sourceVertsNum sourcePiv[2] = sourcePiv[2] + pivotOffset[2] / sourceVertsNum cmds.xform(source, ws=True, piv=(sourcePiv[0], sourcePiv[1], sourcePiv[2]))
def Option_doItChestLine(): if cmds.objExists("Chest_M_all_G"): chestJoint = cmds.listRelatives("Chest_M_all_G",c=1,type="joint")[0] j = cmds.listRelatives(chestJoint,ad=1,type="joint") p1 = cmds.xform(chestJoint,q=1,ws=1,t=1) p2 = cmds.xform(j[1],q=1,ws=1,t=1) p3 = cmds.xform(j[0],q=1,ws=1,t=1) cmds.delete("Chest_M_all_G") j1 = cmds.joint(n="Left_bosomA_joint1",p=p1) j2 = cmds.joint(n="Left_bosomA_joint2",p=p2) cmds.joint(j1,e=1,zso=1,oj="xyz",sao="yup") j3 = cmds.joint(n="Left_bosomA_joint3",p=p3) cmds.joint(j2,e=1,zso=1,oj="xyz",sao="yup") j4 = cmds.joint(n="Left_bosomA_joint4",p=p3) cmds.joint(j3,e=1,zso=1,oj="xyz",sao="yup") cmds.select(cl=1) cmds.setAttr(j3+".drawStyle",2) cmds.setAttr(j4+".ry",-90) cmds.makeIdentity(j4,apply=1,r=1,n=0,pn=1) n = [(x-y)/3.0 for x,y in zip(p2,p3)] p4 = [x-y for x,y in zip(p2,n)] p5 = [x-y for x,y in zip(p4,n)] j1_B = cmds.joint(n="Left_bosomB_joint1",p=p1) j2_B = cmds.joint(n="Left_bosomB_joint2",p=p4) cmds.joint(j1_B,e=1,zso=1,oj="xyz",sao="yup") cmds.select(cl=1) j1_C = cmds.joint(n="Left_bosomC_joint1",p=p1) j2_C = cmds.joint(n="Left_bosomC_joint2",p=p5) cmds.joint(j1_C,e=1,zso=1,oj="xyz",sao="yup") cmds.select(cl=1) [cmds.mirrorJoint(x,mirrorYZ=1,mirrorBehavior=1,searchReplace=("Left","Right")) for x in [j1,j1_B,j1_C] ] ikH1 = cmds.ikHandle(sj=j2,ee=j3,n="Left_bosomA_ikHandle1")[0] ikH2 = cmds.ikHandle(sj=j1_B,ee=j2_B,n="Left_bosomB_ikHandle1")[0] ikH3 = cmds.ikHandle(sj=j1_C,ee=j2_C,n="Left_bosomC_ikHandle1")[0] ctrl = option_createCircle("Left_bosomA") cmds.delete(cmds.parentConstraint(j4,ctrl[1])) [ cmds.parentConstraint(j2,x,mo=1) for x in [ikH2,ikH3] ] [ cmds.parentConstraint(ctrl[0],x,mo=1) for x in [ikH1,j4]] up = cmds.group(n="Left_bosom_Aim_up",em=1) up_g = cmds.group(n="Left_bosom_Aim_up_g",em=1) cmds.parent(up,up_g) cmds.delete( cmds.parentConstraint(j1,up_g,weight=1)) cmds.setAttr(up+".ty",0.05) cmds.parent(up,w=1) cmds.delete(up_g) j1_r = j1.replace("Left","Right") j2_r = j2.replace("Left","Right") j3_r = j3.replace("Left","Right") j4_r = j4.replace("Left","Right") cmds.setAttr(j3_r+".drawStyle",2) j1_B_r = j1_B.replace("Left","Right") j2_B_r = j2_B.replace("Left","Right") j1_C_r = j1_C.replace("Left","Right") j2_C_r = j2_C.replace("Left","Right") ikH1_r = cmds.ikHandle(sj=j2_r,ee=j3_r,n="Right_bosomA_ikHandle1")[0] ikH2_r = cmds.ikHandle(sj=j1_B_r,ee=j2_B_r,n="Right_bosomB_ikHandle1")[0] ikH3_r = cmds.ikHandle(sj=j1_C_r,ee=j2_C_r,n="Right_bosomC_ikHandle1")[0] ctrl_r = option_createCircle("Right_bosomA") cmds.delete(cmds.parentConstraint(j4_r,ctrl_r[1])) [ cmds.parentConstraint(j2_r,x,mo=1) for x in [ikH2_r,ikH3_r] ] [ cmds.parentConstraint(ctrl_r[0],x,mo=1) for x in [ikH1_r,j4_r]] up_r = cmds.group(n="Right_bosom_Aim_up",em=1) up_g_r = cmds.group(n="Right_bosom_Aim_up_g") cmds.select(cl=1) cmds.delete( cmds.parentConstraint(j1_r,up_g_r,weight=1)) cmds.setAttr(up_r+".ty",-0.05) cmds.parent(up_r,w=1) cmds.delete(up_g_r) if cmds.objExists("Shoulder_L_optionAim"): cmds.aimConstraint("Shoulder_L_optionAim",j1,mo=1,weight=1,aimVector=(1,0,0) ,upVector=(0,1,0),worldUpType="object",worldUpObject=up) if cmds.objExists("Shoulder_R_optionAim"): cmds.aimConstraint("Shoulder_R_optionAim",j1_r,mo=1,weight=1,aimVector=(1,0,0) ,upVector=(0,1,0),worldUpType="object",worldUpObject=up_r) if not cmds.objExists("Left_bosom_G"): cmds.group(n="Left_bosom_G",em=1) cmds.parent([j1,j1_B,j1_C,ctrl[1],ikH1,ikH2,ikH3,up],"Left_bosom_G") if not cmds.objExists("Right_bosom_G"): cmds.group(n="Right_bosom_G",em=1) cmds.parent([j1_r,j1_B_r,j1_C_r,ctrl_r[1],ikH1_r,ikH2_r,ikH3_r,up_r],"Right_bosom_G") cmds.select(cl=1) [cmds.setAttr(x+".v",0) for x in [ikH1_r,ikH2_r,ikH3_r,up_r,ikH1,ikH2,ikH3,up] ] if cmds.objExists("optionYiIK_G"): cmds.parent(("Left_bosom_G","Right_bosom_G"),"optionYiIK_G") [cmds.setAttr(x+".radi",getNum.num) for x in [j1,j2,j3,j4,j1_B,j2_B,j1_C,j2_C] ] [cmds.parentConstraint("Chest_M",x,mo=1,weight=1) for x in ["Left_bosom_G","Right_bosom_G"] if cmds.objExists(x) and cmds.objExists("Chest_M")]
def doItAddAdvOptionJoint(*args): if cmds.objExists("Root_M") == 1: n = cmds.createNode("distanceBetween") newG = cmds.group(em=1) cmds.parentConstraint("Root_M",newG) cmds.connectAttr(newG+".translate",n+".point2") flo = cmds.getAttr(n+".distance") num = flo / 1.0137173930603345 cmds.delete(n,newG) else: num = 1 advSlider = cmds.ls("*Slide*") try: ss = cmds.listRelatives("SlideSystem",c=1) except: ss = [] try: ds = cmds.listRelatives("DeformationSystem",c=1) except: ds = [] try: Slider = [ s for s in advSlider if s in (ss + ds) ] except: Slider = [] if Slider != []: bool_T = cmds.confirmDialog(t="ADV Slide joint",m="ÊÇ·ñɾȥADVÉú³ÉµÄ¸¨Öú¹Ç÷À?",b=("Yes","No")) if bool_T == "Yes": cmds.delete(advSlider) advLeg_l = ["Toes_L","Ankle_L","Knee_L","Hip_L"] advLeg_r = [s.replace("L","R") for s in advLeg_l] advSpine = ["Root_M","Spine1_M","Spine2_M","Spine3_M","Neck_M","Head_M"] advShoulder_l = ["Shoulder_L","Elbow_L","Wrist_L"] advShoulder_r = [s.replace("L","R") for s in advShoulder_l] advFinger_five = ["Thumb","Index","Middle","Ring","Pinky"] advFinger_l = [s+"Finger"+str(i)+"_L" for s in advFinger_five for i in [1,2,3]] advFinger_r = [s.replace("L","R") for s in advFinger_l] newB = ["Elbow_L","Knee_L"] adv = optionJointClass() cmds.select((advLeg_l+advShoulder_l+advSpine+advFinger_l)) adv.option_allSelct() adv.option_selectJoint() [ adv.selectJoint.append(x) for x in newB ] allJoints = adv.option_createShiJoint(adv.selectJoint) cmds.select("ShoulderPart2_L","Elbow_L_OptionFirst2_joint1") adv.option_LocatorJoint() cmds.select("HipPart2_L","Knee_L_OptionFirst2_joint1") adv.option_LocatorJoint() cmds.select(cl=1) f = [s[0][0] for s in allJoints] A = [s[i][ii] for s in allJoints for i in range(1,3) for ii in range(0,4)] joints = f + A [cmds.setAttr(j+".radi",0.5*num) for j in joints ] advSetTx(advFinger_l,0.02*num) [ advSetTxToOne(advShoulder_l[i],v*num) for i,v in zip(range(0,3),[0.08,0.05,0.04]) ] [ advSetTxToOne(advLeg_l[i],v*num) for i,v in zip(range(0,4),[0.05,0.06,0.1,0.12]) ] [ advSetTxToOne(newB[i],v*num,AB="B") for i,v in zip(range(0,2),[0.06,0.11]) ] for s in advSpine: sof = s + "_OptionFirst1_joint1" sofp = sof + "_parentConstraint1" parObj = cmds.listConnections(sofp + ".target[0].targetParentMatrix")[0] cmds.delete(sofp) cmds.setAttr(sof+".rz",90) cmds.parentConstraint(parObj,sof,mo=1,weight=1) [ advSetTxToOne(advSpine[i],v*num) for i,v in zip(range(0,6),[0.15,0.15,0.15,0.15,0.08,0.08]) ] [ cmds.setAttr(x+".tx",cmds.getAttr(x+".tx")*0.5) for x in ["Knee_L_OptionA2_joint2","Knee_L_OptionB2_joint2","Hip_L_OptionA2_joint2"]] getNum.num = num opcj = Option_CreateChestJoint(num) yi = Option_CreateADVYIoint(num) print "------ADV¸¨Öú¹Ç÷À´´½¨Íê³É-----------",
def doItAddAdvOptionJointLine(*args): s_L = [ x for x in optionJointClass.selectJoint if "_L" in x ] s_M = [ x for x in optionJointClass.selectJoint if "_M" in x ] optionJointClass.optionShiJointLine(M=True,obj=s_L) optionJointClass.optionShiJointLine(M=False,obj=s_M) if cmds.objExists("Main"): cmds.parent("option_joints_G","Main") cmds.select(cl=1) advLeg_l = ["Toes_L","Ankle_L","Knee_L","Hip_L"] advSpine = ["Root_M","Spine1_M","Spine2_M","Spine3_M","Neck_M","Head_M"] advShoulder_l = ["Shoulder_L","Elbow_L","Wrist_L"] advFinger_five = ["Thumb","Index","Middle","Ring","Pinky"] advFinger_l = [s+"Finger"+str(i)+"_L" for s in advFinger_five for i in [1,2,3]] advSetSlide(advFinger_l,0.02,"A","slide",st="2") advSetSlide((advLeg_l + advSpine + advShoulder_l),0.07,"A","slide",st="2") advSetSlide(["Knee_L","Elbow_L"],0.07,"B","slide",st="2") advSetSlide((advLeg_l + advSpine + advShoulder_l + advFinger_l),0.5,"A","slide",st="1") advSetSlide(["Knee_L","Elbow_L"],0.15,"B","slide",st="1") advSetSlide(["Toes_L","Ankle_L","Hip_L","Elbow_L","Wrist_L"],-1,"A","slide",st="2") advSetSlide(["Elbow_L"],-1,"B","slide",st="2") [cmds.setAttr(x+".slide",0.75) for x in ["Ankle_L_OptionA1_joint1","Ankle_L_OptionA3_joint1"]] [cmds.setAttr(x+".slide",0.25) for x in ["Shoulder_L_OptionA1_joint1","Shoulder_L_OptionA3_joint1"]] [advSetSlideToOne(x,-1,"slide") for x in ["Toes_L_OptionA1_joint2","Toes_L_OptionA2_joint2","Ankle_L_OptionA1_joint2","Ankle_L_OptionA2_joint2","Hip_L_OptionA1_joint2","Shoulder_L_OptionA3_joint2","Wrist_L_OptionA2_joint2","Wrist_L_OptionA1_joint2"]] unFollow = ["Toes_L","Ankle_L","Hip_L","Shoulder_L","Wrist_L"] + advFinger_l advSetFollow(unFollow,"A","2",2) [advSetMirrorAttr(x,"A",1,"slide","erz","rz") for x in advLeg_l + advShoulder_l + advFinger_l] [advSetMirrorAttr(x,"A",2,"slide","etx","tx") for x in advLeg_l + advShoulder_l + advFinger_l] [advSetMirrorAttr(x,"B",1,"slide","erz","rz") for x in ["Knee_L","Elbow_L"] ] [advSetMirrorAttr(x,"B",2,"slide","etx","tx") for x in ["Knee_L","Elbow_L"] ] roL = ["Knee_L_OptionA2_joint2","Knee_L_OptionA4_joint2","Knee_L_OptionB2_joint2","Knee_L_OptionB4_joint2","Elbow_L_OptionB4_joint2","Elbow_L_OptionB2_joint2","Elbow_L_OptionA4_joint2","Elbow_L_OptionA2_joint2" ] roR = [x.replace("L","R") for x in roL] [ advSetNewRo(x,"rz") for x in roL + roR ] [ advSetSlideToOne(x,-1) for x in roL + roR ] cmds.delete("Spine1_M_OptionFirst1_joint1_parentConstraint1") cmds.parentConstraint("Spine1_M","Spine1_M_OptionFirst1_joint1",mo=1,weight=1) [advSetSpineRo(x,"rx",cb=0) for x in advSpine] spine_J = [advGetName(advSpine[x],"A",y,1) for x in range(1,len(advSpine)) for y in [1,3] ] [ advSetSlideToOne(x,-1.5) for x in spine_J ] [ advSetSlideToOne(x,-1) for x in ["Spine2_M_OptionA1_joint1","Spine2_M_OptionA2_joint1","Spine2_M_OptionA3_joint1","Spine2_M_OptionA4_joint1","Neck_M_OptionA4_joint1","Neck_M_OptionA2_joint1","Head_M_OptionA4_joint1","Head_M_OptionA2_joint1"]] [ advSetSlideToOne(x,0) for x in ["Root_M_OptionA4_joint1","Root_M_OptionA2_joint1","Spine1_M_OptionA1_joint1","Spine1_M_OptionA2_joint1","Spine1_M_OptionA3_joint1","Spine1_M_OptionA4_joint1","Spine3_M_OptionA1_joint1","Spine3_M_OptionA2_joint1","Spine3_M_OptionA3_joint1","Spine3_M_OptionA4_joint1","Neck_M_OptionA3_joint1","Neck_M_OptionA1_joint1","Head_M_OptionA3_joint1","Head_M_OptionA1_joint1"]] [ advSetSlideToOne(x,2) for x in ["Root_M_OptionA1_joint1","Root_M_OptionA3_joint1"] ] if cmds.objExists("Root_M_OptionFirst1_joint1_parentConstraint1"): cmds.delete("Root_M_OptionFirst1_joint1_parentConstraint1") cmds.parentConstraint("Root_M","Root_M_OptionFirst1_joint1",mo=1,weight=1) rm4 = cmds.listRelatives("Root_M_OptionFirst1_joint1",c=1,type="joint") [cmds.setAttr(x+".slide",0.5) for x in rm4] advSetFollow(advSpine,"A","2",2) j1 = [s+"_Option"+ss+"_joint2" for s in advSpine for ss in ["A1","A4"]] j2 = [s+"_Option"+ss+"_joint2" for s in advSpine for ss in ["A3","A2"]] [ advSetSlideToOne(x,-1) for x in j1 ] [ advSetSlideToOne(x,5) for x in j1+j2 ] cmds.setAttr("Root_M_OptionA2_joint2.slide",-0.001) cmds.setAttr("Root_M_OptionA3_joint1.slide",0.5) cmds.setAttr("Root_M_OptionA1_joint1.slide",0.5) cmds.setAttr("Spine1_M_OptionA2_joint2.slide",0.001) cmds.setAttr("Spine3_M_OptionA3_joint1.slide",0.75) cmds.setAttr("Spine3_M_OptionA1_joint1.slide",0.75) cmds.setAttr("Spine3_M_OptionA2_joint1.slide",-0.5) cmds.setAttr("Spine3_M_OptionA4_joint1.slide",-0.5) cmds.setAttr("Head_M_OptionA2_joint2.slide",-0.0035) option_setFollow(f=2,obj="Head_M_OptionA2_joint2") option_setFollow(f=2,obj="Root_M_OptionA2_joint2") yi = Option_doItAdvYiLine() chest = Option_doItChestLine() Option_setCircleScale() cmds.select(cl=1) print "------ADV¸¨Öú¹Ç÷À¹ØÁªÍê³É-----------",
def option_createJoint(obj): firstJointName = [] nextJointName = [] lastJointName =[] objName = obj + "_Option" #ro = pm.xform(obj,q=1,ws=1,ro=1) #tr = pm.xform(obj,q=1,ws=1,t=1) five_p =[[0,0,0],[0,1,0],[0,0,1],[0,-1,0],[0,0,-1]] for v in range(1,101): if cmds.objExists(objName+"First"+str(v)+"_joint1") == 0: na1 = objName+"First"+str(v) break for a in ["A","B","C","D","E","F","G","H","L","M","N","O","P","Q","R","S","T","U","I","Y"]: if cmds.objExists(objName+a+"1_joint1") == 0 or cmds.objExists(objName+a+"2_joint1") == 0 or cmds.objExists(objName+a+"3_joint1") == 0 or cmds.objExists(objName+a+"4_joint1") == 0: na2 = objName+a break for i in range(0,5): if i == 0: C_jointName = option_createTwoJoint(name= na1,p=[five_p[0],]) firstJointName.append(C_jointName) else: N_jointName = option_createTwoJoint(name= na2+str(i),p=[five_p[0],five_p[i]]) cmds.parent(N_jointName[0],C_jointName) cmds.select(cl=1) if i == 2 : cmds.setAttr((N_jointName[0]+".rotateX"), -90) if i == 4 : cmds.setAttr((N_jointName[0]+".rotateX"), -90) nextJointName.append(N_jointName[0]) lastJointName.append(N_jointName[1]) #pm.xform(C_jointName,ro=ro) #pm.xform(C_jointName,t = tr) #cmds.select(C_jointName) #mel.eval("channelBoxCommand -freezeRotate;") delp = cmds.parentConstraint(obj,C_jointName,weight=1) cmds.delete(delp) cmds.select(C_jointName) mel.eval("channelBoxCommand -freezeRotate;") par_name = cmds.listRelatives(obj,p=1) if par_name != None: cmds.parentConstraint(par_name[0],C_jointName,mo=1,weight=1) cmds.select(cl=1) for i in range(0,len(nextJointName)): option_lock(lastJointName[i],l=0,attr=["translateX",]) option_lock(nextJointName[i],l=0,attr=["rotateZ",]) allJointName =[firstJointName,nextJointName,lastJointName] if cmds.objExists("option_joints_G"): cmds.parent(firstJointName,"option_joints_G") else: cmds.group(n="option_joints_G",em=1) cmds.parent(firstJointName,"option_joints_G") return allJointName
playbackRangeInit() global listObjects; listObjects = cmds.ls( sl=True ) # Get list of selected object if ( len(listObjects) == 0 ): print "\n||| Need to select 1 or 2 objects |||\n" else: progBar(len(listObjects)) # start progress bar window global listFixed; listFixed = listObjects [:] for i in range( len( listFixed ) ): listFixed[i] = listFixed[i].replace( "|", "_" ) listFixed[i] = listFixed[i].replace( ":", "_" ) if( cmds.objExists( mainLayerName ) ): print "\n||| OVERLAPPY start |||\n" else: cmds.animLayer( mainLayerName ) print "\n||| OVERLAPPY start ||| Layer created |||\n" #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| for i in range( len( listFixed ) ): cmds.progressBar( progressControl, edit=True, step=stepValue ) global aimLoc; aimLoc = listFixed[i] + "_aim_loc" # Aim locator name global tempLoc; tempLoc = listFixed[i] + "_temp_loc" # Physical locator name global tempPart; tempPart = listFixed[i] + "_temp_part" # nParticle name global tempNucl; tempNucl = "nucleus1" # Nucleus node name
def Option_SelectToSkinJoint(): cmds.select(Option_ListOptionJoint2()) if cmds.objExists("optionYiIK_G"): yiSikn =[x for x in cmds.listRelatives("optionYiIK_G",ad=1,type="joint") for y in ["Joint2","joint2","joint4"] if y in x] cmds.select(yiSikn,add=1) print "-----Ñ¡ÔñÍê³É-----",
def mgear_dagmenu_fill(parent_menu, current_control): """Fill the given menu with mGear's custom animation menu Args: parent_menu(str): Parent Menu path name current_control(str): current selected mGear control """ # gets current selection to use later on _current_selection = cmds.ls(selection=True) # get child controls child_controls = [] for ctl in _current_selection: [ child_controls.append(x) for x in get_all_tag_children(ctl) if x not in child_controls ] # [child_controls.append(x) # for x in get_all_tag_children(cmds.ls(cmds.listConnections(ctl), # type="controller")) # if x not in child_controls] child_controls.append(current_control) # handles ik fk blend attributes for attr in cmds.listAttr(current_control, userDefined=True, keyable=True) or []: if (not attr.endswith("_blend") or cmds.addAttr("{}.{}".format(current_control, attr), query=True, usedAsProxy=True)): continue # found attribute so get current state current_state = cmds.getAttr("{}.{}".format(current_control, attr)) states = {0: "Fk", 1: "Ik"} rvs_state = states[int(not (current_state))] cmds.menuItem(parent=parent_menu, label="Switch {} to {}".format( attr.split("_blend")[0], rvs_state), command=partial(__switch_fkik_callback, current_control, False, attr), image="kinReroot.png") cmds.menuItem(parent=parent_menu, label="Switch {} to {} + Key".format( attr.split("_blend")[0], rvs_state), command=partial(__switch_fkik_callback, current_control, True, attr), image="character.svg") cmds.menuItem(parent=parent_menu, label="Range switch", command=partial(__range_switch_callback, current_control, attr)) # divider cmds.menuItem(parent=parent_menu, divider=True) # check is given control is an mGear control if cmds.objExists("{}.uiHost".format(current_control)): # select ui host cmds.menuItem(parent=parent_menu, label="Select host", command=partial(__select_host_callback, current_control), image="hotkeySetSettings.png") # select all function cmds.menuItem(parent=parent_menu, label="Select child controls", command=partial(__select_nodes_callback, child_controls), image="dagNode.svg") # divider cmds.menuItem(parent=parent_menu, divider=True) # reset selected cmds.menuItem(parent=parent_menu, label="Reset", command=partial(reset_all_keyable_attributes, _current_selection), image="holder.svg") # reset all bellow cmds.menuItem(parent=parent_menu, label="Reset all bellow", command=partial(reset_all_keyable_attributes, child_controls)) # add transform resets k_attrs = cmds.listAttr(current_control, keyable=True) for attr in ("translate", "rotate", "scale"): # checks if the attribute is a maya transform attribute if [x for x in k_attrs if attr in x and len(x) == len(attr) + 1]: icon = "{}_M.png".format(attr) if attr == "translate": icon = "move_M.png" cmds.menuItem(parent=parent_menu, label="Reset {}".format(attr), command=partial(__reset_attributes_callback, _current_selection, attr), image=icon) # divider cmds.menuItem(parent=parent_menu, divider=True) # add mirror cmds.menuItem(parent=parent_menu, label="Mirror", command=partial(__mirror_flip_pose_callback, _current_selection, False), image="redrawPaintEffects.png") cmds.menuItem(parent=parent_menu, label="Mirror all bellow", command=partial(__mirror_flip_pose_callback, child_controls, False)) # add flip cmds.menuItem(parent=parent_menu, label="Flip", command=partial(__mirror_flip_pose_callback, _current_selection, True), image="redo.png") cmds.menuItem(parent=parent_menu, label="Flip all bellow", command=partial(__mirror_flip_pose_callback, child_controls, True)) # divider cmds.menuItem(parent=parent_menu, divider=True) # rotate order if (cmds.getAttr("{}.rotateOrder".format(current_control), channelBox=True) or cmds.getAttr("{}.rotateOrder".format(current_control), keyable=True) and not cmds.getAttr("{}.rotateOrder".format(current_control), lock=True)): _current_r_order = cmds.getAttr( "{}.rotateOrder".format(current_control)) _rot_men = cmds.menuItem(parent=parent_menu, subMenu=True, tearOff=False, label="Rotate Order switch") cmds.radioMenuItemCollection(parent=_rot_men) orders = ("xyz", "yzx", "zxy", "xzy", "yxz", "zyx") for idx, order in enumerate(orders): if idx == _current_r_order: state = True else: state = False cmds.menuItem(parent=_rot_men, label=order, radioButton=state, command=partial(__change_rotate_order_callback, current_control, order)) # divider cmds.menuItem(parent=parent_menu, divider=True) # handles constrains attributes (constrain switches) for attr in cmds.listAttr(current_control, userDefined=True, keyable=True) or []: # filters switch reference attributes if (cmds.addAttr("{}.{}".format(current_control, attr), query=True, usedAsProxy=True) or not attr.endswith("ref") and not attr.endswith("Ref")): continue part, ctl = (attr.split("_")[0], attr.split("_")[-1].split("Ref")[0].split("ref")[0]) _p_switch_menu = cmds.menuItem(parent=parent_menu, subMenu=True, tearOff=False, label="Parent {} {}".format(part, ctl), image="dynamicConstraint.svg") cmds.radioMenuItemCollection(parent=_p_switch_menu) k_values = cmds.addAttr("{}.{}".format(current_control, attr), query=True, enumName=True).split(":") current_state = cmds.getAttr("{}.{}".format(current_control, attr)) for idx, k_val in enumerate(k_values): if idx == current_state: state = True else: state = False cmds.menuItem(parent=_p_switch_menu, label=k_val, radioButton=state, command=partial(__switch_parent_callback, current_control, attr, idx, k_val)) # divider cmds.menuItem(parent=parent_menu, divider=True) # select all rig controls selection_set = cmds.ls(cmds.listConnections(current_control), type="objectSet") all_rig_controls = cmds.sets(selection_set, query=True) cmds.menuItem(parent=parent_menu, label="Select all controls", command=partial(__select_nodes_callback, all_rig_controls)) # key all bellow function cmds.menuItem(parent=parent_menu, label="Keyframe child controls", command=partial(__keyframe_nodes_callback, child_controls), image="setKeyframe.png")
def deleteMainLayer(): if ( cmds.objExists( "OVERLAPPY" )): cmds.delete( mainLayerName ) else: print "\n||| Layer not created |||\n"
def optimize(nodeTypes='multiplyDivide'): _str_func = 'optimize' log.debug("|{0}| >> ".format(_str_func)+ '-'*80) _nodeTypes = VALID.listArg(nodeTypes) d_modeToNodes = {} d_modeToPlugs = {} l_oldNodes = [] for t in _nodeTypes: if t in ['plusMinusAverage']: raise ValueError,"Don't handle type: {0}".format(t) nodes = mc.ls(type=t) l_oldNodes.extend(nodes) for n in nodes: _mode = ATTR.get(n,'operation') _operator = ATTR.get_enumValueString(n,'operation') #d_operator_to_NodeType[t][_mode] if not d_modeToNodes.get(_mode): d_modeToNodes[_mode] = [] d_modeToNodes[_mode].append(n) d_plugs = {} d_plugValues = {} for i,inPlug in enumerate(d_node_to_input[t]['in']): d_plugs[i] = ATTR.get_children(n,inPlug) or [] for p in d_plugs[i]: c = ATTR.get_driver(n,p,False,skipConversionNodes=True) if c: d_plugValues[p] = c else: d_plugValues[p] = ATTR.get(n,p) l_outs = ATTR.get_children(n,d_node_to_input[t]['out']) or [] for p in l_outs: d_plugValues[p] = ATTR.get_driven(n,p,False,skipConversionNodes=True) #pprint.pprint(d_modeToNodes) #pprint.pprint(d_plugs) #print l_outs #print cgmGeneral._str_subLine #pprint.pprint(d_plugValues) for i in range(len(l_outs)): _out = d_plugValues[l_outs[i]] if _out: d_set = {'out':_out, 'in':[]} log.debug("|{0}| >> Output found on: {1} ".format(_str_func,_out)) _keys = d_plugs.keys() _keys.sort() for k in _keys: d_set['in'].append(d_plugValues[ d_plugs[k][i] ]) #d_set['in'].append(d_plugs[k][i]) #pprint.pprint(d_set) if not d_modeToPlugs.get(_mode): d_modeToPlugs[_mode] = [] d_modeToPlugs[_mode].append(d_set) # if VALID.stringArg() l_inPlugs = ['input1','input2'] l_outplugs = [u'output'] l_new = [] _cnt = 0 for operator,d_sets in d_modeToPlugs.iteritems(): if operator == 1: for nodeSet in d_sets: newNode = mc.createNode('multDoubleLinear') newNode = mc.rename(newNode,'optimize_{0}_mdNode'.format(_cnt)) _cnt+=1 l_new.append(newNode) _ins = d_set['in'] _outs = d_set['out'] for iii,inPlug in enumerate(_ins): if mc.objExists(inPlug): ATTR.connect(inPlug, "{0}.{1}".format(newNode, l_inPlugs[iii])) else: ATTR.set(newNode,l_inPlugs[iii], inPlug) for out in _outs: ATTR.connect("{0}.output".format(newNode), out) #pprint.pprint(d_setsSorted) print len(d_sets) #print len(d_setsSorted) """ l_inPlugs = {0: [u'input1X', u'input1Y', u'input1Z'], 1: [u'input2X', u'input2Y', u'input2Z']} l_outplugs = [u'outputX', u'outputY', u'outputZ'] for operator,d_sets in d_modeToPlugs.iteritems(): d_setsSorted = LISTS. get_chunks(d_sets,3) for nodeSet in d_setsSorted: newNode = mc.createNode('multiplyDivide') newNode = mc.rename(newNode,'optimize_{0}_mdNode'.format(_cnt)) _cnt+=1 l_new.append(newNode) ATTR.set(newNode,'operation',operator) for i,d_set in enumerate(nodeSet): _ins = d_set['in'] _outs = d_set['out'] for iii,inPlug in enumerate(_ins): if mc.objExists(inPlug): ATTR.connect(inPlug, "{0}.{1}".format(newNode, l_inPlugs[iii][i])) else: ATTR.set(newNode,l_inPlugs[iii][i], inPlug) for out in _outs: ATTR.connect("{0}.{1}".format(newNode, l_outplugs[i]), out) #pprint.pprint(d_setsSorted) print len(d_sets) print len(d_setsSorted) """ mc.delete(l_oldNodes) return len(l_new)
def dpDoAddHandFollow(self, *args): """ Set attributes and call setDrivenKey method. """ sideList = [ self.langDic[self.langName]['p002_left'], self.langDic[self.langName]['p003_right'] ] for side in sideList: armWristIkCtrl = side + "_" + self.langDic[ self.langName]['c037_arm'] + "_" + self.langDic[ self.langName]['c004_arm_extrem'] + "_Ik_Ctrl" if cmds.objExists(armWristIkCtrl): if cmds.objExists(armWristIkCtrl + "." + self.langDic[self.langName]['c032_follow']): return else: cmds.addAttr(armWristIkCtrl, ln=self.langDic[self.langName]['c032_follow'], at="enum", en=self.defaultName + ":" + self.globalName + ":" + self.rootName + ":" + self.hipsName + ":" + self.headName + ":") cmds.setAttr(armWristIkCtrl + "." + self.langDic[self.langName]['c032_follow'], edit=True, keyable=True) parentConst = cmds.parentConstraint( self.spineChestACtrl, self.globalCtrl, self.rootCtrl, self.spineHipsBCtrl, self.headCtrl, armWristIkCtrl + "_Orient_Grp", mo=True, name=armWristIkCtrl + "_Orient_Grp_PaC") cmds.setAttr( armWristIkCtrl + "_Orient_Grp_PaC." + self.globalCtrl + "W1", 0) cmds.setAttr( armWristIkCtrl + "_Orient_Grp_PaC." + self.rootCtrl + "W2", 0) cmds.setAttr( armWristIkCtrl + "_Orient_Grp_PaC." + self.spineHipsBCtrl + "W3", 0) cmds.setAttr( armWristIkCtrl + "_Orient_Grp_PaC." + self.headCtrl + "W4", 0) self.dpSetHandFollowSDK(armWristIkCtrl) cmds.setAttr( armWristIkCtrl + "." + self.langDic[self.langName]['c032_follow'], 1) cmds.setAttr( armWristIkCtrl + "_Orient_Grp_PaC." + self.spineChestACtrl + "W0", 0) cmds.setAttr( armWristIkCtrl + "_Orient_Grp_PaC." + self.globalCtrl + "W1", 1) self.dpSetHandFollowSDK(armWristIkCtrl) cmds.setAttr( armWristIkCtrl + "." + self.langDic[self.langName]['c032_follow'], 2) cmds.setAttr( armWristIkCtrl + "_Orient_Grp_PaC." + self.globalCtrl + "W1", 0) cmds.setAttr( armWristIkCtrl + "_Orient_Grp_PaC." + self.rootCtrl + "W2", 1) self.dpSetHandFollowSDK(armWristIkCtrl) cmds.setAttr( armWristIkCtrl + "." + self.langDic[self.langName]['c032_follow'], 3) cmds.setAttr( armWristIkCtrl + "_Orient_Grp_PaC." + self.rootCtrl + "W2", 0) cmds.setAttr( armWristIkCtrl + "_Orient_Grp_PaC." + self.spineHipsBCtrl + "W3", 1) self.dpSetHandFollowSDK(armWristIkCtrl) cmds.setAttr( armWristIkCtrl + "." + self.langDic[self.langName]['c032_follow'], 4) cmds.setAttr( armWristIkCtrl + "_Orient_Grp_PaC." + self.spineHipsBCtrl + "W3", 0) cmds.setAttr( armWristIkCtrl + "_Orient_Grp_PaC." + self.headCtrl + "W4", 1) self.dpSetHandFollowSDK(armWristIkCtrl) cmds.setAttr( armWristIkCtrl + "." + self.langDic[self.langName]['c032_follow'], 0)
def on_xfer(self, *a): mapping = api.resolveMapping(self.UI_mapping.getMapping()) theSrcs = [] theTgts = [] #perform the hierarchy sort idx = 0 if self.sortBySrcs else 1 toSort = [(len(list(api.iterParents(srcAndTgt[idx]))), srcAndTgt) for srcAndTgt in mapping.iteritems() if cmd.objExists(srcAndTgt[idx])] toSort.sort() for idx, (src, tgt) in toSort: theSrcs.append(src) theTgts.append(tgt) offset = '' isDupe = self.isTraceMode(self.RAD_dupe) isCopy = self.isTraceMode(self.RAD_copy) isTraced = self.isTraceMode(self.RAD_trace) instance = cmd.checkBox(self.UI_check1, q=True, v=True) traceKeys = cmd.checkBox(self.UI_keysOnly, q=True, v=True) matchRo = cmd.checkBox(self.UI_check2, q=True, v=True) startTime = cmd.textField(self.UI_start, q=True, tx=True) endTime = cmd.textField(self.UI_end, q=True, tx=True) world = cmd.checkBox(self.UI_check3, q=True, v=True) #this is also "process trace cmds" nocreate = cmd.checkBox(self.UI_check4, q=True, v=True) if startTime.isdigit(): startTime = int(startTime) else: if startTime == '!': startTime = cmd.playbackOptions(q=True, min=True) elif startTime == '.': startTime = cmd.currentTime(q=True) elif startTime == '$': startTime = cmd.playbackOptions(q=True, animationStartTime=True) if endTime.isdigit(): endTime = int(endTime) else: if endTime == '!': endTime = cmd.playbackOptions(q=True, max=True) elif endTime == '.': endTime = cmd.currentTime(q=True) elif endTime == '$': endTime = cmd.playbackOptions(q=True, animationEndTime=True) withinRange = cmd.checkBox(self.UI_withinRange, q=True, v=True) if withinRange: traceKeys = 2 if isCopy: offset = "*" api.mel.zooXferAnimUtils() if self._clipPreset is not None: print self._clipPreset.asClip() #convert to mapping as expected by animLib... this is messy! animLibMapping = {} for src, tgts in mapping.iteritems(): animLibMapping[src] = tgts[0] self._clipPreset.asClip().apply(animLibMapping) elif isDupe: api.melecho.zooXferBatch( "-mode 0 -instance %d -matchRo %d" % (instance, matchRo), theSrcs, theTgts) elif isCopy: api.melecho.zooXferBatch( "-mode 1 -range %s %s -matchRo %d" + (startTime, endTime, matchRo), theSrcs, theTgts) elif isTraced: api.melecho.zooXferBatch( "-mode 2 -keys %d -postCmds %d -matchRo %d -sortByHeirarchy 0 -range %s %s" % (traceKeys, world, matchRo, startTime, endTime), theSrcs, theTgts)
def __switch_parent_callback(*args): """ Wrapper function to call mGears change space function Args: list: callback from menuItem """ # creates a map for non logical components controls control_map = {"elbow": "mid", "rot": "orbit", "knee": "mid"} # switch_control = args[0].split("|")[-1].split(":")[-1] switch_control = args[0].split("|")[-1] switch_attr = args[1] switch_idx = args[2] search_token = switch_attr.split("_")[-1].split("ref")[0].split("Ref")[0] target_control = None controls_attr = "{}_{}_{}".format( switch_attr.split("_")[0], switch_control.split(":")[-1].split("_")[1], switch_control.split(":")[-1].split("_")[2]) _controls = cmds.getAttr("{}.{}".format(args[0], controls_attr)) # search for target control for ctl in _controls.split(","): if len(ctl) == 0: continue if ctl.split("_")[2] == search_token: target_control = ctl break elif (search_token in control_map.keys() and ctl.split("_")[2] == control_map[search_token]): target_control = ctl break # gets root node for the given control namespace_value = args[0].split("|")[-1].split(":") if len(namespace_value) > 1: namespace_value = namespace_value[0] else: namespace_value = "" root = None current_parent = cmds.listRelatives(args[0], fullPath=True, parent=True) if current_parent: current_parent = current_parent[0] while not root: if cmds.objExists("{}.is_rig".format(current_parent)): root = cmds.ls("{}.is_rig".format(current_parent))[0] else: try: current_parent = cmds.listRelatives(current_parent, fullPath=True, parent=True)[0] except TypeError: break if not root or not target_control: return autokey = cmds.listConnections("{}.{}".format(switch_control, switch_attr), type="animCurve") if autokey: cmds.setKeyframe("{}:{}".format(namespace_value, target_control), "{}.{}".format(switch_control, switch_attr), time=(cmds.currentTime(query=True) - 1.0)) # triggers switch changeSpace(root, switch_control, switch_attr, switch_idx, target_control) if autokey: cmds.setKeyframe("{}:{}".format(namespace_value, target_control), "{}.{}".format(switch_control, switch_attr), time=(cmds.currentTime(query=True)))