def convertConnectionAsAnimCurve( node, attr ):
    
    separateParentConnection( node, attr )
          
    cons = cmds.listConnections( node+'.'+attr, s=1, d=0, p=1, c=1 )
    if not cons: return None
    
    attrType = cmds.attributeQuery( attr, node= node, attributeType=1 )
    
    if attrType == 'doubleLinear':
        animCurveType= 'animCurveUL'
    elif attrType == 'doubleAngle':
        animCurveType = 'animCurveUA'
    else:
        animCurveType = 'animCurveUU'
    
    animCurve = cmds.createNode( animCurveType )
    cmds.connectAttr( cons[1], animCurve+'.input' )
    cmds.connectAttr( animCurve+'.output', cons[0], f=1 )
    
    cmds.setKeyframe( animCurve, f= -1, v= -1 )
    cmds.setKeyframe( animCurve, f=-.5, v=-.5 )
    cmds.setKeyframe( animCurve, f=  0, v=  0 )
    cmds.setKeyframe( animCurve, f= .5, v= .5 )
    cmds.setKeyframe( animCurve, f=  1, v=  1 )
    
    cmds.setAttr( animCurve + ".postInfinity", 1 )
    cmds.setAttr( animCurve + ".preInfinity", 1 )
    
    cmds.selectKey( animCurve )
    cmds.keyTangent( itt='spline', ott='spline' )
    
    return animCurve
Example #2
2
def setSmartKey(time=None, animCurves=None, select=True, insert=True, replace=True, addTo=False):
    
    if not time: time   = animMod.getTimelineTime()    
    getFrom             = "timeline"
    
    if not animCurves:
        getCurves  = animMod.getAnimCurves()
        animCurves = getCurves[0]
        getFrom    = getCurves[1]
    
    
    if animCurves and getFrom != "timeline": 
        cmds.setKeyframe(animCurves, time=time, insert=insert)
        if select: cmds.selectKey(animCurves, replace=replace, addTo=addTo, time=time)
        
    else:
        objects = animMod.getObjsSel()
        if objects:
            
            channelboxSelObjs = animMod.channelBoxSel()
            if channelboxSelObjs:
                #objsAttrs     = ["%s.%s"%(loopObj, loopChannelboxSel) for loopObj in objects for loopChannelboxSel in channelboxSel]
                         
                #key selected attributes in the channelbox
                for n, loopObjAttr in enumerate(channelboxSelObjs):
                    prevKey       = cmds.findKeyframe(loopObjAttr, time=(time,time), which="previous")
                    tangentType   = cmds.keyTangent(loopObjAttr, query=True, outTangentType=True, time=(prevKey,prevKey)) 
               
                    if not tangentType: #if there is no key 
                        tangentType = cmds.keyTangent(query=True, g=True, outTangentType=True)
                        inTangentType  = tangentType[0].replace("fixed", "auto").replace("step", "auto")
                        outTangentType = tangentType[0].replace("fixed", "auto")
                        cmds.setKeyframe(loopObjAttr, time=time, insert=False, shape=False, inTangentType=inTangentType, outTangentType=outTangentType)
                        continue
                    
                    inTangentType  = tangentType[0].replace("fixed", "auto").replace("step", "auto")
                    outTangentType = tangentType[0].replace("fixed", "auto")
                
                    cmds.setKeyframe(loopObjAttr, time=time, insert=insert, shape=False, inTangentType=inTangentType, outTangentType=outTangentType)
                    
            else:
                #allChannels   = animMod.getAllChannels(objects)
                #objAttrs      = ["%s.%s"%(objects[n], loopAttr) for n, loopObj in enumerate(allChannels) for loopAttr in loopObj]
                prevKeys      = [cmds.findKeyframe(obj, time=(time,time), which="previous") for obj in objects]
                tangentTypes  = [cmds.keyTangent(obj, query=True, outTangentType=True, time=(prevKeys[n],prevKeys[n])) for n, obj in enumerate(objects)]
                #prevKeys      = [cmds.findKeyframe(obj, time=(time,time), which="previous") for obj in objAttrs]
                #tangentTypes  = [cmds.keyTangent(obj, query=True, outTangentType=True, time=(prevKeys[n],prevKeys[n])) for n, obj in enumerate(objAttrs)]
                #key all atributes
                cmds.setKeyframe(objects, time=time, insert=insert, shape=False) 
                #cmds.setKeyframe(objAttrs, time=time, insert=insert, shape=False)    
                            
                if insert: #will force create key if there is no key
                    for n, loopTangent in enumerate(tangentTypes):
                        if not loopTangent:
                            cmds.setKeyframe(objects[n], time=time, insert=False, shape=False)
Example #3
1
    def flowAround(self, frames=2, excludeCurrKey=False):

        getCurves = animMod.getAnimCurves()
        animCurves = getCurves[0]
        getFrom = getCurves[1]

        if animCurves:
            # if getFrom == "graphEditor":
            keysSel = animMod.getTarget("keysSel", animCurves, getFrom)
            tangentType = "flow"
            time = None

            # animMod.expandKeySelection(frames)

            index = animMod.getTarget("keysIndexSel", animCurves, getFrom)
            indexTimes = animMod.getTarget("keyIndexTimes", animCurves, getFrom)

            # expand selection
            for n, loopCurve in enumerate(index):
                for x in xrange(frames):
                    if loopCurve[0] >= 1:
                        loopCurve.insert(0, loopCurve[0] - 1)
                    if loopCurve[-1] < indexTimes[n][-1]:
                        loopCurve.append(loopCurve[-1] + 1)

                # if excludeCurrKey:

            self.applyTangent(animCurves, tangentType, getFrom, time, index)

            # select back keys
            if keysSel:
                cmds.selectKey(clear=True)
                for n, aCurve in enumerate(animCurves):
                    for key in keysSel[n]:
                        cmds.selectKey(aCurve, addTo=True, time=(key, key))
def keyFullRotation (pObjectName, pStartTime, pEndTime, pTargetAttribute):
    
     cmds.cutKey (pObjectName, time = (pStartTime, pEndTime), attribute=pTargetAttribute)
     cmds.setKeyframe (pObjectName, time = pStartTime, attribute=pTargetAttribute, value=0)
     cmds.setKeyframe (pObjectName, time = pEndTime, attribute=pTargetAttribute, value=360)
     cmds.selectKey (pObjectName, time = (pStartTime, pEndTime), attribute=pTargetAttribute, keyframe=True)
     cmds.keyTangent (inTangentType='linear', outTangentType='linear')
Example #5
1
def getRoofSineCurve( startInput, endInput, minValue, maxValue ):
    
    animCurve = cmds.createNode( 'animCurveUU' )
    cmds.setKeyframe( f= startInput, v=minValue )
    cmds.setKeyframe( f= (startInput+endInput)/2.0, v=maxValue )
    cmds.setKeyframe( f= endInput,   v=minValue )
    cmds.selectKey( animCurve )
    cmds.setInfinity( poi='cycle', pri='cycle' )
    
    return animCurve
