本文整理汇总了Python中maya.cmds.ls函数的典型用法代码示例。如果您正苦于以下问题:Python ls函数的具体用法?Python ls怎么用?Python ls使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ls函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: blendAttrs
def blendAttrs(targ1=None, targ2=None, driven=None, blendAttr=None, translate=1, rotate=1):
'''
sets up blending of translation / rotation values from targs 1 & 2 on the driven node.
If a blendAttr is supplied, this is connected to the blender value
'''
if not targ1 and not targ2 and not driven:
if len(cmds.ls(sl=1)) == 3:
targ1 = cmds.ls(sl=1)[0]
targ2 = cmds.ls(sl=1)[1]
driven = cmds.ls(sl=1)[2]
else:
return showDialog( 'Argument Error', 'Please supply or select targ1, targ2 and driven nodes' )
if translate:
t_bc = cmds.createNode('blendColors', name='%s_translate_bc' % driven)
cmds.connectAttr('%s.t' % targ2, '%s.color1' % t_bc)
cmds.connectAttr('%s.t' % targ1, '%s.color2' % t_bc)
if blendAttr:
cmds.connectAttr(blendAttr, '%s.blender' % t_bc)
cmds.connectAttr('%s.output' % t_bc, '%s.t' % driven)
if rotate:
r_bc = cmds.createNode('blendColors', name='%s_rotate_bc' % driven)
cmds.connectAttr('%s.rotate' % targ2, '%s.color1' % r_bc)
cmds.connectAttr('%s.rotate' % targ1, '%s.color2' % r_bc)
if blendAttr:
cmds.connectAttr(blendAttr, '%s.blender' % r_bc)
cmds.connectAttr('%s.output' % r_bc, '%s.rotate' % driven)
示例2: _ls
def _ls(nodeType = '', topTransform = True, stringFilter = '', unlockNode = False):
if nodeType:
nodes = cmds.ls(type = nodeType)
if nodes:
final_nodes = []
for each in nodes:
each = cmds.ls(each, long = True)[0]
top_transform = cmds.listRelatives(each, parent = True, fullPath = True) if topTransform else None
final_node = top_transform[0] if top_transform else each
if unlockNode:
try: cmds.lockNode(final_node, lock = False)
except: mel.eval('warning "Failed to unlock %s, skipping...";' % final_node)
if stringFilter:
if stringFilter in final_node:
if final_node not in final_nodes:
final_nodes.append(final_node)
else:
if final_node not in final_nodes:
final_nodes.append(final_node)
return final_nodes
return []
示例3: _validate_item_for_alembic_cache_publish
def _validate_item_for_alembic_cache_publish(self, item):
"""
Validate that the item is valid to be exported
to an alembic cache
"""
errors = []
# check that the group still exists:
if not cmds.objExists(item["name"]):
errors.append("This group couldn't be found in the scene!")
else:
# print "\n\n### %s ###\n\n" %item["name"]
# Deselect all
cmds.select(deselect=True)
# Use selection to get all the children of current "Alembic" objectset
cmds.select(item["name"], hierarchy=True, add=True)
# Get only the selected items. (if necessary take only certain types to export!)
sel=cmds.ls(selection=True, showType=True)
meshesFound = False
for s in sel:
if cmds.ls(s, type="mesh"):
meshesFound = True
break
if not meshesFound:
errors.append("This group doesn't appear to contain any meshes!")
cmds.select(deselect=True)
# finally return any errors
return errors
示例4: maya_move
def maya_move(angular_velocity, time_step):
objects = cmds.ls(sl=True)
if objects == []:
print('* Please select at least an object.')
return
trajectory = cmds.ls('trajectory')
for i, o in enumerate(objects):
x = cmds.getAttr(o + '.translateX')
y = cmds.getAttr(o + '.translateY')
z = cmds.getAttr(o + '.translateZ')
loc = [x, y, z]
state = make_state(loc)
state = simulate_circle(state, angular_velocity, time_step)
old_loc = loc
loc = get_location(state)
cmds.select(o)
cmds.move(loc[0], loc[1], loc[2])
# draw trajectory for the first object
if i == 0:
if trajectory == []:
cv = cmds.curve(point=[old_loc, loc], degree=1)
cmds.rename(cv, 'trajectory')
else:
cmds.curve('trajectory', point=[loc], degree=1, append=True)
# keep all objects selected
cmds.select(objects)
示例5: orderedVertsEdgeLoop
def orderedVertsEdgeLoop(cls):
"""
#select 2 adjasent vertices ( corner and direction vertex)
#list vertexes on edge loop( for curves )
"""
myVert = cmds.ls( os=1, fl=1 )
if len(myVert)==2:
firstVert = myVert[0]
secondVert = myVert[1]
cmds.select (firstVert,secondVert, r =1)
mel.eval('ConvertSelectionToContainedEdges')
firstEdge = cmds.ls( sl=1 )[0]
cmds.polySelectSp( firstEdge, loop =1 )
edges = cmds.ls( sl=1, fl=1 )
edgeDict = cls.getEdgeVertDict(edges) #{edge: [vert1, vert2], ...}
ordered = [firstVert, secondVert]
for i in range( len(edges)-2 ):
del edgeDict[firstEdge]
#print edgeDict
for x, y in edgeDict.iteritems():
if secondVert in y:
xVerts = y
xVerts.remove(secondVert)
firstEdge = x
secondVert = xVerts[0]
ordered.append( secondVert )
return ordered
else:
print 'select 2 adjasent vertex!!'
示例6: __uicb_setReferenceBwavNode
def __uicb_setReferenceBwavNode(self, *args):
'''
: PRO_PACK : set the internal reference offset used to offset the audionode.
.. note::
If you pass this a bwav then it caches that bwav for use as the offset.
If you pass it a node, and that node has the timecode attrs, then it caches the offset itself.
'''
selectedAudio=cmds.ls(sl=True, type='audio')
self.__bwav_reference = None
self.__cached_tc_offset = None
if selectedAudio:
if not len(selectedAudio)==1:
log.warning("Please only select 1 piece of Audio to use for reference")
return
reference=AudioNode(selectedAudio[0])
if reference.isBwav():
self.__bwav_reference=selectedAudio[0]
cmds.text('bwavRefTC', edit=True,
label='frame %s == %s' % (reference.startFrame,reference.bwav_timecodeFormatted()))
else:
raise IOError("selected Audio node is NOT a Bwav so can't be used as reference")
else:
selectedNode = cmds.ls(sl=True,l=True)
if len(selectedNode)==1:
relativeTC = self.pro_audio.Timecode(selectedNode[0]).getTimecode_from_node()
actualframe = cmds.currentTime(q=True)
self.__cached_tc_offset = actualframe - self.pro_audio.timecode_to_frame(relativeTC)
cmds.text('bwavRefTC', edit=True,
label='frame %s == %s' % (cmds.currentTime(q=True), relativeTC))
else:
log.warning("No reference audio track selected for reference")
return
示例7: __init__
def __init__(self):
# Get our joint lists from a json file.
print os.environ["RDOJO_DATA"]
data_path = os.environ["RDOJO_DATA"] + 'data/rig/arm.json'
# Use our readJson function
data = utils.readJson(data_path)
# Load the json into a dictionary
self.module_info = json.loads( data )
""" NOTE: If we wanted to build our arm from some set of joints
in the scene, we could overwrite self.module_info['positions']"""
# Make a new dictionary to store information about the arm rig.
self.rig_info = {}
# Here we will see if we have a selection to get new positions from.
if len(cmds.ls(sl=True, type='joint')) == numjnts :
sel=cmds.ls(sl=True, type='joint')
positions = []
for s in sel:
positions.append(cmds.xform(s, q=True, ws=True, t=True))
self.rig_info['positions']=positions
else:
self.rig_info['positions']=self.module_info['positions']
""" Instead of the else:, we could just return a message that the selection
does not meet requirements for an arm. """
""" What if we want a left and a right arm? For now we will set
a temporary variable to override the name, but later we will build
this into the UI """
self.instance = '_L_'
# Run rig_arm function
self.rig_arm()
示例8: getMaterials
def getMaterials(nodes=None):
""" Returns the materials related to nodes
:param nodes: The nodes to get the related materials from.
If nodes is None the current selection will be used.
:rtype: list
"""
# Get selected nodes if None provided
if nodes is None:
nodes = mc.ls(sl=1)
# Get materials from list
materials = mc.ls(nodes, mat=1, long=True)
# Get materials related to nodes (material from object)
# And add those materials to the material list we already have
if nodes:
nodes_history = mc.listHistory(nodes,f=1)
if nodes_history:
nodes_connections = mc.listConnections(nodes_history)
if nodes_connections:
connected_materials = mc.ls(nodes_connections, mat=True, long=True)
if connected_materials:
# Use a set so we don't have any duplicates
materials = set(materials)
materials.update(connected_materials)
materials = list(materials)
return materials
示例9: selectPaintWeightsInfluence
def selectPaintWeightsInfluence(self,infl):
'''
tries to select influence (provided as string) in current maya's paint weights context and UI
if skin paint context is not available, nothing happens
'''
if not Utils.isCurrentlyPaintingWeights():
return
# influence name can come in any form ('joint3', 'joint2|joint3', 'joint1|joint2|joint3')
# get the absolute shortest possible (but still unique) and longest
try:
longName = cmds.ls(infl,l=True)[0]
shortName = cmds.ls(longName,l=False)[0]
log.info("selecting in paint weights: influence %s" % str(infl))
# try to work around with the mess in the earlier versions of
# maya's paint weights UI:
if Utils.getMayaVersion()<Utils.MAYA2011:
itemName = Utils.mel('artAttrSkinShortName("%s")'%shortName)
Utils.mel('artSkinSelectInfluence("artAttrSkinPaintCtx","%s","%s");' % (shortName,itemName));
else:
Utils.mel('artSkinSelectInfluence("artAttrSkinPaintCtx","%s");' % shortName);
# show paint weights interface
cmds.toolPropertyWindow()
except:
# problems listing given influence.. just die here
Utils.displayError('problem selecting influence %s' % infl)
示例10: connectLoresVis
def connectLoresVis(toggleAttr="allTransA_ctrl.loGeoVis"):
"""
Connect lores geometry visibility to the specified visibility toggle attribute
@param toggleAttr: Visibility toggle attribute
@type toggleAttr: str
"""
# Check visibility toggle attribute
if not mc.objExists(toggleAttr):
raise Exception('Visibility toggle attribute "' + toggleAttr + '" does not exist!')
# Get all joint list
jointList = mc.ls(type="joint")
if not jointList:
return
# Iterate over all joints
for joint in jointList:
# Get all joint mesh shapes
allShapes = mc.listRelatives(joint, s=True, pa=True)
if not allShapes:
continue
meshShapes = mc.ls(allShapes, type="mesh")
if not meshShapes:
continue
# Connect mesh shape visibility to vis toggle attr
for meshShape in meshShapes:
mc.connectAttr(toggleAttr, meshShape + ".v", f=True)
示例11: colourLoresGeo
def colourLoresGeo():
"""
Set default colouring for lores geometry,
"""
# Get all joint list
jointList = mc.ls(type="joint")
if not jointList:
return
# Iterate over all joints
for joint in jointList:
# Get all joint mesh shapes
allShapes = mc.listRelatives(joint, s=True, pa=True)
if not allShapes:
continue
meshShapes = mc.ls(allShapes, type="mesh")
if not meshShapes:
continue
# Colour mesh shape
for meshShape in meshShapes:
mc.setAttr(meshShape + ".overrideEnabled", 1)
if joint.startswith("cn_"):
mc.setAttr(meshShape + ".overrideColor", 24)
if joint.startswith("lf_"):
mc.setAttr(meshShape + ".overrideColor", 15)
if joint.startswith("rt_"):
mc.setAttr(meshShape + ".overrideColor", 4)
示例12: uiSetFlags
def uiSetFlags(self):
'''
Gets the channel state data from the UI and then sets the flags.
'''
# Get channel state flag values
channelState = []
for attr in self.channel:
channelState.append(mc.radioButtonGrp('rbg'+attr.upper(),q=1,sl=1)-2)
# Get list of objects to set flags for
objType = mc.radioButtonGrp('rbgObjType',q=1,sl=1)
objectList = []
if objType == 1: objectList = mc.ls(sl=1)
elif objType == 2:
doit = mc.confirmDialog(title='Confirm Set Flags on ALL Transforms',
m='Are you sure you want to mass edit all the channel state attributes?',
button=('Yes','No'),
defaultButton='No',
cancelButton='No',
dismissString='NO')
if doit == 'No': return
objectList = mc.ls('*.channelState',o=True)
elif objType == 3:
selType = mc.textField('tfType',q=1,text=1)
objectList = mc.ls(type=selType)
# Set Flags
self.setFlags(channelState,objectList)
示例13: __cleanup
def __cleanup(self, version = 2.0):
#--- hide groups and lock attributes
cmds.setAttr(self.negative_grp + '.v', 0)
cmds.setAttr(self.result_grp + '.v', 0)
sf_objs = cmds.ls(self.sf_tool, self.blendshapes, self.shotfinaling,
self.mesh_bsp_grp, self.mesh_shotfinal_grp,
self.negative_grp, self.sculpt_grp, self.result_grp,
'*Negative*', '*Sculpt*', '*Result*', type = 'transform')
for i in sf_objs:
for axis in 'xyz':
cmds.setAttr(i + '.t' + axis, lock = 1, keyable = 0)
cmds.setAttr(i + '.r' + axis, lock = 1, keyable = 0)
cmds.setAttr(i + '.s' + axis, lock = 1, keyable = 0)
cmds.setAttr(i + '.v', keyable = 0)
cmds.setAttr(i + '.ihi', 0)
#--- hide isHistoricallyInteresting
to_ihi = cmds.ls('*BSP*', '*Bshpe*', '*tweak*', '*Shape*')
for i in sf_objs:
to_ihi.append(i)
for i in to_ihi:
cmds.setAttr(i + '.ihi', 0)
#--- add versionNumber of the SHOTFINAL script
if not cmds.objExists(self.shotfinaling + '.version'):
cmds.addAttr(self.shotfinaling,
longName = 'version',
shortName = 'version',
attributeType = 'float',
keyable = True)
cmds.setAttr(self.shotfinaling + '.version',
version,
edit = True,
channelBox = True,
lock = True)
#--- select the sculpt tool
cmds.select(self.sculpt_tool)
示例14: check
def check():
'''
Non-Unique Checker looks for non unique node names.
It will separate shape, dag and dep nodes when reporting.
@version history: 03/30/07 : Gregory Smith : initial release
06/13/07 : Ramiro Gomez : updated header format
04/25/08 : Ramiro Gomez : initial python transfer
@keyword: rig, model, naming
@appVersion: 8.5, 2008
'''
##Create variables
dagErrors=[] ##hold all the nonunique items
shapeErrors=[] ##hold all the nonunique items
depErrors=[] ##hold all the nonunique items
dag = mc.ls(dag=True)
shapes = mc.ls(geometry=True)
dep = mc.ls(dep=True)
for item in shapes:
while dag.count(item): dag.remove(item)
for item in shapes:
while dep.count(item): dep.remove(item)
for item in dag:
while dep.count(item): dep.remove(item)
##Print header statement
print 'Non-Unique Checker'
print '==========================================\n'
print 'DAG NODES'
print '------------'
for item in dag:
if item.count('|'): dagErrors.append(item)
print '\n'.join(sorted(dagErrors)) + '\n'
print 'DEP NODES'
print '------------'
for item in dep:
if item.count('|'): depErrors.append(item)
print '\n'.join(sorted(depErrors)) + '\n'
print 'SHAPE NODES'
print '------------'
for item in shapes:
if item.count('|'): shapeErrors.append(item)
print '\n'.join(sorted(shapeErrors)) + '\n'
del dep
del dag
del shapes
mc.select(cl=True)
print '=========================================='
print ('Non-Unique Check located ' + str(len(dagErrors) + len(depErrors) + len(shapeErrors)) + ' errors.')
示例15: multObjShapeUpdate
def multObjShapeUpdate():
sel_objs = cmds.ls(sl=True,fl=True)
if len(sel_objs)>0:
files_to_import = cmds.fileDialog2(fileFilter = '*.obj', dialogStyle = 2, caption = 'import multiple object files', fileMode = 4,okc="Import")
if len(files_to_import) == len(sel_objs):
object_names = [file_to_import.split('/')[-1].split('.obj')[0] for file_to_import in files_to_import]
if len(sel_objs) == len([x for x in object_names if x in sel_objs]):
for file_to_import in files_to_import:
object_name = file_to_import.split('/')[-1].split('.obj')[0]
returnedNodes = cmds.file('%s' % file_to_import, i = True, type = "OBJ", rnn=True, ignoreVersion = True, options = "mo=0", loadReferenceDepth = "all" )
cmds.delete(cmds.ls(returnedNodes,type="objectSet"))
geo = cmds.listRelatives(cmds.ls(returnedNodes,g=1)[0],p=1)
cmds.rename( geo, "newShape_{0}".format(object_name))
new_shapes = [s for s in cmds.listRelatives(cmds.ls(g=1),p=1) if "newShape_" in s]
cur_shapes = sel_objs
for new in new_shapes:
for cur in cur_shapes:
if new.split("newShape_")[1] == cur:
blendshapeNd = cmds.blendShape(new,cur)[0]
cmds.setAttr("{0}.{1}".format(blendshapeNd,new),1)
cmds.delete(cur_shapes,ch=True)
cmds.delete(new_shapes)
cmds.confirmDialog(m="---===All Shapes Updated!===---")
else:
cmds.confirmDialog(m="--==Not Matching The Name!==--")
else:
cmds.confirmDialog(m="--==Please Select The Same Number Of Objects!==--")
else:
cmds.confirmDialog(m="--==Please Select Something!==--")