예제 #1
1
	def apply( self, attrPath, sourceRange, applyStart, additive=False ):
		'''
		used to put the animation data on this instance to an actual attribute

		sourceRange should be a 2-tuple representing the 0-based time range of the animation data to apply
		applyStart should be the start time at which to place the animation
		'''

		#if the attrPath isn't settable, bail - maya sometimes crashes if you try to pasteKey on a non-settable attr
		if not getAttr( attrPath, se=True ):
			return

		keyCmdKwargs = {}
		if sourceRange:
			keyCmdKwargs[ 't' ] = sourceRange

		animCurveNode = self.constructNode( applyStart )
		if additive:
			if cmd.keyframe( attrPath, q=True, kc=True ):
				for t in cmd.keyframe( animCurveNode, q=True ):
					val = cmd.keyframe( attrPath, t=(t,), q=True, vc=True, eval=True ) or [getAttr( attrPath )]
					cmd.keyframe( animCurveNode, t=(t,), e=True, vc=val[0], relative=True )
			else:
				cmd.keyframe( animCurveNode, e=True, vc=getAttr( attrPath ), relative=True )

		try:
			cmd.copyKey( animCurveNode, clipboard='api', **keyCmdKwargs )
			cmd.pasteKey( attrPath, option='replace', clipboard='api' )
		finally:
			cmd.delete( animCurveNode )
예제 #2
0
def transferAdd(src, tgt, range=None, tgtTime=None, matchRo=False):
    '''
	this is the core proc for copy/paste animation transfers. like the transfer command, this proc only
	works with a single source, single target
	'''
    #if there are no keys, quit
    try:
        if cmd.keyframe(src, q=True, kc=True):
            return
    except RuntimeError:
        return

    time = tgtTime
    if tgtTime is None:
        time = cmd.currentTime(q=True)

    #match the rotation orders of the objects.
    if matchRo:
        try:
            cmd.setAttr(tgt + ".ro", cmd.getAttr(src + ".ro"))
        except RuntimeError:
            pass

    #finally, perform the copy - this may fail as we still haven't validated the existence of tgt...
    try:
        cmd.copyKey(src,
                    time=range,
                    hierarchy='none',
                    animation='objects',
                    o='curve')
        cmd.pasteKey(tgt, time=time, option='merge', animation='objects')
    except RuntimeError:
        return
예제 #3
0
def SendAnimation(a, b, optionType):
    if cmds.selectKey(a) > 0:
        if optionType == option(option.keys):
            cmds.cutKey(a, time=(cTime, cTime), option=optionType.__str__())
        else:
            cmds.copyKey(a, option=optionType.__str__())
        cmds.pasteKey(b, option='replaceCompletely')
예제 #4
0
def loopKeyFrameC(obj,startFrame,endFrame,offsetFrame):
    print "loopKeyFrameC"#,obj,startFrame,endFrame,offsetFrame
    keyAbleAttList=["translateX","translateY","translateZ","rotateX","rotateY","rotateZ","scaleX","scaleY","scaleZ","slot_alpha","slot_red","slot_green","slot_blue"] #["translateX","translateY","translateZ","rotateX","rotateY","rotateZ","scaleX","scaleY","scaleZ"]
    SOframe = float(startFrame +offsetFrame)
    EOframe = float(endFrame + offsetFrame)
    #cmds.keyframe(obj,at="translateX",q=True)
    for attr in keyAbleAttList:
        try:
            keyframeList = cmds.keyframe(obj,at=attr,q=True)
            keyframeListCount = len(keyframeList)
        except:
            keyframeListCount = 0
        print attr,obj,SOframe,EOframe,keyframeList
        if keyframeListCount > 0:
            if startFrame < keyframeList[0]:
              #  print  "startFrame"    
                firstFrame = float(keyframeList[0])               
                startFrameValue = cmds.getAttr('%s.%s'%(obj,attr),t= firstFrame)
                cmds.setKeyframe(t=(startFrame,startFrame),e=True,at=attr,v=startFrameValue)
            if endFrame > keyframeList[-1]:
              #  print  "endFrame"  
                lastFrame =  float(keyframeList[-1])                   
                endFrameValue  = cmds.getAttr('%s.%s'%(obj,attr),t = lastFrame)

                cmds.setKeyframe(t=(endFrame,endFrame),e=True,at=attr,v=endFrameValue)

            cmds.cutKey(obj,at=attr,t= (startFrame,endFrame))
            cmds.pasteKey(obj,at=attr , t= (SOframe,))
            newKeyframeList = cmds.keyframe(obj,at=attr,q=True)
            newLastFrame = newKeyframeList[-1]
           # print "newKeyframeList,newLastFrame",newKeyframeList,newLastFrame
            cmds.setInfinity( obj,pri='cycle', poi='cycle' ,at=attr)
            cmds.keyTangent(obj,t=(newLastFrame,newLastFrame),ott ="step",e=True)
예제 #5
0
def applyCallback(*pArgs):
#	print "-------------applyCallback----------------"
#	print "first mode= %s" %_mode 
#	print "first key= %s" %_key
#	print "attri key= %s" %_attri

# call function to chect array after press "apply"
	checkList()
	
	global index
	index=0

	
	nowJ=cmds.ls(orderedSelection=True)
	nowTime=mc.currentTime(q=1)
	for i in nowJ:
#	    print "now i= %s" %i
	    index += 1
	    if index >= 2:
	        targetJ=nowJ[index-1]
#	        print "target obj is = %s" %(targetJ) 
	        if _key == 2: #all key
	            cmds.copyKey(nowJ,at=_attri)
	            cmds.pasteKey(targetJ,at=_attri,option="replace")
	            if _mode == 2:
	                cmds.scaleKey(targetJ,at=_attri,valueScale=-1)
	        else: # single key

	            cmds.copyKey(nowJ,at=_attri,time=(nowTime,nowTime))
	            cmds.pasteKey(targetJ)
	            if _mode == 2:
	                cmds.scaleKey(targetJ,at=_attri,valueScale=-1,time=(nowTime,nowTime))
예제 #6
0
def copyKeyframes():
    objs = cmds.ls(selection=True)

    if (len(objs) < 2):
        cmds.error("Please select at least two Objects")

    sourceObj = objs[0]  # First selected object is for copy

    # Find animated attributes and put on a list
    animAttributes = cmds.listAnimatable(sourceObj)

    # Go round the list
    for attribute in animAttributes:
        # Get the key frame numbers of animated attributes
        numKeyframes = cmds.keyframe(attribute, query=True, keyframeCount=True)

        if (numKeyframes > 0):
            # Copy keyframes where animated attribute is existed
            cmds.copyKey(attribute)  # Hold keyframes temporarily in memory
            # No additional flag, grabbing all keyframes for the specified attribute

            # Paste keyframes to other objects
            for obj in objs[1:]:
                cmds.pasteKey(obj,
                              attribute=getAttrName(attribute),
                              option="replace")
예제 #7
0
    def individualCurveDenoise(self, curveName, faceGroup, TIME_VAL,
                               THRESHOLD_VAL, sampleFace):

        print "Entered Ind Sample"
        startTime = self.minSliderTime
        endTime = self.maxSliderTime

        nSId = curveName.find(':')
        if nSId != -1:
            outTransform = curveName[:nSId] + str(
                sampleFace) + curveName[nSId:]
        else:
            outTransform = self.OTHER_FACE_IDS % sampleFace
            outTransform = outTransform + curveName

        cmds.cutKey(outTransform,
                    time=(self.minSliderTime + 1, self.maxSliderTime - 1),
                    option="keys")
        cmds.copyKey(curveName,
                     time=(self.minSliderTime, self.maxSliderTime),
                     option="keys")  # or keys?
        cmds.pasteKey(outTransform,
                      time=(self.minSliderTime, self.maxSliderTime),
                      option="replace")

        cmds.filterCurve(outTransform,
                         filter="simplify",
                         timeTolerance=TIME_VAL,
                         tolerance=THRESHOLD_VAL)
예제 #8
0
def copy_keys(source=None, target=None, offset=0, rotateOrder=True):
    if not cmds.keyframe(source, q=True):
        om.MGlobal.displayInfo("Source: {} has no animation".format(source))
        return

    if not isinstance(target, (list, tuple)):
        target = [target]
    # TODO: animLayer check
    # if layer:
    #     cmds.select(target)
    #     cmds.animLayer(layer, edit=True, addSelectedObjects=True)

    #     #we want to make sure rotation values are within 360 degrees, so we don't get flipping when blending layers.
    #     utl.minimizeRotationCurves(source)
    #     for each in target:
    #         utl.minimizeRotationCurves(each)

    if rotateOrder:
        for each in target:
            try:
                if cmds.getAttr(each + ".rotateOrder", keyable=True):
                    cmds.setAttr(each + ".rotateOrder",
                                 cmds.getAttr(source + ".rotateOrder"))
            except:
                pass

    cmds.copyKey(source)
    # if layer:
    #     cmds.animLayer(layer, edit=True, selected=True)
    for each in target:
        cmds.pasteKey(each, option="insert", timeOffset=offset)