Example #6
1
def goToKeyframe(option='next', roundFrame=False, selected=False, selectKeys=False, searchHierarchy=False):
    '''

    '''

    if option != 'next' and option != 'previous':
        OpenMaya.MGlobal.displayWarning('Option argument should be "next" or "previous"')
        return

    if selected and selectKeys:
        OpenMaya.MGlobal.displayWarning('Cannot use selectKeys flag in conjunction with selected flag.')
        selectKeys = False

    sel = mc.ls(sl=True)
    currentTime = mc.currentTime(query=True)
    time = currentTime

    if not sel:
        if option == 'next':
            time+=1
        elif option == 'previous':
            time-=1
        else:
            return
        #if nothing is selected, just go to the next or previous keyframe
        with utl.SkipUndo():
            mc.currentTime(time)
        return

    keySel = utl.KeySelection()

    if searchHierarchy:
        #if we're looking through the hierarchy,
        keySel.keyedInHierarchy()

    else:
        #create the keySelection object.
        #all the heavy lifting is done in ml_utilities.
        if selected and keySel.selectedKeys():
            pass
        if keySel.visibleInGraphEditor():
            pass
        if keySel.selectedObjects():
            pass

    time = keySel.findKeyframe(which=option, roundFrame=roundFrame, loop=True)

    if selectKeys:
        mc.selectKey(keySel.curves, time=(time,))


    #finally, set the time without adding to the undo queue
    with utl.SkipUndo():
        mc.currentTime(time, edit=True)
def keyFullRotation(pObjectName, pStartTime, pEndTime, pTargetAttribute):
    #The keys are deleted
    cmds.cutKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTargetAttribute)

    #Define new keys for the animations (rotation in the axis Y). 
    cmds.setKeyframe(pObjectName, time= pStartTime, attribute=pTargetAttribute, value = 0)
    
    cmds.setKeyframe(pObjectName,time=pEndTime, attribute=pTargetAttribute, value = 360)

    #In order to mantain a constant rate of rotation with linear tangents
    cmds.selectKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTargetAttribute)
    cmds.keyTangent( inTangentType='linear', outTangentType='linear')
def smoothAnimCurves(objects, isLoop):
	"""Set all keys on provided objects to auto tangent, optionally matching in and out tangents."""
	if isinstance(objects, types.StringTypes):
		objects = [objects]
	if not isinstance(objects, types.ListType) and not isinstance(objects, types.TupleType):
		sys.stderr.write("ERROR: Unable to smooth animation curves on object %s. Argument must be a string, list, or tuple of objects or attribute names.\n")
		return False
	for object in objects:
		cmds.selectKey(object)
		cmds.keyTangent(itt="spline", ott="spline")
		if isLoop: matchInOutTangents(object)
	return True
Example #9
1
def keyFullRotation(pObjectName, pStartTime, pEndTime, pTangentAttribute):
            
    # Enable key on selected objects
    cmds.cutKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTangentAttribute)
            
    # Set keyframes
    cmds.setKeyframe(pObjectName, time=pStartTime, attribute=pTangentAttribute, value=0)
    cmds.setKeyframe(pObjectName, time=pEndTime, attribute=pTangentAttribute, value=360)
    
    # Set linear tangent
    cmds.selectKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTangentAttribute)
    cmds.keyTangent(inTangentType='linear', outTangentType='linear')
def make_dof(simplified, name, d):
    node = "%s.%s" % (name, d)
    cmds.selectKey(node, replace=True, k=True)
    cmds.selectKey(node, replace=True, k=True)
    if cmds.selectKey(node, replace=True, k=True) == 0:
        return

    keyframes = simplified[name][d]["keyframes"]
    beziers   = simplified[name][d]["bez"]
    values = get_keyframe_values(name, d, keyframes)
    delete_anim(node)
    create_keyframes(name, d, keyframes, values)
    set_bezier_handles(name, d, beziers, keyframes)
def setKey(insert=True, useSelectedCurves=True):
    """Sets clever keys.  Hohoho.

    If the mouse is over the graph editor, it keys the attributes selected
    there.  Otherwise it keys the attributes selected in the channel box. If
    the channelBox is closed it will key all the attributes on the selected
    node.  It attempts to use the "Insert Key" function which makes keys match
    the curvature of the surrounding keys whenever possible.  Set insert
    parameter to false to disable this behavior."""

    # Get Attributes
    attributes = selectedAttributes.get(detectionType="cursor", useSelectedCurves=useSelectedCurves)
    currentFrame = cmd.currentTime(q=1)

    # Make extra sure attributes are unique (they should already be)
    attributes = list(set(attributes))

    if cmd.optionVar(ex="animBlendingOpt") and cmd.optionVar(q="animBlendingOpt") == 0:
        # PairBlend creation is disabled.  All incomming connections on
        # attributes will spit out warnings if we try to key them.
        removeConnectedAttributes(attributes)

    attrCount = 0
    for attr in attributes:
        # Test if we can use insert
        # canInsert returns 2 if something errored out in it.
        insertAttr = insert
        canInsert = canInsertKey(attr)
        if canInsert != 2:
            if not (insert and canInsert):
                insertAttr = False

            # Key it
            try:
                performSelect = selectNewKeyframe(attr)
                cmd.setKeyframe(attr, i=insertAttr)
                attrCount += 1

                # Select it if in between selected keys, or if adding
                # new keys and the last one was selected.
                if performSelect:
                    cmd.selectKey(attr, add=1, k=1, t=(currentFrame, currentFrame))

            except RuntimeError as err:
                print err
                om.MGlobal.displayError("Could not not set a key on %s." % attr)
    if attrCount:
        om.MGlobal.displayInfo("Set %d keys." % attrCount)
    else:
        om.MGlobal.displayInfo("No keys were set.")
Example #12
1
	def animateLeftWrist(self):
		
		self.currentSelection()
		
		bodyControl = self.selection[0]
		
		#Keyraming X translation
		cmds.cutKey(bodyControl ,  attribute= 'translateX')		
		cmds.setKeyframe(bodyControl , time = self.startTime , attribute = 'translateX' , value = -2)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*0.52) , attribute = 'translateX' , value = -2)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*1) , attribute = 'translateX' , value = -2)		
		cmds.selectKey(bodyControl , time = (self.startTime , self.endTime) , attribute = 'translateY')
		cmds.keyTangent( inTangentType = "linear" , outTangentType = "linear")   
    
    	#Keyraming Y translation
		cmds.cutKey(bodyControl ,  attribute= 'translateY')		
		cmds.setKeyframe(bodyControl , time = self.startTime , attribute = 'translateY' , value = -3.695)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*0.52) , attribute = 'translateY' , value = -3.695)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*1) , attribute = 'translateY' , value = -3.695)		
		cmds.selectKey(bodyControl , time = (self.startTime , self.endTime) , attribute = 'translateY')
		cmds.keyTangent( inTangentType = "linear" , outTangentType = "linear")   
    
    	#Keyraming Z translation
		cmds.cutKey(bodyControl ,  attribute= 'translateZ')		
		cmds.setKeyframe(bodyControl , time = self.startTime , attribute = 'translateZ' , value = -0.651)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*0.52) , attribute = 'translateZ' , value = 1.259)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*1) , attribute = 'translateZ' , value = -0.651)		
		cmds.selectKey(bodyControl , time = (self.startTime , self.endTime) , attribute = 'translateZ')
		cmds.keyTangent( inTangentType = "linear" , outTangentType = "linear")   
		
		#Deleting any keyframes of rotateX
		cmds.cutKey(bodyControl ,  attribute= 'rotateX')	
		
		#Keyraming Y rotation
		cmds.cutKey(bodyControl ,  attribute= 'rotateY')		
		cmds.setKeyframe(bodyControl , time = self.startTime , attribute = 'rotateY' , value = 16.745)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*0.52) , attribute = 'rotateY' , value = -40.855)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*1) , attribute = 'rotateY' , value = 16.745)		
		cmds.selectKey(bodyControl , time = (self.startTime , self.endTime) , attribute = 'rotateY')
		cmds.keyTangent( inTangentType = "linear" , outTangentType = "linear")   
     
     #Keyraming Z rotation
		cmds.cutKey(bodyControl ,  attribute= 'rotateZ')		
		cmds.setKeyframe(bodyControl , time = self.startTime , attribute = 'rotateZ' , value = -75.98)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*0.52) , attribute = 'rotateZ' , value = 0)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*1) , attribute = 'rotateZ' , value = -75.98)		
		cmds.selectKey(bodyControl , time = (self.startTime , self.endTime) , attribute = 'rotateZ')
		cmds.keyTangent( inTangentType = "linear" , outTangentType = "linear")   
