def checkMaxSkinInfluences(self, node, maxInf, debug=1, select=0): '''Takes node name string and max influences int. From CG talk thread (MEL converted to Python, then added some things)''' cmds.select(cl=1) skinClust = self.findRelatedSkinCluster(node) if skinClust == "": cmds.error("checkSkinInfluences: can't find skinCluster connected to '" + node + "'.\n"); verts = cmds.polyEvaluate(node, v=1) returnVerts = [] for i in range(0,int(verts)): inf= cmds.skinPercent(skinClust, (node + ".vtx[" + str(i) + "]"), q=1, v=1) activeInf = [] for j in range(0,len(inf)): if inf[j] > 0.0: activeInf.append(inf[j]) if len(activeInf) > maxInf: returnVerts.append(i) if select: for vert in returnVerts: cmds.select((node + '.vtx[' + str(vert) + ']'), add=1) if debug: print 'checkMaxSkinInfluences>>> Total Verts:', verts print 'checkMaxSkinInfluences>>> Vertices Over Threshold:', len(returnVerts) print 'checkMaxSkinInfluences>>> Indices:', str(returnVerts) return returnVerts
def __init__(self, srcMesh, influences ): srcMeshSkinCluters = sgCmds.getNodeFromHistory( srcMesh, 'skinCluster' ) if not srcMeshSkinCluters: cmds.error( "%s has no skincluster" % srcMesh ); return fnSkinCluster = OpenMaya.MFnDependencyNode( sgCmds.getMObject( srcMeshSkinCluters[0] ) ) self.influenceIndices = [] for origPlug, influencePlug in pymel.core.listConnections( fnSkinCluster.name() + '.matrix', s=1, d=0, p=1, c=1 ): influenceName = influencePlug.node().name() if not influenceName in influences: continue self.influenceIndices.append( origPlug.index() ) self.weightListPlug = fnSkinCluster.findPlug( 'weightList' ) self.vtxIndex = 0 self.weightsPlug = self.weightListPlug.elementByLogicalIndex( self.vtxIndex ).child(0) self.influenceWeights = {} for i in range( self.weightsPlug.numElements() ): weightPlug = self.weightsPlug.elementByPhysicalIndex( i ) logicalIndex = weightPlug.logicalIndex() self.influenceWeights[ logicalIndex ] = weightPlug.asFloat()
def fxCombine(merge=False): targets = m.ls(sl=True, l=True) if not targets: return parent = m.listRelatives(targets[0], p=True, pa=True) try: combineResult = m.polyUnite(targets) except RuntimeError: m.error('Invalid selection for combine operation.') return if parent: combineResult = m.parent(combineResult[0], parent[0]) m.delete(combineResult[0], ch=True) for t in targets: if m.objExists(t): m.delete(t) finalObject = m.rename(combineResult[0], getShortName(targets[0])) m.select(finalObject) if merge: meval('performPolyMerge 0') m.polyOptions(finalObject, displayBorder=True, sizeBorder=4) m.select(finalObject)
def getGrowIndices(self): util = OpenMaya.MScriptUtil() util.createFromInt( 1 ) prevIndex = util.asIntPtr() if not self.checkedIndices: cmds.error( "checked indices is not exists" ); return [] targetVtxIndices = [] for i in range( len( self.checkedIndices ) ): checkedIndex = self.checkedIndices[i] intArrFaces = OpenMaya.MIntArray() self.itMeshVertex.setIndex( checkedIndex, prevIndex ) self.itMeshVertex.getConnectedFaces( intArrFaces ) for j in range( intArrFaces.length() ): faceIndex = intArrFaces[j] intArrVertices = OpenMaya.MIntArray() self.itMeshPolygon.setIndex( faceIndex, prevIndex ) self.itMeshPolygon.getVertices( intArrVertices ) for k in range( intArrVertices.length() ): vtxIndex = intArrVertices[k] if vtxIndex in self.checkedIndices: continue targetVtxIndices.append( vtxIndex ) self.checkedIndices.append( vtxIndex ) return targetVtxIndices
def fileSVNstatus(self, status): # the status of the current file is assigned here and the following branching code handles the results status = self.SVN('status') if not runSVN: cmds.warning( 'SVN integration is currently disabled' ) if runSVN: print 'SVN status is : -> ' + status if type(status) != str: return cmds.warning( 'scene has not been modified' ) if status == 'A': # the file is added to svn but not modified, no need to commit return cmds.warning( 'there are no changes to this scene file.' ) if status == 'C': # the file is added to svn but not modified, no need to commit return cmds.error( 'This file is conflicted!' ) if status == 'M': # this section shold commit the file to SVN, after status return M for modified. if runSVN: SVN('commit ') return cmds.warning( 'modified file has been committed' ) if status == '?': # if the status returns ?, which means the file is not added to SVN, then add the file. if runSVN: SVN('add ') return cmds.warning( 'scene has added to SVN and checked in.' ) else: if runSVN: return cmds.error( 'Unhandled status ' + status )
def cmdRename( *args ): renameTarget = FolderSubRenameUiInfo._renameTarget path = cmds.textField( FolderUIInfo._fieldUI, q=1, tx=1 ) srcPath = path + '/' + renameTarget if not os.path.exists( path + '/' + renameTarget ): cmds.error( '%s is not Exists' % srcPath ) extension = renameTarget.split( '.' )[1] fieldName = cmds.textField( FolderSubRenameUiInfo._renameTextField, q=1, tx=1 ) if not fieldName: return None destPath = path + '/' if os.path.exists( path + '/' + fieldName+'.'+extension): addNum = 0 while os.path.exists( path + '/' + fieldName+str(addNum)+'.'+extension ): addNum += 1 destPath += fieldName+str(addNum)+'.'+extension else: destPath += fieldName+'.'+extension os.rename( srcPath, destPath ) cmds.deleteUI( FolderSubRenameUiInfo._winName, wnd=1 ) cmds.textScrollList( FolderUIInfo._scrollListUI, e=1, ri=renameTarget ) cmds.textScrollList( FolderUIInfo._scrollListUI, e=1, a=fieldName+'.'+extension )
def mtt_log(msg, add_tag=None, msg_type=None, verbose=True): """ Format output message '[TAG][add_tag] Message content' :param msg: (string) message content :param add_tag: (string or list) add extra tag to output :param msg_type: define message type. Accept : None, 'warning', 'error' :param verbose: (bool) enable headsUpMessage output """ # define tags tag_str = '[MTT]' # append custom tags if add_tag: if not isinstance(add_tag, list): add_tag = [add_tag] for tag in add_tag: tag_str += '[%s]' % tag.upper() # output message the right way if msg_type == 'warning': cmds.warning('%s %s' % (tag_str, msg)) elif msg_type == 'error': cmds.error('%s %s' % (tag_str, msg)) else: print '%s %s\n' % (tag_str, msg), if verbose and MTTSettings.value('showHeadsUp'): cmds.headsUpMessage(msg)
def doIt(self, argList): # get only the first object from argument list try: obj = misc.getArgObj(self.syntax(), argList)[0] except: cmds.warning("No object selected!") return if (cmds.objectType(obj) != 'transform'): cmds.error("Object is not of type transform!") return # get and cast array of MPoint-Objects to list structure (needed for ConvexHull) pSet = list([p.x, p.y, p.z] for p in misc.getPoints(obj)) # execute delaunay triangulation algorithm on point set of current object hull = Delaunay(pSet) # delaunay-triangulated tetrahedra are not ordered --> make sure implicit normal points outwards of each tetrahedra for tetra in hull.points[hull.simplices]: center = map(operator.add, map(operator.add, tetra[0], tetra[1]), map(operator.add, tetra[2], tetra[3])) center = map(operator.div, center, [4.0]*3) # check if tetrahedron is oriented in wrong direction (normals should point away from center) v1 = map(operator.sub, tetra[0], tetra[1]) v2 = map(operator.sub, tetra[0], tetra[2]) # check dot product: if smaller 0, swap vertices 0 and 2 if (np.dot(np.cross(v1, v2), map(operator.sub, tetra[0], center) ) > 0): # swap 0 and 2 tetra[[0,2]] = tetra[[2,0]] self.appendToResult(str(tetra.flatten().tolist())[1:-1])
def genConnectors(): connector = getConnectorForType(cmds.optionMenu(componentsMenu, q=True, v=True)) rotation = [] scale = [] print connector if connector != None: locator = cmds.ls(transforms=True, selection=True) connector["out"] = [] for i in range(0, len(locator)): trans = cmds.xform(locator[i], q=1, ws=1, rp=1) rot = cmds.xform(locator[i], q=1, ws=1, ro=1) scal = cmds.xform(locator[i], q=1, ws=1, s=1) obj = { "position": trans, "rotation": rot, "scale": scal } connector["out"].append(obj) print "made it" updateJson() else : cmds.error("Connector Type is invalid")
def measureDistance(mName="none", *args): """first the name of the measure node, then the 2 objects ORRRR select the two objects and run (will give name 'distanceBetween'""" objs = [] if mName == "none": mName = "distanceBetween" objs = getTwoSelection() else: for each in args: objs.append(each) #add check for 2 selectiont if len(objs) != 2: cmds.error("you must enter either a measure name and 2 objects OR no arguments and manually select 2 objs") dist = cmds.shadingNode("distanceBetween", asUtility=True, name=mName) objA = objs[0] objB = objs[1] objAMatrix = objA + ".worldMatrix" objBMatrix = objB + ".worldMatrix" objAPoint = objA + ".rotatePivot" objBPoint = objB + ".rotatePivot" distPoint1 = dist + ".point1" distPoint2 = dist + ".point2" distMatrix1 = dist + ".inMatrix1" distMatrix2 = dist + ".inMatrix2" cmds.connectAttr(objAPoint, distPoint1) cmds.connectAttr(objBPoint, distPoint2) cmds.connectAttr(objAMatrix, distMatrix1) cmds.connectAttr(objBMatrix, distMatrix2) cmds.select(clear=True) return(dist)
def blendScale(blend="none", sourceA="none", sourceB="none", target="none", sourceValue="none"): """name is first arg, then three objects. Blends translation from first two selected into third selected. SourceValue (last input) is for the driving obj.attr. First source is active at '1', second at '2'""" #add input and *args if blend == "none": blend = "blendColors" if sourceA == "none": sel = getSelection() if len(sel) != 3: cmds.error("Error: blendRotation, select three transforms") #inert some kind of break here sourceA = sel[0] sourceB = sel[1] target = sel[2] blend = cmds.shadingNode("blendColors", asUtility=True, name=blend) sourceAOut = sourceA + ".scale" sourceBOut = sourceB + ".scale" targetIn = target + ".scale" blend1 = blend + ".color1" blend2 = blend + ".color2" blendOut = blend + ".output" cmds.connectAttr(sourceAOut, blend1) cmds.connectAttr(sourceBOut, blend2) cmds.connectAttr(blendOut, targetIn) if not sourceValue == "none": cmds.connectAttr(sourceValue, "%s.blender"%blend) return(blend)
def export(anim_curve): """Creates a dictionary of all the data necessary to rebuild the curve.""" # Check the curve exists and is an animation curve. if not cmds.objExists(anim_curve): cmds.error("Failed to find anim curve {0}".format(anim_curve)) type = cmds.nodeType(anim_curve) if not is_type_exportable(type): cmds.error("Node {0} is not an anim curve".format(anim_curve)) # Get the keys on the curve. keys = cmds.keyframe(anim_curve, query=True) key_count = cmds.keyframe(anim_curve, keyframeCount=True, query=True) # Gather the value and in/out tangent type, and x,y coordinates of # each key. data = {'name':anim_curve,'type':type} data['key_data'] = [key_info_by_index(anim_curve, i) for i in range(key_count)] # Get infinity values data['pre'] = cmds.getAttr("{0}.preInfinity".format(anim_curve)) data['post'] = cmds.getAttr("{0}.postInfinity".format(anim_curve)) # Get curve colour values data['useColor'] = cmds.getAttr("{0}.useCurveColor".format( anim_curve)) data['color'] = cmds.getAttr("{0}.curveColor".format(anim_curve))[0] return data
def jointFromList(xformList=[], orient="xyz", secAxis="zup", strip="", suffix="", *args): """ uses the xformlist arg (a list of transforms in scene) to create a joint chain in order. Arguments: xformList (a list), orient ("xyz", etc), secAxis ("xup", "zdown", etc), strip (string to strip off), suffix (string to add to the joints) """ jointList = [] #if no list is provided, get the list from selection order if not xformList: sel = getSelection() if sel: xformList = sel #if no list && no selection then throw error else: cmds.error("you must provide a list of transforms or have the transforms selected in order") #clear selection cmds.select(cl=True) #for each thing in the list create a joint at that location (they'll be parented to the previous) for xform in xformList: xformPos = cmds.xform(xform, q=True, ws=True, t=True) jointName = "%s%s"%(xform.rstrip(strip), suffix) thisJoint = cmds.joint(n=jointName, p=xformPos) jointList.append(thisJoint) #now orient the joint chain based on args and return a list of the joints cmds.joint(jointList[0], e=True, ch=True, oj=orient, sao=secAxis) return(jointList)
def setPupilSize(*args): print args if len(gEyeballCtrler) == 0: cmds.error('Please set current eyeball controler.') else: gPupilValue = args[0] cmds.setAttr(gEyeballCtrler + '.pupilSize', gPupilValue)
def exportSgKeyData( targetTransformNodes, startFrame, endFrame, step, folderPath=None, exportByMatrix=False, *args ): import sgBFunction_scene import copy if step < 0.05: cmds.error( "Step Must be larger then %.f." % step ) sgBFunction_base.autoLoadPlugin( "sgBDataCmd" ) if not folderPath: folderPath = sgBFunction_fileAndPath.getDefaultSgKeyDataPath() sgBFunction_fileAndPath.makeFolder( folderPath ) sgBFunction_fileAndPath.removeChildFiles( folderPath ) targetTransformNodeParents = [] for transformNode in targetTransformNodes: targetTransformNodeParents += sgBFunction_dag.getParents( transformNode ) targetTransformNodeParents.append( transformNode ) targetTransformNodeParents = list( set( targetTransformNodeParents ) ) sgBFunction_scene.exportTransformData( targetTransformNodeParents, folderPath ) cmds.sgBDataCmd_key( targetTransformNodes, se=1, folderPath= folderPath, ebm=exportByMatrix ) cuTime = copy.copy( startFrame ) while cuTime <= endFrame+1: cmds.currentTime( cuTime ) cmds.sgBDataCmd_key( write=1 ) cuTime += step cmds.sgBDataCmd_key( ee=1 )
def saveRig(self): """ Will save current rig if built in file """ # Check all modules are in rig mode modules = self.Modules.keys() for module in modules: if self.Modules[module].rigMode() != 1: cmds.error("Cannot save rig as not all modules are in rig mode") # If file exists prompt warning defaultFilePath = ( self.UI.getFilePath() + "rigFile/" + self.name ) deatultFolderPath = ( self.UI.getFilePath() + "rigFile/" ) # If folder doesn't exist create if os.path.exists( deatultFolderPath ) == False : os.makedirs( deatultFolderPath ) cmds.file( rename= defaultFilePath ) if os.path.exists( (defaultFilePath + ".ma") ): # prompt and save / exit self.UI.createPromptWindow("Overwrite old save?",("cmds.file( save = True, type='mayaAscii' )\nprint ( \"NWRig saved to: " + defaultFilePath+ ".ma\")") ) else: # Save file cmds.file( save = True, type='mayaAscii' ) print ( "Rig saved to: " + defaultFilePath + ".ma")
def setIrisConcave(*args): print args if len(gEyeballCtrler) == 0: cmds.error('Please set current eyeball controler.') else: gIrisConcaveValue = args[0] cmds.setAttr(gEyeballCtrler + '.irisConcave', gIrisConcaveValue)
def setCorneaBulge(*args): print args if len(gEyeballCtrler) == 0: cmds.error('Please set current eyeball controler.') else: gCorneaBulgeValue = args[0] cmds.setAttr(gEyeballCtrler + '.corneaBulge', gCorneaBulgeValue)
def getChild(self, index ): if index > self.mFnDagNode.childCount()-1: cmds.error( "%d Child not Exists" % index ) return None return Dag( self.mFnDagNode.child( index ) )
def bt_moveObjToCamera(): #Check for hotkey and make if possible bt_checkCtrFHotkey() activePanel = cmds.getPanel(wf=1) if "model" in activePanel: activeCamera = cmds.modelEditor(activePanel,q=1,camera=1) else: cmds.error ('No active panel/camera to frame to') selected = cmds.ls(sl=1) locator = cmds.spaceLocator() cmds.select(activeCamera,add=1) cmds.parent(r=1) cmds.move(0,0,-5,locator,r=1,os=1) location = cmds.xform(q=1,t=1,ws=1) for object in selected: cmds.move(location[0],location[1],location[2],object,ws=1,a=1) #cmds.move(location[0],location[1],location[2],'pCube1',ws=1,a=1) cmds.delete(locator) cmds.select(selected,r=1)
def locatorOnly(self): sel = cmds.ls(sl=True) # Gives error if more than one object is selected. if len(sel) > 1: cmds.error("Too many objects selected!") # Creates and snaps a locator to object. elif len(sel): tObj = sel[0] tLoc = "{0}_tLoc".format(tObj) LScale = cmds.floatField(LocScale, q=True, v=True) if cmds.objExists(tLoc): cmds.delete(tLoc) cmds.spaceLocator(n="{0}_tLoc".format(tObj)) cmds.scale(LScale, LScale, LScale) cmds.parentConstraint(tObj, tLoc, mo=False) cmds.parentConstraint(tObj, tLoc, rm=True) print LScale # Gives error if no objects are selected. else: cmds.error("No objects selected!")
def cameraFrustum_build(cam_shape): #make sure a camera is loaded if cam_shape==0: cmds.error('no camera loaded...select a camera and load') else: #create frustum only if one doesnt already exist selCamXform = cmds.listRelatives(cam_shape[0], p=1) prefix = 'frust_' frustumGrpName = prefix + 'camera_frustum_all_grp' if cmds.objExists(frustumGrpName)==0: #create main grp frustumMainGrp = cmds.group(em=1, n=frustumGrpName); cmds.setAttr(frustumGrpName + '.tx', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.ty', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.tz', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.rx', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.ry', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.rz', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.sx', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.sy', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.sz', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.v', lock=1, keyable=0, channelBox=0) #create frustum geo frustumGeo = cmds.polyCube(w=2, h=2, d=2, n=prefix + 'camera_frustum_geo') cmds.delete(frustumGeo[0], constructionHistory=True) cmds.parent(frustumGeo[0], frustumMainGrp) #load plugin "nearestPointOnMesh.mll" if needed and connect plugin = cmds.pluginInfo('nearestPointOnMesh.mll', q=1, l=1) if plugin==0: cmds.loadPlugin('nearestPointOnMesh.mll') nearNodeName = prefix + 'npomNode' npomNode = cmds.createNode('nearestPointOnMesh', n=nearNodeName) cmds.connectAttr(frustumGeo[0] + '.worldMesh', npomNode + '.inMesh') #create clusters cmds.select(frustumGeo[0] + '.vtx[4:7]', r=1) nearCluster = cmds.cluster(n=prefix + 'camera_nearFrustum_cluster') cmds.select(frustumGeo[0] + '.vtx[0:3]', r=1) farCluster = cmds.cluster(n=prefix + 'camera_farFrustum_cluster') #create near/far/camera locs cameraLoc = cmds.spaceLocator(p=(0, 0, 0), n=prefix + 'camera_loc') cmds.parent(cameraLoc[0], frustumMainGrp) nearLoc = cmds.spaceLocator(p=(0, 0, 0), n=prefix + 'camera_nearFrustum_loc') cmds.move(0, 0, -1) farLoc = cmds.spaceLocator(p=(0, 0, 0), n=prefix + 'camera_farFrustum_loc') cmds.move(0, 0, 1) #parent clusters under loc -- parent locs under camera loc cmds.parent(nearCluster[1], nearLoc[0]) cmds.parent(farCluster[1], farLoc[0]) cmds.parent(nearLoc[0], cameraLoc[0]) cmds.parent(farLoc[0], cameraLoc[0]) #constrain camera loc to camera cmds.parentConstraint(selCamXform, cameraLoc, weight=1) return frustumGeo[0]
def loadPlugin(): """ load softSelectionQuery plugin """ mayaVers = int(mayaVersion()) os = cmds.about(os=1) if os == 'win64': pluginName = 'softSelectionQuery_%s-x64.mll' % mayaVers elif os == 'mac': pluginName = 'softSelectionQuery_%s.bundle' % mayaVers elif os == 'linux64': pluginName = 'softSelectionQuery_%s.so' % mayaVers else: cmds.error('Soft Cluster EX is available for 64bit version of Autodesk Maya 2011 ' 'or above under Windows 64bit, Mac OS X and Linux 64bit!') if not cmds.pluginInfo(pluginName, q=True, l=True ): cmds.loadPlugin(pluginName) version = cmds.pluginInfo(pluginName, q=1, v=1) log.info('Plug-in: %s v%s loaded success!' % (pluginName, version)) else: version = cmds.pluginInfo(pluginName, q=1, v=1) log.info('Plug-in: %s v%s has been loaded!' % (pluginName, version))
def sendall(self, filePath= None, longMsg= None, postFunc= None, *args, **kwargs): """ Send file as string split by half of buffer size due to encoding besause @postFunc is using [funcSend] to send a function after package, it's execute result will override the result of the func in package. """ # a global var as buffer: mTeleport_buffer msg = "global mTeleport_buffer; mTeleport_buffer= ''" self.cmdSend(msg, True) # image to string if filePath is not None: package = open(filePath, 'r') else: package = StringIO(longMsg) # sending try: success = False fixBuff = max(4, self.buff / 2) msg = "global mTeleport_buffer\n" \ + "mTeleport_buffer += '%s'.decode('base64')\n" while True: pString= package.read(fixBuff) if not pString: break # encode segment pak = msg % base64.b64encode(pString) self.cmdSend(pak, True) success = True except: cmds.error('Failed to send all.') package.close() # post function if postFunc and success: result = self.funcSend(postFunc, *args, **kwargs) return result return None
def doIt(self, argList): # get only the first object from argument list try: obj = misc.getArgObj(self.syntax(), argList)[0] except: cmds.warning("No object selected!") return if (cmds.objectType(obj) != 'transform'): cmds.error("Object is not of type transform!") return # get and cast array of MPoint-Objects to list structure (needed for ConvexHull) pSet = list([p.x, p.y, p.z] for p in misc.getPoints(obj)) # execute convex hull algorithm on point set of current object hull = ConvexHull(pSet) # get empty mesh object mesh = om2.MFnMesh() # add each polygon (triangle) in incremental process to mesh center = cmds.centerPoint(obj) for i,tri in enumerate(hull.points[hull.simplices]): # triangle vertices are not ordered --> make sure all normals point away from object's center v1 = map(operator.sub, tri[0], tri[1]) v2 = map(operator.sub, tri[0], tri[2]) # cross product of v1 and v2 is the current face normal; if dot product with vector from origin is > 0 use vertex order 0,1,2 and if dot product < 0 reverse order (all triangles are defined clockwise when looking in normal direction -- counter-clockwise when looking onto front of face) if (np.dot(np.cross(v1, v2), map(operator.sub, tri[0], center) ) > 0 ): mesh.addPolygon( ( om2.MPoint(tri[0]), om2.MPoint(tri[1]), om2.MPoint(tri[2]) ) ) else: mesh.addPolygon( ( om2.MPoint(tri[0]), om2.MPoint(tri[2]), om2.MPoint(tri[1]) ) ) # get transform node of shapeNode and rename it to match object's name transformNode = cmds.listRelatives(mesh.name(), p = 1) transformNode = cmds.rename(transformNode, obj + "_ch") self.setResult(transformNode)
def exportObj(): try: fileName = cmds.textField(objNameInput, q=True, tx=True).split(".")[0] + ".obj" cmds.file(os.path.split(furnitureFilePath)[0] + "/meshes/furniture/" + fileName, pr=1, typ="OBJexport", es=1, op="groups=0; ptgroups=0; materials=0; smoothing=0; normals=1") logging.info("Obj Save Success") except: cmds.error("Could not save OBJ - Make sure the plugin is loaded")
def onetwo(self) : sel = m.ls(sl=True) if sel is None or len(sel) != 2 : m.error("Select two items") self.doAssign( sel[0], sel[1] )
def doIt(self, argList): # get only the first object from argument list try: obj = misc.getArgObj(self.syntax(), argList)[0] except: cmds.warning("No object selected!") return if (cmds.objectType(obj) != 'transform'): cmds.error("Object is not of type transform!") return # parse arguments and get flags argData = om.MArgParser (self.syntax(), argList) axisOrder = argData.flagArgumentString('axisOrder', 0) if (argData.isFlagSet('axisOrder')) else 'yzx' fast = argData.flagArgumentBool('fast', 0) if (argData.isFlagSet('fast')) else False # get eigenvectors as matrix (column-wise), reshape matrix and append extra row/column eig = np.matrix(cmds.eigenvector(obj, ao = axisOrder, f = fast)) eig.shape = (3,3) eig = np.append(eig, [[0,0,0]], axis = 0) eig = np.append(eig.transpose(), [[0,0,0,1]], axis = 0).transpose() # return 4x4 matrix as 16 float values util = om.MScriptUtil() util.createFromList(eig.getA1().tolist(), eig.size) self.setResult(om.MDoubleArray(util.asDoublePtr(), eig.size))
def prexText(self, *args): try: selControl = mc.ls(sl=True)[0] preName = selControl.rpartition('_root_')[0] return preName except: mc.error(u'请选择角色控制器')
def createLocators(self): #create list of loc names (self.name) for i in range(len(self.jointList)): self.locList.append("%s_%s_Loc"%(self.jointList[i],self.limbName)) #check that these don't exist already if (cmds.objExists(self.locList[0])): cmds.error("these limb locators exists already!") else: #fill dictionary - assign values from list self.locPos = {} for j in range(len(self.locList)): self.locPos[self.locList[j]] = self.locPosValues[j] #create the locs for key in self.locPos.keys(): thisLoc = cmds.spaceLocator(n=key) cmds.move(self.locPos[key][0], self.locPos[key][1], self.locPos[key][2], thisLoc) #parent them together (from list of loc names) for k in range((len(self.locList)-1),0,-1): cmds.parent(self.locList[k], self.locList[k-1]) ######### make this true only for the arms. . . or figure out how to extract which rot this should be #rotate second joint to just get a preferred angle cmds.setAttr("%s.ry"%self.locList[1], -5)
def getMayaWindow(): ptr = openMayaUI.MQtUtil.mainWindow() if ptr is not None: return shiboken.wrapInstance(long(ptr), QtGui.QWidget) uiFile = None try: selfDirectory = os.path.dirname(__file__) uiFile = selfDirectory + '/drivenKeyVisualizer.ui' except: uiFile = '/Users/ozan/WebstormProjects/ozanserim/maya/python/drivenKeyVisualizer/drivenKeyVisualizer.ui' if os.path.isfile(uiFile): form_class, base_class = loadUiType(uiFile) else: cmds.error('Cannot find UI file: ' + uiFile) ######################################################################## ## SDK WRANGLER ######################################################################## class drivenKeyVisualizer(base_class, form_class): def __init__(self, parent=getMayaWindow()): self.closeExistingWindow() super(drivenKeyVisualizer, self).__init__(parent) self.setupUi(self) wName = openMayaUI.MQtUtil.fullName( long(shiboken.getCppPointer(self)[0]))
def system(): sel = cmds.ls(sl=1) loc = '' if cmds.nodeType(cmds.listRelatives(sel[0], s=1)[0]) == 'locator': loc = sel[0] else: cmds.error() cmds.setAttr(loc + ".visibility", 0) decMatA = cmds.createNode('decomposeMatrix') cmds.connectAttr(loc + '.worldMatrix[0]', decMatA + '.inputMatrix', f=1) cPOM = cmds.createNode('closestPointOnMesh', n='_cPOM') cmds.connectAttr(decMatA + '.outputTranslate', cPOM + '.inPosition', f=1) vecProx = cmds.createNode('vectorProduct', n='vecProA1') cmds.setAttr(vecProx + ".operation", 2) cmds.setAttr(vecProx + ".normalizeOutput", 1) vecProz = cmds.createNode('vectorProduct', n='vecProA2') cmds.setAttr(vecProz + ".input1X", 1) cmds.setAttr(vecProz + ".operation", 2) cmds.setAttr(vecProz + ".normalizeOutput", 1) cmds.connectAttr(cPOM + '.normal', vecProx + '.input1', f=1) cmds.connectAttr(cPOM + '.normal', vecProz + '.input2', f=1) cmds.connectAttr(vecProz + '.output', vecProx + '.input2', f=1) MatrixOnMesh = cmds.createNode('fourByFourMatrix') cmds.connectAttr(vecProx + '.outputX', MatrixOnMesh + '.in00', f=1) cmds.connectAttr(vecProx + '.outputY', MatrixOnMesh + '.in01', f=1) cmds.connectAttr(vecProx + '.outputZ', MatrixOnMesh + '.in02', f=1) cmds.connectAttr(cPOM + '.normalX', MatrixOnMesh + '.in10', f=1) cmds.connectAttr(cPOM + '.normalY', MatrixOnMesh + '.in11', f=1) cmds.connectAttr(cPOM + '.normalZ', MatrixOnMesh + '.in12', f=1) cmds.connectAttr(vecProz + '.outputX', MatrixOnMesh + '.in20', f=1) cmds.connectAttr(vecProz + '.outputY', MatrixOnMesh + '.in21', f=1) cmds.connectAttr(vecProz + '.outputZ', MatrixOnMesh + '.in22', f=1) cmds.connectAttr(cPOM + '.positionX', MatrixOnMesh + '.in30', f=1) cmds.connectAttr(cPOM + '.positionY', MatrixOnMesh + '.in31', f=1) cmds.connectAttr(cPOM + '.positionZ', MatrixOnMesh + '.in32', f=1) mMatrixA = cmds.createNode('multMatrix') cmds.connectAttr(MatrixOnMesh + '.output', mMatrixA + '.matrixIn[0]', f=1) cmds.connectAttr(loc + '.worldInverseMatrix[0]', mMatrixA + '.matrixIn[1]', f=1) decMatB = cmds.createNode('decomposeMatrix') cmds.connectAttr(mMatrixA + '.matrixSum', decMatB + '.inputMatrix', f=1) condition = cmds.createNode('condition') cmds.setAttr(condition + ".operation", 2) cmds.setAttr(condition + ".colorIfTrueR", 1) cmds.setAttr(condition + ".colorIfFalseR", 0) cmds.connectAttr(decMatB + '.outputTranslateY', condition + '.firstTerm', f=1) mMatrixB = cmds.createNode('multMatrix') cmds.connectAttr(mMatrixA + '.matrixSum', mMatrixB + '.matrixIn[0]', f=1) cmds.spaceLocator(n=loc + '_ctrl') locws = cmds.xform(loc, q=1, ws=1, t=1) cmds.setAttr(loc + '_ctrl.tx', locws[0]) cmds.setAttr(loc + '_ctrl.ty', locws[1]) cmds.setAttr(loc + '_ctrl.tz', locws[2]) cmds.parent(loc, loc + '_ctrl') cmds.connectAttr(loc + '_ctrl.worldMatrix[0]', mMatrixB + '.matrixIn[1]', f=1) decMatC = cmds.createNode('decomposeMatrix') cmds.connectAttr(mMatrixB + '.matrixSum', decMatC + '.inputMatrix', f=1) decMatD = cmds.createNode('decomposeMatrix') cmds.connectAttr(loc + '_ctrl.worldMatrix[0]', decMatD + '.inputMatrix', f=1) pairBlend = cmds.createNode('pairBlend') cmds.connectAttr(condition + '.outColorR', pairBlend + '.weight', f=1) cmds.connectAttr(decMatC + '.outputRotate', pairBlend + '.inRotate2', f=1) cmds.connectAttr(decMatC + '.outputTranslate', pairBlend + '.inTranslate2', f=1) cmds.connectAttr(decMatD + '.outputRotate', pairBlend + '.inRotate1', f=1) cmds.connectAttr(decMatD + '.outputTranslate', pairBlend + '.inTranslate1', f=1) cmds.select(cl=1) joint = cmds.joint(n='locskin') cmds.connectAttr(pairBlend + '.outRotate', joint + '.rotate', f=1) cmds.connectAttr(pairBlend + '.outTranslate', joint + '.translate', f=1) '''
def slicePieces(visualize_field, *args): if (len(cmds.ls(sl=True)) == 0): cmds.error("You must have an object selected.") else: object = cmds.ls(sl=True)[0] print "Object: " + object num_verts = cmds.polyEvaluate(object, vertex=True) object_pos = cmds.xform(object, query=True, worldSpace=True, translation=True) object_scale = cmds.xform(object, query=True, relative=True, scale=True) visualize_flag = cmds.checkBox(visualize_field, query=True, value=True) object_latest = cmds.ls(sl=True)[0] object_pos = cmds.xform(object_latest, query=True, worldSpace=True, translation=True) object_scale = cmds.xform(object_latest, query=True, relative=True, scale=True) bbox = cmds.exactWorldBoundingBox(object_latest) min_sc_rad = int( min(bbox[3] - bbox[0], bbox[4] - bbox[1], bbox[5] - bbox[2]) / 2) # minimum scale radius num_edges = cmds.polyEvaluate(object_latest, edge=True) # get random slice plane position and rotation slice_plane_pos = [ object_pos[0] + random.randint(0, min_sc_rad), object_pos[1] + random.randint(0, min_sc_rad), object_pos[2] + random.randint(0, min_sc_rad) ] plane_rotx = random.randint(0, 90) plane_roty = random.randint(0, 90) plane_rotz = random.randint(0, 90) print "Cut plane rotations: " + str(plane_rotx), str(plane_roty), str( plane_rotz) if visualize_flag: # ---- DEBUGGING: DRAW CUT PLANE ---- # cmds.polyPlane(n='plane_visual', w=20, h=20) cmds.xform('plane_visual', worldSpace=True, translation=slice_plane_pos, rotation=(90 + plane_rotx, plane_roty, plane_rotz)) # ----------------------------------- # # slice the mesh cmds.polyCut(object_latest, extractFaces=1, pc=slice_plane_pos, constructionHistory=1, rx=plane_rotx, ry=plane_roty, rz=plane_rotz) new_num_edges = cmds.polyEvaluate(object_latest, edge=True) # fill the openings of the resulting pieces and separate the mesh cmds.select(object_latest + '.e[' + str(num_edges) + ':' + str(new_num_edges) + ']') cmds.polyCloseBorder() cmds.polySeparate(object_latest) pieces = cmds.ls(selection=True) cmds.xform(pieces[0], centerPivots=1) for i in xrange(1, len(pieces)): # center pivot for each piece cmds.xform(pieces[i], centerPivots=1) piece_pos = cmds.xform(pieces[i], query=True, translation=True, worldSpace=True)
def createFacialSkinProxyJoints(cageMesh, facialMesh, proxyJntMaximumInfluences=4): if not cmds.objExists(cageMesh) or not cmds.objExists(facialMesh): cmds.error('Cage mesh or facial mesh does not exist.') return rigCharacterGroup = SERigObjectTypeHelper.findRelatedRigCharacterGroup( facialMesh) if rigCharacterGroup == None: cmds.error('Facial mesh does not belong to a character rig.') return facialRootJoint = getSlaveFacialRootJoint(rigCharacterGroup) if facialRootJoint == None: cmds.error('Slave facial root joint not found.') return # Possibly remove the skin cluster and related skin joints if the facial mesh is skinned. facialMeshSC = findRelatedSkinCluster(facialMesh) if facialMeshSC: cmds.warning( 'Facial mesh already skinned, removing old skin cluster and deleting old influence joints.' ) jnts = cmds.skinCluster(facialMeshSC, q=1, inf=1) cmds.skinCluster(facialMesh, e=True, ub=True) # Only delete face proxy joints. for jnt in jnts: if jointHasTag(jnt, SERigNaming.sJointTagFacialProxy): cmds.delete(jnt) vertices = getMeshVertices(cageMesh) proxyJnts = [] for i in range(vertices.length()): proxyJnt = cmds.createNode('joint', n=SERigNaming.sFacialProxyJointPrefix + str(i)) proxyJnts.append(proxyJnt) # Tagging facial skin proxy joints. jointAddTag(proxyJnt, SERigNaming.sJointTagFacialProxy) cmds.setAttr(proxyJnt + '.radius', 0.35) # Moving proxy joints in position. cmds.setAttr(proxyJnt + '.tx', vertices[i].x) cmds.setAttr(proxyJnt + '.ty', vertices[i].y) cmds.setAttr(proxyJnt + '.tz', vertices[i].z) cmds.parent(proxyJnts, facialRootJoint) cmds.makeIdentity(proxyJnts, apply=True) # Create a one-to-one influence relationship between cage mesh vertices and skin proxy joints. cageMeshSC = cmds.skinCluster(proxyJnts, cageMesh, toSelectedBones=True, skinMethod=0, normalizeWeights=1, obeyMaxInfluences=1, maximumInfluences=1)[0] # Bind skin proxy joints to facial mesh. facialMeshSC = cmds.skinCluster( proxyJnts, facialMesh, toSelectedBones=True, skinMethod=0, normalizeWeights=1, obeyMaxInfluences=1, maximumInfluences=proxyJntMaximumInfluences)[0] # Query mesh current uv set. cageMeshCurUVSet = cmds.polyUVSet(cageMesh, query=True, currentUVSet=True)[0] facialMeshCurUVSet = cmds.polyUVSet(facialMesh, query=True, currentUVSet=True)[0] # Transfer cage mesh's skin weights to facial mesh based on their current uv sets. cmds.copySkinWeights(ss=cageMeshSC, ds=facialMeshSC, noMirror=True, surfaceAssociation='closestPoint', uvSpace=(cageMeshCurUVSet, facialMeshCurUVSet), influenceAssociation='closestJoint', normalize=True) # We have done skin weights transfer, unbind cage mesh's skin. cmds.skinCluster(cageMesh, e=True, ub=True) return proxyJnts
def playblast(saveDir, width, height, renderCamera, modelPanel, renderSize=1): """ Playblasts the timeslider Args: saveDir (str): save directory with *.mov extension width (int): width in pixels height: height in pixels renderCamera: camera to playblast from modelPanel: modelPanel to playblast from renderSize: render size (factor) """ check() # check that everything is in order renderSize = resolutionCheck( width, height, renderSize) # make sure resolution is reasonable aPlayBackSliderPython = mel.eval('$tmpVar=$gPlayBackSlider') audioNode = cmds.timeControl(aPlayBackSliderPython, q=True, s=True) # get audio node # get working values to be changed workingRenderSize = cmds.getAttr("{0}.renderScale".format( mnpr_info.configNode)) workingColorDepth = cmds.getAttr("{0}.colorDepth".format( mnpr_info.configNode)) workingCamera = cmds.modelEditor(modelPanel, cam=True, q=True) workingCameraShape = cmds.listRelatives(workingCamera, s=True) if workingCameraShape: workingCameraShape = workingCameraShape[0] else: # we already have the shape workingCameraShape = workingCamera # set desired attributes cmds.mnpr(g=True) mnprOperations = len(cmds.mnpr(lsO=True)) cmds.mnpr(renderOperation=mnprOperations - 1, s=0) # HUD cmds.mnpr(renderOperation=mnprOperations - 2, s=0) # UI cmds.modelEditor(modelPanel, cam=renderCamera, e=True) # change modelPanel lib.setAttr(mnpr_info.configNode, "renderScale", renderSize) lib.setAttr(mnpr_info.configNode, "colorDepth", 2) # needs to be 32bit to avoid artefacts cmds.refresh() # try playblasting try: cmds.playblast(f=saveDir, format="qt", w=width, h=height, percent=100, qlt=100, v=True, fo=True, os=True, s=audioNode, compression="PNG") except RuntimeError: try: cmds.playblast(f=saveDir, format="avi", w=width, h=height, percent=100, qlt=100, v=True, fo=True, os=True, s=audioNode) except RuntimeError: cmds.error( "Video cannot be playblasted as qt or avi, please check the installed codecs." ) # bring everything back to normal cmds.mnpr(renderOperation=mnprOperations - 1, s=1) # HUD cmds.mnpr(renderOperation=mnprOperations - 2, s=1) # UI cmds.modelEditor(modelPanel, cam=workingCameraShape, e=True) lib.setAttr(mnpr_info.configNode, "renderScale", workingRenderSize) lib.setAttr(mnpr_info.configNode, "colorDepth", workingColorDepth) cmds.mnpr(g=False) cmds.refresh() lib.printInfo( "Video has been successfully playblasted to: {0}".format(saveDir))
# Created by Adam Fatka [email protected] # script captures the selection in Maya and copies the string to the clipboard. import maya.cmds as cmds try: import pyperclip except: try: import sys sys.path.append( '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages' ) import pyperclip except: cmds.error('pyerpclip not installed. Please install pyperclip') def sel2clip(long_form=False): selection = cmds.ls(selection=True, long=long_form, transforms=True) print(selection) if len(selection) < 1: cmds.error('No selection detected, don\'t be dumb...') elif len(selection) == 1: pyperclip.copy(selection[0]) else: to_clipboard = "{}, and {}".format(', '.join(selection[:-1]), selection[-1]) # print(to_clipboard) pyperclip.copy(to_clipboard)
def revert_to_saved(self): if len(self.saved_animations) > 0: self.saved_animations.pop().revert() self.undo_button.setText("Undo (%d)" % len(self.saved_animations)) else: cmds.error("No more animations left in undo history")
def runAutoPro(self): statusUpdate(self, 'Starting AutoPro') #reset textField values to default for error detection reasons resetValue(self) mel.progressBar('autoProProgress', edit = 1, visible=1) statusUpdate(self, 'Optimizing Scene') import maya.mel as mm mm.eval('source cleanupScene.mel') mm.eval('performCleanUpSceneForEverything') statusUpdate(self, 'Finished Optimizing Scene') addProgress() #collect display layers display_Layers = ap.find_layers() #collect the state of display layers display_layers_state = ap.collect_layer_state(display_Layers) #hide layers ap.hide_all_layers(display_Layers) #progressWindow() #Check to see if a file is loaded statusUpdate(self, 'Query Scene Load') if not (mel.file(query=1, sceneName=1)): mel.progressBar('autoProProgress', edit = 1, visible=0) statusUpdate(self, 'No file loaded. Please load a file.') mel.error("No file loaded. Please load a file") #update name variables updateNameVars() addProgress() statusUpdate(self, 'Name Variables Verified') statusUpdate(self, 'Checking File Name') #check the name and edit the GUI accordingly. nameCheck = ap.nameCheck(yearMonth, projNum) mel.textField("studentFileNameTextField", edit = True, text = nameCheck[1]) if(nameCheck[0]): mel.textField("fileNamedTextField", edit=True, text = "Yes", backgroundColor = ap.bgColor(0)) else: mel.textField("fileNamedTextField", edit = True, text = "No", backgroundColor = ap.bgColor(100)) addProgress() statusUpdate(self, 'Name Check Complete') statusUpdate(self, 'Gathering Nodes') #Load the assemblie nodes minus cameras masterNodes = ap.masterGroup() #sort to capture all children nodes as well as main assembly nodes allNodes = ap.nodeCollect(masterNodes) nodes= [] addProgress() statusUpdate(self, 'Nodes Collected') statusUpdate(self, 'PolySurfaceShape Work Around') #this is a bit of a hack to get around the polySurfaceShape node that is created when an object has history for tempNode in allNodes: if 'polySurfaceShape' not in tempNode: nodes.append(tempNode) addProgress() statusUpdate(self, 'Work Around Complete') statusUpdate(self, 'Calculating Node Quantities') #calculate total nodes and place in GUI totalNodes = len(nodes) transformNodes = ap.listCollect(nodes, 'transform') visiNodes = ap.listCollect(nodes, 'mesh') totalShape = len(visiNodes) totalTrans = len(transformNodes) mel.textField("totalObjectsTextField", edit=1, text=totalTrans) mel.textField("totalShapeObjectsTextField", edit=1, text = totalShape) addProgress() statusUpdate(self, 'Node Quantities Complete') statusUpdate(self, 'Comparing Default Names') #compare geometry names to defualt name list and calculate and populate GUI fields global defaultNames defaultNames = ap.defaultCompare(transformNodes) mel.textField("notNamedTextField", edit=1, text=len(defaultNames)) notNamedPercent = int((float(len(defaultNames))/float(totalTrans))*100.0) percentDefaultNames = (str(notNamedPercent) + "%") notNamedColor = ap.bgColor(notNamedPercent) mel.textField("notNamedPercentTextField", edit=1, text=percentDefaultNames, backgroundColor = notNamedColor) addProgress() statusUpdate(self, 'Default Names Compared') statusUpdate(self, 'Checking Master Group') #Check to master Group node and subGroups subGroups = ap.subGroups(masterNodes) if ((len(masterNodes)) ==1) and subGroups != False: mel.textField("groupedTextField", edit=True, text = "Yes", backgroundColor = (0.0, 0.8, 0.0)) else: mel.textField("groupedTextField", edit = True, text = "No", backgroundColor = (0.8, 0.0, 0.0)) mel.textField("masterNodeTextField", edit = True, text = str(masterNodes)) mel.textField("subGroupTextField", edit=True, text = str(subGroups)) #checks to see if there are subGroups addProgress() statusUpdate(self, 'Master Group and SubGroups Checked') statusUpdate(self, 'Checking Display Layers') #Checks for geometry to be in display layer and updates GUI displayLayers = mel.layout('LayerEditorDisplayLayerLayout', query = 1, childArray =1) visibleLayer = [] if displayLayers != None: for dLayer in displayLayers: if mel.objExists(dLayer): if(mel.getAttr('%s.visibility' % dLayer)): visibleLayer.append(dLayer) for layer in visibleLayer: mel.setAttr('%s.visibility' % layer, 0) global notLayered notLayeredLocal = [] for node in visiNodes: if (ap.visibleTest(node)): notLayeredLocal.append(node) if displayLayers != None: for layer2 in visibleLayer: mel.setAttr('%s.visibility' % layer2, 1) notLayered = notLayeredLocal mel.textField("notLayeredTextField", edit = 1, text = len(notLayered)) notLayerPercent = int((float(len(notLayered))/float(len(visiNodes)))*100.0) percentNotLayer = (str(notLayerPercent) + "%") notLayeredColor = ap.bgColor(notLayerPercent) mel.textField("notLayeredPercentTextField", edit=1, text=percentNotLayer, backgroundColor = notLayeredColor) addProgress() statusUpdate(self, 'Display Layers Checked') statusUpdate(self, 'Checking Transforms') #Checks for frozen transforms. global notFroze notFroze = ap.spreadSheet(ap.listCollect(nodes, 'transform')) mel.textField("notFrozenTextField", edit= 1, text=len(notFroze)) notFrozePercent = int((float(len(notFroze))/float(totalTrans))*100.00) percentNotFroze = (str(notFrozePercent) + "%") notFrozeColor = ap.bgColor(notFrozePercent) mel.textField("notFrozenPercentTextField", edit =1, text = percentNotFroze, backgroundColor = notFrozeColor) addProgress() statusUpdate(self, 'Transforms Checked') statusUpdate(self, 'Checking for History') #check for History global withHistory withHistory = ap.historyFinder(ap.listCollect(nodes, 'mesh')) mel.textField("withHistoryTextField", edit = 1, text = len(withHistory)) withHistoryPercent = int((float(len(withHistory))/float(len(visiNodes)))*100.0) percentWithHistory = (str(withHistoryPercent) + "%") withHistoryColor = ap.bgColor(withHistoryPercent) mel.textField("withHistoryPercentTextField", edit=1, text=percentWithHistory, backgroundColor = withHistoryColor) addProgress() statusUpdate(self, 'History Checked') statusUpdate(self, 'Checking Pivots') #Check for pivots global notCentered notCentered = ap.centerPivot(ap.listCollect(nodes, 'transform')) mel.textField("notCenteredTextField", edit=1, text = len(notCentered)) notCenteredPercent = int((float(len(notCentered))/float(totalTrans))*100.0) percentNotCentered = (str(notCenteredPercent) + "%") notCenteredColor = ap.bgColor(notCenteredPercent) mel.textField("notCenteredPercentTextField", edit = 1, text = percentNotCentered, backgroundColor = notCenteredColor) addProgress() statusUpdate(self, 'Pivots Checked') statusUpdate(self, 'Testing N-gons') #Test N-gons global nGonList nGonList = ap.nGonFinder(allNodes) nGonPercent = int((float(len(nGonList[0]))/float(len(visiNodes)))*100.0) percentNGons = (str(nGonPercent) + "%") nGonColor = ap.bgColor(nGonPercent) mel.textField("totalNgonObjectsTextField", edit =1, text = len(nGonList[0])) mel.textField("ngonPercentTextField", edit = 1, text = percentNGons , backgroundColor = nGonColor) mel.textField("totalNgonsTextField", edit =1, text = len(nGonList[1])) addProgress() statusUpdate(self, 'N-gons Complete') statusUpdate(self, 'Testing Lamina Faces') #test Lamina faces global laminaList laminaList = ap.laminaFinder(allNodes) laminaPercent = int((float(len(laminaList[0]))/float(len(visiNodes)))*100.0) percentLamina = (str(laminaPercent) + "%") laminaColor = ap.bgColor(laminaPercent) mel.textField("totalLaminaObjectsTextField", edit =1, text = len(laminaList[0])) mel.textField("laminaPercentTextField", edit = 1, text = percentLamina , backgroundColor = laminaColor) if laminaList[1]==None: laminaListLen =0 else: laminaListLen = len(laminaList[1]) mel.textField("totalLaminaTextField", edit =1, text = laminaListLen) addProgress() statusUpdate(self, 'Laminas Complete') statusUpdate(self, 'Tool Completed') mel.rowLayout( 'progressRowLayout', edit = 1, visible = 0) mel.rowLayout('autoProStatusRowLayout', edit =1, visible = 0) statusUpdate(self, 'Testing Tri Faces') #test Lamina faces global triList triList = ap.triFinder(allNodes) triPercent = int((float(len(triList[0]))/float(len(visiNodes)))*100.0) percentTri = (str(triPercent) + "%") triColor = ap.bgColor(triPercent) mel.textField("totalTriObjectsTextField", edit =1, text = len(triList[0])) mel.textField("triPercentTextField", edit = 1, text = percentTri , backgroundColor = triColor) if triList[1]==None: triListLen =0 else: triListLen = len(triList[1]) mel.textField("totalTriTextField", edit =1, text = triListLen) addProgress() statusUpdate(self, 'Tris Complete') statusUpdate(self, 'Tool Completed') mel.rowLayout( 'progressRowLayout', edit = 1, visible = 0) mel.rowLayout('autoProStatusRowLayout', edit =1, visible = 0) ap.set_layers_visibility(display_Layers, display_layers_state) #push grades auto pushGrades('self')
def align(nodes=None, axis='x', mode='mid'): # default nodes to selection if nothings provided if not nodes: nodes = cmds.ls(sl=True) # If nothing is selected either, then error if not nodes: cmds.error('Nothing selected or provided') # We need to convert any vertexes, edges and faces to just vertexes and flatten any ranges # If we don't flatten we might get polyCube1.vtx[1:5] which is hard to work with # We instead just want polyCube1.vtx[1], polyCube1.vtx[2], polyCube1.vtx[3] etc... # Create a temporary list to store the converted objects in _nodes = [] for node in nodes: # Faces are in the format polyCube1.f[2] # So we check if its a face by looking for .f[ inside the name if '.f[' in node: # If its a face, we convert it from a face to a vertex list node = cmds.polyListComponentConversion(node, fromFace=True, toVertex=True) elif '.e[' in node: # We do the same for edges node = cmds.polyListComponentConversion(node, fromEdge=True, toVertex=True) # To flatten the vertex lists we need to first select it cmds.select(node) # Then we can use the ls command to flatten it out node = cmds.ls(sl=True, fl=True) # Then we extend the _nodes list with this flat list _nodes.extend(node) # Since we changed the selection, lets set it back to the nodes list cmds.select(nodes) # Then lets replace nodes with the _nodes temp list that we made nodes = _nodes # Now we need to figure out which mode we're using # We do this by seeing if mode is equal to a value which gives us True or Fale # We then store that True or False in a variable minMode = mode == 'min' maxMode = mode == 'max' midMode = mode == 'mid' # All our transform values give us back a list of x,y,z # Since we only care about one of these axes at a time, # the start variable tells us where to look # For x we look at the first item (0), y is second (1) and z is third (2) # Remember that lists start from 0 if axis == 'x': start = 0 elif axis == 'y': start = 1 elif axis == 'z': start = 2 else: # If none of these apply then error out cmds.error('Unknown Axis') # We need to store the values and bounding boxes bboxes = {} values = [] # get the dimensions of our objects by looping through them for node in nodes: if '.vtx[' in node: # Vertexes dont have bounding boxes so we just get their worldspace translation values ws = cmds.xform(node, q=True, t=True, ws=True) # In this case minValue, midValue and maxValue will all be equal so we can assign them together minValue = midValue = maxValue = ws[start] else: # If we are a regular object, then get the bounding box of the object # this is a box that describes the height, width and depth of an object # It gives us back a list like # [x-min, y-min, z-min, x-max, y-max, z-max] bbox = cmds.exactWorldBoundingBox(node) # Then we get the minimum value, the max value and use them to calculate the mid value minValue = bbox[start] maxValue = bbox[start+3] midValue = (maxValue+minValue)/2 # We store these in the bboxes dictionary using the node name as the key bboxes[node] = (minValue, midValue, maxValue) # Depending on the mode, we only store that modes value for later use if minMode: values.append(minValue) elif maxMode: values.append(maxValue) else: values.append(midValue) # we calculate the alignment point using the values collected if minMode: # This gives us back the minimum values. min is a python built in function target=min(values) elif maxMode: # This gives us back the maximum values. max is a python built in function target = max(values) else: # This is a formula to average the values target = sum(values)/len(values) # figure out the distance to the target for node in nodes: # Retrieve the values from the dictionary bbox = bboxes[node] # Extract them into variables minValue, midValue, maxValue = bbox # then get the worldspace transform ws = cmds.xform(node, query=True, translation=True, ws=True) # Finally use those values to calculate how far to move the objects width = maxValue - minValue if minMode: distance = minValue - target ws[start] = (minValue-distance) + width/2 elif maxMode: distance = target-maxValue ws[start] = (maxValue + distance) - width/2 else: distance = target - midValue ws[start] = midValue + distance # move the object to the target cmds.xform(node, translation=ws, ws=True)
def __init__( self, prefix='pre', name='name', suffix='con', scale=1.0, parent='', shape='circle', color='auto', lockChannels=[], translateTo='', rotateTo='', offsetLocs=1, offsetGrps=1 ): ''' @param prefix: str, prefix name for control @param name: str, main name for control @param scale: float, scale size for control shape @param parent: str, parent for control @param shape: str, shape for the control @param lockChannels: list( str ), list of channels to lock on creation @param translateTo: str, object to match translation too @param rotateTo: str, object to match rotation too @param offsetLocs: int, number of offset locators to add too control @param offsetGrps: int, number of offset groups to add too control ''' shapeDict = dictionaries.curveShapes() colorDict = dictionaries.colorDictionary() ctrlObject = None # check if shape is inside dictionary if shape not in shapeDict: mc.error('requested shape - {0} - not found'.format(shape)) # get unique name fullName = checks.uniqueName(prefix, name, suffix) # create control ctrlObject = mc.curve(n=fullName, p=shapeDict[shape], d=1) # rename ctrlObject shape shape = checks.getShape(ctrlObject) mc.rename(shape, '{0}Shape'.format(ctrlObject)) # control overrides overrides.lockAttrs(ctrlObject, channels=lockChannels) # scale control self.transformControlShape(ctrlObject, s=(scale, scale, scale)) # color control based on prefix if color == 'auto': if prefix == 'l': overrides.override(ctrlObject, col='b') elif prefix == 'r': overrides.override(ctrlObject, col='r') elif prefix == 'c': overrides.override(ctrlObject, col='y') elif prefix == 'global': overrides.override(ctrlObject, col='g') # use specified color if not auto else: if color in colorDict.keys(): overrides.override(ctrlObject, col=color) else: mc.error('{0} - does not exist in dictionary'.format(color)) # translate and rotate too if mc.objExists(translateTo): mc.delete(mc.pointConstraint(translateTo, ctrlObject)) if mc.objExists(rotateTo): mc.delete(mc.orientConstraint(rotateTo, ctrlObject)) # parent control if mc.objExists(parent): mc.parent(ctrlGrp, parent) # offset locs and groups self.offsetLoc(ctrlObject, count=offsetLocs) self.offsetGrp(ctrlObject, count=offsetGrps) # global members self.con = ctrlObject
import maya.OpenMaya as om import maya.OpenMayaFX as omx import maya.utils as utils from time import gmtime, strftime import time, datetime, sys, os, subprocess, shutil, re, getpass import maya.OpenMayaUI as omui import maya.mel as mel import gc # check maya version support = 0 ver = int(cmds.about(file=True)[:4]) if 2010 < ver:# < 2014: support = 1#version OK else: cmds.error('Maya version not support. Use 2011-2013') #try import pyqt qt = '' try: from PyQt4.QtGui import * from PyQt4.QtCore import * qt = 'qt' except ImportError: try: from PySide.QtGui import * from PySide.QtCore import * qt = 'side' except ImportError: cmds.error('PyQt or PySide not found!!!') #Load modules
def createWireOffsetCtl(nodeName, dfmGeo, attachGeo=None, ctlNum=1, size=1, addGrp=1, form=0): ''' attachGeo [string] - plug of mesh to attach controls to e.g. 'abc_wireOffset_wireDfm.outputGeometry[0]' or 'skinCluster1.outputGeometry[0]' ''' #=========================================================================== # DRIVER SYSTEM #=========================================================================== # check whether selection is edge or vertex firstSel = mc.ls(os=True)[0] if '.vtx' in firstSel: # vertex drvSys, drvLocs = createPtDriverSys(nodeName, attachGeo=attachGeo) elif '.e' in firstSel: # edge print 'form: %s' % form drvSys, drvLocs = createCrvDriverSys(nodeName, ctlNum, attachGeo=attachGeo, form=form) else: # invalid selection mc.error('invalid selection: %s' % firstSel) return 0 #=========================================================================== # CONTROL SYSTEM #=========================================================================== ctlSys, ctls = createCtlSys(nodeName, drvLocs) #=========================================================================== # DEFORMATION SYSTEM #=========================================================================== dfmSys = createDfmSys(nodeName, drvLocs, ctls, dfmGeo) #=========================================================================== # MASTER NODE #=========================================================================== masterGrp = mc.group(em=True, n=nodeName+'_wireOffset_mod') mc.parent(ctlSys, dfmSys, drvSys, masterGrp) # add a unique attribute to find it easily mc.addAttr(masterGrp, ln='lsWireOffsetNode', at='bool') # hide unnecessary attrs abRT.hideAttr(masterGrp, ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v']) # add attributes for customization mc.addAttr(masterGrp, ln='enabled', at='bool', dv=True, k=True) mc.addAttr(masterGrp, ln='ctlVis', at='bool', dv=True, k=True) mc.addAttr(masterGrp, ln='envelope', at='double', dv=1, min=0, max=1, k=True) mc.addAttr(masterGrp, ln='dropoff', at='double', dv=5, min=0, k=True) mc.addAttr(masterGrp, ln='rotation', at='double', dv=0, min=0, max=1, k=True) mc.connectAttr(masterGrp+'.ctlVis', ctlSys+'.ctlVis', f=True) mc.connectAttr(masterGrp+'.envelope', dfmSys+'.envelope', f=True) mc.connectAttr(masterGrp+'.dropoff', dfmSys+'.dropoff', f=True) mc.connectAttr(masterGrp+'.rotation', dfmSys+'.rotation', f=True) # "enabled" attribute is more tricky # first, we'll hide everything mc.connectAttr(masterGrp+'.enabled', masterGrp+'.v', f=True) # to speed things up, we'll also disable the drvSys and dfmSys mc.connectAttr(masterGrp+'.enabled', drvSys+'.enabled', f=True) mc.connectAttr(masterGrp+'.enabled', dfmSys+'.enabled', f=True) mc.select(masterGrp, r=True) return masterGrp
def getExportTargets(*args): exportTargets = [] def searchIsRight(tr, searchForType, searchFor, splitName): if splitName: compairTr = tr.split(splitName)[-1] else: compairTr = tr if searchForType == 0 and compairTr.find(searchFor) != -1: return True elif searchForType == 1 and compairTr[:len(searchFor )] == searchFor: return True elif searchForType == 2 and compairTr[-len(searchFor ):] == searchFor: return True exportType = WinA_Cmd.getExportType() if exportType == 0: meshObjs = sgBFunction_selection.getTransformNodesFromGroup( cmds.ls(sl=1)) for meshObj in meshObjs: meshObj = cmds.ls(meshObj)[0] exportTargets.append(meshObj) elif exportType == 1: searchFor = cmds.textField(WinA_Global.searchFor_txf, q=1, tx=1) searchForType = WinA_Cmd.getSearchForType() splitName = WinA_Cmd.getSplitName() if not searchFor: cmds.error("Check Search For String") targets = [] for tr in cmds.ls(tr=1): if searchIsRight(tr, searchForType, searchFor, splitName): targets.append(tr) meshObjs = sgBFunction_selection.getTransformNodesFromGroup( targets) for meshObj in meshObjs: meshObj = cmds.ls(meshObj)[0] exportTargets.append(meshObj) elif exportType == 2: searchFor = cmds.textField(WinA_Global.searchFor_txf, q=1, tx=1) searchForType = WinA_Cmd.getSearchForType() splitName = WinA_Cmd.getSplitName() if not searchFor: cmds.error("Check Search For String") targets = [] trChildren = cmds.listRelatives(cmds.ls(sl=1), c=1, ad=1, f=1, type='transform') trChildren += cmds.ls(sl=1) for tr in trChildren: if searchIsRight(tr, searchForType, searchFor, splitName): targets.append(tr) meshObjs = sgBFunction_selection.getMeshObjectFromGroup(targets) for meshObj in meshObjs: meshObj = cmds.ls(meshObj)[0] exportTargets.append(meshObj) return exportTargets
def positionReorderDoIt(*args): meshes = [] sourceMeshText = cmds.textField( 'sourceMeshTextField', query=True, text=True ) if sourceMeshText == '': cmds.error('source mesh textfield is empty') if cmds.objExists(sourceMeshText) == False: cmds.error('the source mesh ( '+sourceMeshText+' ) does not exist') if cmds.nodeType(sourceMeshText) != 'mesh': shapes = cmds.listRelatives( sourceMeshText, shapes=True ) if shapes is None or len(shapes) < 1 or cmds.nodeType(shapes[0]) != 'mesh': cmds.error('source ( '+sourceMeshText+' ) is not a mesh') meshes.append( sourceMeshText ) destinationMeshText = cmds.textField( 'destinationMeshTextField', query=True, text=True ) if destinationMeshText == '': cmds.error('destination mesh textfield is empty') if cmds.objExists(destinationMeshText) == False: cmds.error('the destination mesh ( '+destinationMeshText+' ) does not exist') if cmds.nodeType(destinationMeshText) != 'mesh': shapes = cmds.listRelatives( destinationMeshText, shapes=True ) if shapes is None or len(shapes) < 1 or cmds.nodeType(shapes[0]) != 'mesh': cmds.error('destination ( '+destinationMeshText+' ) is not a mesh') meshes.append( destinationMeshText ) positionReorder( meshes=meshes )
def sortSelection(self): """Re-order the selection list based on various criteria""" # Remove locator from selection self.deselectLocator(self.locName) # Create list from selection, and dictionary for sorting sel = mc.ls(selection=True, flatten=True) selDic = {} # Get options mode1 = mc.radioButtonGrp("sortBy1", query=True, select=True) mode2 = mc.radioButtonGrp("sortBy2", query=True, select=True) mode = mode1 + mode2 * 10 rev = mc.checkBox("reverse", query=True, value=True) # Check locator exists if in proximity mode if mode == 20 and not mc.objExists(self.locName): mc.error("Create locator before sorting by proximity.") #self.createLocator(self.locName) return False # Construct name to give to new group self.grpName = "sortedBy" if mode == 1: self.grpName += "X" elif mode == 2: self.grpName += "Y" elif mode == 3: self.grpName += "Z" elif mode == 10: self.grpName += "Name" elif mode == 20: self.grpName += "Distance" if rev: self.grpName += "Inv" # Populate the selection dictionary based on the sort criteria for i in range(len(sel)): if mode == 1: selDic[sel[i]] = (mc.objectCenter(sel[i], x=True)) elif mode == 2: selDic[sel[i]] = (mc.objectCenter(sel[i], y=True)) elif mode == 3: selDic[sel[i]] = (mc.objectCenter(sel[i], z=True)) elif mode == 10: selDic[sel[i]] = sel[i] elif mode == 20: p = mc.objectCenter(sel[i]) q = mc.xform(self.locName, query=True, translation=True) selDic[sel[i]] = gps.distanceBetween(p, q) # Sort the dictionary based on the values and save to a new sorted list selSorted = sorted(selDic.iteritems(), key=operator.itemgetter(1), reverse=rev) # Re-select objects from sorted list mc.select(clear=True) for selObj in selSorted: mc.select(selObj[0], add=True)
def positionReorder(**kwargs): meshes = kwargs.get('meshes',[]) ################################################################ # # do some error checking # ################################################################ if len(meshes) < 2: cmds.error('please select 2 meshes') fromMesh = meshes[0] toMesh = meshes[1] if cmds.nodeType(fromMesh) != 'mesh': shapes = cmds.listRelatives( fromMesh, shapes=True) if shapes is not None and len(shapes) > 0 and cmds.nodeType(shapes[0]) == 'mesh': fromMesh = shapes[0] else: cmds.error('source mesh was not found') if cmds.nodeType(toMesh) != 'mesh': shapes = cmds.listRelatives( toMesh, shapes=True) if shapes is not None and len(shapes) > 0 and cmds.nodeType(shapes[0]) == 'mesh': toMesh = shapes[0] else: cmds.error('destination mesh was not found') if len( cmds.listHistory( toMesh ) ) > 1: cmds.error('destination mesh ( '+toMesh+' ) has history, please delete history') ################################################################ # # use api to get the mesh data from # the source and destination meshes # ################################################################ selectionList = om.MSelectionList() selectionList.add( fromMesh ) selectionList.add( toMesh ) fromDagPath = selectionList.getDagPath(0) toDagPath = selectionList.getDagPath(1) fromMeshFn = om.MFnMesh( fromDagPath ) toMeshFn = om.MFnMesh( toDagPath ) fromPoints = fromMeshFn.getPoints() toPoints = toMeshFn.getPoints() fromDagNodeFn = om.MFnDagNode(fromDagPath) toDagNodeFn = om.MFnDagNode(toDagPath) fromBoundingBox = fromDagNodeFn.boundingBox toBoundingBox = toDagNodeFn.boundingBox ################################################################ # # More error checking! # make sure source mesh doesn't have # more points than the destination mesh # ################################################################ if len(fromPoints) > len(toPoints): cmds.error('source mesh ( '+fromMesh+' ) has more points than destination mesh ( '+toMesh+' ). Source mesh must have the same number of points or less points than the destination mesh') ################################################################ # # build lookup tables for points and faces # ################################################################ fromVertices = fromMeshFn.getVertices() toVertices = toMeshFn.getVertices() fromVertPolyTable = [None]*len(fromPoints) fromPolyVertTable = [] index = 0 for faceID,numberOfVerts in enumerate(fromVertices[0]): fromPolyVertTable.append([]) for x in range(numberOfVerts): vertID = fromVertices[1][index] fromPolyVertTable[faceID].append(vertID) if fromVertPolyTable[vertID] is None: fromVertPolyTable[vertID] = [faceID] else: fromVertPolyTable[vertID].append(faceID) index = index+1 toVertPolyTable = [None]*len(toPoints) toPolyVertTable = [] index = 0 for faceID,numberOfVerts in enumerate(toVertices[0]): toPolyVertTable.append([]) for x in range(numberOfVerts): vertID = toVertices[1][index] toPolyVertTable[faceID].append(vertID) if toVertPolyTable[vertID] is None: toVertPolyTable[vertID] = [faceID] else: toVertPolyTable[vertID].append(faceID) index = index+1 ################################################################ # # create a list of destination points that # are in the bounding box of the source # mesh and have a matching point # ################################################################ toSearchPoints = {} toMatchingPoints = {} for index,point in enumerate(toPoints): if fromBoundingBox.contains(point): matchingPoint = findMatchingPoint(point=point, meshFn=fromMeshFn, meshPoints=fromPoints) if matchingPoint != None: #print(index,matchingPoint) toSearchPoints[index] = None toMatchingPoints[index] = matchingPoint ################################################################ # # create a list of destination faceIds # associated with bounding box points # ################################################################ toMatchingPolys = {} toBorderingPolys = {} for toIndex in toSearchPoints: toPolyIds = toVertPolyTable[toIndex] for toPolyId in toPolyIds: toVerts = toPolyVertTable[toPolyId] for toVert in toVerts: found = toSearchPoints.get(toVert,False) #toUsePoints[toVert] = False if found == False: toBorderingPolys[toPolyId] = True else: toMatchingPolys[toPolyId] = True # just a double check to make sure the matching # polys list doesn't contain any connecting polys items for toPolyId in toBorderingPolys: toMatchingPolys.pop(toPolyId,False) ################################################################ # # Find any matching points, from the connecting polys, # between the source and destination meshes # ################################################################ toPointsConvert = {} for toPolyId in toBorderingPolys: toPolyVerts = toMeshFn.getPolygonVertices( toPolyId ) for toPolyVert in toPolyVerts: matchingPoint = toMatchingPoints.get(toPolyVert,None) if matchingPoint != None: toPointsConvert[toPolyVert] = matchingPoint ################################################################ # # create points conversion table for the destination mesh # ################################################################ newIndex = len(fromPoints) for toIndex,toPoint in enumerate(toPoints): matchingPointFound = toMatchingPoints.get(toIndex,None) if matchingPointFound == None: toPointsConvert[toIndex] = newIndex newIndex = newIndex+1 ################################################################ # # new points, poly and polyconnects lists # ################################################################ newPoints = om.MPointArray() newPoints.setLength( len(toPoints) ) newPolys = [] newPolyConnects = [] ################################################################ # # get info from the source mesh (the from mesh) # ################################################################ for index,fromPoint in enumerate(fromPoints): newPoints[index] = fromPoint for fromPolyVerts in fromPolyVertTable: newPolys.append(len(fromPolyVerts)) for fromPolyVert in fromPolyVerts: newPolyConnects.append(fromPolyVert) ################################################################ # # get data from the destination mesh (the to mesh) # ################################################################ for toPointId,toPointConvertId in toPointsConvert.iteritems(): newPoints[toPointConvertId] = toPoints[toPointId] for toPolyId,toPolyVerts in enumerate(toPolyVertTable): isMatchingPoly = toMatchingPolys.get(toPolyId,None) if isMatchingPoly == None: newPolys.append(len(toPolyVerts)) for toPolyVert in toPolyVerts: newPolyConnects.append(toPointsConvert[toPolyVert]) ################################################################ # # create a new mesh with the vertex IDs reordered # ################################################################ reorderedMesh = om.MFnMesh() reorderedMesh.create( newPoints, newPolys, newPolyConnects ) meshShape = reorderedMesh.partialPathName() meshTransform = cmds.listRelatives(meshShape,parent=True)[0] cmds.select(meshTransform) cmds.hyperShade(assign='initialShadingGroup') cmds.polySoftEdge(meshTransform, angle=0, ch=False) toMeshTransform = cmds.listRelatives(toMesh,parent=True)[0] newMeshName = cmds.rename(meshTransform,toMeshTransform+'_reordered') cmds.select(newMeshName) print('Finished Reordering Vertex IDs')
def getSymPlanCoords(self): selection = mc.ls(sl=True) # selection must be 2 faces if( len(selection) == 2 ) and ( '.f[' in selection[0] ) and ( '.f[' in selection[1] ): obj = selection[0].split('.')[0] indexs = [ selection[0].split('[')[1].split(']')[0] , selection[1].split('[')[1].split(']')[0] ] elif( len(selection) == 1 ) and ( '.f[' in selection[0] ) and ( ':' in selection[0] ): obj = selection[0].split('.')[0] indexsString = selection[0].split('[')[1].split(']')[0].split(':') indexs = [ int(indexsString[0]) , int(indexsString[1]) ] if not( indexs[0] + 1 == indexs[1]): mc.error( ' you must select only 2 faces ') else: mc.error( ' you must select only 2 faces ') # sort face vtx in 3 paire of vtx vtxARaw = utilsMaya.convertFaceEdgeTovtx( [ '{0}.f[{1}]'.format( obj , indexs[0] ) ] ) vtxAindexs = utilsPython.getArrayIndexsOfObjs( vtxARaw ) vtxA = [] for i in vtxAindexs: vtxA.append( '{0}.vtx[{1}]'.format( obj , i ) ) vtxBRaw = utilsMaya.convertFaceEdgeTovtx( [ '{0}.f[{1}]'.format( obj , indexs[1] ) ] ) vtxBindexs = utilsPython.getArrayIndexsOfObjs( vtxBRaw ) vtxB = [] for i in vtxBindexs: vtxB.append( '{0}.vtx[{1}]'.format( obj , i ) ) vtxCouples = [] loop = 0 while( len(vtxCouples) < 3 ): distances = [] dico = {} for vA in vtxA: for vB in vtxB: coordsA = mc.xform( vA , q = True , t = True , ws = True ) coordsB = mc.xform( vB , q = True , t = True , ws = True ) distance = ompy.MVector( ( coordsA[0] - coordsB[0] ) , ( coordsA[1] - coordsB[1] ) , ( coordsA[2] - coordsB[2] ) ).length() distances.append(distance) dico[str(distance)] = vA + '/' + vB distances.sort() vtxCoupleCurent = dico[ str(distances[0] ) ].split('/') vtxA.remove(vtxCoupleCurent[0]) vtxB.remove(vtxCoupleCurent[1]) vtxCouples.append(vtxCoupleCurent) loop += 1 if( 400 < loop ): mc.error('loop') #find the middle of this pair middleCoords = [] for couple in vtxCouples: coordsA = mc.xform( couple[0] , q = True , t = True , ws = True ) coordsB = mc.xform( couple[1] , q = True , t = True , ws = True ) middleCoords += [ ( coordsA[0] + coordsB[0] )/2 , ( coordsA[1] + coordsB[1] )/2 , ( coordsA[2] + coordsB[2] )/2 ] # ui mc.radioButton( self.radioButtonsName[3] , e = True , sl = True ) print( ' get sym plan coords ' ) self.planeCoordsChoice[3] = middleCoords self.setCoordsBoard() return middleCoords
def traverseReorderDoIt(*args): faces = [sourceComponents['face'], destinationComponents['face']] vertex1s = [sourceComponents['vertex1'], destinationComponents['vertex1']] vertex2s = [sourceComponents['vertex2'], destinationComponents['vertex2']] definedError = False if sourceComponents['face'] == '': cmds.warning('source face has not been defined') definedError = True if sourceComponents['vertex1'] == '': cmds.warning('source vertex1 has not been defined') definedError = True if sourceComponents['vertex2'] == '': cmds.warning('source vertex2 has not been defined') definedError = True if destinationComponents['face'] == '': cmds.warning('destination face has not been defined') definedError = True if destinationComponents['vertex1'] == '': cmds.warning('destination vertex1 has not been defined') definedError = True if destinationComponents['vertex2'] == '': cmds.warning('destination vertex2 has not been defined') definedError = True if definedError: cmds.error('not all components have not been defined') sourcePointsList = cmds.polyListComponentConversion( sourceComponents['face'], ff=True, tv=True ) sourcePoints = cmds.ls(sourcePointsList,fl=True) destinationPointsList = cmds.polyListComponentConversion( destinationComponents['face'], ff=True, tv=True ) destinationPoints = cmds.ls(destinationPointsList,fl=True) ##################################################################### # # make sure the faces contain the same number of points # ##################################################################### if len(sourcePoints) != len(destinationPoints): cmds.error('faces have different number of points, faces need to have the same number of points') ##################################################################### # # make sure the points are part of the same face # ##################################################################### pointsError = False pointsFound = False pointsList = cmds.polyListComponentConversion( sourceComponents['face'], ff=True, tv=True ) points = cmds.ls(pointsList, fl=True) if sourceComponents['vertex1'] in points and sourceComponents['vertex2'] in points: pointsFound = True if not pointsFound: cmds.warning('source points need to be part of the same face') pointsError = True pointsFound = False pointsList = cmds.polyListComponentConversion( destinationComponents['face'], ff=True, tv=True ) points = cmds.ls(pointsList, fl=True) if destinationComponents['vertex1'] in points and destinationComponents['vertex2'] in points: pointsFound = True if not pointsFound: cmds.warning('destination points need to be part of the same face') pointsError = True if pointsError: cmds.error( 'points need to be part of the same face' ) ##################################################################### # # make sure the points are part of the same edge # ##################################################################### sourceEdgesList = cmds.polyListComponentConversion( sourceComponents['face'], ff=True, te=True ) sourceEdges = cmds.ls(sourceEdgesList, fl=True) destinationEdgesList = cmds.polyListComponentConversion( destinationComponents['face'], ff=True, te=True ) destinationEdges = cmds.ls(destinationEdgesList, fl=True) edgeError = False edgeFound = False for edge in sourceEdges: pointsList = cmds.polyListComponentConversion( edge, fe=True, tv=True ) points = cmds.ls(pointsList,fl=True) if sourceComponents['vertex1'] in points and sourceComponents['vertex2'] in points: edgeFound = True if not edgeFound: cmds.warning('source points need to be part of the same edge') edgeError = True edgeFound = False for edge in destinationEdges: pointsList = cmds.polyListComponentConversion( edge, fe=True, tv=True ) points = cmds.ls(pointsList,fl=True) if destinationComponents['vertex1'] in points and destinationComponents['vertex2'] in points: edgeFound = True if not edgeFound: cmds.warning('destination points need to be part of the same edge') edgeError = True if edgeError: cmds.error( 'points need to be part of the same edge' ) ##################################################################### # # make sure destination mesh and target # meshes have the same number of points # ##################################################################### destMesh = cmds.listRelatives( destinationComponents['face'], parent=True )[0] destMeshTransform = cmds.listRelatives( destMesh, parent=True )[0] destPoints = cmds.ls( destMeshTransform+'.vts[*]', fl=True ) targetList = cmds.textScrollList( 'traverseTargetTextScrollList', query=True, ai=True ) if targetList == None: targetList = [] wrongNumberOfPointFound = False for target in targetList: targetPoints = cmds.ls( target+'.vts[*]', fl=True ) if (len(targetPoints) != len(destPoints)): cmds.warning(target+' has a different number of points') wrongNumberOfPointFound = True if wrongNumberOfPointFound: cmds.error( 'all target meshes must have the same number of points as the destination mesh' ) traverseReorder( faces=faces, vertex1s=vertex1s, vertex2s=vertex2s, targetList=targetList )
def importSkinWeights_DoImport(self): """ Gather the information from the interface and import the skin weights with that information. For each piece of geometry, get the associated .weight file on disk, then call on import_skin_weights from riggingUtils, passing in the .weight file path and the mesh. """ # which method? # method = self.importSkinWeights_importMethod.currentText() # error report messages errorMessages = [] # weight files weightFiles = [] # find each lineEdit in the scrollArea and get the entered text for i in range(self.importSkinWeights_VLayout.count()): hboxLayout = self.importSkinWeights_VLayout.itemAt(i) value, fileName, mesh = None, None, None for x in range(hboxLayout.count()): widget = hboxLayout.itemAt(x) # go through each widget in the hboxLayout, and get values if type(widget.widget()) == QtWidgets.QLabel: geoName = widget.widget().text() geoName = geoName.partition(" :")[0] if cmds.objExists(geoName): mesh = cmds.ls(geoName, long=True)[0] # see if the user wants to export the weights for this entry if type(widget.widget()) == QtWidgets.QCheckBox: value = widget.widget().isChecked() # get the fileName if type(widget.widget()) == QtWidgets.QLineEdit: fileName = widget.widget().text() # if the box is checked for import, do the import if (value and mesh and fileName): ############################### # BEGIN WEIGHT IMPORT # try to load the given file if os.path.exists(fileName): weightFiles.append(fileName) else: cmds.error('ART_ImportWeights: Skin file does not exist: ' + fileName) return False if not mesh: cmds.error('ART_ImportWeights: Mesh does not exist!') return False # update the total progress bar incrementValue = self.importSkinWeights_progBarTotal.value() + 1 self.importSkinWeights_progBarTotal.setValue(incrementValue) # create a skinWeights class with the skin file if fileName: print 'Loading skinWeights from ', str(fileName) riggingUtils.import_skin_weights(fileName, mesh, True) # ask if user wants to delete weight files file_string = "" for file in weightFiles: file_name = os.path.basename(file) file_string += file_name + "\n" msgBox = QtWidgets.QMessageBox() msgBox.setIcon(QtWidgets.QMessageBox.Warning) msgBox.setText("Would you like to delete the following weight files?") msgBox.setDetailedText(file_string) msgBox.addButton("Yes", QtWidgets.QMessageBox.YesRole) msgBox.addButton("No", QtWidgets.QMessageBox.NoRole) ret = msgBox.exec_() if ret == 0: for file in weightFiles: try: os.remove(file) except: cmds.warning("Unable to delete file: " + str(file)) if ret == 1: return
def scanScene(): global util, charnames, propnames, setnames, adcharnames, adpropnames, adsetnames, charopt, propopt, setopt util = Utils.utils() #declaring and initialising variables charnames, propnames, setnames, miscnames, charopt, propopt, setopt = [], [], [], [], [], [], [] #find rim/key light folder path from config.xml rmkyfldr = "%s/%s/Location" % (util.path, util.litePath) rmkyfiles = os.listdir(rmkyfldr) ltbgs = [x.replace('', '') for x in rmkyfiles] unrefs = [] #find time folder path from config.xml try: litefldr = "%s/%s/Location/%s" % (util.path, util.litePath, rmkyfiles[0]) except: mc.error("Please set the correct project") return Litefiles = os.listdir(litefldr) ltlites = [x.replace('_rimkey.ma', '') for x in Litefiles] #list all reference nodes in scene and list all unloaded references refs = mc.ls(type="reference") if refs: for each in refs: if each != "sharedReferenceNode" and each != "_UNKNOWN_REF_NODE_": try: nodes = mc.referenceQuery(each, nodes=True) if not nodes: unrefs.append(each) except: pass else: print '\nNo valid References found.\n' #prompt to load all unloaded references for the scan to proceed, cancel will still show assets but setup will not work if unrefs: nonrefassets = "Following references are unloaded\nLoad all the references?\n\n" + "\n".join( unrefs) + "\n" rslt = mc.confirmDialog(t='Warning', m=nonrefassets, b=['Continue', 'Cancel'], db='Continue', cb='Cancel', ds='Cancel', ma='center') if rslt == 'Cancel': pass else: for refs in unrefs: refpath = mc.referenceQuery(refs, f=True) mc.file(refpath, lr=True) #list all assets in the scenes using Utils.listAssets() charnames, propnames, setnames, miscnames = Utils.listAssets() if adcharnames: for each in adcharnames: if not each in charnames: charnames.append(each) if adpropnames: for each in adpropnames: if not each in propnames: propnames.append(each) if adsetnames: for each in adsetnames: if not each in setnames: setnames.append(each) #set the scroll menu placeholder in main UI as the parent menu of the dynamic that we're about to create mc.setParent('scrll') numlayers = mc.intFieldGrp("numgrps", q=True, v1=True) #column layout for the dynamic menu if mc.columnLayout("assetcol", ex=True): mc.deleteUI("assetcol") mc.columnLayout("assetcol") #listing the characters in the scene mc.separator(h=5, w=470, st='in') mc.text(l=" CHARACTERS ", fn="boldLabelFont") mc.separator(h=5, w=470, st='in') mc.columnLayout(co=('left', 10)) mc.separator(h=5, w=470, st='none') #creating the menu for each of the characters in the scene for i in range(len(charnames)): mc.rowLayout(nc=3, cw3=(200, 150, 50)) #name of the character mc.text(l=charnames[i]) #select button command com = "mc.select(\"%s\", r = True)" % charnames[i] menulabel = "chmenu%s" % str(i).zfill(2) charopt.append(menulabel) #dropdown list for selecting the render layer group that the character will go into mc.optionMenu(menulabel, label='Render Grp : ') for ii in range(numlayers): mc.menuItem(label="ch%s" % str(ii + 1).zfill(2)) mc.menuItem(label="None") #button for selecting the character mc.button(l="Select", c=com) mc.setParent('..') mc.separator(h=5, w=470, st='none') mc.rowLayout(nc=2, cw2=(100, 300)) #button to add a character that didn't show up in the scan mc.button(l=" Add Character", w=80, al="center", c=lambda event: addAsset(0)) mc.text(label="Select a group and press button to add the character") mc.setParent('..') mc.separator(h=5, w=400, st='none') mc.setParent('..') #listing the props in the scene mc.separator(h=5, w=470, st='in') mc.text(l=" PROPS ", fn="boldLabelFont") mc.separator(h=5, w=470, st='in') mc.columnLayout(co=('left', 10)) mc.separator(h=5, w=470, st='none') #creating the menu for each of the props in the scene for k in range(len(propnames)): mc.rowLayout(nc=3, cw3=(200, 150, 50)) #name of the prop mc.text(l=propnames[k]) #select button command com = "mc.select(\"%s\", r = True)" % propnames[k] menulabel = "prmenu%s" % str(k).zfill(2) propopt.append(menulabel) #dropdown list for selecting the render layer group that the prop will go into mc.optionMenu(menulabel, label='Render Grp : ') for kk in range(numlayers): mc.menuItem(label="ch%s" % str(kk + 1).zfill(2)) mc.menuItem(label="None") #button for selecting the prop mc.button(l="Select", c=com) mc.setParent('..') mc.separator(h=5, w=470, st='none') mc.rowLayout(nc=2, cw2=(100, 300)) #button to add a prop that didn't show up in the scan mc.button(l=" Add Prop", w=80, al="center", c=lambda event: addAsset(1)) mc.text(label="Select a group and press button to add the prop") mc.setParent('..') mc.separator(h=5, w=470, st='none') mc.setParent('..') #listing the bgs in the scene mc.separator(h=5, w=470, st='in') mc.text(l=" SETS ", fn="boldLabelFont") mc.separator(h=5, w=470, st='in') mc.columnLayout(co=('left', 10)) mc.separator(h=5, w=470, st='none') #creating the menu for each of the bgs in the scene for l in range(len(setnames)): mc.rowLayout(nc=3, cw3=(200, 150, 50)) #name of the bg mc.text(l=setnames[l]) #select button command com = "mc.select(\"%s\", r = True)" % setnames[l] menulabel = "bgmenu%s" % str(l).zfill(2) setopt.append(menulabel) #dropdown list for selecting the render layer group that the bg will go into mc.optionMenu(menulabel, label='Render Grp : ') for ll in range(numlayers): mc.menuItem(label="ch%s" % str(ll + 1).zfill(2)) mc.menuItem(label="None") #button for selecting the bg mc.button(l="Select", c=com) mc.setParent('..') mc.separator(h=5, w=470, st='none') mc.rowLayout(nc=2, cw2=(100, 300)) #button to add a bg that didn't show up in the scan mc.button(l=" Add Set", w=80, al="center", c=lambda event: addAsset(2)) mc.text(label="Select a group and press button to add the set") mc.setParent('..') mc.separator(h=5, w=470, st='none') mc.setParent('..') mc.separator(h=5, w=470, st='in') #creating the light options menu mc.setParent('ltopts') if mc.columnLayout("ltopscol", ex=True): mc.deleteUI("ltopscol") mc.columnLayout('ltopscol') mc.rowLayout(nc=2) mc.rowLayout(nc=4, cw4=(39, 39, 39, 39)) mc.checkBox("selchk", label="all", v=1, w=50, cc=lambda event: chkchange()) mc.checkBox("keychk", label="key", v=1, w=39) mc.checkBox("rimchk", label="rim", v=1, w=39) mc.checkBox("colchk", label="col", v=1, w=39) mc.setParent('..') mc.rowLayout(nc=4, cw4=(39, 39, 39, 39)) mc.checkBox("occchk", label="occ", v=1, w=39) mc.checkBox("rgbachk", label="rgba", v=1, w=43) mc.checkBox("gshchk", label="gsh", v=1, w=39) mc.checkBox("matchk", label="mat", v=1, w=39) mc.setParent('..') mc.setParent('..') mc.separator(h=15, w=470, st='none') mc.rowLayout(nc=3, cw3=(30, 250, 150)) mc.text(label='') #checkbox to query whether the references need to be cut mc.checkBox("refchk", label="Import all references(Cut the references)", v=0) #checkbox to query whether the cameras need to be exported mc.checkBox("camchk", label="Export cameras", v=0) mc.setParent('..') mc.separator(h=15, w=470, st='none') mc.rowLayout(nc=4, cw4=(80, 90, 110, 125)) mc.text(label="Ambient Light") mc.text(label=" Location") mc.text(label=" Time") mc.text(label=" Render Scene Camera") mc.setParent('..') mc.separator(h=5, w=470, st='none') mc.rowLayout(nc=4, cw4=(80, 100, 110, 145)) #dropdown to query what kind of ambient light to use mc.optionMenu('amblite', label='') mc.menuItem(label="None") mc.menuItem(label="GI") mc.menuItem(label="ambient") #mc.menuItem( label="GILight") #dropdown to query which rim/key file to use mc.optionMenu('Location', label='', cc=lambda event: locc()) for each in ltbgs: mc.menuItem(label=each) #dropdown to query which time lights to use mc.optionMenu('Time', label='') for each in ltlites: mc.menuItem(label=each) #list all cameras in the scene to find out renderable camera cams = mc.ls(type="camera") rencams = [] epcams = [] #list all cameras that are children of 'CAMERAS' group if mc.objExists('CAMERAS'): epcams = mc.listRelatives('CAMERAS', c=True, ad=True, type='camera') #find out the scene camera and set it to renderable if epcams: for each in cams: if each in epcams: rencams.append(each) mc.setAttr((each + ".renderable"), 1) if not rencams: rencams = cams #dropdown to show renderable cameras in the scene. the scene camera will be selected by default mc.optionMenu( 'camlite', label='', ) renParentCams = [mc.listRelatives(x, p=True)[0] for x in rencams] for each in renParentCams: mc.menuItem(label=each) mc.optionMenu('camlite', e=True, v=(renParentCams[0])) mc.setParent('..') #calculate optimum height of UI window based on the number of assets to be processed numasts = len(charnames) + len(propnames) + len(setnames) if numasts > 12: numasts = 12 scrht = 300 + numasts * 25 winht = 590 + numasts * 25 #edit the window and scrolllayout heights to be the optimum value mc.window('liteshot', e=True, wh=(483, winht)) mc.scrollLayout('scrll', e=True, h=scrht, w=450, vis=True)
#__________________________ NODE DRAW INFO nodeTypeDraw = 'glDraw' pathNodeCppDraw = 'D:/mcantat_BDD/projects/code/maya/c++/mayaNode/glDraw/Build/Release/glDraw.mll'.format( releaseFolder[releaseMode]) print('BUILD TEST __________________________ SOURCE') import sys sys.path.append(pathPythonFiles) import python import maya.cmds as mc from python.plugIn.utilsMayaNodesBuild import * if (mc.objExists("pCube1")): clean([pathNode, pathNodeCppDraw], [nodeType, nodeTypeDraw]) mc.error("****CLEAN FOR RECOMPILING NODE*****") print('BUILD TEST __________________________ PREPARE SCENE') mc.file(pathBuildTest, i=True) mesh = 'pCube1' meshShape = mc.listRelatives(mesh, c=True, s=True)[0] print('BUILD TEST __________________________ LOAD NODE') mc.loadPlugin(pathNode) print('BUILD TEST __________________________ CREATE NODE') mc.select(mesh) newNode = mc.deformer(type=nodeType)[0] print('BUILD TEST __________________________ CONNECT IN')
def execute(self): sx = self.sx sy = self.sy sdv = self.sdv sdu = self.sdu tap = self.tap degs = self.degs subCurve = self.subCurve clean = self.clean do_uvs = self.do_uvs rbc = self.rbc cTol = self.cTol cSubd = self.cSubd if cmds.checkBox(self.aUACCB, q=True, v=True): useAltShape = True else: useAltShape = False multSel = cmds.ls(sl=True, fl=True, ap=True) if cmds.objectType(multSel[0]) == 'mesh': thisIsAMesh = True else: thisIsAMesh = False # Select curve type to extrude along - convert and store for x in multSel: print x if thisIsAMesh != True: cmds.select(x) else: cmds.select(multSel) objSel = cmds.ls(sl=True, fl=True, ap=True) if self.ko == 1: dupObj = cmds.duplicate(objSel) objSel = dupObj if len(objSel) > 1: print objSel if degs == 0: curveDg = cmds.promptDialog( t='Enter Degrees:', m='Enter Degrees - ie. 1 for linear, 3 for curved') objSel = cmds.polyToCurve(f=2, dg=int( cmds.promptDialog(q=True, tx=True))) else: objSel = cmds.polyToCurve(f=2, dg=int(degs), n='%s_curve' % objSel[0].split('.')[0]) else: objType = cmds.listRelatives(objSel[0], f=True) if cmds.objectType( objType[0]) != 'nurbsCurve' and cmds.objectType( objType[0]) != 'bezierCurve': cmds.error( 'Select the nurbs curve first, then the object to align' ) if cmds.objectType(objType[0]) == 'bezierCurve': mm.eval("bezierCurveToNurbs;") # Create a nurbs curve for the extrusion if useAltShape: nurbsCir = self.objToUse else: nurbsCir = cmds.circle(n='extrudeCircle', d=3, r=1, nr=(0, 0, 1), sw=360, ch=True, s=8) objCV = cmds.ls('%s.ep[*]' % objSel[0], fl=True) noOfCV = len(objCV) firstCV = 0 lastCV = noOfCV - 1 cvNumberToUse = firstCV # Rebuild the curve to help with uniformity if self.rev == 1: cmds.reverseCurve(objSel[0], ch=0, rpo=1) if rbc == 1: try: cmds.rebuildCurve(objSel[0], ch=0, rpo=1, rt=4, end=1, kr=0, kcp=0, kep=1, kt=0, s=cSubd, d=3, tol=cTol) cmds.rebuildCurve(objSel[0], ch=0, rpo=1, rt=0, end=1, kr=0, kcp=0, kep=1, kt=0, s=cSubd, d=3, tol=cTol) except: cmds.warning( 'Tolerance for rebuild likely to low, try a higher value or turn Rebuild Curve off' ) if do_uvs == 1: objShape = cmds.listRelatives(objSel[0], c=True, type='shape') mInfo = cmds.shadingNode('curveInfo', n='cMeasure', asUtility=True) cmds.connectAttr('%s.local' % objShape[0], '%s.inputCurve' % mInfo) curveLength = cmds.getAttr('%s.arcLength' % mInfo) cmds.delete(mInfo) self.uvRatio = float( (((sx * sy) * 2.0) * math.pi) / curveLength) print "uvRatio: " + str(self.uvRatio) # Create a tangent contraint to position nurbs circle to the first cv cvPos = cmds.xform('%s.ep[%d]' % (objSel[0], cvNumberToUse), query=True, ws=True, t=True) cmds.xform(nurbsCir[0], ws=True, t=(cvPos[0], cvPos[1], cvPos[2])) fastCon = cmds.tangentConstraint(objSel[0], nurbsCir[0], aim=(0, 0, 1)) cmds.delete(fastCon[0]) # Extrude along curve and set attributes pipeExt = cmds.extrude(nurbsCir[0], objSel[0], n='%s_pipe' % objSel[0], ch=True, rn=subCurve, po=1, et=2, ucp=1, fpt=1, upn=1, rotation=0, scale=1, rsp=1) pipeTes = cmds.listConnections(pipeExt[1], type='nurbsTessellate') if subCurve != 0: pipeSubCurve = cmds.listConnections(pipeExt[1], type='subCurve') cmds.setAttr('%s.format' % pipeTes[0], 2) cmds.setAttr('%s.polygonType' % pipeTes[0], 1) cmds.setAttr('%s.uType' % pipeTes[0], 2) cmds.setAttr('%s.vType' % pipeTes[0], 2) cmds.setAttr('%s.vNumber' % pipeTes[0], sdv) cmds.setAttr('%s.uNumber' % pipeTes[0], sdu) # Add attributes if clean == 0: cmds.addAttr(pipeExt[0], ln='________', k=True) cmds.setAttr('%s.________' % pipeExt[0], l=True) cmds.addAttr(pipeExt[0], ln='Ext_ScaleX', k=True, dv=sx) cmds.addAttr(pipeExt[0], ln='Ext_ScaleY', k=True, dv=sy) cmds.connectAttr('%s.Ext_ScaleX' % pipeExt[0], '%s.scaleX' % nurbsCir[0]) cmds.connectAttr('%s.Ext_ScaleY' % pipeExt[0], '%s.scaleY' % nurbsCir[0]) cmds.addAttr(pipeExt[0], ln='Ext_DivisionV', at='short', k=True, dv=sdv) cmds.connectAttr('%s.Ext_DivisionV' % pipeExt[0], '%s.vNumber' % pipeTes[0]) cmds.addAttr(pipeExt[0], ln='Ext_DivisionU', at='short', k=True, dv=sdu) cmds.connectAttr('%s.Ext_DivisionU' % pipeExt[0], '%s.uNumber' % pipeTes[0]) if subCurve != 0: cmds.addAttr(pipeExt[0], ln='Ext_Length', k=True, dv=1, max=1, min=0) cmds.connectAttr('%s.Ext_Length' % pipeExt[0], '%s.maxValue' % pipeSubCurve[1]) cmds.addAttr(pipeExt[0], ln='Ext_Taper', k=True, dv=tap, min=0) cmds.connectAttr('%s.Ext_Taper' % pipeExt[0], '%s.scale' % pipeExt[1]) cmds.addAttr(pipeExt[0], ln='Ext_Twist', k=True, dv=1) cmds.connectAttr('%s.Ext_Twist' % pipeExt[0], '%s.rotation' % pipeExt[1]) cmds.addAttr(pipeExt[0], ln='Ext_ComponentPivot', k=True, dv=1) cmds.connectAttr('%s.Ext_ComponentPivot' % pipeExt[0], '%s.useComponentPivot' % pipeExt[1]) curveGrpNode = cmds.createNode('transform', n='pipeCurves') cmds.parent(nurbsCir, curveGrpNode) cmds.parent(objSel, curveGrpNode) cmds.setAttr('%s.inheritsTransform' % curveGrpNode, 0) cmds.setAttr('%s.visibility' % curveGrpNode, 1) cmds.parent(curveGrpNode, pipeExt[0]) cmds.select(pipeExt[0]) if do_uvs == 1: cmds.polyLayoutUV(ps=0.2) cmds.polyEditUV(sv=1, su=self.uvRatio) cmds.polyEditUV(sv=0.95, su=0.95) cmds.select(pipeExt[0]) CentreUVs() if clean == 1: cmds.delete(ch=True) cmds.delete(curveGrpNode) cmds.select(pipeExt[0]) if thisIsAMesh == True: print 'hello' break
def _error(self, message): cmds.confirmDialog(title='Scene Name Error', message=message, icon='critical') cmds.error(message)
def adjustment_blend_selected(): sel = cmds.ls(sl=1) if not sel: cmds.warning("Nothing happened. Nothing selected.") return None for thing in sel: cmds.select(clear=True) cmds.select(thing) attributes = cmds.listAnimatable() for attribute in attributes: attribute = attribute.split('|')[-1] layer_membership = get_layer_membership(attribute) if len(layer_membership) > 2: cmds.error( "Selected channel belongs to more than two layers -> {}". format(layer_membership)) cmds.warning( "For proper use, the channel should belong to only BaseAnimation plus one anim layer to composite the offset." ) continue if len(layer_membership) < 2: print "No adjustment curve found for {}.".format(attribute) continue # This is much simpler: layers_curves = {} for layer in layer_membership: curves = cmds.animLayer( layer, q=True, findCurveForPlug=attribute) or [] for curve in curves: layers_curves[layer] = curve adjustment_range = [] adjustment_curve = '' base_curve = '' adjustment_layer = '' base_layer = '' for layer, curve in layers_curves.items(): if layer != cmds.animLayer(query=True, root=True): times = cmds.keyframe(curve, q=True, timeChange=True) adjustment_range = [min(times), max(times)] adjustment_curve = curve adjustment_layer = layer else: base_curve = curve base_layer = layer adjustment_range_filled = get_curve_range(base_curve, adjustment_curve) if len(adjustment_range_filled) < 3: print "No meaningful adjustment found for {0}".format( attribute) continue base_curve_values = [] for time in adjustment_range_filled: base_curve_values.append( cmds.keyframe(base_curve, query=True, time=(time, ), eval=True, valueChange=True, absolute=True)[0]) base_value_graph = [0.0] for i in xrange(len(base_curve_values)): if i > 0: current_value = base_curve_values[i] previous_value = base_curve_values[i - 1] base_value_graph.append(abs(current_value - previous_value)) adjustment_curve_values = [] for time in adjustment_range_filled: adjustment_curve_values.append( cmds.keyframe(adjustment_curve, query=True, time=(time, ), eval=True, valueChange=True, absolute=True)[0]) adjustment_value_graph = [0.0] for i in xrange(len(adjustment_curve_values)): if i > 0: current_value = adjustment_curve_values[i] previous_value = adjustment_curve_values[i - 1] adjustment_value_graph.append( abs(current_value - previous_value)) if sum(adjustment_value_graph) > sum(base_value_graph): print "sum({0}) is larger than sum({1}). This *may* lead to weird results. Or it might be fine.".format( adjustment_curve, base_curve) normalized_adjustment_value_graph = normalize_values( adjustment_value_graph) if abs(sum(base_value_graph)) > 0.0: normalized_base_value_graph = normalize_values( base_value_graph) else: # Be 'smart' about rotates and translates by bundling them for stragglers # Check neighboring axis other_value_graphs = {} current_axis = [ x for x in AXIS if (x in attribute.split('.')[-1]) ] or None if current_axis: for axis in AXIS: # Sorry if axis != current_axis[0]: adjacent_attribute = attribute.split( '.')[-1].replace(current_axis[0], axis) new_adjacent_attribute_name = attribute.replace( attribute.split('.')[-1], adjacent_attribute) adjacent_curve = cmds.animLayer( base_layer, q=True, findCurveForPlug=new_adjacent_attribute_name) if adjacent_curve: adjacent_curve_values = [] for time in adjustment_range_filled: value = cmds.keyframe(adjacent_curve, query=True, time=(time, ), eval=True, valueChange=True, absolute=True) or [] adjacent_curve_values.extend(value) adjacent_curve_value_graph = [0.0] for i in xrange(len(adjacent_curve_values)): if i > 0: current_value = adjacent_curve_values[ i] previous_value = adjacent_curve_values[ i - 1] adjacent_curve_value_graph.append( abs(current_value - previous_value)) other_value_graphs[ axis] = adjacent_curve_value_graph # Add the other axis together to see if it's non-zero added_graphs = [0.0 for x in adjustment_range_filled] for _, values in other_value_graphs.items(): for i, value in enumerate(values): added_graphs[i] += value # Normalize the added graphs normalized_base_value_graph = normalize_values( added_graphs) if normalized_base_value_graph: adjustment_curve_keys = cmds.keyframe(adjustment_curve, q=True, timeChange=True) adjustment_spans = zip(adjustment_curve_keys, adjustment_curve_keys[1:]) # Ok, this area got FUGLY but it works. Sorry. # TODO: Come back and make this not look like shit. for span in adjustment_spans: if span[-1] - 1.0 == span[0]: continue # Ignore please new_value_curve = [] sum_percentage = 0.0 adjustment_range_filled_cropped = [] adjustment_curve_values_cropped = [] cropped_base_value_graph = [] for index, time in enumerate(adjustment_range_filled): if time >= min(span) and time <= max(span): adjustment_range_filled_cropped.append(time) adjustment_curve_values_cropped.append( adjustment_curve_values[index]) cropped_base_value_graph.append( normalized_base_value_graph[index]) normalized_cropped_base_value_graph = normalize_values( cropped_base_value_graph) if normalized_cropped_base_value_graph: for i in xrange(len(adjustment_range_filled_cropped)): sum_percentage += normalized_cropped_base_value_graph[ i] # This will add up to 100 along the life of the curve new_value = map_from_to( sum_percentage, 0, 100, adjustment_curve_values_cropped[0], adjustment_curve_values_cropped[-1]) new_value_curve.append(new_value) # Now set the keys for index, time in enumerate( adjustment_range_filled_cropped): cmds.setKeyframe(adjustment_curve, animLayer=adjustment_layer, time=(time, ), value=new_value_curve[index]) else: for index, time in enumerate(adjustment_range_filled): cmds.setKeyframe( adjustment_curve, animLayer=adjustment_layer, time=(time, ), value=adjustment_curve_values[index]) else: for index, time in enumerate(adjustment_range_filled): cmds.setKeyframe(adjustment_curve, animLayer=adjustment_layer, time=(time, ), value=adjustment_curve_values[index]) cmds.select(clear=True) cmds.select(sel)
def armIconScale(): global arm_RefRig_offset # variables Initialization armType = cmds.radioButtonGrp("armType_Btn", q=True, sl=True) ikShape = cmds.optionMenu('ikIcon_Menu', q=True, sl=True) fkShape = cmds.optionMenu('fkIcon_Menu', q=True, sl=True) pvShape = cmds.optionMenu('pvIcon_Menu', q=True, sl=True) handShape = cmds.optionMenu('handIcon_Menu', q=True, sl=True) pvType = (cmds.radioButtonGrp('addPVElbow_Btn', q=True, sl=True)) - 1 selected = cmds.ls(sl=True, dag=True, type='joint') # check the selection is valid selectionCheck = cmds.ls(sl=1, type="joint") # check if something is selected if not selectionCheck: cmds.error("Please select any joint") # creating a temporary list transform_list = [] icon_test_list = [] # creating the ik icon # cube ik_box = cmds.curve(n='ik_arm_box_curve', d=1, p=[(1, 1, -1), (1, 1, 1), (1, -1, 1), (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, -1), (-1, -1, 1), (-1, 1, 1), (-1, 1, -1), (-1, -1, -1), (1, -1, -1), (1, -1, 1), (-1, -1, 1), (-1, 1, 1), (1, 1, 1)]) # cmds.rename (ik_box, 'ik_arm_box_curve') ik_box_List = cmds.ls(ik_box, dag=True) # 4 Arrows ik_arrows = cmds.curve(n='ik_arm_4arrows_curve', d=1, p=[(-1, 0, -3), (-2, 0, -3), (0, 0, -5), (2, 0, -3), (1, 0, -3), (1, 0, -1), (3, 0, -1), (3, 0, -2), (5, 0, 0), (3, 0, 2), (3, 0, 1), (1, 0, 1), (1, 0, 3), (2, 0, 3), (0, 0, 5), (-2, 0, 3), (-1, 0, 3), (-1, 0, 1), (-3, 0, 1), (-3, 0, 2), (-5, 0, 0), (-3, 0, -2), (-3, 0, -1), (-1, 0, -1), (-1, 0, -3)]) ik_arrows_List = cmds.ls(ik_arrows, dag=True) cmds.setAttr(ik_arrows_List[0] + '.rotateZ', -90) cmds.scale(0.2, 0.2, 0.2, ik_arrows_List[0], scaleXYZ=True) cmds.makeIdentity(ik_arrows_List[0], apply=True, t=1, r=1, s=1, pn=1) # 4 Pin ik_4pin = cmds.curve(n='ik_arm_4pin_curve', d=1, p=[(0, 0, 0), (0, 0, -2), (-1, 0, -2), (-1, 0, -4), (1, 0, -4), (1, 0, -2), (0, 0, -2), (0, 0, 0), (2, 0, 0), (2, 0, -1), (4, 0, -1), (4, 0, 1), (2, 0, 1), (2, 0, 0), (0, 0, 0), (0, 0, 2), (1, 0, 2), (1, 0, 4), (-1, 0, 4), (-1, 0, 2), (0, 0, 2), (0, 0, 0), (-2, 0, 0), (-2, 0, 1), (-4, 0, 1), (-4, 0, -1), (-2, 0, -1), (-2, 0, 0)]) ik_4pin_List = cmds.ls(ik_4pin, dag=True) cmds.setAttr(ik_4pin_List[0] + '.rotateY', 90) cmds.scale(0.2, 0.2, 0.2, ik_4pin_List[0], scaleXYZ=True) cmds.makeIdentity(ik_4pin_List[0], apply=True, t=1, r=1, s=1, pn=1) # Empty Groups Creation to put all the shapes for contrls in the parent ik_cntrl = cmds.group(empty=True, n='ARM_IK_SCALE_TEST_DONT_DELETE') curveIK = cmds.parent(ik_box_List[1], ik_arrows_List[1], ik_4pin_List[1], ik_cntrl, r=True, s=True) transform_list.append(ik_box_List[0]) transform_list.append(ik_arrows_List[0]) transform_list.append(ik_4pin_List[0]) # setting Visibility to just show what shape is selected in the UI if ikShape == 1: cmds.setAttr('curveShape2.v', 0) cmds.setAttr('curveShape3.v', 0) if ikShape == 2: cmds.setAttr('curveShape1.v', 0) cmds.setAttr('curveShape3.v', 0) if ikShape == 3: cmds.setAttr('curveShape1.v', 0) cmds.setAttr('curveShape2.v', 0) # positioning the control tempCONST = cmds.parentConstraint(selected[1], ik_cntrl, mo=False) cmds.delete(tempCONST) tempCONST = cmds.pointConstraint(selected[-1], ik_cntrl, mo=False) cmds.delete(tempCONST) cmds.parentConstraint(ik_cntrl, selected[-1], mo=True) icon_test_list.append(ik_cntrl) # create the FK Icon fk_circle = cmds.circle(n='fk_arm_circle_curve', c=(0, 0, 0), nr=(1, 0, 0), sw=360, r=1, d=3, ut=0, tol=0.01, s=1)[ 0] fk_circle_List = cmds.ls(fk_circle, dag=True) # 180 Arrows fk_turn = cmds.curve(n='fk_arm_turnarrows_curve', d=1, bez=False, p=[(0, 0, 0), (0, 0, 1), (0, 0, 2), (1, 0, 2), (0, 0, 3), (-1, 0, 2), (0, 0, 2), (0, 0, 1), (0, 0, 0), (0, 0, -1), (0, 0, -2), (-1, 0, -2), (0, 0, -3), (1, 0, -2), (0, 0, -2)]) fk_turn_List = cmds.ls(fk_turn, dag=True) cmds.setAttr(fk_turn_List[0] + '.rotateY', -90) cmds.setAttr(fk_turn_List[0] + '.rotateX', 90) cmds.makeIdentity(fk_turn_List[0], apply=True, t=1, r=1, s=1, n=0, pn=1) # empty group creation fk_cntrl = cmds.group(empty=True, n='ARM_FK_SCALE_TEST_DONT_DELETE') cmds.parent(fk_circle_List[1], fk_turn_List[1], fk_cntrl, r=True, s=True) transform_list.append(fk_circle_List[0]) transform_list.append(fk_turn_List[0]) # visibility to switch off the controls which are not selected in the gui if fkShape == 1: cmds.setAttr('curveShape4.v', 0) if fkShape == 2: cmds.setAttr(fk_circle + 'Shape.v', 0) # positioning the cntrl tempCONST = cmds.parentConstraint(selected[0], fk_cntrl, mo=False) cmds.delete(tempCONST) tempCONST = cmds.parentConstraint(fk_cntrl, selected[0], mo=True) icon_test_list.append(fk_cntrl) # creating the PV Icon # pv diamond pvDmnd = cmds.curve(d=1, n='pv_dmnd_curve', p=[(0.00664267, -0.0106004, 1), (1, -0.00526262, 0), (0, 2, 0), (0.00088465, -0.0106004, 1), (-1, -0.0106004, 0.0127566), (-0.00050717, 2, 0), (0.00088465, -0.0106004, -1), (-1, -0.0220406, 0), (0.00088465, -0.0106004, -1), (1.000885, -0.0106004, 0), (0.00176521, -2, -0.00452318), (0.00088465, -0.0106004, -1), (0.00176921, -2, 0), (-1, -0.0106004, 0), (0.00176771, -2, 0.00170249), (-0.00080412, -0.0106004, 1)]) pv_dmnd_List = cmds.ls(pvDmnd, dag=True) # pv Arrow creation pvArrow = cmds.curve(d=1, n='pv_arrow_curve', p=[(-2, 0, -1), (1, 0, -1), (1, 0, -2), (3, 0, 0), (1, 0, 2), (1, 0, 1), (-2, 0, 1), (-2, 0, -1)]) pv_arrow_List = cmds.ls(pvArrow, dag=True) cmds.xform(pvArrow, pivots=[0, 0, 0], ws=True) cmds.makeIdentity(pv_arrow_List[0], apply=True, t=1, r=1, s=1, n=0, pn=1) # empty group creation pvIcon = cmds.group(empty=True, n='ARM_PV_SCALE_TEST_DONT_DELETE') cmds.parent(pv_dmnd_List[1], pv_arrow_List[1], pvIcon, r=True, s=True) transform_list.append(pv_dmnd_List[0]) transform_list.append(pv_arrow_List[0]) # shape curve name # visibility to switch off the controls which are not selected in the gui if pvShape == 1: cmds.setAttr('curveShape6.v', 0) if pvShape == 2: cmds.setAttr('curveShape5.v', 0) icon_test_list.append(pvIcon) # making hand controls # circle Creation handCircle = cmds.circle(n='hand_circle_curve', c=(0, 0, 0), nr=(1, 0, 0), sw=360, r=1, d=3, ut=0, tol=0.01, s=1)[0] handCircle_List = cmds.ls(handCircle, dag=True) cmds.setAttr(handCircle + '.rotateX', 90) cmds.makeIdentity(handCircle, apply=True, t=1, r=1, s=1, n=0, pn=1) # cog Creation handCOG = cmds.circle(n='hand_cog_curve', c=(0, 0, 0), nr=(0, 1, 0), sw=360, r=1, d=3, ut=0, tol=0.01, s=16)[0] handCOG_List = cmds.ls(handCOG, dag=True) cmds.select(handCOG + ".cv[0]", handCOG + ".cv[2]", handCOG + ".cv[4]", handCOG + ".cv[6]", handCOG + ".cv[8]", handCOG + ".cv[10]", handCOG + ".cv[12]", handCOG + ".cv[14]") cmds.scale(0.480612, 0.480612, 0.480612) cmds.xform(handCOG, pivots=[0, 0, 0], ws=True) cmds.makeIdentity(handCOG, apply=True, t=1, r=1, s=1, n=0, pn=1) # empty group creation handIcon = cmds.group(empty=True, n='ARM_HAND_SCALE_TEST_DONT_DELETE') cmds.parent(handCircle_List[1], handCOG_List[1], handIcon, r=True, s=True) transform_list.append(handCircle_List[0]) transform_list.append(handCOG_List[0]) # visibility to switch off the controls which are not selected in the gui if handShape == 1: cmds.setAttr(handCOG + 'Shape.v', 0) if handShape == 2: cmds.setAttr(handCircle + 'Shape.v', 0) # positioning the control tempCONST = cmds.parentConstraint(selected[1], handIcon, mo=False) cmds.delete(tempCONST) tempCONST = cmds.parentConstraint(selected[-1], handIcon, mo=False) cmds.delete(tempCONST) icon_test_list.append(handIcon) # getting the pole vector location pvLoc = cmds.spaceLocator(p=(0, 0, 0), name='pv_local_loc') cmds.setAttr('pv_local_locShape.visibility', 0) pvgrp = cmds.group(pvLoc, name='pv_local_grp') pvoffset = cmds.group(pvIcon, name='pv_pos_grp') pvGrpMain = cmds.group(pvgrp, pvoffset, name='pv_main_grp') cmds.pointConstraint(selected[0], selected[-1], pvgrp, mo=False) cmds.aimConstraint(selected[0], pvgrp, mo=False, weight=1, aimVector=(1, 0, 0), upVector=(0, 1, 0), worldUpType="objectrotation") cmds.pointConstraint(selected[1], pvLoc, skip=["y", "z"], mo=False) cmds.pointConstraint(selected[1], pvoffset, mo=False) cmds.parentConstraint(selected[0], pvGrpMain, mo=True) cmds.aimConstraint(pvLoc, pvoffset, mo=False, aimVector=(0, 0, 1), upVector=(0, 0, 1), worldUpType="objectrotation") for each in ['.tx', '.ty', '.rx', '.ry', '.rz']: cmds.setAttr(pvIcon + each, lock=True, keyable=False, channelBox=False) # visiblity for the main controls if armType == 1: cmds.setAttr(ik_cntrl + '.v', 1) cmds.setAttr(fk_cntrl + '.v', 0) cmds.setAttr(handIcon + '.v', 0) cmds.setAttr(pvIcon + '.v', pvType) if armType == 2: cmds.setAttr(ik_cntrl + '.v', 0) cmds.setAttr(fk_cntrl + '.v', 1) cmds.setAttr(handIcon + '.v', 0) cmds.setAttr(pvIcon + '.v', 0) if armType == 3: cmds.setAttr(ik_cntrl + '.v', 1) cmds.setAttr(fk_cntrl + '.v', 1) cmds.setAttr(handIcon + '.v', 1) cmds.setAttr(pvIcon + '.v', pvType) # parenting all the preset arm rig armRefOffset = cmds.group(empty=True, n='arm_RefRig_offset') cmds.parent(ik_cntrl, fk_cntrl, handIcon, pvGrpMain, armRefOffset) # deleting old transform nodes for each in transform_list: cmds.delete(each) # setting the cntrl in refrence to length of joint jointVal = cmds.getAttr(selected[1] + '.tx') finalVal = (jointVal / 8) for each in icon_test_list: cmds.scale(finalVal, finalVal, finalVal, each)
def polyMeshCalculator(calculateMode,inputMesh1,inputMesh2,outputMesh): outputObj=MObject() inputDgPath1=MDagPath() inputObj2=MObject() skinNodeObj=MObject() tweakNodeObj=MObject() inputDgPath2=MDagPath() finalPos=MPoint() soucePos=MPoint() convertMatrix=MMatrix() selections=MSelectionList() selections.add(inputMesh1) selections.add(inputMesh2) selections.add(outputMesh) selections.getDependNode(2,outputObj) selections.getDagPath(0,inputDgPath1) fnDN=MFnDependencyNode() fnFinalMesh=MFnMesh(inputDgPath1) fnMatrix=MFnMatrixData() vtxIter=MItMeshVertex(outputObj) vtxIter.reset() if(calculateMode==1): skinClusterNodes=[] tweakNodes=[] inputs=mc.listHistory(inputMesh2) for i in inputs: if mc.nodeType(i)=='skinCluster': skinClusterNodes.append(i) if mc.nodeType(i)=='tweak': tweakNodes.append(i) if not skinClusterNodes: mc.error('Can\'t find any skin object!!') skinClusterNode=skinClusterNodes[0] tweakNode=tweakNodes[0] selections.add(skinClusterNode) selections.add(tweakNode) selections.getDependNode(1,inputObj2) selections.getDependNode(3,skinNodeObj) selections.getDependNode(4,tweakNodeObj) fnDN.setObject(skinNodeObj) weightListPlug=fnDN.findPlug('weightList') BPMatrixPlug=fnDN.findPlug('bindPreMatrix') matrixPlug=fnDN.findPlug('matrix') fnDN.setObject(inputObj2) skinObjMatrixPlug=fnDN.findPlug('worldMatrix').elementByLogicalIndex(0) skinMeshMatrixObj=skinObjMatrixPlug.asMObject() fnMatrix.setObject(skinMeshMatrixObj) skinMeshMatrixValue=fnMatrix.matrix() fnDN.setObject(tweakNodeObj) vlistPlug=fnDN.findPlug('vlist').elementByLogicalIndex(0).child(0) while not vtxIter.isDone(): index=vtxIter.index() pos=vtxIter.position() fnFinalMesh.getPoint(index,finalPos,MSpace.kObject) infJointWeightsPlug=weightListPlug.elementByLogicalIndex(index).child(0) infJointNum=infJointWeightsPlug.numElements() convertMatrix*=0 for i in range(infJointNum): infJointWeightPlug=infJointWeightsPlug.elementByPhysicalIndex(i) infJointIndex=infJointWeightPlug.logicalIndex() BPMatrixObj=BPMatrixPlug.elementByLogicalIndex(infJointIndex).asMObject() fnMatrix.setObject(BPMatrixObj) BPMatrixValue=fnMatrix.matrix() matrixObj=matrixPlug.elementByLogicalIndex(infJointIndex).asMObject() fnMatrix.setObject(matrixObj) matrixValue=fnMatrix.matrix() weightValue=infJointWeightsPlug.elementByLogicalIndex(infJointIndex).asDouble() tweakPointX=vlistPlug.elementByLogicalIndex(index).child(0).asDouble() tweakPointY=vlistPlug.elementByLogicalIndex(index).child(1).asDouble() tweakPointZ=vlistPlug.elementByLogicalIndex(index).child(2).asDouble() tweakPoint=MPoint(tweakPointX,tweakPointY,tweakPointZ) skinMatrix=BPMatrixValue*matrixValue*weightValue convertMatrix+=skinMatrix newPos=finalPos*skinMeshMatrixValue*convertMatrix.inverse()*skinMeshMatrixValue.inverse()-tweakPoint mc.xform(outputMesh+'.vtx[%d]'%index,os=1,a=1,t=[newPos.x,newPos.y,newPos.z]) vtxIter.next() else: selections.getDagPath(1,inputDgPath2) fnSouceMesh=MFnMesh(inputDgPath2) if(calculateMode==2): while not vtxIter.isDone(): index=vtxIter.index() pos=vtxIter.position() fnFinalMesh.getPoint(index,finalPos,MSpace.kObject) fnSouceMesh.getPoint(index,soucePos,MSpace.kObject) newPos=pos+MVector(finalPos)-MVector(soucePos) mc.xform(outputMesh+'.vtx[%d]'%index,os=1,a=1,t=[newPos.x,newPos.y,newPos.z]) vtxIter.next() if(calculateMode==3): while not vtxIter.isDone(): index=vtxIter.index() pos=vtxIter.position() fnFinalMesh.getPoint(index,finalPos,MSpace.kObject) fnSouceMesh.getPoint(index,soucePos,MSpace.kObject) newPos=finalPos+MVector(soucePos)-MVector(pos) mc.xform(outputMesh+'.vtx[%d]'%index,os=1,a=1,t=[newPos.x,newPos.y,newPos.z]) vtxIter.next()
def locator_segments(count, sels=[], from_curve=False): sels = get_sels(sels) curves = [] n_locs = [] step = 1.0 / (count + 1) if from_curve: step = 1.0 / (count - 1) #Create/gather selected curves if from_curve: for sel in sels[:]: sel = sel.partition('.')[0] shape = cmds.listRelatives(sel, shapes=True)[0] or [] if cmds.nodeType(shape) == 'nurbsCurve': curves.append(sel) if not curves: cmds.error('Select curve(s) to build segments.') else: if len(sels) < 2: cmds.error('Select at least 2 objects to build segments between.') for i in range(1, len(sels)): space1, space2 = 'pivot', 'pivot' if '.' in sels[i - 1]: space1 = 'center' if '.' in sels[i]: space2 = 'center' pos1 = get_position(sels[i - 1], space=space1)[0][1] pos2 = get_position(sels[i], space=space2)[0][1] curve = cmds.curve(d=1, p=[(pos1), (pos2)], k=[0, 1]) curves.append(curve) #Create motion paths and space new locators evenly along curve. for curve in curves: curve_shape = cmds.listRelatives(curve, shapes=True, fullPath=True)[0] motion_path = cmds.createNode('motionPath') cmds.setAttr('%s.fractionMode' % motion_path, 1) cmds.setAttr('%s.follow' % motion_path, 1) cmds.connectAttr('%s.worldSpace[0]' % curve_shape, '%s.geometryPath' % motion_path, f=True) for i in range(count): loc = cmds.spaceLocator(p=[0, 0, 0])[0] c_step = cmds.getAttr('%s.uValue' % motion_path) c_step = max(min(.9999, c_step + step), 0.0) if i == 0 and from_curve: c_step = 0.0001 cmds.setAttr('%s.uValue' % motion_path, c_step) cmds.connectAttr('%s.allCoordinates' % motion_path, '%s.translate' % loc, f=True) cmds.connectAttr('%s.rotate' % motion_path, '%s.rotate' % loc, f=True) cmds.disconnectAttr('%s.allCoordinates' % motion_path, '%s.translate' % loc) cmds.disconnectAttr('%s.rotate' % motion_path, '%s.rotate' % loc) n_locs.append(loc) cmds.delete(motion_path) if not from_curve: cmds.delete(curve) cmds.select(n_locs, r=True) return n_locs
cam_name = cam.name() cam_start = cam_name.split('_')[-2] cam_end = cam_name.split('_')[-1] frange = map(int, (playbackOptions(q=1, min=1), playbackOptions(q=1, max=1))) if not cmds.currentUnit(q=True, t=True) == 'film': # cmds.inViewMessage(amg=u'相机帧速率不对 <hl>!!!</hl>.', pos='midCenter', fade=1, backColor=0x16151515, a=1.0, fontSize=20) message = u'<font size="15"><b>相机帧速率不对<\font><br><b>' cmds.confirmDialog(title=u'提交检查', message=message, button=['Cancel', 'OK'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') cmds.error(u"相机帧速率不对") if int(cam_start) == frange[0]: print 'ok' else: # cmds.inViewMessage(amg=u'起始帧与相机不一样 <hl>!!!</hl>.', pos='midCenter', fade=1, backColor=0x16151515, a=1.0, # fontSize=20) message = u'<font size="15"><b>起始帧与相机不一样<\font><br><b>' cmds.confirmDialog(title=u'提交检查', message=message, button=['Cancel', 'OK'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') cmds.error(u"起始帧与相机不一样")
def Error(text): commands.error(text)
def align(nodes=None, axis='x', mode='mid'): # default node to selection if nothing provided if not nodes: nodes = cmds.ls(sl=True) # sl, selection if not nodes: cmds.error('Nothing selected or provied') _nodes = [] for node in nodes: if '.f[' in node: node = cmds.polyListComponentConversion(node, fromFace=True, toVertex=True) elif '.e[' in node: node = cmds.polyListComponentConversion(node, fromEdge=True, toVertex=True) cmds.select(node) node = cmds.ls(sl=True, fl=True) #sl, select. fl, flatten _nodes.extend(node) nodes = _nodes if axis == 'x': start = 0 elif axis == 'y': start = 1 elif axis == 'z': start = 2 else: cmds.error('Unknown Axis') minMode = mode == 'min' maxMode = mode == 'max' midMode = mode == 'mid' bboxes = {} values = [] # gets the dimension of our objects for node in nodes: if '.vtx[' in node: ws = cmds.xform(node, q=True, t=True, ws=True) # q, query. t, tranform. ws, world space minValue = midValue = maxValue = ws[start] else: bbox = cmds.exactWorldBoundingBox(node) # bbox, bounding box minValue = bbox[start] maxValue = bbox[start + 3] midValue = (minValue + maxValue) / 2 bboxes[node] = (minValue, midValue, maxValue) #print minValue, maxValue, midValue if minMode: values.append(minValue) elif maxMode: values.append(maxValue) else: values.append(midValue) # we calculate the alignment point if minMode: target = min(values) elif maxMode: target = max(values) else: target = sum(values) / len(values) # get the average #print target # figure out the distance to the target for node in nodes: bbox = bboxes[node] minValue, midValue, maxValue = bbox ws = cmds.xform(node, query=True, translation=True, ws=True) # ws, world space width = maxValue - minValue if minMode: distance = minValue - target ws[start] = (minValue - distance) + width / 2 elif maxMode: distance = target - maxValue ws[start] = (maxValue + distance) - width / 2 else: distance = target - midValue ws[start] = midValue + distance # move the objecct to the target cmds.xform(node, translation=ws, ws=True) pass