def connectShapeVis(*args):
"""Connects the attr from the assoc. text field to the shape Visibility of selected objects"""
sel = cmds.ls(sl=True, type="transform")
driver = cmds.textFieldButtonGrp(widgets["toShapeVis"], q=True, tx=True)
if sel:
if driver:
for obj in sel:
shapes = cmds.listRelatives(obj, s=True)
for shape in shapes:
try:
cmds.connectAttr(driver, "%s.v" % shape, f=True)
cmds.warning("Connected %s to %s" % (driver, shape))
except:
cmds.warning("Couldn't connect %s to %s. Sorry! Check the Script Editor." % (driver, shape))
else:
cmds.warning("You need to select an object to connect the shape.vis!")
python类listRelatives()的实例源码
def shape_from_element(element):
"""Return shape of given 'element'
Supports components, meshes, and surfaces
"""
try:
# Get either shape or transform, based on element-type
node = cmds.ls(element, objectsOnly=True)[0]
except:
cmds.warning("Could not find node in %s" % element)
return None
if cmds.nodeType(node) == 'transform':
try:
return cmds.listRelatives(node, shapes=True)[0]
except:
cmds.warning("Could not find shape in %s" % element)
return None
else:
return node
def get_goz_objs():
"""Grab meshes from selection, filter out extraneous DAG objects and
freeze transforms on objects.
"""
objs = cmds.ls(selection=True, type='mesh', dag=True)
if objs:
xforms = cmds.listRelatives(objs, parent=True, fullPath=True)
# freeze transform
cmds.makeIdentity(xforms, apply=True, t=1, r=1, s=1, n=0)
cmds.select(xforms)
objs = cmds.ls(selection=True)
return objs
#------------------------------------------------------------------------------
# Renaming
#------------------------------------------------------------------------------
def create(obj):
"""Tell ZBrush to treat `obj` as a new object.
Under the hood this changes a gozbruhBrush ID to match object name.
"""
# does not change selection:
cmds.delete(obj, constructionHistory=True)
shape = cmds.ls(obj, type='mesh', dag=True)[0]
xform = cmds.listRelatives(shape, parent=True, fullPath=True)[0]
goz_check_xform = cmds.attributeQuery(
'gozbruhBrushID', node=xform, exists=True)
goz_check_shape = cmds.attributeQuery(
'gozbruhBrushID', node=shape, exists=True)
if goz_check_shape:
cmds.setAttr(shape + '.gozbruhBrushID', obj, type='string')
if goz_check_xform:
cmds.setAttr(xform + '.gozbruhBrushID', obj, type='string')
return xform
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 isNodeVisible(node):
'''
Simply return whether or not the node can be seen.
'''
if not mc.attributeQuery('visibility', node=node, exists=True):
return False
if not mc.getAttr(node+'.v'):
return False
if mc.attributeQuery('intermediateObject', node=node, exists=True):
if mc.getAttr(node+'.intermediateObject'):
return False
if not mc.getAttr(node+'.lodVisibility'):
return False
if mc.getAttr(node+'.overrideEnabled') and not mc.getAttr(node+'.overrideVisibility'):
return False
parent = mc.listRelatives(node, parent=True, pa=True)
if parent:
return isNodeVisible(parent[0])
return True
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 getSkinCluster(mesh):
'''
Return the first skinCluster affecting this mesh.
'''
if mc.nodeType(mesh) in ('mesh','nurbsSurface','nurbsCurve'):
shapes = [mesh]
else:
shapes = mc.listRelatives(mesh, shapes=True, path=True)
for shape in shapes:
history = mc.listHistory(shape, groupLevels=True, pruneDagObjects=True)
if not history:
continue
skins = mc.ls(history, type='skinCluster')
if skins:
return skins[0]
return None
def colorShape(obj, rgb=None, hsv=None):
if not rgb:
if hsv and len(hsv) == 3:
rgb = colorsys.hsv_to_rgb(*hsv)
else:
raise RuntimeError('colorShape requires an rgb or hsv input.')
mc.setAttr('{}.overrideEnabled'.format(obj), 1)
mc.setAttr('{}.overrideRGBColors'.format(obj), 1)
mc.setAttr('{}.overrideColorRGB'.format(obj), *rgb)
shapes = mc.listRelatives(obj, shapes=True, pa=True)
for shape in shapes:
#if mc.getAttr('{}.overrideEnabled'.format(shape)):
mc.setAttr('{}.overrideEnabled'.format(shape), 1)
mc.setAttr('{}.overrideRGBColors'.format(shape), 1)
mc.setAttr('{}.overrideColorRGB'.format(shape), *rgb)
def run_command(self, *args):
curve_sel = self.curve_name()
vert_sel_list = cmds.ls(sl=True, fl = True)
if '.' in vert_sel_list[0]:
dummy_item_index = vert_sel_list[0].index('.')
self.geo_name = vert_sel_list[0][0:dummy_item_index]
Chain_Constrain(curve_sel, vert_sel_list, self.geo_name)
Spline_Rig_Chain(curve_sel, vert_sel_list)
self.chain_list = cmds.listRelatives(str(self.geo_name + '_geo_grp'))
joint_list = cmds.ls(type = 'joint')
for dummy_geo in self.chain_list:
cmds.select(dummy_geo, add = True)
for dummy_joint in joint_list:
if 'ikHandle' in dummy_joint:
pass
elif curve_sel in dummy_joint:
cmds.select(dummy_joint, add=True)
cmds.select('ikHandle*', d = True)
mel.eval('newBindSkin " -byClosestPoint -toSkeleton";')
def match_transform(src, dst):
"""Transform `src` to `dst`, taking worldspace into account
Arguments:
src (str): Absolute path to source transform
dst (str): Absolute path to destination transform
"""
try:
parent = cmds.listRelatives(src, parent=True)[0]
except Exception:
parent = None
node_decompose = cmds.createNode("decomposeMatrix")
node_multmatrix = cmds.createNode("multMatrix")
connections = {
dst + ".worldMatrix": node_multmatrix + ".matrixIn[0]",
node_multmatrix + ".matrixSum": node_decompose + ".inputMatrix",
node_decompose + ".outputTranslate": src + ".translate",
node_decompose + ".outputRotate": src + ".rotate",
node_decompose + ".outputScale": src + ".scale",
}
if parent:
connections.update({
parent + ".worldInverseMatrix": node_multmatrix + ".matrixIn[1]"
})
for s, d in connections.iteritems():
cmds.connectAttr(s, d, force=True)
cmds.refresh()
cmds.delete([node_decompose, node_multmatrix])
def combine(nodes):
"""Produce a new mesh with the contents of `nodes`
Arguments:
nodes (list): Path to shapes
"""
unite = cmds.createNode("polyUnite", n=nodes[0] + "_polyUnite")
count = 0
for node in nodes:
# Are we dealing with transforms, or shapes directly?
shapes = cmds.listRelatives(node, shapes=True) or [node]
for shape in shapes:
try:
cmds.connectAttr(shape + ".outMesh",
unite + ".inputPoly[%s]" % count, force=True)
cmds.connectAttr(shape + ".worldMatrix",
unite + ".inputMat[%s]" % count, force=True)
count += 1
except Exception:
cmds.warning("'%s' is not a polygonal mesh" % shape)
if count:
output = cmds.createNode("mesh", n=nodes[0] + "_combinedShape")
cmds.connectAttr(unite + ".output", output + ".inMesh", force=True)
return output
else:
cmds.delete(unite)
return None
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 create_ncloth():
selection = cmds.ls(selection=True)[0]
input_mesh = cmds.listRelatives(selection, shapes=True)[0]
current_mesh = commands.create_ncloth(input_mesh)
# Optionally append suffix
comp = selection.rsplit("_", 1)
suffix = ("_" + comp[-1]) if len(comp) > 1 else ""
cmds.rename(current_mesh, "currentMesh%sShape" % suffix)
# Mimic default nCloth command
cmds.hide(selection)
def process(self, instance):
from maya import cmds
has_multiple_shapes = list()
# Consider entire hierarchy of nodes included in an Instance
hierarchy = cmds.listRelatives(instance, allDescendents=True)
# Consider only nodes of type="mesh"
meshes = cmds.ls(hierarchy, type="mesh", long=True)
transforms = cmds.listRelatives(meshes, parent=True)
for transform in set(transforms):
shapes = cmds.listRelatives(transform, shapes=True) or list()
# Ensure the one child is a shape
has_single_shape = len(shapes) == 1
self.log.info("has single shape: %s" % has_single_shape)
# Ensure the one shape is of type "mesh"
has_single_mesh = (
has_single_shape and
cmds.nodeType(shapes[0]) == "mesh"
)
self.log.info("has single mesh: %s" % has_single_mesh)
if not all([has_single_shape, has_single_mesh]):
has_multiple_shapes.append(transform)
assert not has_multiple_shapes, (
"\"%s\" has transforms with multiple shapes: %s" % (
instance, ", ".join(
"\"" + member + "\"" for member in has_multiple_shapes))
)
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):
from maya import cmds
nodes = list(instance)
nodes += cmds.listRelatives(instance, allDescendents=True) or list()
missing = list()
for node in nodes:
# Only check transforms with shapes that are meshes
if not cmds.nodeType(node) == "transform":
continue
shapes = cmds.listRelatives(node,
shapes=True,
type="mesh") 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 getShapes(node):
"""Returns the shape of the dagNode
Arguments:
node (dagNode): The input node to search the shape
Returns:
list: The shapes of the node
"""
return node.listRelatives(shapes=True)
def findComponentChildren(node, name, sideIndex):
"""Returns the component children of input component root.
Note:
This method is specific to work with shifter guides naming conventions
Arguments:
node (dagNode): The input node to search
name (str): The name to search
sideIndex (str): the side
Returns:
dagNode list: The children dagNodes
>>> objList = dag.findComponentChildren(self.parent,
oldName,
oldSideIndex)
"""
children = []
for item in node.listRelatives(allDescendents=True,
type="transform"):
checkName = item.name().split("|")[-1].split("_")
if checkName[0] == name and checkName[1] == sideIndex:
children.append(item)
return children
def findComponentChildren2(node, name, sideIndex):
"""Returns the component children of input component root.
This function is using Maya cmds instead of PyMel
Note:
This method is specific to work with shifter guides naming conventions
Arguments:
node (dagNode): The input node to search
name (str): The name to search
sideIndex (str): the side
Returns:
dagNode list: The children dagNodes
>>> objList = dag.findComponentChildren(self.parent,
oldName,
oldSideIndex)
"""
children = []
for item in cmds.listRelatives(node.name(), allDescendents=True,
type="transform"):
checkName = item.split("|")[-1].split("_")
if checkName[0] == name and checkName[1] == sideIndex:
children.append(item)
return [pm.PyNode(x) for x in children]