Example #13
1
	def animateRightWrist(self):
		
		self.currentSelection()
		
		bodyControl = self.selection[0]
		
		#Keyraming X translation
		cmds.cutKey(bodyControl ,  attribute= 'translateX')		
		cmds.setKeyframe(bodyControl , time = self.startTime , attribute = 'translateX' , value = -2)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*0.52) , attribute = 'translateX' , value = -2)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*1) , attribute = 'translateX' , value = -2)		
		cmds.selectKey(bodyControl , time = (self.startTime , self.endTime) , attribute = 'translateY')
		cmds.keyTangent( inTangentType = "linear" , outTangentType = "linear")   
    
    	#Keyraming Y translation
		cmds.cutKey(bodyControl ,  attribute= 'translateY')		
		cmds.setKeyframe(bodyControl , time = self.startTime , attribute = 'translateY' , value = -3.692)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*0.52) , attribute = 'translateY' , value = -3.692)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*1) , attribute = 'translateY' , value = -3.692)		
		cmds.selectKey(bodyControl , time = (self.startTime , self.endTime) , attribute = 'translateY')
		cmds.keyTangent( inTangentType = "linear" , outTangentType = "linear")   
    
    	#Keyraming Z translation
		cmds.cutKey(bodyControl ,  attribute= 'translateZ')		
		cmds.setKeyframe(bodyControl , time = self.startTime , attribute = 'translateZ' , value = -1.328)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*0.52) , attribute = 'translateZ' , value = 0.766)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*1) , attribute = 'translateZ' , value = -1.328)		
		cmds.selectKey(bodyControl , time = (self.startTime , self.endTime) , attribute = 'translateZ')
		cmds.keyTangent( inTangentType = "linear" , outTangentType = "linear")   
		
		#Deleting any keyframes of rotateX
		cmds.cutKey(bodyControl ,  attribute= 'rotateX')	
		
		#Keyraming Y rotation
		cmds.cutKey(bodyControl ,  attribute= 'rotateY')		
		cmds.setKeyframe(bodyControl , time = self.startTime , attribute = 'rotateY' , value = 39.6)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*0.52) , attribute = 'rotateY' , value = 0)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*1) , attribute = 'rotateY' , value = 39.6)		
		cmds.selectKey(bodyControl , time = (self.startTime , self.endTime) , attribute = 'rotateY')
		cmds.keyTangent( inTangentType = "linear" , outTangentType = "linear")   
     
     	#Keyraming Z rotation
		cmds.cutKey(bodyControl ,  attribute= 'rotateZ')		
		cmds.setKeyframe(bodyControl , time = self.startTime , attribute = 'rotateZ' , value = -105.923)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*0.52) , attribute = 'rotateZ' , value = 0)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*1) , attribute = 'rotateZ' , value = -105.923)		
		cmds.selectKey(bodyControl , time = (self.startTime , self.endTime) , attribute = 'rotateZ')
		cmds.keyTangent( inTangentType = "linear" , outTangentType = "linear")   
def make_move(simplified):
    for [maya_dof, data_dof] in [["tx", "rx"], ["ty", "ry"], ["tz", "rz"]]:

        node = "root.%s" % maya_dof
        cmds.selectKey(node, replace=True, k=True)
        cmds.selectKey(node, replace=True, k=True)
        if cmds.selectKey(node, replace=True, k=True) == 0:
            return

        keyframes = simplified["move"][data_dof]["keyframes"]
        beziers   = simplified["move"][data_dof]["bez"]

        values = get_keyframe_values("root", maya_dof, keyframes)
        delete_anim(node)
        create_keyframes("root", maya_dof, keyframes, values)
        set_bezier_handles("root", maya_dof, beziers, keyframes)
Example #15
1
 def create_fk_setup(self):
     """Creates the FK setup."""
     cmds.orientConstraint(self.controls['fan'], self.result_jnts[0], mo=True)
     mdl = cmds.shadingNode('multDoubleLinear', asUtility=True)
     mdl = cmds.rename(mdl, '%s_%s_MDL' % (self.side, self.modulename))
     if self.side == 'R':
         cmds.expression(s='%s.input1 = time * (-1);' % mdl, o=mdl, ae=1, uc='all')
     else:
         cmds.expression(s='%s.input1 = time;' % mdl, o=mdl, ae=1, uc='all')
     # END if
     cmds.connectAttr('%s.speed' % self.controls['fan'], '%s.input2' % mdl, f=True)
     cmds.setDrivenKeyframe('%s.rotate%s' % (self.controls['offset'], self._up_axis), cd='%s.output' % mdl, dv=0, v=0)
     cmds.setDrivenKeyframe('%s.rotate%s' % (self.controls['offset'], self._up_axis), cd='%s.output' % mdl, dv=1, v=1)
     cmds.keyTangent('%s_rotate%s' % (self.controls['offset'], self._up_axis), itt='linear', ott='linear', f=(0, 1))
     cmds.selectKey('%s_rotate%s' % (self.controls['offset'], self._up_axis), add=True, k=True, f=(0, 1))
     cmds.setInfinity(pri='cycleRelative', poi='cycleRelative')
Example #16
1
   	def animateHeightControl(self):
		
		self.currentSelection()
		
		bodyControl = self.selection[0]
	 	
	 	#Keyraming Y translation
		cmds.cutKey(bodyControl , attribute= 'translateY')		
		cmds.setKeyframe(bodyControl , time = self.startTime , attribute = 'translateY' , value = self.height)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*0.16) , attribute = 'translateY' , value = self.height*2)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*0.4) , attribute = 'translateY' , value = -1*self.height/2)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*0.52) , attribute = 'translateY' , value = self.height)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*0.64) , attribute = 'translateY' , value = self.height*2)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*0.76) , attribute = 'translateY' , value = self.height/2)
		cmds.setKeyframe(bodyControl, time = int((self.endTime-self.startTime+1)*1) , attribute = 'translateY' , value = self.height)		
		cmds.selectKey(bodyControl , time = (self.startTime , self.endTime) , attribute = 'translateY')
		cmds.keyTangent( inTangentType = "linear" , outTangentType = "linear")   