예제 #9
0
def copyAnim(filename, objs, *args):
    #objs = cmds.ls(sl=1)
    # first: is there even anything here?
    if len(objs) < 1:
        return False
    # check for unknown nodes: this prevents ASCII conversion.
    unk = cmds.ls(type='unknown')
    if len(unk) > 0:
        cmds.error(
            'You have unknown nodes in your scene. Run the cleanup utility before exporting animation.'
        )
    if cmds.objExists('animXferTEMP'): cmds.delete('animXferTEMP')
    cmds.createNode('transform', n='animXferTEMP')
    for obj in objs:
        attrs = cmds.listAttr(obj, k=1)
        startTime = -100000
        endTime = 100000
        for attr in attrs:
            numkeys = cmds.keyframe(obj, q=1, at=attr, kc=1)
            if numkeys > 0:
                cmds.addAttr('animXferTEMP',
                             at='double',
                             longName=obj.replace(':', '___') + '_ANIM_' +
                             attr)
                cmds.copyKey(obj, t=(startTime, endTime), at=attr)
                cmds.pasteKey('animXferTEMP',
                              option='replaceCompletely',
                              at=obj.replace(':', '___') + '_ANIM_' + attr)
    cmds.select('animXferTEMP')
    if filename.split('.')[-1] != '.ma':
        filename = filename + '.ma'
    f = cmds.file(filename, es=1, chn=1, type='mayaAscii', force=1)
    print 'wrote animation to file: %s' % (f)
    cmds.delete('animXferTEMP')
예제 #10
0
파일: utils.py 프로젝트: lazerdaze/lancer
def transfer_anim(node, attribute, layer):
    time_range = get_time_range()
    can_paste = False

    try:
        cmds.copyKey(node,
                     attribute=attribute,
                     time=time_range,
                     animLayer='BaseAnimation')
        can_paste = True
    except RuntimeError:
        try:
            cmds.copyKey(node, attribute=attribute, time=time_range)
            can_paste = True
        except RuntimeError:
            pass

    # Fixme: Attributes with no animation connections
    if can_paste:
        try:
            cmds.pasteKey(node,
                          attribute=attribute,
                          option="replace",
                          animLayer=layer)
        except:
            pass
    return
예제 #11
0
 def mirror_animation(self):
     """
     Mirrors the animation based on the selected controls, selected anim layer(if any) and selected selected frames
     """
     controls = animMod.get_controls(selected=True)
     selected_frames = animMod.get_frames()
     anim_layers = animMod.get_anim_layers(selected=True)
     if len(anim_layers) > 0:
         for anim_layer in anim_layers:
             for control in controls:
                 opposite_control = animMod.get_opposite_control(node=control)
                 attributes = animMod.get_attributes(node=control, attribute_options=["unlocked", "c", "keyable"]) or []
                 for attribute in attributes:
                     for frame in selected_frames:
                         if cmds.copyKey(control, time=(frame, frame), at=attribute, option="keys", al=anim_layer) != None:
                             cmds.animLayer(anim_layer, edit=True, at="{0}.{1}".format(opposite_control, attribute))
                             cmds.setKeyframe(opposite_control, time=(frame,frame), at=attribute, al=anim_layer)
                             cmds.pasteKey(opposite_control, time=(frame, frame), option="replaceCompletely", al=anim_layer)
     else:
         for control in controls:
             opposite_control = animMod.get_opposite_control(node=control)
             attributes = animMod.get_attributes(node=control, attribute_options=["unlocked", "c", "keyable"]) or []
             for attribute in attributes:
                 for frame in selected_frames:
                     current_key = cmds.copyKey(control, time=(frame, frame), at=attribute, option="keys")
                     if current_key > 0:
                         cmds.setKeyframe(opposite_control, time=(frame), at=attribute)
                         cmds.pasteKey(opposite_control, animation="keysOrObjects", option="replace")
예제 #12
0
def clone():
    selected = cmds.ls(sl=True)
    source = selected.pop(0)
    cmds.copyKey(source, option="curve")
    for target in selected:
        cmds.pasteKey(target, option='replaceCompletely' )
    print "Keys copied successfully",
예제 #13
0
def bakeCameraMeatAnimToClone(camMeta):
    """Given a camera node which has meta data(MetaCamera), create a temporary meta camera which is a clone
    of the camera and bake per frame anim data down. The passed in camera will be renamed so that the camera clone has the
    shot name however we dont not rename the original back to the correct name. The reason for this is so the client
    can do further operations on the baked cam.

    :param camMeta: The MetaCamera instance which is attached to the camera
    :type camMeta: MetaCamera
    :return: The new Baked camera if the keys were baked. otherwise None
    :rtype: MetaCamera or None
    """
    # temp rename so that the the baked camera has the original name
    camMeta.rename("_".join([camMeta.shotName.asString(), "ORIG"]))
    bakedCam = createCamera(camMeta.shotName.asString(),
                            camMeta.startFrame.asInt(),
                            camMeta.endFrame.asInt())
    bakedCam.copyFrom(camMeta)

    result = cmds.copyKey(camMeta.fullPathName())
    if result == 0:
        bakedCam.delete()
        camMeta.rename(camMeta.shotName.asString())
        return
    padding = bakedCam.framePadding.asInt()
    targetName = bakedCam.fullPathName()
    cmds.pasteKey(targetName, option="replace")
    cmds.bakeResults(targetName,
                     t=((bakedCam.startFrame.asInt() - padding),
                        (bakedCam.endFrame.asInt() + padding)),
                     sb=1)
    return bakedCam
예제 #14
0
def transferAdd( src, tgt, range=None, tgtTime=None, matchRo=False ):
	'''
	this is the core proc for copy/paste animation transfers. like the transfer command, this proc only
	works with a single source, single target
	'''
	#if there are no keys, quit
	try:
		if cmd.keyframe(src, q=True, kc=True):
			return
	except RuntimeError: return

	time = tgtTime
	if tgtTime is None:
		time = cmd.currentTime(q=True)

	#match the rotation orders of the objects.
	if matchRo:
		try:
			cmd.setAttr(tgt +".ro", cmd.getAttr(src +".ro"))
		except RuntimeError:
			pass

	#finally, perform the copy - this may fail as we still haven't validated the existence of tgt...
	try:
		cmd.copyKey(src, time=range, hierarchy='none', animation='objects', o='curve')
		cmd.pasteKey(tgt, time=time, option='merge', animation='objects')
	except RuntimeError:
		return
예제 #15
0
    def copyFromProxy(self):
        animCurves = []
        for ac in cmds.ls(type="animCurveTL"):
            animCurves.append(ac)
        for ac in cmds.ls(type="animCurveTA"):
            animCurves.append(ac)
        for ac in cmds.ls(type="animCurveTU"):
            animCurves.append(ac)

        cmds.progressWindow(title=u"导入动画", status=u"导入中...")
        cmds.progressWindow(e=True, progress=0, max=len(animCurves))

        for cv in animCurves:
            cmds.progressWindow(e=True, step=1)
            if cmds.referenceQuery(cv, isNodeReferenced=True): continue
            out = cmds.connectionInfo("%s.output" % cv,
                                      destinationFromSource=True)
            if not out: continue
            out = out[0]
            if out.find('___Proxy') == -1: continue
            if not len((':%s' % out).split(self.namespace)) == 2: continue

            attr = out.split(".")[-1]
            target = out.split("___")[0]

            try:
                cmds.copyKey(cv)
                cmds.pasteKey(target,
                              attribute=attr,
                              option=self.configuration['mode'])
            except Exception, e:
                print "%s" % e
예제 #16
0
    def copyToProxy(self, startTime, endTime):
        animCurves = []
        for ac in cmds.ls(type="animCurveTL"):
            animCurves.append(ac)
        for ac in cmds.ls(type="animCurveTA"):
            animCurves.append(ac)
        for ac in cmds.ls(type="animCurveTU"):
            animCurves.append(ac)

        cmds.progressWindow(title=u"导出动画", status=u"导出中...")
        cmds.progressWindow(e=True, progress=0, max=len(animCurves))

        for cv in animCurves:
            cmds.progressWindow(e=True, step=1)
            if cmds.referenceQuery(cv, isNodeReferenced=True): continue
            out = cmds.connectionInfo("%s.output" % cv,
                                      destinationFromSource=True)
            if out and len((':%s' % out[0]).split(self.namespace)) == 2:
                out = out[0]
                loc = "%s|%s___Proxy" % (self.grp, out.split(".")[0])
                attr = out.split(".")[-1]
                #print "%s.output"%cv, "-> %s.%s"%(loc, attr)

                try:
                    cmds.copyKey(cv)
                    cmds.pasteKey(loc, attribute=attr)
                    cmds.setKeyframe(loc, time=[startTime, endTime])
                except Exception, e:
                    print u"%s" % e
