def addCount(): global progressCurrent global progressLength progressCurrent += 1 row, left, right = uiInst._progressBarList[ progressIndex ] percent = progressCurrent/float(progressLength) leftWidth = percent*200 rightWidth = 200-leftWidth if leftWidth < 1: leftWidth = 1 rightWidth = 199 if rightWidth < 1: leftWidth = 199 rightWidth = 1 cmds.rowColumnLayout( row, e=1, cw=[ (1,leftWidth),(2,rightWidth)] ) if progressCurrent == 1: cmds.text( left, e=1, bgc=[1,1,0] ) elif progressCurrent == progressLength: cmds.text( right, e=1, bgc=[1,1,0] ) cmds.refresh()
def start(): global uiInst global progressIndex progressIndex = 0 uiInst = UI() uiInst.show() cmds.refresh()
def renameSelection(): """rename all the selected objects going 1 by 1""" sel = mn.ls( sl = True ) for s in sel: s() #select mc.refresh() result = mc.promptDialog( title = 'Rename Object ' + s.name, message = 'Enter Name:', button = ['OK', 'Cancel','Stop'], defaultButton = 'OK', tx = s.name, cancelButton = 'Cancel', dismissString = 'Cancel') if result == 'OK': text = mc.promptDialog(query=True, text=True) if '#' in text: similars = mn.ls( text.replace( '#', '*' ) ) if not similars: similars = [] s.name = text.replace( '#', str( len( similars ) ) ) else: s.name = text if result == 'Stop': return
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)
def doEditPivotDriver(self, *args): newValue = mc.floatSliderButtonGrp(self.floatSlider, query=True, value=True) try: mc.deleteUI(self.pivotDriverWindow) except: pass currentValue = mc.getAttr(self.pivotDriver) if newValue == currentValue: return oldRP = mc.getAttr(self.node+'.rotatePivot')[0] mc.setAttr(self.pivotDriver, newValue) newRP = mc.getAttr(self.node+'.rotatePivot')[0] mc.setAttr(self.pivotDriver, currentValue) parentPosition = mc.group(em=True) offsetPosition = mc.group(em=True) offsetPosition = mc.parent(offsetPosition, parentPosition)[0] mc.setAttr(offsetPosition+'.translate', newRP[0]-oldRP[0], newRP[1]-oldRP[1], newRP[2]-oldRP[2]) mc.delete(mc.parentConstraint(self.node, parentPosition)) utl.matchBake(source=[self.node], destination=[parentPosition], bakeOnOnes=True, maintainOffset=False, preserveTangentWeight=False) mc.cutKey(self.pivotDriver) mc.setAttr(self.pivotDriver, newValue) mc.refresh() utl.matchBake(source=[offsetPosition], destination=[self.node], bakeOnOnes=True, maintainOffset=False, preserveTangentWeight=False, rotate=False) mc.delete(parentPosition)
def GenTerrain(DATA_SIZE, SEED, h, j): createTerrainData(DATA_SIZE, SEED, h, j) name = 'Terrain' totalPoints=(DATA_SIZE)*(DATA_SIZE) if (cmds.objExists(name) == True): cmds.delete(name) cmds.polyPlane( n=name, sx=(DATA_SIZE-1), sy=(DATA_SIZE-1), h=20, w=20) count = 0 cmds.progressWindow(title='Setting Points', progress=count, max = totalPoints, status='Setting: 0/'+str(totalPoints)) for i in xrange(DATA_SIZE): if True: cmds.refresh() cmds.delete(name, ch = True) for j in xrange(DATA_SIZE): offset = dataArray[i][j] cmds.polyMoveVertex( name+'.vtx['+str(count)+']', ws = True, ty = offset, cch=True) cmds.progressWindow(edit=True, progress=count, status='Setting: '+str(count)) count+=1 cmds.progressWindow(endProgress=1) #cmds.polySmooth(n=name, cch = True) cmds.delete(name, ch = True)
def updateOutMesh(srcMesh=None, outMesh=None, force=True): """ Update given outMesh, then remove connection :param srcMesh: Source mesh :type srcMesh: str :param outMesh: Out mesh :type outMesh: str :param force: Force connection :type force: True """ # --- Check Object List ---# if srcMesh is None and outMesh is None: selObjects = mc.ls(sl=True) print selObjects if not selObjects: print "!!! Error: Select srcMesh, then outMesh !!!" else: srcMesh = selObjects[0] outMesh = selObjects[1] # --- Update Mesh ---# connectOutMesh(srcMesh, outMesh, force=force) mc.refresh() mc.disconnectAttr("%s.worldMesh" % srcMesh, "%s.inMesh" % outMesh) print "// Update %s.worldMesh ---> %s.inMesh" % (srcMesh, outMesh)
def populateVersionList(self): self.cmdLoadingHintToggle(on=False) cmds.textField(self.control.heading7, e=True, tx=' -- LOADING -- ') cmds.refresh() cmds.textScrollList(self.control.scroll2, edit=True, ra=True) sel = cmds.textScrollList(self.control.scroll1, q=True, si=True)[0] version = [] for f in self.clipFiles: if f.split('.')[0] == sel: vr = f.split('.')[1] if vr != 'clip': # print f, '===========', vr, sel version.append(vr) else: version.append('') else: # print f + ' not in ' + sel + '_______________' pass if version: # print version version = sorted(version) if len(version) == 1 and version[0] == '': # dont draw versions if only 1 exists and matches string '' pass else: # for i in reversed(version): cmds.textScrollList(self.control.scroll2, edit=True, append=i) cmds.textScrollList(self.control.scroll2, edit=True, sii=[1]) self.populatePreview()
def drag(self, *args): '''Called continuously when holding the mouse button down, updates self.x and self.y with the mouse position, and runs the corresponding method for whichever button is being pressed.''' self.dragPoint = mc.draggerContext(self.draggerContext, query=True, dragPoint=True) self.x = ((self.dragPoint[0] - self.anchorPoint[0]) * self.multiplier) + self.defaultValue self.y = ((self.dragPoint[1] - self.anchorPoint[1]) * self.multiplier) + self.defaultValue if self.minValue is not None and self.x < self.minValue: self.x = self.minValue if self.maxValue is not None and self.x > self.maxValue: self.x = self.maxValue #dragString if self.modifier == 'control': if self.button == 1: self.dragControlLeft() elif self.button == 2: self.dragControlMiddle() elif self.modifier == 'shift': if self.button == 1: self.dragShiftLeft() elif self.button == 2: self.dragShiftMiddle() else: if self.button == 1: self.dragLeft() elif self.button == 2: self.dragMiddle() mc.refresh()
def rigUpdate(self): #disable refresh until the rig update is complete cmds.refresh(su=True) rigNodeFound = False try: rigGuiNode = self.scene.sceneNodes["Rig"] rigNodeFound = True except KeyError: rigNodeFound = False if rigNodeFound: #kill all script jobs created by controllers to avoid #an update loop which the rig is updated for jobNum in self.scriptJobNumbers: if jobNum != globals.currentScriptJobNum: cmds.scriptJob(k=jobNum) self.scriptJobNumbers = [] rigGuiNode.updateVersion += 0.1 rootElem = self.recursiveGetXML(rigGuiNode) self.indent(rootElem) tree = xml.ElementTree(rootElem) file = open(self.updateXmlPath, 'w') tree.write(file) file.close() self.recursiveZeroOutControllers(rigGuiNode) if rigGuiNode.metaNodeName is not None and rigGuiNode.metaNodeName != "": self.rootNodeName = mel.eval("updateMetaDataManager -n \""+rigGuiNode.metaNodeName+"\";") else: self.rootNodeName = mel.eval("loadRig -p \""+self.updateXmlPath+"\";") cmds.select(cl=True) self.recursiveUpdateMetaNodes(rigGuiNode,self.rootNodeName) self.recursiveSetupScriptJobs(rigGuiNode) cmds.refresh(su=False)
def importAovs(self): """import aovs into scene""" LayersInfo = pickle.load( open( self.aovsPath.path, "rb") ) mc.refresh( su = 1 ) for ao in LayersInfo.keys(): aov.create( ao, LayersInfo[ao]['name'], LayersInfo[ao]['type'], LayersInfo[ao]['enabled'] ) mc.refresh( su = 0 )
def bake(constraint, start=None, end=None, sampleBy=1, simulation=True): """ Bake specified constraint @param constraint: Constraint to bake animation for. @type constraint: str @param start: Start frame of bake animation range @type start: float or None @param end: End frame of bake animation range @type end: float or None @param sampleBy: Sample every Nth frame @type sampleBy: int @param simulation: Simulation option for bakeResults @type simulation: bool """ # ========== # - Checks - # ========== # Check Constraint if not glTools.utils.constraint.isConstraint(constraint): raise Exception('Object "' + constraint + '" is not a valid constraint node!') # Check Start/End Frames if start == None: start = cmds.playbackOptions(q=True, min=True) if end == None: end = cmds.playbackOptions(q=True, max=True) # ==================================== # - Get Slave Transform and Channels - # ==================================== # Get Slave Transform slave = glTools.utils.constraint.slave(constraint) # Get Slave Channels attrList = cmds.listConnections(constraint, s=False, d=True, p=True) or [] slaveAttrs = [i.split('.')[-1] for i in attrList if i.startswith(slave + '.')] or [] if not slaveAttrs: raise Exception('No slave channels to bake!') # =================== # - Bake Constraint - # =================== cmds.refresh(suspend=True) cmds.bakeResults(slave, at=slaveAttrs, time=(start, end), disableImplicitControl=True, simulation=simulation, sampleBy=sampleBy) cmds.refresh(suspend=False) # ================= # - Return Result - # ================= return [slave + '.' + i for i in slaveAttrs]
def onDrag(self): baseDraggerCtx.onDrag(self) cntrl, alt, shift = self.mods if self.btn ==1: if not cntrl and not alt and not shift: self.paintOnDrag() elif cntrl and not shift and not alt: self.paintOnPolyOnDrag() #curve(self.crv, append=1, p=[pnt]) elif self.btn==2: if not cntrl and not shift and not alt: self.moveOpOnDrag() elif cntrl and not shift and not alt: self.moveOpOnDrag() elif cntrl and shift and not alt: self.moveOpOnDrag() elif not cntrl and shift and not alt: self.moveOpOnDrag() elif cntrl and shift and alt: self.moveEndsOpDrag() mc.refresh(cv=True)
def fix(self): import os if os.name == 'posix': viewport.hide() cmds.refresh() viewport.show() pass
def suspend_refresh(): """A context mananger that stops the graph from running or the view updating. Can be nested, where only the outermost context manager will resume refresing. :: >>> with suspend_refresh(): ... do_something_with_high_drawing_cost() .. seealso:: There are caveats with disabling the refresh cycle. Be sure to read about :cmds:`refresh`. """ global _suspend_depth try: if not _suspend_depth: cmds.refresh(suspend=True) _suspend_depth += 1 yield finally: _suspend_depth -= 1 if not _suspend_depth: cmds.refresh(suspend=False)
def duplicateObj( self, targetObj, skinNode, addName='_add' ): if cmds.nodeType( targetObj ) != 'transform': targetObj = cmds.listRelatives( targetObj, p=1 ) if targetObj: targetObj = targetObj [0] else: return None targetShape = cmds.listRelatives( targetObj, s=1 )[0] targetAttr = targetShape+'.outMesh' outputAttr = cmds.listConnections( skinNode+'.input[0].inputGeometry', s=1, d=0, p=1, c=1 )[1] secondMesh = cmds.createNode( 'mesh' ) thirdMesh = cmds.createNode( 'mesh' ) secondObj = cmds.listRelatives( secondMesh, p=1 )[0] thirdObj = cmds.listRelatives( thirdMesh, p=1 )[0] cmds.connectAttr( targetAttr, secondMesh+'.inMesh' ) cmds.connectAttr( outputAttr, thirdMesh +'.inMesh' ) cmds.refresh() cmds.disconnectAttr( targetAttr, secondMesh+'.inMesh' ) cmds.disconnectAttr( outputAttr, thirdMesh +'.inMesh' ) secondObj = cmds.rename( secondObj, targetObj+addName ) thirdObj = cmds.rename( thirdObj , targetObj+addName+'_inv' ) return secondObj, thirdObj
def savePositions(objects): positions = [] sel = cmd.ls(sl=1) # Stop undo, so this doesn't get annoying for artist disableUndo() # Create tempgroup and parent constrain it to object to get position # Maya likes this approach better tempGroup = cmd.group(n='jh_savePos_tmpGrp', em=1) # If passed a string instead of a list if isinstance(objects, basestring): objects = [objects] # Get position with parent constraints for obj in objects: tempConst = cmd.parentConstraint(obj, tempGroup) cmd.refresh() positions.append(cmd.xform(tempGroup, q=1, ws=1, matrix=1)) cmd.delete(tempConst) # Delete temp group cmd.delete(tempGroup) # Restore selection and undo cmd.select(sel) enableUndo() return positions
def putObjects(self, atCurrentFrame=False): # print self.sel # print self.putObjectList autoKey = cmds.autoKeyframe(q=True, state=True) cmds.autoKeyframe(state=False) # current #NO LONGER USED, REMOVE ONCE MERGED WITH WORK COPY OF KET # CLASS if atCurrentFrame: current = cmds.currentTime(q=True) if self.start > current: self.offset = current - self.start else: self.offset = ((self.start - current) * -1.0) + 0.0 # print self.offset # put num = len(self.objects) i = 1 uiEnable() for obj in self.objects: if cmds.objExists(obj.name): message(str(i) + ' of ' + str(num) + ' -- ' + obj.name, maya=True) cmds.refresh(f=1) obj.offset = self.offset obj.putAttribute() else: cmds.warning( 'Object ' + obj.name + ' does not exist, skipping.') i = i + 1 uiEnable() cmds.autoKeyframe(state=autoKey)
def duplicateOnlyCurve( curves ): import sgBFunction_dag curves = sgBFunction_dag.getChildrenCurveExists( curves ) newCurves = [] for curve in curves: curveP = sgBFunction_dag.getParent( curve ) if curveP: newCurveParent = sgBFunction_dag.makeCloneObject( curveP ) else: newCurveParent = None newCurveShape = cmds.createNode( 'nurbsCurve' ) curveShape = sgBFunction_dag.getShape( curve ) cmds.connectAttr( curveShape+'.local', newCurveShape+'.create' ) newCurve = sgBFunction_dag.getTransform( newCurveShape ) newCurve = cmds.rename( newCurve, 'du_' + curve.split( '|' )[-1] ) if newCurveParent: newCurve = cmds.parent( newCurve, newCurveParent )[0] newCurves.append( newCurve ) cmds.refresh() for i in range( len( newCurves ) ): curveShape = sgBFunction_dag.getShape( curves[i] ) newCurveShape = sgBFunction_dag.getShape( newCurves[i] ) if cmds.isConnected( curveShape+'.local', newCurveShape+'.create' ): cmds.disconnectAttr( curveShape+'.local', newCurveShape+'.create' ) return newCurves
def refresh(): cmds.undoInfo(stateWithoutFlush=False) # cmds.refresh(force=True) # print "refresh" cmds.refresh(suspend=False) cmds.currentTime(cmds.currentTime(query=True), edit=True) cmds.undoInfo(stateWithoutFlush=True)
def cameraOrientMoveManip(): selection = cmds.ls(selection=True) if len(selection) == 0: return shotCamera = animMod.getShotCamera() if not shotCamera or not cmds.objExists(shotCamera): cmds.warning("No shot camera detected.") return cmds.refresh(suspend=True) sourceObjs = selection[0:-1] targetObj = selection[-1] locator = animMod.createNull("tempCameraOrient_locator") cameraNode = utilMod.getCamFromSelection([shotCamera])[0] G.aToolsBar.align.align([locator], targetObj, translate=True, rotate=False) with G.aToolsBar.createAToolsNode: constraint = cmds.aimConstraint(cameraNode, locator, name="tempCameraOrient_constraint", aimVector=[0, 0, 1], worldUpType="objectrotation", worldUpObject=cameraNode, maintainOffset=False)[0] cmds.select(selection) cmds.select(locator, add=True) orientMoveManip() if cmds.objExists(locator): cmds.delete(locator) if cmds.objExists(constraint): cmds.delete(constraint) cmds.refresh(suspend=False)
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 drag(self, *args): self.dragPoint = mc.draggerContext(self.draggerContext, query=True, dragPoint=True) #if this doesn't work, try getmodifier self.modifier = mc.draggerContext(self.draggerContext, query=True, modifier=True) self.x = ((self.dragPoint[0] - self.anchorPoint[0]) * self.multiplier) + self.defaultValue self.y = ((self.dragPoint[1] - self.anchorPoint[1]) * self.multiplier) + self.defaultValue if self.minValue is not None and self.x < self.minValue: self.x = self.minValue if self.maxValue is not None and self.x > self.maxValue: self.x = self.maxValue #dragString if self.modifier == 'control': if self.button == 1: self.dragControlLeft(*args) elif self.button == 2: self.dragControlMiddle(*args) elif self.modifier == 'shift': if self.button == 1: self.dragShiftLeft(*args) elif self.button == 2: self.dragShiftMiddle(*args) else: if self.button == 1: self.dragLeft() elif self.button == 2: self.dragMiddle() mc.refresh()
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()
def createInCurveFromCurve( numCurve ): import sgBFunction_surface import sgBFunction_dag def optimizeConnection( targetObject ): targetShape = sgBFunction_dag.getShape( targetObject ) src = cmds.listConnections( targetShape + '.create', p=1 )[0] dst = cmds.listConnections( targetShape, d=1, s=0, p=1,type="volumeCurvesOnSurface" )[0] cmds.connectAttr( src, dst, f=1 ) cmds.delete( targetObject ) curves = sgBFunction_dag.getChildrenShapeExists( cmds.ls( sl=1 ) ) surface = sgBFunction_surface.getLoftSurfaceFromSelCurves( curves, True ) curves = sgBFunction_surface.createInCurve( surface, numCurve ) surfShape = cmds.listRelatives( surface, s=1, f=1 )[0] reverseNode = cmds.listConnections( surfShape, s=1, type='reverseSurface' )[0] cmds.setAttr( reverseNode+'.direction', 0 ) cmds.refresh() cmds.setAttr( reverseNode+'.direction', 3 ) cmds.refresh() cmds.select( curves ) #cmds.setAttr( surfShape+'.io', 1 ) optimizeConnection( surfShape ) return curves
def reset_pivot(*args): sel = mc.ls(sl=True) if not sel: om.MGlobal.displayWarning('Nothing selected.') return if len(sel) > 1: om.MGlobal.displayWarning('Only works on one node at a time.') return node = sel[0] driver = None driver_value = None driver_default = None if is_pivot_connected(node): driver = pivot_driver_attr(node) if driver: dNode,dAttr = driver.split('.',1) driver_value = mc.getAttr(driver) driver_default = mc.attributeQuery(dAttr, node=dNode, listDefault=True)[0] if driver_default == driver_value: return else: om.MGlobal.displayWarning('Pivot attribute is connected, unable to edit.') return if not driver: pivotPosition = mc.getAttr(node+'.rotatePivot')[0] if pivotPosition == (0.0,0.0,0.0): return tempPosition = mc.group(em=True) tempPivot = mc.group(em=True) tempPivot = mc.parent(tempPivot, node)[0] if driver: mc.setAttr(driver, driver_default) newRP = mc.getAttr(node+'.rotatePivot')[0] mc.setAttr(driver, driver_value) mc.setAttr(tempPivot+'.translate', *newRP) else: mc.setAttr(tempPivot+'.translate', 0,0,0) mc.setAttr(tempPivot+'.rotate', 0,0,0) utl.matchBake(source=[tempPivot], destination=[tempPosition], bakeOnOnes=True, maintainOffset=False, preserveTangentWeight=False, rotate=False) if driver: mc.setAttr(driver, driver_default) else: mc.setAttr(node+'.rotatePivot', 0,0,0) mc.refresh() utl.matchBake(source=[tempPosition], destination=[node], bakeOnOnes=True, maintainOffset=False, preserveTangentWeight=False, rotate=False) mc.delete(tempPosition,tempPivot) mc.select(node)
def do(currentFileNodes): sys.stdout.write("Checking if a similar shader has already been published. This might take a minute...\n") cmds.refresh() textureLabels = ["DIFF", "SPEC", "NRML"] currentAssetDirectory = getAssetLibrary() # Get selected category folder. directory = getCategoryFolder() # Get the list of files on disk. mayaShaderFiles = [x for x in os.listdir(directory) if x.endswith(".ma")] currentFiles = dict() for fileNode in currentFileNodes: found = False fileTextureName = cmds.getAttr("%s.fileTextureName" % fileNode) for label in textureLabels: if label in fileTextureName: currentFiles[label] = fileTextureName found = True if not found: cnxList = cmds.listConnections(fileNode, source=False, destination=True, plugs=True) or [] for cnx in cnxList: attr = cnx.partition(".")[2] if attr in ddConstants.textureTypes.keys(): currentFiles[ddConstants.textureTypes[attr]] = fileTextureName for mayaShaderFile in mayaShaderFiles: # Find the files attached to file nodes. publishedFiles = dict() f = open(os.path.join(directory, mayaShaderFile), "r") for line in f: if not ((currentAssetDirectory in line) or (currentAssetDirectory.replace(os.sep, "/") in line)): continue filename = os.path.join(currentAssetDirectory, "%s" % line.replace("/", os.sep).rpartition("%s\\" % currentAssetDirectory)[2].rpartition('"')[0]) for label in textureLabels: if label in filename: publishedFiles[label] = filename f.close() if not len(currentFiles) == len(publishedFiles): # MayaShaderFile does not contain the same number of file nodes. continue allSameFiles = True for label in textureLabels: if (label in currentFiles.keys()) and (label in publishedFiles.keys()): sameFile = compareTifFiles(currentPath=currentFiles[label], publishedPath=publishedFiles[label]) if sameFile == "Fail": return "Fail" if not sameFile: allSameFiles = False break if allSameFiles: return mayaShaderFile.rpartition(os.sep)[2].replace(".ma", "") return None
def snap(master, slave): # constrains oCons = mc.orientConstraint(master, slave, w=1) pCons = mc.pointConstraint(master, slave, w=1) mc.refresh() mc.delete(oCons) mc.delete(pCons)
def importScene( evt=0 ): rootPath = cmds.textField( Window_global.txf_rootPath, q=1, tx=1 ) abcPath = rootPath + '/' + cmds.textField( Window_global.txf_abcPath, q=1, tx=1 ) sceneInfoPath = rootPath + '/' + cmds.textField( Window_global.txf_sceneInfoPath, q=1, tx=1 ) cmds.AbcImport( abcPath, mode='import' ) def getBBCenter( targetTransform ): bbmin = cmds.getAttr( targetTransform + '.boundingBoxMin' )[0] bbmax = cmds.getAttr( targetTransform + '.boundingBoxMax' )[0] bbcenter = OpenMaya.MPoint( (bbmin[0] + bbmax[0])/2.0, (bbmin[1] + bbmax[1])/2.0, (bbmin[2] + bbmax[2])/2.0 ) pmtx = cmds.getAttr( targetTransform + '.parentMatrix' ) mtx = OpenMaya.MMatrix() OpenMaya.MScriptUtil.createMatrixFromList( pmtx, mtx ) bbcenter *= mtx return [bbcenter.x, bbcenter.y,bbcenter.z] def addNamespaceToChildren( namespace, rootNode ): import pymel.core children = pymel.core.listRelatives( rootNode, c=1, ad=1, type='transform' ) if not children: children = [] for child in children: child.rename( namespace + ':' + child.name().split( '|' )[-1] ) f = open( sceneInfoPath, 'r' ) data = json.load( f ) f.close() cmds.currentUnit( time=data['timeUnit'] ) cmds.playbackOptions( min=data['minFrame'], max=data['maxFrame'] ) cmds.currentTime( data['exportFrame'] ) cmds.refresh() namespaceRoots = data['namespaceRoots'] rootCenters = data['rootCenters'] for i in range( len( namespaceRoots ) ): namespaceRoot = namespaceRoots[i] localName = namespaceRoot.split( '|' )[-1] namespace = ':'.join( localName.split( ':' )[:-1] ) try:cmds.namespace( add=namespace ) except:pass target = '|'.join( namespaceRoot.split( '|' )[:-1] ) + '|' + localName.replace( namespace+':', '' ) + '*' targets = cmds.ls( target, type='transform' ) if len( targets ) == 1: target = targets[0] addNamespaceToChildren( namespace, target ) cmds.rename( target, namespaceRoot.split( '|' )[-1] ) else: for target in targets: targetCenter = OpenMaya.MPoint( *getBBCenter( target ) ) rootCenter = OpenMaya.MPoint( *rootCenters[i] ) if targetCenter.distanceTo( rootCenter ) < 0.0001: addNamespaceToChildren( namespace, target ) cmds.rename( target, namespaceRoot.split( '|' )[-1] )
def wrap_hair_plates(character): """ Wraps the hairplate objects to the character object :param character: a Character object, singular :return: """ flg = logging.getLogger("lettuce.xgenSetup.wrap_hair_plates") flg.info("Wrapping hair plates to {}".format(character.get_charName())) char_col = character.get_current_collection() flg.debug("Current Collection: {}".format(char_col)) char_mesh = search_namespaces_for_mesh(character) char_hair_plates = char_col.get_hairPlates() flg.info("Character mesh object: {}".format(char_mesh)) flg.info("Character hair plate objects: {}".format(char_hair_plates)) deformer_input_list = [] history_list = mc.listHistory(char_mesh) flg.debug("Character mesh history nodes: {}".format(history_list)) filtered_list = node_type_filter(history_list, "joint", "animCurveUU", ) flg.debug("Character mesh history nodes, filtered: ".format(filtered_list)) for n in filtered_list: print n node_attr = mc.listAttr(n, leaf=True) if "envelope" in node_attr: deformer_input_list.append(n) flg.debug("Objects containing envelope attributes: {}".format(deformer_input_list)) for o in deformer_input_list: flg.info("Setting {0} input {1} envelope to 0".format(char_mesh, o)) mc.setAttr("{}.envelope".format(o), 0) flg.info("Viewport refresh") mc.refresh() for hp in char_hair_plates: tools.create_wrap(char_mesh, hp, exclusiveBind=True, falloffMode=1, shapeDeformed=True ) flg.info("Binding {0} to {1}".format(hp, char_mesh)) flg.info("Viewport refresh") mc.refresh() for o in deformer_input_list: flg.info("Setting {0} input {1} envelope to 1".format(char_mesh, o)) mc.setAttr("{}.envelope".format(o), 1)
def _independent_panel(width, height, off_screen=False): """Create capture-window context without decorations Arguments: width (int): Width of panel height (int): Height of panel Example: >>> with _independent_panel(800, 600): ... cmds.capture() """ # center panel on screen screen_width, screen_height = _get_screen_size() topLeft = [ int((screen_height - height) / 2.0), int((screen_width - width) / 2.0) ] window = cmds.window(width=width, height=height, topLeftCorner=topLeft, menuBarVisible=False, titleBar=False, visible=not off_screen) cmds.paneLayout() panel = cmds.modelPanel(menuBarVisible=False, label='CapturePanel') # Hide icons under panel menus bar_layout = cmds.modelPanel(panel, q=True, barLayout=True) cmds.frameLayout(bar_layout, edit=True, collapse=True) if not off_screen: cmds.showWindow(window) # Set the modelEditor of the modelPanel as the active view so it takes # the playback focus. Does seem redundant with the `refresh` added in. editor = cmds.modelPanel(panel, query=True, modelEditor=True) cmds.modelEditor(editor, edit=True, activeView=True) # Force a draw refresh of Maya so it keeps focus on the new panel # This focus is required to force preview playback in the independent panel cmds.refresh(force=True) try: yield panel finally: # Delete the panel to fix memory leak (about 5 mb per capture) cmds.deleteUI(panel, panel=True) cmds.deleteUI(window)
def onDrag(self): intersection, hitFacePtr = self.getIntersection() if intersection: fId = om.MScriptUtil.getInt(hitFacePtr) if not len(self.fidDeq): self.fidDeq.append(fId) else: index = self.appendDeq(inputDeq=self.fidDeq, index=len(self.fidDeq) - 1, inputVal=fId) if not index: return # cmds.select('%s.f[%d]' % (self.selectedMesh, fId)) self.fnPolys.setIndex(fId, self.indexUtilPtr) edgeList = om.MIntArray() self.fnPolys.getEdges(edgeList) if not len(self.fDeq): self.fDeq.append(edgeList) print 'initial fdeq', self.fDeq return else: #print self.fDeq returnCode = self.appendDeq(inputDeq=self.fDeq, index=len(self.fDeq) - 1, inputVal=edgeList, edge=True) if not returnCode: print 'Did not append edge deq' return # TODO: Do not allow to go back and forth over the same edge prev = list(self.fDeq[0]) curr = list(self.fDeq[1]) matchingEdge = list(set(curr).intersection(prev)) if matchingEdge: if self.sewEdge: matchingEdge = matchingEdge[0] # TODO: This is where we have our crash. Must figure out whats going on... cmds.select('%s.e[%d]' % (self.selectedTransform, matchingEdge), replace=True) #cmds.refresh() # Deleting the context to test single sew function print 'SEWING BRA' #cmds.polyMapSewMove() cmds.refresh()
def readSetDrivenKeyDataFromFile(filePath, lock=False): ''' Reads and reconstructs setDrivenKeyfraomes from json file exported from writeSetDrivenKeyDataToFile() sdkFile = 'Z:/users/tcoleman/code/temp_sdk_data.json' readSetDrivenKeyDataFromFile(sdkFile) ''' fh = open(filePath, 'r') sdkDataDict = json.load(fh) fh.close() # iterate through dict keys for sdkCurve, sdkDict in sdkDataDict.iteritems(): driver = sdkDict['driver'] driven = sdkDict['driven'] driverKeys = sdkDict['driverKeys'] drivenKeys = sdkDict['drivenKeys'] itt = sdkDict['itt'] ott = sdkDict['ott'] pri = sdkDict['pri'] poi = sdkDict['poi'] if mc.objExists(driver) and mc.objExists(driven): i = 0 for driverKey, drivenKey in zip(driverKeys, drivenKeys): # Create setDrivenKeyframes mc.setDrivenKeyframe(driven, cd=driver, dv=driverKey, value=drivenKey) LOG.debug('SetDrivenKeyframe: Driver=%s.%s, Driven=%s.%s' % (driver, driven, driverKey, drivenKey)) # Set keyframe tangents mc.selectKey(sdkCurve, add=True, k=True, f=(driverKey, driverKey)) mc.keyTangent(itt=itt[i], ott=ott[i]) i = i + 1 # Set pre/post infinity mc.selectKey(sdkCurve, add=True, k=True, f=(driverKeys[0], driverKeys[0])) mc.setInfinity(pri=pri) mc.selectKey(clear=True) mc.selectKey(sdkCurve, add=True, k=True, f=(driverKeys[-1], driverKeys[-1])) mc.setInfinity(poi=poi) # Lock setDrivenKeyframes if specified if lock: mc.setAttr('%s.keyTimeValue' % sdkCurve, lock=True) mc.refresh() LOG.info('SetDrivenKeyframe Data read from %s' % filePath)
def snapCtrlToWorld(self, minValue, maxValue): with undoCheck(): myCtrl = cmds.ls(sl=True) if (minValue < maxValue): if self.dirChk.isChecked() == False: currentT = minValue cmds.currentTime(currentT) myLoc = self.snapToObj(myCtrl) nextFrame = currentT + 1 cmds.refresh(suspend=1) while (nextFrame <= maxValue): cmds.currentTime(nextFrame) self.snapSelection(myLoc, myCtrl) currentT = cmds.currentTime(q=True) nextFrame = currentT + 1 cmds.refresh(suspend=0) cmds.delete(myLoc) cmds.select(myCtrl) else: currentT = maxValue cmds.currentTime(currentT) myLoc = self.snapToObj(myCtrl) nextFrame = currentT - 1 cmds.refresh(suspend=1) while (nextFrame >= minValue): cmds.currentTime(nextFrame) self.snapSelection(myLoc, myCtrl) currentT = cmds.currentTime(q=True) nextFrame = currentT - 1 cmds.refresh(suspend=0) cmds.delete(myLoc) cmds.select(myCtrl) else: cmds.confirmDialog(t="Notice", m="Range Error")
def _item_selection_changed(self): for s in self._last_selection: cmds.tcMotionPathCmd(deselectBufferPathAtIndex=s) self._last_selection = [] items = self._buffer_paths.selectedItems() for item in items: index = self._buffer_paths.indexFromItem(item) cmds.tcMotionPathCmd(selectBufferPathAtIndex=index.row()) self._last_selection.append(index.row()) self._refresh_button_states(bool(items)) cmds.refresh()
def generateView(self): view = mui.M3dView.active3dView() cam = OpenMaya.MDagPath() view.getCamera(cam) camName = cam.partialPathName() cam = mc.listRelatives(camName, parent=True)[0] self.hide() time.sleep(2) currentViewPosition = mc.xform(cam, query=True, worldSpace=True, translation=True) currentViewOrientation = mc.xform(cam, query=True, worldSpace=True, rotation=True) for view in self.viewList: mc.xform(cam, worldSpace=True, translation=view['viewPosition']) mc.xform(cam, worldSpace=True, rotation=view['viewOrientation']) previousValues = [] for View in view['data']: obj = View['obj'] attr = View['attr'] val = mc.getAttr(obj + '.' + attr) valDict = {'obj': obj, 'attr': attr, 'value': val} previousValues.append(valDict) for View in view['data']: obj = View['obj'] attr = View['attr'] val = View['value'] mc.setAttr(obj + '.' + attr, float(val)) mc.refresh() time.sleep(1) self.takeScreenshot(view['name']) time.sleep(1) for val in previousValues: obj = val['obj'] attr = val['attr'] val = val['value'] mc.setAttr(obj + '.' + attr, float(val)) print 'value restored' self.show() mc.xform(cam, worldSpace=True, translation=currentViewPosition) mc.xform(cam, worldSpace=True, rotation=currentViewOrientation)
def updateSelected(self): current = self.rigList.currentItem() if current is not None: rigName = current.text() name = "MRN_" + rigName #disable refresh until the rig update is complete cmds.refresh(su=True) mel.eval(self.updateString) cmds.select(cl=True) #enable refresh after update cmds.refresh(su=False) self.refreshListWidget() self.populateVersionBox(rigName) self.updateSelectedBtn.setStyleSheet("")
def openMaya(self, fileName): print " \n openMaya : ", fileName # fileName = fileName.replace('\\', '/') # print " \n openMaya FIX : " , fileName # print " \n\n\n " # file -open "fred.ma"; import maya.cmds as cmx cmx.file(modified=0) cmx.file(fileName, open=True) if self.forceLocal: cmx.refresh() time.sleep(1)
def alert(color='green', guiElement='VLC_record|top', message=''): colors = { 'red': [1.0, 0.0, 0.0], 'orange': [0.8, 0.4, 0.0], 'green': [0.0, 1.0, 0.0], 'blue': [0.0, 0.0, 1.0], 'grey': [0.2, 0.2, 0.2] } #getColor = cmd.columnLayout(guiElement, q=True, bgc=True) newColor = colors.setdefault(color, [0.2, 0.2, 0.2]) cmd.columnLayout(guiElement, e=True, bgc=(newColor[0], newColor[1], newColor[2])) cmd.refresh()
def getSelectedRegionNode(self): if self.renderlayer_listWidget.selectedItems(): renderlayer = self.renderlayer_listWidget.selectedItems()[0].text() cmds.editRenderLayerGlobals(currentRenderLayer=renderlayer) cmds.refresh() regionNode = cmds.listConnections(renderlayer + '.message', type='network')[0] return regionNode else: return None
def ruleDict(i, condition, index, input_namespace): ''' this function specifies all of the different ways that points on the spiral can be connected, a simple connection, no connection, and two ways of 'forking' the curve. i : the numerical name condition : the connection method to be used index : the number of midpoints, ensures the forking options select the correct point to fork to input namespace : for unique naming of the curves ''' if condition == 1: ###straight connection between two spiral points, a 'perfect' connection. cmds.select('spiralPoint' + str(i)) cmds.select('spiralPoint' + str(i + 1), add=True) generateCurve(1, 'spiral', str(input_namespace)) cmds.refresh() cmds.select(clear=True) if condition == 2: ###no connection between two points. cmds.refresh() cmds.select(clear=True) if condition == 3: ###downward-end-fork, a connection that looks like this: --< #creates an intermediate point at a random distance between the points to 'fork' from midPoint = createIntermediatePoint('spiralPoint' + str(i), 'spiralPoint' + str(i + 1), 'connectionPoint', random.uniform(0, 0.5), i) #connect the first point to the midpoint cmds.select('spiralPoint' + str(i)) cmds.select(midPoint, add=True) generateCurve(1, 'spiral', str(input_namespace)) #connect the midpoint to the second point cmds.select(midPoint) cmds.select('spiralPoint' + str(i + 1), add=True) generateCurve(1, 'spiral', str(input_namespace)) #connect the midpoint to the spiral point perpendicular TOWARDS the middle of the web to the second point. cmds.select(midPoint) cmds.select('spiralPoint' + str(i + 1 - index), add=True) generateCurve(1, 'connecting', str(input_namespace)) cmds.refresh() cmds.select(clear=True) cmds.delete(midPoint) #deletes the midpoint. if condition == 4: ###downward-start-fork, a connection that looks like this: >-- #creates an intermediate point at a random distance between the points to 'fork' from midPoint = createIntermediatePoint('spiralPoint' + str(i), 'spiralPoint' + str(i + 1), 'connectionPoint', random.uniform(0.5, 1), i) #connect the first point to the midpoint cmds.select('spiralPoint' + str(i)) cmds.select(midPoint, add=True) generateCurve(1, 'spiral', str(input_namespace)) #connect the midpoint to the second point cmds.select(midPoint) cmds.select('spiralPoint' + str(i + 1), add=True) generateCurve(1, 'spiral', str(input_namespace)) #connect the midpoint to the spiral point perpendicular TOWARDS the middle of the web to the first point. cmds.select(midPoint) cmds.select('spiralPoint' + str(i - index), add=True) generateCurve(1, 'connecting', str(input_namespace)) cmds.refresh() cmds.select(clear=True) cmds.delete(midPoint) #deletes the midpoint.
def testObjectPosition(self): """ Tests that an object created interactively is positioned correctly on the live surface. """ # Create a new custom viewport. window = cmds.window(widthHeight=(500, 400)) cmds.paneLayout() panel = cmds.modelPanel() cmds.modelPanel(panel, edit=True, camera='persp') cmds.modelEditor(cmds.modelPanel(panel, q=True, modelEditor=True), edit=True, displayAppearance='smoothShaded', rnm='vp2Renderer') cmds.showWindow(window) # Force all views to re-draw. This causes us to block until the # geometry we're making live has actually been evaluated and is present # in the viewport. Otherwise execution of the test may continue and the # create tool may be invoked before there's any geometry there, in # which case the tool won't create anything. cmds.refresh() # Get the viewport widget. view = OMUI.M3dView() OMUI.M3dView.getM3dViewFromModelPanel(panel, view) viewWidget = wrapInstance(long(view.widget()), QWidget) # Make our proxy shape live. cmds.makeLive('Block_1') # Enter interactive creation context. cmds.setToolTo('CreatePolyTorusCtx') # Click in the center of the viewport widget. QTest.mouseClick(viewWidget, QtCore.Qt.LeftButton, QtCore.Qt.NoModifier, viewWidget.rect().center()) # Find the torus (it should be called pTorus1). self.assertTrue(cmds.ls('pTorus1')) # Check the torus's transform. # The Block_1 is originally 1 unit deep and centered at the origin, so # its original top plane is aligned at z=0.5. # It is scaled 5x, which makes the top plane aligned at z=2.5. # Then it is translated along z by 4.0, so its top plane is finally # aligned at z=6.5. translate = cmds.xform('pTorus1', q=True, t=True) self.assertAlmostEqual(translate[2], 6.5, places=3)
def BakeBinderData(rootNode=None, debugView=False, ignoreInFilter=[]): ''' From a given Root Node search all children for the 'BoundCtr' attr marker. If none were found then search for the BindNode attr and use the message links to walk to the matching Controller. Those found are then baked out and the marker attribute is deleted ''' BoundCtrls = GetBoundControls(rootNode) #Found no Ctrls, try and walk the message from the BndNodes if not BoundCtrls: BndNodes = GetBindNodes() for node in BndNodes: cons = cmds.listConnections('%s.BindNode' % node) if cons: BoundCtrls.append(cmds.ls(cons[0], l=True)[0]) else: log.info('Nothing connected to %s.BindNode' % node) if BoundCtrls: try: if not debugView: cmds.refresh(su=True) cmds.bakeResults(BoundCtrls, simulation=True, sampleBy=1, time=(cmds.playbackOptions(q=True, min=True), cmds.playbackOptions(q=True, max=True)), disableImplicitControl=True, preserveOutsideKeys=True, sparseAnimCurveBake=True, removeBakedAttributeFromLayer=False, controlPoints=False, shape=False) for node in BoundCtrls: #Remove the BindMarker from the baked node try: cmds.deleteAttr('%s.BoundCtr' % node) except StandardError, error: log.info(error) if ignoreInFilter: BoundCtrls = [ node for node in BoundCtrls if node.split('|')[-1].split(':')[-1] not in ignoreInFilter ] cmds.filterCurve(BoundCtrls) cmds.delete(BoundCtrls, sc=True) # static channels except StandardError, error: raise StandardError(error)
def click(s): try: # Grab mouse co-ords on screen viewX, viewY, viewZ = cmds.draggerContext(s.myTool, q=True, ap=True) position = om.MPoint() direction = om.MVector() # Convert 2D screen positions into 3D world positions omui.M3dView().active3dView().viewToWorld(int(viewX), int(viewY), position, direction) sel = om.MSelectionList() sel.add(s.sel) dagPath = sel.getDagPath(0) fnMesh = om.MFnMesh(dagPath) intersection = fnMesh.closestIntersection( om.MFloatPoint(position), om.MFloatVector(direction), om.MSpace.kWorld, 99999, False) # Did our ray intersect with the object? if intersection: hitPoint, hitRayParam, hitFace, hitTriangle, hitBary1, hitBary2 = intersection if hitTriangle != -1: # Grab Skin Cluster skin = mel.eval("findRelatedSkinCluster %s" % s.sel) if skin: # Get Face points cmds.select("%s.f[%s]" % (s.sel, hitFace)) face = cmds.polyInfo(fv=True) # Get vertexes verts = [ "%s.vtx[%s]" % (s.sel, v) for v in findall(r"\s(\d+)\s", face[0]) ] # Get Joints cmds.select(verts, r=True) joints = cmds.skinPercent(skin, q=True, t=None) # Get weights weights = sorted( [(j, cmds.skinPercent(skin, t=j, q=True)) for j in joints], key=lambda x: x[1], reverse=True) cmds.select(weights[0][0], r=True) else: print "No skin found" # Return to previous tool cmds.setToolTo(s.tool) cmds.refresh() except RuntimeError: print "There was an issue selecting the object."
def test_toggleShapeVis(self): cmds.setAttr("{}.visibility".format(self.cubeShape), False) self.assertFalse(cmds.getAttr("{}.visibility".format(self.cubeShape))) cmds.refresh() self.assertNotIn( self.cubeRprim, self.getVisibleIndex()) cmds.setAttr("{}.visibility".format(self.cubeShape), True) self.assertTrue(cmds.getAttr("{}.visibility".format(self.cubeShape))) cmds.refresh() self.assertIn( self.cubeRprim, self.getVisibleIndex())
def testSimpleSceneDrawsAndReloads(self): # a memory issue would sometimes cause maya to crash when opening a new # scene. for _ in xrange(20): cmds.file(new=True, force=True) for i in xrange(10): usdFilePath = os.path.abspath('plane%d.usda' % (i%2)) assembly = cmds.assembly(name='plane', type='pxrUsdReferenceAssembly') cmds.setAttr("%s.filePath" % assembly, usdFilePath, type='string') cmds.assembly(assembly, edit=True, active='Collapsed') cmds.refresh() cmds.file(new=True, force=True)
def Snap_To_Ground_Main(): # Axis , Ground_Geometry_list , Object_list , Axis_Method , PointCheckThreshold , Threshold_On , Align_to_Surface Axis_RadioButton_List = ['POSX', 'POSY', 'POSZ', 'NEGX', 'NEGY', 'NEGZ'] Axis_index = 0 for indRB in Axis_RadioButton_List: if cmds.radioButton(indRB, q=1, sl=1): # print ('Axis ' + indRB) break else: Axis_index += 1 Object_list = cmds.ls(selection=True) # Axis_Method 0 : bbox 1 : ObjectAxis 2: Lowest/extreme Position # Axis_Method = cmds.radioButton( 'Object_Axis' , q = 1 , sl = 1) # Axis_Method = cmds.optionMenu( "Transfrom_Method" , q = 1 , v = 1) Axis_Method = cmds.optionMenu("Transfrom_Method", q=1, sl=1) Check_Other_Point = cmds.checkBox('Check_Other_Point', query=1, value=1) threshold = cmds.floatField('PointCheckThreshold', query=1, value=1) Align_to_Surface = cmds.checkBox('Align_to_Surface', query=1, value=1) Refresh_Viewport_each_Move = cmds.checkBox('Refresh_Viewport_each_Move', query=1, value=1) # print (Ground_Geometry_list) # print (" Axis_Method " + str(Axis_Method)) # print ( 'Check_Other_Point' + str ( Check_Other_Point ) ) # print (threshold) # print ("-----------------------------Snap_To_Ground_Main") cmds.select(cl=1) for indObject in Object_list: for indGround in Ground_Geometry_list: # print ( ('indProjection ')+str((indObject , indGround )) ) Action_Success = indProjection(indObject, indGround, Axis_index, Axis_Method, threshold, Check_Other_Point, Align_to_Surface) # print ( "Action_Success " + str(Action_Success) ) if Action_Success: print("Success : Move < " + indObject + " > to < " + indGround) if Refresh_Viewport_each_Move: cmds.refresh() break else: print("Operation Failed Try next Ground") cmds.select(Object_list)
def train(s, *_): """ Begin/continue training on new data """ train_path = s._train_path_train.get_text() source_path = s._train_path_source.get_text() expect_path = s._train_path_expect.get_text() if not os.path.isdir(train_path) or not os.path.isfile( source_path) or not os.path.isfile(expect_path): raise RuntimeError("One or more paths are invalid.") print( "Training. Please wait. This can take a while. Press Esc to abort." ) data_stream = itertools.chain( maya_utils.join_streams(source_path, expect_path)) brain = learn.Brain(train_path) progctrl = mel.eval("$tmp = $gMainProgressBar") cmds.progressBar(progctrl, e=True, bp=True, st="Thinking...", max=100, ii=True) best_acc = [0] def update(prog, acc): best_acc[0] = max(acc, best_acc[0]) prog *= 100 if not prog % 1: if cmds.progressBar(progctrl, q=True, ic=True): raise StopIteration print("Training %s%%. Accuracy %s%%" % (int(prog), best_acc[0])) cmds.progressBar(progctrl, e=True, progress=prog) if best_acc[0] == 1.0: raise StopIteration cmds.refresh(suspend=True) try: d1, d2 = itertools.tee(data_stream, 2) brain.train(d1, epochs=500, callback=update) acc = brain.evaluate(d2)[1] print("Training complete. Estimated accuracy:", acc) except StopIteration: print("Training cancelled!") finally: cmds.refresh(suspend=False) cmds.progressBar(progctrl, e=True, ep=True)
def showMayaWindow(menuPath): if not os.path.exists(menuPath): return None menuPath = menuPath.replace('\\', '/') menuLabel = Menu_Global.getMenuLabel(menuPath) menuName = Menu_Global.getMenuName(menuPath) if cmds.menu(menuName, q=1, ex=1): cmds.deleteUI(menuName) cmds.menu(menuName, l=menuLabel, parent='MayaWindow', to=1) cmds.refresh() SGFileBaseMenu.renameTargets(menuPath) SGFileBaseMenu.assignCommand(menuName, menuPath)
def makeClouds(): for i in range(0, 3): cmds.polySphere(r=20, sx=6, sy=6, n='cloud' + str(i)) cmds.scale(1, 0.2, 0.5, 'cloud' + str(i)) x = random.uniform(10, 100) y = random.uniform(60, 80) z = random.uniform(10, 100) cmds.move(i * x, y, z, 'cloud' + str(i)) for j in range(0, 3): cmds.duplicate('cloud' + str(i), n='cloud' + str(i) + str(j)) x = random.uniform(10, 100) y = random.uniform(60, 80) z = random.uniform(10, 100) cmds.move(i * x, y, j * z, 'cloud' + str(i) + str(j)) cmds.refresh(f=True)
def makeDisplayMod( baseModel ): import sgBFunction_dag targetShape = cmds.createNode( 'mesh' ) baseShape = sgBFunction_dag.getShape( baseModel ) cmds.connectAttr( baseShape+'.outMesh', targetShape+'.inMesh' ) cmds.refresh() cmds.disconnectAttr( baseShape+'.outMesh', targetShape+'.inMesh' ) target = cmds.listRelatives( targetShape, p=1, f=1 )[0] cmds.select( target ) cmds.sets( e=1, forceElement='initialShadingGroup' ) cmds.xform( target, ws=1, matrix= cmds.getAttr( baseModel+'.wm' ) ) return cmds.rename( target, 'display_' + baseModel.split( '|' )[-1] )
def goToKey(which, type="key"): cmds.undoInfo(stateWithoutFlush=False) cmds.refresh(suspend=True) frame = cmds.findKeyframe( timeSlider=True, which=which) if type == "key" else cmds.currentTime( query=True) + (1 if which == "next" else -1) cmds.currentTime(frame) G.aToolsBar.timeoutInterval.removeFromQueue("goToKey") G.aToolsBar.timeoutInterval.setTimeout(animMod.refresh, sec=.05, id="goToKey") cmds.undoInfo(stateWithoutFlush=True)
def startUpFunctions(self): #wait cursor state n = 0 while True: if not cmds.waitCursor(query=True, state=True) or n > 100: break cmds.waitCursor(state=False) n += 1 #refresh state cmds.refresh(suspend=False) #undo state if not cmds.undoInfo(query=True, stateWithoutFlush=True): cmds.undoInfo(stateWithoutFlush=True) #progress bar state utilMod.setProgressBar(status=None, progress=None, endProgress=True)
def _showCurveChanged(self, *args): self.graphWidget.setVisible(False) cmds.refresh() def cmd(obj): value = cmds.checkBox(obj.showCurve, query=True, value=True) and cmds.getAttr( obj.attr("use_directional_weight")) self.graphWidget.setVisible(value) cmds.refresh() self.graphWidget.update() maya.utils.executeDeferred(cmd, self)
def alert(color='green', guiElement='playBetter|mainColumn', message=''): colors = { 'red': [1.0, 0.0, 0.0], 'orange': [0.8, 0.4, 0.0], 'green': [0.0, 1.0, 0.0], 'blue': [0.0, 0.0, 1.0], 'grey': [0.2, 0.2, 0.2] } #getColor = cmd.columnLayout(guiElement, q=True, bgc=True) newColor = colors.setdefault(color, [0.2, 0.2, 0.2]) cmd.columnLayout(guiElement, e=True, bgc=(newColor[0], newColor[1], newColor[2])) cmd.text(guiElement + '|message', e=True, l=(message)) cmd.refresh()
def __init__(self): """ initializing ui """ super(UI, self).__init__() #-check license self.licenseKey = License.License.readLicense() self.validator = '' if not self.licenseKey: self.licenseValidation() if not self.licenseKey: return exec(cn.connect('initialize', self.licenseKey)) # adding widgets widgets = [ 'Justin', 'Warrior', 'vertical', 'ShiftKey', 'MicroControl', 'vertical', 'EasyInBetween', 'vertical', 'MagicLocator', 'separator', 'FakeConIt', 'separator', 'ExFootStep', 'separator', 'SnapIt', 'separator', 'LockDown', 'vertical', 'Decalcomanie', 'separator', 'ResetIt', 'separator', 'DrawArc', 'vertical', 'SelectionGrp', 'separator', 'AnimCopySession', 'vertical', 'ViewportRefresh', 'separator', 'bhPlayblast', 'vertical', 'Misc' ] #-mainLayout------------------------------------------------------------------ self.mainLayout = cmds.rowLayout(numberOfColumns=len(widgets) + 2, adjustableColumn=1, columnAttach=([2, 'right', 0])) #- logo --------------------------------------------------------------------- cmds.image(image=os.path.join(imagesPath, 'beaverLogo.png'), w=48, h=41) self.sepStyle = 'in' self.height = 20 self.marginSize = 0 self.sepWidth = 30 # for freeze tool check cmds.refresh(su=False) # ading widgets for widget in widgets: self.addWidget(widget)
def delUVTransferAttributesNode(obj): SH = cmds.listRelatives(obj, s=True, f=True, ni=True, type='mesh') allSH = cmds.listRelatives(obj, s=True, f=True, type='mesh') orgSH = [] deformers = [] inputType = ('skinCluster', 'blendShape', 'ffd', 'wrap', 'cluster', 'nonLinear', 'sculpt', 'jiggle', 'wire', 'groupParts', 'groupId') deformerType = ('skinCluster', 'blendShape', 'ffd', 'wrap', 'cluster', 'nonLinear', 'sculpt', 'jiggle', 'wire') hist = cmds.listHistory(obj) for histIt in hist: ListNode = cmds.nodeType(histIt) if (deformerType.count(ListNode) and deformers.append(histIt)): pass for itSH in allSH: if (cmds.getAttr((itSH + '.intermediateObject')) and (cmds.listConnections(itSH, d=False) == None)): orgSH.append(itSH) if (len(SH) == 1): imputNode = cmds.listConnections((SH[0] + '.inMesh'), d=False, sh=True) if (len(imputNode) and (inputType.count(cmds.nodeType(imputNode)) != True)): if len(orgSH): mesh = cmds.createNode('mesh') for orgIt in orgSH: cmds.connectAttr((SH[0] + '.outMesh'), (mesh + '.inMesh'), f=True) cmds.refresh() cmds.disconnectAttr((SH[0] + '.outMesh'), (mesh + '.inMesh')) cmds.polyTransfer(orgIt, v=False, vc=False, uv=True, ao=mesh) transfer = cmds.listConnections(orgIt, d=False) NewOrg = cmds.listConnections((transfer[0] + '.inputPolymesh'), d=False, sh=True) cmds.delete(NewOrg) if cmds.delete(cmds.listRelatives(mesh, p=True, f=True)): pass n = True while n: inputNode = cmds.listConnections((SH[0] + '.inMesh'), d=False, sh=True) if (len(inputNode) is None): n = False break breakWhile = [] selINode = cmds.nodeType(inputNode) breakWhile.append(str(selINode)) if (inputType.count(breakWhile) == True): n = False break cmds.delete(inputNode) n = False
def changeEditMeshMode(self): blinns = cmds.ls(type='blinn') editMeshShader = None for blinn in blinns: if cmds.attributeQuery('isEditMeshShader', node=blinn, ex=1): editMeshShader = blinn if not editMeshShader: blinn = cmds.shadingNode('blinn', asShader=1) editMeshShader = cmds.rename(blinn, 'EditMeshShader') SG = cmds.sets(renderable=True, noSurfaceShader=True, empty=1, n='EditMeshSG') cmds.connectAttr(editMeshShader + '.outColor', SG + '.surfaceShader') cmds.setAttr(editMeshShader + '.color', .2, 1, .6, type='double3') cmds.setAttr(editMeshShader + '.specularColor', .2, .2, .2, type='double3') for meshObj in self._meshList: meshShape = cmds.listRelatives(meshObj, s=1)[0] editShape = cmds.createNode('mesh') cmds.connectAttr(meshShape + '.outMesh', editShape + '.inMesh') cmds.refresh() cmds.disconnectAttr(meshShape + '.outMesh', editShape + '.inMesh') editMeshObj = cmds.listRelatives(editShape, p=1)[0] if not cmds.attributeQuery('editMeshTarget', node=meshObj, ex=1): cmds.addAttr(meshObj, ln='editMeshTarget', at='message') cons = cmds.listConnections(meshObj + '.editMeshTarget') if cons: cmds.delete(cons) cmds.connectAttr(editMeshObj + '.message', meshObj + '.editMeshTarget') cmds.sets(editMeshObj, e=1, forceElement=SG) cmds.setAttr(meshObj + '.v', 0)
def __init__(self, target, withSkin=False): self.namespace = self.getNamespace(target) self.allInit = self.namespace + 'All_Init' #self.getPanelCondition() #self.setPanelWireframe() cmds.refresh() self.mocSet() self.splineDriverMocSet() if withSkin: self.copySkinedMesh() #self.setPanelOriginal() cmds.select(self.allMoc)
def test(): import pymel.core as pm import maya.cmds as cmds for x in [ 'spine_C0_fk0_local_npo', 'spine_C0_fk1_local_npo', 'spine_C0_fk2_local_npo', 'spine_C0_fk3_local_npo' ]: n = pm.PyNode(x) xf = getTransform(n)[3] xf = map(lambda x: "{0:.2f}".format(x), xf) print(x, xf) print(x, map(lambda x: "{0:.2f}".format(x), n.getMatrix(worldSpace=False)[3])) cmds.refresh(suspend=True) cmds.refresh(suspend=False)