Example #17
1
    def query(self) : 

        sel = m.ls(sl=True)
        if sel is None or len(sel) == 0 : m.error("Nothing selected")

        rangemode   = self.sourceRangeSelector.currentText()  # none, fill, segment, spike, all, selected
        if rangemode == 'gap':
            if len(sel) < 2:
                print "Need to markers to find the gap"
                return
            s = curve.currentSegmentOrGap( sel[1], datarate.nodeRate(sel[1]) )
            if s is None or s[0] != 'gap' :
                print "Skipping: " + str(sel[1]) + " (not currently in a gap)"
                return

            sourceIn, sourceOut = s[1]
        else:
            sourceIn, sourceOut = assign.getSourceRange( sel[0], rangemode )
        m.selectKey( sel[0], t=(sourceIn, sourceOut) )
Example #18
1
File: RPM.py Project: boochos/work
def addSection(rpm=100, startFrame=1000, totalFrames=110):
    '''
    used to setup rpm wedge
    '''
    # BUG: keys dont maintain tangent type when setting keyframe
    #
    sel = cmds.ls(sl=1)[0]
    attr = 'rotateY'
    crv = cmds.findKeyframe(sel + '.' + attr, c=True)
    #
    r = valueChangePerFrame(rpm)
    print '________________'
    print '_____ for', rpm, 'rpm'
    print r, ' x value'
    x = r * totalFrames
    print x, ' on totalFrames'
    cmds.setKeyframe(crv, time=(startFrame, startFrame), value=0, shape=False)
    cmds.setKeyframe(crv, time=(startFrame + totalFrames, startFrame + totalFrames), value=x, shape=False)
    cmds.selectKey(crv)
    cmds.keyframe(animation='keys', relative=1, timeChange=(0 - (totalFrames + 1)))
Example #19
1
def expandKeySelection(frames=1):
    getCurves = getAnimCurves()
    animCurves = getCurves[0]
    getFrom = getCurves[1]

    if animCurves:

        keysSel = getTarget("keysSel", animCurves, getFrom)
        keyTimes = getTarget("keyTimes", animCurves)

        # add tail and head keys
        for n, loopCurve in enumerate(animCurves):
            for key in keysSel[n]:
                index = keyTimes[n].index(key)
                startIndex = index - frames
                endIndex = index + frames
                if startIndex < 0:
                    startIndex = 0

                cmds.selectKey(loopCurve, addTo=True, index=(startIndex, endIndex))
Example #20
0
    def delete_redundant_keys(self):

        controls = animMod.get_target("controls", selected=True)
        print controls

        for control in controls:
            print control
            attributes = animMod.get_target("attributes", attribute_options = ["keyable"], node=control)
            for attribute in attributes:
                anim_layers = animMod.get_target("anim_layers", selected=False)

                for anim_layer in anim_layers:
                    anim_curves = animMod.get_target("anim_curves", anim_layer=anim_layer, attribute=attribute, node=control)
                    for anim_curve in anim_curves:
                        print anim_curve
                        redundant_keys = []
                        keyframes = cmds.keyframe(anim_curve, query=True, timeChange=True)
                        for previous_frame, current_frame, next_frame in animMod.get_prev_current_next(keyframes):
                            if previous_frame is None:
                                previous_frame = current_frame
                            if next_frame is None:
                                next_frame = current_frame
                            break
                            previous_value = cmds.keyframe(anim_curve, query=True, time=(previous_frame, previous_frame), valueChange=True)
                            current_value = cmds.keyframe(anim_curve, query=True, time=(current_frame, current_frame), valueChange=True)
                            next_value = cmds.keyframe(anim_curve, query=True, time=(next_frame, next_frame), valueChange=True)

                            if previous_value == current_value == next_value:
                                redundant_keys.append(current_frame)

                        for frame in redundant_keys:
                            cmds.selectKey(anim_curve, time=(frame,frame), keyframe=True, remove=True)
                        cmds.cutKey(animation="keys", clear=True)
Example #21
0
def create_moon():
    """
    create the moon
    """
    n = 'moon'
    moon_time_period = 0.0748
    cmds.sphere(name=n, axis=[0, 1.0, 0], radius=moon_radius * 0.025)
    cmds.setAttr(n + 'Shape.castsShadows', 0)
    cmds.setAttr(n + 'Shape.receiveShadows', 0)
    cmds.select(n)
    create_texture(n)
    cmds.circle(radius=0.25, normalY=1, normalZ=0, name=n + '_orbit')
    cmds.parent('moon_orbit', 'earth')
    cmds.select(n, n + '_orbit')
    cmds.pathAnimation(name=n + '_path',
                       fractionMode=True,
                       follow=True,
                       followAxis='x',
                       upAxis='y',
                       worldUpType='vector',
                       worldUpVector=[0, 1, 0],
                       inverseUp=False,
                       bank=False,
                       startTimeU=1,
                       endTimeU=int(moon_time_period * 10000 / time_period[3] /
                                    2))
    cmds.selectKey(clear=True)
    cmds.selectKey(n + '_path',
                   keyframe=True,
                   time=(1,
                         int(moon_time_period * 10000 / time_period[3] / 2)))
    cmds.keyTangent(inTangentType='linear', outTangentType='linear')
    cmds.setInfinity(postInfinite='cycle')
    animate_rotation('moon',
                     int(moon_time_period * 10000 / time_period[3] / 2))
    def keyFullRotation(self,
                        pObjectName,
                        pStartTime,
                        pEndTime,
                        pTargetAttribute,
                        reverse=False,
                        isTangent=False):

        if reverse == False:
            startValue = 0
            endValue = 360
        else:
            startValue = 360
            endValue = 0

        cmds.cutKey(pObjectName,
                    time=(pStartTime, pEndTime),
                    attribute=pTargetAttribute)

        cmds.setKeyframe(pObjectName,
                         time=pStartTime,
                         attribute=pTargetAttribute,
                         value=startValue)

        cmds.setKeyframe(pObjectName,
                         time=pEndTime,
                         attribute=pTargetAttribute,
                         value=endValue)

        cmds.selectKey(pObjectName,
                       time=(pStartTime, pEndTime),
                       attribute=pTargetAttribute,
                       keyframe=True)
        cmds.keyTangent(inTangentType='linear', outTangentType='linear')
Example #23
0
 def select_curves_to_filter(self,frameBased=True):
     curves = []
     if self.filterAll is True:
         self.select_all_curves()
     else:
         curves = cmds.keyframe(q=True, sl=True, name=True)
         if curves is None:
             cmds.warning("Error: No keys selected, please select at least 4 keys on a curve and try again.")
             return 0
         keys_to_filter = []
         for curve in curves:
             if self.excludeState is True:
                 if curve in self.excludedCurves:
                     curves.remove(curve)
                     continue
             keys = cmds.keyframe(curve,q=True, sl=True)
             min_key = min(keys)
             max_key = max(keys)
             if keys is None:
                 continue
             window_length = 0
             if frameBased:
                 window_length = max_key - min_key
             else:
                 window_length - len(keys)
             if window_length >= 3:
                 keys_to_filter.append((curve,min_key,max_key))
             elif window_length < 3:
                 s = str(" Skipping the curve " + curve +" as not enough keys (<4) selected on curve.")
                 cmds.warning(s)
         cmds.select(cl=1)
         for curve_keys in (keys_to_filter):
             cmds.select(curve_keys[0], add=True)
             cmds.selectKey(curve_keys[0], add=True, t=(curve_keys[1],curve_keys[2]))