예제 #17
0
def cutPasteKey(src, dst):
    """
    @param dst:
    @param src:
    """
    keys = cmds.cutKey(src)
    if keys: cmds.pasteKey(dst)
예제 #18
0
    def setFaceAsElite(self, id, *args):

        self.lastElite = self.saveFaceCurves()

        eliteChoice = cmds.optionMenu("controlGroup" + str(id),
                                      value=True,
                                      query=True)
        eliteNum = int(eliteChoice[-1])

        shapeTree = self.strongestShapesTree

        for faceGroup, ctlDict in shapeTree.iteritems():

            for ctlName, ctlVal in ctlDict.iteritems():

                nSId = ctlName.find(':')
                if nSId != -1:
                    print "in"
                    out1 = ctlName[:nSId] + str(eliteNum) + ctlName[nSId:]

                else:
                    out1 = (self.OTHER_FACE_IDS + ctlName) % eliteNum

                cmds.cutKey(ctlName,
                            time=(self.minSliderTime + 1,
                                  self.maxSliderTime - 1),
                            option="keys")
                cmds.copyKey(out1,
                             time=(self.minSliderTime, self.maxSliderTime),
                             option="keys")  # or keys?
                cmds.pasteKey(ctlName,
                              time=(self.minSliderTime, self.maxSliderTime),
                              option="replace")

        self.EliteGenes = self.saveFaceCurves()
예제 #19
0
def copyAnimation(source=None,
                  destination=None,
                  pasteMethod='replace',
                  offset=0,
                  start=None,
                  end=None,
                  layer=None):
    '''
    Actually do the copy and paste from one node to another. If start and end frame is specified,
    set a temporary key before copying, and delete it afterward.
    '''

    if pasteMethod == 'replaceCompletely' or not start or not end:
        mc.copyKey(source)
        mc.pasteKey(destination, option=pasteMethod, timeOffset=offset)
    else:

        #need to do this per animation curve, unfortunately, to make sure we're not adding or removing too many keys
        animCurves = mc.keyframe(source, query=True, name=True)
        if not animCurves:
            return

        #story cut keytimes as 2 separate lists means we only have to run 2 cutkey commands, rather than looping through each
        cutStart = list()
        cutEnd = list()
        for curve in animCurves:

            #does it have keyframes on the start and end frames?
            startKey = mc.keyframe(curve,
                                   time=(start, ),
                                   query=True,
                                   timeChange=True)
            endKey = mc.keyframe(curve,
                                 time=(end, ),
                                 query=True,
                                 timeChange=True)

            #if it doesn't set a temporary key for start and end
            #and store the curve name in the appropriate list
            if not startKey:
                mc.setKeyframe(curve, time=(start, ), insert=True)
                cutStart.append(curve)
            if not endKey:
                mc.setKeyframe(curve, time=(end, ), insert=True)
                cutEnd.append(curve)

        mc.copyKey(source, time=(start, end))
        mc.pasteKey(destination,
                    option=pasteMethod,
                    time=(start, end),
                    copies=1,
                    connect=0,
                    timeOffset=offset)

        #if we set temporary source keys, delete them now
        if cutStart:
            mc.cutKey(cutStart, time=(start, ))
        if cutEnd:
            mc.cutKey(cutEnd, time=(end, ))
예제 #20
0
def animCopyPaste():
    sel = cmds.ls(sl=True)
    if len(sel) == 2:
        frame = frameRange()
        cmds.copyKey(sel[0], time=(frame[0], frame[1]), option='keys', hierarchy='none', controlPoints=0, shape=1)
        cmds.pasteKey(sel[1], time=(frame[0], ), f=(frame[0], ), option='merge', copies=1, connect=0, timeOffset=0, floatOffset=0, valueOffset=0)
    else:
        cmds.warning('////... Select 2 objects. The first should have keys...////')
예제 #21
0
파일: assign.py 프로젝트: mocap-ca/cleanup
def assign( source, target, rangemode, replacemode ) :

    ''' Assign a marker, copying from source to destination 
    
    :param source: the source marker to copy data from
    :param target: the target marker to paste data on to
    :param replacemode: 'swap' or 'extract'
    :param rangemode: sett getSourceRange

    '''

    print "Assign: %s ---> %s  Modes:  %s/%s" % (source, target, rangemode, replacemode )

    if not m.objExists( target ) :
        print "renaming: " + source + " as " + target
        m.rename( source, target) 
        return True


    if rangemode == 'gap' :

        # fill the gap in the target using keys from the source

        s = curve.currentSegmentOrGap( target, datarate.nodeRate(source) )
        if s is None or s[0] != 'gap' :
            print "Skipping: " + str(source) + " (not currently in a gap)"
            return

        # values of surrounding keyframes
        sourceIn, sourceOut = s[1]
	# contract range
	sourceIn = sourceIn + 0.5
	sourceOut = sourceOut - 0.5

    else :

        sourceIn, sourceOut = getSourceRange( source, rangemode )
	# expand to 
	sourceIn = sourceIn - 0.5
	sourceOut = sourceOut + 0.5

    print "In: %f  Out: %f" % (sourceIn, sourceOut)
 
    if replacemode == 'swap' :       
        keyTools.swap( (source,target), sourceIn, sourceOut )

    if replacemode == 'extract' :
        # copy the segment over, any clashing keys on the marker will be removed as unlabelled
        keyTools.extractRange( target, sourceIn, sourceOut )
        m.cutKey( source, t = ( sourceIn, sourceOut ) )
        m.pasteKey( target, option='replace' )


    keyTools.setActiveKeys( source, delete=True )
    keyTools.setActiveKeys( target )
    #m.select(target)

    m.dgdirty(a=True)
예제 #22
0
def animPaste():
    # paste anim
    sel = animSelList()
    if len(sel) > 0:
        frame = frameRange()
        cmds.pasteKey(sel, time=(frame[0], ), f=(frame[0], ), option='merge', copies=1, connect=0, timeOffset=0, floatOffset=0, valueOffset=0)
        mel.eval('print \"' + 'Animation pasted at  -' + str(frame[0]) + '-\";')
    else:
        cmds.warning('////... Select at least one object with animation...////')
예제 #23
0
def loopKeyFrame(obj,startFrame,endFrame,offsetFrame):
    print "loopKeyFrame"#,obj,startFrame,endFrame,offsetFrame
    offsetNewStartFrame = startFrame +offsetFrame
    dividFrame = float(endFrame -offsetFrame)
    dividOffsetFrame = dividFrame - 0.01
    endOffsetFrame = endFrame -0.01
    offsetNewEndFrame = endFrame +offsetFrame
    cmds.getAttr('%s.translateX'%obj,t=15.0)
    keyAbleAttList=["translateX","translateY","translateZ","rotateX","rotateY","rotateZ","scaleX","scaleY","scaleZ","slot_alpha","slot_red","slot_green","slot_blue"] #["translateX","translateY","translateZ","rotateX","rotateY","rotateZ","scaleX","scaleY","scaleZ"]

    #cmds.keyframe(obj,at="translateX",q=True)
    for attr in keyAbleAttList:
        cmds.keyTangent(obj,itt ="linear", ott ="linear")
        keyFramesList = cmds.keyframe(obj,at=attr,q=True)
        #print attr,keyFramesList
        if offsetFrame == 0:
            try:
                endFrameAttrValue = cmds.getAttr('%s.%s'%(obj,attr),t=endFrame)
                startFrameAttrValue = cmds.getAttr('%s.%s'%(obj,attr),t=startFrame)
                cmds.setKeyframe(obj,at=attr,t=startFrame,v=startFrameAttrValue) 
                cmds.setKeyframe(obj,at=attr,t=endFrame,v=endFrameAttrValue)
            except:
                pass
            
        else:
            try:
                if len(keyFramesList) >0 :
                   # keyframeListAttr = cmds.keyframe(obj,at=attr)
                    divideFrameAttrValue = cmds.getAttr('%s.%s'%(obj,attr),t=dividFrame)
                    endFrameAttrValue = cmds.getAttr('%s.%s'%(obj,attr),t=endFrame)
                    startFrameAttrValue = cmds.getAttr('%s.%s'%(obj,attr),t=startFrame)
                    offsetFrameValue = cmds.getAttr('%s.%s'%(obj,attr),t=offsetFrame)
                    cmds.setKeyframe(obj,at=attr,t=startFrame,v=startFrameAttrValue) 
                    cmds.setKeyframe(obj,at=attr,t=endFrame,v=endFrameAttrValue) 
                    cmds.keyTangent(obj,itt ="linear", ott ="linear")
         
                    cmds.setKeyframe(obj,at=attr,t=dividFrame,v=divideFrameAttrValue)
                    cmds.setKeyframe(obj,at=attr,t=dividOffsetFrame,v=divideFrameAttrValue)
                    cmds.setKeyframe(obj,at=attr,t=endOffsetFrame,v=endFrameAttrValue)
                    cmds.setKeyframe(obj,at=attr,t=endFrame,v=startFrameAttrValue)

                    cmds.keyTangent(obj,itt ="linear", ott ="linear")
                    
                    #
                    
                   # print attr,currentAttrValue
                    
            except:
                pass
    if offsetFrame == 0:
        pass
    else:
        cmds.cutKey(obj,t=(startFrame,endFrame))
        cmds.pasteKey(obj,t=(offsetNewStartFrame,))
        cmds.keyTangent(obj,itt ="linear", ott ="linear")
        cmds.cutKey(obj,t=(endFrame,offsetNewEndFrame))
        cmds.pasteKey(obj,t=(startFrame,offsetNewStartFrame),o="replace")
