def CreateTurntable(createCamera = True, *args):
     
     cmds.undoInfo(openChunk = True)
     
     Index = len( TurntableClass.Turntables )
     
     TurntableClass.Turntables.append( TurntableClass( Index ))
     
     if createCamera:
         TurntableClass.Turntables[Index].CreateCamera()
     
     #Create render layer adjustments
     RenderLayerManagerFile.RenderLayerManagerClass.assignTurntable(TurntableClass.Turntables[Index].Camera)
     
     TurntableClass.Turntables[Index].CreateUI()
     
     #Hide all the cameras
     for i in cmds.ls(cameras = True):
         try:
             cmds.setAttr(i + ".visibility", False)
         except:pass
     
     TurntableClass.UpdateDisplayLayer()
     
     cmds.undoInfo(closeChunk = True)
Example #2
0
def Create():

    cmds.undoInfo(openChunk=True)

    sel = cmds.ls(selection=True)
    if not sel:
        cmds.warning('No nodes selected!')

    if len(sel) == 1:
        children = cmds.listRelatives(sel[0], ad=True)
        if children:
            if len(children) == 2:
                sel.append(children[-1])
                sel.append(children[0])
                __create(sel)
            else:
                cmds.warning('Select a 3 chain hierarchy!')
        else:
            cmds.warning('No children found on %s!' % sel[0])
    elif len(sel) == 3:
        __create(sel)
    else:
        cmds.warning('Select 3 nodes, or first node of a 3 chain hierarchy!')

    cmds.undoInfo(closeChunk=True)
    def renameItems(self,):
        if not hasattr(self, "renameWidget"):
            return

        renameTo = self.renameInput.text()
        if renameTo:
            cmds.undoInfo(openChunk=True)
            count = len(self._getSelItems())
            if count > 1:
                items = self._getSelItems()
                for x in range(count):
                    curItem = items[x].text().replace(SEP, "|")
                    if "#" in renameTo:
                        cmds.rename(curItem, "{0}".format(renameTo.replace("#", "{0:02d}".format(x))))
                    else:
                        cmds.rename(curItem, "{0}{1:02d}".format(renameTo, x))
            else:
                name = self.reportTree.currentItem().text().replace(SEP, "|")
                if "#" in renameTo:
                    cmds.rename(name, renameTo.replace("#", "00"))
                else:
                    cmds.rename(name, renameTo)
            cmds.undoInfo(closeChunk=True)
        else:
            logger.info("Please type a name?!")
 def doRelease(self, event ):
     cmds.move( self.beforePosition[0], self.beforePosition[1], self.beforePosition[2], self.transform, ws=1 )
     cmds.undoInfo( swf=1 )
     cmds.move( self.currentPosition[0], self.currentPosition[1], self.currentPosition[2], self.transform, ws=1 )
     
     self.beforeJoint = self.transform
     pass
Example #5
0
 def wrapper(*args, **kwargs):
     mc.undoInfo(openChunk=True)
     try:
         ret = func(*args, **kwargs)
     finally:
         mc.undoInfo(closeChunk=True)
     return ret
Example #6
0
 def connectCommand():
     
     cmds.undoInfo( ock=1 )
     sels = cmds.ls( sl=1 )
     numItems = self.layout.count()
     
     optionWidget = self.layout.itemAt( numItems-2 ).widget()
     
     for i in range( 1, numItems-2 ):
         targetWidget = self.layout.itemAt( i ).widget()
         
         srcAttr = targetWidget.lineEdit_srcAttr.text()
         dstAttr = targetWidget.lineEdit_dstAttr.text()
         
         if not srcAttr or not dstAttr: continue
         
         try: 
             for sel in sels[1:]:
                 target = sel
                 if optionWidget.checkBox.isChecked():
                     selParents = cmds.listRelatives( sel, p=1, f=1 )
                     if selParents:
                         target = selParents[0]
                 cmds.connectAttr( sels[0] + '.' + srcAttr, target + '.' + dstAttr )
         except: pass
     cmds.undoInfo( cck=1 )
    def doPress( self, event ):
        
        if event.mouseButton() == OpenMayaUI.MEvent.kMiddleMouse: 
            cmds.select( d=1 )
            self.beforeJoint = None
            return None
        
        self.transform = None
        mouseX, mouseY = self.getMouseXY( event )

        intersectPoint = Functions.getIntersectPoint( self.dagPath, mouseX, mouseY )
        if not intersectPoint: 
            return None
        
        if not self.beforeJoint:
            cmds.select( d=1 )
        self.transform = cmds.joint()    
        cmds.select( self.transform )
        self.beforePosition = cmds.xform( self.transform, q=1, ws=1, t=1 )[:3]
        cmds.undoInfo( swf=0 )
        cmds.move( intersectPoint.x, intersectPoint.y, intersectPoint.z, self.transform, ws=1 )
        self.currentPosition = [intersectPoint.x, intersectPoint.y, intersectPoint.z]
        
        if self.beforeJoint:
            Functions.setOrientByChild( self.beforeJoint )
            cmds.setAttr( self.transform + '.r', 0,0,0 )
        
        cmds.refresh()
Example #8
0
def run():	
	#get selected edgeloop
	edgeLoop = cmds.ls(selection=True)
	#get verticles in the edge loop
	vertLoop = cmds.polyListComponentConversion(edgeLoop, fromEdge=True, toVertex=True)
	#sort individual verticles into a list
	vertLoop = cmds.ls(vertLoop, flatten=True)

	#open undo chunk so entire operation is a single action
	cmds.undoInfo(openChunk = True)

	#soften the mesh normals
	mesh = cmds.listRelatives(parent=1)
	cmds.polySoftEdge(mesh, angle=180)

	#run on each vertex on the edgeloop
	for vert in vertLoop:
		#unlock the normal of the vertex
		cmds.polyNormalPerVertex(vert, unFreezeNormal=True)
		#get the normals of the vertex on the loop
		vertNormals = list(cmds.polyNormalPerVertex(vert, query=True, xyz=True))
		#get only the first three vectors
		vertNormals = vertNormals[:3]

		# select the neighboring verticles using the declared function below
		vertNeighbors(vert, vertLoop)

		#set their normal angle to match the vertex on the loop
		cmds.polyNormalPerVertex(xyz=vertNormals)

	#reselect the edge loops
	cmds.select(edgeLoop)

	#close undo chunk, operation is done
	cmds.undoInfo(closeChunk = True)
Example #9
0
 def combineShader( shaderList ):
     
     cmds.undoInfo( ock=1 )
     
     targetObjs = []
     for shader in shaderList:
         cmds.hyperShade( objects = shader )
         targetObjs += cmds.ls( sl=1 )
     shadingEngines = cmds.listConnections( shaderList, s=0, d=1, type='shadingEngine' )
     if not shadingEngines: return None
     shadingEngines = list( set( shadingEngines ) )
     targetShadingEngine = shadingEngines[0]
     
     cmds.sets( targetObjs, e=1, forceElement = targetShadingEngine )
     
     cmds.delete( shadingEngines[1:] )
     for shader in shaderList:
         shadingEngines = cmds.listConnections( shader, s=0, d=1, type='shadingEngine' )
         if not shadingEngines:
             cmds.delete( shader )
         elif not targetShadingEngine in shadingEngines:
             cmds.delete( shader, shadingEngines )
     
     Window_global.nodeInfomation = {}
     
     cmds.undoInfo( cck=1 )
Example #10
0
def sliderA(prefix):
    cmds.undoInfo(openChunk=True)
    
    #create nodes
    grp=cmds.group(empty=True,n=(prefix+'_grp'))
    cnt=cmds.circle(r=0.1,ch=False,n=(prefix+'_cnt'))
    shp=cmds.circle(o=True,r=1,ch=False,d=1,s=4,n=(prefix+'_shp'))
    
    #setup shp
    cmds.move(-1,0,0,'%s.cv[0]' % shp[0],r=True,os=True)
    cmds.move(-1,0,0,'%s.cv[4]' % shp[0],r=True,os=True)
    cmds.move(0,-1,0,'%s.cv[1]' % shp[0],r=True,os=True)
    cmds.move(1,0,0,'%s.cv[2]' % shp[0],r=True,os=True)
    cmds.move(0,1,0,'%s.cv[3]' % shp[0],r=True,os=True)
    
    cmds.parent(shp,grp)
    
    cmds.setAttr('%s.overrideEnabled' % shp[0],1)
    cmds.setAttr('%s.overrideDisplayType' % shp[0],2)
    
    #setup cnt
    cmds.parent(cnt,shp)
    
    cmds.setAttr('%s.overrideEnabled' % cnt[0],1)
    
    cmds.transformLimits(cnt,tx=(-1,1),etx=(1,1))
    cmds.transformLimits(cnt,ty=(-1,1),ety=(1,1))
    
    setupAttrs(prefix,cnt[0])
    
    return grp
    
    cmds.undoInfo(closeChunk=True)
Example #11
0
def componentSelectionInOrder():
	'''
	Returns a list of the selected components in the order they were selected.
	'''
	# Get selection
	selection = []
	selectionAll = mc.ls(sl=1)
	lastCommand = mc.undoInfo(q=True,un=True)
	counter = 0
	
	# Traverse undo list
	while lastCommand.count('select'):
		lastCommand = mc.undoInfo(q=True,un=True)
		if lastCommand.count('select'):
			selectElem = lastCommand.split(' ')
			selection.append(selectElem[2])
			mc.undo()
	
	# Sort selection
	selection.reverse()
	realSelection = []
	[realSelection.append(i) for i in selection if not realSelection.count(i)]
	
	# Return result
	return realSelection
Example #12
0
def latticeRemove():

    #undo enable
    cmds.undoInfo(openChunk=True)

    #getting nodes
    sel = cmds.ls(selection=True)
    if not sel:
        cmds.warning('No nodes selected!')
        return

    lat = sel[-1]
    objs = sel[0:-1]

    if cmds.nodeType(cmds.listRelatives(lat, shapes=True)[0]) != 'lattice':
        cmds.warning('Last selected is NOT a lattice!')
        return

    #removing from lattice
    for obj in objs:
        try:
            cmds.lattice(lat, e=True, remove=True, geometry=obj)

            #disconnecting shapes
            shapes = cmds.listRelatives(obj, shapes=True)
            for shp in shapes:
                source = cmds.listConnections(shp + '.inMesh', source=True)
                if cmds.nodeType(source) == 'ffd':
                    attr = cmds.listConnections(shp + '.inMesh', plugs=True)[0]
                    cmds.disconnectAttr(attr, shp + '.inMesh')
        except:
            pass

    cmds.undoInfo(closeChunk=True)
Example #13
0
def mirror_objs(objs):
    # Only work on transforms
    objs = filter(
        lambda obj: isinstance(obj, pymel.nodetypes.Transform) and not isinstance(obj, pymel.nodetypes.Constraint),
        objs)

    # Resolve desired poses without affecting anything
    tms_by_objs = {}
    for obj_dst in objs:
        # Resolve source object
        obj_src = get_ctrl_friend(obj_dst)
        if obj_src is None:
            obj_src = obj_dst

        # Resolve mirror definition
        # If we didn't find any friend, we'll use a default mirror definition.
        data = get_obj_mirror_def(obj_dst)
        if data is None:
            continue

        m = obj_dst.__apimfn__().transformation().asMatrix()

        m = mirror_matrix(m, *data)


        tms_by_objs[obj_src] = OpenMaya.MTransformationMatrix(m)

    # Apply desired poses
    cmds.undoInfo(openChunk=True)
    for mfn_transform_src in tms_by_objs.keys():
        tm = tms_by_objs[mfn_transform_src]
        # HACK: Use cmds so undoes are working
        # mfn_transform_src.set(tm)
        cmds.xform(mfn_transform_src.__melobject__(), matrix=list_from_MMatrix(tm.asMatrix()))
    cmds.undoInfo(closeChunk=True)