Example #24
0
def keyFullRotation(pObjectName, pStartTime, pEndTime, pTargetAttribute):
    """Create a keyframe rotation animation for the specified object.

    Rotates the pObjectName around an axis pTargetAttribute, 
    between pStartTime and pEndTime.
    """

    # Remove any animations within the timerange
    cmds.cutKey(pObjectName,
                time=(pStartTime, pEndTime),
                attribute=pTargetAttribute)

    # Sets the target values for start and end points
    cmds.setKeyframe(pObjectName,
                     time=pStartTime,
                     attribute=pTargetAttribute,
                     value=0)
    cmds.setKeyframe(pObjectName,
                     time=pEndTime,
                     attribute=pTargetAttribute,
                     value=360)

    # Ensure the rotation has linear velocity
    cmds.selectKey(pObjectName,
                   time=(pStartTime, pEndTime),
                   attribute=pTargetAttribute,
                   keyframe=True)
    cmds.keyTangent(inTangentType='linear', outTangentType='linear')
Example #25
0
def sweepPipe(circle, pipeCurve):
	numberOfCVs = cmds.getAttr('%s.cp' % pipeCurve[0], size=1)
	motionPath = cmds.pathAnimation("%s" % circle[0], curve=pipeCurve[0], follow=True, startTimeU=1, endTimeU=numberOfCVs)
	cmds.selectKey("%s.uValue" % motionPath)
	cmds.keyTangent( itt="linear", ott="linear")
	pipeSweep = cmds.snapshot(circle, startTime=1, endTime=numberOfCVs)
	return pipeSweep
def set_handle_in(name, dof, time, tangent, weight):
    node = "%s.%s" % (name, dof)
    cmds.selectKey(node, replace=True, k=True, t=(time,time))
    cmds.keyTangent( edit=True
                   , absolute=True
                   , inAngle=tangent * 180.0 / m.pi
                   , inWeight=weight )
def select_objfrom_curve(*args):
    if not cmds.keyframe(query=True, selected=True, name=True):
        print 'No Curve is selected'
    else:
        selected_list = cmds.ls(selection=True)
        selected_f_curve = cmds.keyframe(query=True, selected=True,
                                         name=True)[0]
        selected_connect = cmds.listConnections(selected_f_curve,
                                                plugs=True)[0]

        if cmds.nodeType(selected_connect) == 'character':
            selected_obj = cmds.listConnections(selected_connect,
                                                type='transform')[0]
        else:
            selected_att = cmds.listConnections(selected_f_curve,
                                                plugs=True)[0]
            selected_obj = selected_att.split(".")[0]

        cmds.select(clear=True)

        if selected_obj in selected_list:
            selected_list.remove(selected_obj)
            cmds.select(clear=True)
            cmds.select(selected_obj, r=True)
            cmds.selectKey(selected_f_curve, add=True)
            for o_obj in selected_list:
                cmds.select(o_obj, add=True)
        else:
            cmds.select(selected_obj, r=True)
            cmds.selectKey(selected_f_curve, add=True)
def filter_sz(dragControl, x, y, modifiers):
    if not cmds.ls(sl=True):
        print 'Nothing is selected'
    else:
        if modifiers == 0:
            first_selected = cmds.ls(sl=True)
            for i in range(len(first_selected)):
                if i == 0:
                    cmds.selectKey(first_selected[i],
                                   replace=True,
                                   attribute='scaleZ')
                else:
                    cmds.selectKey(first_selected[i],
                                   add=True,
                                   attribute='scaleZ')
        elif modifiers == 1:
            outline_ed_name = "graphEditor" + dragControl.split(
                "|").pop()[len('b_c_sz'):] + 'OutlineEd'
            mel.eval('string $outlineed_name = "%s"' % outline_ed_name)
            c_sz = cmds.button(dragControl.split("|").pop(), q=1, bgc=True)
            if (c_sz == [0.0, 0.0, 0.30000762951094834]):
                cmds.button(dragControl.split("|").pop(),
                            edit=1,
                            bgc=[0.0, 0.0, 1.0])
                mel.eval(
                    'filterUISelectAttributesCheckbox scaleZ 1 $outlineed_name;'
                )
            elif (c_sz == [0.0, 0.0, 1.0]):
                cmds.button(dragControl.split("|").pop(),
                            edit=1,
                            bgc=[0.0, 0.0, 0.3])
                mel.eval(
                    'filterUISelectAttributesCheckbox scaleZ 0 $outlineed_name;'
                )
Example #29
0
def createDummyKey(objects=None, select=False):

    objs = filterNoneObjects(objects)

    if len(objs) == 0: objs = getObjsSel()
    cmds.setKeyframe(objs, time=(-50000, -50000), insert=False)
    if select: cmds.selectKey(objs, replace=True, time=(-50000, -50000))
Example #30
0
def gpsTurntable():
	# Set up framerange
	startTime = cmds.playbackOptions ( query = True, minTime = True )
	endTime = cmds.playbackOptions ( query = True, maxTime = True )

	# Get current selection
	selectionList = cmds.ls (selection = True)

	if selectionList:

		# Get centre of selection
		bbox = cmds.exactWorldBoundingBox()

		centre_x = (bbox[0] + bbox[3]) / 2.0
		centre_y = (bbox[1] + bbox[4]) / 2.0
		centre_z = (bbox[2] + bbox[5]) / 2.0
		
		# Create new group
		new_grp = cmds.group(empty=True, name="Turntable_%s_grp#" %selectionList[0])
		cmds.move(centre_x, centre_y, centre_z, new_grp)

		# Create Turntable camera
		new_cam = cmds.camera()
		cmds.select (selectionList, r = True)
		cmds.viewFit (new_cam[0], allObjects = False)
		cmds.parent (new_cam[0], new_grp)
		cmds.setKeyframe (new_grp, time = startTime-1, attribute = "rotateY", value=0)
		cmds.setKeyframe (new_grp, time = endTime, attribute = "rotateY", value=360)
		cmds.selectKey (new_grp, time = (startTime-1, endTime), attribute = "rotateY", keyframe = True)
		cmds.keyTangent (inTangentType = "linear", outTangentType = "linear")
		cmds.rename ("Turntable_%s_cam#" %selectionList[0])
		
	else:
		cmds.warning("Please select one or more objects!")
def change_key_color(onOff):
    current_time = cmds.currentTime(q=True)
    cmds.selectKey(clear=True)
    cmds.selectKey(add=True, keyframe=True, time=(current_time,current_time))
    cmds.keyframe(tds=onOff)
    if onOff:
        mel.eval('timeSliderEditKeys makeKey;')