예제 #24
0
def legIkToFk(rigNS,side,start=None,end=None,sampleBy=1):
	'''
	Bake IK leg animation to FK controls
	@param rigNS: IK/FK toggle attribute
	@type rigNS: str
	@param side: Leg side ("lf" or "rt")
	@type side: str
	@param start: Transfer animation start frame
	@type start: int or None
	@param end: Transfer animation end frame
	@type end: int or None
	@param sampleBy: Bake animation by N frames
	@type sampleBy: int
	'''
	# Get Start/End
	if start == None: start = mc.playbackOptions(q=True,min=True)
	if end == None: end = mc.playbackOptions(q=True,max=True)
	
	# Set Leg to IK mode
	mc.setAttr(rigNS+':config.'+side+'LegIkFkBlend',0) # IK
	
	# Build IK/FK Joint List
	ikJntList = [rigNS+':'+side+'_leg_ik'+i+'_jnt' for i in ['A','B']]
	ikJntList += [rigNS+':'+side+'_foot_ik'+i+'_jnt' for i in ['A','B']]
	fkJntList = [rigNS+':'+side+'_leg_fk'+i+'_jnt' for i in ['A','B']]
	fkJntList += [rigNS+':'+side+'_foot_fk'+i+'_jnt' for i in ['A','B']]
	
	# Duplicate FK Joints and Constrain to IK
	fkDupList = []
	fkOriList = []
	for i in range(len(ikJntList)):
		fkDupList.append(mc.duplicate(fkJntList[i],po=True)[0])
		fkOriList.append(mc.orientConstraint(ikJntList[i],fkDupList[-1])[0])
	
	# Transfer Baked Anim to FK Joints
	mc.refresh(suspend=True)
	for i in range(len(fkDupList)):
		mc.bakeResults(	fkDupList[i],
						t=(start,end),
						at=['rx','ry','rz'],
						simulation=True,
						preserveOutsideKeys=True,
						sampleBy=sampleBy	)
		mc.copyKey(fkDupList[i],at=['rx','ry','rz'],t=(start,end))
		mc.pasteKey(fkJntList[i],at=['rx','ry','rz'],t=(start,end),option='replace')
	mc.refresh(suspend=False)
	
	# Delete Duplicate Joints and Constraints
	if fkOriList:
		try: mc.delete(fkOriList)
		except Exception, e: print('Error deleting nodes '+str(fkOriList)+'! Exception Msg: '+str(e))
	if fkDupList:
		try: mc.delete(fkDupList)
		except Exception, e: print('Error deleting nodes '+str(fkDupList)+'! Exception Msg: '+str(e))
	
	# Set to FK mode
	mc.setAttr(rigNS+':config.'+side+'LegIkFkBlend',1) # FK
예제 #25
0
def copyAnimation(source=None, destination=None, pasteMethod='replace', offset=0, start=None, end=None, layer=None):
    '''
    Actually do the copy and paste from one node to another. If start and end frame is specified,
    set a temporary key before copying, and delete it afterward.
    '''
    
    if layer:
        mc.select(destination)
        mc.animLayer(layer, edit=True, addSelectedObjects=True)
        
        #we want to make sure rotation values are within 360 degrees, so we don't get flipping when blending layers.
        utl.minimizeRotationCurves(source)
        utl.minimizeRotationCurves(destination)
    
    if pasteMethod=='replaceCompletely' or not start or not end:
        mc.copyKey(source)
        if layer:
            mc.animLayer(layer, edit=True, selected=True)
        mc.pasteKey(destination, option=pasteMethod, timeOffset=offset)
    else:
        
        #need to do this per animation curve, unfortunately, to make sure we're not adding or removing too many keys
        animCurves = mc.keyframe(source, query=True, name=True)
        if not animCurves:
            return
        
        #story cut keytimes as 2 separate lists means we only have to run 2 cutkey commands, rather than looping through each
        cutStart = list()
        cutEnd = list()
        for curve in animCurves:
        
            #does it have keyframes on the start and end frames?
            startKey = mc.keyframe(curve, time=(start,), query=True, timeChange=True)
            endKey = mc.keyframe(curve, time=(end,), query=True, timeChange=True)

            #if it doesn't set a temporary key for start and end
            #and store the curve name in the appropriate list
            if not startKey:
                mc.setKeyframe(curve, time=(start,), insert=True)
                cutStart.append(curve)
            if not endKey: 
                mc.setKeyframe(curve, time=(end,), insert=True)
                cutEnd.append(curve)
            
        mc.copyKey(source, time=(start,end))
        if layer:
            for each in mc.ls(type='animLayer'):
                mc.animLayer(each, edit=True, selected=False, preferred=False)
            mc.animLayer(layer, edit=True, selected=True, preferred=True)
        mc.pasteKey(destination, option=pasteMethod, time=(start,end), copies=1, connect=0, timeOffset=offset)

        #if we set temporary source keys, delete them now
        if cutStart:
            mc.cutKey(cutStart, time=(start,))
        if cutEnd:
            mc.cutKey(cutEnd, time=(end,))
예제 #26
0
    def PasteKeys(self):

        cmds.copyKey('Cube0', attribute='translateY')
        for i in range(0, self.MC.GroupCubeD):

            for j in range(0, self.MC.GroupCubeW):
                if i == 0 and j == 0:
                    continue
                cmds.pasteKey("Cube" + str(i * self.MC.GroupCubeW + j),
                              attribute='translateY')
예제 #27
0
 def pasteTheseKeys(self, *args):
     self.offsetVal = mc.intFieldGrp(self.int_offset, q=True, value1=True)
     self.selObj_pasteKeys = mc.ls(sl=True)
     
     for objectQuant in self.selObj_pasteKeys:
         print objectQuant
         self.ct = mc.currentTime(query = True)
         self.t = self.ct + self.offsetVal
         mc.currentTime(self.t)
        # mc.selectKey(selObj_pasteKeys[objectQuant])
         mc.pasteKey(time=(self.t,self.t), f=(1.0,1.0), option="merge", copies=1, to=0, fo=0, vo=0)
예제 #28
0
def swapAnimation(fromNode, toNode):

    if not mc.keyframe(fromNode, query=True, name=True):
        mc.cutKey(toNode, clear=True)
        return

    attrs = mc.listAttr(fromNode, keyable=True)
    if not attrs:
        return

    for attr in attrs:
        if not mc.attributeQuery(attr, node=toNode, exists=True):
            mc.cutKey(fromNode, attribute=attr, clear=True)
            continue

        fromPlug = '{}.{}'.format(fromNode, attr)
        toPlug = '{}.{}'.format(toNode, attr)

        srcCurve = mc.listConnections(fromPlug,
                                      source=True,
                                      destination=False,
                                      type='animCurve')
        dstCurve = mc.listConnections(toPlug,
                                      source=True,
                                      destination=False,
                                      type='animCurve')

        copySrc = None
        copyDst = None

        if srcCurve:
            copySrc = mc.duplicate(srcCurve[0])[0]

        if dstCurve:
            copyDst = mc.duplicate(dstCurve[0])[0]

        if copySrc:
            try:
                mc.cutKey(copySrc)
                mc.pasteKey(toNode, attribute=attr, option='replaceCompletely')
            except:
                pass
        if copyDst:
            try:
                mc.cutKey(copyDst)
                mc.pasteKey(fromNode,
                            attribute=attr,
                            option='replaceCompletely')
            except:
                pass

    for axis in getMirrorAxis(toNode):
        mc.scaleKey(toNode, attribute=axis, valueScale=-1)
        mc.scaleKey(fromNode, attribute=axis, valueScale=-1)
