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))
python类delete()的实例源码
extern_maya_sequencer.py 文件源码
项目:OpenTimelineIO
作者: PixarAnimationStudios
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
def build_sequence(timeline, clean=False):
existing_shots = cmds.ls(type='shot') or []
if clean:
cmds.delete(existing_shots)
existing_shots = []
tracks = [
track for track in timeline.tracks
if track.kind == otio.schema.TrackKind.Video
]
for track_no, track in enumerate(reversed(tracks)):
_build_track(track, track_no, existing_shots=existing_shots)
def DeleteMenu():
# Check for existing control, remove it if we can
if cmds.control(MENU_DATA['menu'][0], exists=True):
# Found it, delete it
cmds.deleteUI(MENU_DATA['menu'][0], menu=True)
# Create the menu
def CreateMenu():
# Set the diplay's parent
cmds.setParent(mel.eval("$temp1=$gMainWindow"))
# Purge old one
DeleteMenu()
# Make new menu
menu = cmds.menu(MENU_DATA['menu'][0], label=MENU_DATA["menu"][1], tearOff=True) # Recreate the base
# Add children
cmds.menuItem(label="Import <- SEAnim", command=lambda x:ImportSEAnim(), annotation="Imports a SEAnim, resetting the scene first")
cmds.menuItem(label="Import and Blend <- SEAnim", command=lambda x:ImportMergeSEAnim(), annotation="Imports a SEAnim without resetting the scene (Blending the animations together)")
cmds.menuItem(divider=True)
cmds.menuItem(label="Export -> SEAnim", command=lambda x:ExportEntireSceneAnim(), annotation="Exports all joints, or all selected joints to a SEAnim file")
cmds.menuItem(divider=True)
cmds.menuItem(label="Clean Namespaces", command=lambda x:NamespaceClean(), annotation="Removes all namespaces from the scene")
cmds.menuItem(label="Place Notetrack", command=lambda x:PlaceNote(), annotation="Places a notetrack at the current scene time")
cmds.menuItem(label="Select All Joints", command=lambda x:SelectAllJoints(), annotation="Selects all joints")
cmds.menuItem(label="Select Keyed Joints", command=lambda x:SelectKeyframes(), annotation="Selects keyed joints, this feature does not work with conversion rigs")
cmds.menuItem(divider=True)
cmds.menuItem(label="Reset Scene", command=lambda x:ResetSceneAnim(), annotation="Manually reset the scene to bind position")
cmds.menuItem(label="Clear Curves", command=lambda x:PurgeAllKeyframes(), annotation="Manually delete all cached keyframe curves in the scene")
cmds.menuItem(divider=True)
game_menu = cmds.menuItem(label="Game Specific Tools", subMenu=True) # Make game specific submenu
cmds.menuItem(label="Call of Duty", subMenu=True)
cmds.menuItem(label="Attach Weapon to Rig", command=lambda x:WeaponBinder(), annotation="Attatches the weapon to the viewhands, does not work properly with conversion rigs")
cmds.setParent(game_menu, menu=True) # Close out menu (Call of Duty)
cmds.setParent(menu, menu=True) # Close out menu (Game tools)
cmds.menuItem(divider=True)
cmds.menuItem(label="Reload Plugin", command=lambda x:ReloadMayaPlugin(), annotation="Attempts to reload the plugin")
cmds.menuItem(label="About", command=lambda x:AboutWindow())
# Reloads a maya plugin
def PurgeAllKeyframes():
# Grab existing curves
ExistingFrames = cmds.ls(type="animCurveTA") + cmds.ls(type="animCurveTL")
# Iterate and remove
for KeyCurve in ExistingFrames:
# Delete it
cmds.delete(KeyCurve)
# Resets a bones keyframes
def conform_curve(source, destination):
point_on_curve = cmds.createNode('nearestPointOnCurve')
cmds.connectAttr(destination + '.worldSpace', point_on_curve + '.inputCurve')
for i, point in enumerate(cmds.getAttr(source + '.cv[*]')):
cmds.setAttr(point_on_curve + '.inPosition', point[0], point[1], point[2])
result_point = cmds.getAttr(point_on_curve + '.result.position')[0]
cmds.setAttr('{}.cv[{}]'.format(source, i), result_point[0], result_point[1], result_point[2])
cmds.delete(point_on_curve)
def deleteMush(self):
mesh = self.sourceField.text()
if not mesh:
return
if not cmds.objExists(mesh + '_Mush'):
return
cmds.delete(mesh + '_Mush')
def zbw_swapRotateOrder():
#find frame range from slider
startF = cmds.playbackOptions (query=True, minTime=True)
endF = cmds.playbackOptions (query=True, maxTime=True)
objs = cmds.ls (selection=True)
#dummy check for two objects!
objA = objs[0]
objB = objs[1]
#get list of keys to use
keysAtFull = cmds.keyframe (objA, query=True, time=(startF,endF), attribute=('tx','ty','tz','rx','ry','rz'))
keysSet = set(keysAtFull)
keyList=[]
for key in keysSet:
keyList.append(key)
keyList.sort()
#print keyList
for thisKey in keyList: #populate the dictionary with the key values
cmds.currentTime(thisKey) #set currentTime to the value
cmds.pointConstraint(objA, objB, name="pointConst")#pointConstriain B to A
cmds.orientConstraint(objA, objB, name="orientConst")#orientConstan B to A
getRot() #getData() for B and puts it in keyBuffer
getTrans() #gets tranlslation data for same
cmds.delete('pointConst','orientConst') # delete the constaints on B
#since I can't add the keys while I"m constraining, do it now from dictionary
for newKey in keyList:
objRot = rotBuffer[newKey]
objTrans = transBuffer[newKey]
cmds.setKeyframe( objB, t=newKey,at='tx', v=objTrans[0]) #set keys for B on all the frames in keyBuffer to values in keyBuffer
cmds.setKeyframe( objB,t=newKey,at='ty', v=objTrans[1])
cmds.setKeyframe( objB,t=newKey,at='tz', v=objTrans[2])
cmds.setKeyframe( objB,t=newKey,at='rx', v=objRot[0])
cmds.setKeyframe( objB,t=newKey,at='ry', v=objRot[1])
cmds.setKeyframe( objB,t=newKey,at='rz', v=objRot[2])
cmds.filterCurve((objB+'_rotateX'), (objB+'_rotateY'), (objB+'_rotateZ' )) #run Euler filter on curves for rotation?
def deleteRig(*args):
# check for ctrl
sel = cmds.ls(sl=True, type="transform")
if sel:
for ctrl in sel:
# try
rpt = cmds.connectionInfo("{0}.rptMult".format(ctrl), sfd=True).partition(".")[0]
dens = cmds.connectionInfo("{0}.densMult".format(ctrl), sfd=True).partition(".")[0]
curve = cmds.connectionInfo("{0}.origCrv".format(ctrl), sfd=True).partition(".")[0]
para = cmds.connectionInfo("{0}.paraMult".format(ctrl), sfd=True).partition(".")[0]
if rig.parentCheck(curve):
cmds.parent(curve, world=True)
cmds.setAttr("{0}.v".format(curve), 1)
# check for file node, grab it, then find p2d from that and delete it
fTextFull = cmds.connectionInfo("{0}.fileTexture".format(ctrl), sfd=True)
print
"fTextFull:", fTextFull
if fTextFull:
fText = fTextFull.partition(".")[0]
print
fText
p2dFull = cmds.connectionInfo("{0}.uvCoord".format(fText), sfd=True)
print
p2dFull
if p2dFull:
p2d = p2dFull.partition(".")[0]
cmds.delete(p2d)
print
"ready to delete"
cmds.delete(fText)
cmds.delete([ctrl, rpt, dens, para])
def alignToUV(targetObj="none", sourceObj="none", sourceU=0.0, sourceV=0.0, mainAxis="+z", secAxis="+x", UorV="v"):
"""
inputs should be 1. targetObj 2. sourceObj 3. sourceU 4. sourceV 5. mainAxis(lowerCase, + or -, i.e."-x" 8. secAxis (lowcase, + or -) 7, UorV ("u" or "v" for the direction along surface for the sec axis)
"""
axisDict = {"+x":(1,0,0), "+y":(0,1,0), "+z":(0,0,1), "-x":(-1,0,0), "-y":(0,-1,0), "-z":(0,0,-1)}
#Does this create a new node? no To create a node, use the flag "ch=True". That creates a pointOnSurface node
pos = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, position=True)
posVec = om.MVector(pos[0], pos[1], pos[2])
cmds.xform(targetObj, ws=True, t=pos)
#get normal, tanU and tanV at selected UV position on source surface
tanV = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, tv=True)
tanU = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, tu=True)
norm = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, nn=True)
#decide where up axis is on normal constraint, u or v tangent
if UorV == "v":
wup = tanV
elif UorV == "u":
wup = tanU
#create normal constraint
nc = cmds.normalConstraint(sourceObj, targetObj, aimVector=axisDict[mainAxis], upVector=axisDict[secAxis], worldUpVector=(wup))
cmds.delete(nc) #delete constraint
def swapDupe(obj, target, delete = True, name="", *args):
"""
replaces an target with a duplicate of the obj
select the object you want to duplicate, then the target(s), delete bool, name optional
[obj] is the object to duplicate
[target] is the target to match and delete(?)
[delete] is bool to tell whether to delete the target or not
[name] is string to rename to
"""
if not name:
name = obj
# get pos, rot, scale of target
pos = cmds.xform(target, q=True, ws=True, rp=True)
rot = cmds.xform(target, q=True, ws=True, ro=True)
scl = cmds.getAttr("{0}.scale".format(target))
# duplicate the object and rename to name, if no name just use unique names
dupe = cmds.duplicate(obj, name=name, returnRootsOnly=True, renameChildren=True)
cmds.xform(dupe, ws=True, t=pos)
cmds.xform(dupe, ws=True, ro=rot)
cmds.xform(dupe, ws=True, s=scl[0])
parent = cmds.listRelatives(target, parent=True)
if parent:
cmds.parent(dupe, parent[0])
if delete:
cmds.delete(target)
return(dupe[0])
def closest_pt_on_mesh_rotation(point, mesh, *args):
# TODO - generalize for various orientations, and various rotation orders
"""
takes a point (can be name of transform or iterable(3) of rotations and a poly mesh and gives the rotation [rot
order xyz] (for
aim along y) align to surface of
the xform at that point
"""
if isinstance(point, basestring):
if isType(point, "transform"):
cmds.select(point, r=True)
ptPos = cmds.xform(point, ws=True, q=True, rp=True)
name = point
else:
cmds.warning("zbw_rig.closest_pt_on_mesh_position: the string you gave me isn't a transform")
return ()
elif isinstance(point, (list, tuple)):
if len(point) == 3:
ptPos = point
name = mesh
else:
cmds.warning("zbw_rig.closest_pt_on_mesh_position: there are not the right number of entries in the "
"list you gave me")
# get the rotations to align to normal at this point
loc = cmds.spaceLocator()
CPOMesh = closest_pt_on_mesh_position(point, mesh)
cmds.xform(loc, ws=True, t=CPOMesh)
aimVec = (0, 1, 0)
upVec = (0, 1, 0)
nc = cmds.normalConstraint(mesh, loc, aim=aimVec, upVector=upVec)
rot = cmds.xform(loc, ws=True, q=True, ro=True)
cmds.delete(nc, loc)
return (rot)
def deleteAll(*args):
"""deletes all audio in the scene"""
nodes = cmds.textScrollList(widgets["audioTSL"], q=True, ai=True)
for node in nodes:
cmds.delete(node)
cmds.textScrollList(widgets["audioTSL"], e=True, ra=True)
def dupeIt(*args):
"""uses the first selection and duplicates it to the transforms of the rest of the selected objects, with or without connections"""
sel=cmds.ls(sl=True, type="transform", l=True)
inputs = cmds.radioButtonGrp("inputsRBG", q=True, sl=True)
if sel:
base=sel[0]
if len(sel)>1:
objs=sel[1:]
transforms = {}
x=0
for obj in objs:
#get pos, rot, scale
pos = cmds.xform(obj, ws=True, q=True, t=True)
rot = cmds.xform(obj, ws=True, q=True, ro=True)
scal = cmds.getAttr("%s.scale"%obj)[0]
transforms[x] = [pos, rot, scal]
#delete the obj
cmds.delete(obj)
x=x+1
for key in transforms.keys():
if inputs == 1:
dupe = cmds.duplicate(base)[0]
elif inputs == 3:
dupe = cmds.duplicate(base, un=True, rr=True)[0]
elif inputs == 2:
dupe = cmds.duplicate(base, ic=True)[0]
print dupe
cmds.xform(dupe, ws=True, t=transforms[key][0])
cmds.xform(dupe, ws=True, ro=transforms[key][1])
cmds.setAttr("%s.scale"%dupe, transforms[key][2][0], transforms[key][2][1], transforms[key][2][2])
#TODO - checkbox to copy inputs on orig objects to corresponding inputs on top level of duplicates
else:
cmds.warning("You need to select more than one object in order to swap!")
else:
cmds.warning("Please select some transform nodes to dupe!")
def unlock():
"""Permanently unlock a locked scene
Doesn't throw an error if scene is already unlocked.
"""
try:
cmds.delete("lock")
except ValueError:
pass
def remove(container):
"""Remove an existing `container` from Maya scene
Deprecated; this functionality is replaced by `api.remove()`
Arguments:
container (avalon-core:container-1.0): Which container
to remove from scene.
"""
node = container["objectName"]
# Assume asset has been referenced
reference_node = next((node for node in cmds.sets(node, query=True)
if cmds.nodeType(node) == "reference"), None)
assert reference_node, ("Imported container not supported; "
"container must be referenced.")
log.info("Removing '%s' from Maya.." % container["name"])
namespace = cmds.referenceQuery(reference_node, namespace=True)
fname = cmds.referenceQuery(reference_node, filename=True)
cmds.file(fname, removeReference=True)
try:
cmds.delete(node)
except ValueError:
# Already implicitly deleted by Maya upon removing reference
pass
try:
# If container is not automatically cleaned up by May (issue #118)
cmds.namespace(removeNamespace=namespace, deleteNamespaceContent=True)
except RuntimeError:
pass
def relink(obj, goz_id):
"""Relink object name with existing gozbruhBrushID.
"""
# manages re linking gozbruhBrush IDs, checks for attribute on shape/xform
# in the case of a object being duplicated this removes the duplicate
# to prevent deletion, the 'create' option is prefered
# is only happens when an object was duplicated and merged (original
# still exists)
if cmds.objExists(goz_id):
cmds.delete(goz_id)
cmds.rename(obj, goz_id)
return create(goz_id)
def channelbox_command_break(box, menuItem, key, *args):
with sysCmd.Undo():
for plug in channelBox_SelectedPlugs(box):
if cmds.connectionInfo(plug, isDestination=1):
destination = cmds.connectionInfo(plug, getExactDestination=1)
# when delete source conn from character, must remove from character set or set becomes inconsistent
src_conn = cmds.listConnections(destination, s=1, d=0, type="character")
if src_conn:
warn_msg = "Removed \'^1s\' from character \'^2s\'."
cmds.warning(cmds.format(warn_msg, s=(destination, src_conn[0])))
cmds.character(destination, e=1, rm=src_conn[0])
# is tracking edits?
import maya.api.OpenMaya as om
obj = om.MSelectionList().add(destination).getDependNode(0)
depend_fn = om.MFnDependencyNode(obj)
tracking_edits = depend_fn.isTrackingEdits()
del obj
del depend_fn
if tracking_edits:
src = cmds.connectionInfo(destination, sourceFromDestination=1)
cmds.disconnectAttr(src, destination)
else:
cmds.delete(destination, icn=1)
def channelbox_command_deleteNode(box, menuItem, key, *args):
cmds.delete(cmds.channelBox(box.channelbox, q=1, historyObjectList=1),
cmds.channelBox(box.channelbox, q=1, outputObjectList=1))
def create_and_animate_trees():
"""
Function uses the create_palm() support function to create and animate some palm trees.
It was created to show how to create basic geometry objects, use instances and use modificators.
"""
palm1 = create_palm(diameter=1.3, segs_num=20, leafs_num=9, bending=34, id_num=1, anim_start=11, anim_end=26)
palm2 = create_palm(diameter=1.6, segs_num=20, leafs_num=9, bending=34, id_num=2, anim_start=40, anim_end=45)
palm3 = create_palm(diameter=1.1, segs_num=18, leafs_num=9, bending=24, id_num=3, anim_start=20, anim_end=35)
palm4 = create_palm(diameter=1.1, segs_num=24, leafs_num=9, bending=24, id_num=4, anim_start=25, anim_end=40)
cmds.currentTime(55) # The removal of history had strange effect when it was applied before tree animation
# Next line is intended to avoid a bug. If the history has to be deleted with a cmds.delete function. If it
# would not be modified then the bend modifictor would have to be moved wit an object or it would affect an object
# in different ways then desired during a changes in its position. The problem is, that during that an evaluation
# of commands may take some time and the removing of history resulted in not deformed mesh or a partialy
# deformed mesh. This is why cmds.refresh() ommand was used.
cmds.refresh(f=True)
cmds.delete(palm1, ch=True)
cmds.rotate(0.197, 105, 0.558, palm1, absolute=True) # Rotate the palm
cmds.move(-8.5, -4.538, 18.1, palm1, absolute=True) # Position the palm
cmds.parent(palm1, 'land', relative=True) # Rename it
cmds.delete(palm2, ch=True)
cmds.rotate(-16.935, 74.246, -23.907, palm2)
cmds.move(29.393, -3.990, 4.526, palm2)
cmds.parent(palm2, 'land', relative=True)
cmds.delete(palm3, ch=True)
cmds.move(24.498, -3.322, 36.057, palm3)
cmds.rotate(0.023, 0.248, -1.950, palm3)
cmds.parent(palm3, 'land', relative=True)
cmds.delete(palm4, ch=True)
cmds.move(4.353, -1.083, 22.68, palm4)
cmds.rotate(-150, -102.569, 872.616, palm4)
cmds.parent(palm4, 'land', relative=True)