Example #32
0
def convertConnectionAsAnimCurve(node, attr):

    separateParentConnection(node, attr)

    cons = cmds.listConnections(node + '.' + attr, s=1, d=0, p=1, c=1)
    if not cons: return None

    attrType = cmds.attributeQuery(attr, node=node, attributeType=1)

    if attrType == 'doubleLinear':
        animCurveType = 'animCurveUL'
    elif attrType == 'doubleAngle':
        animCurveType = 'animCurveUA'
    else:
        animCurveType = 'animCurveUU'

    animCurve = cmds.createNode(animCurveType)
    cmds.connectAttr(cons[1], animCurve + '.input')
    cmds.connectAttr(animCurve + '.output', cons[0], f=1)

    cmds.setKeyframe(animCurve, f=-1, v=-1)
    cmds.setKeyframe(animCurve, f=-.5, v=-.5)
    cmds.setKeyframe(animCurve, f=0, v=0)
    cmds.setKeyframe(animCurve, f=.5, v=.5)
    cmds.setKeyframe(animCurve, f=1, v=1)

    cmds.setAttr(animCurve + ".postInfinity", 1)
    cmds.setAttr(animCurve + ".preInfinity", 1)

    cmds.selectKey(animCurve)
    cmds.keyTangent(itt='spline', ott='spline')

    return animCurve
Example #33
0
def goToKeyframe(option='next',
                 roundFrame=False,
                 selected=False,
                 selectKeys=False,
                 searchHierarchy=False):
    '''

    '''

    if option != 'next' and option != 'previous':
        OpenMaya.MGlobal.displayWarning(
            'Option argument should be "next" or "previous"')
        return

    if selected and selectKeys:
        OpenMaya.MGlobal.displayWarning(
            'Cannot use selectKeys flag in conjunction with selected flag.')
        selectKeys = False

    sel = mc.ls(sl=True)
    currentTime = mc.currentTime(query=True)
    time = currentTime

    if not sel:
        if option == 'next':
            time += 1
        elif option == 'previous':
            time -= 1
        else:
            return
        #if nothing is selected, just go to the next or previous keyframe
        with utl.SkipUndo():
            mc.currentTime(time)
        return

    keySel = utl.KeySelection()

    if searchHierarchy:
        #if we're looking through the hierarchy,
        keySel.keyedInHierarchy()

    else:
        #create the keySelection object.
        #all the heavy lifting is done in ml_utilities.
        if selected and keySel.selectedKeys():
            pass
        if keySel.visibleInGraphEditor():
            pass
        if keySel.selectedObjects():
            pass

    time = keySel.findKeyframe(which=option, roundFrame=roundFrame, loop=True)

    if selectKeys:
        mc.selectKey(keySel.curves, time=(time, ))

    #finally, set the time without adding to the undo queue
    with utl.SkipUndo():
        mc.currentTime(time, edit=True)
Example #34
0
    def selectKeys( self, keys ) :

        ''' select the provided keys in the fcurve editor '''

        m.select( self.node )
        m.selectKey(clear=True)
        for i in keys :
            m.selectKey( self.node + '.' + self.attr, t=(i,i), add=True)
Example #35
0
 def reselect(self, objects=True):
     if objects:
         if self.selection:
             sel = cmds.ls(sl=True)
             if sel != self.selection:
                 cmds.select(self.selection)
     if self.pack:
         for cr in self.pack:
             cmds.selectKey(cr[0], add=True, time=(cr[1][0], cr[1][len(cr[1]) - 1]))
Example #36
0
def stepTangents(*args):
    selection = cmds.ls(sl=True)
    if selection:
        cmds.selectKey()
    else:
        cmds.warning(
            'there is no object selected but new keys will be in stepped')
    cmds.keyTangent(itt='linear', ott='step')
    cmds.keyTangent(g=True, itt='linear', ott='step')
 def eulerFilter(self, *args, **kwargs):
     try:
         curveSel=mc.ls(type="animCurve")
         mc.selectKey(curveSel, add=1, k=1)
         mel.eval('filterCurve %s;'%" ".join(curveSel))
         mel.eval('keyTangent -itt linear -ott linear;')
         mc.selectKey(cl=1)
     except:
         print "can't run euler filter"
Example #38
0
def autoTangents(*args):
    selection = cmds.ls(sl=True)
    if selection:
        cmds.selectKey()
    else:
        cmds.warning(
            'there is no object selected but new keys will be in auto')
    cmds.keyTangent(itt='auto', ott='auto')
    cmds.keyTangent(g=True, itt='auto', ott='auto')
def create_keyframes(name, dof, keyframes, dof_values):
    for i in range(len(keyframes)):
        cmds.setKeyframe(name, attribute=dof, v=dof_values[i], t=keyframes[i]+1)

    # enable differences for weights and tangents of input/output for a keyframe
    cmds.selectKey(name, replace=True, k=True)
    cmds.keyTangent(e=True, weightedTangents=True)
    cmds.keyTangent(weightLock=0)
    cmds.keyTangent(lock=0)
Example #40
0
def createDummyKey(objects=None, select=False):

    objs = filterNoneObjects(objects)

    if len(objs) == 0:
        objs = getObjsSel()
    cmds.setKeyframe(objs, time=(-50000, -50000), insert=False)
    if select:
        cmds.selectKey(objs, replace=True, time=(-50000, -50000))
def keyRotation(instance_group, min_play, max_play, attr):
    """ Prepare key frames according to dialog """
    cmds.cutKey(instance_group, time=(min_play, max_play), attribute=attr)
    cmds.setKeyframe(instance_group, time=min_play, attribute=attr, value=0)
    cmds.setKeyframe(instance_group, time=max_play, attribute=attr, value=360)
    cmds.selectKey(instance_group,
                   time=(min_play, max_play),
                   attribute=attr,
                   keyframe=True)
    cmds.keyTangent(inTangentType="linear", outTangentType="linear")
def keyFullRotation(pObjectName, pStartTime, pEndTime, pTargetAttribute):
    cmds.cutKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTargetAttribute)

    cmds.setKeyframe(pObjectName, time=pStartTime, attribute=pTargetAttribute, value=0)

    cmds.setKeyframe(pObjectName, time=pEndTime, attribute=pTargetAttribute, value=360)

    cmds.selectKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTargetAttribute, keyframe=True)

    cmds.keyTangent(inTangentType='linear', outTangentType='linear')
Example #43
0
 def create_fk_setup(self):
     """Creates the FK setup."""
     cmds.setDrivenKeyframe('%s.translateX' % self.fk_jnts[1], cd='%s.length' % self.fk_jnts[0], dv=1, itt='linear', ott='linear')
     cmds.setDrivenKeyframe('%s.translateX' % self.fk_jnts[1], cd='%s.length' % self.fk_jnts[0], dv=0, v=0, itt='linear', ott='linear')
     cmds.setDrivenKeyframe('%s.translateX' % self.fk_jnts[2], cd='%s.length' % self.fk_jnts[1], dv=1, itt='linear', ott='linear')
     cmds.setDrivenKeyframe('%s.translateX' % self.fk_jnts[2], cd='%s.length' % self.fk_jnts[1], dv=0, v=0, itt='linear', ott='linear')
     cmds.selectKey('%s_translateX' % self.fk_jnts[1], k=True, f=(1,))
     cmds.setInfinity(poi='cycleRelative')
     cmds.selectKey('%s_translateX' % self.fk_jnts[2], k=True, f=(1,))
     cmds.setInfinity(poi='cycleRelative')
Example #44
0
def getRoofLinearCurve( startInput, endInput, minValue, maxValue ):
    
    animCurve = cmds.createNode( 'animCurveUU' )
    cmds.setKeyframe( f= startInput, v=minValue )
    cmds.setKeyframe( f= endInput,   v=maxValue )
    cmds.keyTangent( itt='linear', ott='linear' )
    cmds.selectKey( animCurve )
    cmds.setInfinity( poi='cycle', pri='cycle' )
    
    return animCurve
