def test_validateBoneNames(): newFile(f=True) a = card.makeCard(jointCount=3, jointNames={'head': ['aa', 'bb', 'cc']}) x = card.makeCard(jointCount=3, jointNames={'head': ['xx', 'yy', 'zz']}) assert not main.RigTool.validateBoneNames([a, x]) data = a.rigData data['nameInfo']['head'] = ['aa', 'bb', 'cc', 'xx'] a.rigData = data assert not main.RigTool.validateBoneNames([a, x]) # No issues because the xx is extra, therefore not build data = a.rigData data['nameInfo']['head'] = ['aa', 'bb', 'xx'] a.rigData = data assert len(main.RigTool.validateBoneNames([a, x])) == 1 assert 'overlap' in main.RigTool.validateBoneNames([a, x])[0] data = a.rigData data['nameInfo']['head'] = ['aa', 'aa', 'xx'] a.rigData = data assert len(main.RigTool.validateBoneNames([a, x])) == 2 #assert 'overlap' in main.RigTool.validateBoneNames([a, x])[0] data = a.rigData data['nameInfo']['head'] = ['aa', 'bb'] a.rigData = data assert len(main.RigTool.validateBoneNames([a, x])) == 1 assert 'enough' in main.RigTool.validateBoneNames([a, x])[0]
def clean_environment(self): # Open a new file to clear out any AOVs created by the tests pm.newFile(force=True) # defaultArnoldDriver (among other objects) doesn't load until needed. # The following 2 lines will force them to load to avoid runtime errors. from mtoa.core import createOptions createOptions()
def prepare(): """ Prepares the scene for a rig. Returns: (pm.nodetypes.Transform): Rig transform that holds all skinned meshes referenced. """ # getRelativeArt checks if scene is saved skeleton_path = paths.getRelativeArt() # if scene is modified, ask user if they would like to save, not save, or cancel operation if not uiwindow.save(): pm.error('Scene not saved.') # perform a bone health check before referencing to emphasize any possible errors bone.health() # create new file, reference the skeleton into the new file, create rig group pm.newFile(force=True) rig_grp = pipernode.createRig() pm.createReference(skeleton_path, namespace=pcfg.skeleton_namespace) pm.createReference(skeleton_path, namespace=pcfg.bind_namespace) skinned_meshes = pipernode.get('piperSkinnedMesh') [ node.visibility.set(False) for node in skinned_meshes if node.name().startswith(pcfg.bind_namespace) ] pm.parent(skinned_meshes, rig_grp) lockMeshes() return rig_grp
def convertSmoothSkin( name, path='C:/Users/Darrick/Documents/Maya/projects/_UE4-Chars/scenes'): pm.newFile(force=True) pm.importFile(path + '/Mesh/Ref/Mesh_' + name + '.ma') pm.importFile(path + '/Rig/Ref/Skel_' + name + '.ma') print('Smoothing meshes. Please wait...') for mesh in pm.ls(type='mesh'): pm.polySmooth(mesh, ch=False) pm.select(None) print('Averaging seam vertex normals...') edge_dict = FIGURE_EDGES['g8f'] for name, edge in edge_dict.items(): mesh = pm.ls(name + ':Mesh')[0] pm.polySelect(mesh, edgeBorder=edge, add=True) pm.select(pm.polyListComponentConversion(pm.ls(sl=True), toVertex=True)) pm.polyAverageNormal() pm.select(None) print('Applying skins...') applySkins() print('Saving file to {}'.format('{0}/Rig/Ref/Skin_{1}.ma'.format( path, name))) print('Completed.')
def test_get_plane_normal(run_with_maya_pymel, setup_path): # Maya imports from maya import OpenMaya import pymel.core as pm # mGear imports from mgear.core.vector import get_plane_normal vector_a = OpenMaya.MVector(0, 0, 0) vector_b = OpenMaya.MVector(1, 0, 0) vector_c = OpenMaya.MVector(0, 0, 1) result = get_plane_normal(vector_a, vector_b, vector_c) assert type(result) == OpenMaya.MVector assert [result[0], result[1], result[2]] == [0, 1, 0] pm.newFile(force=True) vector_a = pm.createNode("transform") vector_b = pm.createNode("transform") vector_c = pm.createNode("transform") vector_b.translate.set(-1, 0, 0) vector_c.translate.set(0, 0, 1) result = get_plane_normal(vector_a, vector_b, vector_c) assert [result[0], result[1], result[2]] == [0, -1, 0] result = get_plane_normal(list(vector_a.getTranslation()), list(vector_b.getTranslation()), list(vector_c.getTranslation())) assert [result[0], result[1], result[2]] == [0, -1, 0]
def publishFile(self, *args): # get database info on item item = Item(task=self.task, code=self.code, itemType=self.type) item.proxyMode = self.proxyMode item.publishAs() version.takeSnapShot(item.getDataDict()) self.closeWin() logger.debug('publish ver %s, at %s' % (item.publishVer, item.getPublishPath())) resp = pm.confirmDialog( title='Warning', ma='center', message='PUBLISH: %s %s \n Reopen working task?' % (item.name, item.task), button=['Ok', 'No'], defaultButton='Ok', dismissString='No') if resp == 'Ok': version.open(type=item.type, task=item.task, code=item.code, force=True) else: pm.newFile(f=True, new=True)
def test_apply_dict(self): # New scene pm.newFile(f=True) # Create plane and ncloth self.plane = pm.polyPlane()[0] pm.select(self.plane, r=1) nClothCreate() self.ncloth = pm.PyNode('nCloth1') self.nucleus = pm.PyNode('nucleus1') d = {'bounce': 3.0, 'evaluationOrder': 1} ims.apply_dict(self.ncloth, d) self.assertEqual(self.ncloth.getShape().bounce.get(), 3.0) self.assertEqual(self.ncloth.getShape().evaluationOrder.get(), 1) d = {'planeNormal': (0.0, 0.0, 1.0)} ims.apply_dict(self.nucleus, d) self.assertEqual(self.nucleus.planeNormal.get(), (0.0, 0.0, 1.0))
def saved_file(tmpdir): pm.newFile(force=True) path = os.path.join(tmpdir.dirname, "maya_test_scene.ma") pm.saveAs(path) return path
def importMixamoFbx(self) : print 'importMixamoFbx' pm.newFile(f=1) if self.fbxFile: if os.path.isfile(self.fbxFile): #import the FBX file pm.mel.eval( 'FBXImport -f "' + (self.fbxFile) + '"') #check for a default mesh in T-Pose. If found, replace geometry self.replaceGeometry() #clean its namespace removeNamespace() hips = pm.ls("Hips",type='joint') #add root joint for scale rootJnt = pm.joint(n='Root') pm.parent(hips[0],rootJnt) #clean up textures self.cleanUpTextures() pm.currentUnit(t='ntsc') return 1 else: pm.error('Fbx file %s doesn\'t exist'%self.fbxFile) return 0 else: pm.error('No file was given') return 0
def test_apply_dict(self): # New scene pm.newFile(f=True) # Create plane and ncloth self.plane = pm.polyPlane()[0] pm.select(self.plane, r=1) nClothCreate() self.ncloth = pm.PyNode('nCloth1') self.nucleus = pm.PyNode('nucleus1') d = {'bounce': 3.0, 'evaluationOrder': 1} ims.apply_dict(self.ncloth, d) self.assertEqual(self.ncloth.getShape(). bounce.get(), 3.0) self.assertEqual(self.ncloth.getShape(). evaluationOrder.get(), 1) d = {'planeNormal': (0.0, 0.0, 1.0)} ims.apply_dict(self.nucleus, d) self.assertEqual(self.nucleus.planeNormal.get(), (0.0, 0.0, 1.0))
def test_get_scene_name(self): """Check that a untitled file is also named untitled""" import pymel.core as pm pm.newFile(force=True) manager = maya_manager.Maya_Manager() self.assertTrue('untitled' in manager.get_scene_name())
def setUp(self): """setup the test """ # create a new scene pm.newFile(force=True) # create a render camera self.camera = pm.nt.Camera()
def wrapper(*arg, **kwarg): if kwarg.get("newScene"): pc.newFile(f=True) else: pass return func(*arg, **kwarg)
def using_pymel(): import pymel.core as pm pm.newFile(force=1) for x in pm.ls(type='transform'): print(x.longName()) # object oriented design # make and break some connections # connection operator x.sx >> x.sy x.sx >> x.sz # disconnection operator x.sx // x.sy # smarter methods -- (automatically disconnects all inputs and outputs # when no arg is passed) x.sx.disconnect() # add and set a string array attribute with the history of this # transform's shape if not x.hasAttr('newAt'): x.addAttr('newAt', dataType='stringArray') x.newAt.set(x.getShape().history()) # get and set some attributes x.rotate.set([1, 1, 1]) trans = x.translate.get() # vector math trans *= x.scale.get() # ability to pass list/vector args x.translate.set(trans) # automatic handling of mel procedures pm.mel.myMelScript(x.type(), trans)
def importMixamoFbx(self): print 'importMixamoFbx' pm.newFile(f=1) if self.fbxFile: if os.path.isfile(self.fbxFile): # import the FBX file pm.mel.eval('FBXImport -f "' + (self.fbxFile) + '"') # clean its namespace removeNamespace() # self.logger.info('Imported file %s',self.fbxFile) hips = pm.ls("Hips", type='joint') # add root joint for scale rootJnt = pm.joint(n='Root') pm.parent(hips[0], rootJnt) # self.logger.info('Added root joint %s',rootJnt) # clean up textures self.cleanUpTextures() pm.currentUnit(t='ntsc') # add shadow plane return 1 else: pm.error('Fbx file %s doesn\'t exist' % self.fbxFile) return 0 else: pm.error('No file was given') return 0
def importMixamoFbx(self): print "importMixamoFbx" pm.newFile(f=1) if self.fbxFile: if os.path.isfile(self.fbxFile): # import the FBX file pm.mel.eval('FBXImport -f "' + (self.fbxFile) + '"') # clean its namespace removeNamespace() # self.logger.info('Imported file %s',self.fbxFile) hips = pm.ls("Hips", type="joint") # add root joint for scale rootJnt = pm.joint(n="Root") pm.parent(hips[0], rootJnt) # self.logger.info('Added root joint %s',rootJnt) # clean up textures self.cleanUpTextures() pm.currentUnit(t="ntsc") # add shadow plane return 1 else: pm.error("Fbx file %s doesn't exist" % self.fbxFile) return 0 else: pm.error("No file was given") return 0
def del_maya_lic_string(self): ''' Deletes the license info in the mayaAscii file. ''' logger.debug("Maya License String") # Get Scene Path filePath = pmc.sceneName() if filePath.splitext()[-1] == ".mb": logger.warning("Scene needs to be saved as .ma!") return False bakPath = filePath + ".bak" # Closing the scene to prevent crashes try: pmc.newFile() except RuntimeError as e: logger.error("Could not close scene!") logger.error(e) return False # Creating Backup file try: shutil.copy(filePath, bakPath) except IOError as e: logger.error("Could not create backup file!") logger.error(e) return False else: logger.info("Created Backup file") # transfering file content, line by line try: with open(bakPath, "r") as srcFile: with open(filePath, "w") as trgFile: for line in srcFile: if 'fileInfo "license" "student";' in line: logger.info("Student License String found") trgFile.write('fileInfo "license" "education";') else: trgFile.write(line) except IOError as e: logger.error( "An Error occurred while reading/writing the scene file") logger.error(e) return False # Reopening current scene try: pmc.openFile(filePath) except IOError as e: logger.error("Could not reopen current scene!") logger.error(e) return False except RuntimeError as e: logger.error(e) return False return True
def create_simple_ik(self): pm.newFile(f=1) mainSystem = core.TransSubSystem(side="C", part="Core") self.ikSystem = limb.LimbIk(side="C", part="Core") mainSystem.addMetaSubSystem(self.ikSystem, "IK") # ikSystem.ikControlToWorld = True self.ikSystem.testBuild() self.ikSystem.convertSystemToSubSystem(self.ikSystem.systemType)
def _run_tests(self): self._reset() with CaptureTestStream(self.text_edit): pytest.main(ARGS + TARGETS) self.rollback_importer.uninstall() pm.newFile(force=True)
def openFbx(self, path): if os.path.isfile(path): pm.newFile(f=1) pm.importFile(path.replace('\\', '/'), f=1) self.log('Open {0}'.format(path)) else: self.log('Invalid file name {0}'.format(path), logLevels.lWarning)
def tearDown(self): pCore.newFile(f=True) self.standardAttrs = { "MyString": "Test", "MyInt": 5, "MyFloat": 10.998547 } self.MetaNode = None
def shotAssemble(partField, sequenceField, shotField, listPhase, act): # New scene pm.newFile(f=True) # Extract SHOT NUMBER from UI codePart = partField.getText() codeSequence = sequenceField.getText() codeShot = shotField.getText() # Build SHOT DICTIONARY from FTrack data dataShotDic = dna.buildShotDic(codePart, codeSequence, 'SHOT_{0}'.format(codeShot)) listChars = dataShotDic['characters'] listProps = dataShotDic['props'] listEDA = dataShotDic['eda'] listEnv = dataShotDic['environments'] # START ASSEMBLING for action in act: if action == 'save': fileNameFull = '{0}{1}{2}/{3}/SHOT_{4}/{5}E{3}_S{4}_001.mb'.format( rootScene, listPhase[1], codePart, codeSequence, codeShot, listPhase[2]) dna.exportFileLV(fileNameFull) # Save scene dna.rangeSetup(codePart, codeSequence, codeShot) # PLAYBACK START/END RANGE SETUP dna.setRes() # Setup RESOLUTION elif action == 'add assets': dna.referenceItems( listChars, listPhase[0] ) # reference ( list of CHARS, RIG-GEO triger, asset type) print ' << CHARACTERS DONE! >>' dna.referenceItems(listProps, listPhase[0]) # REF PROPS print ' << PROPS DONE! >>' if listEnv: dna.referenceItems(listEnv, 'GEO') # REF ENVIRONMENT print ' << ENVIRONMENNT DONE! >>' if listEDA[0]: print listEDA dna.referenceItems(listEDA, listPhase[0]) # REF EDA print ' << EDA DONE! >>' elif action == 'create camera': cam = pm.camera() camName = 'E' + codeSequence + '_S' + codeShot cam[0].rename(camName) cam[1].rename(str(camName) + 'Shape') dna.camSetup(cam[1]) elif action == 'add ML': for i in listChars: matPath = dna.buildItemFullPath(i, 'MAT') dna.importData(matPath) # IMPORT ML for CHAR print '<< IMPORTED MATERIAL FOR: {} >>'.format(i) if listEnv: matPath = dna.buildItemFullPath(listEnv[0], 'MAT') dna.importData(matPath) # IMPORT ML for ENV print '<< IMPORTED MATERIAL FOR: {} >>'.format(listEnv[0]) # SAVE SCENE pm.saveFile() # CREATE REPORT print 'ASSEMBLING DONE!'
def stopTest(self, test): """Called after an individual test is run. Args: test ([type]): [description] """ super(TestResult, self).stopTest(test) if Config.get(TestVars.new_file, default=True): pm.newFile(f=1)
def buildscene(): #scene building pm.newFile( f=True ) #anorld 가 laod 되어 있는지를 체크 한다. if not pm.pluginInfo('mtoa', q=True, loaded=True): pm.loadPlugin('mtoa') #랜더러를 anorld로 만들어 준다. defaultRenderGlobals = pm.PyNode('defaultRenderGlobals') defaultRenderGlobals.currentRenderer.set('arnold')
def test_build_rig_from_json_file(self): """ Test for building a rig with a json file. """ file_path = os.path.normpath("{}/temp/test_rig_build.json".format( constants.BUILD_JSON_PATH)) pmc.newFile(force=True) self.build_instance = build.MainBuild() self.build_instance.build_from_json_file(file_path)
def close_scene(self): ''' Closes the scene, without changing any meta ''' logger.debug("Closing Scene") try: pmc.newFile() return True except RuntimeError as e: logger.error("Could not close scene!") logger.error(e) return False
def test_open_loads_the_references(self): """testing if the open method loads the references """ # create a couple of versions and reference them to each other # and reference them to the the scene and check if maya updates the # Version.references list versionBase = Version(**self.kwargs) versionBase.save() # change the take naem self.kwargs["take_name"] = "Take1" version1 = Version(**self.kwargs) version1.save() self.kwargs["take_name"] = "Take2" version2 = Version(**self.kwargs) version2.save() self.kwargs["take_name"] = "Take3" version3 = Version(**self.kwargs) version3.save() # now create scenes with these files self.mEnv.save_as(version1) self.mEnv.save_as(version2) self.mEnv.save_as(version3) # this is the dummy version # create a new scene pm.newFile(force=True) # check if the versionBase.references is an empty list self.assertTrue(versionBase.references==[]) # reference the given versions self.mEnv.reference(version1) self.mEnv.reference(version2) # save it as versionBase self.mEnv.save_as(versionBase) # clean scene pm.newFile(force=True) # re-open the file self.mEnv.open_(versionBase, force=True) self.mEnv.post_open(versionBase) # check if the references are loaded ref_data = self.mEnv.get_referenced_versions() for data in ref_data: ref_node = data[1] self.assertTrue(ref_node.isLoaded())
def test_open_loads_the_references(self): """testing if the open method loads the references """ # create a couple of versions and reference them to each other # and reference them to the the scene and check if maya updates the # Version.references list versionBase = Version(**self.kwargs) versionBase.save() # change the take naem self.kwargs["take_name"] = "Take1" version1 = Version(**self.kwargs) version1.save() self.kwargs["take_name"] = "Take2" version2 = Version(**self.kwargs) version2.save() self.kwargs["take_name"] = "Take3" version3 = Version(**self.kwargs) version3.save() # now create scenes with these files self.mEnv.save_as(version1) self.mEnv.save_as(version2) self.mEnv.save_as(version3) # this is the dummy version # create a new scene pm.newFile(force=True) # check if the versionBase.references is an empty list self.assertTrue(versionBase.references == []) # reference the given versions self.mEnv.reference(version1) self.mEnv.reference(version2) # save it as versionBase self.mEnv.save_as(versionBase) # clean scene pm.newFile(force=True) # re-open the file self.mEnv.open_(versionBase, force=True) self.mEnv.post_open(versionBase) # check if the references are loaded ref_data = self.mEnv.get_referenced_versions() for data in ref_data: ref_node = data[1] self.assertTrue(ref_node.isLoaded())
def reinitialise_meta_network(self): self.save_file() pm.newFile(f=1) self.open_file() from PKD_Tools.Red9 import Red9_Meta reload(Red9_Meta) from PKD_Tools.Rigging import core reload(core) self.mRig = Red9_Meta.MetaClass("CharacterRig") self.myCtrl = Red9_Meta.MetaClass("C_Core_FK_Ctrl")
def load_file(self): item_path = self.get_item_datas()["PATH"] f_path, f_name, f_ext = FileDir_Management.pathSplit(item_path) pmc.newFile(force=True) pmc.system.openFile(item_path, force=True) pmc.workspace(f_path, o=True) pmc.workspace(dir=f_path) print "#\tFILE PATH --> %s" % item_path
def saveRenderFile(self, forAnim, cacheFolder, log): lightingFolder = pm.optionVar.get('lightingFolderString', '') lightingString = pm.optionVar.get('lightingString', '') animString = pm.optionVar.get('animString', '') timeUnit = pm.currentUnit(q=1, time=True) startTime = pm.playbackOptions(query=True, minTime=True) endTime = pm.playbackOptions(query=True, maxTime=True) print 'Saving render file asfasfasfsfasf' pm.newFile(force=True) pm.currentUnit(time=timeUnit) pm.currentTime(startTime, edit=True) pm.playbackOptions(ast=startTime) pm.playbackOptions(aet=endTime) pm.playbackOptions(minTime=startTime) pm.playbackOptions(maxTime=endTime) workspace = pm.workspace.path print workspace print forAnim animRoot = forAnim.replace('\\', '/').replace(workspace, '') lightingFile = animRoot.split('/')[-1].replace(animString, lightingString) foldersToFile = animRoot.split('/')[2:-1] for folder in foldersToFile: if not os.path.isdir(os.path.join(lightingFolder, folder)): os.mkdir(os.path.join(lightingFolder, folder)) lightingFolder = os.path.join(lightingFolder, folder) else: lightingFolder = os.path.join(lightingFolder, folder) fullPath = os.path.join(lightingFolder, lightingFile) f, ext = os.path.splitext(lightingFile) print ext filetype = 'mayaAscii' if ext == '.mb': filetype = 'mayaBinary' pm.saveAs(fullPath, f=1, type=filetype) for reference in self.exportReferences: self.importAlembic(reference[1], reference[2], cacheFolder) for cam in self.userCameras: self.importAlembicCamera(cam, cacheFolder) pm.saveFile()
def shotAssemble(partField, sequenceField, shotField, listPhase, act ): # New scene pm.newFile(f = True) # Extract SHOT NUMBER from UI codePart = partField.getText() codeSequence = sequenceField.getText() codeShot = shotField.getText() # Build SHOT DICTIONARY from FTrack data dataShotDic = dna.buildShotDic( codePart, codeSequence, 'SHOT_{0}'.format(codeShot)) listChars = dataShotDic['characters'] listProps = dataShotDic['props'] listEDA = dataShotDic['eda'] listEnv = dataShotDic['environments'] # START ASSEMBLING for action in act: if action == 'save': fileNameFull = '{0}{1}{2}/{3}/SHOT_{4}/{5}E{3}_S{4}_001.mb'.format(rootScene, listPhase[1], codePart, codeSequence, codeShot, listPhase[2]) dna.exportFileLV( fileNameFull ) # Save scene dna.rangeSetup(codePart, codeSequence, codeShot) # PLAYBACK START/END RANGE SETUP dna.setRes() # Setup RESOLUTION elif action == 'add assets': dna.referenceItems(listChars, listPhase[0]) # reference ( list of CHARS, RIG-GEO triger, asset type) print ' << CHARACTERS DONE! >>' dna.referenceItems(listProps, listPhase[0]) # REF PROPS print ' << PROPS DONE! >>' if listEnv: dna.referenceItems(listEnv, 'GEO' ) # REF ENVIRONMENT print ' << ENVIRONMENNT DONE! >>' if listEDA[0]: print listEDA dna.referenceItems(listEDA, listPhase[0] ) # REF EDA print ' << EDA DONE! >>' elif action == 'create camera': cam = pm.camera() camName = 'E' + codeSequence + '_S' + codeShot cam[0].rename(camName) cam[1].rename(str(camName) + 'Shape') dna.camSetup(cam[1]) elif action == 'add ML': for i in listChars: matPath = dna.buildItemFullPath(i, 'MAT') dna.importData(matPath) # IMPORT ML for CHAR print '<< IMPORTED MATERIAL FOR: {} >>'.format(i) if listEnv: matPath = dna.buildItemFullPath(listEnv[0], 'MAT') dna.importData(matPath) # IMPORT ML for ENV print '<< IMPORTED MATERIAL FOR: {} >>'.format( listEnv[0] ) # SAVE SCENE pm.saveFile() # CREATE REPORT print 'ASSEMBLING DONE!'
def newScene(**kwargs): bForce = kwargs.get("force", kwargs.get("f", False)) if not bForce: sScenePath = saveScene() else: sScenePath = "newSceneForced" if sScenePath: pm.newFile(force=True) return sScenePath
def setUp(self): self.temp = tempfile.mkdtemp(prefix='referencesTest') print "created temp dir: %s" % self.temp # Refs: # sphere.ma # (no refs) # cube.ma # :sphere => sphere.ma # cone.ma # :cubeInCone => cube.ma # :cubeInCone:sphere => sphere.ma # master.ma # :sphere1 => sphere.ma # :sphere2 => sphere.ma # :cube1 => cube.ma # :cube1:sphere => sphere.ma # :cone1 => cone.ma # :cone1:cubeInCone => cube.ma # :cone1:cubeInCone:sphere => sphere.ma # create sphere file print "sphere file" # cmds.file(new=1, f=1) pm.newFile(f=1) sphere = pm.polySphere() # We will use this to test failed ref edits... pm.addAttr(sphere, ln='zombieAttr') self.sphereFile = pm.saveAs(os.path.join(self.temp, 'sphere.ma'), f=1) # create cube file print "cube file" pm.newFile(f=1) pm.polyCube() pm.createReference(self.sphereFile, namespace='sphere') pm.PyNode('sphere:pSphere1').attr('translateX').set(2) self.cubeFile = pm.saveAs(os.path.join(self.temp, 'cube.ma'), f=1) # create cone file print "cone file" pm.newFile(f=1) pm.polyCone() pm.createReference(self.cubeFile, namespace='cubeInCone') pm.PyNode('cubeInCone:pCube1').attr('translateZ').set(2) pm.PyNode('cubeInCone:sphere:pSphere1').attr('translateZ').set(2) self.coneFile = pm.saveAs(os.path.join(self.temp, 'cone.ma'), f=1) print "master file" pm.newFile(f=1) self.sphereRef1 = pm.createReference(self.sphereFile, namespace='sphere1') pm.PyNode('sphere1:pSphere1').attr('translateY').set(2) self.sphereRef2 = pm.createReference(self.sphereFile, namespace='sphere2') pm.PyNode('sphere2:pSphere1').attr('translateY').set(4) self.cubeRef1 = pm.createReference(self.cubeFile, namespace='cube1') pm.PyNode('cube1:sphere:pSphere1').attr('translateY').set(6) pm.PyNode('cube1:pCube1').attr('translateY').set(6) self.coneRef1 = pm.createReference(self.coneFile, namespace='cone1') self.masterFile = pm.saveAs(os.path.join(self.temp, 'master.ma'), f=1)
def test_get_meshes_in_selection_should_handle_shapes_correctly(): import pymel.core as pm from arnold_subdiv_manager.maya_abstraction_implementation import ( MayaAbstractionImplementation, ) pm.newFile(f=True) pm.camera() pm.polyCube() pm.select(["|pCube1|pCubeShape1", "|pCube1"]) maya_abstraction = MayaAbstractionImplementation() meshes = maya_abstraction.get_meshes_in_selection() assert meshes == [Mesh("|pCube1|pCubeShape1"), Mesh("|pCube1")]
def test_get_meshes_in_selection_should_only_return_meshes(): import pymel.core as pm from arnold_subdiv_manager.maya_abstraction_implementation import ( MayaAbstractionImplementation, ) pm.newFile(f=True) pm.camera() pm.polyCube() pm.select(["pCube1", "camera1"]) maya_abstraction = MayaAbstractionImplementation() meshes = maya_abstraction.get_meshes_in_selection() assert meshes == [Mesh("|pCube1")]
def setUp(self): # New scene pm.newFile(f=True) # Get ncloth attributes from file self.ncloth_attrs = [] self.ncloth_attrsFile = os.path.dirname(__file__).\ replace('tests', 'tool') self.ncloth_attrsFile = self.ncloth_attrsFile + \ os.sep + 'ncloth_attrs.txt' if not os.path.exists(self.ncloth_attrsFile): msg = 'File not found: ', self.ncloth_attrsFile raise Exception(msg) f = open(self.ncloth_attrsFile, 'r') self.ncloth_attrs = f.readlines() f.close() # Get nucleus attributes from file self.nucleus_attrs = [] self.nucleus_attrsFile = os.path.dirname(__file__).\ replace('tests', 'tool') self.nucleus_attrsFile = self.nucleus_attrsFile + \ os.sep + 'nucleus_attrs.txt' if not os.path.exists(self.nucleus_attrsFile): msg = 'File not found: ', self.nucleus_attrsFile raise Exception(msg) f = open(self.nucleus_attrsFile, 'r') self.nucleus_attrs = f.readlines() f.close() # Create plane and ncloth self.plane = pm.polyPlane()[0] pm.select(self.plane, r=1) nClothCreate() self.ncloth = pm.PyNode('nCloth1') self.nucleus = pm.PyNode('nucleus1') # Create expected name now = datetime.now() self.name = self.ncloth.name() + '_' + \ str(now.year) + '-' + str(now.month) + '-' + \ str(now.day) + '_' + \ str(now.hour) + '-' + str(now.minute)
def tearDown(self): """clean the test """ # create a new file pm.newFile(f=True) # delete any .rsmap in the test_data folder import os import glob test_data_path = os.path.abspath('./test_data/') for f in glob.glob('%s/*.rstexbin' % test_data_path): try: os.remove(f) except OSError: pass
def test_basic_file_cmds(self): print "Exporting all", os.path.join( self.temp, 'all.ma' ) expFile = pm.exportAll( os.path.join( self.temp, 'all.ma' ), preserveReferences=1, force=1) print "Importing" # if we don't do this newFile first, maya crashes... # BSPR-18231 Maya crashes on import after exporting with references pm.newFile(f=1) pm.importFile( expFile ) print "Exporting all" pm.exportAll( os.path.join( self.temp, 'all.ma' ), preserveReferences=1, force=1) print "Exporting animation" pm.exportAnim( os.path.join( self.temp, 'anim.ma' ), force=1) pm.select(pm.SCENE.persp) print "Exporting selected animation" pm.exportSelectedAnim( os.path.join( self.temp, 'selAnim.ma' ), force=1)
def test_save_as_fills_the_referenced_versions_list(self): """testing if the save_as method updates the Version.references list with the current references list from the Maya """ # create a couple of versions and reference them to each other # and reference them to the the scene and check if maya updates the # Version.references list versionBase = Version(**self.kwargs) versionBase.save() # change the take name self.kwargs["take_name"] = "Take1" version1 = Version(**self.kwargs) version1.save() self.kwargs["take_name"] = "Take2" version2 = Version(**self.kwargs) version2.save() self.kwargs["take_name"] = "Take3" version3 = Version(**self.kwargs) version3.save() # now create scenes with these files self.mEnv.save_as(version1) self.mEnv.save_as(version2) self.mEnv.save_as(version3) # this is the dummy version # create a new scene pm.newFile(force=True) # check if the versionBase.references is an empty list self.assertTrue(versionBase.references==[]) # reference the given versions self.mEnv.reference(version1) self.mEnv.reference(version2) # save it as versionBase self.mEnv.save_as(versionBase) # now check if versionBase.references is updated self.assertTrue(len(versionBase.references)==2) self.assertTrue(version1 in versionBase.references) self.assertTrue(version2 in versionBase.references)
def setUp(self): self.temp = tempfile.mkdtemp(prefix='referencesTest') print "created temp dir: %s" % self.temp # Refs: # sphere.ma # (no refs) # cube.ma # :sphere => sphere.ma # cone.ma # :cubeInCone => cube.ma # :cubeInCone:sphere => sphere.ma # master.ma # :sphere1 => sphere.ma # :sphere2 => sphere.ma # :cube1 => cube.ma # :cube1:sphere => sphere.ma # :cone1 => cone.ma # :cone1:cubeInCone => cube.ma # :cone1:cubeInCone:sphere => sphere.ma # create sphere file print "sphere file" # cmds.file(new=1, f=1) pm.newFile(f=1) sphere = pm.polySphere() # We will use this to test failed ref edits... pm.addAttr(sphere, ln='zombieAttr') self.sphereFile = pm.saveAs( os.path.join( self.temp, 'sphere.ma' ), f=1 ) # create cube file print "cube file" pm.newFile(f=1) pm.polyCube() pm.createReference( self.sphereFile, namespace='sphere' ) pm.PyNode('sphere:pSphere1').attr('translateX').set(2) self.cubeFile = pm.saveAs( os.path.join( self.temp, 'cube.ma' ), f=1 ) # create cone file print "cone file" pm.newFile(f=1) pm.polyCone() pm.createReference( self.cubeFile, namespace='cubeInCone' ) pm.PyNode('cubeInCone:pCube1').attr('translateZ').set(2) pm.PyNode('cubeInCone:sphere:pSphere1').attr('translateZ').set(2) self.coneFile = pm.saveAs( os.path.join( self.temp, 'cone.ma' ), f=1 ) print "master file" pm.newFile(f=1) self.sphereRef1 = pm.createReference( self.sphereFile, namespace='sphere1' ) pm.PyNode('sphere1:pSphere1').attr('translateY').set(2) self.sphereRef2 = pm.createReference( self.sphereFile, namespace='sphere2' ) pm.PyNode('sphere2:pSphere1').attr('translateY').set(4) self.cubeRef1 = pm.createReference( self.cubeFile, namespace='cube1' ) pm.PyNode('cube1:sphere:pSphere1').attr('translateY').set(6) pm.PyNode('cube1:pCube1').attr('translateY').set(6) self.coneRef1 = pm.createReference( self.coneFile, namespace='cone1' ) self.masterFile = pm.saveAs(os.path.join(self.temp, 'master.ma'), f=1)
def bdPerformPlayblast(self,folder,outFolder,characterRig, blastFormat, blastCompression, referenceCam): animDir = folder animFiles = [] for i in range(self.mayaFilesTableWidget.rowCount()): status = self.mayaFilesTableWidget.item(i,0).text() if status == 'Yes': animFiles.append(self.mayaFilesTableWidget.item(i,1).text()) #pm.mel.eval('setAllMainWindowComponentsVisible 0;') for f in sorted(animFiles): pathFile = animDir + '/' + f if outFolder == '': pathMovie = 'movies/' + f[:-3] else: pathMovie = outFolder + '/' +f[:-3] if os.path.isfile(pathFile): print pathFile else: print 'no file' return checkFileCallbackId = OM.MSceneMessage.addCheckFileCallback(OM.MSceneMessage.kBeforeReferenceCheck, self.bdReplaceRig) pm.newFile(f=1) pm.openFile(pathFile,f=1) #pm.mel.eval('setNamedPanelLayout "Four View"; updateToolbox();') ''' openWin = pm.lsUI(windows=1) for win in openWin: if 'MayaWindow' not in win.name() and WINDOW_NAME not in win.name() and 'scriptEditorPanel' not in win.name(): pm.deleteUI(win) ''' pm.setAttr("defaultResolution.width",1280) pm.setAttr("defaultResolution.height",720) OM.MMessage.removeCallback(checkFileCallbackId) self.bdSetCamera(referenceCam) print folder,outFolder,characterRig, blastFormat, blastCompression, referenceCam try: self.mayaFilesTableWidget.item(row,0).setBackground(QtGui.QColor(255,100,150)) self.mayaFilesTableWidget.item(row,1).setBackground(QtGui.QColor(255,100,150)) pm.playblast(format = blastFormat, filename = pathMovie,forceOverwrite=1,sequenceTime=0,clearCache=0,viewer=0,showOrnaments=1,fp=4,percent = 100,compression = blastCompression,quality=100, widthHeight= [1280, 720]) except: print "WTF!!!!!!!!!!!" progress = (float(animFiles.index(f) + 1.0) / float(len(animFiles)) ) * 100.0 self.progressBar.setValue(int(progress)) row = animFiles.index(f)
def setUp(self): """setup the tests """ # ----------------------------------------------------------------- # start of the setUp # create the environment variable and point it to a temp directory conf.database_url = "sqlite://" self.temp_config_folder = tempfile.mkdtemp() self.temp_projects_folder = tempfile.mkdtemp() os.environ["OYPROJECTMANAGER_PATH"] = self.temp_config_folder os.environ[conf.repository_env_key] = self.temp_projects_folder # create a test project self.project = Project("Test Project") self.project.create() # create a test asset self.asset1 = Asset(self.project, "Test Asset 1") # version type self.asset_vtypes = VersionType.query()\ .filter(VersionType.type_for == "Asset").all() self.shot_vtypes = VersionType.query()\ .filter(VersionType.type_for == "Shot").all() self.user1 = User(name="Test User 1", email="*****@*****.**") # create a test version self.kwargs = { "version_of":self.asset1, "base_name":self.asset1.code, "type":self.asset_vtypes[0], "created_by":self.user1, "extension":"ma" } self.version1 = Version(**self.kwargs) self.version1.save() # create the environment instance self.mEnv = mayaEnv.Maya() # just renew the scene pm.newFile(force=True)
def create_simple_ctrl_meta_network(self): pm.newFile(f=1) subSystem = core.TransSubSystem(side="C", part="Core") self.mRig = Red9_Meta.MetaRig(name='CharacterRig', nodeType="transform") self.mRig.connectChild(subSystem, 'Arm') subSystem.setParent(self.mRig) fkSystem = core.TransSubSystem(side="C", part="Core") subSystem.addMetaSubSystem(fkSystem,"FK") self.myCtrl = core.Ctrl(side="C", part="Core") self.myCtrl.build() self.myCtrl.setParent(fkSystem) self.myCtrl.debugMode = True fkCtrls = [self.myCtrl] fkSystem.connectChildren(fkCtrls, "Ctrl") fkSystem.convertSystemToSubSystem("FK")
def test_save_as_references_to_a_version_in_same_workspace_are_replaced_with_abs_path_with_env_variable(self): """testing if the save_as method updates the references paths with an absolute path starting with conf.repository_env_key for references to a version in the same project thus the referenced path is relative """ # create project proj1 = Project("Proj1") proj1.save() proj1.create() # create assets asset1 = Asset(proj1, "Asset 1") asset1.save() # create a version of asset vtype vers1 = Version(asset1, asset1.code, self.asset_vtypes[0], self.user1) vers1.save() # save it self.mEnv.save_as(vers1) # new scene pm.newFile(force=True) # create another version with different type vers2 = Version(asset1, asset1.code, self.asset_vtypes[1], self.user1) vers2.save() # reference the other version self.mEnv.reference(vers1) # save it self.mEnv.save_as(vers2) # now check if the referenced vers1 starts with $REPO refs = pm.listReferences() # there should be only one ref self.assertTrue(len(refs)==1) # and the path should start with conf.repository_env_key self.assertTrue( refs[0].unresolvedPath().startswith("$" + conf.repository_env_key) )
def SetupSimScene(platform): # get the current scene path and extract fields from it # using the work template: scene_path = os.path.abspath(cmds.file(query=True, sn=True)) fields = work_template.get_fields(scene_path) publish_version = fields["version"] #prepare all the paths and variables clothFile = "Z:/work/00719_grandpa/assets/Props/Main_Outift/publish/mainOutfit.cloth.v001.ma" abcFile = "Y:/RENDERS/00719_grandpa/000_dummy/0000/cache/grandpa.abc" ncachePath = "Y:/RENDERS/00719_grandpa/000_dummy/0000/cache/nCache" abcNodes = "shoes l_eye r_eye topTeeth bottomTeeth body" #loading alembic plugin cmds.loadPlugin('AbcImport.mll') #import all the necessary data pm.newFile(f=1, type='mayaAscii') pm.importFile(clothFile) pm.AbcImport(abcFile, mode="import", ct=abcNodes, ftr=True, crt=True, sts=True) #query time data startTime=pm.playbackOptions(q=True,animationStartTime=True) endTime=pm.playbackOptions(q=True,animationEndTime=True) pm.currentTime(startTime) #find all nCloth objects clothObjects = pm.ls(type='nCloth') #create simulation cache for all nCloth nodes in the scene print ('caching theses nCloth objects: ' + str(clothObjects)) cacheFiles = pm.cacheFile(cnd=clothObjects, st=startTime, et=endTime, dir=ncachePath, dtf=True, fm='OneFile', r=True, ws=True) #apply created cache to simulated objects cacheShapes = pm.ls('outputCloth*') i=0 for shape in cacheShapes: switch = mel.eval('createHistorySwitch(\"' + str(shape) + '\",false)') cacheNode = pm.cacheFile(f=cacheFiles[i], cnm=str(shape), ia='%s.inp[0]' % switch ,attachFile=True, dir=ncachePath) pm.setAttr( '%s.playFromCache' % switch, 1 ) i += 1
def setUp(self): self.temp = os.path.join(tempfile.gettempdir(), "referencesTest") if not os.path.isdir(self.temp): os.makedirs(self.temp) print "created temp dir: %s" % self.temp # Refs: # sphere.ma # (no refs) # master.ma # :sphere1 => sphere.ma # :sphere2 => sphere.ma # create sphere file print "sphere file" # cmds.file(new=1, f=1) pm.newFile(f=1) sphere = pm.polySphere()[0] pm.addAttr(sphere, ln="zombieAttr1") pm.addAttr(sphere, ln="zombieAttr2") cmds.setAttr("%s.v" % sphere, lock=1) cmds.setAttr("%s.zombieAttr1" % sphere, lock=1) self.sphereFile = pm.saveAs(os.path.join(self.temp, "sphere.ma"), f=1) print "master file" pm.newFile(f=1) self.sphereRef1 = pm.createReference(self.sphereFile, namespace="sphere1") self.sphereRef2 = pm.createReference(self.sphereFile, namespace="sphere2") self.sphere1 = pm.PyNode("sphere1:pSphere1") self.sphere2 = pm.PyNode("sphere2:pSphere1") self.sphere1.attr("translateY").set(2) self.sphere2.attr("translateY").set(4) self.cube = pm.polyCube()[0] pm.addAttr(self.cube, ln="zombieAttr1") pm.addAttr(self.cube, ln="zombieAttr2") cmds.setAttr("%s.v" % self.cube, lock=1) cmds.setAttr("%s.zombieAttr1" % self.cube, lock=1) self.masterFile = pm.saveAs(os.path.join(self.temp, "master.ma"), f=1)
def test_save_as_of_a_scene_with_two_references_to_the_same_version(self): """testing if the case where the current maya scene has two references to the same file is gracefully handled by assigning the version only once """ # create project proj1 = Project("Proj1") proj1.save() proj1.create() # create assets asset1 = Asset(proj1, "Asset 1") asset1.save() # create a version of asset vtype vers1 = Version(asset1, asset1.code, self.asset_vtypes[0], self.user1) vers1.save() # save it self.mEnv.save_as(vers1) # new scene pm.newFile(force=True) # create another version with different type vers2 = Version(asset1, asset1.code, self.asset_vtypes[1], self.user1) vers2.save() # reference the other version twice self.mEnv.reference(vers1) self.mEnv.reference(vers1) # save it and expect no InvalidRequestError self.mEnv.save_as(vers2) self.mEnv.reference(vers1) vers3 = Version(asset1, asset1.code, self.asset_vtypes[1], self.user1) vers3.save() self.mEnv.save_as(vers3)
def test_reference_creates_references_to_Versions_in_other_workspaces_loaded(self): """testing if reference method creates references to Versions with different VersionType and the reference state will be loaded """ proj1 = Project("Test Project 1") proj1.create() proj1.save() asset1 = Asset(proj1, "Test Asset 1") asset1.save() vers1 = Version(asset1, asset1.code, self.asset_vtypes[0], self.user1) vers1.save() vers2 = Version(asset1, asset1.code, self.asset_vtypes[1], self.user1) vers2.save() self.mEnv.save_as(vers1) pm.newFile(force=True) self.mEnv.save_as(vers2) # refence vers1 to vers2 self.mEnv.reference(vers1) # now check if the referenced files unresolved path is already starting # with conf.repository_env_key refs = pm.listReferences() # there should be only one reference self.assertEqual(len(refs), 1) # the unresolved path should start with $REPO self.assertTrue( refs[0].unresolvedPath().startswith("$" + conf.repository_env_key) ) self.assertTrue(refs[0].isLoaded())
def exportCmd(*args, **kwargs): ''' export models with animation ''' kx = kxTool.KXTool() kx.getSceneName() sceneName = kx.sceneName scenePath = kx.scenePath cachePath = "{path}/{name}/{name}_cloth.abc".format(path = scenePath.replace('scenes', 'cache/alembic'), name = sceneName) cacheFile = name.compileFileName(cachePath) fileName = name.compileFileName("{path}/{name}_cloth.mb".format(path = scenePath, name = sceneName)) geos = pm.PyNode('kx_cloth_export_layer').listMembers() exportGeos = [] for geo in geos: dup = pm.duplicate(geo, name = '{0}_toCloth'.format(geo.name()))[0] dup.setParent(w=1) shapes = dup.getShapes() pm.delete(shapes[1:]) pm.blendShape(geo, dup, o = 'world', w = (0,1)) exportGeos.append(dup) cache.exportAbcCache(exportGeos, cacheFile, useTimeline = True, verbose = True) pm.newFile(f=1) sourceGrp = pm.createNode('transform', name = 'source_Grp') abcNodeName = cache.importAbcCache(cacheFile) objs = pm.PyNode(abcNodeName).outputs() for obj in objs: obj.rename(obj.name().replace('_toCloth', '_anim')) obj.setParent(sourceGrp) pm.saveAs(fileName, f=1) return fileName
def setUp(self): print "getting temp dir" self.temp = os.path.join(tempfile.gettempdir(), 'referencesTest') if not os.path.isdir(self.temp): os.makedirs(self.temp) # create sphere file print "sphere file" # cmds.file(new=1, f=1) pm.newFile(f=1) sphere = pm.polySphere() # We will use this to test failed ref edits... pm.addAttr(sphere, ln='zombieAttr') self.sphereFile = pm.saveAs( os.path.join( self.temp, 'sphere.ma' ), f=1 ) # create cube file print "cube file" pm.newFile(f=1) pm.polyCube() pm.createReference( self.sphereFile, namespace='sphere' ) pm.PyNode('sphere:pSphere1').attr('translateX').set(2) self.cubeFile = pm.saveAs( os.path.join( self.temp, 'cube.ma' ), f=1 ) # create cone file print "cone file" pm.newFile(f=1) pm.polyCone() pm.createReference( self.cubeFile, namespace='cubeInCone' ) pm.PyNode('cubeInCone:pCube1').attr('translateZ').set(2) pm.PyNode('cubeInCone:sphere:pSphere1').attr('translateZ').set(2) self.coneFile = pm.saveAs( os.path.join( self.temp, 'cone.ma' ), f=1 ) print "master file" pm.newFile(f=1) self.sphereRef1 = pm.createReference( self.sphereFile, namespace='sphere1' ) pm.PyNode('sphere1:pSphere1').attr('translateY').set(2) self.sphereRef2 = pm.createReference( self.sphereFile, namespace='sphere2' ) pm.PyNode('sphere2:pSphere1').attr('translateY').set(4) self.cubeRef1 = pm.createReference( self.cubeFile, namespace='cube1' ) pm.PyNode('cube1:sphere:pSphere1').attr('translateY').set(6) pm.PyNode('cube1:pCube1').attr('translateY').set(6) self.coneRef1 = pm.createReference( self.coneFile, namespace='cone1' )
def tearDown(self): pm.newFile(f=1) shutil.rmtree(self.temp, ignore_errors=True)
def setUp(self): pm.newFile(f=1) self.rawDict = {'testKey': 'testValue'} for key, val in self.rawDict.iteritems(): cmds.fileInfo(key, val)
# Set the weight weightManager.pynode.input2X.set(singleWeight) # Connect to the rotateAverage weightManager.pynode.outputX >> rotateAverage @property def ikJointSystem(self): # The help joint system has the solver return self.helpJointSystem core.Red9_Meta.registerMClassInheritanceMapping() core.Red9_Meta.registerMClassNodeMapping(nodeTypes=['pointOnCurveInfo']) if __name__ == '__main__': pm.newFile(f=1) # mainSystem = core.TransSubSystem(side="C", part="Core") # ikSystem = HumanSpine(side="L", part="Core", numHighLevelCtrls=5, fallOffMethod="Position") ikSystem = HumanSpine(side="L", part="Core") ikSystem.ikControlToWorld = True #ikSystem.devSpine = True ikSystem.isStretchable = True ikSystem.testBuild() ikSystem.addStretch() # mainSystem.addMetaSubSystem(ikSystem, "FK") # ikSystem.convertSystemToSubSystem(ikSystem.systemType)
def newfile(): pm.newFile(f=1)
def setUp(self): pm.newFile(f=1) cmds.fileInfo('testKey', 'testValue')