我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用maya.cmds.sets()。
def get_outputs(self): """ Retrieve all settings of each available sub widgets :return: """ inputs = self.get_inputs(as_preset=False) outputs = dict() outputs['off_screen'] = inputs['off_screen'] import capture_gui.lib # Get isolate view members of the active panel if inputs['isolate_view']: panel = capture_gui.lib.get_active_editor() filter_set = mc.modelEditor(panel, query=True, viewObjects=True) isolate = mc.sets(filter_set, query=True) if filter_set else None outputs['isolate'] = isolate return outputs
def copyShader(src = "", tgts = [], *args): """ gets the shader from the src and assigns it to the tgt objs Args: src (string): the object we're getting the shader FROM tgts (list[strings]): the objects we're setting the shaders TO """ confirm = confirmDialog("Should I copy shaders?") if confirm == "Yes": for tgt in tgts: shp = cmds.listRelatives(src, s=True)[0] sg = cmds.listConnections(shp, t="shadingEngine")[0] tshp = cmds.listRelatives(tgt, s=True)[0] cmds.sets(tshp, e=True, forceElement=sg) else: print "Copy shader assignment cancelled" return()
def copySkinComponents(source, destinationVerts): if not mc.listRelatives(source, shapes=True): raise RuntimeError('Source object must be geometry.') sourceSkin = getSkinCluster(source) if not sourceSkin: raise RuntimeError("Source mesh doesn't have a skinCluster to copy from.") destMesh = mc.ls(destinationVerts[0], o=True)[0] destMesh = mc.listRelatives(destMesh, parent=True)[0] destSkin = copySkinInfluences(source, destMesh) tempSet = mc.sets(destinationVerts) mc.select(source, tempSet) mc.copySkinWeights(noMirror=True, surfaceAssociation='closestPoint', influenceAssociation='closestJoint', normalize=True) mc.delete(tempSet) mc.select(destinationVerts)
def apply_shaders(relationships, namespace=None): """Given a dictionary of `relationships`, apply shaders to meshes Arguments: relationships (avalon-core:shaders-1.0): A dictionary of shaders and how they relate to meshes. """ if namespace is not None: # Append namespace to shader group identifier. # E.g. `blinn1SG` -> `Bruce_:blinn1SG` relationships = { "%s:%s" % (namespace, shader): relationships[shader] for shader in relationships } for shader, ids in relationships.items(): print("Looking for '%s'.." % shader) shader = next(iter(cmds.ls(shader)), None) assert shader, "Associated shader not part of asset, this is a bug" for id_ in ids: mesh, faces = (id_.rsplit(".", 1) + [""])[:2] # Find all meshes matching this particular ID # Convert IDs to mesh + id, e.g. "nameOfNode.f[1:100]" meshes = list( ".".join([mesh, faces]) for mesh in avalon.maya.lib.lsattr("mbID", value=mesh) ) if not meshes: continue print("Assigning '%s' to '%s'" % (shader, ", ".join(meshes))) cmds.sets(meshes, forceElement=shader)
def create_ncloth(input_mesh): """Replace Create nCloth menu item This performs the identical option of nCloth -> Create nCloth with the following changes. 1. Input mesh not made intermediate 2. Current mesh and shape named "currentMesh" Arguments: input_mesh (str): Path to shape """ assert cmds.nodeType(input_mesh) == "mesh", ( "%s was not of type mesh" % input_mesh) nucleus = cmds.createNode("nucleus", name="nucleus1") ncloth = cmds.createNode("nCloth", name="nClothShape1") current_mesh = cmds.createNode("mesh", name="currentMesh") cmds.connectAttr(input_mesh + ".worldMesh[0]", ncloth + ".inputMesh") cmds.connectAttr(ncloth + ".outputMesh", current_mesh + ".inMesh") cmds.connectAttr("time1.outTime", nucleus + ".currentTime") cmds.connectAttr("time1.outTime", ncloth + ".currentTime") cmds.connectAttr(ncloth + ".currentState", nucleus + ".inputActive[0]") cmds.connectAttr(ncloth + ".startState", nucleus + ".inputActiveStart[0]") cmds.connectAttr(nucleus + ".outputObjects[0]", ncloth + ".nextState") cmds.connectAttr(nucleus + ".startFrame", ncloth + ".startFrame") # Assign default shader cmds.sets(current_mesh, addElement="initialShadingGroup") return current_mesh
def process(self, name, namespace, context, data): from maya import cmds self[:] = cmds.file( self.fname, namespace=namespace, reference=True, returnNewNodes=True, groupReference=True, groupName=namespace + ":" + name ) # Assign default shader to meshes meshes = cmds.ls(self, type="mesh") cmds.sets(meshes, forceElement="initialShadingGroup")
def process(self, instance): from maya import cmds missing = list() for member in ("controls_SET", "out_SET"): if member not in instance: missing.append(member) assert not missing, "\"%s\" is missing members: %s" % ( instance, ", ".join("\"" + member + "\"" for member in missing)) # Ensure all output has IDs. # As user may inadvertently add to the out_SET without # realising, and some of the new members may be non-meshes, # or meshes without and ID missing = list() for node in cmds.sets("out_SET", query=True) or list(): # Only check transforms with shapes that are meshes shapes = cmds.listRelatives(node, shapes=True) or list() meshes = cmds.ls(shapes, type="mesh") if not meshes: continue try: self.log.info("Checking '%s'" % node) cmds.getAttr(node + ".mbID") except ValueError: missing.append(node) assert not missing, ("Missing ID attribute on: %s" % ", ".join(missing))
def process(self, instance): import os from maya import cmds # Resources are optional if "resources_SEL" not in instance: return resources = dict() for resource in cmds.sets("resources_SEL", query=True): if cmds.nodeType(resource) == "reference": path = cmds.referenceQuery(resource, filename=True, unresolvedName=True) elif cmds.nodeType(resource) == "AlembicNode": path = cmds.getAttr(resource + ".abc_File") else: # Unsupported path = None resources[resource] = path # All resources were resolved assert all(resources.values()), ( "Unsupported resource(s): " + ", ".join("'%s': '%s'" % (resource, path) for resource, path in resources.items() if path is not None) ) # No resource contains an absolute path assert not any(os.path.isabs(fname) for fname in resources), ( "Some resources are absolute: " + ", ".join(resources) )
def assignShaderList(self, *args): #assign the list of shaders to the geo in the new scene #check about namespaces, etc. How to deal with that? type in a namespace? #select the top node then use the | to split split the names of the objects #check-top node replaces top node, then replace on each object the first bit with selection, then other bits with SEL|thenRest . . . # #use this code to assign shadingGrp "sg" to object "obj" # cmds.sets(obj, fe=sg) pass
def process(self): nodes = list() if (self.options or {}).get("useSelection"): nodes = cmds.ls(selection=True) instance = cmds.sets(nodes, name=self.name) lib.imprint(instance, self.data) return instance
def apply_shaders(relationships, namespace=None): """Given a dictionary of `relationships`, apply shaders to meshes Arguments: relationships (avalon-core:shaders-1.0): A dictionary of shaders and how they relate to meshes. """ if namespace is not None: # Append namespace to shader group identifier. # E.g. `blinn1SG` -> `Bruce_:blinn1SG` relationships = { "%s:%s" % (namespace, shader): relationships[shader] for shader in relationships } for shader, ids in relationships.items(): print("Looking for '%s'.." % shader) shader = next(iter(cmds.ls(shader)), None) assert shader, "Associated shader not part of asset, this is a bug" for id_ in ids: mesh, faces = (id_.rsplit(".", 1) + [""])[:2] # Find all meshes matching this particular ID # Convert IDs to mesh + id, e.g. "nameOfNode.f[1:100]" meshes = list(".".join([mesh, faces]) for mesh in lsattr("mbID", value=mesh)) if not meshes: continue print("Assigning '%s' to '%s'" % (shader, ", ".join(meshes))) cmds.sets(meshes, forceElement=shader)
def remove(container): """Remove an existing `container` from Maya scene Deprecated; this functionality is replaced by `api.remove()` Arguments: container (avalon-core:container-1.0): Which container to remove from scene. """ node = container["objectName"] # Assume asset has been referenced reference_node = next((node for node in cmds.sets(node, query=True) if cmds.nodeType(node) == "reference"), None) assert reference_node, ("Imported container not supported; " "container must be referenced.") log.info("Removing '%s' from Maya.." % container["name"]) namespace = cmds.referenceQuery(reference_node, namespace=True) fname = cmds.referenceQuery(reference_node, filename=True) cmds.file(fname, removeReference=True) try: cmds.delete(node) except ValueError: # Already implicitly deleted by Maya upon removing reference pass try: # If container is not automatically cleaned up by May (issue #118) cmds.namespace(removeNamespace=namespace, deleteNamespaceContent=True) except RuntimeError: pass
def create_object(verts_pos, face_verts): """ Function creates an object with mesh given by vertice and face data. :type face_verts: Python list :type verts_pos: Python list """ shark_mesh = om.MObject() points = om.MFloatPointArray() # An array that is storing positions od vertices. Do not include id of vertices for vert in verts_pos: # add every point to Maya float points array p = om.MFloatPoint(vert[0], vert[2], -vert[1]) points.append(p) face_connects = om.MIntArray() # an array for vertice numbers per face. face_counts = om.MIntArray() # an array for total number of vertices per face for verts in face_verts: # In Maya mesh is created on a base of two arrays: list of vertice numbers and list of numbers of vertices # of faces. Vertice numbers from the first list are not grouped by faces, this is just a one dimmension array. # Based on this list only it would be impossible to recreate mesh, becouse number of vertices in faces may vary # (in this example every face have 3 vertices, but this is not obligatory). # The second array stores the number of vertices of faces. From this list Mata gets a number of vertices of a # face, let's call it N, then assigns next N vertices to this face. The process is repeated for every face. face_connects.append(verts[0]) # Append vertices of face. face_connects.append(verts[1]) face_connects.append(verts[2]) face_counts.append(len(verts)) # append the number of vertices for this face mesh_fs = om.MFnMesh() mesh_fs.create(points, face_counts, face_connects, parent=shark_mesh) mesh_fs.updateSurface() node_name = mesh_fs.name() cmds.polySoftEdge(node_name, a=30, ch=1) # Automatically soften the edges of the mesh # assign new mesh to default shading group cmds.sets(node_name, e=True, fe='initialShadingGroup') return cmds.listRelatives(node_name, fullPath=True, parent=True) # node name stores a name of Shape node. # Most functions need a Transform node. Ths line returns it.
def clone(shape, worldspace=False): """Clone `shape` Arguments: shape (str): Absolute path to shape worldspace (bool, optional): Whether or not to consider worldspace Returns: node (str): Newly created clone """ type = cmds.nodeType(shape) assert type in ("mesh", "nurbsSurface", "nurbsCurve"), ( "clone() works on polygonal and nurbs surfaces") src, dst = { "mesh": (".outMesh", ".inMesh"), "nurbsSurface": (".local", ".create"), "nurbsCurve": (".local", ".create"), }[type] nodetype = cmds.nodeType(shape) name = lib.unique(name=shape.rsplit("|")[-1]) clone = cmds.createNode(nodetype, name=name) cmds.connectAttr(shape + src, clone + dst, force=True) if worldspace: transform = cmds.createNode("transformGeometry", name=name + "_transformGeometry") cmds.connectAttr(shape + src, transform + ".inputGeometry", force=True) cmds.connectAttr(shape + ".worldMatrix[0]", transform + ".transform", force=True) cmds.connectAttr(transform + ".outputGeometry", clone + dst, force=True) # Assign default shader cmds.sets(clone, addElement="initialShadingGroup") return clone
def auto_connect_assets(src, dst): """Attempt to automatically two assets Arguments: src (str): Name of source reference node dst (str): Name of destination reference node Raises: StopIteration on missing in_SET """ in_set = None for node in cmds.referenceQuery(dst, nodes=True): if node.endswith("in_SET"): in_set = node break for input_transform in cmds.sets(in_set, query=True): mbid = cmds.getAttr(input_transform + ".mbID") input_shape = cmds.listRelatives(input_transform, shapes=True)[0] for output_transform in lib.lsattr("mbID", value=mbid): ref = cmds.referenceQuery(output_transform, referenceNode=True) if ref != src: continue print("Connecting %s -> %s" % (output_transform, input_transform)) output_shape = cmds.listRelatives(output_transform, shapes=True)[0] try: auto_connect(output_transform, input_transform) except RuntimeError: # Already connected pass try: auto_connect(output_shape, input_shape) except RuntimeError: # Already connected pass
def process(self, context): from maya import cmds for objset in cmds.ls("*.id", long=True, # Produce full names type="objectSet", # Only consider objectSets recursive=True, # Include namespace objectsOnly=True): # Return objectSet, rather # than its members is_empty = cmds.sets(objset, query=True) is None if is_empty: self.log.info("%s skipped, it was empty." % objset) continue if not cmds.objExists(objset + ".id"): continue if cmds.getAttr(objset + ".id") not in ( "pyblish.avalon.instance", # Backwards compatibility "pyblish.mindbender.instance"): continue # The developer is responsible for specifying # the family of each instance. assert cmds.objExists(objset + ".family"), ( "\"%s\" was missing a family" % objset) data = dict() # Apply each user defined attribute as data for attr in cmds.listAttr(objset, userDefined=True) or list(): try: value = cmds.getAttr(objset + "." + attr) except Exception: # Some attributes cannot be read directly, # such as mesh and color attributes. These # are considered non-essential to this # particular publishing pipeline. value = None data[attr] = value name = cmds.ls(objset, long=False)[0] # Use short name instance = context.create_instance(data.get("name", name)) instance[:] = cmds.sets(objset, query=True) or list() instance.data.update(data) # Produce diagnostic message for any graphical # user interface interested in visualising it. self.log.info("Found: \"%s\" " % instance.data["name"])
def create(name, family): """Create new instance Associate nodes with a name and family. These nodes are later validated, according to their `family`, and integrated into the shared environment, relative their `name`. Data relative each family, along with default data, are imprinted into the resulting objectSet. This data is later used by extractors and finally asset browsers to help identify the origin of the asset. Arguments: name (str): Name of instance family (str): Name of family Raises: NameError on `name` already exists KeyError on invalid dynamic property RuntimeError on host error """ for item in api.registered_families(): if item["name"] == family: break assert item is not None, "{0} is not a valid family".format(family) data = api.registered_data() + item.get("data", []) # Convert to dictionary data = dict((i["key"], i["value"]) for i in data) instance = "%s_SEL" % name if cmds.objExists(instance): raise NameError("\"%s\" already exists." % instance) instance = cmds.sets(name=instance) # Resolve template for key, value in data.items(): try: data[key] = value.format( name=name, family=family ) except KeyError as e: raise KeyError("Invalid dynamic property: %s" % e) lib.imprint(instance, data) cmds.select(instance, noExpand=True) return instance
def process(self, context): from maya import cmds try: # Assertion also made in pyblish_starter.install() # but as plug-ins can be used vanilla, the check # must also be made here. import pyblish_maya assert pyblish_maya.is_setup() except (ImportError, AssertionError): raise RuntimeError("pyblish-starter requires pyblish-maya " "to have been setup.") for objset in cmds.ls("*.id", long=True, # Produce full names type="objectSet", # Only consider objectSets recursive=True, # Include namespace objectsOnly=True): # Return objectSet, rather # than its members if not cmds.objExists(objset + ".id"): continue if not cmds.getAttr(objset + ".id") == "pyblish.starter.instance": continue # The developer is responsible for specifying # the family of each instance. assert cmds.objExists(objset + ".family"), ( "\"%s\" was missing a family" % objset) name = cmds.ls(objset, long=False)[0] # Use short name instance = context.create_instance(name) instance[:] = cmds.sets(objset, query=True) or list() # Apply each user defined attribute as data for attr in cmds.listAttr(objset, userDefined=True) or list(): try: value = cmds.getAttr(objset + "." + attr) except: # Some attributes cannot be read directly, # such as mesh and color attributes. These # are considered non-essential to this # particular publishing pipeline. value = None instance.data[attr] = value # Produce diagnostic message for any graphical # user interface interested in visualising it. self.log.info("Found: \"%s\" " % instance.data["name"])
def containerise(name, namespace, nodes, context, loader=None, suffix="CON"): """Bundle `nodes` into an assembly and imprint it with metadata Containerisation enables a tracking of version, author and origin for loaded assets. Arguments: name (str): Name of resulting assembly namespace (str): Namespace under which to host container nodes (list): Long names of nodes to containerise context (dict): Asset information loader (str, optional): Name of loader used to produce this container. suffix (str, optional): Suffix of container, defaults to `_CON`. Returns: container (str): Name of container assembly """ container = cmds.sets(nodes, name="%s_%s_%s" % (namespace, name, suffix)) data = [ ("schema", "avalon-core:container-2.0"), ("id", "pyblish.avalon.container"), ("name", name), ("namespace", namespace), ("loader", str(loader)), ("representation", context["representation"]["_id"]), ] for key, value in data: if not value: continue if isinstance(value, (int, float)): cmds.addAttr(container, longName=key, attributeType="short") cmds.setAttr(container + "." + key, value) else: cmds.addAttr(container, longName=key, dataType="string") cmds.setAttr(container + "." + key, value, type="string") main_container = cmds.ls(AVALON_CONTAINERS, type="objectSet") if not main_container: main_container = cmds.sets(empty=True, name=AVALON_CONTAINERS) else: main_container = main_container[0] cmds.sets(container, addElement=main_container) return container
def prepare_scene(path): """ The function sets the basic parameters of the scene: time range and render settings. :param path: string - The directory with necessary files """ cmds.playbackOptions(min=0, max=260) # Set the animation range cmds.autoKeyframe(state=False) # Make sure, that the AutoKey button is disabled plugins_dirs = mel.getenv("MAYA_PLUG_IN_PATH") # Mental Ray plugin is necessaryfor this script to run propperly. # Next lines check if the plugin is avaible and installs it or displays an allert window. # The plugins are accualy files placed in "MAYA_PLUG_IN_PATH" directories, so this script gets those paths # and checks if there is a mental ray plugin file. for plugins_dir in plugins_dirs.split(';'): for filename in glob.glob(plugins_dir + '/*'): # For every filename in every directory of MAYA_PLUG_IN_PATH if 'Mayatomr.mll' in filename: # if there is a mental ray plugin file then make sure it is loaded if not cmds.pluginInfo('Mayatomr', query=True, loaded=True): cmds.loadPlugin('Mayatomr', quiet=True) cmds.setAttr('defaultRenderGlobals.ren', 'mentalRay', type='string') # Set the render engine to MR # Next lines are a workaround for some bugs. The first one is that the render settings window has to be # opened before setting attributes of the render. If it would not be, thhen Maya would display an error # saying that such options do not exist. # The second bug is that after running this scrpt the window was blank and it was impossible to set # parameters. This is a common bug and it can be repaired by closing this window with # cmds.deleteUI('unifiedRenderGlobalsWindow') command cmds.RenderGlobalsWindow() cmds.refresh(f=True) cmds.deleteUI('unifiedRenderGlobalsWindow') cmds.setAttr('miDefaultOptions.finalGather', 1) cmds.setAttr('miDefaultOptions.miSamplesQualityR', 1) cmds.setAttr('miDefaultOptions.lightImportanceSamplingQuality', 2) cmds.setAttr('miDefaultOptions.finalGather', 1) break else: continue break else: print("Mental Ray plugin is not avaible. It can be found on the Autodesk website: ", "https://knowledge.autodesk.com/support/maya/downloads/caas/downloads/content/", "mental-ray-plugin-for-maya-2016.html") alert_box = QtGui.QMessageBox() alert_box.setText("Mental Ray plugin is not avaible. It can be found on the Autodesk website: " + "https://knowledge.autodesk.com/support/maya/downloads/caas/downloads/content/" + "mental-ray-plugin-for-maya-2016.html") alert_box.exec_() cam = cmds.camera(name="RenderCamera", focusDistance=35, position=[-224.354, 79.508, 3.569], rotation=[-19.999,-90,0]) # create camera to set background (imageplane) # Set Image Plane for camera background cmds.imagePlane(camera=cmds.ls(cam)[1], fileName=(path.replace("\\", "/") + '/bg.bmp')) cmds.setAttr("imagePlaneShape1.depth", 400) cmds.setAttr("imagePlaneShape1.fit", 4)