我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用maya.cmds.objExists()。
def unique(name): assert isinstance(name, basestring), "`name` must be string" while cmds.objExists(name): matches = re.findall(r"\d+$", name) if matches: match = matches[-1] name = name.rstrip(match) number = int(match) + 1 else: number = 1 name = name + str(number) return name
def get_node_in_namespace_hierarchy(node, namespace=None, shape=False): """Searches a namespace and all nested namespaces for the given node. :param node: Name of the node. :param namespace: Root namespace :param shape: True to get the shape node, False to get the transform. :return: The node in the proper namespace. """ if shape and node and cmds.objExists(node): node = get_shape(node) if node and cmds.objExists(node): return node if node and namespace: # See if it exists in the namespace or any child namespaces namespaces = [namespace.replace(':', ''),] namespaces += cmds.namespaceInfo(namespace, r=True, lon=True) or [] for namespace in namespaces: namespaced_node = '{0}:{1}'.format(namespace, node) if shape: namespaced_node = get_shape(namespaced_node) if namespaced_node and cmds.objExists(namespaced_node): return namespaced_node return None
def mirror(joint, search_for, replace_with): joints = [joint, ] + (cmds.listRelatives(joint, ad=True, path=True) or []) for joint in joints: mirrored_joint = joint.replace(search_for, replace_with) if cmds.objExists(mirrored_joint): translate = list(cmds.getAttr('{0}.t'.format(joint))[0]) parent = cmds.listRelatives(joint, parent=True, path=True) if parent and search_for not in parent[0]: translate[2] *= -1.0 else: translate = [x * -1.0 for x in translate] cmds.setAttr('{0}.t'.format(mirrored_joint), *translate) rotate = cmds.getAttr('{0}.r'.format(joint))[0] cmds.setAttr('{0}.r'.format(mirrored_joint), *rotate) scale = cmds.getAttr('{0}.s'.format(joint))[0] cmds.setAttr('{0}.s'.format(mirrored_joint), *scale)
def assert_hierarachies_match(self): self.assertEqual(7, len(cmds.ls(type='joint'))) # Make sure the joint orients are the same translates = [cmds.getAttr('{0}.t'.format(x))[0] for x in cmds.ls(type='joint')] rotates = [cmds.getAttr('{0}.r'.format(x))[0] for x in cmds.ls(type='joint')] orients = [cmds.getAttr('{0}.jo'.format(x))[0] for x in cmds.ls(type='joint')] for orient, new_orient in zip(self.orients, orients): self.assertListAlmostEqual(orient, new_orient) for translate, new_translate in zip(self.translates, translates): self.assertListAlmostEqual(translate, new_translate) for rotate, new_rotate in zip(self.rotates, rotates): self.assertListAlmostEqual(rotate, new_rotate) # The geometry should not have been exported self.assertFalse(cmds.objExists(self.cube)) self.assertTrue(cmds.objExists(self.group)) self.assertEqual('joint1', cmds.listRelatives(self.group, children=True)[0])
def BT_ConnectSetup(set = None): if not set or not cmds.objExists(set): return False if BT_IsSetupConnected(set = set): cmds.warning('Setup already connected!') return False btNode = cmds.getAttr(set +'.Blend_Node') if not btNode or not cmds.objExists(btNode): return False transforms = cmds.listConnections(set +'.dagSetMembers') for i in range(0, len(transforms)): try: BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i]) except: pass mults = cmds.listConnections(btNode, d = True, type = 'multiplyDivide') if mults: cmds.delete(mults) return True
def ResetSceneAnim(): # Loop through them all SceneJoints = cmds.ls(type="joint") # Loop for name in SceneJoints: # Disconnect if required ResetBoneKeyframes(DagPathFromJoint(name, False).transform()) # Check for undo if (cmds.objExists(name + ".seanimUndoT")): # Reset to it ResetTranslation = cmds.getAttr(name + ".seanimUndoT")[0] ResetScale = cmds.getAttr(name + ".seanimUndoS")[0] ResetRotation = cmds.getAttr(name + ".seanimUndoR")[0] # Apply cmds.setAttr(name + ".t", ResetTranslation[0], ResetTranslation[1], ResetTranslation[2]) cmds.setAttr(name + ".scale", ResetScale[0], ResetScale[1], ResetScale[2]) cmds.setAttr(name + ".r", 0, 0, 0) cmds.setAttr(name + ".jo", ResetRotation[0], ResetRotation[1], ResetRotation[2]) # Remove notetracks if cmds.objExists("SENotes"): # Delete cmds.delete("SENotes") # Processes a joint, creating it's rest position, and returning a dag path
def texture_sampler(texture, uvs_list=None): ''' Create a textureSampler node :param texture_node: Path to texture node like "ramp1" :param uvs_list: List of uvs like [(0.0, 0.5), (0.5, 1.0)] ''' texture_attr = texture + '.outColor' if not cmds.objExists(texture_attr): raise Exception('texture must have an outColor attribute') texture_node = cmds.shadingNode('textureSampler', asUtility=True) sampler = TextureSampler(texture_node) sampler.inColor = texture_attr uvs_list = uvs_list or [(0.5, 0.5)] sampler.set_uvs(uvs_list) return sampler
def add_curve_to_system(curve_shape, hair_system=None): if hair_system is None: selection = cmds.ls(sl=True, dag=True, leaf=True, type='hairSystem') if selection: hair_system = selection[0] else: hair_system = create_hair_system() follicle_nodes, out_curve_nodes = curve_to_hair(curve_shape, hair_system) follicles_grp = hair_system + 'Follicles' if not cmds.objExists(follicles_grp): cmds.group(empty=True, name=follicles_grp) cmds.parent(follicle_nodes[0], follicles_grp) outcurves_grp = hair_system + 'OutputCurves' if not cmds.objExists(outcurves_grp): cmds.group(empty=True, name=outcurves_grp) cmds.parent(out_curve_nodes[0], outcurves_grp) return follicle_nodes
def attr(self, attr): # self.validCheck() if self._cache: if attr in self._cache_attribute: return self._cache_attribute[attr] attrname = self.name()+u"."+attr if cmds.objExists(attrname): _attribute = Attribute(attrname, cache=self._cache) if self._cache: self._cache_attribute[attr] = _attribute return _attribute else: attrname = self.name() + u"." + self._MPlug.partialName() + attr if cmds.objExists(attrname): _attribute = Attribute(attrname, cache=self._cache) if self._cache: self._cache_attribute[attr] = _attribute return _attribute else: raise AttributeError("%r has no attribute or method named '%s'" % (self, attr))
def lock(): """Lock scene Add an invisible node to your Maya scene with the name of the current file, indicating that this file is "locked" and cannot be modified any further. """ if not cmds.objExists("lock"): with lib.maintained_selection(): cmds.createNode("objectSet", name="lock") cmds.addAttr("lock", ln="basename", dataType="string") # Permanently hide from outliner cmds.setAttr("lock.verticesOnlySet", True) fname = cmds.file(query=True, sceneName=True) basename = os.path.basename(fname) cmds.setAttr("lock.basename", basename, type="string")
def _cleanup(name): """Removes un-used nodes on import of obj """ # Don't delete the old mesh if gozbruh_delete option var exists and is set to # false, simply rename it if cmds.optionVar(ex='gozbruh_delete') and not cmds.optionVar(q='gozbruh_delete'): if cmds.objExists(name): cmds.rename(name, name + '_old') else: if cmds.objExists(name): cmds.delete(name) for node in GARBAGE_NODES: node = name + '_' + node if cmds.objExists(node): cmds.delete(node) #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------
def getParent(self,name, filter=None): if cmds.objExists(name): if cmds.nodeType(name) == 'mesh': name = cmds.listRelatives(name, p=True, f=True) par = cmds.listRelatives(name, p=True, f=True) if par: parent = par[0].split('|')[-1] if filter: tok = self.tokenPrefix(filter) for t in tok: if t in parent: return parent return self.getParent(par[0], filter) else: return parent else: return 'NoParent'
def parent_group(source, transferTransform=True): """Create and transfer transforms to parent group""" assert cmds.objExists(source), "%s does not exist" % source assert cmds.nodeType(source) == "transform", ( "%s must be transform" % source) parent = cmds.listRelatives(source, parent=True) if transferTransform: group = cmds.createNode("transform", n="%s_parent" % source) match_transform(group, source) try: cmds.parent(source, group) except Exception: cmds.warning("Failed to parent child under new parent") cmds.delete(group) if parent: cmds.parent(group, parent[0]) else: cmds.select(source) group = cmds.group(n="%s_parent" % source) return group
def _set_uuid(node): """Add mbID to `node` Unless one already exists. """ attr = "{0}.mbID".format(node) if not cmds.objExists(attr): cmds.addAttr(node, longName="mbID", dataType="string") _, uid = str(uuid.uuid4()).rsplit("-", 1) cmds.setAttr(attr, uid, type="string")
def create_curves(curves): for curve in curves: create_curve(curve) # Now parent the curves for curve in curves: if curve.get('parent'): parent = curve['parent'] if cmds.objExists(parent): cmds.parent(curve['name'], parent) # Then create the stacks for curve in curves: if curve.get('stack'): create_transform_stack(curve['name'], curve['stack'])
def execute(self): cmds.loadPlugin('cmt_py', qt=True) for container in self.swingtwists: driver = container['driver'].value() driven = container['driven'].value() if not cmds.objExists(driver) or not cmds.objExists(driven): logger.warning('{0} or {1} does not exist.'.format(driver, driven)) continue logger.info('Creating swingtwist on {0} from {1}'.format(driven, driver)) name = container['name'].value() twist = container['twist'].value() swing = container['swing'].value() twist_axis = 'XYZ'.index(container['twist_axis'].value()) cmds.swingTwist(driver, driven, name=name, twist=twist, swing=swing, twistAxis=twist_axis)
def test_execute_component_with_array_of_containers(self): data = { 'spheres': [ {'sphere_name': 'sphere1', 'radius': 2.5}, {'sphere_name': 'sphere2', 'radius': 5.0}, ] } comp = ContainerComponent() comp.set_data(data) comp.execute() self.assertTrue(cmds.objExists('sphere1')) self.assertEqual(2.5, cmds.getAttr('polySphere1.radius')) self.assertTrue(cmds.objExists('sphere2')) self.assertEqual(5.0, cmds.getAttr('polySphere2.radius'))
def test_instantiate_component_from_constructor(self): name = 'blah_blah' comp = Component(sphere_name=name, radius=10.0) self.assertFalse(cmds.objExists(name)) comp.execute() self.assertTrue(cmds.objExists(name)) self.assertEqual(10.0, cmds.getAttr('polySphere1.radius'))
def test_execute_queue(self): queue = core.ComponentQueue() comp = Component(sphere_name='sphere1') queue.add(comp) comp = Component(sphere_name='sphere2') queue.add(comp) queue.execute() self.assertTrue(cmds.objExists('sphere1')) self.assertTrue(cmds.objExists('sphere2'))
def test_disable_component(self): queue = core.ComponentQueue() comp = Component(sphere_name='sphere1', enabled=False) queue.add(comp) comp = Component(sphere_name='sphere2') queue.add(comp) queue.execute() self.assertFalse(cmds.objExists('sphere1')) self.assertTrue(cmds.objExists('sphere2'))
def test_component_break_point(self): queue = core.ComponentQueue() comp = Component(sphere_name='sphere1', break_point=True) queue.add(comp) comp = Component(sphere_name='sphere2') queue.add(comp) queue.execute() self.assertTrue(cmds.objExists('sphere1')) self.assertFalse(cmds.objExists('sphere2'))
def test_export_queue(self): queue = core.ComponentQueue() comp1 = Component(sphere_name='sphere1') queue.add(comp1) comp2 = Component(sphere_name='sphere2') queue.add(comp2) file_path = self.get_temp_filename('queue.json') queue.export(file_path) queue = core.load_queue(file_path) queue.execute() self.assertTrue(cmds.objExists('sphere1')) self.assertTrue(cmds.objExists('sphere2'))
def test_import_skin(self): file_path = self.get_temp_filename('temp.skin') skinio.export_skin(file_path, self.shape) cmds.delete(self.skin) skinio.import_skin(file_path) self.assertTrue(cmds.objExists(self.skin))
def validate(self): errors = [] camera = self.cameras.currentText() if not cmds.objExists(camera): errors.append("{} : Selected camera '{}' " "does not exist!".format(self.id, camera)) self.cameras.setStyleSheet(self.highlight) else: self.cameras.setStyleSheet("") return errors
def connectSetup(self): uiSet = str(self.ui.setEdit.text()) if not uiSet: return False if not cmds.objExists(uiSet): return False BT_ConnectSetup(set = uiSet) return True
def disconnectSetup(self): uiSet = str(self.ui.setEdit.text()) if not uiSet: return False if not cmds.objExists(uiSet): return False BT_DisconnectSetup(set = uiSet) return True
def BT_IsSetupConnected(set = None): if not set or not cmds.objExists(set): return None #test the first transform in the set setItems = cmds.listConnections(set +'.dagSetMembers') if not setItems: return None connections = cmds.listConnections(setItems[0], source = True, type = 'BlendTransforms') if connections: return True return False
def BT_DisconnectSetup(set = None): if not set: return False if not BT_IsSetupConnected(set = set): cmds.warning('Setup already disconnected!') return False btNode = cmds.getAttr(set +'.Blend_Node') if not btNode or not cmds.objExists(btNode): return False numOutputs = cmds.getAttr(btNode +'.output', size = True) print numOutputs tempMult = None for i in range(0, numOutputs): conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputT', s = False, d = True) if conns: tempMult = cmds.createNode('multiplyDivide') cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputT', conns[0] +'.translate') cmds.connectAttr(btNode +'.output[' +str(i) +'].outputT', tempMult +'.input1') conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputR', s = False, d = True) if conns: tempMult = cmds.createNode('multiplyDivide') cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputR', conns[0] +'.rotate') cmds.connectAttr(btNode +'.output[' +str(i) +'].outputR', tempMult +'.input1') conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputS', s = False, d = True) if conns: tempMult = cmds.createNode('multiplyDivide') cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputS', conns[0] +'.scale') cmds.connectAttr(btNode +'.output[' +str(i) +'].outputS', tempMult +'.input1') cmds.select(cl = True) return True
def PlaceNote(): # Notetrack number note_tracks = 0 # We need to ask for a name if not (cmds.objExists("SENotes")): # We need to make the SENotes parent first base_track = cmds.spaceLocator() # Rename cmds.rename(base_track, "SENotes") # Notetrack name noteName = "new_notetrack" + str(note_tracks) # Now we can make the child (if you have > 50000 notetracks, we got a problem...) for npos in xrange(note_tracks, 50000): # Setup noteName = "new_notetrack" + str(npos) # Check if not (cmds.objExists(noteName)): # Exit break # Now make it and parent it notetrack = cmds.spaceLocator() # Rename cmds.rename(notetrack, noteName) # Parent it mel.eval("parent " + noteName + " SENotes") # Get current time currentFrame = cmds.currentTime(query = True) # Key it cmds.setKeyframe(noteName, time = currentFrame) # Log it print("A new notetrack was created") # Selects all bones
def DagPathFromJoint(name, needsRest=True): # Check for it if not cmds.objExists(name): # Not found in scene return False # Check to add if needsRest: # Check for the attr (to set rest pos) if not cmds.objExists(name + ".seanimUndoT"): # We need to setup the undo data ResetTranslation = cmds.getAttr(name + ".t")[0] ResetScale = cmds.getAttr(name + ".scale")[0] ResetRotation = cmds.getAttr(name + ".jo")[0] # Make the attributes cmds.addAttr(name, longName="seanimUndoT", dataType="double3", storable=True) cmds.addAttr(name, longName="seanimUndoS", dataType="double3", storable=True) cmds.addAttr(name, longName="seanimUndoR", dataType="double3", storable=True) # Set them cmds.setAttr(name + ".seanimUndoT", ResetTranslation[0], ResetTranslation[1], ResetTranslation[2], type="double3") cmds.setAttr(name + ".seanimUndoS", ResetScale[0], ResetScale[1], ResetScale[2], type="double3") cmds.setAttr(name + ".seanimUndoR", ResetRotation[0], ResetRotation[1], ResetRotation[2], type="double3") # Make selector sList = OpenMaya.MSelectionList() # Add it sList.add(name) # New Path dResult = OpenMaya.MDagPath() # Set it sList.getDagPath(0, dResult) # Return return dResult # Disconnects a MDagPath from it's input keyframes
def attr(self, attr): self.validCheck() if self._cache: if attr in self._cache_attribute: return self._cache_attribute[attr] attrname = self.name()+u"."+attr if cmds.objExists(attrname): _attribute = Attribute(attrname, cache=self._cache) if self._cache: self._cache_attribute[attr] = _attribute return _attribute else: raise AttributeError("%r has no attribute or method named '%s'" % (self, attr))
def hasAttr(self, attr): if isinstance(attr, basestring): if u"[" in attr or u"." in attr: return cmds.objExists(self.name()+"."+attr) else: return self._MFn.hasAttribute(attr) elif attr.__class__.__name__ == Attribute.__name__: return self._MFn.hasAttribute(attr.attrName())
def toggleMeshVisibility(self): mesh = self.sourceField.text() if not mesh: return if not cmds.objExists(mesh): return try: cmds.setAttr(mesh + '.visibility', not bool(cmds.getAttr(mesh + '.visibility'))) except Exception as e: print(e)
def toggleMushVisbility(self): mush = self.sourceField.text() if not mush: return mush += '_Mush' if not cmds.objExists(mush): return try: cmds.setAttr(mush + '.visibility', not bool(cmds.getAttr(mush + '.visibility'))) except Exception as e: print(e)
def createMush(self): mesh = self.sourceField.text() if not mesh: return if cmds.objExists(mesh + '_Mush'): print(mesh + '_Mush already exists!') return cmds.currentTime(cmds.playbackOptions(q=True, min=True)) dup = cmds.duplicate(mesh, inputConnections=True, n=mesh + '_Mush') cmds.deltaMush(dup, smoothingIterations=20, smoothingStep=0.5, pinBorderVertices=True, envelope=1)
def deleteMush(self): mesh = self.sourceField.text() if not mesh: return if not cmds.objExists(mesh + '_Mush'): return cmds.delete(mesh + '_Mush')