Example #45
0
def polyImagePlane():
    camera = None
    cameraShape = None
    imagePlane = []
    tmp = cmds.ls(sl=True, dag=True, type='imagePlane')
    if len(tmp) > 0:
        imagePlane.append(tmp[0])
    camList = cmds.ls(sl=True, dag=True, type="camera")
    for camName in camList:
        camIP = cmds.listConnections("%s.imagePlane" % camName,
                                     sh=True,
                                     d=True)
        if camIP:
            imagePlane.append(camIP[0])
    imagePlaneList = list(set(imagePlane))
    if len(imagePlaneList) == 0:
        return False
    for imagePlane in imagePlaneList:
        conn = [
            str(m) for m in cmds.listConnections(
                imagePlane, type="camera", shapes=True)
            if str(m) == imagePlane.split("->")[0]
        ]
        if len(conn) > 0:
            cameraShape = getLongName(conn[0])
            camera = cmds.listRelatives(cameraShape, parent=True)[0]
            camera = getLongName(camera)
        else:
            return False
        implane, planeShape, polyPlane = createPolyImagePlane(
            camera, cameraShape, imagePlane)
        cmds.select(implane, replace=True)
        cmds.setAttr("%s.overrideLevelOfDetail" % planeShape, 1)
    seldp = str(cmds.duplicate(implane, rr=True)[0])
    cmds.parent(seldp, w=True)
    temp = str(cmds.parentConstraint(implane, seldp, mo=False, w=True)[0])
    minT = cmds.playbackOptions(q=True, min=True)
    maxT = cmds.playbackOptions(q=True, max=True)
    cmds.bakeResults(seldp, sm=False, t=(minT, maxT), mr=True, pok=True)
    cmds.delete(temp)
    scaleList = ["scaleX", "scaleY", "scaleZ"]
    scl = [float(cmds.getAttr(implane + "." + i)) for i in scaleList]
    cmds.delete(implane)
    if cmds.objExists("|aniGeom"):
        cmds.parent(seldp, "|aniGeom")
    for sca in scaleList:
        cmds.setAttr(seldp + "." + sca, scl[scaleList.index(sca)])
    try:
        cmds.rename(seldp, "projectionCard")
    except:
        pass
    cmds.selectKey(k=True)
    cmds.filterCurve(f="euler")
    return True
Example #46
0
def SwapAnimation(a, b, optionType):
    null = cmds.spaceLocator(name="tempCopyNull")
    cmds.select(null, r=True)
    cmds.animLayer(GetSelectedLayers()[0], edit=True, addSelectedObjects=True)
    if cmds.selectKey(a) > 0:
        SendAnimation(a, null, optionType)
    if cmds.selectKey(b) > 0:
        SendAnimation(b, a, optionType)
    if cmds.selectKey(null) > 0:
        SendAnimation(null, b, optionType)
    cmds.delete(null)
Example #47
0
def j_fixAdv3_99_forMaya2016():
    'fix advanceSkeleton v3.99 stretch not work in maya2016'
    j_drivenKey = {"antiPop":4.990848, "normal":4.878867}
    
    for drv in j_drivenKey: #数值 
        for pat in ("Arm","Leg"):  #arm or leg
            for side in ("_R","_L"):
                for i in ("antiPop","normal"):
                    mc.selectKey(("IKdistance" + pat + side +"Shape_"+ i), ot =True, f = (j_drivenKey[drv],))
                    mc.keyTangent(("IKdistance" + pat + side +"Shape_"+ i), lock = False,)
                    mc.keyTangent( itt = "clamped",ott = "clamped",)       
Example #48
0
def animate_rotation(n, period):
    """
    animates rotation of an object
    """
    cmds.select(n)
    cmds.currentTime(1)
    cmds.setKeyframe(n, breakdown=False, attribute="rotateY")
    cmds.currentTime(period)
    cmds.setAttr(n + '.rotateY', 360)
    cmds.setKeyframe(n, breakdown=False, attribute="rotateY")
    cmds.selectKey(n + '.rotateY')
    cmds.keyTangent(inTangentType='linear', outTangentType='linear')
    cmds.setInfinity(postInfinite='cycle')
Example #49
0
def mirrorKeys(newKeyNode):
    '''Mirror keyframe node procedure, in case you need to flip your SDK's.
    Also works with ordinary keyframe nodes.
    '''

    keyType = cmds.ls(newKeyNode, st=True)[1]
    try:
        cmds.selectKey(clear=True)
    except:
        pass

    # Get the number of keyframes.
    numKeys = len(cmds.listAttr(newKeyNode + '.ktv', multi=True)) / 3

    # Iterate through each key and multiply the values by -1,
    # then set the keyframe value.
    for x in range(0, numKeys):
        v = cmds.getAttr(newKeyNode + '.keyTimeValue[' + str(x) + ']')
        v = [v[0][0], v[0][1] * -1]
        if keyType in ('animCurveTU', 'animCurveTA', 'animCurveTL'):
            cmds.selectKey(newKeyNode, add=True, k=True, t=(v[0], v[0]))
        elif keyType in ('animCurveUU', 'animCurveUA', 'animCurveUL'):
            cmds.selectKey(newKeyNode, add=True, k=True, f=(v[0], v[0]))

        if keyType in ('animCurveTA', 'animCurveUA'):
            cmds.keyframe(animation='keys',
                          absolute=True,
                          valueChange=math.degrees(v[1]))
        else:
            cmds.keyframe(animation='keys', absolute=True, valueChange=v[1])
        try:
            cmds.selectKey(clear=True)
        except:
            pass
Example #50
0
def smoothAnimCurves(objects, isLoop):
    """Set all keys on provided objects to auto tangent, optionally matching in and out tangents."""
    if isinstance(objects, types.StringTypes):
        objects = [objects]
    if not isinstance(objects, types.ListType) and not isinstance(
            objects, types.TupleType):
        sys.stderr.write(
            "ERROR: Unable to smooth animation curves on object %s. Argument must be a string, list, or tuple of objects or attribute names.\n"
        )
        return False
    for object in objects:
        cmds.selectKey(object)
        cmds.keyTangent(itt="spline", ott="spline")
        if isLoop: matchInOutTangents(object)
    return True
Example #51
0
 def select_all_curves(self):
     cmds.select(clear=True)
     curves = cmds.ls(typ='animCurve')
     if curves is None:
         cmds.error("No animation curves are present to select keys from.")
     for curve in curves:
         if self.excludeState is True:
             if curve in self.excludedCurves:
                 continue
         keys = cmds.keyframe(curve,q=True)
         if keys is None:
             continue
         elif len(keys) > 3:
             cmds.select(curve,add=True)
             cmds.selectKey(curve,add=True)
Example #52
0
def key_full_rotation(objectName, start_time, end_time, targetAttr):
    cmds.cutKey(objectName, time=(start_time, end_time), attribute=targetAttr)
    cmds.setKeyframe(objectName,
                     time=start_time,
                     attribute=targetAttr,
                     value=0)
    cmds.setKeyframe(objectName,
                     time=end_time,
                     attribute=targetAttr,
                     value=360)
    cmds.selectKey(objectName,
                   time=(start_time, end_time),
                   attribute=targetAttr,
                   keyframe=True)
    cmds.keyTangent(inTangentType='linear', outTangentType='linear')