예제 #29
0
def preroll():
    amintime = cmds.playbackOptions(query=1, minTime=1)
    amaxtime = cmds.playbackOptions(query=1, maxTime=1)
    arolltime = amintime - 21
    amidtime = amintime - 11
    cmds.playbackOptions(minTime=arolltime)
    cmds.cutKey(t=(arolltime, amintime - 1))
    cmds.copyKey(t=(amintime, amintime))
    cmds.pasteKey(t=(amidtime, amidtime))
    cmds.pasteKey(t=(arolltime, arolltime))
    cmds.currentTime(arolltime, update=1, edit=True)
예제 #30
0
def paste_clipboard_curves(anim_curves, start, end):
    # type: (list, float, float) -> None
    """
    Paste original anim curves we stored when the preview button was pressed

    :param anim_curves: list of animation curves
    :param start: start frame
    :param end: end frame
    :return: None
    """
    cmds.pasteKey(anim_curves, t=(start, end), o="replace")
예제 #31
0
def copy_animation(source, destination, offset=0):
    """
    Copy animation from source to destination
    :param str source: Transform node name.
    :param str destination: Transform node name.
    :param int offset: Time offset.
    """
    if not cmds.objExists(source) or not cmds.objExists(destination):
        return
    cmds.copyKey(source)
    delete_connected_curves(destination)
    cmds.pasteKey(destination, option='replaceCompletely', timeOffset=offset)
예제 #32
0
    def CopyAnimation(self):
        ''' Copies the animations of list one into list two '''

        i = 0
        while i < len(self.ListOne):
            cmds.copyKey(self.ListOne[i],
                         time=(cmds.intFieldGrp(self.intGrp, q=True, v1=True),
                               cmds.intFieldGrp(self.intGrp, q=True, v2=True)))
            cmds.pasteKey(self.ListTwo[i], o='replace')
            cmds.warning('Animations copied from ' + self.ListOne[i] + ' to ' +
                         self.ListTwo[i])
            i += 1
예제 #33
0
def parentBake(objs, parent=None, bakeOnOnes=False):

    #check objects can be parented
    parentReferenced = mc.referenceQuery(
        parent, isNodeReferenced=True) if parent else False

    culledObjs = []
    for each in objs:
        eachParent = mc.listRelatives(each, parent=True)
        if mc.referenceQuery(each, isNodeReferenced=True):
            if parentReferenced:
                OpenMaya.MGlobal.displayWarning(
                    "Child and parent are both referenced, skipping: {} > {}".
                    format(each, parent))
                continue
            if eachParent and mc.referenceQuery(eachParent[0],
                                                isNodeReferenced=True):
                OpenMaya.MGlobal.displayWarning(
                    "Node is referenced and can't be reparented, skipping: {}".
                    format(each))
                continue
        if not parent and not eachParent:
            OpenMaya.MGlobal.displayWarning(
                "Node is already child of the world, skipping: {}".format(
                    each))
            continue
        culledObjs.append(each)

    if not culledObjs:
        OpenMaya.MGlobal.displayWarning("No nodes could be reparented.")
        return

    source = []
    destination = []
    for each in culledObjs:
        source.append(mc.duplicate(each, parentOnly=True)[0])
        mc.copyKey(each)
        mc.pasteKey(source[-1], option='replaceCompletely')
        try:
            if parent:
                destination.append(mc.parent(each, parent)[0])
            else:
                destination.append(mc.parent(each, world=True)[0])
        except RuntimeError as err:
            mc.delete(source)
            raise err

    utl.matchBake(source=source,
                  destination=destination,
                  bakeOnOnes=bakeOnOnes)

    mc.delete(source)
예제 #34
0
    def _pasteTiming(self, source, target, key):

        if key.next:
            cmds.copyKey(source, time=(key.keyIndex, key.keyIndex))

            cmds.pasteKey(target, time=(self.currentTime, self.currentTime))

            self.currentTime = self.currentTime + (
                (key.next.time - key.time) * 25)

            self._pasteTiming(source, target, key.next)
        else:
            return
예제 #35
0
파일: gui.py 프로젝트: leandropim/Tapp
    def _pasteTiming(self, source, target, key):

        if key.next:
            cmds.copyKey(source, time=(key.keyIndex, key.keyIndex))

            cmds.pasteKey(target, time=(self.currentTime, self.currentTime))

            self.currentTime = self.currentTime + ((key.next.time
                                                     - key.time) * 25)

            self._pasteTiming(source, target, key.next)
        else:
            return
 def CutAndPasteKeys(self, *args):
     if(self.rootName.GetText()):
         Statics.Commands.DeselectAll()
         self.AddRootJoint()
         currentOption = self.omClamp.GetValue()
         Statics.Commands.SetTime(0)
         position = Statics.Commands.GetTranslation(self.hipName.GetText())
         for i in range(len(self.attributes)):
                 times = Statics.Commands.GetAnimatedTimes(self.hipName.GetText(), self.attributes[i]) or []       
                 keys = commands.keyframe(self.hipName.GetText() + "_" + self.attributes[i], q= True, vc = True) or []
                 if(self.attributes[i] == "translateY"):
                     if(self.bttnCutAllKeys.GetValue1() == False):
                         if(currentOption == "Constrain To Ground"):
                             for f in range(len(keys)):
                                 if(keys[f] > position[0][1]):
                                     commands.setKeyframe(self.rootName.GetText(), attribute = "translateY", time = (0,0), value = 0)                    
                                     commands.cutKey(self.hipName.GetText(), attribute = "translateY", index= (f, (f)))
                                     commands.setKeyframe(self.hipName.GetText(), attribute = "translateY", time = (times[f],times[f]), value = position[0][1])
                                     commands.pasteKey(self.rootName.GetText(), attribute = "translateY", time = (times[f],times[f]), valueOffset = -position[0][1])
                                 elif(keys[f] < position[0][1]):
                                     commands.setKeyframe(self.rootName.GetText(),attribute = "translateY", time = (times[f],times[f]), value = 0)
                         elif(currentOption == "UnConstrain To Ground"):
                             commands.cutKey(self.hipName.GetText(), attribute = "translateY", time = ())
                             commands.pasteKey(self.rootName.GetText(), attribute = "translateY",time = (0,0), valueOffset = -position[0][1])
                     else:
                         commands.cutKey(self.hipName.GetText(), attribute = self.attributes[i],time = ())
                         commands.pasteKey(self.rootName.GetText(), attribute = self.attributes[i],time = (0,0), valueOffset = -position[0][1])
                 else:
                     commands.cutKey(self.hipName.GetText(), attribute = self.attributes[i], time = ())
                     commands.pasteKey(self.rootName.GetText(), attribute = self.attributes[i], time = (0,0), valueOffset = -position[0][2])
     else:
         Statics.Commands.Warning("No root joint name povided in Settings tab")
예제 #37
0
def duplicateFirst(doShaders=False):
    #1. make an array of all selected objects
    target = mc.ls(sl=1)

    #2. if only one selection, just make a new duplicate at the same coordinates...
    if(len(target)==1):
        #call through mel because python has no rc option!
        mel.eval("duplicate -un -ic -rc")

    else:
        try:
            #3. check if the first selection is skinned.
            mc.select(target[0])
            mc.skinCluster(q=True)
            print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
            print "Select the root joint for this to work properly."
            print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
        except:
            #4. ...otherwise, for each selected object...
            for i in range(1,len(target)):

                #5. ...get current selection's position and copy keyframes and shader
                mc.select(target[i])
                pos = mc.xform(target[i], q=True, t=True, ws=True)
                try:
                    shader = getShader()
                except:
                    print "Couldn't get shader."
                try:
                    mc.copyKey()
                except:
                    print "Couldn't copy keys."

                #6. duplicate the first selection
                mc.select(target[0])
                #call through mel because python has no rc option!
                mel.eval("duplicate -un -ic -rc")
            
                #7. move first selection to position and paste keyframes and shader
                mc.move(pos[0],pos[1],pos[2])
                if(doShaders==True):
                    setShader(shader)
                try:
                    mc.pasteKey()
                except:
                    print "Couldn't paste keys."
               
                #8. delete selection
                mc.delete(target[i])
예제 #38
0
def duplicateFirst(doShaders=False):
    #1. make an array of all selected objects
    target = mc.ls(sl=1)

    #2. if only one selection, just make a new duplicate at the same coordinates...
    if (len(target) == 1):
        #call through mel because python has no rc option!
        mel.eval("duplicate -un -ic -rc")

    else:
        try:
            #3. check if the first selection is skinned.
            mc.select(target[0])
            mc.skinCluster(q=True)
            print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
            print "Select the root joint for this to work properly."
            print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
        except:
            #4. ...otherwise, for each selected object...
            for i in range(1, len(target)):

                #5. ...get current selection's position and copy keyframes and shader
                mc.select(target[i])
                pos = mc.xform(target[i], q=True, t=True, ws=True)
                try:
                    shader = getShader()
                except:
                    print "Couldn't get shader."
                try:
                    mc.copyKey()
                except:
                    print "Couldn't copy keys."

                #6. duplicate the first selection
                mc.select(target[0])
                #call through mel because python has no rc option!
                mel.eval("duplicate -un -ic -rc")

                #7. move first selection to position and paste keyframes and shader
                mc.move(pos[0], pos[1], pos[2])
                if (doShaders == True):
                    setShader(shader)
                try:
                    mc.pasteKey()
                except:
                    print "Couldn't paste keys."

                #8. delete selection
                mc.delete(target[i])