Example #14
0
 def exportBake( self, ctls, timeRange ):
     
     cmds.undoInfo( swf=0 )
     time = ( timeRange[0], timeRange[1] )
     sampleValue = timeRange[2]
     
     cmds.bakeResults( ctls, simulation=True, t=time, sampleBy=sampleValue, disableImplicitControl=True, preserveOutsideKeys=False, 
               sparseAnimCurveBake=False, removeBakedAttributeFromLayer=False, bakeOnOverrideLayer=False, minimizeRotation=False, 
               controlPoints=False, shape=False )
     
     timeControl = cmds.createNode( 'timeControl', n='timeControl' )
     
     dgtrAnimCurves = cmds.ls( 'DGTR_*', type='animCurve' )
 
     for anim in dgtrAnimCurves:
         cmds.connectAttr( timeControl+'.outTime', anim+'.input' )
         
     for ctl in ctls:
         animNodeRx = cmds.listConnections( ctl+'.rx', s=1, d=0, type='animCurve' )[0]
         animNodeRy = cmds.listConnections( ctl+'.ry', s=1, d=0, type='animCurve' )[0]
         animNodeRz = cmds.listConnections( ctl+'.rz', s=1, d=0, type='animCurve' )[0]
         
         animNodeIrx = cmds.listConnections( ctl+'.irx', s=1, d=0, type='animCurve' )[0]
         animNodeIry = cmds.listConnections( ctl+'.iry', s=1, d=0, type='animCurve' )[0]
         animNodeIrz = cmds.listConnections( ctl+'.irz', s=1, d=0, type='animCurve' )[0]
         
         self.eulerFilter( [animNodeRx, animNodeRy, animNodeRz] )
         self.eulerFilter( [animNodeIrx, animNodeIry, animNodeIrz] )
     cmds.undoInfo( swf=1 )
 def loadData(self, onlySelectedNodes=False, crashFolder=None, *args):  
     
     cmds.waitCursor(state=True)
     cmds.refresh(suspend=True)
     cmds.undoInfo(openChunk=True)
     utilMod.startProgressBar("aTools Animation Crash Recovery - Loading data...")                
     
     self.pause      = True
     savedData       = self.getSavedData(crashFolder, onlySelectedNodes)
             
     if savedData:
     
         animData    = savedData["animData"]["data"]
         attrData    = savedData["attrData"]["data"] 
     
         self.applyAttrData(attrData)
         self.applyAnimData(animData)
         if not crashFolder: self.loadInfoData()
     
     utilMod.setProgressBar(endProgress=True)
     
     self.pause = False
     
     cmds.undoInfo(closeChunk=True)
     cmds.refresh(suspend=False)    
     cmds.waitCursor(state=False)
Example #16
0
def autoUndoOn():
    undoStatus = cmds.undoInfo(q=True, st=True)
    if not undoStatus:
        print 'Undo status OFF. Change to ON.'
        cmds.undoInfo(st=True)
    else:
        print 'Undo status ON.'
Example #17
0
 def doIt(self):
     
     cmds.undoInfo( swf=0 )
     for tr in self._trs:
         
         dgtrName = 'DGTR_'+tr.replace( self._namespace, '' )
         
         if cmds.listConnections( tr, s=0, d=1, type='dgTransform' ):
             continue
         
         dgTransform = cmds.createNode( 'dgTransform', n= dgtrName.replace( self._namespace, self._namespace[:-1]+'_DGTR'+self._namespace[-1] ) )
         decomposeMatrix = cmds.createNode( 'decomposeMatrix', n=dgTransform+'_DCMP' )
         cmds.connectAttr( tr+'.pm', decomposeMatrix+'.inputMatrix' )
         
         attrList = ['tx','ty','tz','rx','ry','rz','sx','sy','sz']
         
         for attr in attrList:
             cmds.connectAttr( decomposeMatrix+'.o'+attr, dgTransform+'.i'+attr )
             cmds.connectAttr( tr+'.'+attr, dgTransform+'.'+attr )
         
         if cmds.nodeType( tr ) == 'joint':
             cmds.connectAttr( tr+'.jox', dgTransform+'.jox' )
             cmds.connectAttr( tr+'.joy', dgTransform+'.joy' )
             cmds.connectAttr( tr+'.joz', dgTransform+'.joz' )
     cmds.undoInfo( swf=1 )
Example #18
0
	def func( *args, **kwargs ):
		initialState = cmd.undoInfo( q=True, state=True )
		cmd.undoInfo( stateWithoutFlush=False )
		try:
			return f( *args, **kwargs )
		finally:
			cmd.undoInfo( stateWithoutFlush=initialState )
Example #19
0
def cutSkin(mesh, weightThreshold=0.25, reducePercent=None, parentShape=False):
    """
    Extract a per influence proxy mesh from a skinned mesh based on influence weights.
    @param mesh: Mesh to extract faces from
    @type mesh: str
    @param weightThreshold: Influence to use to extract faces
    @type weightThreshold: float
    @param reducePercent: Influence to use to extract faces
    @type reducePercent: int or None
    """
    # Initialize
    startTime = cmds.timerX()
    cmds.undoInfo(state=False)

    # Get Skin Info
    skin = glTools.utils.skinCluster.findRelatedSkinCluster(mesh)
    if not skin:
        print('Cut Skin: Mesh "" has no skinCluster! Skipping...')
        return None

    # Prune Weights
    glTools.utils.skinCluster.lockSkinClusterWeights(skin, lock=False, lockAttr=False)
    pruneWts = glTools.utils.mathUtils.distributeValue(10, rangeStart=0.001, rangeEnd=weightThreshold)
    cmds.select(mesh)
    for wt in pruneWts:
        try:
            mel.eval('doPruneSkinClusterWeightsArgList 1 {"' + str(wt) + '"}')
        except Exception, e:
            print('Prune weight FAILED (' + mesh + ')! ' + str(e))
            break
Example #20
0
 def offsetCurveDragCmd(self, *args ):
     
     if not self._dragStart:
         
         selCurves = cmds.ls( sl=1 )
     
         self._targetCurves = []
         self._keepTargetCurveValues = []
         for curve in selCurves:
             if cmds.attributeQuery( 'centerRate' , node = curve, ex=1 ):
                 self._targetCurves.append( curve )
                 self._keepTargetCurveValues.append( cmds.getAttr( curve+'.centerRate' ) )
         
         if not self._targetCurves:
             cmds.warning( "Select VolumeCurves" )
             return None
         
         self._dragStart = True
         cmds.undoInfo( swf=0 )
         
     multRate = cmds.floatSliderGrp( self._offsetCurve, q=1, v=1 )
         
     for i in range( len( self._targetCurves ) ):
         targetCurve = self._targetCurves[i]
         value       = self._keepTargetCurveValues[i]
         
         cmds.setAttr( targetCurve+'.centerRate', value*multRate )
Example #21
0
 def startRecording(self):
     """Start recording all future undoable commands onto this stack.
     The previous stack will be safed and restored once this class gets destroyed
     or once `stopRecording` gets called.
     
     :note: this method may only be called once, subsequent calls have no effect
     :note: This will forcibly enable the undo queue if required until 
         stopRecording is called."""
     if self._orig_stack is not None:
         return
         
     if self._is_recording:
         raise AssertionError("Another instance already started recording")
         
     # force undo enabled
     if not undoInfo(q=1, st=1):
         self.__class__._disable_undo = True
         cmds.undoInfo(swf=1)
     # END undo info handling
     
     self._undoable_helper = StartUndo()         # assures we have a stack
     
     self.__class__._is_recording = True
     self._orig_stack = sys._maya_stack
     sys._maya_stack = list()            # will record future commands 
     
     # put ourselves on the previous undo queue which allows us to integrate 
     # with the original undo stack if that is required
     self._orig_stack.append(self)
Example #22
0
 def stopRecording(self):
     """Stop recording of undoable comamnds and restore the previous command stack.
     The instance is now ready to undo and redo the recorded commands
     
     :note: this method may only be called once, subsequent calls have no effect"""
     if self._recorded_commands is not None:
         return
     
     try:
         if not self._is_recording:
             raise AssertionError("startRecording was not called")
             
         if self._orig_stack is None:
             raise AssertionError("startRecording was not called on this instance, but on another one")
         
         self.__class__._is_recording = False
         self._recorded_commands = sys._maya_stack
         sys._maya_stack = self._orig_stack
         
         # restore previous undo queue state
         if self._disable_undo:
             self.__class__._disable_undo = False
             cmds.undoInfo(swf=0)
         # END handle undo
     finally:
         # tigger deletion
         self._undoable_helper = None
def ShapeInverterCmdold(base=None, corrective=None, name=None):
    mc.undoInfo(openChunk=True)
    if not base or not corrective:
        sel = mc.ls(sl=True)
        base, corrective = sel
    shapes = mc.listRelatives(base, children=True, shapes=True)
    for s in shapes:
        if mc.getAttr("%s.intermediateObject" % s) and mc.listConnections("%s.worldMesh" % s, source=False):
            origMesh = s
            break
    deformed = mc.polyPlane(ch=False)[0]
    mc.connectAttr("%s.worldMesh" % origMesh, "%s.inMesh" % deformed)
    mc.setAttr("%s.intermediateObject" % origMesh, 0)
    mc.delete(deformed, ch=True)
    mc.setAttr("%s.intermediateObject" % origMesh, 1)
    if not name:
        name = "%s_inverted#" % corrective
    invertedShape = duplicateMesh(base, name=name)
    deformer = mc.deformer(invertedShape, type="ShapeInverter")[0]
    mc.ShapeInverterCmd(baseMesh=base, invertedShape=invertedShape, ShapeInverterdeformer=deformer, origMesh=deformed)
    # correctiveShape = duplicateMesh(base,name=corrective+"_corrective#")
    # mc.connectAttr('%s.outMesh' % getShape(correctiveShape), '%s.correctiveMesh' % deformer)
    # transferMesh(corrective,[correctiveShape])
    mc.connectAttr("%s.outMesh" % getShape(corrective), "%s.correctiveMesh" % deformer)
    mc.setAttr("%s.activate" % deformer, True)
    mc.delete(deformed)
    bdingBx = mc.polyEvaluate(corrective, boundingBox=True)
    xDifVal = bdingBx[0][1] - bdingBx[0][0]
    # mc.move(xDifVal*1.10,correctiveShape,r=True,moveX=True)
    mc.move(xDifVal * 2.20, invertedShape, r=True, moveX=True)
    mc.undoInfo(closeChunk=True)
    return invertedShape  # ,correctiveShape
    def processItems(self, sender = None, all = False, case = ''):
        cmds.undoInfo(openChunk = True)
        cmds.select(clear = True)
        if not all:
            for eachItem in self._getSelItems():
                itemName = eachItem.text().replace(SEP, "|")
                if not cmds.objExists(itemName):
                    itemName = itemName.split("|")[-1] or None

                if itemName:
                    if case == 'select':
                        cmds.select(itemName, add = True, ne = True)
                    elif case == 'delete':
                        cmds.delete(itemName)
                    elif case == 'deleteCH':
                        cmds.delete(itemName, ch = True)
        else:
            count = self.reportTree.count()
            items = []
            for x in range(count):
                if "-----" not in self.reportTree.item(x).text():
                    itemName = self.reportTree.item(x).text().replace(SEP, "|")
                    if not cmds.objExists(itemName):
                        itemName = itemName.split("|")[-1] or None
                    if itemName:
                        items.extend([itemName])

            if case == 'select':
                cmds.select(items, r = True, ne = True)
            elif case == 'delete':
                cmds.delete(items)
            elif case == 'deleteCH':
                cmds.delete(items, ch = True)

        cmds.undoInfo(closeChunk = True)
def updateSelection(undoState):
    global sel
    global selCmp
    global win

    if undoState:
        mc.select( cl=1)
        for obj in sel: obj.getSavedSelection()
        for cmp in selCmp: cmp.getSavedSelection()
    mc.undoInfo( stateWithoutFlush=undoState)

    ratio = mc.floatSliderGrp( win.selection, q=1, v=1)
    mc.select( cl=1)
    #if len( sel) : random.seed( sel[0].tx)
    #elif len( selCmp): random.seed( selCmp[0].tx)

    for obj in sel:
        if obj.tx < ratio:
            mc.select( obj.name,  add=1)

    for cmp in selCmp:
        if cmp.tx < ratio:
            mc.select( cmp.name,  add=1)

    if undoState:
        for obj in sel: obj.saveSelection( ratio)
        for cmp in selCmp: cmp.saveSelection( ratio)
