def getRootAndCOM(node):
'''
Given either the root or COM, return root and COM based on connections.
'''
com = None
root = None
if mc.attributeQuery(COM_ATTR, node=node, exists=True):
com = node
messageCon = mc.listConnections(com+'.'+COM_ATTR, source=True, destination=False)
if not messageCon:
raise RuntimeError('Could not determine root from COM, please select root and run again.')
root = messageCon[0]
else:
messageCon = mc.listConnections(node+'.message', source=False, destination=True, plugs=True)
if messageCon:
for each in messageCon:
eachNode, attr = each.rsplit('.',1)
if attr == COM_ATTR:
com = eachNode
root = node
break
return root, com
python类select()的实例源码
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 _populateSelectionField(self, channel, field, *args):
selectedChannels = None
if channel:
selectedChannels = getSelectedChannels()
if not selectedChannels:
raise RuntimeError('Please select an attribute in the channelBox.')
if len(selectedChannels) > 1:
raise RuntimeError('Please select only one attribute.')
sel = mc.ls(sl=True)
if not sel:
raise RuntimeError('Please select a node.')
if len(sel) > 1:
raise RuntimeError('Please select only one node.')
selection = sel[0]
if selectedChannels:
selection = selection+'.'+selectedChannels[0]
mc.textFieldButtonGrp(field, edit=True, text=selection)
def _populateSelectionList(self, channel, control, *args):
selectedChannels = None
if channel:
selectedChannels = getSelectedChannels()
if not selectedChannels:
raise RuntimeError('Please select an attribute in the channelBox.')
if len(selectedChannels) > 1:
raise RuntimeError('Please select only one attribute.')
sel = mc.ls(sl=True)
if not sel:
raise RuntimeError('Please select a node.')
if len(sel) > 1:
raise RuntimeError('Please select only one node.')
selection = sel[0]
if selectedChannels:
selection = selection+'.'+selectedChannels[0]
mc.textScrollList(control, edit=True, append=[selection])
def copySingle(source=None, destination=None, pasteMethod='replace', offset=0, addToLayer=False, rotateOrder=True):
'''
Copy animation from a source node and paste it to a destination node
'''
start, end = _getStartAndEnd()
if not source and not destination:
sel = mc.ls(sl=True)
if len(sel) != 2:
OpenMaya.MGlobal.displayWarning('Please select exactly 2 objects.')
return
source = sel[0]
destination = sel[1]
layer = None
if addToLayer:
layer = utl.createAnimLayer(destination, namePrefix='ml_cp')
copyAnimation(source=source, destination=destination, pasteMethod=pasteMethod, offset=offset, start=start, end=end, layer=layer, rotateOrder=rotateOrder)
#if sel:
#mc.select(sel)
def toLocators(bakeOnOnes=False, space='world', spaceInt=None, constrainSource=False):
'''
Creates locators, and bakes their position to selection.
Creates connections to the source objects, so they can
be found later to bake back.
'''
if spaceInt and 0 <= spaceInt <= 2:
space = ['world', 'camera', 'last'][spaceInt]
sel = mc.ls(sl=True)
parent = None
if space == 'camera':
parent = utl.getCurrentCamera()
elif space == 'last':
parent = sel[-1]
sel = sel[:-1]
mc.select(sel)
matchBakeLocators(parent=parent, bakeOnOnes=bakeOnOnes, constrainSource=constrainSource)
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 makeTeeth(self, teeth=10, length=0.3):
# The logic here is exactly the same as in the makeTeeth function we created
cmds.select(clear=True)
faces = self.getTeethFaces(teeth)
for face in faces:
cmds.select('%s.%s' % (self.transform, face), add=True)
# Instead of returning a value, lets just store the extrude node onto the class as a class variable
self.extrude = cmds.polyExtrudeFacet(localTranslateZ=length)[0]
cmds.select(clear=True)
def _maintained_selection_decorator(func):
"""Function decorator to maintain the selection once called
Example:
>>> @_maintained_selection
... def my_function():
... # Modify selection
... cmds.select(clear=True)
...
>>> # Selection restored
"""
def wrapper(*args, **kwargs):
previous_selection = cmds.ls(selection=True)
try:
return func(*args, **kwargs)
finally:
if previous_selection:
cmds.select(previous_selection,
replace=True,
noExpand=True)
else:
cmds.select(deselect=True,
noExpand=True)
return wrapper
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 connect_matching_attributes(source, target):
"""Connect matching attributes from source to target
Arguments:
source (str): Absolute path to node from which to connect
target (str): Target node
Example:
>>> # Select two matching nodes
>>> source = cmds.createNode("transform", name="source")
>>> target = cmds.createNode("transform", name="target")
>>> cmds.select([source, target], replace=True)
>>> source, target = cmds.ls(selection=True)
>>> connect_matching_attributes(source, target)
"""
dsts = cmds.listAttr(target, keyable=True)
for src in cmds.listAttr(source, keyable=True):
if src not in dsts:
continue
try:
src = "." + src
cmds.connectAttr(source + src,
target + src,
force=True)
except RuntimeError as e:
cmds.warning("Could not connect %s: %s" % (src, e))
def process(self, context, plugin):
from maya import cmds
cmds.select(plugin.assemblies)
def process(self, instance):
import os
import polly
from maya import cmds
from avalon import maya
dirname = polly.format_staging_dir(
root=instance.context.data["workspaceDir"],
time=instance.context.data["time"],
name=instance.data["name"])
try:
os.makedirs(dirname)
except OSError:
pass
filename = "{name}.ma".format(**instance.data)
path = os.path.join(dirname, filename)
# Perform extraction
self.log.info("Performing extraction..")
with maya.maintained_selection(), maya.without_extension():
cmds.select(instance, noExpand=True)
cmds.file(path,
force=True,
typ="mayaAscii",
exportSelected=True,
preserveReferences=False,
constructionHistory=True)
# Store reference for integration
if "files" not in instance.data:
instance.data["files"] = list()
instance.data["files"].append(filename)
instance.data["stagingDir"] = dirname
self.log.info("Extracted {instance} to {path}".format(**locals()))
def zero_orient(joints):
for joint in joints:
children = _unparent_children(joint)
cmds.setAttr('{0}.jointOrient'.format(joint), 0, 0, 0)
_reparent_children(joint, children)
if joints:
cmds.select(joints)
def template_joints(joints=None, reorient_children=True, reset_orientation=True):
if joints is None:
joints = cmds.ls(sl=True, type='joint')
if not joints:
raise RuntimeError('No joint selected to orient.')
if reorient_children:
children = cmds.listRelatives(fullPath=True, allDescendents=True, type='joint')
joints.extend(children)
red, green, blue = create_shaders()
orient_group = cmds.createNode('transform', name=ORIENT_GROUP)
manips = []
for joint in joints:
if reset_orientation:
cmds.makeIdentity(joint, apply=True)
cmds.joint(joint, edit=True, orientJoint='xyz', secondaryAxisOrient='yup', children=False, zeroScaleOrient=True)
if not cmds.listRelatives(joint, children=True):
zero_orient([joint])
continue
group, manip = create_orient_manipulator(joint, blue)
manips.append(manip)
cmds.parent(group, orient_group)
cmds.parentConstraint(joint, group)
cmds.setAttr(joint + '.template', 1)
cmds.select(manips)
def create_orient_manipulator(joint, material):
joint_scale = cmds.jointDisplayScale(query=True)
joint_radius = cmds.getAttr('{0}.radius'.format(joint))
radius = joint_scale * joint_radius
children = cmds.listRelatives(joint, children=True, path=True)
if children:
p1 = cmds.xform(joint, q=True, ws=True, t=True)
p1 = OpenMaya.MPoint(*p1)
p2 = cmds.xform(children[0], q=True, ws=True, t=True)
p2 = OpenMaya.MPoint(*p2)
radius = p1.distanceTo(p2)
arrow_cvs = [[-1, 0, 0], [-1, 2, 0], [-2, 2, 0], [0, 4, 0], [2, 2, 0], [1, 2, 0], [1, 0, 0], [-1, 0, 0]]
arrow_cvs = [[x[0]*radius, x[1]*radius, x[2]*radius] for x in arrow_cvs]
shape = cmds.curve(name='{0}_zForward'.format(joint), degree=1, point=arrow_cvs)
# shape = cmds.sphere(n='{0}_zForward'.format(joint), p=(0, 0, 0), ax=(0, 0, -1), ssw=0, esw=180, r=radius, d=3, ut=0, tol=0.01, s=8, nsp=4, ch=0)[0]
# cmds.setAttr('{0}.sz'.format(shape), 0)
# cmds.select(shape)
# cmds.hyperShade(assign=material)
group = cmds.createNode('transform', name='{0}_grp'.format(shape))
cmds.parent(shape, group)
cmds.makeIdentity(shape, apply=True)
cmds.addAttr(shape, longName=MESSAGE_ATTRIBUTE, attributeType='message')
cmds.connectAttr('{0}.message'.format(joint), '{0}.{1}'.format(shape, MESSAGE_ATTRIBUTE))
for attr in ['tx', 'ty', 'tz', 'ry', 'rz', 'v']:
cmds.setAttr('{0}.{1}'.format(shape, attr), lock=True, keyable=False)
return group, shape
def dump(curves=None, stack=False):
"""Get a data dictionary representing all the given curves.
:param curves: Optional list of curves.
:return: A json serializable list of dictionaries containing the data required to recreate the curves.
"""
if curves is None:
curves = cmds.ls(sl=True) or []
data = []
for node in curves:
shape = shortcuts.get_shape(node)
if cmds.nodeType(shape) == 'nurbsCurve':
control = {
'name': node,
'cvs': cmds.getAttr('{0}.cv[*]'.format(node)),
'degree': cmds.getAttr('{0}.degree'.format(node)),
'form': cmds.getAttr('{0}.form'.format(node)),
'xform': cmds.xform(node, q=True, ws=True, matrix=True),
'knots': get_knots(node),
'pivot': cmds.xform(node, q=True, rp=True),
'overrideEnabled': cmds.getAttr('{0}.overrideEnabled'.format(node)),
'overrideRGBColors': cmds.getAttr('{0}.overrideRGBColors'.format(node)),
'overrideColorRGB': cmds.getAttr('{0}.overrideColorRGB'.format(node))[0],
'overrideColor': cmds.getAttr('{0}.overrideColor'.format(node)),
}
if stack:
control['stack'] = get_stack_count(node)
control['parent'] = get_stack_parent(node)
data.append(control)
if curves:
cmds.select(curves)
return data
def test_duplicate_chain(self):
for i in range(5):
cmds.joint(p=(0, i, 0))
cmds.select(cl=True)
for i in range(5):
cmds.joint(p=(i+1, 0, 0))
cmds.parent('joint6', 'joint2')
joints, original_joints = shortcuts.duplicate_chain('joint1', 'joint5',
search_for='joint', replace_with='dupejoint')
self.assertEqual(5, len(joints))
self.assertListEqual(['dupejoint{0}'.format(x) for x in range(1, 6)], joints)
self.assertListEqual(['joint{0}'.format(x) for x in range(1, 6)], original_joints)
def _select(self, *args):
selected = cmds.textScrollList(self.text_scroll, q=True, si=True)
if not selected:
return
camera = selected[0]
cmds.select(camera)
def _select_file_node(self, index):
u"""index?????????????????
:param index: TableView??????index
:type index: QModelIndex
"""
index = self.proxy_model.mapToSource(index)
if not index.isValid():
return
model = self.model.items[index.row()]
cmds.select(model.node)