def Keyframe_Match(MotionPathText,LocText):
    MotionPath = cmds.textField(MotionPathText,q=1,tx=1)
    Locator = cmds.textField(LocText,q=1,tx=1)
    Selection = cmds.ls(sl=1)[0]
    cmds.cutKey("%s.uValue"%MotionPath,clear=True)

    AnimCurve = cmds.listConnections( "%s.uValue"%Locator, d=False, s=True )[0]

    StartTime = cmds.findKeyframe(Locator,w="first")
    EndTime = cmds.findKeyframe(Locator,w="last")

    cmds.copyKey( "%s.uValue" % Locator, time=(StartTime,EndTime))
    cmds.pasteKey("%s.uValue" % MotionPath)

    cmds.headsUpMessage(u"关键帧匹配完成")
예제 #40
0
    def saveKeys(self, attrs, replaceStored=True, removeOld=True):
        if self.hasSavedKeys and replaceStored:
            mc.delete(self._animStoreLoc)

        func = mc.copyKey
        if removeOld:
            func = mc.cutKey
        self.hasSavedKeys = func(
            self.obj.mNode,
            at=attrs,
            time=(mc.currentTime(q=True),
                  mc.findKeyframe(self.obj.mNode, which='last') + 1))
        if self.hasSavedKeys:
            self._animStoreLoc = LOC.create(name='animStoreLoc')
            mc.pasteKey(self._animStoreLoc, at=attrs, o='replaceCompletely')
		def copyPaste_main_animation(i):
			cmds.animLayer(obj.final_layer_name, e = True, at = obj.nonLockedList)
			cmds.select(obj.temp_obj_node, r = True)
			
			if (obj.check_cycle):
				#print myLog, 'Infinity changed to "Cycle"'
				cmds.cutKey(time = (obj.min_loop_time, obj.start_time - 1))
				cmds.cutKey(time = (obj.end_time + 1, obj.max_loop_time))
				cmds.setInfinity(pri = "cycle", poi = "cycle")
			else:
				#print myLog, 'Infinity changed to "Constant"'
				cmds.setInfinity(pri = "constant", poi = "constant")
				
			temp_copyKey = cmds.copyKey(obj.temp_obj_node, at = obj.nonLocked_attributes)
			#cmds.copyKey(obj.temp_obj_node, at = nonLocked_attributes)
			cmds.pasteKey(obj.list_objects[i], o = "replace", al = obj.final_layer_name, at = obj.nonLocked_attributes)
예제 #42
0
파일: rigTools.py 프로젝트: myCodeTD/pkmel
def createCleanedCamera() :

	# Select camera then run the script.
	# Script will duplicate selected camera.

	cleanedCam = 'cleanedNuke_cam'

	if mc.objExists( cleanedCam ) :
		mc.delete( cleanedCam )

	selectedCam = ''
	selectedCamShp = ''

	selected = mc.ls( sl=True , l=True )[0]
	
	if mc.nodeType( selected ) == 'camera' :
		selectedCamShp = selected
		selectedCam = mc.listRelatives( selected , p=True , f=True )[0]
	else :
		selectedCam = selected
		selectedCamShp = mc.listRelatives( selected , type='shape' , f=True )[0]

	mc.select( selectedCam )
	mc.duplicate( selectedCam , rr=True , n=cleanedCam )
	mc.parent( w=True )

	duppedCamShp = mc.listRelatives( cleanedCam , type='shape' , f=True )[0]

	for attr in ( 'tx' , 'ty' , 'tz' , 'rx' , 'ry' , 'rz' ) :
		mc.setAttr( '%s.%s' % ( cleanedCam , attr ) , l=False )

	minTime = mc.playbackOptions( q=True , min=True )
	maxTime = mc.playbackOptions( q=True , max=True )

	animCurves = mc.listConnections( selectedCamShp , s=True , type='animCurve' )
	attrs = []
	if animCurves :
		for animCurve in animCurves :
			
			attr = mc.listConnections( animCurve , d=True , p=True )[0].split( '.' )[1]
			
			mc.copyKey( selectedCamShp , attribute=attr )
			mc.pasteKey( duppedCamShp , attribute=attr )
	
	parCons = mc.parentConstraint( selectedCam , cleanedCam )
	mc.bakeResults( cleanedCam , simulation=True , t=( minTime , maxTime ) )
	mc.delete( parCons )
예제 #43
0
	def apply( self, attrPath, sourceRange, applyStart ):
		'''
		used to put the animation data on this instance to an actual attribute

		sourceRange should be a 2-tuple representing the 0-based time range of the animation data to apply
		applyStart should be the start time at which to place the animation
		'''
		keyCmdKwargs = {}
		if sourceRange:
			keyCmdKwargs[ 't' ] = sourceRange

		animCurveNode = self.constructNode( applyStart )
		try:
			cmd.copyKey( animCurveNode, clipboard='api', **keyCmdKwargs )
			cmd.pasteKey( attrPath, option='replace', clipboard='api' )
		finally:
			cmd.delete( animCurveNode )
예제 #44
0
def extractBefore() :

    ''' extract all the keys after the current frame '''

    sel = m.ls(sl=True)
    cur = m.currentTime(q=True)
    for i in sel :
        keys = m.keyframe(i, q=True)
        if keys is None : continue
        m.cutKey(i, time=(min(keys), cur))
        loc = createBox(current = i)
        m.pasteKey(loc[0], option="replace")

    m.select(sel)

    for i in sel :  setActiveKeys( i )
    setActiveKeys( loc[0] )    
예제 #45
0
파일: bombKey.py 프로젝트: atsbomb/bombKey
def copyAnim():
	sels = mc.ls(sl=1)
	if len(sels) >= 2:
		source = sels[0]
		target = sels[1]
		keyableAttrs = mc.listAttr(source, k=1)
		for keyableAttr in keyableAttrs:
			value = mc.getAttr(source+'.'+str(keyableAttr))
			# check if target has the attribute
			if mc.objExists(target + '.' + str(keyableAttr)):
				# making sure it's either not locked or not having an input
				if mc.getAttr(target+'.'+str(keyableAttr), l=1) != 1 and mc.connectionInfo(target+'.'+keyableAttr, id=1) != 1:
					mc.setAttr(target + '.' + str(keyableAttr), value)
		mc.copyKey(source)
		try: mc.pasteKey(target)
		except: pass
	else:
		print 'Please select 2 objects to copy from and paste to.'
예제 #46
0
def swapAnimation(fromNode, toNode):

    if not mc.keyframe(fromNode, query=True, name=True):
        mc.cutKey(toNode, clear=True)
        return

    attrs = mc.listAttr(fromNode, keyable=True)
    if not attrs:
        return

    for attr in attrs:
        if not mc.attributeQuery(attr, node=toNode, exists=True):
            mc.cutKey(fromNode, attribute=attr, clear=True)
            continue

        fromPlug = '{}.{}'.format(fromNode, attr)
        toPlug = '{}.{}'.format(toNode, attr)

        srcCurve = mc.listConnections(fromPlug, source=True, destination=False, type='animCurve')
        dstCurve = mc.listConnections(toPlug, source=True, destination=False, type='animCurve')

        copySrc=None
        copyDst=None

        if srcCurve:
            copySrc = mc.duplicate(srcCurve[0])[0]

        if dstCurve:
            copyDst = mc.duplicate(dstCurve[0])[0]

        if copySrc:
            try:
                mc.cutKey(copySrc)
                mc.pasteKey(toNode, attribute=attr, option='replaceCompletely')
            except:pass
        if copyDst:
            try:
                mc.cutKey(copyDst)
                mc.pasteKey(fromNode, attribute=attr, option='replaceCompletely')
            except:pass

    for axis in getMirrorAxis(toNode):
        mc.scaleKey(toNode, attribute=axis, valueScale=-1)
        mc.scaleKey(fromNode, attribute=axis, valueScale=-1)
예제 #47
0
def extractRange(node, begin, end, inclusive=True) :

    ''' extract a range of keyframes on to a new locator '''

    animCurves = m.keyframe(q=True, name=True)
    keys = m.keyframe(node, q=True, t=(begin, end))
    if keys is None or len(keys)==0 : return None

    loc = createBox(node + "_cut", current=node)
    m.cutKey(node, time=(begin, end))
    m.pasteKey(loc[0], option="replace")
    if m.objExists(loc[0] + ".active") :
        m.setKeyframe(loc[0] + ".active", t=begin, v=0)
        m.setKeyframe(loc[0] + ".active", t=end, v=0)

    setActiveKeys( loc[0] )
    setActiveKeys( node  )

    return loc