Example #26
0
def load():
    '''loads animation environment'''
    print "loading animation environment presets..."
    #set autoKey
    cmds.autoKeyframe( state=True )
    #set 24fps and playback on all viewports
    cmds.playbackOptions(ps=1.0, v='all')
    #set unlimited undo's
    cmds.undoInfo( state=True, infinity=True )
    #set manipulator sizes
    if lib.checkAboveVersion(2014):
        cmds.manipOptions( r=False, hs=55, ls=4, sph=1 )
    else:
        cmds.manipOptions( r=False, hs=55, ls=4 )
    #set framerate visibility
    mel.eval("setFrameRateVisibility(1);")
    #gimbal rotation
    cmds.manipRotateContext('Rotate', e=True, mode=2)
    #world translation
    cmds.manipMoveContext('Move', e=True, mode=2)
    #time slider height
    aPlayBackSliderPython = mel.eval('$tmpVar=$gPlayBackSlider')
    cmds.timeControl(aPlayBackSliderPython, h=45, e=True);
    #special tick color
    cmds.displayRGBColor("timeSliderTickDrawSpecial", 1,0.5,0)

    #check if hotkeys have been set
    if (cmds.hotkey( 't', ctl=True, query=True, name = True)== 'CharacterAnimationEditorNameCommand'):
        print "Hotkeys have been previously loaded"
    else:
        setHotkeys('default')

    print "ENVIRONMENT SET\n", #the comma forces output on the status line
Example #27
0
 def orientJoints(s):
     """
     Face joints in the correct direction.
     """
     sel = cmds.ls(sl=True)
     err = cmds.undoInfo(openChunk=True)
     try:
         markers = s.markers
         joints = markers.keys()
         with ReSeat(joints):
             for j in joints:
                 m = markers[j]
                 if cmds.objExists(m.marker) and cmds.objExists(j):
                     with Isolate(j):
                         m.setJoint()
                         try:
                             cmds.makeIdentity(
                                 j,
                                 apply=True,
                                 r=True) # Freeze Rotations
                         except RuntimeError:
                             pass
                 else: # User deleted marker / joint. Stop tracking.
                     m.removeMarker()
                     del markers[j]
             cmds.select(sel, r=True)
     except Exception as err:
         raise
     finally:
         cmds.undoInfo(closeChunk=True)
         if err: cmds.undo()
