def addCacheToScene(self): item = self.getItem() print item.getDataDict() for cache_ns, cacheMData in item.caches.iteritems(): cache = CacheComponent(cache_ns, cacheMData, self.parent) if cache.cacheVer == 0: print 'Component %s not yet published!!' % ( cache_ns + ':' + cacheMData['task'] + cacheMData['code']) continue cacheFullPath = cache.getPublishPath() if cache_ns != 'cam': pm.createReference(cacheFullPath, namespace=cache_ns, groupReference=True, groupName=cache_ns + ':geo_group', type='Alembic') else: pm.AbcImport(cache.getPublishPath(), mode='import', fitTimeRange=True, setToStartFrame=True, connect='/') return item.caches
def autoCreateRef(): searchDir = mc.fileDialog2(fm=3, okc=u'确定路径', ds=2, rf=False) if not searchDir: return LIST_Files = {} for root, dirs, files in os.walk(searchDir[0]): for eaf in files: if os.path.splitext(eaf)[-1] == '.mb': fn_noExt = os.path.splitext(eaf)[0] re_ed = re.compile('_[a-z]*\d+$', re.I) fn_noEdt = fn_noExt if re_ed.search(fn_noExt): edt = re_ed.search(fn_noExt).group() fn_noEdt = re.sub(edt, "", fn_noExt) if fn_noEdt not in LIST_Files: LIST_Files[fn_noEdt] = {fn_noEdt: [root, eaf]} else: LIST_Files[fn_noEdt][fn_noExt] = [root, eaf] Need_Files = [] for ea in LIST_Files: k_list = LIST_Files[ea].keys() k_list.sort() Need_Files.append(LIST_Files[ea][k_list[-1]]) for ea in Need_Files: nms = '_'.join(ea[1].split('_')[:2]) ref_dir = os.path.abspath(os.path.join(ea[0], ea[1])) pm.createReference(ref_dir, namespace=nms)
def addXloToScene(self): item = self.getItem() for xlo_ns, xloMData in item.components.iteritems(): if xlo_ns == 'cam': continue task = xloMData['task'] xloMData['task'] = 'xlo' xlo = XloComponent(xlo_ns, xloMData, parent=self.parent) if xlo.ver == 0: print 'Component %s not yet published!!' % ( xlo_ns + ':' + xlo.task + xlo.code) continue pm.createReference(xlo.getPublishPath(), namespace=xlo_ns) item.components[xlo_ns]['assembleMode'] = 'xlo' item.components[xlo_ns]['task'] = task for cache_ns, cacheMData in item.caches.iteritems(): cache = CacheComponent(cache_ns, cacheMData, self.parent) if cache.cacheVer == 0: print 'Component %s not yet published!!' % ( cache_ns + ':' + cache.task + cache.code) continue pm.AbcImport(cache.getPublishPath(), mode='import', fitTimeRange=True, setToStartFrame=True, connect='/') item.components[cache_ns]['cacheVer'] = cache.cacheVer return item.components
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 setCamera(self): pm.mel.eval( 'setNamedPanelLayout "Single Perspective View"; updateToolbox();') sceneReferences = pm.getReferences() print sceneReferences camera = '' for item in sceneReferences: if sceneReferences[item].isLoaded(): if referenceCam.lower() in sceneReferences[item].path.lower(): print 'cam loaded already' camera = pm.ls(item + ':*', type='camera')[0] break print referenceCam stageCam = pm.ls(referenceCam + '*', type='camera')[0] print stageCam if stageCam: camera = stageCam if camera == '': if os.path.isfile(referenceCam): pm.createReference(referenceCam, namespace="CAM") camera = pm.ls('CAM:*', type='camera')[0] else: print 'No cam file, creating a default one' cameraList = pm.camera(n='playblastCam') camera = cameraList[1] cameraList[0].setTranslation([0, 10, 60])
def importAlembic(self, ns, rigPath, cacheFolder): shadeFile = self.getShadePath(rigPath) geoSuffix = pm.optionVar.get('geoString', 'REN') if os.path.isfile(shadeFile): pm.createReference(shadeFile, namespace=ns) meshes = [ mesh.fullPath() for mesh in pm.ls(ns + ':*' + geoSuffix, type='transform') ] if meshes: #print meshes pm.select(meshes) filePath = ns + '.abc' filePath = os.path.join(cacheFolder, filePath).replace('\\', '/') jobstring = "AbcImport " jobstring += "-mode import -fitTimeRange -connect \"" for mesh in meshes: jobstring += mesh + ' ' jobstring += '\" \"' + filePath + '\"' print jobstring try: pm.mel.eval(jobstring) except: pm.warning('Could not import %s rig' % ns)
def setCamera(self): pm.mel.eval('setNamedPanelLayout "Single Perspective View"; updateToolbox();') sceneReferences = pm.getReferences() print sceneReferences camera = '' for item in sceneReferences : if sceneReferences[item].isLoaded(): if referenceCam.lower() in sceneReferences[item].path.lower(): print 'cam loaded already' camera = pm.ls(item + ':*',type='camera')[0] break print referenceCam stageCam = pm.ls(referenceCam + '*',type='camera')[0] print stageCam if stageCam: camera = stageCam if camera == '': if os.path.isfile(referenceCam): pm.createReference(referenceCam,namespace="CAM") camera = pm.ls('CAM:*',type='camera')[0] else: print 'No cam file, creating a default one' cameraList = pm.camera(n='playblastCam') camera = cameraList[1] cameraList[0].setTranslation([0,10,60])
def reference_lightcam_rig(): lightcampath = 'xrefs/pepper_lightcam/dog_lightscamera.ma' projectpath = pm.Workspace().getPath() fullpath = os.path.join(projectpath, lightcampath) for r in pm.listReferences(): filepathwithoutprojectpath = str(r).replace(projectpath, '') if lightcampath in filepathwithoutprojectpath: print 'Lightcam rig already loaded: %s' % (r.refNode) return False print 'Referencing lightcam rig from %s' % (fullpath) try: pm.createReference(fullpath, groupReference=True, groupName='lightcam', namespace='dog_lightscamera') return True except: pm.err( 'Could not reference file %s. Do you have your project set correctly?' % (fullpath)) return False
def scaleChara(self, mayaFalse): #this part does the importing and admin stuff try: pm.createReference( '//p.sv/Prism/project/Parallel/element/character_Roll/scenes/' + pm.optionMenu(self.charalist, q=True, value=True)[-4:-1] + '001_SP01.mb', namespace=':') except: pm.confirmDialog(title=u'Parallel scaling', message=u'Parallel フォルダーの許可がないです。') #this part does the scaling pm.optionMenu('listofchara', q=True, value=True) inverseScale = 1 / self.nameScale[pm.optionMenu( self.charalist, q=True, value=True)] pm.scale('Reference|Root', inverseScale, inverseScale, inverseScale) for i in pm.listRelatives('Reference', ad=True, type='joint'): try: pm.copyKey(i) pm.pasteKey(i.replace('Reference', 'Reference1')) except: print 'no keys to copypasta' pm.scaleKey('Reference1|Root|Hips', valueScale=inverseScale, valuePivot=0, attribute='translate') #this part cleans up the file pm.delete('Reference') pm.listReferences()[0].importContents(removeNamespace=False) pm.rename('Reference1', 'Reference')
def create_reference(self, sid_ref): """ create a reference to the scene defined by sid_ref on the current scene. """ import pymel.core as pm cur_sid = self.get_sid() task_name = sid_ref.get("task") task_name = task_name.split("_")[-1] if sid_ref.is_shot(): # create the namespace based on the sid file_namespace = "{0}_{1}_{2}".format(sid_ref.get("seq"), sid_ref.get("shot"), task_name) else: # create the namespace based on the sid file_namespace = "{0}_{1}".format(sid_ref.get("name"), task_name) namespace_list = pm.listNamespaces( ) # get the namespace list of all references counter = self.make_counter( file_namespace, namespace_list) # return a formatted counter file_namespace += "__" + counter # create the reference pm.createReference(sid_ref.path, namespace=file_namespace)
def referenceButton(self, mayaFalse): if not pm.textField(self.sceneName, q=True, text=True): pm.confirmDialog(title=u'SER シーン管理', message=u'シーンを選択してください。') else: if pm.textField(self.refNamespace, q=True, text=True): #if namespace is present pm.createReference(pm.radioButton( pm.radioCollection(self.radColle, sl=True, q=True), q=True, annotation=True) + '/' + pm.radioButton(pm.radioCollection( self.radColle, sl=True, q=True), q=True, label=True), namespace=pm.textField(self.refNamespace, q=True, text=True)) else: pm.createReference(pm.radioButton( pm.radioCollection(self.radColle, sl=True, q=True), q=True, annotation=True) + '/' + pm.radioButton(pm.radioCollection( self.radColle, sl=True, q=True), q=True, label=True), namespace=':')
def replace_location(location_path, shot_filename): print '@DEBUG start replace_location' all_scene_refs = pm.listReferences() if location_path: location_path = location_path.split('\n') exclude_list = get_exclude_asset_list() for ref in all_scene_refs: ref_path = str(ref.path) ref_namespace = str(ref.namespace) if [ True for i in exclude_list if i in ref_path.split('/') or i in ref_namespace.split('_') ]: print 'LEAVE REF:', str(ref) else: print 'REMOVE REF:', str(ref) ref.remove() for loc in location_path: print loc #shot_filename_no_ext = shot_filename.split('.')[0] loc_namespace = loc.rsplit('\\', 1)[1].split('.')[0] print 'LOCATION', loc pm.createReference(loc, namespace=loc_namespace) else: print 'NO LOCATION PROVIDED'
def referenceItem( itemPathFull, nameSpace ): # REFERENCE SINGLE ASSET. INPUT <P:/TANNER/PROD/3D/scenes/ASSETS/CHARACTERS/KIRILLA/GEO/GEO_KIRILLA_039.mb>, <C01> pm.createReference(itemPathFull, sharedNodes=('shadingNetworks', 'displayLayers', 'renderLayersByName'), ns=nameSpace) print 'dnaCore.referenceItem: {}'.format(nameSpace)
def ref_something(self, one): if not (one in self.ref_item): # print one, type(one) self.ref_item.append(one) newFileName = self.library.load(str(one)) # print 'newFileName>>>', newFileName # cmds.file(newFileName, r=True, ns='ref') pm.createReference(newFileName)
def addToScene(self): """ Find last publish of this component and reference on the current file :return: """ item = self.getItem() componentPath = item.getPublishPath() pm.createReference(componentPath, namespace=self.ns)
def bs_createReference(filePath, prefixStyle='normal', prefixName='MSH'): """ @ reference file using three different style naming prefix. Args: filePath (str): full file path. prefixStyle (str): prefix type 3 supported (normal, namespace, prefix). prefixName (str): prefix name. Returns: bool. """ if prefixStyle == 'normal': pm.createReference(filePath) return True elif prefixStyle == 'fileName': namespace = filePath.split('/')[-1].split('.')[0] return pm.createReference(filePath, gl=True, namespace=namespace) elif prefixStyle == 'namespace': pm.createReference(filePath, namespace=prefixName) return True elif prefixStyle == 'prefix': pm.createReference(filePath, rpr=prefixName) return True elif prefixStyle == 'withoutNamespace': pm.createReference(filePath, namespace=':') return False
def _import_asset_in_task(self): assetName = self.assetList.currentText() taskName = self.taskList.currentText() importpath = getAssetPath(assetName, taskName) if importpath: postfix = '' if taskName == 'shader': postfix = '_shd' pm.createReference(importpath, namespace=assetName + postfix) self.previewBar.showMessage('Done!', 100000) self.previewBar.showMessage('Ready!')
def atomFixIKFK(self): # # NOTE 获取时间滑块 # env = pm.language.Env() # playBackTimes = env.getPlaybackTimes() # ref_list = pm.listReferences() # if len(ref_list) != 1: # raise RuntimeError(u"存在多个参考或没有参考") self.updateCombo() currentText = self.combo.currentText() for ref_node in pm.listReferences(): ref_path = ref_node.path if "%s -> %s" % (ref_node.refNode, ref_node) == currentText: break else: raise RuntimeError(u"存在多个参考或没有参考") namespace = ref_node.namespace # namespace = os.path.splitext(os.path.basename(ref_path))[0] # NOTE 加载 Atom 插件 if not pm.pluginInfo('atomImportExport', q=True, loaded=True): pm.loadPlugin('atomImportExport') # NOTE 保存当前文件 pm.saveFile() # NOTE 选择所有带关键帧的控制器 ctrl_list = { node for crv in pm.ls(type="animCurve") for node in crv.listConnections() if type(node) is nt.Transform } pm.select(ctrl_list) ctrl_list = [str(ctrl) for ctrl in ctrl_list] atom_file = os.path.join(tempfile.gettempdir(), "IKFK_Fix.atom").replace("\\", "/") mel.eval(""" file -force -options "precision=8;statics=1;baked=1;sdk=0;constraint=0;animLayers=1;selected=selectedOnly;whichRange=1;range=1:10;hierarchy=none;controlPoints=0;useChannelBox=1;options=keys;copyKeyCmd=-animation objects -option keys -hierarchy none -controlPoints 0 " -typ "atomExport" -es "%s"; """ % atom_file) # NOTE 去除当前参考 ref_node.remove() pm.createReference(ref_path, r=1, namespace=namespace) # print([ctrl.fullPathName() for ctrl in ctrl_list]) pm.select(ctrl_list) mel.eval(""" file -import -type "atomImport" -ra true -options ";;targetTime=3;option=insert;match=hierarchy;;selected=selectedOnly;" "%s"; """ % atom_file)
def import_reference(self): item_path = self.get_item_datas()["PATH"] namespace = self.get_item_datas()["NAMESPACE"] if not namespace: namespace = FileDir_Management.pathSplit(item_path)[1] pmc.createReference(item_path, namespace=namespace) print "#\tNAMESPACE --> %s" % namespace print "#\tFILE PATH --> %s" % item_path
def addToScene(self): """ Reference this cache on the current maya scene :return: """ cacheFullPath = self.getPublishPath() pm.createReference(cacheFullPath, namespace=self.ns, groupReference=True, groupName='geo_group', type='Alembic')
def ref_shading_lightset(): logger.debug("Create Reference for Lightset") try: pmc.createReference( "M:/04_workflow/scenes/assets/locations/shadingSetup/Maya/shadingSetup_REF.ma", ns="shadingSetup") except RuntimeError as e: logger.error(e) return False return True
def create_assets(self, asset_data, create_type): from pymel import core self.set_bounding_box() for each_asset in asset_data: asset_name = asset_data[each_asset]['name'] asset_path = asset_data[each_asset]['path'] asset_format = asset_data[each_asset]['format'] if create_type == 'reference': core.createReference(asset_path, iv=True, ns=asset_name) if create_type == 'import': core.importFile(asset_path, iv=True, ns=asset_name) return True
def makeRN(self, name): print '?' objName = name assetType = self.assetType mbPath = commonPath + assetType mbFile = mbPath + objName + '/rig/' + assetType[:2] + '_' + objName + '_rig_v000.ma' if os.path.isfile(mbFile): pm.createReference(mbFile, groupLocator=1, loadReferenceDepth='all' ,namespace=objName + '0' ,rfn=assetType.replace('/', '_') + objName + '_RN0')
def remove_namespace_from_reference(): """Converted a referenced file with name space to one without namespace""" # Check if there are namespaces if pm.listReferences(): # Get the First reference file ref = pm.listReferences()[0] # Get the path path = ref.path # Remove the path name ref.remove() # Reload the reference pm.createReference(path, namespace=":", mergeNamespacesOnClash=False) else: pm.warning("No namespaces found")
def bdSetCamera(camera,referenceCam): if referenceCam: pm.createReference(referenceCam,namespace="CAM") camera = pm.ls('CAM:*',type='camera')[0] perspModel = "".join(pm.getPanel(withLabel = 'Persp View')) pm.setFocus(perspModel) perspView = pm.getPanel(wf=1) pm.lookThru(perspView,camera) #pm.modelPanel (perspView, query=1,label=1) pm.modelEditor(perspView,e=1,alo=0) pm.modelEditor(perspView,e=1,polymeshes=1,grid=0) pm.modelEditor(perspView,e=1,displayAppearance='smoothShaded',displayTextures=1) perspCam = pm.ls('persp',type='transform')[0]
def bdSetCamera(self, referenceCam): pm.mel.eval( 'setNamedPanelLayout "Single Perspective View"; updateToolbox();') sceneReferences = pm.getReferences() print sceneReferences camera = '' for item in sceneReferences: if sceneReferences[item].isLoaded(): if referenceCam.lower() in sceneReferences[item].path.lower(): print 'cam loaded already' camera = pm.ls(item + ':*', type='camera')[0] break print referenceCam stageCam = pm.ls(referenceCam + '*', type='camera')[0] print stageCam if stageCam: camera = stageCam if camera == '': if os.path.isfile(referenceCam): pm.createReference(referenceCam, namespace="CAM") camera = pm.ls('CAM:*', type='camera')[0] else: print 'No cam file, creating a default one' cameraList = pm.camera(n='playblastCam') camera = cameraList[1] cameraList[0].setTranslation([0, 10, 60]) ''' perspModel = "".join(pm.getPanel(withLabel = 'Persp View')) if perspModel == '': perspModel = "".join(pm.getPanel(withLabel = 'Side View')) print camera, perspModel pm.setFocus(perspModel) ''' perspView = pm.getPanel(wf=1) pm.modelEditor(perspView, e=1, alo=0, activeView=True) pm.modelEditor(perspView, e=1, polymeshes=1, wos=0, grid=0) pm.modelEditor(perspView, e=1, displayAppearance='smoothShaded', displayTextures=1) try: pm.lookThru(perspView, camera) except: print 'Failed to look through playblast camera'
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 bdSetCameraVP2(cam): pm.createReference("P:/smurfs/working_project/cameras/worldcup_cam.ma",ns='cam') pm.mel.eval('setNamedPanelLayout \"Single Perspective View\"'); perspModel = "".join(pm.getPanel(withLabel = 'Persp View')) pm.setFocus(perspModel) perspView = pm.getPanel(wf=1) pm.lookThru(perspView,cam) #pm.modelPanel (perspView, query=1,label=1) pm.modelEditor(perspView,e=1,alo=0) pm.modelEditor(perspView,e=1,polymeshes=1,imagePlane=1,grid=0) pm.modelEditor(perspView,e=1,displayAppearance='smoothShaded',displayTextures=1,wireframeOnShaded=0) consolidate = pm.mel.eval('checkMemoryForConsolidatedWorld()') if consolidate: pm.modelEditor(perspView,e=1,rnm="vp2Renderer",rom='')
def bdSetCamera(self,referenceCam): pm.mel.eval('setNamedPanelLayout "Single Perspective View"; updateToolbox();') sceneReferences = pm.getReferences() print sceneReferences camera = '' for item in sceneReferences : if sceneReferences[item].isLoaded(): if referenceCam.lower() in sceneReferences[item].path.lower(): print 'cam loaded already' camera = pm.ls(item + ':*',type='camera')[0] break print referenceCam stageCam = pm.ls(referenceCam + '*',type='camera')[0] print stageCam if stageCam: camera = stageCam if camera == '': if os.path.isfile(referenceCam): pm.createReference(referenceCam,namespace="CAM") camera = pm.ls('CAM:*',type='camera')[0] else: print 'No cam file, creating a default one' cameraList = pm.camera(n='playblastCam') camera = cameraList[1] cameraList[0].setTranslation([0,10,60]) ''' perspModel = "".join(pm.getPanel(withLabel = 'Persp View')) if perspModel == '': perspModel = "".join(pm.getPanel(withLabel = 'Side View')) print camera, perspModel pm.setFocus(perspModel) ''' perspView = pm.getPanel(wf=1) pm.modelEditor(perspView,e=1,alo=0,activeView = True) pm.modelEditor(perspView,e=1,polymeshes=1,wos=0,grid=0) pm.modelEditor(perspView,e=1,displayAppearance='smoothShaded',displayTextures=1) try: pm.lookThru(perspView,camera) except: print 'Failed to look through playblast camera'
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 run(): camfocusfile = get_latest_focus_camera() if camfocusfile: fileref = pm.createReference(camfocusfile, namespace='CamFocus') fileref.importContents(removeNamespace=True) else: pm.warning(u'请检查场景文件名或者cam publish目录....')
def loadAnimFile(self, file_path, index): # NOTE 打开文件 pm.openFile(file_path, f=1) target = self.target_line.text() source = self.source_line.text() for hik_node in pm.ls(typ="HIKCharacterNode"): if source in str(hik_node): source = hik_node break else: err_msg = "%s - 找不到旧绑定 HIK角色 " % file_path self.error_list.append(err_msg) return # NOTE 导入 reference rig_path = self.rig_line.text() name, ext = os.path.splitext(os.path.basename(rig_path)) ref = pm.createReference(rig_path, r=1, namespace=name) target = "%s:%s" % (name, target) if ":" not in target else target if not pm.objExists(target): err_msg = "%s - 找不到新绑定 HIK角色 " % file_path self.error_list.append(err_msg) return # NOTE 重定向 pm.mel.hikSetCharacterInput(target, source) export_path = self.export_line.text() pm.renameFile(os.path.join(export_path, pm.sceneName().basename())) pm.saveFile(f=1)
def assert_reference(namespace, path): model_group = assert_group_chain('animated', '{}_group'.format(namespace), 'model') existing = pm.getReferences() if namespace in existing: ref_node = existing[namespace] ref_path = ref_node.unresolvedPath() if ref_path != path: raise ValueError("Existing {!r} reference {!r} should be {!r}".format( namespace, ref_path, path, )) all_nodes = set(ref_node.nodes()) nodes = [] for node in all_nodes: if pm.nodeType(node) != 'transform': continue parents = pm.listRelatives(node, allParents=True) if not parents or all(p not in all_nodes for p in parents): nodes.append(node) else: before = set(pm.ls(assemblies=True)) ref_node = pm.createReference(path, namespace=namespace, ) if ref_node.namespace != namespace: raise ValueError("Could not create namespace {!r}; got {!r}.".format(namespace, ref_node.namespace)) nodes = list(set(pm.ls(assemblies=True)) - before) for node in nodes: if model_group not in pm.listRelatives(node, allParents=True): pm.parent(node, model_group) return nodes
def test_export_referenced_mesh(self): ref_cube, ref_joints, ref_skincluster = self.create_skinned_cube() ref_cube_name = ref_cube.nodeName() pm.skinPercent(ref_skincluster, ref_cube.vtx, transformValue=(ref_joints[2], 1.0)) with tempfile.TemporaryDirectory() as tempdir_name: # skin a cube and export it to a separate file ref_filename = os.path.join(tempdir_name, 'ref_test.ma') stuff = [ref_cube] + ref_joints pm.select(stuff, r=True) pm.exportSelected(ref_filename, type='mayaAscii', constructionHistory=True, force=True) # clean scene then reference in the file just exported self._clean_scene() file_reference = pm.createReference(ref_filename) ref_nodes = file_reference.nodes() ref_cube = [ r for r in ref_nodes if r.nodeName().endswith(ref_cube_name) ][0] # export the skin weights dest_filename = os.path.join(tempdir_name, 'test_weights.ma') skinio.export_skinned_mesh(ref_cube, dest_filename) # open the exported skin file pm.openFile(dest_filename, force=True) result_cube = skinutils.get_skinned_meshes_from_scene()[0] result_skincl = skinutils.get_skincluster(result_cube) result_joints = result_skincl.influenceObjects() result = skinutils.get_weighted_influences(result_cube.vtx[0]) expected = {result_joints[2]: 1.0} self.assertEqual(expected, result)
def createReference(path, stripVersionInNamespace=True): if not path or not op.exists(path): return None before = pc.listReferences() namespace = op.basename(path) namespace = op.splitext(namespace)[0] if stripVersionInNamespace: # version part of the string is recognized as .v001 match = re.match('(.*)([-._]v\d+)(.*)', namespace) if match: namespace = match.group(1) + match.group(3) pc.createReference(path, namespace=namespace, mnc=False) after = pc.listReferences() new = [ref for ref in after if ref not in before and not ref.refNode.isReferenced()] return new[0]
def test_live_edits_returning_an_empty_list(self): """testing if the le=True or liveEdits=True with no reference edit will return an empty list """ # create a new reference with no edits ref = pm.createReference(self.sphereFile, namespace='sphere') edits = pm.referenceQuery(ref, es=1, le=1) self.assertEqual(edits, [])
def humanAnatomyImport(self, btn): """ This function can execute all functions related to importing the human anatomy shaping mesh Args: None Returns (None) """ print 'YOU DID IT ENJOY THAT HUMAN ANATOMY!' path = '/jobs/tvcUsers2015/michael-ni/michael-ni_sequence/maya/scenes/model/blendShapeMask_RnD/skinMask_Import_v002_man.ma' importHuman = pm.createReference(path, type="mayaAscii", ignoreVersion=True, gl=True, loadReferenceDepth = "all", mergeNamespacesOnClash = False, namespace = "tempMask")
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 reference_lightcam_rig(): lightcampath = "xrefs/pepper_lightcam/dog_lightscamera.ma" projectpath = pm.Workspace().getPath() fullpath = os.path.join(projectpath, lightcampath) for r in pm.listReferences(): filepathwithoutprojectpath = str(r).replace(projectpath, "") if lightcampath in filepathwithoutprojectpath: print "Lightcam rig already loaded: %s" % (r.refNode) return False print "Referencing lightcam rig from %s" % (fullpath) try: pm.createReference(fullpath, groupReference=True, groupName="lightcam", namespace="dog_lightscamera") return True except: pm.err("Could not reference file %s. Do you have your project set correctly?" % (fullpath)) return False
def addAovs(self): fileToRef = pm.fileDialog2(dir='/jobs/loca/common/aovs', okc = 'Reference', fileFilter = '*.mb', fileMode = 4, ds=2) references = pm.listReferences() if fileToRef: for each in fileToRef: if each not in references: namespace = each.split('/')[-1].split('.mb')[0] pm.createReference(each, namespace = namespace) pm.setAttr('%s:%s.enabled' % (namespace, namespace), 0) self.renderLayers[0] adjustmentPlugs = str(pm.listAttr('%s.adjustments' % self.renderLayers[0], m=1)[-3]) lastAdjsNum = int(adjustmentPlugs.split('[')[-1].split(']')[0]) newAdjsNum = lastAdjsNum + 1 pm.connectAttr('%s:%s.enabled' % (namespace, namespace), '%s.adjustments[%d].plug' % (self.renderLayers[0],newAdjsNum), f=1) self.close() self.__init__() self.show() else: fileName = each.split('/')[-1].split('.m')[0] pm.warning('%s is already referenced so skipped' % fileName) else: pass return 0
def copyAnimation(self,sourceAnim,sourceChar,fuseChar,start,end): rigFile = os.path.join(CHARACTERS_PATH,self.name,'rigging',self.name + '.ma') pm.openFile(rigFile,f=1) referenceAnim = pm.createReference(sourceAnim,namespace='source') pm.playbackOptions(e=1,ast=start,aet=end,min=start,max=end) pm.mel.eval('hikSetCurrentCharacter("' + fuseChar + '")') #pm.mel.eval('mayaHIKsetStanceInput( "' + fuseChar + '" )') #pm.mel.eval('HIKCharacterControlsTool()') pm.mel.eval('hikToggleLockDefinition') #self.logger.info('Characterized the skeleton') pm.mel.eval('mayaHIKsetCharacterInput( "' + fuseChar + '","' + sourceChar + '")') #pm.mel.eval('HIKCharacterControlsTool()') pm.mel.eval('hikBakeCharacter 0') referenceAnim.remove()
def reference(self, version): """References the given Version instance to the current Maya scene. :param version: The desired :class:`~oyProjectManager.models.version.Version` instance to be referenced. """ # use the file name without extension as the namespace namespace = os.path.basename(version.filename) repo = Repository() workspace_path = pm.workspace.path new_version_full_path = version.full_path if version.full_path.startswith(workspace_path): new_version_full_path = utils.relpath( workspace_path, version.full_path.replace("\\", "/"), "/", ".." ) # replace the path with environment variable new_version_full_path = repo.relative_path(new_version_full_path) ref = pm.createReference( new_version_full_path, gl=True, loadReferenceDepth='none', namespace=namespace, options='v=0' ) # replace external paths self.replace_external_paths(1) # set the reference state to loaded if not ref.isLoaded(): ref.load() # append the referenced version to the current versions references # attribute current_version = self.get_current_version() if current_version: current_version.references.append(version) current_version.save() return True
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 importFile(sFilePath, **kwargs): if not isinstance(sFilePath, basestring): raise TypeError, 'Wrong type passed to file path argument: {0}'.format(type(sFilePath)) if ("%" in sFilePath) or ("$" in sFilePath): sResolvedPath = pathResolve(sFilePath) else: sResolvedPath = sFilePath if not osp.isfile(sResolvedPath): raise ValueError, 'Import failed. No such file found : "{0}"'.format(sResolvedPath) kwargs.pop("defaultNamespace", kwargs.pop("dns", None)) bReference = kwargs.pop("reference", kwargs.pop("r", False)) bViewFit = kwargs.pop('viewFit', False) bOutNewNodes = kwargs.pop('returnNewNodes', kwargs.pop('rnn', True)) bPreserveRefs = kwargs.pop('preserveReferences', kwargs.pop('pr', True)) bNewScene = kwargs.pop('newScene', kwargs.pop('nsc', False)) if bReference: bUseNamespaces = True bNewScene = False else: bUseNamespaces = kwargs.pop('useNamespaces', kwargs.pop('uns', False)) # sNamespace = "" if bUseNamespaces: sNamespace = kwargs.pop("namespace", kwargs.pop("ns" , "")) if not sNamespace: sNamespace = osp.basename(sResolvedPath).rsplit(".", 1)[0] ##Three states kwarg: ##if newScene == True , importing NewScene is forced ##if newScene == False, importing in the CurrentScene ##if newScene == "NoEntry", so choose between NewScene and CurrentScene if bNewScene == "NoEntry": sConfirm = pm.confirmDialog(title="Import File", message='Import file into ... ?', button=["New Scene", "Current Scene", "Cancel"], defaultButton="New Scene", cancelButton="Cancel", dismissString="Cancel", ) if sConfirm == "Cancel": logMsg("Cancelled !" , warning=True) return bNewScene = True if sConfirm == "New Scene" else False if bNewScene: if newScene(**kwargs): return if bReference: oNewNodeList = pm.createReference(sFilePath, namespace=sNamespace, returnNewNodes=bOutNewNodes, **kwargs) else: if bUseNamespaces: kwargs["namespace"] = sNamespace oNewNodeList = pm.importFile(sResolvedPath, returnNewNodes=bOutNewNodes, preserveReferences=bPreserveRefs, **kwargs) oNewNodeList = listForNone(oNewNodeList) if oNewNodeList and bViewFit: pm.viewFit(all=True) return oNewNodeList
def _createNode(self): assert self.reference is None self.reference = pm.createReference(self.path, namespace=self.name) # Maya automatically increments the namespace in case of conflict self.name = self.reference.namespace return self.reference.refNode
exportScene = currScene.parent / 'pymel_test_ref.ma' # if a file already exists where we want to export, delete it first if exportScene.exists(): print "removing existing pymel export scene" exportScene.remove() print "exporting new scene:", exportScene pm.exportSelected( exportScene, f=1 ) # delete the original group pm.delete(g) # reference it in a few times for i in range(1,4): ref = pm.createReference( exportScene, namespace=('foo%02d' % i) ) # offset each newly created reference: # first we list all the nodes in the new reference, and get the first in the list. # this will be the 'newGroup' node. allRefNodes = ref.nodes() print "moving" , allRefNodes[0] allRefNodes[0].tx.set( 2*i ) # print out some information about our newly created references allRefs = pm.listReferences() for r in allRefs: print r.namespace, r.refNode, r.withCopyNumber() # the namespace property of the FileReference class can be used to set the namespace as well as to get it. allRefs[2].namespace = 'super'
def reference_asset(self, res='low'): print '%s has been added @ %s.' % (self.asset_name, res) pm.createReference(self.scene_name)
def referenceItem (itemPathFull, nameSpace): # REFERENCE SINGLE ASSET. INPUT <P:/TANNER/PROD/3D/scenes/ASSETS/CHARACTERS/KIRILLA/GEO/GEO_KIRILLA_039.mb>, <C01> pm.createReference(itemPathFull , sharedNodes =( 'shadingNetworks', 'displayLayers', 'renderLayersByName') , ns = nameSpace ) print 'dnaCore.referenceItem: {}'.format(nameSpace)
def referenceScene(scenePath): _pmCore.createReference(scenePath, namespace=_os.path.basename(scenePath))