예제 #48
0
def parentBake(objs, parent=None, bakeOnOnes=False):

    #check objects can be parented
    parentReferenced = mc.referenceQuery(parent, isNodeReferenced=True) if parent else False

    culledObjs = []
    for each in objs:
        eachParent = mc.listRelatives(each, parent=True)
        if mc.referenceQuery(each, isNodeReferenced=True):
            if parentReferenced:
                OpenMaya.MGlobal.displayWarning("Child and parent are both referenced, skipping: {} > {}".format(each, parent))
                continue
            if eachParent and mc.referenceQuery(eachParent[0], isNodeReferenced=True):
                OpenMaya.MGlobal.displayWarning("Node is referenced and can't be reparented, skipping: {}".format(each))
                continue
        if not parent and not eachParent:
            OpenMaya.MGlobal.displayWarning("Node is already child of the world, skipping: {}".format(each))
            continue
        culledObjs.append(each)

    if not culledObjs:
        OpenMaya.MGlobal.displayWarning("No nodes could be reparented.")
        return

    source = []
    destination = []
    for each in culledObjs:
        source.append(mc.duplicate(each, parentOnly=True)[0])
        mc.copyKey(each)
        mc.pasteKey(source[-1], option='replaceCompletely')
        try:
            if parent:
                destination.append(mc.parent(each, parent)[0])
            else:
                destination.append(mc.parent(each, world=True)[0])
        except RuntimeError as err:
            mc.delete(source)
            raise err

    utl.matchBake(source=source, destination=destination, bakeOnOnes=bakeOnOnes)

    mc.delete(source)
예제 #49
0
파일: lib.py 프로젝트: adamcobabe/AnimIO
	def paste_animation( self, sTimeRange=tuple(), tTimeRange=tuple(), option="fitInsert", predicate=None, converter=None ):
		"""paste the stored animation to their respective target animation curves, if target does not exist it will be created
		:param sTimeRange: tuple of timerange passed to copyKey
		:param tTimeRange: tuple of timerange passed to pasteKey
		:param option: option on how to paste forwarded to pasteKey (useful: "fitInsert", "fitReplace", "scaleInsert", "scaleReplace")
		:param predicate and converter: passed to ``iter_assignments``, see documentation there
		:todo: handle if range is out of curve (error:nothing to paste from) - should paste the pose in this range"""
		iter_plugs=self.iter_assignments(predicate=predicate, converter=converter)
		
		# get animCurves form plugs and copy pate
		for s_plug, t_plug in iter_plugs:
			s_animcrv=s_plug.mwn()
			
			if apianim.MAnimUtil.isAnimated(t_plug):
				t_animcrv=t_plug.minput().mwn()
			else:
				t_animcrv=nt.Node(apianim.MFnAnimCurve().create(t_plug))
			# END get new or existing animCurve
				
			cmds.copyKey(s_animcrv, time=sTimeRange, option="curve"  )
			cmds.pasteKey(t_animcrv, time=tTimeRange, option=option)
예제 #50
0
def extractSelected() :
    '''
    select a few keys (bad?) and extract them on to a temp locator    
    '''

    sel = m.ls(sl=True)
    if sel is None or len(sel) == 0 :
        m.warning("Nothing selected to extract from")
        return

    if len(sel) > 1 : 
        m.error("Error: more than one object selected while extracting")
        return None

    selectTimes = selectedKeys()
    if selectTimes is None or len(selectTimes) == 0 :
        m.error("Select some keys to extract")
        return

    m.selectKey(clear=True);

    loc = createBox(current = sel[0])

    for i in selectTimes :
        m.cutKey(sel[0], time=(i,i))
        m.pasteKey(loc[0], time=(i, i))
        if m.objExists(sel[0] + ".active") :
            m.setAttr( sel[0] + ".active", 0)

    
    setActiveKeys( loc[0] )

    m.select(sel)

    for i in sel : setActiveKeys(i)
    setActiveKeys( loc[0] )
    setActiveKeys( sel[0] )

    return loc
예제 #51
0
def instanceFirst(doShaders=False):
    #1. make an array of all selected objects
    target = mc.ls(sl=1)

    #2. if only one selection, just make a new instance at the same coordinates...
    if(len(target)==1):
        mc.instance()

    else:
        #3. ...otherwise, for each selected object...
        for i in range(1,len(target)):

            #4. ...get current selection's position and copy keyframes and shader
            mc.select(target[i])
            pos = mc.xform(target[i], q=True, t=True, ws=True)
            try:
                shader = getShader()
            except:
                print "Couldn't get shader."
            try:
                mc.copyKey()
            except:
                print "Couldn't copy keys."

            #5. instance the first selection
            mc.select(target[0])
            mc.instance()
        
            #6. move first selection to position and paste keyframes and shader
            mc.move(pos[0],pos[1],pos[2])
            if(doShaders==True):
                setShader(shader)
            try:
                mc.pasteKey()
            except:
                print "Couldn't paste keys."
           
            #7. delete selection
            mc.delete(target[i])
예제 #52
0
def moveFirstToSecond():
    '''  move the keys on selected[0] to selected[1] '''
    sel = m.ls(sl=True)
    if(len(sel) < 2) :
        print "Select at least two items to use"
        return;

    keys = []
    for i in sel :
        kz = m.keyframe(i + ".tx", q=True)
        if kz is not None : keys.append( set( kz ) )

    count = 0
    for i in keys : count = count+ len(i)

    if count != len( set.union( *keys ) ) :
        ret = m.confirmDialog(m='You may have overlapping keys... continue?', b=['yes', 'no', 'skip'])

        if ret not in ['yes', 'skip'] : return

        if ret == 'skip' :
            # do not copy any keys if there is one already on the target
            for i in range(len(sel)-1) :
                for k in keys[i] :
                    if k in keys[-1] : continue
                    m.cutKey(sel[i], time=(k,k))
                    m.pasteKey(sel[-1], option='merge')
            return


    for i in sel[:-1] :
        if m.cutKey(i) > 0 : m.pasteKey(sel[-1], option="merge")
        m.delete(i)

    m.select(sel[-1])

    setActiveKeys( sel[-1] )
예제 #53
0
def copyFillGap( source, target ) :

    rate = datarate.guess(target)
    ret = curve.currentSegmentOrGap( target + '.tx', rate )
    if ret is None :
        print "Could not find gap on " + str( target ) 
        return

    mode, gap = ret
    
    if mode == 'segment' :
        print "No gap to fill for " + target
        return

    a,b = gap
    
    keys = m.keyframe( source + ".tx", q=True, tc=True) 
    if keys is None or len(keys) == 0 : 
        print "No keys to copy from on " + str(source)
        return

    keys = sorted( keys )

    if a is None : a = min(keys)
    if b is None : b = max(keys)

    keyRange = m.keyframe( source + ".tx", t=(a,b), q=True )
    if keyRange is None or len(keyRange) == 0 :
        print "No keys in range to copy from %s   %g-%g" % ( source, a, b )
        return

    for ch in ['tx', 'ty', 'tz' ] :
        m.cutKey( source + '.' + ch, t=(a,b) )
        m.pasteKey( target + '.' + ch,  option='merge' )

    setActiveKeys( source )
    setActiveKeys( target )
예제 #54
0
파일: gui.py 프로젝트: leandropim/Tapp
    def on_slider_released(self):

        #checking selection
        if cmds.ls(selection=True):

            start = self._findStart(self.currentKey)
            #self._printDownstream(start)

            #undo enable
            cmds.undoInfo(openChunk=True)

            obj = cmds.ls(selection=True)[0]
            for t in range(int(self.startFrame), int(self.endFrame) + 1):

                cmds.currentTime(t)
                cmds.setKeyframe(obj)

            #transfer original animation to temp transform
            loc = cmds.spaceLocator()[0]
            cmds.cutKey(obj, time=(self.startFrame, self.endFrame))
            cmds.pasteKey(loc)

            #paste timing
            self.currentTime = self.startFrame
            self._pasteTiming(loc, obj, start)

            #cleanup
            cmds.delete(loc)
            cmds.keyTangent(obj, itt='auto', ott='auto')
            cmds.delete(staticChannels=True)

            cmds.undoInfo(closeChunk=True)

        else:

            cmds.warning('No nodes selected!')
