def test_listconnections(self):
print(u"test_listconnections")
cmds.file(new=True, f=True)
cube = cmds.polyCube()[0]
m = mtn.M(u"pCube1")
cmds.setKeyframe("pCube1.tx", "pCube1.ty", "pCube1.tz",
"pCube1.rx", "pCube1.ry", "pCube1.rz",
"pCube1.sx", "pCube1.sy", "pCube1.sz")
assert(type(m.listConnections()) == list)
assert(m.listConnections(asGenerator=True).__class__.__name__ == "generator")
m.listConnections(asGenerator=True, c=True)
m.listConnections(asGenerator=True, p=True)
m.listConnections(asGenerator=True, c=True, p=True)
m.listConnections(c=True)
m.listConnections(p=True)
m.listConnections(c=True, p=True)
assert(m.listConnections(c=True,s=False) == [])
assert(m.listConnections(p=True,s=False) == [])
python类setKeyframe()的实例源码
def delete_later_keys(obj, frame, *args):
"""sets a key at 'frame' and then deletes all subsequent keys in the timeline (time based only)"""
animTypes = ["animCurveTL","animCurveTA", "animCurveTT", "animCurveTU"]
animNodes = cmds.listConnections(obj, type="animCurve")
if not animNodes:
return()
for a in animNodes:
if (cmds.objectType(a)in animTypes):
cmds.setKeyframe(a, time=frame)
cmds.cutKey(a,clear=1, time=(frame + 1, 100000))
def cutSelected(selectionOption=1, setKey=True):
keySel = _getKeySelection(selectionOption)
if keySel.selectedKeys():pass
elif keySel.frameRange():pass
if setKey:
start, end = keySel.time
if keySel.findKeyframe('previous', time=(start-1,)) < start-1:
mc.setKeyframe(keySel.curves, time=(start-1,), insert=True)
if keySel.findKeyframe('next', time=(end,)) > end:
mc.setKeyframe(keySel.curves, time=(end,), insert=True)
keySel.cutKey()
def cutUnselected(selectionOption=1, setKey=True):
keySel = _getKeySelection(selectionOption)
start = None
end = None
if keySel.keyRange():
start, end = keySel.time
else:
start, end = utl.frameRange()
if setKey:
if keySel.findKeyframe('previous', time=(start,)) < start:
mc.setKeyframe(keySel.curves, time=(start,), insert=True)
if keySel.findKeyframe('next', time=(end-1,)) > end-1:
mc.setKeyframe(keySel.curves, time=(end-1,), insert=True)
keySel.cutKey(time=(':'+str(start),))
keySel.cutKey(time=(str(end)+':',))
def minimizeRotationCurves(obj):
'''
Sets rotation animation to the value closest to zero.
'''
rotateCurves = mc.keyframe(obj, attribute=('rotateX','rotateY', 'rotateZ'), query=True, name=True)
if not rotateCurves or len(rotateCurves) < 3:
return
keyTimes = mc.keyframe(rotateCurves, query=True, timeChange=True)
tempFrame = sorted(keyTimes)[0] - 1
#set a temp frame
mc.setKeyframe(rotateCurves, time=(tempFrame,), value=0)
#euler filter
mc.filterCurve(rotateCurves)
#delete temp key
mc.cutKey(rotateCurves, time=(tempFrame,))
def setAnimValue(plug, value, tangentType=None):
'''
Sets key if the channel is keyed, otherwise setAttr
'''
if mc.keyframe(plug, query=True, name=True):
mc.setKeyframe(plug, value=value)
if tangentType:
time = mc.currentTime(query=True)
itt = tangentType
ott = tangentType
if tangentType == 'step':
itt = 'linear'
mc.keyTangent(plug, time=(time,), edit=True, itt=itt, ott=ott)
mc.setAttr(plug, value)
def PlaceNote():
# Notetrack number
note_tracks = 0
# We need to ask for a name
if not (cmds.objExists("SENotes")):
# We need to make the SENotes parent first
base_track = cmds.spaceLocator()
# Rename
cmds.rename(base_track, "SENotes")
# Notetrack name
noteName = "new_notetrack" + str(note_tracks)
# Now we can make the child (if you have > 50000 notetracks, we got a problem...)
for npos in xrange(note_tracks, 50000):
# Setup
noteName = "new_notetrack" + str(npos)
# Check
if not (cmds.objExists(noteName)):
# Exit
break
# Now make it and parent it
notetrack = cmds.spaceLocator()
# Rename
cmds.rename(notetrack, noteName)
# Parent it
mel.eval("parent " + noteName + " SENotes")
# Get current time
currentFrame = cmds.currentTime(query = True)
# Key it
cmds.setKeyframe(noteName, time = currentFrame)
# Log it
print("A new notetrack was created")
# Selects all bones
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 zbw_stepAll():
sel = cmds.ls(sl=True)
keyList = []
keySet = set()
allKeys = []
#get timeslider range start
startF = cmds.playbackOptions(query=True, min=True)
#get end frame
endF = cmds.playbackOptions(query=True, max=True)
#get all the keyed frames
for this in sel:
keyList = cmds.keyframe(this, query=True, time=(startF,endF))
for key in keyList:
key = int(key)
keySet.add(key)
#print keyList
keySet = set(keyList)
for frame in keySet:
allKeys.append(frame)
allKeys.sort()
allKeys.reverse()
#print allKeys
for object in sel:
for thisKey in allKeys:
cmds.currentTime(thisKey)
cmds.setKeyframe(object, t=thisKey, ott="step")
#pull down anim from master
def set_scale_keys(target, keyframes):
"""
Function animates the scale of given object by creating the given keyframes.
:param obj: String - Name of an object which scale will be animated
:param keyframes: Python list - Keyframes that will be created: [[int time, float scale (1 = 100%),] ...]
"""
for keyframe in keyframes: # For every keyframe from the list of keyframes scale object at proper time
scale_value = float(keyframe[0])
cmds.setKeyframe(target, attribute='scaleX', v=scale_value, time=keyframe[1], itt="fast", ott="fast")
cmds.setKeyframe(target, attribute='scaleY', v=scale_value, time=keyframe[1], itt="fast", ott="fast")
cmds.setKeyframe(target, attribute='scaleZ', v=scale_value, time=keyframe[1], itt="fast", ott="fast")
def set_position_keys(target, keyframes):
"""
Function animates the position of given object by creating the given keyframes.
:param obj: String - Name of an object which scale will be animated
:param keyframes: Python list - Keyframes that will be created: [[int time, [float x, float y, float z]], ...]
"""
for keyframe in keyframes: # For every keyframe from the list of keyframes scale object at proper time
cmds.setKeyframe(target, attribute='translateX', v=keyframe[0][0], time=keyframe[1], itt="fast", ott="fast")
cmds.setKeyframe(target, attribute='translateY', v=keyframe[0][1], time=keyframe[1], itt="fast", ott="fast")
cmds.setKeyframe(target, attribute='translateZ', v=keyframe[0][2], time=keyframe[1], itt="fast", ott="fast")
def change_hierarchy_and_animate():
"""
Function modifies the hierarchy of scene and creates some final animations, that ware not possible to create earlier.
It also creates cameras and lights.
"""
cmds.lookThru( 'perspView', 'RenderCamera1') # Change the perspective viewport to the render camera.
top_locator = cmds.spaceLocator() # Parent for all the elemements that will rotate together
objects_list = ['land', 'water', 'cloud', 'shark', ]
for obj in objects_list:
cmds.parent(obj, top_locator)
cmds.setKeyframe(top_locator, attribute='rotateY', v=20, time=260, itt="plateau", ott="plateau")
cmds.setKeyframe(top_locator, attribute='rotateY', v=0, time=0, itt="linear", ott="linear")
dome_light = cmds.polySphere(r=500) # This sphere is a substitute of a skylight in 3Ds Max
cmds.polyNormal(dome_light, normalMode=0) # The normals have to point to inside
cmds.setAttr(dome_light[0]+".miDeriveFromMaya", 0) # Enable changes in object render settings
cmds.setAttr(dome_light[0]+".miVisible", 0) # This object will be invisible to camera
cmds.setAttr(dome_light[0]+".miShadow", 0) # And will not affect shadows
cmds.rename(dome_light[0], "dome_light")
area_light = cmds.shadingNode('areaLight', asLight=True)
cmds.scale(25, 25, 25, area_light, absolute=True)
cmds.move(-230.59, 178.425, 99.192, area_light)
cmds.rotate(0, -68.929, -37.987, area_light)
cmds.setAttr(area_light+".intensity", 120000.0)
cmds.setAttr(area_light+".areaLight", 1)
cmds.setAttr(area_light+".areaType", 1)
cmds.setAttr(area_light+".decayRate", 2)
cmds.setAttr(area_light+".areaHiSamples", 64)
def cutEarlier(selectionOption=1, setKey=True):
keySel = _getKeySelection(selectionOption)
keySel.fromBeginning()
if setKey and keySel.findKeyframe('previous', time=(keySel._timeRangeEnd,)) < keySel._timeRangeEnd :
mc.setKeyframe(keySel.curves, time=keySel._timeRangeEnd)
keySel.cutKey()
def cutLater(selectionOption=1, setKey=True):
keySel = _getKeySelection(selectionOption)
keySel.toEnd()
timeValue = keySel._timeRangeStart-keySel.shortestTime
if setKey and keySel.findKeyframe('next', time=(timeValue,)) > timeValue:
mc.setKeyframe(keySel.curves, time=(timeValue,))
keySel.cutKey()
def __init__(self, curve_sel, vertex_list, chain_geo):
self.curve_sel = curve_sel
self.verts = vertex_list
self.chain_geo = chain_geo
self.find_length = Find_Out()
self.link_length = self.find_length.edge_length(self.verts)
self.chain_length = self.find_length.curve_length(self.curve_sel)
self.link_total = int(self.chain_length/self.link_length)
self.motion_path_name = str(self.chain_geo) + '_Path'
cmds.pathAnimation(self.chain_geo, name = self.motion_path_name, fractionMode = True, follow= True, followAxis = 'x',
upAxis = 'y', worldUpType = 'object', startTimeU = 1, endTimeU = self.link_total, c = self.curve_sel)
cmds.setKeyframe(self.motion_path_name + '.frontTwist', v = 0.0, t = 1 )
cmds.setKeyframe(self.motion_path_name + '.frontTwist', v = 60.0*self.link_total, t = self.link_total )
cmds.keyTangent(self.motion_path_name + '.uValue', itt = 'linear', ott = 'linear' )
cmds.keyTangent(self.motion_path_name + '.frontTwist', itt = 'linear', ott = 'linear')
cmds.snapshot( self.chain_geo, constructionHistory=True, startTime=1, endTime = self.link_total, increment=1, update = 'animCurve',
name = str(self.chain_geo) + '_snapShot' )
self.chain_group = cmds.group( em=True, name=str(self.chain_geo) + '_geo_grp' )
self.chain_list = cmds.listRelatives(str(self.chain_geo + '_snapShotGroup'))
for dummy_geo in self.chain_list:
cmds.delete(icn = True, ch = True)
cmds.parent(dummy_geo, self.chain_group)
def addMarksToScene(marks):
'''
This is temp and will possibly be rolled into future releases.
'''
start,end = utl.frameRange()
camera = utl.getCurrentCamera()
camShape = mc.listRelatives(camera, shapes=True)[0]
aov = mc.getAttr(camShape+'.horizontalFilmAperture')
name = 'ml_stopwatch_'
numStopwatches = len(mc.ls(name+'*', type='locator'))
top = mc.spaceLocator(name=name+'#')
ename = ':'.join([str(x) for x in marks])
mc.addAttr(top, longName='keyTimes', at='enum', enumName=ename, keyable=True)
markRange = float(marks[-1]-marks[0])
viewWidth = aov*2
viewHeight = -0.4*aov+(numStopwatches*aov*0.08)
depth = 5
for mark in marks[1:-1]:
ann = mc.annotate(top, text=str(mark))
mc.setAttr(ann+'.displayArrow', 0)
#parent
annT = mc.parent(mc.listRelatives(ann, parent=True, path=True), top)[0]
annT = mc.rename(annT, 'mark_'+str(round(mark)))
ann = mc.listRelatives(annT, shapes=True, path=True)[0]
#set the position
normalX = float(mark-marks[0])/markRange-0.5
mc.setAttr(annT+'.translateX', viewWidth*normalX*2)
mc.setAttr(annT+'.translateY', viewHeight)
mc.setAttr(annT+'.translateZ', -depth)
#keyframe for color
mc.setAttr(ann+'.overrideEnabled', 1)
mc.setKeyframe(ann, attribute='overrideColor', value=17, time=(int(marks[0]-1),int(mark+1)))
mc.setKeyframe(ann, attribute='overrideColor', value=13, time=(int(mark),))
mc.keyTangent(ann+'.overrideColor', ott='step')
mc.select(clear=True)
mc.parentConstraint(camera, top)
def setKeyframe(self, deleteSubFrames=False, **kwargs):
'''
Wrapper for the setKeyframe command. Curve and time arguments will be provided based on
how this object was intitialized, otherwise usage is the same as maya's setKeyframe command.
Option to delete sub-frames after keying.
'''
if not 'time' in kwargs:
#still not sure about how I want to do this, but we need a discrete time.
#if time is a string set to current time
if isinstance(self.time, tuple) and (isinstance(self.time[0], str) or len(self.time)>1):
kwargs['time'] = mc.currentTime(query=True)
else:
kwargs['time'] = self.time
if 'insert' in kwargs and kwargs['insert'] == True:
#setKeyframe fails if insert option is used but there's no keyframes on the channels.
#key any curves with insert, then key everything again without it
if self.curves:
mc.setKeyframe(self.curves, **kwargs)
kwargs['insert'] = False
#want to try setting keys on nodes first, since certain setKeyframe arguments wont work
#as expected with channels
if self._nodes:
mc.setKeyframe(self.nodes, **kwargs)
self._curves = mc.keyframe(self.nodes, query=True, name=True)
else:
mc.setKeyframe(self.channels, **kwargs)
self._curves = mc.keyframe(self.channels, query=True, name=True)
#there's a new selection of curves, so reset the member variables
self._channels = list()
self._nodes = list()
self._time = kwargs['time']
if deleteSubFrames:
#remove nearby sub-frames
#this breaks at higher frame ranges because maya doesn't keep enough digits
#this value is also different for different frame rates
if self.currentTime % 1 == 0 and -9999 < self.currentTime < 9999:
#the distance that keys can be is independent of frame rate, so we have to convert based on the frame rate.
tol = self.shortestTime
self.cutKey(time=(self.currentTime+tol, self.currentTime+0.5))
self.cutKey(time=(self.currentTime-0.5, self.currentTime-tol))