Example #28
0
    def copyWorld(self, *args):
        #print "copyworld"
        self.selection   = cmds.ls(selection=True)
        
        if len(self.selection) < 1: return
        
        if len(self.selection) > 20: 
            message         = "Too many objects selected, continue?"
            confirm         = cmds.confirmDialog( title='Confirm', message=message, button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
            if confirm != 'Yes': return  
        
        cmds.refresh(suspend=True)
        cmds.undoInfo(stateWithoutFlush=False)
        
        self.flushCopyCache(force=True)        
        self.scriptJob()       
        
        self.sourceObjs = self.selection
        self.targetObj  = "world"
        
        for loopObj in self.sourceObjs:        
            matrix     = cmds.xform(loopObj, query=True, ws=True, matrix=True)

            self.copyCache.append(matrix)

        
        cmds.iconTextButton("fakeConstrainBtn", edit=True, image= uiMod.getImagePath("specialTools_fake_constrain_active"),         highlightImage= uiMod.getImagePath("specialTools_fake_constrain_active copy"))
       
        cmds.refresh(suspend=False)
        cmds.undoInfo(stateWithoutFlush=True)
def cacheVP():
    """
    //Cache viewport geometry for playback

    undoInfo -stateWithoutFlush off;

    string $activePanel = `getPanel -wf`;
    modelEditor -e -grid false $activePanel;
    modelEditor -e -allObjects 0 $activePanel;
    modelEditor -e -polymeshes 1 $activePanel;

    int $rangeStartFrame = `playbackOptions -q -min`;

    currentTime -e $rangeStartFrame;
    playbackOptions -playbackSpeed 0 -loop "once" -by 1;
    playButtonForward;
    playbackOptions -playbackSpeed 1 -loop "continuous";

    undoInfo -stateWithoutFlush on;
    """

    cmds.undoInfo(swf=False)
    panType = cmds.getPanel(wf=True)
    cmds.modelEditor(panType, e=True, gr=False)
    cmds.modelEditor(panType, e=True, alo=False)
    cmds.modelEditor(panType, e=True, pm=True)

    rangeStartFrame = cmds.playbackOptions(q=True, min=True)

    cmds.currentTime = int(rangeStartFrame)
    cmds.playbackOptions(ps=0, l="once", by=1)
    cmds.play(f=True, ps=True)
    cmds.playbackOptions(ps=1, l="continuous")
    cmds.undoInfo(swf=True)
Example #30
0
        def setAttrCommand():
            
            import pymel.core
            cmds.undoInfo( ock=1 )
            sels = pymel.core.ls( sl=1 )
            numItems = self.layout.count()
            
            for i in range( 1, numItems-1 ):
                targetWidget = self.layout.itemAt( i ).widget()
                
                attrName = targetWidget.lineEdit_srcAttr.text()
                attrValue = targetWidget.lineEdit_dstAttr.text()
                
                if not attrName or not attrValue: continue

                for sel in sels:
                    attrType = sel.attr( attrName ).type()
                    if attrType == 'string':
                        sel.attr( attrName ).set( attrValue )
                    else:
                        print "attr value : ", attrValue
                        if attrValue.find( ',' ) != -1:
                            values = [ float( value ) for value in attrValue.split( ',' ) ]
                            sel.attr( attrName ).set( values )
                        else:
                            sel.attr( attrName ).set( float( attrValue ) ) 

            cmds.undoInfo( cck=1 )
def invert(base=None, corrective=None, name=None):
    """@brief Inverts a shape through the deformation chain.

    @param[in] base Deformed base mesh.
    @param[in] corrective Sculpted corrective mesh.
    @param[in] name Name of the generated inverted shape.
    @return The name of the inverted shape.
    """
    if not cmds.pluginInfo('cvShapeInverter.py', query=True, loaded=True):
        cmds.loadPlugin('cvShapeInverter.py')
    cmds.undoInfo(openChunk=True)
    if not base or not corrective:
        sel = cmds.ls(sl=True)
        if not sel or len(sel) != 2:
            cmds.undoInfo(closeChunk=True)
            raise RuntimeError, 'Select base then corrective'
        base, corrective = sel

    # Get points on base mesh
    basePoints = getPoints(base)
    numPoints = basePoints.length()

    # Get points on corrective mesh
    correctivePoints = getPoints(corrective)

    # Get the intermediate mesh
    shapes = cmds.listRelatives(base, children=True, shapes=True)
    for s in shapes:
        if cmds.getAttr('%s.intermediateObject' % s) and cmds.listConnections(
                '%s.worldMesh' % s, source=False):
            origMesh = s
            break
    else:
        cmds.undoInfo(closeChunk=True)
        raise RuntimeError('No intermediate shape found for %s.' % base)

    # Get the component offset axes
    origPoints = getPoints(origMesh)
    xPoints = OpenMaya.MPointArray(origPoints)
    yPoints = OpenMaya.MPointArray(origPoints)
    zPoints = OpenMaya.MPointArray(origPoints)

    for i in range(numPoints):
        xPoints[i].x += 1.0
        yPoints[i].y += 1.0
        zPoints[i].z += 1.0
    setPoints(origMesh, xPoints)
    xPoints = getPoints(base)
    setPoints(origMesh, yPoints)
    yPoints = getPoints(base)
    setPoints(origMesh, zPoints)
    zPoints = getPoints(base)
    setPoints(origMesh, origPoints)

    # Create the mesh to get the inversion deformer
    if not name:
        name = '%s_inverted' % corrective

    invertedShape = cmds.duplicate(base, name=name)[0]
    # Delete the unnessary shapes
    shapes = cmds.listRelatives(invertedShape, children=True, shapes=True)
    for s in shapes:
        if cmds.getAttr('%s.intermediateObject' % s):
            cmds.delete(s)
    setPoints(invertedShape, origPoints)
    # Unlock the transformation attrs
    for attr in 'trs':
        for x in 'xyz':
            cmds.setAttr('%s.%s%s' % (invertedShape, attr, x), lock=False)
    cmds.setAttr('%s.visibility' % invertedShape, 1)
    deformer = cmds.deformer(invertedShape, type='cvShapeInverter')[0]

    # Calculate the inversion matrices
    oDeformer = getMObject(deformer)
    fnDeformer = OpenMaya.MFnDependencyNode(oDeformer)
    plugMatrix = fnDeformer.findPlug('inversionMatrix', False)
    fnMatrixData = OpenMaya.MFnMatrixData()
    for i in range(numPoints):
        matrix = OpenMaya.MMatrix()
        setMatrixRow(matrix, xPoints[i] - basePoints[i], 0)
        setMatrixRow(matrix, yPoints[i] - basePoints[i], 1)
        setMatrixRow(matrix, zPoints[i] - basePoints[i], 2)
        matrix = matrix.inverse()
        oMatrix = fnMatrixData.create(matrix)

        plugMatrixElement = plugMatrix.elementByLogicalIndex(i)
        plugMatrixElement.setMObject(oMatrix)

    # Store the base points.
    fnPointData = OpenMaya.MFnPointArrayData()
    oPointData = fnPointData.create(basePoints)
    plugDeformedPoints = fnDeformer.findPlug('deformedPoints', False)
    plugDeformedPoints.setMObject(oPointData)

    cmds.connectAttr('%s.outMesh' % getShape(corrective),
                     '%s.correctiveMesh' % deformer)
    cmds.setAttr('%s.activate' % deformer, True)

    cmds.undoInfo(closeChunk=True)
    return invertedShape
Example #32
0
 def __exit__(self, *exc):
     cmds.undoInfo(closeChunk=True)
Example #33
0
 def __enter__(self):
     cmds.undoInfo(openChunk=True)
Example #34
0
def dm2skin_doMushOptimization(mesh,
                               mushMesh=None,
                               maxInfluences=4,
                               progressBar=None):
    """Does the actual job of solving the minimization problem."""

    if not mushMesh:
        return False

    minTime = cmds.playbackOptions(q=True, min=True)
    maxTime = cmds.playbackOptions(q=True, max=True)
    # assume the first frame is the bind pose
    cmds.currentTime(minTime)

    skinClusterStr = 'findRelatedSkinCluster("' + mesh + '")'
    skinCluster = mel.eval(skinClusterStr)
    if not skinCluster:
        return False

    allInfluences = cmds.skinCluster(skinCluster, q=True, inf=True)
    numVerts = cmds.polyEvaluate(mesh, v=True)

    invMatrices = dm2skin_getMatrices(allInfluences,
                                      matrixString='.worldInverseMatrix')
    transMatrices = dm2skin_getMatricesOverRange(allInfluences,
                                                 matrixString='.worldMatrix',
                                                 startFrame=int(minTime) + 1,
                                                 endFrame=int(maxTime))

    bindVertList = dm2skin_getVertexLocationList(mesh, frame=int(minTime))
    mushedVertList = dm2skin_getVertexPositionsOverRange(
        mushMesh, startFrame=int(minTime) + 1, endFrame=int(maxTime))

    # if there is a progress bar provided, set the maximum value to
    # the total number of verts
    if progressBar:
        progressBar.setMaximum(numVerts)

    setWeightList = []

    # reset to the first frame again before we start
    cmds.currentTime(minTime)
    for i in range(numVerts):

        if progressBar:
            progressBar.setValue(i)

        largestInf = dm2skin_getLargestInfluenceOnVert(
            mesh + '.vtx[' + str(i) + ']', skinCluster)
        vertInfluences = dm2skin_getNeighbouringJoints(
            largestInf,
            vertexString=mesh + '.vtx[' + str(i) + ']',
            cluster=skinCluster,
            influences=maxInfluences)

        if not vertInfluences:
            print("Error getting neighbour joints")
            progressBar.setValue(0)
            return

        properInfIndices = [allInfluences.index(inf) for inf in vertInfluences]

        currentInvMatrices = []
        currentTransMatrices = []

        currentInvMatrices = [invMatrices[pi] for pi in properInfIndices]

        for t in range(len(transMatrices)):
            currentTransMatrices.append(
                [transMatrices[t][ind] for ind in properInfIndices])

        boundsList = []
        startValList = []
        for j in range(len(vertInfluences)):
            boundsList.append((0, 1))
            startValList.append(1.0 / len(vertInfluences))

        cons = ({'type': 'eq', 'fun': dm2skin_normalizeWeightsConstraint})
        result = minimize(dm2skin_computeSourceMushDistance,
                          startValList,
                          method='SLSQP',
                          args=(mushMesh, mesh, i, bindVertList,
                                mushedVertList, currentInvMatrices,
                                currentTransMatrices, vertInfluences),
                          constraints=cons,
                          bounds=boundsList)
        tempList = []
        for j in range(len(vertInfluences)):
            tempList.append((vertInfluences[j], np.around(result.x[j], 3)))
        setWeightList.append(tempList)

    # open an undo chunk
    cmds.undoInfo(openChunk=True)

    # lock the allInfluences, then we can change the max influences on
    # the skin cluster
    for inf in allInfluences:
        cmds.skinCluster(skinCluster, e=True, inf=inf, lw=True)

    # the scipy solve might not neccesarily have used all the
    # available influences, so this block checks through each
    # set of weights and finds the highest number of non zero
    # ones
    maxInfsUsed = 0
    for i in range(numVerts):
        vertInfVals = [
            setWeightList[i][j][1] for j in range(len(setWeightList[i]))
        ]
        numNonZero = dm2skin_getNumberOfNonZeroElements(vertInfVals)
        if numNonZero > maxInfsUsed:
            maxInfsUsed = numNonZero

    # set the new number of influences on the skin cluster and
    # unlock the influences
    cmds.skinCluster(skinCluster, e=True, mi=maxInfsUsed)
    for inf in allInfluences:
        cmds.skinCluster(skinCluster, e=True, inf=inf, lw=False)

    # set the new weights
    for i in range(numVerts):
        cmds.skinPercent(skinCluster,
                         mesh + '.vtx[' + str(i) + ']',
                         normalize=True,
                         relative=False,
                         zri=True,
                         transformValue=setWeightList[i])

    # close undo chunk and reset progress bar
    cmds.undoInfo(closeChunk=True)

    if progressBar:
        progressBar.setValue(0)
Example #35
0
    def compute( self, plug , dataBlock ):
        
        outsAttr = [ self.outputTAttr , self.outputRAttr , self.outputSAttr ]                    
        if not ( plug in outsAttr ):
            return om.kUnknownParameter


        # _________________________________ IN MATRIX
        
        dataHandle     = dataBlock.inputValue( self.inputMatrixAAttr )
        floatMatrix    = dataHandle.asFloatMatrix()
        matrixA        = MMatrixToNum(floatMatrix) 

        dataHandle     = dataBlock.inputValue( self.inputMatrixBAttr )
        floatMatrix    = dataHandle.asFloatMatrix()
        matrixB        = MMatrixToNum(floatMatrix)         


        dataHandle     = dataBlock.inputValue( self.inputMatrixBaseAAttr )
        floatMatrix      = dataHandle.asFloatMatrix()
        matrixBaseA  = MMatrixToNum(floatMatrix) 

        dataHandle     = dataBlock.inputValue( self.inputMatrixBaseBAttr )
        floatMatrix      = dataHandle.asFloatMatrix()
        matrixBaseB  = MMatrixToNum(floatMatrix)         
                     
        dataHandle     = dataBlock.inputValue( self.inputMatrixBaseGAttr )
        floatMatrix      = dataHandle.asFloatMatrix()
        matrixBaseG  = MMatrixToNum(floatMatrix)           
               
        
        # _________________________________ IN DYN ATTR 
        
        dataHandle     = dataBlock.inputValue( self.inputTimeAttr )
        intime         = dataHandle.asFloat()           

        dataHandle     = dataBlock.inputValue( self.inputActivateAttr )
        activate       = dataHandle.asFloat()         
               
        dataHandle     = dataBlock.inputValue( self.input1Attr )
        mass           = dataHandle.asFloat()           
                         
        dataHandle     = dataBlock.inputValue( self.input2Attr )
        elasticity     = dataHandle.asFloat()
                        
        dataHandle     = dataBlock.inputValue( self.input3Attr )
        damping        = dataHandle.asFloat()   
        
        dataHandle     = dataBlock.inputValue( self.input4Attr )
        gravity        = dataHandle.asFloat()     

        # _________________________________ SAVE NEXT EVAL        
        
        dataHandle     = dataBlock.inputValue( self.inputNext1Attr )
        self.nbrEval   = dataHandle.asFloat()
        
        dataHandle     = dataBlock.inputValue( self.inputNext2Attr ) 
        self.lastTime  = dataHandle.asFloat()                    
  
        dataHandle     = dataBlock.inputValue( self.inputNext3Attr )
        self.lastSpeed = dataHandle.asFloat3()
        self.lastSpeed = [ self.lastSpeed[0] , self.lastSpeed[1] , self.lastSpeed[2] ]      
        
        dataHandle     = dataBlock.inputValue( self.inputNext4Attr )           
        self.slaveValue= dataHandle.asFloat3()          
        self.slaveValue= [ self.slaveValue[0] , self.slaveValue[1] , self.slaveValue[2] ]             
                    
        #_____________________________________________________________________________________COMPUTE
        
        gravityVector = [ 0 , gravity * -1 , 0 ]
               
        #_______________ DELTA TIME        
        incrEval      = 0.04
        self.nbrEval += incrEval
        
        curTime       = self.nbrEval       
        deltaTime     = curTime - self.lastTime         
        self.lastTime = curTime 
        
        #_______________ TRS  
        trsObj           = trsClass.trsClass()         
        masterATrs  = trsObj.createFromFloatMatrix( matrixA ) 
        masterBTrs  = trsObj.createFromFloatMatrix( matrixB )   
 
        baseATrs  = trsObj.createFromFloatMatrix( matrixBaseA ) 
        baseBTrs  = trsObj.createFromFloatMatrix( matrixBaseB )   
        baseGTrs  = trsObj.createFromFloatMatrix( matrixBaseG )          
        
        
        
        middleTrs = trsObj.getMiddleTrs( masterBTrs , inTrsValue = masterATrs )
          

        #_______________ CALCULATE F TENSION SELF COLLISION
        
        #_______________ DYNAMIC       
        curentFrame   = mc.currentTime( query = True )
        startFrame    = mc.playbackOptions( query = True , minTime = True )

        if( activate == 0 ) or ( curentFrame == startFrame ):
            
            self.nbrEval          = 0
            self.lastTime         = 0
            self.lastSpeed       = [ 0 , 0 , 0 ]       
            self.slaveValue     = middleTrs[0:3]
            
            
            self.convertSpaceInfoToDynParameters( baseATrs , baseBTrs , baseGTrs , mass )
            print()

                
        else:

            # DYNAMIC
            for i in range( 0 , 3 ):
                self.slaveValue[i] , self.lastSpeed[i] = self.computeTubeDynamic2( masterATrs[i] , masterBTrs[i] , self.slaveValue[i] , self.lastSpeed[i] , mass , elasticity , damping , gravityVector[i] ,  deltaTime )         

        
        
        
        translate = self.slaveValue
        rotate    = [0,0,0]        
        scale     = [1,1,1] 
        
        #_____________________________________________________________________________________ OUT NEXT
 
        nodeName = self.name()  
        mc.undoInfo( swf = 0 )
        
        mc.setAttr( nodeName +'.'+ self.kInputNext1AttrName  , self.nbrEval  ) 
        mc.setAttr( nodeName +'.'+ self.kInputNext2AttrName  , self.lastTime  )        
        mc.setAttr( nodeName +'.'+ self.kInputNext3AttrName  , self.lastSpeed[0] ,  self.lastSpeed[1] ,  self.lastSpeed[2] , type = 'double3')            
        mc.setAttr( nodeName +'.'+ self.kInputNext4AttrName  , self.slaveValue[0] , self.slaveValue[1] , self.slaveValue[2] , type = 'double3')  
        
        mc.undoInfo( swf = 1 )        

        #_____________________________________________________________________________________COMPUTE OUT

        dataHandle = dataBlock.outputValue( self.outputTAttr )       
        dataHandle.set3Double( translate[0] , translate[1] , translate[2] )
        dataHandle.setClean()        
     
        dataHandle = dataBlock.outputValue( self.outputRAttr )       
        dataHandle.set3Double( math.radians(rotate[0]) , math.radians(rotate[1]) , math.radians(rotate[2]) )  
        dataHandle.setClean()    
        
        dataHandle = dataBlock.outputValue( self.outputSAttr )       
        dataHandle.set3Double( scale[0] , scale[1] , scale[2]  ) 
        dataHandle.setClean()            

        dataBlock.setClean( plug ) 
Example #36
0
def HotKey_NextKey():
    # NextKey v2.0.1
    cmds.undoInfo(swf=0)
    cmds.currentTime(cmds.findKeyframe(timeSlider=True, which='next'))
    GreenTickKeys()
    cmds.undoInfo(swf=1)
Example #37
0
    def Action_MoveTransformsPivot(self):
        maya_cmds.undoInfo(openChunk=True)
        try:
            transforms = self.window.Text_Transforms.toPlainText().strip(
            ).split('\n')
            checkX = self.window.Check_X.isChecked()
            checkY = self.window.Check_Y.isChecked()
            checkZ = self.window.Check_Z.isChecked()

            locator = self.window.Line_Locator.text().strip()
            checkRotate = self.window.Check_MoveTransformsPivotRotPiv.isChecked(
            )
            checkScale = self.window.Check_MoveTransformsPivotScaPiv.isChecked(
            )
            rotatePivot = maya_cmds.xform(locator,
                                          q=True,
                                          worldSpace=True,
                                          rotatePivot=True)
            scalePivot = maya_cmds.xform(locator,
                                         q=True,
                                         worldSpace=True,
                                         scalePivot=True)

            for i in xrange(len(transforms)):
                rotatePivotObj = transforms[i] + '.rotatePivot'
                scalePivotObj = transforms[i] + '.scalePivot'
                if checkX:
                    if checkRotate:
                        maya_cmds.move(rotatePivot[0],
                                       0,
                                       0,
                                       rotatePivotObj,
                                       absolute=True,
                                       x=True)
                    if checkScale:
                        maya_cmds.move(scalePivot[0],
                                       0,
                                       0,
                                       scalePivotObj,
                                       absolute=True,
                                       x=True)
                if checkY:
                    if checkRotate:
                        maya_cmds.move(rotatePivot[1],
                                       0,
                                       0,
                                       rotatePivotObj,
                                       absolute=True,
                                       y=True)
                    if checkScale:
                        maya_cmds.move(scalePivot[1],
                                       0,
                                       0,
                                       scalePivotObj,
                                       absolute=True,
                                       y=True)
                if checkZ:
                    if checkRotate:
                        maya_cmds.move(rotatePivot[2],
                                       0,
                                       0,
                                       rotatePivotObj,
                                       absolute=True,
                                       z=True)
                    if checkScale:
                        maya_cmds.move(scalePivot[2],
                                       0,
                                       0,
                                       scalePivotObj,
                                       absolute=True,
                                       z=True)
        except Exception as e:
            print >> stderr, str(e)
        maya_cmds.undoInfo(closeChunk=True)
Example #38
0
def undoContext():
	cmds.undoInfo(openChunk=True)
	try:
		yield
	finally:
		cmds.undoInfo(closeChunk=True)
 def __exit__(self, exc_type, exc_value, traceback):
     cmds.undoInfo(closeChunk=True)
     if exc_type:
         log.exception('%s : %s' % (exc_type, exc_value))
     # If this was false, it would re-raise the exception when complete
     return True
 def __enter__(self):
     if self.initialUndo:
         self.undoCall()
     cmds.undoInfo(openChunk=True)
    def compute(self, plug, dataBlock):

        outsAttr = [self.outputXAttr, self.outputYAttr, self.outputZAttr]
        if not (plug in outsAttr):
            return om.kUnknownParameter
    #_____________________________________________________________________________________ IN

        dataHandle = dataBlock.inputValue(self.inputTimeAttr)
        intime = dataHandle.asFloat()

        dataHandle = dataBlock.inputValue(self.input1Attr)
        activate = dataHandle.asFloat()

        dataHandle = dataBlock.inputValue(self.input2Attr)
        leadMFloatMatrix = dataHandle.asFloatMatrix()
        leadMatrix = MMatrixToNum(leadMFloatMatrix)

        dataHandle = dataBlock.inputValue(self.input3Attr)
        worldMFloatMatrix = dataHandle.asFloatMatrix()
        worldMatrix = MMatrixToNum(worldMFloatMatrix)

        dataHandle = dataBlock.inputValue(self.input4Attr)
        mass = dataHandle.asFloat()

        dataHandle = dataBlock.inputValue(self.input5Attr)
        elasticity = dataHandle.asFloat()

        dataHandle = dataBlock.inputValue(self.input6Attr)
        damping = dataHandle.asFloat()

        dataHandle = dataBlock.inputValue(self.input7Attr)
        collision = dataHandle.asFloat()

        dataHandle = dataBlock.inputValue(self.input8Attr)
        self.minRotValues = dataHandle.asFloat3()
        self.minRotValues = [
            self.minRotValues[0], self.minRotValues[1], self.minRotValues[2]
        ]

        dataHandle = dataBlock.inputValue(self.input9Attr)
        self.maxRotValues = dataHandle.asFloat3()
        self.maxRotValues = [
            self.maxRotValues[0], self.maxRotValues[1], self.maxRotValues[2]
        ]

        dataHandle = dataBlock.inputValue(self.input10Attr)
        distance = dataHandle.asFloat()

        dataHandle = dataBlock.inputValue(self.input11Attr)
        self.nbrEval = dataHandle.asFloat()

        dataHandle = dataBlock.inputValue(self.input12Attr)
        self.lastTime = dataHandle.asFloat()

        dataHandle = dataBlock.inputValue(self.input13Attr)
        self.lastSpeed = dataHandle.asFloat3()
        self.lastSpeed = [
            self.lastSpeed[0], self.lastSpeed[1], self.lastSpeed[2]
        ]

        dataHandle = dataBlock.inputValue(self.input14Attr)
        self.slaveValue = dataHandle.asFloat3()
        self.slaveValue = [
            self.slaveValue[0], self.slaveValue[1], self.slaveValue[2]
        ]

        dataHandle = dataBlock.inputValue(self.input15Attr)
        axeDirWay = dataHandle.asInt()

        dataHandle = dataBlock.inputValue(self.input16Attr)
        ctrlTranslate = dataHandle.asFloat3()

        dataHandle = dataBlock.inputValue(self.input17Attr)
        ctrlRotate = dataHandle.asFloat3()

        dataHandle = dataBlock.inputValue(self.input18Attr)
        ctrlScale = dataHandle.asFloat3()

        dataHandle = dataBlock.inputValue(self.input19Attr)
        follow = dataHandle.asFloat()

        #_____________________________________________________________________________________COMPUTE
        trsObj = trsClass.trsClass()

        #_______________ SIGN AXE
        signDir = 1
        axeDir = axeDirWay
        if (2 < axeDir):
            signDir = -1
            axeDir -= 3

    #_______________ DELTA TIME
        incrEval = 0.04
        self.nbrEval += incrEval

        curTime = self.nbrEval
        deltaTime = curTime - self.lastTime
        self.lastTime = curTime

        #_______________ TRS
        origTrsWorld = trsObj.createFromFloatMatrix(worldMatrix)

        ctrlTrsLocal = [
            ctrlTranslate[0], ctrlTranslate[1], ctrlTranslate[2],
            ctrlRotate[0], ctrlRotate[1], ctrlRotate[2], ctrlScale[0],
            ctrlScale[1], ctrlScale[2]
        ]
        ctrlTrsWorld = trsObj.unParent(origTrsWorld, inTrsValue=ctrlTrsLocal)

        ctrlTrsLocalClamped = ctrlTrsLocal[:]
        if not (collision == 0):
            for i in range(0, 3):
                if not (i == axeDir):
                    ctrlTrsLocalClamped[i + 3] = max(
                        min(ctrlTrsLocal[i + 3], self.maxRotValues[i]),
                        self.minRotValues[i])

        ctrlTrsWorldClamped = trsObj.unParent(origTrsWorld,
                                              inTrsValue=ctrlTrsLocalClamped)

        offsetTrsBase = [0, 0, 0, 0, 0, 0, 1, 1, 1]
        offsetTrsBase[axeDir] = distance * signDir
        ctrlOffsetTrs = trsObj.offsetItself(offsetTrsBase,
                                            inTrsValue=ctrlTrsWorldClamped)

        #_______________ DYNAMIC
        curentFrame = mc.currentTime(query=True)
        startFrame = mc.playbackOptions(query=True, minTime=True)

        if (activate == 0) or (curentFrame == startFrame):

            self.nbrEval = 0
            self.lastTime = 0
            self.lastSpeed = [0, 0, 0]
            self.slaveValue = ctrlOffsetTrs[0:3]
            self.leadCollision = None
            angleOut = self.angleCompute(axeDirWay, ctrlTrsWorld,
                                         ctrlOffsetTrs, self.slaveValue)

        else:

            # DYNAMIC
            for i in range(0, 3):
                self.slaveValue[i], self.lastSpeed[i] = self.computeDynamic(
                    ctrlOffsetTrs[i], self.slaveValue[i], self.lastSpeed[i],
                    mass, elasticity, damping, deltaTime)

            # FOLLOW SYS
            if not (follow == 0):
                vToTarget = ompy.MVector(
                    self.slaveValue[0] - ctrlTrsWorldClamped[0],
                    self.slaveValue[1] - ctrlTrsWorldClamped[1],
                    self.slaveValue[2] - ctrlTrsWorldClamped[2])
                vFollow = vToTarget * (distance / vToTarget.length())
                self.slaveValue = [
                    ctrlTrsWorldClamped[0] + vFollow.x,
                    ctrlTrsWorldClamped[1] + vFollow.y,
                    ctrlTrsWorldClamped[2] + vFollow.z
                ]

            # COLLISION
            allAxesLimites = [[0, 2, 1], [2, 1, 0], [1, 0, 2]]
            axeLimites = allAxesLimites[axeDir]

            if not (collision == 0):

                ctrlTrsWorldOrigOrient = ctrlTrsWorld[0:3] + origTrsWorld[
                    3:6] + ctrlTrsWorld[6:9]
                origOffsetTrs = trsObj.offsetItself(
                    offsetTrsBase, inTrsValue=ctrlTrsWorldOrigOrient)
                angleOutCollision = self.angleCompute(
                    axeDirWay, ctrlTrsWorldOrigOrient, origOffsetTrs,
                    self.slaveValue + [0, 0, 0, 1, 1, 1])

                # RECOMPUTE NEXT DYN:   slaveValue   lastSpeed

                for i in range(0, 3):

                    if (i == axeDir):
                        continue

                    if (self.minRotValues[i] == 0) and (self.maxRotValues[i]
                                                        == 0):
                        planeCoords = trsObj.toPlaneCoords(
                            axeNormal=axeLimites[i],
                            inTrsValue=ctrlTrsWorldOrigOrient)
                        self.slaveValue = trsObj.snapOnPlane(
                            planeCoords,
                            inTrsValue=self.slaveValue + [0, 0, 0, 1, 1, 1])
                        continue

                    if (angleOutCollision[i] < self.minRotValues[i]) or (
                            self.maxRotValues[i] < angleOutCollision[i]):

                        if (angleOutCollision[i] < self.minRotValues[i]):
                            limitRotValue = self.minRotValues
                        elif (self.maxRotValues[i] < angleOutCollision[i]):
                            limitRotValue = self.maxRotValues

                        # plane coord corresponding to the limit

                        offsetTrsBase = [0, 0, 0, 0, 0, 0, 1, 1, 1]
                        offsetTrsBase[i + 3] = limitRotValue[i]
                        trsObj.offsetItself(offsetTrsBase,
                                            inTrsValue=ctrlTrsWorldOrigOrient)
                        planeCoords = trsObj.toPlaneCoords(
                            axeNormal=axeLimites[i])

                        #slaveValue
                        self.slaveValue = trsObj.snapOnPlane(
                            planeCoords,
                            inTrsValue=self.slaveValue + [0, 0, 0, 1, 1, 1])

                        #lastSpeed
                        mVectorA = ompy.MVector(
                            planeCoords[1][0] - planeCoords[0][0],
                            planeCoords[1][1] - planeCoords[0][1],
                            planeCoords[1][2] - planeCoords[0][2])
                        mVectorB = ompy.MVector(
                            planeCoords[2][0] - planeCoords[0][0],
                            planeCoords[2][1] - planeCoords[0][1],
                            planeCoords[2][2] - planeCoords[0][2])
                        mVectorMoyen = ompy.MVector(
                            origOffsetTrs[0] - self.slaveValue[0],
                            origOffsetTrs[1] - self.slaveValue[1],
                            origOffsetTrs[2] - self.slaveValue[2])
                        mVectorNormal = utilsMayaApi.get2VectorsNormal(
                            mVectorA, mVectorB, mVectorMoyen)

                        mlastSpeed = ompy.MVector(self.lastSpeed[0],
                                                  self.lastSpeed[1],
                                                  self.lastSpeed[2])

                        if (mVectorNormal * mlastSpeed < 0):
                            self.lastSpeed = self.getReflectVector(
                                self.lastSpeed, planeCoords, collision)

            # OUT ANGLE
            angleOut = self.angleCompute(axeDirWay, ctrlTrsWorld,
                                         ctrlOffsetTrs, self.slaveValue)

            angleOut = [
                activate * angleOut[0], activate * angleOut[1],
                activate * angleOut[2]
            ]

    #_____________________________________________________________________________________ OUT

        nodeName = self.name()
        mc.undoInfo(swf=0)
        mc.setAttr(nodeName + '.' + self.kInput11AttrName, self.nbrEval)
        mc.setAttr(nodeName + '.' + self.kInput12AttrName, self.lastTime)
        mc.setAttr(nodeName + '.' + self.kInput13AttrName,
                   self.lastSpeed[0],
                   self.lastSpeed[1],
                   self.lastSpeed[2],
                   type='double3')
        mc.setAttr(nodeName + '.' + self.kInput14AttrName,
                   self.slaveValue[0],
                   self.slaveValue[1],
                   self.slaveValue[2],
                   type='double3')
        mc.undoInfo(swf=1)

        output = angleOut[0]
        dataHandle = dataBlock.outputValue(self.outputXAttr)
        dataHandle.setFloat(output)

        output = angleOut[1]
        dataHandle = dataBlock.outputValue(self.outputYAttr)
        dataHandle.setFloat(output)

        output = angleOut[2]
        dataHandle = dataBlock.outputValue(self.outputZAttr)
        dataHandle.setFloat(output)

        dataBlock.setClean(plug)
Example #42
0
def chunk_undo():
    cmds.undoInfo(openChunk=True)
    yield
    cmds.undoInfo(closeChunk=True)
Example #43
0
    def Action_Center(self):
        maya_cmds.undoInfo(openChunk=True)
        try:
            transforms = self.window.Text_Transforms.toPlainText().strip(
            ).split('\n')
            checkX = self.window.Check_X.isChecked()
            checkY = self.window.Check_Y.isChecked()
            checkZ = self.window.Check_Z.isChecked()

            checkRotate = self.window.Check_MinMaxCenRotPiv.isChecked()
            checkScale = self.window.Check_MinMaxCenScaPiv.isChecked()

            for i in xrange(len(transforms)):
                boundaries = maya_cmds.exactWorldBoundingBox(
                    transforms[i], calculateExactly=True)
                rotatePivotObj = transforms[i] + '.rotatePivot'
                scalePivotObj = transforms[i] + '.scalePivot'
                if checkX:
                    if checkRotate:
                        maya_cmds.move((boundaries[0] + boundaries[3]) / 2.0,
                                       0,
                                       0,
                                       rotatePivotObj,
                                       absolute=True,
                                       x=True)
                    if checkScale:
                        maya_cmds.move((boundaries[0] + boundaries[3]) / 2.0,
                                       0,
                                       0,
                                       scalePivotObj,
                                       absolute=True,
                                       x=True)
                if checkY:
                    if checkRotate:
                        maya_cmds.move((boundaries[1] + boundaries[4]) / 2.0,
                                       0,
                                       0,
                                       rotatePivotObj,
                                       absolute=True,
                                       y=True)
                    if checkScale:
                        maya_cmds.move((boundaries[1] + boundaries[4]) / 2.0,
                                       0,
                                       0,
                                       scalePivotObj,
                                       absolute=True,
                                       y=True)
                if checkZ:
                    if checkRotate:
                        maya_cmds.move((boundaries[2] + boundaries[5]) / 2.0,
                                       0,
                                       0,
                                       rotatePivotObj,
                                       absolute=True,
                                       z=True)
                    if checkScale:
                        maya_cmds.move((boundaries[2] + boundaries[5]) / 2.0,
                                       0,
                                       0,
                                       scalePivotObj,
                                       absolute=True,
                                       z=True)
        except Exception as e:
            print >> stderr, str(e)
        maya_cmds.undoInfo(closeChunk=True)
def move(source_target=(), translate=('x', 'y', 'z'),
         rotate=('x', 'y', 'z'), scale=(),
         world_space=True, mirror=False, mirror_axis='x',
         behavior=False):
    """
    Move an object according to another object's coordinates, to snap or
    mirror position, in world or object space, using a specified mirror
    axis.

    :param source_target: couple source/target
    :type source_target: list

    :param translate: tuple of translate channel to move
    :type translate: tuple

    :param rotate: tuple of rotate channel to move
    :type rotate: tuple

    :param scale: tuple of scale channel to move
    :type scale: tuple

    :param world_space: world space by default, object space if False
    :type world_space: boolean

    :param mirror: mirror state
    :type mirror: boolean

    :param mirror_axis: mirror axis
    :type mirror_axis: str

    :param behavior: mirroring behavior/orientation
    :type behavior: boolean

    :return:
    """
    # UNDO : Open history chunk
    mc.undoInfo(openChunk=True)

    try:
        # Define couple source/target if not already defined
        if len(source_target) == 0:
            if len(mc.ls(sl=True)) > 1:
                source_target = mc.ls(sl=True)[:2]
            else:
                source_target = mc.ls(sl=True)

        # If no source and target given, or to get from selection : return
        if len(source_target) == 0:
            print "No source and no target, skipped."
            return
        # If only one object selected : mirror from its own coordinates
        elif len(source_target) == 1:
            source_target.append(source_target[0])
        else:
            source_target = source_target[:2]

        source = source_target[0]
        target = source_target[1]

        # Get initial transforms from source and target
        if world_space:
            source_translate = mc.xform(source, q=True, t=True, ws=True)
            source_rotate = mc.xform(source, q=True, ro=True, ws=True)
            source_scale = mc.xform(source, q=True, s=True, ws=True)

            target_translate = mc.xform(target, q=True, t=True, ws=True)
            target_rotate = mc.xform(target, q=True, ro=True, ws=True)
            target_scale = mc.xform(target, q=True, s=True, ws=True)
        else:
            source_translate = mc.xform(source, q=True, t=True, os=True)
            source_rotate = mc.xform(source, q=True, ro=True, os=True)
            source_scale = mc.xform(source, q=True, s=True, os=True)

            target_translate = mc.xform(target, q=True, t=True, os=True)
            target_rotate = mc.xform(target, q=True, ro=True, os=True)
            target_scale = mc.xform(target, q=True, s=True, os=True)

        # Defining mirror multiplier
        if mirror and mirror_axis == 'x':
            mir_val = [-1, 1, 1]
        elif mirror and mirror_axis == 'y':
            mir_val = [1, -1, 1]
        elif mirror and mirror_axis == 'z':
            mir_val = [1, 1, -1]
        else:
            mir_val = [1, 1, 1]

        translate_value = [0, 0, 0]
        rotate_value = [0, 0, 0]
        scale_value = [1, 1, 1]

        # Defining transforms
        # ------------------------------------------------------------------
        # TRANSLATE
        if 'x' in translate:
            translate_value[0] = source_translate[0] * mir_val[0]
        else:
            translate_value[0] = target_translate[0]

        if 'y' in translate:
            translate_value[1] = source_translate[1] * mir_val[1]
        else:
            translate_value[1] = target_translate[1]

        if 'z' in translate:
            translate_value[2] = source_translate[2] * mir_val[2]
        else:
            translate_value[2] = target_translate[2]
        # ------------------------------------------------------------------
        # ROTATE
        # X axis
        if 'x' in rotate:
            # If mirror
            if mirror:
                # If behavior
                if behavior:
                    # If mirror X or Y
                    if mirror_axis == 'x' or mirror_axis == 'y':
                        rotate_value[0] = source_rotate[0] + 180
                        # If mirror Z
                    else:
                        rotate_value[0] = source_rotate[0]
                # If orientation
                else:
                    # If mirror X or Y
                    if mirror_axis == 'x' or mirror_axis == 'y':
                        rotate_value[0] = 180 - source_rotate[0]
                    # If mirror Z
                    else:
                        rotate_value[0] = -source_rotate[0]
            # If rotate X in attribute BUT NOT mirror
            else:
                rotate_value[0] = source_rotate[0]
        # If NOT rotate X in attributes
        else:
            rotate_value[0] = target_rotate[0]
        # --------------------
        # Y axis
        if 'y' in rotate:
            # If mirror
            if mirror:
                # If behavior
                if behavior:
                    # If mirror X or Y
                    if mirror_axis == 'x' or mirror_axis == 'y':
                        rotate_value[1] = - source_rotate[1]
                    # If mirror Z
                    else:
                        rotate_value[1] = source_rotate[1]
                # If orientation
                else:
                    # If mirror X or Y
                    if mirror_axis == 'x' or mirror_axis == 'y':
                        rotate_value[1] = source_rotate[1]
                    # If mirror Z
                    else:
                        rotate_value[1] = -source_rotate[1]
            # If rotate Y in attribute BUT NOT mirror
            else:
                rotate_value[1] = source_rotate[1]
        # If NOT rotate Y attributes
        else:
            rotate_value[1] = target_rotate[1]
        # --------------------
        # Z axis
        if 'z' in rotate:
            # If mirror
            if mirror:
                # If behavior
                if behavior:
                    # If mirror X
                    if mirror_axis == 'x':
                        rotate_value[2] = -source_rotate[2]
                    # If mirror Y
                    elif mirror_axis == 'y':
                        # If rotate z is negative
                        if source_rotate[2] < 0:
                            rotate_value[2] = -180 - source_rotate[2]
                        # If rotate z is positive
                        else:
                            rotate_value[2] = 180 - source_rotate[2]
                    # If mirror Z
                    else:
                        # If rotate z is negative
                        if source_rotate[2] < 0:
                            rotate_value[2] = source_rotate[2] + 180
                        # If rotate z is positive
                        else:
                            rotate_value[2] = source_rotate[2] - 180
                # If orientation
                else:
                    # If mirror X
                    if mirror_axis == 'x':
                        rotate_value[2] = 180 - source_rotate[2]
                    # If mirror Y
                    elif mirror_axis == 'y':
                        rotate_value[2] = -source_rotate[2]
                    # If mirror Z
                    else:
                        rotate_value[2] = source_rotate[2]
            # If rotate Z in attribute BUT NOT mirror
            else:
                rotate_value[2] = source_rotate[2]
        # If NOT rotate Z in attributes
        else:
            rotate_value[2] = target_rotate[2]
        # ------------------------------------------------------------------
        # SCALE
        if 'x' in scale:
            scale_value[0] = source_scale[0] * mir_val[0]
        else:
            scale_value[0] = target_scale[0]

        if 'y' in scale:
            scale_value[1] = source_scale[1] * mir_val[1]
        else:
            scale_value[1] = target_scale[1]

        if 'z' in scale:
            scale_value[2] = source_scale[2] * mir_val[2]
        else:
            scale_value[2] = target_scale[2]

        # Normalize rotate values
        for i, value in enumerate(rotate):
            if value > 180:
                rotate_value[i] -= 360
            elif value < -180:
                rotate_value[i] += 360
            else:
                rotate_value[i] = value

        # Move the target according to the new coordinates
        if world_space:
            print(source_translate, source_rotate, source_scale,
                  target_translate, target_rotate, target_scale,)
            mc.xform(target, t=translate_value, ws=True)
            mc.xform(target, ro=rotate_value, ws=True)
            mc.xform(target, s=scale_value, ws=True)
        else:
            print(source_translate, source_rotate, source_scale,
                  target_translate, target_rotate, target_scale,)
            mc.xform(target, t=translate_value, os=True)
            mc.xform(target, ro=rotate_value, os=True)
            mc.xform(target, s=scale_value, os=True)
            # UNDO : Close history chunk
    finally:
        mc.undoInfo(closeChunk=True)
Example #45
0
def HotKey_PreviousKey():
    # PrevKey v2.0.1
    cmds.undoInfo(swf=0)
    cmds.currentTime(cmds.findKeyframe(timeSlider=True, which='previous'))
    GreenTickKeys()
    cmds.undoInfo(swf=1)
Example #46
0
 def _wrapper(*args, **kwargs):
     cmds.undoInfo(openChunk=True)
     func(*args, **kwargs)
     cmds.undoInfo(closeChunk=True)
def fKBuilder(nameSearchString):
    """Function to execute FK building given the nameSearchString, which it will get from the UI"""
    mySel = cmds.ls(sl=True)
    #print mySel

    myCtrlGrp = mySel[
        len(mySel) -
        1]  #This is going to be the Control that is duplicated - MAKE SURE THE CONTROL GROUP IS SELECTED LAST!
    validCtrl = False
    myJnts = cmds.ls(
        mySel, type="joint")  #This is going to be the Joint that is controlled
    #print "my Joints : "  + str(myJnts)

    #print myCtrlGrp

    validJointNames = True

    for jnt in myJnts:
        if not jointNameCheck(jnt, nameSearchString):
            validJointNames = False

    if validJointNames:
        if "Ctrl" in myCtrlGrp:
            grpChild = cmds.listRelatives(myCtrlGrp, children=True)
            #print grpChild #Finds Transform
            grpCurveChild = cmds.listRelatives(grpChild[0], children=True)
            #print grpCurveChild
            grpCurveShape = cmds.ls(grpCurveChild, type="nurbsCurve")
            #print grpCurveShape
            if len(grpCurveShape) == 1:
                #print "We have a valid Control"
                validCtrl = True
            else:
                print "No valid Control Selected"
        else:
            print "No valid Control Selected"

        myNewCtrlGrps = []

        if validCtrl and (len(myJnts)) != 0:
            cmds.undoInfo(openChunk=True)

            #We are good to go
            for jnt in myJnts:
                #print "My control is : " + myCtrlGrp
                newCtrlPack = (cmds.duplicate(myCtrlGrp, renameChildren=True))
                newGrpName = nameRebuild(jnt,
                                         nameSearchString,
                                         "jnt",
                                         "grp",
                                         nameAddition="fkCtrl")
                newCtrlName = nameRebuild(jnt,
                                          nameSearchString,
                                          "jnt",
                                          "cv",
                                          nameAddition="fkCtrl")
                cmds.rename(newCtrlPack[0], newGrpName)
                cmds.rename(newCtrlPack[1], newCtrlName)
                myNewCtrlGrps.append(newGrpName)
                #print "My new Ctrl is : " + str(newGrpName)
                tempConst = cmds.parentConstraint(jnt, newGrpName)
                cmds.delete(tempConst)  #Delete the temporary constraint
                #Sonow correctly parent Constrain the Joint to the control
                parCName = nameRebuild(jnt,
                                       nameSearchString,
                                       "jnt",
                                       "parC",
                                       nameAddition="fk")
                cmds.parentConstraint(cmds.listRelatives(newGrpName,
                                                         children=True)[0],
                                      jnt,
                                      name=parCName)
        else:
            print "Selection Error - Bad Control or No Joints Selected"

        #Now go through all the resulting controls and setup Parent Constrain relationships
        for i, ctrlGrp in enumerate(myNewCtrlGrps):
            if i != 0:
                parentCVCtrl = cmds.listRelatives(myNewCtrlGrps[i - 1],
                                                  children=True)[0]
                cmds.parentConstraint(parentCVCtrl,
                                      ctrlGrp,
                                      maintainOffset=True)

        cmds.select(mySel)  #Return Selection to orginal before Tool Execution
        cmds.undoInfo(closeChunk=True)
cmds.file(
    '/mnt/luma_i/assets/chr/rig/ij_chr_alejandro/50/characters_ij_chr_alejandro_50.mb',
    open=True,
    force=True,
    resetError=True)
print 'Opening ', anim_file_path
cmds.file(anim_file_path, open=True, force=True, resetError=True)
cmds.loadPlugin('AbcExport')

# The fun starts here... ######################################################
print '\n' * 5
print '*' * 80
print 'Starting Animation Shot Character Export... Good luck!'

# OPEN UNDO CHUNK
cmds.undoInfo(openChunk=True)

shot_root = os.environ['IJ_SHOT_PATH']
json_file = open(os.path.join(shot_root, 'shot_info.json'), 'r')
json_data = json.load(json_file)[0]
json_file.close()
chars = json_data['assets']['chars']
if type(chars) != list:
    tmp = chars
    chars = []
    chars.append(tmp)
frame_s = int(json_data['clip_start'])
frame_e = int(json_data['clip_end'])
char_roots = cmds.ls('*IJ_CHR_*')
rig_controllers = cmds.ls('*ij_chr_*:rig_controllers_set', sets=True)
print '\tWorking in %s' % shot_root
Example #49
0
def keys_editor_func(option, piv):
    keyCount = cmds.keyframe(q=True, sl=True, kc=True)
    if keyCount == 0:
        return

    cmds.undoInfo(openChunk=True, chunkName="keys_editor_func")

    if option == "push":
        scaleValue = 1 / 0.9
    elif option == "pull":
        scaleValue = 0.9
    elif option == "neg":
        scaleValue = -1
    elif option == "offset":
        pass
    else:
        cmds.undoInfo(closeChunk=True, chunkName="keys_editor_func")
        return

    selectedCurves = cmds.keyframe(q=True, n=True, sl=True)
    for crv in selectedCurves:
        timeArray = cmds.keyframe(crv, q=True, tc=True, sl=True)
        if piv == "left":
            pivTime = cmds.findKeyframe(crv,
                                        which="previous",
                                        time=(timeArray[0], timeArray[0]))
            keyValue = cmds.keyframe(crv,
                                     q=True,
                                     time=(timeArray[0], timeArray[0]),
                                     vc=True)[0]
            pivValue = cmds.keyframe(crv,
                                     q=True,
                                     time=(pivTime, pivTime),
                                     vc=True)[0]
        elif piv == "right":
            pivTime = cmds.findKeyframe(crv,
                                        which="next",
                                        time=(timeArray[-1], timeArray[-1]))
            keyValue = cmds.keyframe(crv,
                                     q=True,
                                     time=(timeArray[-1], timeArray[-1]),
                                     vc=True)[0]
            pivValue = cmds.keyframe(crv,
                                     q=True,
                                     time=(pivTime, pivTime),
                                     vc=True)[0]
        elif piv == "avg":
            keyValues = cmds.keyframe(crv, q=True, sl=True, vc=True)
            pivValue = (max(keyValues) + min(keyValues)) / 2
        else:
            break

        selectedValues = cmds.keyframe(crv, q=True, iv=True, sl=True)
        if option == "offset":
            offsetValue = pivValue - keyValue
            for slv in selectedValues:
                cmds.keyframe(crv,
                              relative=True,
                              index=(slv, slv),
                              vc=offsetValue)
        else:
            for slv in selectedValues:
                cmds.scaleKey(crv,
                              index=(slv, slv),
                              vp=pivValue,
                              vs=scaleValue)

    cmds.undoInfo(closeChunk=True, chunkName="keys_editor_func")
Example #50
0
 def applyFilter(self):
     #apply original curve for undo step
     cmds.undoInfo(swf=True)
     cmds.undoInfo(openChunk=True, chunkName = "Apply curve changes")
     try:
         apply_curves(self.animCurvesBuffer)
     finally:
         cmds.undoInfo(closeChunk=True)
     #apply processed curve for undo step
     cmds.undoInfo(swf=True)
     cmds.undoInfo(openChunk=True)
     try:
         if self.animCurvesProcessed is not None:
             apply_curves(self.animCurvesBuffer, self.animCurvesProcessed)
         select_curves(self.animCurvesBuffer)
     finally:
         cmds.undoInfo(closeChunk=True)
     self.switchButtons(False)
     self.switchTabs(True)
     self.animCurvesBuffer = None
     self.animCurvesProcessed = None
     self.previewActive = False
     self.controllingCurve = None
     self.MainWindowUI.statusBar().showMessage("")
def invert(base=None, name=None):
    """
    Create an inverted blend shape for the selected mesh.

    The mesh must have a front-of-chain blendShape deformer.
    """
    _load_plugin()
    if not base:
        sel = cmds.ls(sl=True, l=True)
        if not sel or len(sel) != 1:
            OpenMaya.MGlobal.displayError(
                'Select a mesh to create an inverted blend shape for.')
            return
        base = sel[0]

    # Find the front of chain blendShape node.
    foc_blend_shape = _find_first_blend_shape(base)
    # print 'Using blend shape node: %s' % foc_blend_shape
    if foc_blend_shape is None:
        OpenMaya.MGlobal.displayError('%s has no blendShape.' % base)
        return

    if not name:
        name = '%s_inverted' % base

    cmds.undoInfo(openChunk=True)
    try:
        # Create a new mesh to be the inverted shape.  The base mesh will be the same as the input
        # into the blend shape.
        blend_shape_input_geometry = _get_plug_from_node(
            '%s.input[0].inputGeometry' % foc_blend_shape)
        inverted_shape_transform_node = OpenMaya.MFnMesh().copy(
            blend_shape_input_geometry.asMObject())
        inverted_shape_transform = OpenMaya.MFnTransform(
            inverted_shape_transform_node).partialPathName()

        # Important: The new mesh will have no shading group.  This looks like it works, but sculpting
        # tools will get confused and the mesh will randomly begin rendering corrupt in VP2.0 if we don't
        # assign a SG.
        cmds.sets(inverted_shape_transform,
                  e=True,
                  forceElement='initialShadingGroup')

        # Rename the new mesh's transform.
        inverted_shape_transform = cmds.rename(inverted_shape_transform, name)

        # Find the shape.
        inverted_shape = cmds.listRelatives(inverted_shape_transform,
                                            shapes=True,
                                            pa=True)[0]

        # print 'Shape node:', inverted_shape

        # Hide the new blend shape.
        cmds.setAttr('%s.visibility' % inverted_shape_transform, False)

        # Apply the same transform to the new shape as the input mesh.  This is just cosmetic,
        # since we only use the object space mesh.
        cmds.xform(inverted_shape_transform,
                   ws=True,
                   ro=cmds.xform(base, ws=True, ro=True, q=True))
        cmds.xform(inverted_shape_transform,
                   ws=True,
                   t=cmds.xform(base, ws=True, t=True, q=True))
        cmds.xform(inverted_shape_transform,
                   ws=True,
                   s=cmds.xform(base, ws=True, s=True, q=True))

        blend_shape_index = _add_blend_shape(foc_blend_shape, base,
                                             inverted_shape)

        # Enable our new blend shape.  It needs to be enabled for update_inversion to work,
        # and the user is probably about to edit the blend shape he just created.
        cmds.setAttr('%s.weight[%i]' % (foc_blend_shape, blend_shape_index), 1)

        # Create the deformer.
        deformer = cmds.deformer(inverted_shape, type='zInvertedBlendShape')[0]

        # Hack: If we don't have at least one element in the array, compute() won't be called on it.
        cmds.setAttr('%s.invertedTweak[0]' % deformer, 0, 0, 0)

        cmds.select(inverted_shape_transform)
        OpenMaya.MGlobal.displayInfo('Result: %s' % inverted_shape)
        return inverted_shape

    finally:
        cmds.undoInfo(closeChunk=True)
def invert_existing(inverted=None):
    """
    Create an inversion for an existing inverted blend shape.  Select the inverted
    blend shape, optionally followed by the final output shape.  If no output shape
    is selected, we'll guess the output shape to use.

    This can be used if you've deleted the blend shape deformer, or if you've
    recreated the blend shape mesh from a delta blend shape.
    """
    _load_plugin()

    cmds.undoInfo(openChunk=True)
    try:
        if not inverted:
            sel = cmds.ls(sl=True, l=True)
            if not sel or not len(sel):
                OpenMaya.MGlobal.displayError('Select an inverted mesh')
                return

            inverted = sel[0]

        inverted_shape = _find_visible_shape(inverted)
        if not inverted_shape:
            OpenMaya.MGlobal.displayError('Couldn\'t find a shape under %s' %
                                          inverted)

        print 'Shape: %s' % inverted_shape

        # There shouldn't already be zInvertedBlendShape deformer on the mesh.
        for history_node in cmds.listHistory(inverted_shape):
            if 'zInvertedBlendShape' in cmds.nodeType(history_node,
                                                      inherited=True):
                OpenMaya.MGlobal.displayError(
                    '%s already has a zInvertedBlendShape deformer (%s).' %
                    (inverted, history_node))
                return

        # Find the blendShape that the mesh feeds into.
        for history_node in cmds.listHistory(inverted_shape,
                                             f=True,
                                             gl=True,
                                             pdo=True):
            if 'blendShape' not in cmds.nodeType(history_node, inherited=True):
                continue

            foc_blend_shape = history_node
            break
        else:
            OpenMaya.MGlobal.displayError('%s has no blendShape.' %
                                          inverted_shape)
            return

        # Retrieve the current vertices for the inverted mesh.  Do this before we clobber it below.
        inverted_points = _get_mesh_points(inverted_shape)

        # Retrieve the input vertices coming into the blend shape.  These will become the input
        # into the deformer, and the deformer will apply the changes to get back to the inverted
        # mesh.
        blend_shape_input_geometry = _get_plug_from_node(
            '%s.input[0].inputGeometry' % foc_blend_shape)
        blend_shape_input_points = _get_points(
            blend_shape_input_geometry.asMObject())
        if inverted_points.length() != blend_shape_input_points.length():
            raise RuntimeError(
                'Expected %s and %s to have the same number of points' %
                (inverted_points, blend_shape_input_points))

        # Replace the input geometry (the input to the deformer) with the original geometry
        # coming into the blend shape.  The inverted shape will be applied by the deformer.
        inverted_points_iterator = _get_geometry_iterator(inverted_shape)
        inverted_points_iterator.setAllPositions(blend_shape_input_points,
                                                 OpenMaya.MSpace.kObject)

        # Create the deformer.
        deformer = cmds.deformer(inverted_shape, type='zInvertedBlendShape')[0]

        # Hack: If we don't have at least one element in the array, compute() won't be called on it.
        cmds.setAttr('%s.invertedTweak[0]' % deformer, 0, 0, 0)

        # Create .invertedTweak from the inverted mesh and the original mesh.
        deformer_node = _get_mobject(deformer)
        dep_node = OpenMaya.MFnDependencyNode(deformer_node)
        inverted_tweak_attr = dep_node.attribute('invertedTweak')
        data_block = dep_node.userNode()._forceCache()

        output_tweak = data_block.outputArrayValue(inverted_tweak_attr)
        builder = output_tweak.builder()

        for idx, i in enumerate(xrange(inverted_points.length())):
            delta = inverted_points[i] - blend_shape_input_points[i]

            # Always create index 0, but skip other vertices with no change.
            if idx != 0 and abs(delta[0]) < 0.001 and abs(
                    delta[1]) < 0.001 and abs(delta[2]) < 0.001:
                continue

            element = builder.addElement(idx)
            element.set3Float(delta.x, delta.y, delta.z)

            # This is simpler, but slow.
            # cmds.setAttr('%s.invertedTweak[%i]' % (deformer, idx), *delta)

        output_tweak.set(builder)
        output_tweak.setAllClean()

        OpenMaya.MGlobal.displayInfo('Result: %s' % deformer)
        return deformer

    finally:
        cmds.undoInfo(closeChunk=True)
Example #53
0
def next_frame():
    updateVars()
    cmds.undoInfo(swf=False)
    frame = cmds.currentTime(q=True) + increment
    cmds.currentTime(min_time if bounds and frame > max_time else frame)
    cmds.undoInfo(swf=True)
Example #54
0
def previous_frame():
    updateVars()
    cmds.undoInfo(swf=False)
    frame = cmds.currentTime(q=True) - increment
    cmds.currentTime(max_time if bounds and frame < min_time else frame)
    cmds.undoInfo(swf=True)
Example #55
0
from Qt.QtGui import *
from Qt import __binding__
import maya.cmds as mc


def undo(func):
    def _undo(*args, **kwargs):
        try:
            mc.undoInfo(ock=1)
            result = func(*args, **kwargs)
        except Exception, e:
            raise e
        else:
            return result
        finally:
            mc.undoInfo(cck=1)

    return _undo


def get_maya_win(module="PySide"):
    """
    get a QMainWindow Object of maya main window
    :param module (optional): string "PySide"(default) or "PyQt4"
    :return main_window: QWidget or QMainWindow object
    """
    import maya.OpenMayaUI as mui
    prt = mui.MQtUtil.mainWindow()
    if module == "PyQt":
        import sip
        from Qt.QtCore import *
Example #56
0
    def set_color(reset=False):
        '''' 
        Uses the provided settings to manage colors (Main function of this script) 
        
                Parameter:
                    reset (bool): Type of operation. Reset active will restore default colors.
        
        '''
        errors = ''
        try:
            function_name = 'GT Color Manager - Set Color'
            cmds.undoInfo(openChunk=True, chunkName=function_name)
            valid_selection = True
            objects_to_color = []
            colored_total = 0

            # Grab Necessary Values
            mode = cmds.optionMenu(mode_option, q=True, value=True)
            target = cmds.optionMenu(target_option, q=True, value=True)
            color = gt_color_manager_settings.get('current_color')
            set_outliner = cmds.checkBox(outliner_chk, q=True, value=True)
            set_viewport = cmds.checkBox(viewport_chk, q=True, value=True)

            # Functions
            def set_color_drawing_override(obj_to_set):
                ''' 
                Uses drawing override settings to set the color of an object 

                        Parameters:
                            obj_to_set (str): Name (path) of the object to affect.
                
                '''
                using_wireframe = cmds.getAttr(obj_to_set + '.useObjectColor')
                if using_wireframe != 0:
                    cmds.color(obj_to_set)
                cmds.setAttr(obj_to_set + '.overrideEnabled', 1)
                cmds.setAttr(obj_to_set + '.overrideRGBColors', 1)
                cmds.setAttr(obj_to_set + '.overrideColorR', color[0])
                cmds.setAttr(obj_to_set + '.overrideColorG', color[1])
                cmds.setAttr(obj_to_set + '.overrideColorB', color[2])
                return 1

            def set_color_wireframe_tool(obj_to_set):
                ''' 
                Uses wireframe color to set the color of an object 
                
                        Parameters:
                            obj_to_set (str): Name (path) of the object to affect.
                
                '''
                using_override = cmds.getAttr(obj_to_set + '.overrideEnabled')
                if using_override:
                    cmds.setAttr(obj_to_set + '.overrideEnabled', 0)
                    cmds.setAttr(obj_to_set + '.overrideColorR', 0)
                    cmds.setAttr(obj_to_set + '.overrideColorG', 0)
                    cmds.setAttr(obj_to_set + '.overrideColorB', 0)
                cmds.color(obj_to_set, rgb=(color[0], color[1], color[2]))
                return 1

            def set_color_outliner(obj_to_set):
                ''' 
                Sets the outliner color for the selected object 
                
                        Parameters:
                            obj_to_set (str): Name (path) of the object to affect.
                
                '''
                extrated_r = math.pow(color[0], 0.454)
                extrated_g = math.pow(color[1], 0.454)
                extrated_b = math.pow(color[2], 0.454)

                cmds.setAttr(obj_to_set + '.useOutlinerColor', 1)
                cmds.setAttr(obj_to_set + '.outlinerColorR', extrated_r)
                cmds.setAttr(obj_to_set + '.outlinerColorG', extrated_g)
                cmds.setAttr(obj_to_set + '.outlinerColorB', extrated_b)
                return 1

            def set_color_reset(obj_to_set,
                                reset_overrides=False,
                                reset_wireframe=False,
                                reset_outliner=False):
                ''' Resets the color of the selected objects
                
                        Parameters:
                            obj_to_set (str): Name (path) of the object to affect.
                            reset_overrides (bool) : Reseting Overrides
                            reset_wireframe (bool) : Reseting Wireframe
                            reset_outliner (bool) : Reseting Outliner
                
                '''
                if reset_overrides:
                    using_override = cmds.getAttr(obj_to_set +
                                                  '.overrideEnabled')
                    if using_override:
                        cmds.setAttr(obj_to_set + '.overrideEnabled', 0)
                        cmds.setAttr(obj_to_set + '.overrideColorR', 0)
                        cmds.setAttr(obj_to_set + '.overrideColorG', 0)
                        cmds.setAttr(obj_to_set + '.overrideColorB', 0)

                if reset_wireframe:
                    using_wireframe = cmds.getAttr(obj_to_set +
                                                   '.useObjectColor')
                    if using_wireframe != 0:
                        cmds.color(obj_to_set)

                if reset_outliner:
                    try:
                        cmds.setAttr(obj_to_set + '.useOutlinerColor', 0)
                    except:
                        pass
                return 1

            selection = cmds.ls(selection=True)

            if len(selection) < 1:
                valid_selection = False
                cmds.warning('You need to select at least one object.')

            if valid_selection:
                # Determine what to color
                if target == 'Transform':
                    objects_to_color = selection
                else:
                    for sel in selection:
                        shapes = cmds.listRelatives(
                            sel, shapes=True, fullPath=True) or []
                        for shape in shapes:
                            objects_to_color.append(shape)

                # Determine total of objects to be colored
                if len(objects_to_color) < 1:
                    valid_selection = False
                    cmds.warning(
                        'No shapes were found. Make sure you\'re using the correct "Target" option.'
                    )

            # Set Color
            if valid_selection and reset == False:
                for obj in objects_to_color:
                    if set_viewport:
                        try:
                            if mode == 'Drawing Override':
                                colored_total += set_color_drawing_override(
                                    obj)
                            else:
                                colored_total += set_color_wireframe_tool(obj)
                        except Exception as e:
                            errors += str(e) + '\n'
                    if set_outliner:
                        try:
                            if set_viewport:
                                set_color_outliner(obj)
                            else:
                                colored_total += set_color_outliner(obj)
                        except Exception as e:
                            errors += str(e) + '\n'

            if valid_selection and reset == True:
                for obj in objects_to_color:
                    if set_viewport:
                        try:
                            colored_total += set_color_reset(
                                obj,
                                reset_overrides=True,
                                reset_wireframe=True)
                        except Exception as e:
                            errors += str(e) + '\n'
                    if set_outliner:
                        try:
                            if set_viewport:
                                set_color_reset(obj, reset_outliner=True)
                            else:
                                colored_total += set_color_reset(
                                    obj, reset_outliner=True)
                        except Exception as e:
                            errors += str(e) + '\n'

            # Create message
            message = '<' + str(
                random.random()
            ) + '><span style=\"color:#FF0000;text-decoration:underline;\">' + str(
                colored_total) + ' </span>'
            is_plural = 'objects were'
            if colored_total == 1:
                is_plural = 'object was'
            if reset:
                message += is_plural + '  reset to the default color.'
            else:
                message += is_plural + '  colored.'

            cmds.inViewMessage(amg=message, pos='botLeft', fade=True, alpha=.9)

        except Exception as e:
            errors += str(e) + '\n'
        finally:
            cmds.undoInfo(closeChunk=True, chunkName=function_name)
        if errors != '':
            cmds.warning(
                'An error occured. Open the script editor for more information.'
            )
            print('######## Errors: ########')
            print(errors)
Example #57
0
 def _undo(*args, **kwargs):
     try:
         mc.undoInfo(ock=1)
         result = func(*args, **kwargs)
     except Exception, e:
         raise e
    def Action_Apply(self):
        self.window.Button_Apply.setEnabled(False)
        self.window.Button_Revert.setEnabled(True)

        maya_cmds.undoInfo(openChunk=True)
        try:
            self.groupLow = maya_cmds.listRelatives(
                self.window.Text_GroupLow.toPlainText().strip().split('\n'),
                path=True,
                children=True,
                type='transform')
            self.groupHig = maya_cmds.listRelatives(
                self.window.Text_GroupHig.toPlainText().strip().split('\n'),
                path=True,
                children=True,
                type='transform')
            if len(self.groupLow) != len(self.groupHig):
                raise TypeError(
                    'Children Of Transforms Does Not Match between Low Groups and High Groups'
                )

            self.groupLowChi = maya_cmds.listRelatives(self.groupLow,
                                                       path=True,
                                                       allDescendents=True,
                                                       type='transform')
            self.pivotLowChi = []
            for i in xrange(len(self.groupLowChi)):
                self.pivotLowChi.append(
                    maya_cmds.xform(self.groupLowChi[i],
                                    q=True,
                                    worldSpace=True,
                                    rotatePivot=True))

            self.groupHigChi = maya_cmds.listRelatives(self.groupHig,
                                                       path=True,
                                                       allDescendents=True,
                                                       type='transform')
            self.pivotHigChi = []
            for i in xrange(len(self.groupHigChi)):
                self.pivotHigChi.append(
                    maya_cmds.xform(self.groupHigChi[i],
                                    q=True,
                                    worldSpace=True,
                                    rotatePivot=True))

            xMin = self.window.Float_XMin.value()
            xMax = self.window.Float_XMax.value()
            yMin = self.window.Float_YMin.value()
            yMax = self.window.Float_YMax.value()
            zMin = self.window.Float_ZMin.value()
            zMax = self.window.Float_ZMax.value()

            self.pivotLow = []
            self.pivotHig = []
            for i in xrange(len(self.groupLow)):
                self.pivotLow.append(
                    maya_cmds.xform(self.groupLow[i],
                                    q=True,
                                    worldSpace=True,
                                    rotatePivot=True))
                self.pivotHig.append(
                    maya_cmds.xform(self.groupHig[i],
                                    q=True,
                                    worldSpace=True,
                                    rotatePivot=True))
                maya_cmds.move(uniform(xMin, xMax),
                               uniform(yMin, yMax),
                               uniform(zMin, zMax),
                               self.groupLow[i],
                               self.groupHig[i],
                               relative=True)
        except Exception as e:
            print >> stderr, str(e)
        maya_cmds.undoInfo(closeChunk=True)
Example #59
0
 def __exit__(self, *_):
     if self.undo_state:
         if not self.flush:
             cmds.undoInfo(stateWithoutFlush=True)
         else:
             cmds.undoInfo(state=True)
Example #60
0
def undo_start():
    return cmds.undoInfo(openChunk=True)