def add_bookmark(type, value):
'''
?????????????
:param type: ??????????
:param value: ??????
:return:
'''
option_var_name = get_bookmark_option_var_name(type)
ls = cmds.optionVar(q=option_var_name)
if ls == 0:
ls = []
if value not in ls:
ls.append(value)
cmds.optionVar(ca=option_var_name)
[cmds.optionVar(sva=(option_var_name, i)) for i in ls]
return
python类ls()的实例源码
def delete_bookmark(ui, value):
'''
???????????
:param type: ??????????
:param value: ??????
:return:
'''
if ui.radio_bookmark_file.isChecked():
type = 'file'
elif ui.radio_bookmark_directory.isChecked():
type = 'directory'
option_var_name = get_bookmark_option_var_name(type)
ls = cmds.optionVar(q=option_var_name)
if ls != 0:
if value in ls:
ls.remove(value)
cmds.optionVar(ca=option_var_name)
[cmds.optionVar(sva=(option_var_name, i)) for i in ls]
return
def add_rectnt_file(file_path, file_type):
'''
????????????
:param file_path:
:param file_type:
:return:
'''
optvar = cmds.optionVar
opt_list = 'RecentFilesList'
opt_type = 'RecentFilesTypeList'
max_size = optvar(q='RecentFilesMaxSize')
ls = optvar(q=opt_list)
# ???????????
for i, x in enumerate(ls):
if file_path == x:
optvar(rfa=[opt_list, i])
optvar(rfa=[opt_type, i])
optvar(sva=[opt_list, file_path])
optvar(sva=[opt_type, file_type])
if len(optvar(q=opt_list)) > max_size:
optvar(rfa=[opt_list, 0])
optvar(rfa=[opt_type, 0])
def execute(my):
# get the search key from the delivered package
search_key = my.get_package_value("search_key")
# get the sobject from the server
sobject = my.server.get_by_search_key(search_key)
if not sobject:
raise Exception("SObject with search key [%s] does not exist" % \
search_key)
# code and verify in maya that the node is in session
code = sobject.get('code')
if not cmds.ls(code):
raise Exception("Cannot checkin: [%s] does not exist" % code)
my.set_output_value('sobject', sobject)
def _maintained_selection_context():
"""Maintain selection during context
Example:
>>> scene = cmds.file(new=True, force=True)
>>> node = cmds.createNode("transform", name="Test")
>>> cmds.select("persp")
>>> with maintained_selection():
... cmds.select("Test", replace=True)
>>> "Test" in cmds.ls(selection=True)
False
"""
previous_selection = cmds.ls(selection=True)
try:
yield
finally:
if previous_selection:
cmds.select(previous_selection,
replace=True,
noExpand=True)
else:
cmds.select(deselect=True,
noExpand=True)
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 Exception:
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 Exception:
cmds.warning("Could not find shape in %s" % element)
return None
else:
return node
def set_defaults(*args):
"""Set currently selected values from channel box to their default value
If no channel is selected, default all keyable attributes.
"""
for node in cmds.ls(selection=True):
selected_channels = read_selected_channels()
for channel in (selected_channels or
cmds.listAttr(node, keyable=True)):
try:
default = cmds.attributeQuery(channel,
node=node,
listDefault=True)[0]
except Exception:
continue
else:
cmds.setAttr(node + "." + channel, default)
def clone_special(*args):
"""Clone in localspace, and preserve user-defined attributes"""
for transform in cmds.ls(selection=True, long=True):
if cmds.nodeType(transform) != "transform":
cmds.warning("Skipping '%s', not a `transform`" % transform)
continue
shape = _find_shape(transform)
type = cmds.nodeType(shape)
if type not in ("mesh", "nurbsSurface", "nurbsCurve"):
cmds.warning("Skipping '{transform}': cannot clone nodes "
"of type '{type}'".format(**locals()))
continue
cloned = commands.clone(shape, worldspace=False)
new_transform = cmds.listRelatives(cloned,
parent=True,
fullPath=True)[0]
new_transform = cmds.rename(new_transform,
new_transform.rsplit(":", 1)[-1])
for attr in cmds.listAttr(transform,
userDefined=True) or list():
try:
cmds.addAttr(new_transform, longName=attr, dataType="string")
except Exception:
continue
value = cmds.getAttr(transform + "." + attr)
cmds.setAttr(new_transform + "." + attr, value, type="string")
# Connect visibility
cmds.connectAttr(transform + ".visibility",
new_transform + ".visibility")
def _clone(worldspace=False):
"""Clone selected objects in viewport
Arguments:
worldspace (bool): Whether or not to append a transformGeometry to
resulting clone.
"""
clones = list()
for node in cmds.ls(selection=True, long=True):
shape = _find_shape(node)
type = cmds.nodeType(shape)
if type not in ("mesh", "nurbsSurface", "nurbsCurve"):
cmds.warning("Skipping '{node}': cannot clone nodes "
"of type '{type}'".format(**locals()))
continue
cloned = commands.clone(shape, worldspace=worldspace)
clones.append(cloned)
if not clones:
return
# Select newly created transform nodes in the viewport
transforms = list()
for clone in clones:
transform = cmds.listRelatives(clone, parent=True, fullPath=True)[0]
transforms.append(transform)
cmds.select(transforms, replace=True)
def process(self, instance):
from maya import cmds
from avalon import maya
with maya.maintained_selection():
cmds.select(instance, replace=True)
nodes = cmds.file(
constructionHistory=True,
exportSelected=True,
preview=True,
force=True,
)
self.assemblies[:] = cmds.ls(nodes, assemblies=True)
if not self.assemblies:
raise Exception("No assembly found.")
if len(self.assemblies) != 1:
self.assemblies = '"%s"' % '", "'.join(self.assemblies)
raise Exception(
"Multiple assemblies found: %s" % self.assemblies
)
def process(self, instance):
from maya import cmds
invalid = list()
for mesh in cmds.ls(instance, type="mesh", long=True):
faces = cmds.polyListComponentConversion(mesh, toVertexFace=True)
locked = cmds.polyNormalPerVertex(faces,
query=True,
freezeNormal=True)
invalid.append(mesh) if any(locked) else None
# On locked normals, indicate that validation has failed
# with a friendly message for the user.
assert not invalid, (
"Meshes found with locked normals: %s" % invalid)
self.log.info("The normals of \"%s\" are correct." % instance)
def getObjects(self, model, includeShapes=True):
"""Get the objects of the component.
Args:
model(dagNode): The root of the component.
includeShapes (boo): If True, will include the shapes.
Returns:
list of dagNode: The list of the objects.
"""
objects = {}
if includeShapes:
children = pm.listRelatives(model, ad=True)
else:
children = pm.listRelatives(model, ad=True, typ='transform')
pm.select(children)
for child in pm.ls(self.fullName + "_*", selection=True):
objects[child[child.index(
self.fullName + "_") + len(self.fullName + "_"):]] = child
return objects
def getObjects3(self, model):
"""
NOTE: Experimental function
Get the objects of the component.
This version only get the transforms by Name using Maya Cmds
Args:
model(dagNode): The root of the component.
Returns:
list of dagNode: The list of the objects.
"""
objects = {}
for child in cmds.ls(self.fullName + "_*", type="transform"):
if pm.PyNode(child).getParent(-1) == model:
objects[child[child.index(
self.fullName + "_") + len(self.fullName + "_"):]] = child
return objects
def make_position_planar(*args):
sel = cmds.ls(sl=True, type='joint')
if len(sel) <= 3:
raise RuntimeError('Select 3 joints to make a plane and then additional joints to move onto that plane.')
a, b, c = [get_position(sel[i]) for i in range(3)]
ab = (b - a).normal()
ac = (c - a).normal()
normal = (ab ^ ac).normal()
joints = sel[3:]
for joint in joints:
children = _unparent_children(joint)
p = get_position(joint)
pa = a - p
dot = pa*normal
p = p + (normal*dot)
cmds.xform(joint, ws=True, t=(p.x, p.y, p.z))
_reparent_children(joint, children)
if sel:
cmds.select(sel)
def dump(root=None, file_path=None):
"""Dump the hierarchy data starting at root to disk.
:param root: Root node of the hierarchy.
:param file_path: Export json path.
:return: The hierarchy data that was exported.
"""
if root is None:
root = cmds.ls(sl=True)
if root:
root = root[0]
else:
return
if file_path is None:
file_path = cmds.fileDialog2(fileFilter='Skeleton Files (*.json)', dialogStyle=2, caption='Export Skeleton',
fileMode=0, returnFilter=False)
if file_path:
file_path = file_path[0]
else:
return
data = get_data(root)
fh = open(file_path, 'w')
json.dump(data, fh, indent=4)
fh.close()
logger.info('Exported skeleton to %s', file_path)
return data, file_path
def create_selected(self):
"""Create the curves selected in the curve list."""
curves = []
sel = cmds.ls(sl=True)
target = sel[0] if sel else None
for item in self.control_list.selectedItems():
text = item.text()
control_file = os.path.join(CONTROLS_DIRECTORY, '{0}.json'.format(text))
fh = open(control_file, 'r')
data = json.load(fh)
fh.close()
curve = create_curve(data)
if target:
cmds.delete(cmds.parentConstraint(target, curve))
curves.append(curve)
if curves:
cmds.select(curves)
def setUp(self):
self.group = cmds.createNode('transform', name='skeleton_grp')
cmds.select(cl=True)
j1 = cmds.joint(p=(0, 10, 0))
cmds.joint(p=(1, 9, 0))
cmds.joint(p=(2, 8, 0))
j = cmds.joint(p=(3, 9, 0))
cmds.joint(p=(4, 6, 0))
cmds.joint(p=(5, 5, 0))
cmds.joint(p=(6, 3, 0))
self.cube = cmds.polyCube()[0]
cmds.parent(self.cube, j)
cmds.parent(j1, self.group)
self.translates = [cmds.getAttr('{0}.t'.format(x))[0] for x in cmds.ls(type='joint')]
self.rotates = [cmds.getAttr('{0}.r'.format(x))[0] for x in cmds.ls(type='joint')]
self.orients = [cmds.getAttr('{0}.jo'.format(x))[0] for x in cmds.ls(type='joint')]
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 get_unused_utility_nodes():
u"""?????????????????????
:return: ??????????????????
:rtype: list of unicode
"""
utility_node_types = cmds.listNodeTypes("utility")
utility_nodes = []
for ul in utility_node_types:
nodes = cmds.ls(type=ul)
if not nodes:
continue
utility_nodes.extend(nodes)
unused = []
for u in utility_nodes:
if not [x for x in cmds.listConnections(u) if x != "defaultRenderUtilityList1"]:
unused.append(u)
return unused
def get_unused_shading_engines():
u"""????ShadingEngine???????
:return: ????ShadingEngine????
:rtype: list of unicode
"""
shading_engines = cmds.ls(type="shadingEngine")
unused_shading_engines = []
for s in shading_engines:
if s in _DEFAULT_SHADING_ENGINES:
continue
unused = True
for c in cmds.listConnections(s):
node_type = cmds.nodeType(c)
if "shader" in cmds.getClassification(node_type)[0]:
unused = False
break
if unused:
unused_shading_engines.append(s)
return unused_shading_engines
def BT_DoSetup():
sets = cmds.ls(sl = True, type = 'objectSet')
if len(sets) <= 0:
cmds.warning("Select a set.")
return False
set = sets[0]
unitResult = BT_SetUnits()
if unitResult:
QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Units set to centimetres.", "Okay")
result = BT_Setup(set = set)
if not result:
QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Problem with setup. May already be connected.", "Okay")
return False
print('Success!')
return True
def BT_DoSetup():
sets = cmds.ls(sl = True, type = 'objectSet')
if len(sets) <= 0:
cmds.warning("Select a set.")
return False
set = sets[0]
unitResult = BT_SetUnits()
if unitResult:
QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Units set to centimetres.", "Okay")
result = BT_Setup(set = set)
if not result:
QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Problem with setup. May already be connected.", "Okay")
return False
print('Success!')
return True
def BT_DoSetup():
sets = cmds.ls(sl = True, type = 'objectSet')
if len(sets) <= 0:
cmds.warning("Select a set.")
return False
set = sets[0]
unitResult = BT_SetUnits()
if unitResult:
QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Units set to centimetres.", "Okay")
result = BT_Setup(set = set)
if not result:
QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Problem with setup. May already be connected.", "Okay")
return False
print('Success!')
return True
extern_maya_sequencer.py 文件源码
项目:OpenTimelineIO
作者: PixarAnimationStudios
项目源码
文件源码
阅读 33
收藏 0
点赞 0
评论 0
def read_sequence():
rate = FPS.get(cmds.currentUnit(q=True, time=True), 25)
shots = cmds.ls(type='shot') or []
per_track = {}
for shot in shots:
track_no = cmds.shot(shot, q=True, track=True)
if track_no not in per_track:
per_track[track_no] = []
per_track[track_no].append(shot)
timeline = otio.schema.Timeline()
timeline.global_start_time = otio.opentime.RationalTime(0, rate)
for track_no in reversed(sorted(per_track.keys())):
track_shots = per_track[track_no]
timeline.tracks.append(_read_track(track_shots))
return timeline
def SelectKeyframes():
# Clear current selection
cmds.select(clear=True)
# Get a list of bones
boneList = cmds.ls(type = 'joint')
# Iterate and select ones with frames on loc/rot/scale
for bone in boneList:
# Check for loc
keysTranslate = cmds.keyframe(bone + ".translate", query=True, timeChange=True)
keysRotate = cmds.keyframe(bone + ".rotate", query=True, timeChange=True)
keysScale = cmds.keyframe(bone + ".scale", query=True, timeChange=True)
# Check for frames
if keysTranslate is not None:
if len(keysTranslate) >= 1:
cmds.select(bone, add=True)
if keysRotate is not None:
if len(keysRotate) >= 1:
cmds.select(bone, add=True)
if keysScale is not None:
if len(keysScale) >= 1:
cmds.select(bone, add=True)
# Cleans namespaces
def NamespaceClean():
# Get a list of bones
boneList = cmds.ls(type = 'joint')
# Loop
for bone in boneList:
# Check if it has a namespace
if bone.find(":") > -1:
# We got one, prepare to clean
resultSplit = bone.split(":")
# Get the last one
newName = resultSplit[len(resultSplit)-1]
# Rename it
try:
# Do it
cmds.rename(bone, newName)
except:
# Continue
pass
def cross_stitch(stitches=108, stitch_points=8, u_offset=0, tangent_offset=0, normal_fn=None):
'''Create cross stitching between two curves'''
a, b = cmds.ls(sl=True, dag=True, leaf=True)
if not normal_fn:
normal_fn = partial(sphere_normal, center=MVector(0, 0, 0))
half_stitches = int(stitches * 0.5)
u_offset_a = u_offset
u_offset_b = u_offset + 1.0 / (half_stitches * 2)
a0, a1 = MVector(*point_at_parameter(a, 0)), MVector(*point_at_parameter(a, u_offset_b))
tangent_offset += (a0-a1).length() * 0.3
print tangent_offset
points = stitch_curves(a, b, half_stitches, stitch_points, u_offset_a, tangent_offset, normal_fn)
cmds.curve(point=points)
points = stitch_curves(a, b, half_stitches, stitch_points, u_offset_b, tangent_offset, normal_fn)
cmds.curve(point=points)
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 process(self, instance):
from maya import cmds
invalid = list()
for mesh in cmds.ls(instance, type="mesh", long=True):
faces = cmds.polyListComponentConversion(mesh, toVertexFace=True)
locked = cmds.polyNormalPerVertex(faces,
query=True,
freezeNormal=True)
invalid.append(mesh) if any(locked) else None
# On locked normals, indicate that validation has failed
# with a friendly message for the user.
assert not invalid, (
"Meshes found with locked normals: %s" % invalid)
self.log.info("The normals of \"%s\" are correct." % instance)
def populateCrvField(tfgKey="", *args):
if tfgKey not in ["cntrPivTFBG", "cntrPiv2TFBG", "upLoc2TFBG", "upLocTFBG"]:
sel = cmds.ls(sl=True)
if sel and len(sel)!=1:
cmds.warning("only select the curve you want to rig up!")
else:
if rig.isType(sel[0], "nurbsCurve"):
cmds.textFieldButtonGrp(widgets[tfgKey], e=True, tx=sel[0])
else:
cmds.warning("That's not a curve!")
else:
sel = cmds.ls(sl=True)
if sel and len(sel)!=1:
cmds.warning("only select the object you want to rig up!")
else:
cmds.textFieldButtonGrp(widgets[tfgKey], e=True, tx=sel[0])
if tfgKey == "upLocTFBG":
cmds.textFieldButtonGrp(widgets["upLoc2TFBG"], e=True, tx=sel[0])
if tfgKey == "cntrPivTFBG":
cmds.textFieldButtonGrp(widgets["cntrPiv2TFBG"], e=True, tx=sel[0])