def __init__(self, mObj): self.mObject = mObj plugin_queue = [i for i in self.KNOWN if i not in (CommandBase, UndoableBase)] for plugin in plugin_queue: MGlobal.displayInfo("deregistering plugin %s" % plugin) plugin_obj = MFnPlugin(mObj) try: plugin_obj.deregisterCommand(plugin.NAME) except: MGlobal.displayError("Unable to unload plugin %s" % plugin) finally: self.KNOWN.remove(plugin)
def skinClusterData(skinCluster, meshPath, component): # now if we have a skincluster lets fill in the blanks we had before selectionList2 = MGlobal.getSelectionListByName(skinCluster[0]) skinObj = selectionList2.getDependNode(0) skinFn = MFnSkinCluster(skinObj) indexMap = {y: x for x, y in getJointIndexMap(skinCluster[0]).items()} jointWeights = skinFn.getWeights(meshPath, component)[0] return indexMap, jointWeights
def scaleAlongVector(self, scaleValue, scaleDirectionVector): """ For proper results this method assumes that scaleDirectionVector is on the same plane as WireSection (in world space). """ self.isWireProfileDataModified = True self.wireProfileDataModified = WireProfileData( self.wireProfileData.getSubprofileList()) scaleDirectionVectorLocalSpace = scaleDirectionVector * self.modelMatrix.asMatrixInverse( ) scaleDirectionVectorLocalSpace.z = 0.0 if (scaleDirectionVectorLocalSpace != MVector(0.0, 0.0, 0.0)): self.wireProfileDataModified.scaleAlongVector( scaleValue, scaleDirectionVectorLocalSpace) else: MGlobal.displayWarning( "Could not scale wire section along provided vector.")
def getDag(name): sel_list = omg.getSelectionListByName(name) print(sel_list) # ''' iterator = om.MItSelectionList(sel_list, om.Mfn.kDagNode) dagPath = om.MDagPath() result = [] if not iterator.isDone(): iterator.getDagPath(dagPath) result = [dagPath] ''' return result
def __init__(self, mObj): self.mObject = mObj plugin_queue = [i for i in self.KNOWN if i not in (CommandBase, UndoableBase)] for plugin in plugin_queue: MGlobal.displayInfo("registering plugin %s" % plugin) vendor = getattr(plugin, 'VENDOR', 'plugger module') version = getattr(plugin, 'VERSION', "0.9") apiversion = getattr(plugin, "API_VERSION", "Any") plugin_obj = MFnPlugin(mObj, vendor, version, apiversion) try: plugin_obj.registerCommand(plugin.NAME, plugin.creator, plugin.syntax) except RuntimeError as e: MGlobal.displayError("Unable to load plugin %s" % plugin) MGlobal.displayError(traceback.format_exc(e)) finally: self.KNOWN.remove(plugin)
def uninitializePlugin(mObj): fnPlugin = MFnPlugin(mObj) #-------------------------------------------------------------------------# # CLEANUP #-------------------------------------------------------------------------# # DELETE WIRE TOOLS MENU ITEM global g_wireToolsMenuItemID if (g_wireToolsMenuItemID != ""): cmds.deleteUI(g_wireToolsMenuItemID, menuItem=True) #-------------------------------------------------------------------------# # DATA #-------------------------------------------------------------------------# # WIRE PROFILE DATA try: fnPlugin.deregisterData(WireProfileData.dataID) except: MGlobal.displayError("Failed to deregister " + WireProfileData.dataName + " data!") #-------------------------------------------------------------------------# # COMMANDS #-------------------------------------------------------------------------# # WIRE MESH FROM CURVE try: fnPlugin.deregisterCommand(WireMeshFromCurveCommand.commandName) except: MGlobal.displayError("Failed to deregister " + WireMeshFromCurveCommand.commandName + " command!") #-------------------------------------------------------------------------# # NODES #-------------------------------------------------------------------------# # WIRE MESH CREATOR NODE try: fnPlugin.deregisterNode(WireMeshCreatorNode.nodeID) except: MGlobal.displayError("Failed to deregister " + WireMeshCreatorNode.nodeName + " node!")
def initializePlugin(mObj): fnPlugin = MFnPlugin(mObj, "Piotr Makal", "0.2.1", "Any") #-------------------------------------------------------------------------# # INITIALIZATION CODE #-------------------------------------------------------------------------# # ADD MENU ITEM (WIRE TOOLS) global g_wireToolsMenuItemID try: # build Maya's Create menu # Since Maya doesn't build menus (their contents) on startup but rather # on demand (when user clicks specific menu) we need to invoke special # MEL procedure to make sure our menu item will be added when plugin is # loaded but user still haven't clicked on a specific menu (i.e. Create menu). parentMenu = pm.melGlobals["$gMainCreateMenu"] pm.mel.eval("ModCreateMenu " + parentMenu) # MAYA_LOCATION/scripts/startup # check for possible insert positions menuItemList = cmds.menu(parentMenu, itemArray=True, query=True) if "createCurveTools" in menuItemList: insertAfterMenuItem = "createCurveTools" else: insertAfterMenuItem = menuItemList[ 6] # more or less the position I want # add menu item with submenu g_wireToolsMenuItemID = cmds.menuItem("wireTools", label="Wire Tools", parent=parentMenu, insertAfter=insertAfterMenuItem, subMenu=True, tearOff=True) # add nested menu items # I'm using old API addMenuItem method because: (1) new API 2.0 does not # have it; (2) using cmds.menuItem to add menu item will result in situation # in which you click on menu item holding Ctrl+Shift to add it to shelf as # a button and Maya will attach pointer to Python function instead of actual # Python command when button on the shelf is clicked - this will cause Maya # to lose track of that pointer next time Maya is opened and clicking that # button on the shelf will cause warning/error and nothing else. oldFnPlugin = oldOMMpx.MFnPlugin() oldFnPlugin.addMenuItem("Wire Mesh from Curve", g_wireToolsMenuItemID, WireMeshFromCurveCommand.commandName, "-oneNodePerCurve false", False, "", "-image \"shelf_wireMeshFromCurve.png\"") except: if (g_wireToolsMenuItemID != ""): cmds.deleteUI(g_wireToolsMenuItemID, menuItem=True) g_wireToolsMenuItemID = "" MGlobal.displayWarning( "Could not add Wire Tools menu item to Maya's Create menu.") #-------------------------------------------------------------------------# # DATA #-------------------------------------------------------------------------# # WIRE PROFILE DATA wireProfileDataRegistrationFlag = True try: fnPlugin.registerData(WireProfileData.dataName, WireProfileData.dataID, WireProfileData.dataCreator, MPxData.kData) except: MGlobal.displayError("Failed to register " + WireProfileData.dataName + " data!") wireProfileDataRegistrationFlag = False #-------------------------------------------------------------------------# # COMMANDS #-------------------------------------------------------------------------# # WIRE MESH FROM CURVE try: fnPlugin.registerCommand(WireMeshFromCurveCommand.commandName, WireMeshFromCurveCommand.commandCreator, WireMeshFromCurveCommand.commandSyntax) except: MGlobal.displayError("Failed to register " + WireMeshFromCurveCommand.commandName + " command!") #-------------------------------------------------------------------------# # NODES #-------------------------------------------------------------------------# # WIRE MESH CREATOR NODE if (wireProfileDataRegistrationFlag == True): try: fnPlugin.registerNode(WireMeshCreatorNode.nodeName, WireMeshCreatorNode.nodeID, WireMeshCreatorNode.nodeCreator, WireMeshCreatorNode.nodeInitializer, MPxNode.kDependNode) except: MGlobal.displayError("Failed to register " + WireMeshCreatorNode.nodeName + " node!") else: MGlobal.displayError("Because " + WireProfileData.dataName + " data failed to be registered, " + WireMeshCreatorNode.nodeName + " node also can not be registered.")
def print_error(self): MGlobal.displayError('Python API 2.0 Error')
def exportAllMeshes(source, target, isSkinned=False): if source: cmds.file(source, open=True, force=True) if isSkinned: skinnedJoints = exportSkeleton(target) else: skinnedJoints = [] with open(target, 'wb') as fh: # write version fh.write(b'MSH\0MAYA') meshes = cmds.ls(type='mesh', ni=True, l=True) # write mesh count fh.write(struct.pack('<I', len(meshes))) for mesh in meshes: # write mesh name name = mesh.encode('utf8') fh.write(struct.pack('<I', len(name))) fh.write(name) # write material name try: lambert = cmds.listConnections(cmds.listConnections( mesh, type='shadingEngine'), d=False, s=True, type='lambert')[0] except: lambert = '' material = lambert.encode('utf8') fh.write(struct.pack('<I', len(material))) fh.write(material) # get API handles to object name selectionList = MGlobal.getSelectionListByName(mesh) dagPath = selectionList.getDagPath(0) polyIterator = MItMeshPolygon(dagPath) meshFn = MFnMesh(dagPath) jointWeights = [] logicalIndexMap = {} physicalToLogicalMap = {} if isSkinned: # if we flag the mesh as skinned lets have a look if we have a skincluster # some of these values are predetermined so if it turns out not to be skinned then we leave it alone skinCluster = cmds.ls(cmds.listHistory(mesh), type="skinCluster") if skinCluster: meshPath, component = selectionList.getComponent(0) logicalIndexMap, jointWeights = skinClusterData( skinCluster, meshPath, component) physicalToLogicalMap = { physicalIndex: logicalIndex for (physicalIndex, logicalIndex) in enumerate(logicalIndexMap.keys()) } else: isSkinned = False # extract mesh data in 1 go, uses more memory but faster to execute and I assume a duplicate of 1 mesh will fit in memory normals = meshFn.getNormals(MSpace.kWorld) tangents = meshFn.getTangents(MSpace.kWorld) uvSetNames = meshFn.getUVSetNames() colorSetNames = meshFn.getColorSetNames() # write attribute layout now we know all the attributes floatsPerVertex = 3 + 3 + 3 + len(uvSetNames) * 2 + len( colorSetNames) * 4 + int(isSkinned) * 8 # num attributes fh.write( struct.pack( '<I', 3 + len(uvSetNames) + len(colorSetNames) + int(isSkinned) * 2)) # write position, normal and tangent attributes: semantic & nr of floats fh.write( struct.pack('<II', VertexAttribute.Semantic.POSITION.value, 3)) fh.write( struct.pack('<II', VertexAttribute.Semantic.NORMAL.value, 3)) fh.write( struct.pack('<II', VertexAttribute.Semantic.TANGENT.value, 3)) for i, n in enumerate(uvSetNames): assert i < 8, 'We currently only anticipated 8 texcoords, please use a color set instead.' fh.write( struct.pack('<II', VertexAttribute.Semantic.TEXCOORD0.value + i, 2)) for i, n in enumerate(colorSetNames): fh.write( struct.pack('<II', VertexAttribute.Semantic.COLOR0.value + i, 4)) if isSkinned: fh.write( struct.pack('<II', VertexAttribute.Semantic.BLENDINDICES.value, 4)) fh.write( struct.pack('<II', VertexAttribute.Semantic.BLENDWEIGHT.value, 4)) # storage vertexDataHashes = {} vertexData = [] indexData = [] # pre-alloc uvSets = [None] * len(uvSetNames) colorSets = [None] * len(colorSetNames) vertexChunk = [0.0] * floatsPerVertex # walk mesh faces while not polyIterator.isDone(): positions, vertexIndices = polyIterator.getTriangles( MSpace.kWorld) # get colors and uvs for this face for index, n in enumerate(uvSetNames): u, v = polyIterator.getUVs(n) uvSets[index] = (u, v, n) for index, n in enumerate(colorSetNames): c = polyIterator.getColors(n) colorSets[index] = (c, n) # itr.getNormals(normals, MSpace.kWorld) untriangulatedVertexIndices = polyIterator.getVertices() localVertexIndices = { j: i for i, j in enumerate(untriangulatedVertexIndices) } # walk face triangulation for i in range(len(vertexIndices)): localVertexIndex = localVertexIndices[vertexIndices[i]] # build vertex data for this face-vertex P = positions[i] N = normals[polyIterator.normalIndex(localVertexIndex)] T = tangents[polyIterator.tangentIndex(localVertexIndex)] vertexChunk[: 9] = P.x, P.y, P.z, N.x, N.y, N.z, T.x, T.y, T.z j = 9 for u, v, n in uvSets: vertexChunk[j] = u[localVertexIndex] vertexChunk[j + 1] = v[localVertexIndex] j += 2 for c, n in colorSets: C = c[localVertexIndex] vertexChunk[j] = C.r vertexChunk[j + 1] = C.g vertexChunk[j + 2] = C.b vertexChunk[j + 3] = C.a j += 4 if isSkinned: jointCount = len(logicalIndexMap) weightRange = list( jointWeights[vertexIndices[i] * jointCount:(vertexIndices[i] + 1) * jointCount]) highToLow = sorted(enumerate(weightRange), key=lambda pair: -pair[1]) MAX_INDICES = 4 padded = highToLow[:MAX_INDICES] + [ (0, 0.0) ] * (MAX_INDICES - len(highToLow)) factor = sum(pair[1] for pair in padded) if factor: factor = 1.0 / factor for index, (jointId, weight) in enumerate(padded): # this jointId is local to this skin-cluster, # use the indexMap to extract the name and then map it to a global jointId logicalIndex = physicalToLogicalMap[jointId] index = logicalIndexMap[logicalIndex] vertexChunk[j + index] = skinnedJoints.get( index, 0) vertexChunk[j + MAX_INDICES + index] = weight * factor # normalized j += MAX_INDICES * 2 vertex = tuple(vertexChunk) hsh = hash(vertex) # reuse vertex data if possible n = len(vertexDataHashes) vertexId = vertexDataHashes.setdefault(hsh, n) if vertexId == n: vertexData.append(vertex) # build index buffer indexData.append(vertexId) polyIterator.next() # write buffer sizes fh.write( struct.pack('<II', len(vertexData) * floatsPerVertex, len(indexData))) # write mesh data for vertex in vertexData: fh.write(struct.pack('<%if' % floatsPerVertex, *vertex)) fh.write(struct.pack('<%iI' % len(indexData), *indexData))
import pymel.core as pm from maya.api.OpenMaya import MTransformationMatrix, MGlobal, MSelectionList, MFnDagNode, MMatrix, MFnTransform, MFnMatrixAttribute import maya.api.OpenMaya as om dgn = MFnDagNode() mobj = om.MObject() m_dagPath = om.MDagPath() mattr = MFnMatrixAttribute() sel = MGlobal.getActiveSelectionList() # selection srcDagpath = sel.getDependNode(0) # first node srctransform_node = MFnTransform(srcDagpath) # MFnTransform srcBaseMtx = srctransform_node.transformation().asMatrix() # matrix srcName = (dgn.setObject(sel.getDagPath(0))).name() #dagname srcPym = pm.PyNode(srcName) #dagPynode tgtDagpath = sel.getDependNode(1) # first node tgttransform_node = MFnTransform(tgtDagpath) # MFnTransform tgtBaseMtx = tgttransform_node.transformation().asMatrix() # matrix tgtName = (dgn.setObject(sel.getDagPath(1))).name() #dagname tgtPym = pm.PyNode(tgtName) #dagPynode srcBattr = mattr.create("srcBaseMtx", "mm") #createAttr srctransform_node.addAttribute(srcBattr) #addAttr srcPym.srcBaseMtx.set(srcBaseMtx) #setAttronPym tgtBAttr = mattr.create("tgtBaseMtx", "mm") #createAttr srctransform_node.addAttribute(tgtBAttr) #addAttr srcPym.tgtBaseMtx.set(tgtBaseMtx) #setAttronPym