Example #53
0
def GreenTickKeys(iAllFrame=0):

    oKeyPoseFrames = 'KeyPoseFrames'
    aKeyFrames = []
    if cmds.objExists(oKeyPoseFrames):
        for i in range(cmds.keyframe(oKeyPoseFrames + '.tx', kc=True, q=True)):
            aKeyFrames.extend(
                cmds.keyframe(oKeyPoseFrames + '.tx', index=(i, i), q=True))

        aObjList = [
            str(s) for s in cmds.selectionConnection(
                'graphEditor1FromOutliner', q=True, object=True) or []
        ]
        #aCurveList = [str(s) for s in cmds.keyframe(q = True, name = True)]

        # Store Selected Keys
        aSelection = []
        for o in aObjList:
            aName = cmds.keyframe(o, query=True, name=True)
            aKeys = cmds.keyframe(o, sl=True, q=True)

            if aName and aKeys:
                aSelection.append([str(aName[0]), aKeys])

        if cmds.ls(sl=True):
            cmds.selectKey(clear=True)

        # DO
        fTime = cmds.currentTime(q=True)
        if fTime in aKeyFrames:
            cmds.keyframe(t=(fTime, fTime), tds=True)

        # Select Stored keys
        if aSelection:
            for a in aSelection:
                sName = a[0]
                for t in a[1]:
                    cmds.selectKey(sName, t=(t, t), tgl=True)

        # Update All Frames red/green.
        if iAllFrame:
            iIn = int(cmds.playbackOptions(q=True, minTime=True))
            iOut = int(cmds.playbackOptions(q=True, maxTime=True))
            for i in range(iIn, iOut + 1):
                if i in aKeyFrames:
                    cmds.keyframe(t=(i, i), tds=True)
                else:
                    cmds.keyframe(t=(i, i), tds=False)
Example #54
0
    def keep_extreme_keys(self):
        cmds.undoInfo(openChunk = True)
        cut_keys = {}
        anim_curves = cmds.keyframe(q = True, sl = True, n = True)
        for anim_curve in anim_curves:
            selected_keys = cmds.keyframe(anim_curve, q = True, sl = True)
            remove_keys = self.get_extreme_frames(anim_curve)
            print remove_keys
            cut_keys[anim_curve] = [x for x in selected_keys if x not in remove_keys]
        for anim_curve in cut_keys:
            select_keys = cut_keys[anim_curve]
            for frame in select_keys:
                cmds.selectKey(anim_curve, time=(frame,frame), keyframe=True)
                cmds.cutKey(animation="keys", clear=True)

        cmds.undoInfo(closeChunk = True)
Example #55
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')
Example #56
0
def MirrorAnimation(item, optionType, scaleMatrix):
    attr = [
        "translateX", "translateY", "translateZ", "rotateX", "rotateY",
        "rotateZ"
    ]
    for idx, a in enumerate(attr):
        if cmds.getAttr(item + '.' + a, lock=True) == False:
            cmds.select(cl=True)
            key = cmds.selectKey(item, attribute=a)
            if (key > 0):
                if optionType == option(option.keys):
                    cmds.selectKey(item, time=(cTime, cTime), attribute=a)
                else:  #"curve"
                    cmds.selectKey(item, attribute=a)
                cmds.scaleKey(valueScale=scaleMatrix[idx], valuePivot=0.0)
    cmds.select(item)
Example #57
0
def bake(world=0, constraint=0):
	if _getTime('rangeSelected'):
		range = [_getTime('rangeMin'), _getTime('rangeMax')]
	else:
		range = [_getTime('playbackMin'), _getTime('playbackMax')]

	if world:
		sels = mc.ls(sl=1)
		selLocs = []
		for sel in sels:
			loc = mc.spaceLocator(name=sel+'_worldBake_loc')[0]
			mc.addAttr(loc, ln='target', dt='string')
			mc.setAttr(loc+'.target', sel, type='string')
			mc.pointConstraint(sel, loc)
			mc.orientConstraint(sel, loc)
			mc.scaleConstraint(sel, loc)
			selLocs.append(loc)

		mc.select(selLocs)
		mc.bakeResults(time=(int(range[0]), int(range[1])), sampleBy=1, sm=1)
		mc.delete(constraints=1)

		if constraint:
			for loc in selLocs:
				target = mc.getAttr(loc+'.target')
				mc.delete(target, channels=1)
				if mc.getAttr(target+'.tx', l=1) or mc.getAttr(target+'.ty', l=1) or mc.getAttr(target+'.tz', l=1):
					mc.warning('Skipping applying pointConstraint because translate channel is locked.')
					pass
				else:
					mc.pointConstraint(loc, target)

				if mc.getAttr(target+'.rx', l=1) or mc.getAttr(target+'.ry', l=1) or mc.getAttr(target+'.rz', l=1):
					mc.warning('Skipping applying orientConstraint because rotate channel is locked.')
					pass
				else:
					mc.orientConstraint(loc, target)

				if mc.getAttr(target+'.sx', l=1) or mc.getAttr(target+'.sy', l=1) or mc.getAttr(target+'.sz', l=1):
					mc.warning('Skipping applying scaleConstraint because scale channel is locked.')
					pass
				else:
					mc.scaleConstraint(loc, target)

	else:
		mc.selectKey(cl=1)
		mc.bakeResults(time=(int(range[0]), int(range[1])), sampleBy=1, sm=1)
Example #58
0
def plot():
	curves = mc.keyframe(q=1, sl=1, name=1)
	if type(curves).__name__ != 'NoneType':
		for curve in curves:
			indexes = mc.keyframe(curve, q=1, sl=1, iv=1)
			if len(indexes) != 1:
				startTime = int(mc.keyframe(curve, q=1, tc=1, index=tuple([indexes[0]]))[0])
				endTime = int(mc.keyframe(curve, q=1, tc=1, index=tuple([indexes[1]]))[0])
				mc.selectKey(cl=1)
				for point in range(startTime, endTime):
					mc.setKeyframe(curve, insert=1, time=point)
					mc.selectKey(curve, time=( (startTime+0.01), (endTime-0.01) ), add=1, k=1)
			else:
				mc.warning('Only one keyframe is selected for the curve ' + curve + '.')
	else:
		sels = mc.ls(sl=1)
		if sels:
			timeSlider = mm.eval('$tmp = $gPlayBackSlider')
			if mc.timeControl(timeSlider, q=1, rv=1) == 1:
				startTime = int(mc.timeControl(timeSlider, q=1, ra=1)[0])
				endTime = int(mc.timeControl(timeSlider, q=1, ra=1)[1])
			else:
				startTime = int(mc.playbackOptions(q=1, min=1))
				endTime = int(mc.playbackOptions(q=1, max=1))

			curves = mc.keyframe(q=1, name=1)
			for curve in curves:
				for point in range(startTime, endTime):
					mc.setKeyframe(curve, insert=1, time=point)
					mc.selectKey(curve, time=( (startTime+0.01), (endTime-0.01) ), add=1, k=1)
		else:
			mc.warning('Nothing is selected.')