예제 #55
0
 def _transfer_keys(self, from_controls, to_controls):
     """
     Responsible for the transfer of keys, given a provided frame range.
     @param:
         from_controls: Controls with keys you want to transfer.
         to_controls: Controls you want to transfer keys too.
     """
     start = self.start_frame
     end = self.end_frame
     for count, control in enumerate(from_controls):
         copy = cmds.copyKey(control, time=(start, end), at=TR_ATTRS)
         try:
             paste = cmds.pasteKey(to_controls[count], at=TR_ATTRS)
         except RuntimeError:
             continue
예제 #56
0
def swap( markers = None, inPoint = None, outPoint =None ) : 

    ''' swap data on two markers, between the in and out
        @param markers: list of 2 markers to swap, defaults to selection
        @param inPoint: frame to start swap, defaults to current frame
        @param outPoint: frame to end swap, defaults to last frame '''

    if markers is None :
        markers = m.ls(sl=True)
        if len(markers) != 2 : 
            print "select two markers to swap"
            return
     
    # these do not need to be sorted
    keysA = m.keyframe(markers[0], q=True)
    keysB = m.keyframe(markers[1], q=True)   

    if inPoint  is None : inPoint = m.currentTime(q=True)
    if outPoint is None : outPoint = max(keysA)
    
    
    # cut the keys from markers 0
    if inPoint == 'all' :
        count = m.cutKey(markers[0])
    else :
        count = m.cutKey(markers[0], time=(inPoint, outPoint))

    loc = None

    if count > 0 :
        # paste the key to a temp object
        loc = createBox(boxName = "temp") # temp, current not needed
        m.pasteKey(loc[0], option="replace")

    # cut the keys from markers 1 and paste on to markers 0
    if inPoint == 'all' :
        count = m.cutKey(markers[1])
    else :
        count = m.cutKey(markers[1], time=(inPoint, outPoint))

    if count > 0 : m.pasteKey(markers[0], option="replace")

    if loc != None :
        # cut the keys from the temp object (markers 0 data) and paste on to markers 1
        m.cutKey(loc[0])
        m.pasteKey(markers[1], option="replace")

        # delete the temp object
        m.delete(loc)
예제 #57
0
def moveToCurrent(id=""):

    ''' move all the keys on selected[0] to current item '''

    sel = m.ls(sl=True)
    if(len(sel) != 1) :
        print "Select one item to use"
        return;
    currentItem = m.optionVar(q="mocap_currentItem" + id)

    if currentItem is None or currentItem == 0 :
        print "No current item #" + id
        return

    # move sel[0] to temp
    print("Copying keys from: %s" % sel[0])
    animCurves = m.keyframe(q=True, name=True)
    selectTimes = m.keyframe(animCurves[0], q=True, sl=True, timeChange=True)  
    if selectTimes is None or len(selectTimes) == 0 :
        print "No keys selected, moving all keys"
        m.select(currentItem, add=True)
        moveFirstToSecond()
        m.select(currentItem)
        return

    box = createBox() # temp item, current not needed
    print("Pasting %d keys on to: %s" % (len(selectTimes), box))
    for i in selectTimes :
        m.cutKey(sel[0], time=(i,i))
        m.pasteKey(box[0], time=(i, i))

    # move currentItem to sel[0]
    print("Moving keys from: %s" % (currentItem))
    for i in selectTimes :
        n = m.cutKey(currentItem, time=(i,i))
        if n > 0 : m.pasteKey(sel[0], time=(i, i))

    # move temp to currentItem 
    print("Moving from temp to currentItem")
    for i in selectTimes :
        n = m.cutKey(box, time=(i,i))
        if n > 0 : m.pasteKey(currentItem, time=(i, i))

    m.delete(box)

    setActiveKeys( currentItem )

    m.select(currentItem)
예제 #58
0
def limbsIkToFkOLD(rigNS,start=None,end=None,sampleBy=1):
	'''
	Bake IK limb animation to FK controls
	@param rigNS: IK/FK toggle attribute
	@type rigNS: str
	@param start: Transfer animation start frame
	@type start: int or None
	@param end: Transfer animation end frame
	@type end: int or None
	@param sampleBy: Bake animation by N frames
	@type sampleBy: int
	'''
	# ==========
	# - Checks -
	# ==========
	
	# Get Start/End
	if start == None: start = mc.playbackOptions(q=True,min=True)
	if end == None: end = mc.playbackOptions(q=True,max=True)
	
	# ==========================
	# - Build IK/FK Joint List -
	# ==========================
	
	ikJntList = []
	fkJntList = []
	
	index = ['A','B']
	sides = ['lf','rt']
	for side in sides:
		if not mc.getAttr(rigNS+':config.'+side+'ArmIkFkBlend'):
			#ikJntList += [rigNS+':'+side+'_arm_ik'+i+'_jnt' for i in index]
			#fkJntList += [rigNS+':'+side+'_arm_fk'+i+'_jnt' for i in index]
			
			armIkToFk(rigNS,side,True,start,end,sampleBy)
			
		if not mc.getAttr(rigNS+':config.'+side+'LegIkFkBlend'):
			#ikJntList += [rigNS+':'+side+'_leg_ik'+i+'_jnt' for i in index]
			#fkJntList += [rigNS+':'+side+'_leg_fk'+i+'_jnt' for i in index]
			#ikJntList += [rigNS+':'+side+'_foot_ik'+i+'_jnt' for i in index]
			#fkJntList += [rigNS+':'+side+'_foot_fk'+i+'_jnt' for i in index]
			
			legIkToFk(rigNS,side,start,end,sampleBy)
	
	# Check IK/FK State
	if not fkJntList:
		print('Limbs already in FK mode! Nothing to do...')
		return fkJntList
	
	# ====================================
	# - Bake Wrist Animation to Locators -
	# ====================================
	
	# Build Wrist Duplicates for Baking
	wristJnts = [rigNS+':'+side+'_handA_jnt' for side in sides]
	wristDups = [mc.duplicate(jnt,po=True)[0] for jnt in wristJnts]
	keys = mc.copyKey(wristJnts,at=['rx','ry','rz'],t=(start,end))
	if keys: mc.pasteKey(wristDups,at=['rx','ry','rz'],t=(start,end),option='replace')
	
	# Bake Wrists to Locators
	wristLocs = glTools.anim.utils.bakeAnimToLocators(	objList		= wristJnts,
														start		= start,
														end			= end,
														sampleBy	= sampleBy,
														simulation	= True,
														attrList	= ['rx','ry','rz'] )
	
	# =======================
	# - Bake Limb Animation -
	# =======================
	
	# Duplicate FK Joints and Constrain to IK
	fkDupList = []
	fkOriList = []
	for i in range(len(ikJntList)):
		fkDupList.append(mc.duplicate(fkJntList[i],po=True)[0])
		fkOriList.append(mc.orientConstraint(ikJntList[i],fkDupList[-1])[0])
	
	# Transfer Baked Anim to FK Joints
	mc.refresh(suspend=True)
	for i in range(len(fkDupList)):
		mc.bakeResults(	fkDupList[i],
						t=(start,end),
						at=['rx','ry','rz'],
						simulation=True,
						preserveOutsideKeys=True,
						sampleBy=sampleBy )
	
	# Transfer Keys
	for i in range(len(fkDupList)):
		keys = mc.copyKey(fkDupList[i],at=['rx','ry','rz'],t=(start,end))
		if keys: mc.pasteKey(fkJntList[i],at=['rx','ry','rz'],t=(start,end),option='replace')
	
	mc.refresh(suspend=False)
	
	# Delete Duplicate Joints and Constraints
	if fkOriList:
		try: mc.delete(fkOriList)
		except Exception, e: print('Error deleting nodes '+str(fkOriList)+'! Exception Msg: '+str(e))
	if fkDupList:
		try: mc.delete(fkDupList)
		except Exception, e: print('Error deleting nodes '+str(fkDupList)+'! Exception Msg: '+str(e))
	
	# ======================================
	# - Bake Wrist Animation from Locators -
	# ======================================
	
	# Set to FK Mode
	for side in sides:
		mc.setAttr(rigNS+':config.'+side+'ArmIkFkBlend',1)
		mc.setAttr(rigNS+':config.'+side+'LegIkFkBlend',1)
	
	# Bake Wrists from Locators
	glTools.anim.utils.bakeAnimFromLocators(	locList		= wristLocs,
											start		= start,
											end			= end,
											sampleBy	= sampleBy,
											simulation	= True,
											attrList	= ['rx','ry','rz'] )
	
	# Transfer Baked Keys
	keys = mc.copyKey(wristDups,at=['rx','ry','rz'],t=(start,end))
	if keys: mc.pasteKey(wristJnts,at=['rx','ry','rz'],t=(start,end),option='replace')
	
	# Cleanup
	if wristLocs:
		try: mc.delete(wristLocs)
		except: pass
	if wristDups:
		try: mc.delete(wristDups)
		except: pass
	
	# =================
	# - Return Result -
	# =================
	
	return fkJntList