Python maya.cmds.keyframe() Examples

The following are 30 code examples of maya.cmds.keyframe(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module maya.cmds , or try the search function .
Example #1
Source File: ml_setKey.py    From ml_tools with MIT License 7 votes vote down vote up
def ui():
    '''
    User interface for ml_setKey
    '''

    with utl.MlUi('ml_setKey', 'SetKey', width=400, height=220, info='''Press Set Key to set a keyframe with the current checkbox settings.
Right click the button to create a hotkey or shelf button
with the currently selected settings.''') as win:

        mc.checkBoxGrp('ml_setKey_chanBox_checkBox', label='Selected Channels', annotation='Only key channels that are selected in the Channel Box')
        mc.checkBoxGrp('ml_setKey_graphVis_checkBox', label='Visible in Graph Editor', annotation='Only key curves visible in Graph Editor')
        mc.checkBoxGrp('ml_setKey_keyKeyed_checkBox', label='Key Only Keyed Channels', annotation='Only set keys on channels that are already keyed')
        mc.checkBoxGrp('ml_setKey_subFrames_checkBox', label='Delete Sub-Frames', annotation='Delete sub-frame keys surrounding the current frame')
        mc.checkBoxGrp('ml_setKey_insert_checkBox', label='Insert Key', annotation='Insert key (preserve tangents)')
        mc.checkBoxGrp('ml_setKey_shapes_checkBox', label='Key Shapes', annotation='Set keyframes on shapes')

        win.ButtonWithPopup(label='Set Key', name=win.name, command=setKey, annotation='Set a keyframe.',
            readUI_toArgs={
                'selectedChannels':'ml_setKey_chanBox_checkBox',
                'visibleInGraphEditor':'ml_setKey_graphVis_checkBox',
                'keyKeyed':'ml_setKey_keyKeyed_checkBox',
                'deleteSubFrames':'ml_setKey_subFrames_checkBox',
                'insert':'ml_setKey_insert_checkBox',
                'keyShapes':'ml_setKey_shapes_checkBox',
                }) 
Example #2
Source File: ml_utilities.py    From ml_tools with MIT License 6 votes vote down vote up
def selectedLayers(self, includeLayerWeight=True):
        '''
        This affects keys on all layers that the node belongs to.
        If includeLayerWeight, the keys on the layer's weight attribute will be affected also.
        '''
        layers = getSelectedAnimLayers()
        curves = list()
        for layer in layers:
            layerCurves = mc.animLayer(layer, query=True, animCurves=True)
            if layerCurves:
                curves.extend(layerCurves)
            if includeLayerWeight:
                weightCurve = mc.keyframe(layer+'.weight', query=True, name=True)
                if weightCurve:
                    curves.append(weightCurve[0])
        self._curves = curves
        #we only want to use curves, since nodes or channels wont accurately represent all layers
        self._nodes = None
        self._channels = None 
Example #3
Source File: ml_utilities.py    From ml_tools with MIT License 6 votes vote down vote up
def time(self):
        '''
        The keySelection's time, formatted for maya's various keyframe command arguments.
        '''
        if self._time:
            if isinstance(self._time, list):
                return tuple(self._time)
            elif isinstance(self._time, float) or isinstance(self._time, int):
                return (self._time,)
            return self._time
        elif self._timeRangeStart and self._timeRangeEnd:
            return (self._timeRangeStart,self._timeRangeEnd)
        elif self._timeRangeStart:
            return (str(self._timeRangeStart)+':',)
        elif self._timeRangeEnd:
            return (':'+str(self._timeRangeEnd),)
        elif self.selected:
            #if keys are selected, get their times
            timeList = self.keyframe(query=True, timeChange=True)
            return tuple(set(timeList))
        return (':',) 
Example #4
Source File: ml_graphEditorMask.py    From ml_tools with MIT License 6 votes vote down vote up
def selected(*args):

    curves = mc.keyframe(query=True, selected=True, name=True)
    if not curves:
        return

    try:
        mc.delete(ATTR_FILTER_NAME)
    except:pass
    try:
        mc.delete(OBJ_FILTER_NAME)
    except:pass

    filters = list()
    for c in curves:
        plug = mc.listConnections(c, plugs=True, source=False, destination=True)[0]
        print plug
        filters.append(mc.itemFilter(byName=plug, classification='user'))

    print filters
    selectedFilter = mc.itemFilter(union=filters)
    #mc.delete(filters)
    print selectedFilter
    mc.outlinerEditor('graphEditor1OutlineEd', edit=True, attrFilter=selectedFilter) 
Example #5
Source File: ml_animCurveEditor.py    From ml_tools with MIT License 6 votes vote down vote up
def scaleValue(percent=100, selectionOption=1, pivotOption=0):

    value = percent/100.0
    keySel = _getKeySelection(selectionOption)
    valuePivot = 0
    if pivotOption:
        values = keySel.keyframe(query=True, valueChange=True)
        values = sorted(list(set(values)))
        if pivotOption == 1:
            valuePivot = values[-1]
        elif pivotOption == 2:
            valuePivot = values[0]
        elif pivotOption == 3:
            valuePivot = (values[0]+values[-1])/2

    keySel.scaleKey(valueScale=value, valuePivot=valuePivot) 
Example #6
Source File: ml_breakdown.py    From ml_tools with MIT License 6 votes vote down vote up
def dragLeft(self):
        '''This is activated by the left mouse button, and weights to the next or previous keys.'''

        #clamp it
        if self.x < -1:
            self.x = -1
        if self.x > 1:
            self.x = 1

        if self.x > 0:
            self.drawString('>> '+str(int(self.x*100))+' %')
            for curve in self.keySel.curves:
                for i,v,n in zip(self.time[curve],self.value[curve],self.next[curve]):
                    mc.keyframe(curve, time=(i,), valueChange=v+((n-v)*self.x))
        elif self.x <0:
            self.drawString('<< '+str(int(self.x*-100))+' %')
            for curve in self.keySel.curves:
                for i,v,p in zip(self.time[curve],self.value[curve],self.prev[curve]):
                    mc.keyframe(curve, time=(i,), valueChange=v+((p-v)*(-1*self.x))) 
Example #7
Source File: ml_utilities.py    From ml_tools with MIT License 6 votes vote down vote up
def setAnimValue(plug, value, tangentType=None):
    '''
    Sets key if the channel is keyed, otherwise setAttr
    '''

    if mc.keyframe(plug, query=True, name=True):
        mc.setKeyframe(plug, value=value)
        if tangentType:
            time = mc.currentTime(query=True)
            itt = tangentType
            ott = tangentType
            if tangentType == 'step':
                itt = 'linear'
            mc.keyTangent(plug, time=(time,), edit=True, itt=itt, ott=ott)

    mc.setAttr(plug, value) 
Example #8
Source File: ml_utilities.py    From ml_tools with MIT License 6 votes vote down vote up
def minimizeRotationCurves(obj):
    '''
    Sets rotation animation to the value closest to zero.
    '''

    rotateCurves = mc.keyframe(obj, attribute=('rotateX','rotateY', 'rotateZ'), query=True, name=True)

    if not rotateCurves or len(rotateCurves) < 3:
        return

    keyTimes = mc.keyframe(rotateCurves, query=True, timeChange=True)
    tempFrame = sorted(keyTimes)[0] - 1

    #set a temp frame
    mc.setKeyframe(rotateCurves, time=(tempFrame,), value=0)

    #euler filter
    mc.filterCurve(rotateCurves)

    #delete temp key
    mc.cutKey(rotateCurves, time=(tempFrame,)) 
Example #9
Source File: ml_animCurveEditor.py    From ml_tools with MIT License 6 votes vote down vote up
def rippleCut(selectionOption=1, setKey=True):

    keySel = _getKeySelection(selectionOption)

    if keySel.selectedFrameRange():pass
    else: return

    start, end = keySel.time

    if setKey:
        if keySel.findKeyframe('previous', time=(start-1,)) < start-1:
            mc.setKeyframe(keySel.curves, time=(start-1,), insert=True)
        if keySel.findKeyframe('next', time=(end,)) > end:
            mc.setKeyframe(keySel.curves, time=(end,), insert=True)
        mc.setKeyframe(keySel.curves, time=(start-1,end), insert=True)

    keySel.cutKey()

    #move everything after the cut
    keySel.keyframe(edit=True, time=(str(end)+':',), relative=True, timeChange=start-end) 
Example #10
Source File: ml_animCurveEditor.py    From ml_tools with MIT License 5 votes vote down vote up
def clampValues(value=0, selectionOption=1, clampOption=0):
    keySel = _getKeySelection(selectionOption)

    for curve, values in zip(keySel.curves, keySel.values):
        indicies = None
        if clampOption==0:
            indicies = [i for i, x in enumerate(values) if x > value]
        elif clampOption==1:
            indicies = [i for i, x in enumerate(values) if x < value]
        if indicies:
            mc.keyframe(curve, index=utl.castToTime(indicies), edit=True, valueChange=value)
            mc.keyTangent(curve, index=utl.castToTime(indicies), itt='auto', ott='auto') 
Example #11
Source File: ml_utilities.py    From ml_tools with MIT License 5 votes vote down vote up
def keyedInHierarchy(self, includeRoot=True):
        '''
        Initializes the keySelection object with all the animation curves in the hierarchy.
        Returns True if successful.
        '''

        if not self.nodeSelection:
            return False

        tops = getRoots(self.nodeSelection)

        if not tops:
            #if we haven't been sucessful, we're done
            return False

        nodes = mc.listRelatives(tops, pa=True, type='transform', ad=True)
        if not nodes:
            nodes = list()

        if includeRoot:
            nodes.extend(tops)

        if not nodes:
            return False

        #now that we've determined the hierarchy, lets find keyed nodes
        #for node in nodes:
        # this will only return time based keyframes, not driven keys
        self._curves = mc.keyframe(nodes, time=(':',), query=True, name=True)

        #nodes or channels can be acessed by the node or channel property
        if not self._curves:
            return False

        return True 
Example #12
Source File: ml_utilities.py    From ml_tools with MIT License 5 votes vote down vote up
def keyframe(self,**kwargs):
        '''
        Wrapper for the keyframe command. Curve and time arguments will be provided based on
        how this object was intitialized, otherwise usage is the same as maya's keyframe command.
        '''
        if self.selected:
            #it's important that selection test first, becuase it's called by the time property
            kwargs['sl'] = True
        elif not 'time' in kwargs:
            kwargs['time'] = self.time

        return mc.keyframe(self.curves, **kwargs) 
Example #13
Source File: ml_utilities.py    From ml_tools with MIT License 5 votes vote down vote up
def moveKey(self, frames):
        '''
        A wrapper for keyframe -edit -timeChange
        '''

        if not frames:
            return

        self.keyframe(edit=True, relative=True, timeChange=frames) 
Example #14
Source File: ml_animCurveEditor.py    From ml_tools with MIT License 5 votes vote down vote up
def cutFrame(selectionOption=1):

    keySel = _getKeySelection(selectionOption)

    frame = mc.currentTime(query=True)
    keySel.cutKey(time=(frame,frame), includeSubFrames=True)

    #move everything after the cut
    keySel.keyframe(edit=True, time=(str(frame)+':',), relative=True, timeChange=-1) 
Example #15
Source File: ml_animCurveEditor.py    From ml_tools with MIT License 5 votes vote down vote up
def insertFrame(selectionOption=1):

    keySel = _getKeySelection(selectionOption)

    #move everything after the current frame
    keySel.keyframe(edit=True, time=(str(mc.currentTime(query=True))+':',), relative=True, timeChange=1) 
Example #16
Source File: ml_utilities.py    From ml_tools with MIT License 5 votes vote down vote up
def times(self):
        '''
        This returns an expanded list of times, which is synced with the curve list.
        '''
        timeList = list()
        theTime = self.time
        for c in self.curves:
            curveTime = tuple(mc.keyframe(c, time=(theTime,), query=True, timeChange=True))
            if len(curveTime) == 1:
                curveTime = (curveTime[0],)
            timeList.append(curveTime)
        return timeList 
Example #17
Source File: ml_hold.py    From ml_tools with MIT License 5 votes vote down vote up
def ui():
    '''
    user interface for ml_hold
    '''

    with utl.MlUi('ml_hold', 'Hold Keys', width=400, height=150, info='''Press Next and Previous to match keys to the next or previous keyframes.
Press Current or Average to turn a frame range into a hold.''') as win:

        win.buttonWithPopup(label='Hold Current', command=current, annotation='Creates a hold for the selected range, or the surrounding keys, based on current frame.', shelfLabel='cur', shelfIcon='defaultTwoStackedLayout')
        win.buttonWithPopup(label='Hold Average', command=average, annotation='Creates a hold for the selected range, or the surrounding keys, based on average of keys.', shelfLabel='avg', shelfIcon='defaultTwoStackedLayout')

        mc.paneLayout(configuration='vertical2',separatorThickness=1)
        win.buttonWithPopup(label='<< Previous', command=previous, annotation='Matches selected key or current frame to the previous keyframe value.', shelfLabel='<_', shelfIcon='defaultTwoStackedLayout')
        win.buttonWithPopup(label='Next >>', command=next, annotation='Matches selected key or current frame to the next keyframe value.', shelfLabel='_>', shelfIcon='defaultTwoStackedLayout') 
Example #18
Source File: ml_hold.py    From ml_tools with MIT License 5 votes vote down vote up
def next(*args):
    '''Matches selected key or current frame to the next keyframe value.'''
    holdFrame(next=True) 
Example #19
Source File: ml_hold.py    From ml_tools with MIT License 5 votes vote down vote up
def previous(*args):
    '''Matches selected key or current frame to the previous keyframe value.'''
    holdFrame(previous=True) 
Example #20
Source File: keyframeReduction.py    From maya-keyframe-reduction with MIT License 5 votes vote down vote up
def getIndices(self):
        """
        :return: List of keyframe indices
        :rtype: list
        """
        return cmds.keyframe(self.path, query=True, indexValue=True) 
Example #21
Source File: keyframeReduction.py    From maya-keyframe-reduction with MIT License 5 votes vote down vote up
def getFrames(self):
        """
        :return: List of keyframe frames
        :rtype: list
        """
        indices = self.getIndices()
        return cmds.keyframe(
            self.path,
            query=True,
            index=(indices[0], indices[-1])
        ) or [] 
Example #22
Source File: keyframeReduction.py    From maya-keyframe-reduction with MIT License 5 votes vote down vote up
def getValues(self, frames):
        """
        :param list frames: Frames to sample
        :return: List of values
        :rtype: list
        """
        return [
            cmds.keyframe(self.path, query=True, eval=True, time=(frame,))[0]
            for frame in frames
        ]

    # ------------------------------------------------------------------------ 
Example #23
Source File: keyframeReduction.py    From maya-keyframe-reduction with MIT License 5 votes vote down vote up
def _removeKeys(self, frames, start):
        """
        Remove all keys appart from the start key and move this start key to
        the start frame. This needs to be done to make sure the start frame
        is on an even frame.

        :param list frames:
        :param int start:
        """
        # remove keys
        cmds.cutKey(self.path, time=(frames[0] + 0.01, frames[-1]), option="keys")

        # move first key to start position in case start position is not on
        # an even frame.
        cmds.keyframe(self.path, edit=True, index=(0,), timeChange=start) 
Example #24
Source File: keyframeReduction.py    From maya-keyframe-reduction with MIT License 5 votes vote down vote up
def _addKeys(self, keyframes, weightedTangents):
        """
        Loop all the keyframes and create a keyframe and set the correct
        tangent information.

        :param list keyframes:
        :param bool weightedTangents:
        """
        # variables
        inAngle = Vector2D(-1, 0)
        outAngle = Vector2D(1, 0)

        # loop keyframes
        for keyframe in keyframes:
            # create keyframe point
            cmds.setKeyframe(self.path, time=keyframe.point.x, value=keyframe.point.y)

            # set keyframe tangent variable
            arguments = {"edit": True, "absolute": True, "time": (keyframe.point.x,)}

            # set weighted tangents
            cmds.keyTangent(self.path, weightedTangents=weightedTangents, **arguments)

            # unlock tangents if either in our out handle is not defined.
            if not keyframe.inHandle or not keyframe.outHandle:
                cmds.keyTangent(self.path, lock=False, **arguments)

                # add in tangent to arguments
            if keyframe.inHandle:
                arguments["inAngle"] = math.degrees(inAngle.signedAngle(keyframe.inHandle))
                arguments["inWeight"] = keyframe.inHandle.length()

            # add out tangent to arguments
            if keyframe.outHandle:
                arguments["outAngle"] = math.degrees(outAngle.signedAngle(keyframe.outHandle))
                arguments["outWeight"] = keyframe.outHandle.length()

            # set keyframe tangent
            cmds.keyTangent(self.path, **arguments)

    # ------------------------------------------------------------------------ 
Example #25
Source File: ml_utilities.py    From ml_tools with MIT License 5 votes vote down vote up
def values(self):
        valueList = list()
        for c in self.curves:
            curveValues = mc.keyframe(c, query=True, valueChange=True)
            if len(curveValues) == 1:
                curveValues = (curveValues[0],)
            valueList.append(curveValues)
        return valueList 
Example #26
Source File: anim_utils.py    From mgear_core with MIT License 5 votes vote down vote up
def keyObj(model, object_names):
    """Set the keyframe in the controls pass by a list in obj_names variable

    Args:
        model (Str): Name of the namespace that will define de the model
        object_names (Str): names of the controls, without the name space

    Returns:
        None
    """
    with pm.UndoChunk():
        nodes = []
        nameSpace = getNamespace(model)
        for name in object_names:
            if nameSpace:
                node = getNode(nameSpace + ":" + name)
            else:
                node = getNode(name)

            if not node:
                continue

            if not node and nameSpace:
                mgear.log("Can't find object : %s:%s" % (nameSpace, name),
                          mgear.sev_error)
            elif not node:
                mgear.log("Can't find object : %s" % (name), mgear.sev_error)
            nodes.append(node)

        if not nodes:
            return

        pm.setKeyframe(*nodes) 
Example #27
Source File: ml_utilities.py    From ml_tools with MIT License 5 votes vote down vote up
def curves(self):
        '''
        The keySelections's animation curve list.
        '''

        # if self._curves is False or None, then it has been initialized and curves haven't been found.
        if self._curves == []:

            #find anim curves connected to channels or nodes
            for each in (self._channels, self._nodes):
                if not each:
                    continue
                # this will only return time based keyframes, not driven keys
                self._curves = mc.keyframe(each, time=(':',), query=True, name=True)

                if self._curves:
                    self._curvesCulled = False
                    break
            if not self._curves:
                self._curves = False

        # need to remove curves which are unkeyable
        # supposedly referenced keys are keyable in 2013, I'll need to test that and update
        if self._curves and not self._curvesCulled:
            remove = list()
            for c in self._curves:
                if mc.referenceQuery(c, isNodeReferenced=True):
                    remove.append(c)
                else:
                    plug = mc.listConnections('.'.join((c,'output')), source=False, plugs=True)
                    if plug:
                        if not mc.getAttr(plug, keyable=True) and not mc.getAttr(plug, settable=True):
                            remove.append(c)
            if remove:
                for r in remove:
                    self._curves.remove(r)
            self._curvesCulled = True

        return self._curves 
Example #28
Source File: ml_utilities.py    From ml_tools with MIT License 5 votes vote down vote up
def castToTime(time):
    '''
    Maya's keyframe commands are finnicky about how lists of times or indicies are formatted.
    '''
    if isinstance(time, (list, tuple)):
        return [(x,) for x in time]
    return (time,) 
Example #29
Source File: standalone.py    From AdvancedPythonForMaya with GNU General Public License v3.0 5 votes vote down vote up
def commands():
    """This function will use the Maya commands API to query keyframes in a scene"""
    # Get the start time so we can calculate how long this took
    start = time.time()

    # Ask Maya to fetch all the animCurves for the joints
    curves = cmds.ls(type='animCurveTA')
    # Then query all the keyframes
    keyframes = set(cmds.keyframe(curves, q=True))

    # Finally calculate how long those two lines took
    delta = time.time() - start
    # And then return it so we tally it up
    return delta 
Example #30
Source File: ml_pivot.py    From ml_tools with MIT License 5 votes vote down vote up
def bakePivot(self):

        if not mc.objExists(self.pivotHandle) or not mc.objExists(self.node):
            self.cleanup()
            return

        newPivot = mc.getAttr(self.pivotHandle+'.translate')[0]

        if newPivot == mc.getAttr(self.node+'.rotatePivot')[0]:
            self.cleanup()
            return

        if not mc.keyframe(self.node, attribute=('tx','ty','tz','rx','ry','rz'), query=True, name=True):
            mc.setAttr(self.node+'.rotatePivot', *newPivot)
            self.cleanup()
            return

        tempPosition = mc.group(em=True)
        mc.delete(mc.parentConstraint(self.pivotHandle, tempPosition))

        utl.matchBake(source=[self.node], destination=[tempPosition], bakeOnOnes=True, maintainOffset=True, preserveTangentWeight=False, rotate=False)

        mc.setAttr(self.node+'.rotatePivot', *newPivot)
        utl.matchBake(source=[tempPosition], destination=[self.node], bakeOnOnes=True, maintainOffset=False, preserveTangentWeight=False, rotate=False)

        mc.delete(tempPosition)

        mc.select(self.node)

        self.cleanup()

        #end context
        try:
            qt_maya_window.removeEventFilter(self.keypressFilter)
        except:
            pass