def exportSelectionAsABC(): # check for AbcExport command if not 'AbcExport' in dir(pm): pm.error('AbcExport: command not found.') return # retrieve all selected node paths selection = pm.ls(sl=True, recursive=True, dagObjects=True) if not selection: return nodePathtoExport = [] for n in selection: if n.type() != 'transform': nodePathtoExport.append(n.getParent().fullPath()) # get out file path from user outfile = pm.fileDialog2(fileMode=0) if not outfile: return # ensure we use a '*.abc' file extension outfile = os.path.splitext(outfile[0])[0] + '.abc' # build the AbcExport command exportCmd = '-worldSpace -attr mvg_imageSourcePath -attr mvg_intrinsicParams -file %s -uvWrite' % outfile for p in nodePathtoExport: exportCmd += ' -root %s' % p exportCmd = ''' import pymel.core as pm pm.AbcExport(j="%s")''' % exportCmd pm.evalDeferred(exportCmd)
def main(): objs = pm.ls(sl=True) #use the current filepath as the clue to query the destination current_path = pm.mel.eval("file -q -sn") filename = os.path.basename(current_path) abc_name = os.path.splitext(filename)[0] + "_plug" + ".abc" rp_code = os.path.dirname(current_path).split("/")[-1] dirname = os.path.join( os.path.dirname(current_path)[:-len(rp_code)], "abc") abc_name = os.path.normpath(os.path.join(dirname, abc_name)) sel_frameRange = str(pm.playbackOptions(q=True, minTime=True) - 10) + " " + str( pm.playbackOptions(q=True, maxTime=True) + 10) geo = "" for obj in objs: geo += "-root %s " % obj pm.AbcExport( j="-frameRange {frameRange} -uvWrite -worldSpace -writeVisibility -dataFormat ogawa {file} -file {path}" .format(frameRange=sel_frameRange, file=geo, path=abc_name))
def export_asset_abc(obj_file, root_node): """Export the obj hierarchy from Maya as alembic. We export the rebuilt model hierarchy as alembic so that we can use it in any other DCC like gaffer. Arguments: obj_file {str} -- Path to the imported and rebuilt obj file. root_node {PyNode} -- PyNode object of the top root node of the model. Returns: str -- Path of the exported abc file. """ obj_dir = os.path.dirname(obj_file) obj_name = os.path.basename(obj_file) abc_dir = obj_dir.replace('obj', 'abc') abc_name = obj_name.replace('.obj', '.abc') abc_file = os.path.join(abc_dir, abc_name) if not os.path.exists(abc_dir): os.makedirs(abc_dir) pm.select(root_node) root_node_name = root_node.fullPath() abc_args = ['-frameRange 1 1', '-uvWrite', '-worldSpace', '-writeUVSets', '-dataFormat ogawa', '-root ' + root_node_name, '-file ' + abc_file] abc_arg = ' '.join(abc_args) pm.AbcExport(j=abc_arg) return abc_file
def runCameraExport(scale, frange, houdiniexp, mayaexp, guiobject): # SETTING THE VARIABLES FOR THE ABC EXPORT selectedcam = SelectedCamera() path = filenaming.getExportFilePath() exportcams = [] if path: # checking if cam needs to be exported and baking if mayaexp: rootcam = RootCamera("maya") exportcams.append( str(rootcam.selection )) #replacing the 1 in the name...find a better way print(rootcam.selection + " was added to the exportcams list") bakedrootcam = BasicCameraBake(rootcam, selectedcam) bakedrootcam.bakeme(frange[0], frange[1], 1) # checking if cam needs to be exported and baking if houdiniexp: houdinicam = RootCamera("houdini") exportcams.append( str(houdinicam.selection )) #replacing the 1 in the name....find a better way print(houdinicam.selection + " was added to the exportcams list") bakedhoudinicam = BasicCameraBake(houdinicam, selectedcam) bakedhoudinicam.bakeme(frange[0], frange[1], scale) # for the object.selection toggle camindex = 0 for app in exportcams: pathname, dirname = filenaming.buildFileName(app, path) newDir = os.path.split(pathname)[0] if not os.path.exists(newDir): os.mkdir(newDir) myfile = str("-file " + pathname) print(myfile) root = str("-root " + str(app)) myframerange = "-frameRange " + str(frange[0]) + " " + str( frange[1]) exportcommand = myfile + " " + root + " " + myframerange + " " + "-eulerFilter -worldspace" pm.AbcExport(j=exportcommand) try: pm.delete(houdinicam.selection) except: print("There is no need to delete the houdini camera") try: pm.delete(rootcam.selection) except: ("There is no need to delete the maya camera") del guiobject
def abc_custom_export(framemode='currentframe', qstart=0, qend=0, preroll=False, path='', preframe=0, nodes=[]): """wrapper the abcexport export abc file with abcexport maya command with some preset like uvwrite, world space, color groups, face groups :type framemode: string :param framemode: currentframe, timeslider, startend :type qstart: int :param qstart: precise start frame manualy for startend framemode option :type qend: int :param qend: precise end frame manualy for startend framemode option :type preroll: bool :param preroll: active a preroll compute frames :type preframe: int :param preframe: precise the preroll start frame :type nodes: list :param nodes: list of maya transform nodes :type path: string :param path: the alembic path file """ if framemode == 'currentframe': start = int(pmc.currentTime(query=True)) end = int(pmc.currentTime(query=True)) elif framemode == 'timeslider': start = int(pmc.playbackOptions(q=True, ast=True)) end = int(pmc.playbackOptions(q=True, aet=True)) elif framemode == 'startend': start = qstart end = qend else: raise ValueError(("Wrong framemode, must be currentframe or timeslider" " or startend")) if path == '': raise ValueError("Must precise a string path") prerollstring = '' if preroll: prerollstring = ( '-frameRange {prerollstart} {startp} -step 1 -preRoll').format( prerollstart=preframe, startp=start - 1) if len(nodes) == 0: raise ValueError("obj arg cant be an empty list of transform") objects = '' for obj in nodes: objects += ' -root |' + obj.name() abcstring = ( '{prerollstring} -frameRange {start} {end} -attr GuerillaTags -Attr Center -attr Front -attr Up -attr PupilSize' ' -uvWrite -writeColorSets -writeFaceSets -writeVisibility -worldSpace -dataFormat ogawa' ' {objects} -file {path}').format(prerollstring=prerollstring, start=start, end=end, objects=objects, path=path) pmc.AbcExport(jobArg=abcstring, verbose=True)
def exportAlembic(self, mdag_paths): self.setBoundingBox() min, max = self.getFrameRange() format = 'ogawa' root = self.getRoot(mdag_paths) command = '-frameRange {} {} -dataFormat {} {} -file {}'.format( min, max, format, root, self.stuio_path) core.AbcExport(j=command) return self.stuio_path
def mkChar(self, rootObj, filepath, start=None, end=None): if start is None: start = pym.playbackOptions(ast=True, q=True) if end is None: end = pym.playbackOptions(aet=True, q=True) job = self.job.format(start=start, end=end, rootObj=rootObj, filepath=filepath) pym.AbcExport(j=job)
def export_camera(self, camera_node, file_path, first_frame, last_frame): camera_name = camera_node.name() mel_command = \ '-frameRange {0} {1} -uvWrite -worldSpace \ -writeVisibility -dataFormat \ ogawa -root {2} -file {3}' .format( first_frame, last_frame, camera_name, file_path ) pm.AbcExport(j=mel_command)
def _publish_alembic_cache_for_item(self, item, output, work_template, primary_publish_path, sg_task, comment, thumbnail_path, progress_cb): """ Export an Alembic cache for the specified item and publish it to Shotgun. """ asset_name = item["name"].strip("|") tank_type = output["tank_type"] publish_template = output["publish_template"] # 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"] # update fields with the group name: fields["Asset"] = asset_name name = os.path.basename(cmds.file(query=True, sn=True)) fields["name"] = name.split('.')[0] # create the publish path by applying the fields # with the publish template: publish_path = publish_template.apply_fields(fields) # node loop nodesString = '' item["other_params"] for node in item["other_params"]: nodesString += '-root ' + node + ' ' #export with assets attribute attrstring = '-a asset' # build and execute the Alembic export command for this item: frame_start = int(cmds.playbackOptions(q=True, min=True)) frame_end = int(cmds.playbackOptions(q=True, max=True)) #abc_export_cmd = "AbcExport -j \"-frameRange 1 100 -stripNamespaces -uvWrite -worldSpace -wholeFrameGeo -writeVisibility %s -file %s\"" % (nodesString,publish_path) try: #self.parent.log_debug("Executing command: %s" % abc_export_cmd) #mel.eval(abc_export_cmd) pm.AbcExport( j='-frameRange %s %s %s -stripNamespaces -uvWrite -worldSpace -wholeFrameGeo -writeVisibility %s-file %s' % (frame_start, frame_end, attrstring, nodesString, publish_path)) except Exception, e: raise TankError("Failed to export Alembic Cache: %s" % e)
def cacheCamera(task, code): shot = Item(task=task, code=code, itemType='shot') if 'cam' not in shot.caches: shot.caches['cam'] = { 'code': '0000', 'ver': 1, 'updateMode': 'last', 'task': 'rig', 'assembleMode': 'camera', 'type': 'asset', 'cacheVer': 0, 'name': '' } camera = CameraComponent('cam', shot.caches['cam'], parent=shot) camera.wrapData() if not camera.cameraTransform: pm.confirmDialog(title='No Camera', ma='center', icon='information', message='No camera to cache', button=['OK'], defaultButton='OK', dismissString='ok') return shot.caches['cam']['cacheVer'] += 1 cacheFullPath = camera.getCachePublishPath(make=True) jobCam = ' -root ' + camera.cameraTransform.name() jobFile = " -file " + cacheFullPath ini = str(int(pm.playbackOptions(q=True, min=True))) fim = str(int(pm.playbackOptions(q=True, max=True))) jobFrameRange = ' -frameRange ' + ini + ' ' + fim # set parameters for alembic cache jobAttr = ' -attr translateX -attr translateY -attr translateZ -attr rotateX ' \ '-attr rotateY -attr rotateZ -attr scaleX -attr scaleY -attr scaleZ -attr visibility' jobOptions = " -worldSpace -writeVisibility" # build cache arguments jobArg = jobFrameRange + jobOptions + jobAttr + jobCam + jobFile # do caching pm.AbcExport(j=jobArg) shot.putDataToDB()
def export_abc(): fstart = pmc.playbackOptions(query=True, animationStartTime=True) fend = pmc.playbackOptions(query=True, animationEndTime=True) roots = "" for item in pmc.ls(sl=True): roots += "-root {root} ".format(root=item.fullPath()) name = pmc.sceneName().splitext()[0].split("/")[-1] + ".abc" output = pmc.sceneName().parent.parent / "Caches" / name args = "-frameRange {fstart} {fend} -ro -stripNamespaces -uvWrite -writeVisibility -dataFormat ogawa {roots} -file {output}".format( fstart=fstart, fend=fend, roots=roots, output=output) pmc.AbcExport(jobArg=args)
def exportCFX(items): for tran in items(): # begin = pm.playbackOptions(q=True, ast=True) end = pm.playbackOptions(q=True, aet=True) cmd = '-frameRange {} {} -stripNamespaces -uvWrite -root {} -file {}'.format(950, end, pm.PyNode(tran).name(long=True), os.path.normpath( os.path.join(cfx, '{}.abc'.format( tran.split( ':')[ 0] )))) print cmd pm.sysFile(cfx, md=True) pm.AbcExport(j=cmd)
def exportArchive_abc(self, path, name, group): frame_mode = self.frameRange_comboBox.currentText() if frame_mode == "Current Frame": frame = pm.currentTime(query=True) s_frame = frame e_frame = frame elif frame_mode == "Animation": s_frame = self.startFrame_LE.text() e_frame = self.endFrame_LE.text() save_abc = path+'/'+name+'.abc' frame_range = "-frameRange " + s_frame + " " + e_frame prman_preset = "-attrPrefix rman__torattr -attrPrefix rman__riattr -attrPrefix rman_emitFaceIDs -uvWrite -writeColorSets -writeFaceSets -writeVisibility -autoSubd -writeUVSets -dataFormat ogawa" root = "-root " + group file = "-file " + save_abc command = frame_range + " " + prman_preset + " " + root + " "+file pm.AbcExport(j=command)
def exportCFX(chars, begin, end): for char in chars: possibleName = char + '*:' + char + '_CFX' trans = pm.ls(possibleName) if trans: for tran in trans: # begin = pm.playbackOptions(q=True, ast=True) # end = pm.playbackOptions(q=True, aet=True) cmd = '-frameRange {} {} -stripNamespaces -uvWrite -root {} -file {}'.format( begin, end, tran.name(long=True), os.path.normpath( os.path.join( cfx, '{}.abc'.format(tran.name().split(':')[0])))) print cmd mc.sysFile(cfx, md=True) pm.AbcExport(j=cmd)
def ExportABC(startFrame, endFrame, ExportRootsString, outPath, additionalFlags=''): # sets the frame range to export rangeFlag = '-frameRange {0} {1} '.format(startFrame, endFrame) # add custom flags to if needed customFlag = '-uvWrite {0} -worldSpace -writeUVSets -dataFormat ogawa '.format( additionalFlags) # export flag rootFlag = '-root {0} '.format(ExportRootsString) # file name fileFlag = '-file {0}'.format(outPath) jExport = rangeFlag + customFlag + rootFlag + fileFlag print 'jExport is: ', jExport print pm.AbcExport(j=jExport)
def alembicExport(startFrame, endFrame, filePath, nodes, attributes=None): ''' Exports alembic file ''' #making sure plugin is loaded pm.loadPlugin('AbcExport') # defining variables nodesString = '' # node loop for node in nodes: nodesString += '-root ' + node + ' ' attrstring = '' if attributes != None: if len(attributes) > 0: for attr in attributes: attrstring += '-a ' + attr + ' ' # export alembic file pm.AbcExport( j='-frameRange %s %s %s-stripNamespaces -uvWrite -worldSpace -wholeFrameGeo -writeVisibility %s-file %s' % (startFrame, endFrame, attrstring, nodesString, filePath))
def _publish_alembic_cache_for_item(self, item, output, work_template, primary_publish_path, sg_task, comment, thumbnail_path, progress_cb): """ Export an Alembic cache for the specified item and publish it to Shotgun. """ #loading plugin cmds.loadPlugin('AbcExport.mll', quiet=True) group_name = item["name"].strip("|") publish_template = output["publish_template"] # 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"] # update fields with the group name: fields["Asset"] = group_name sg_step = fields["Step"] if sg_step == 'Anim': tank_type = 'Alembic Animation' elif sg_step == 'Sim': tank_type = 'Alembic Simulation' elif sg_step == 'FX': tank_type = 'Alembic FX' # create the publish path by applying the fields # with the publish template: publish_path = publish_template.apply_fields(fields) #export with assets attribute attrstring = '-a asset -a sim -a abcStep' # build and execute the Alembic export command for this item: frame_start = int(cmds.playbackOptions(q=True, min=True)) frame_end = int(cmds.playbackOptions(q=True, max=True)) sampling = 1.0 nodesString = '' rootSet = set([]) #The extras logic should eventually be removed. It's kept only for backwards compatibility--- if group_name != 'extras': # node loop for node in item["other_params"]: root = node.root() rootSet.add(root) for root in rootSet: nodesString += '-root ' + root + ' ' elif group_name == 'extras': for node in item["other_params"]: nodesString += '-root ' + node + ' ' fields["Asset"] = 'extras' publish_path = publish_template.apply_fields(fields) sampling = node.abcStep.get() print('exporting: ' + nodesString) try: #self.parent.log_debug("Executing command: %s" % abc_export_cmd) #mel.eval(abc_export_cmd) print 'exporting ABC' pm.AbcExport( j='-step %s -frameRange %s %s %s -stripNamespaces -uvWrite -worldSpace -writeVisibility %s-file %s' % (sampling, frame_start, frame_end, attrstring, nodesString, publish_path)) except Exception, e: raise TankError("Failed to export Alembic Cache: %s" % e)
def exportSelection(self, *args): fileName = "" # Get Selection selection = cmds.ls(sl=True) # Get Framerange frameIn = cmds.playbackOptions(q=True, ast=True) frameOut = cmds.playbackOptions(q=True, aet=True) # Get Destination Path dest_path = cmds.textFieldButtonGrp("tfbPath", q=True, tx=True) + "/" # Set Flags for Export flag1 = "-frameRange " + str(frameIn) + " " + str(frameOut) + " " flag2 = " -step 1 -attr visibility -noNormals -stripNamespaces -uvWrite -worldSpace -writeVisibility" + " -file %s" # Export every char for item in selection: # Set filename if (cmds.radioButtonGrp("rbFileName", q=True, sl=True) == 2): fileName = "char_" + item.lower() elif (cmds.radioButtonGrp("rbFileName", q=True, sl=True) == 3): fileName = "prop_" + item.lower() else: fileName = item.lower() shot = cmds.textFieldGrp("tfShot", q=True, text=True) if len(shot) > 0: fileName = shot + "_" + fileName fileName = fileName.split(":")[0] if fileName[len(fileName) - 1] == "_": fileName = fileName[:len(fileName) - 2] # Exception for MIDDLEGROUND, FOREGROUND and BACKGROUND if item == "MIDDLEGROUND" or item == "FOREGROUND" or item == "BACKGROUND": flags = flag1 + "-root " + item + " " + flag2 % ( dest_path + fileName + ".abc") pm.AbcExport(j=flags) continue cmds.select(item, hi=True) shapes = cmds.ls(sl=True, type='mesh', fl=True) deformer = cmds.ls(sl=True, type="deformBend", fl=True) meshes = "" for mesh in shapes: transformNode = cmds.listRelatives(mesh, parent=True, f=True)[0] # Kick hidden meshes parentNode = cmds.listRelatives(transformNode, parent=True, f=True) if cmds.getAttr(transformNode + ".visibility") == False or ( parentNode == None and cmds.getAttr(parentNode[0] + ".visibility") == False): continue # Kick other unwanted meshes if "body_scale" in transformNode or "blendShape_master" in transformNode: continue meshes += "-root " + transformNode + " " print meshes meshes = meshes[0:(len(meshes) - 1)] flags = flag1 + meshes + flag2 % (dest_path + fileName + ".abc") pm.AbcExport(j=flags)
def cacheScene(task, code): ver = 0 collection = database.getCollection('shot') shotMData = database.getItemMData(task=task, code=code, itemType='shot') if 'caches' not in shotMData: shotMData['caches'] = copy.deepcopy(shotMData['components']) for item in shotMData['caches'].itervalues(): item['ver'] = 0 item['type'] = 'cache' item['assembleMode'] = 'cache' item['cacheVer'] = 0 item['name'] = '' itemComponents = shotMData['components'] itemCaches = shotMData['caches'] geoGroups = pm.ls('geo_group', r=True) choosen = pm.layoutDialog(ui=lambda: cachePrompt(geoGroups)) if 'Abort' in choosen: return path = database.getPath(shotMData, dirLocation='cacheLocation', ext='') cachePath = os.path.join(*path) if not os.path.exists(cachePath): os.makedirs(cachePath) choosenGeoGroups = [pm.PyNode(x) for x in choosen.split(',')] for geoGroup in choosenGeoGroups: # get all geometry on geo_group geosShape = geoGroup.getChildren(allDescendents=True, type='geometryShape') geos = [x.getParent() for x in geosShape] jobGeos = '' for geo in geos: if '|' in geo: logger.error('Naming problem on geo %s' % geo) else: jobGeos = jobGeos + ' -root ' + geo # make path and name for alembic file ns = geoGroup.namespace()[:-1] cacheMData = itemCaches[ns] # get the data for this component # get version and increment cacheMData['cacheVer'] += 1 ver = cacheMData['cacheVer'] # get cache publish path cacheName = database.templateName(cacheMData) + '_' + ns cacheFileName = str('v%03d_' % ver) + cacheName cacheFullPath = os.path.join(cachePath, cacheFileName) jobFile = " -file " + cacheFullPath + ".abc " # get scene frame range ini = str(int(pm.playbackOptions(q=True, min=True))) fim = str(int(pm.playbackOptions(q=True, max=True))) jobFrameRange = ' -frameRange ' + ini + ' ' + fim # set parameters for alembic cache jobAttr = ' -attr translateX -attr translateY -attr translateZ -attr rotateX ' \ '-attr rotateY -attr rotateZ -attr scaleX -attr scaleY -attr scaleZ -attr visibility' jobOptions = " -worldSpace -uv -writeVisibility" # build cache arguments jobArg = jobFrameRange + jobOptions + jobAttr + jobGeos + jobFile # do caching pm.AbcExport(j=jobArg) collection.find_one_and_update({ 'task': task, 'code': code }, {'$set': shotMData}) logger.info('Cache Ver: %s')
# Ensure target folder exists target = (u'F:\local_WIP\pythonAbcExport') try: os.makedirs(target) except OSError as error: if error.errno != errno.EEXIST: raise #build filepath cache_path = os.path.join(target, 'cache.abc') #main try: pm.select(selection, hierarchy=True, replace=True) options = [] for entry in selection: options.append('-root {0}'.format(entry)) options.append('-frameRange {0} {1}'.format(fstart, fend)) options.append('-step {0}'.format(step)) options.append('-uvWrite') options.append( '-writeColorSets -writeFaceSets -writeUVSets -dataFormat ogawa') options.append('-file {0}'.format(cache_path)) pm.AbcExport(verbose=True, jobArg=' '.join(options)) finally: pm.select(clear=True) pm.select(previouse_selection, replace=True) pm.currentTime(fcurrent)
def exportSelected(self, scene, shot, filename, dumbify, history): # geo list is the one that will be exported geoList = [] # dumbify set contains all geo under current selection dumbifySet = set() lightSet = set() selection = pm.selected() # add file node from displacements to selection. otherwise it will be ignored in export for obj in selection: if obj.type() =='VRayDisplacement' and obj.displacement.connections(): selection.append(obj.displacement.connections()[0]) if dumbify: # dumbify # this duplicates all geometry and links them with a blendshape. # the duplicates are moved to a seperate group and then cached. # this has the effect of removing any logic and just leaving geometry for sel in selection: for mesh in sel.getChildren(ad=True, type='mesh'): if not mesh.intermediateObject.get() and self.visibleInHierarchy(mesh): dumbifySet.add(mesh.getParent()) for light in sel.getChildren(ad=True, type=['VRayLightSphereShape', 'VRayLightDomeShape', 'VRayLightRectShape','VRayLightIESShape', 'VRayLightMesh']): lightSet.add(light.getParent()) exportGrp = pm.group(em=True, name=filename+'_grp') geoGrp = pm.group(em=True, name='geoGrp') geoGrp.setParent(exportGrp) for obj in dumbifySet: dupli = pm.duplicate(obj)[0] for child in dupli.getChildren(): if not child.type() == 'mesh': pm.delete(child) elif child.hasAttr('intermediateObject') and child.intermediateObject.get(): pm.delete(child) dupli.setParent(geoGrp) # renaming the duplicate so it get's the namespace back dupli.rename(obj.nodeName()) try: pm.blendShape(self.getNonIntermediateShape(obj), self.getNonIntermediateShape(dupli), origin='world', n=dupli.nodeName()+'_bs', w=[0,1]) except Exception as e: print '%s throws %s'%(obj,e) # keep object sets for easy vray clipping inheritedSets = self.getInheritedSetMembership(obj) for s in inheritedSets: if not pm.objExists(s.nodeName(stripNamespace=True)+'Export'): newSet = pm.sets(em=True, n = s.nodeName(stripNamespace=True)+'Export') geoList.append(newSet) pm.sets(pm.PyNode(s.nodeName(stripNamespace=True)+'Export'), forceElement=dupli) if lightSet: lightGrp = pm.group(em=True, name='lightGrp') lightGrp.setParent(exportGrp) for light in lightSet: dupli = pm.duplicate(light)[0] dupli.setParent(lightGrp) dupli.rename(light.nodeName()) geoList.append(exportGrp) else: geoList = selection # export geo pm.select(geoList, r=True, ne=True) geoPath = pm.exportSelected(os.path.join(self.cachePath, scene, shot, filename+'.ma'), typ='mayaAscii', constructionHistory = history, channels = False, constraints = False, expressions = False, force =True, shader = True, preserveReferences=False ) self.removeStudentLic(geoPath) self.removeNamespaces(geoPath) # export abc abcOptions = [] for sel in geoList: if 'dagNode' in sel.type(inherited=True): abcOptions.append('-root %s'%sel.fullPath()) frameRange = [pm.playbackOptions(q=True, min=True), pm.playbackOptions(q=True, max=True)] abcOptions.append('-frameRange %s %s'%(frameRange[0], frameRange[1])) abcPath = os.path.join(self.cachePath, scene, shot, filename+'.abc') abcOptions.append('-file "' + abcPath.replace('\\', '/') + '"') abcOptions.append('-uvWrite') abcOptions.append('-wholeFrameGeo') abcOptions.append('-worldSpace') abcOptions.append('-writeVisibility') abcOptions.append('-writeCreases') abcOptions.append('-writeUVSets') abcOptions.append('-dataFormat ogawa') pm.AbcExport(verbose = True, jobArg = ' '.join(abcOptions)) # cleanup if dumbify: for obj in geoList: pm.delete(obj)
def scene_publish(sequence, shot, scene, version, puppets=None): ''' :example sequence = 'sequence_101' shot = 'shot_1001' scene = 'animation' version = '0.0.0' assets = ['batman:batman', 'jasmin:jasmin', 'scene:scene'] # assets = ['batman:batman', 'jasmin:jasmin', 'scene:scene', 'motorcycle:motorcycle'] from tools.maya_publish import publish scene_publish(sequence, shot, scene, version) ''' from pymel import core print '#info scene publish(%s)' % scene model_panels = core.getPanel(type='modelPanel') for model_panel in model_panels: core.modelEditor(model_panel, edit=True, displayAppearance='boundingBox') core.modelEditor(model_panel, edit=True, allObjects=False) core.modelEditor(model_panel, edit=True, nurbsCurves=True) core.modelEditor(model_panel, edit=True, polymeshes=True) if not puppets: puppets = get_valid_puppets() dirname = os.path.join( resources.get_show_path(), # '/venture/shows/katana_tutorials/scene', sequence, shot, scene, version) if os.path.isdir(dirname): try: shutil.rmtree(dirname) except Exception: pass if not os.path.isdir(dirname): os.makedirs(dirname) min = int(core.playbackOptions(q=True, min=True)) max = int(core.playbackOptions(q=True, max=True)) puppet_attributes = [ 'name', 'category', 'type', 'version', 'model', 'lookdev' ] amination_attributes = ['min', 'max', 'latest_lookdev'] puppet_contents = {} for puppet in puppets: py_node = core.PyNode(puppet) for each in amination_attributes: attribute = '%s.%s' % (py_node.name(), each) if core.objExists(attribute): core.deleteAttr(attribute) py_node.addAttr(each, dt='string') py_node.setAttr('min', str(min)) py_node.setAttr('max', str(max)) puppet_name = puppet.split(':')[0] for puppet_attribute in puppet_attributes: value = py_node.getAttr(puppet_attribute) name = puppet.split(':')[0] if puppet_name not in puppet_contents: puppet_contents.setdefault(puppet_name, {}) puppet_contents[puppet_name].setdefault(puppet_attribute, value) category = py_node.getAttr('category') name = py_node.getAttr('name') model = py_node.getAttr('model') model_depnendency = get_lookdev_model_depnendency(category, name) latest_lookdev = 'None' if model_depnendency: if model_depnendency[model]: latest_lookdev = model_depnendency[model][0] py_node.setAttr('latest_lookdev', latest_lookdev) abc_path = os.path.join(dirname, '%s.abc' % puppet_name) ud_attrubutes = [] for attrubute in py_node.listAttr(ud=True): ud_attrubutes.append(attrubute.attrName()) asset_attributes = '-attr ' + ' -attr '.join(ud_attrubutes) command = '-frameRange %s %s %s -uvWrite -attrPrefix xgen -worldSpace -root %s -stripNamespaces -file %s ' % ( min, max, asset_attributes, puppet, abc_path) py_node.select(r=True) core.AbcExport(j=command) print '\t', abc_path core.select(puppets, r=True) maya_path = os.path.join(dirname, '%s.ma' % shot) manifest_path = os.path.join(dirname, 'manifest.json') core.exportSelected(maya_path, preserveReferences=True, f=True) manifest_data = { 'pipe': 'scene', 'data': { 'frame_range': [min, max], 'sequence': sequence, 'scene': scene, 'puppets': puppet_contents, 'version': version } } with open(manifest_path, 'w') as manifest: manifest.write(json.dumps(manifest_data, indent=4)) os.system('xdg-open \"%s\"' % dirname) print '\t', manifest_path print '\t', maya_path
if framemode == 'currentframe': start = int(pmc.currentTime(query=True)) end = int(pmc.currentTime(query=True)) elif framemode == 'timeslider': start = int(pmc.playbackOptions(q=True, ast=True)) end = int(pmc.playbackOptions(q=True, aet=True)) elif framemode == 'startend': start = qstart end = qend else: raise ValueError(("Wrong framemode, must be currentframe or timeslider" " or startend")) if path == '': raise ValueError("Must precise a string path") prerollstring = '' if preroll: prerollstring = ('-frameRange {prerollstart} {startp} -step 1 -preRoll' ).format(prerollstart=preframe, startp=start-1) if len(nodes) == 0: raise ValueError("obj arg cant be an empty list of transform") objects = '' for obj in nodes: objects += ' -root |' + obj.name() abcstring = ('{prerollstring} -frameRange {start} {end} -attr GuerillaTags' ' -uvWrite -writeColorSets -writeFaceSets -worldSpace -step {step} -dataFormat ogawa' ' {objects} -file {path}').format( prerollstring=prerollstring, start=start, end=end, objects=objects, path=path, step=step) pmc.AbcExport(jobArg=abcstring, verbose=True)
def asset_publish(name, category, type, version, model, lookdev): ''' :example name = 'jasmin' category = 'character' type = 'model' version = '1.0.0' model = 'None' lookdev = 'None' from tools.maya_publish import publish asset_publish(name, category, type, version, model, lookdev) ''' from pymel import core print '#info asset publish(%s)' % type py_node = core.PyNode(name) attributes = { 'name': name, 'category': category, 'type': type, 'model': model, 'version': version, 'lookdev': lookdev } orders = ['name', 'category', 'type', 'version', 'model', 'lookdev'] for order in orders: current_attribute = '%s.%s' % (py_node.name(), order) if core.objExists(current_attribute): core.deleteAttr(current_attribute) py_node.addAttr(order, dt='string') py_node.setAttr(order, attributes[order]) dirname = os.path.join( resources.get_show_path(), # '/venture/shows/katana_tutorials/asset', category, name, type, version) if os.path.isdir(dirname): try: shutil.rmtree(dirname) except Exception: pass if not os.path.isdir(dirname): os.makedirs(dirname) maya_path = os.path.join(dirname, '%s.ma' % name) abc_path = os.path.join(dirname, '%s.abc' % name) manifest_path = os.path.join(dirname, 'manifest.json') py_node.select(r=True) core.exportSelected(maya_path, f=True) asset_attributes = '-attr ' + ' -attr '.join(orders) command = '-frameRange 1001 1002 %s -uvWrite -attrPrefix xgen -worldSpace -root %s -stripNamespaces -file %s ' % ( asset_attributes, name, abc_path) py_node.select(r=True) core.AbcExport(j=command) manifest_data = {'pipe': 'asset', 'data': attributes} with open(manifest_path, 'w') as manifest: manifest.write(json.dumps(manifest_data, indent=4)) os.system('xdg-open \"%s\"' % dirname) print '\t', maya_path print '\t', abc_path print '\t', manifest_path
def main(): obj_list = cmds.ls(sl=True, long=True, dag=True) obj_list.sort(key=len, reverse=True) renamedict = {} namelist = [] cmds.loadPlugin("AbcExport.mll") for obj in obj_list: obj_name = obj.split("|")[-1] print obj_name if not namelist.count(obj_name): namelist.append(obj_name) renamedict[obj_name] = [obj] else: renamedict[obj_name].append(obj) try: for name in namelist: paths = renamedict[name] paths.sort(key=len, reverse=True) if len(paths) == 1: continue print name, paths index = 1 for path in paths: new_name = "%s_%s" % (name, index) index += 1 cmds.rename(path, new_name) except: pm.inViewMessage(smg="rename error", pos="midCenterTop", bkc=0x00FF1010, fade=True) # the function to get the top level of the selection def get_top(obj): parent_node = pm.listRelatives(obj, children=True, fullPath=True, allParents=True) if parent_node: parent_node = parent_node print "get %s" % parent_node return get_top(parent_node) else: result = obj print "final one %s" % result return result # get the top one objs = pm.ls(sl=True) pm.select(clear=True) for obj in objs: parent_node = pm.listRelatives(obj, children=True, fullPath=True, allParents=True) if parent_node: final = get_top(obj)[0] else: final = obj pm.select(final, add=True) objs = pm.ls(sl=True, long=True) geo_list = [] for obj in objs: print obj geo = None children = pm.listRelatives(obj, children=True, fullPath=True) for child in children: print pm.objectType(child) if "geo" in child.name() or "Geo" in child.name(): geo = child geo_list.append(geo) break else: geo = None if not geo: if len(children) == 1 and pm.objectType(children) == "mesh": geo = obj geo_list.append(geo) continue else: for child in children: if get_next(child): geo = child geo_list.append(geo) pm.select(clear=True) pm.select(geo_list, add=True) #use the current filepath as the clue to query the destination current_path = pm.mel.eval("file -q -sn") filename = os.path.basename(current_path) abc_name = os.path.splitext(filename)[0] + ".abc" rp_code = os.path.dirname(current_path).split("/")[-1] dirname = os.path.join( os.path.dirname(current_path)[:-len(rp_code)], "abc") abc_name = os.path.normpath(os.path.join(dirname, abc_name)) sel_frameRange = str(pm.playbackOptions(q=True, minTime=True) - 10) + " " + str( pm.playbackOptions(q=True, maxTime=True) + 10) geo = "" for obj in geo_list: geo += "-root %s " % obj pm.AbcExport( j="-frameRange {frameRange} -uvWrite -worldSpace -writeVisibility -dataFormat ogawa {file} -file {path}" .format(frameRange=sel_frameRange, file=geo, path=abc_name))
def main(): cmds.loadPlugin("AbcExport.mll") # get the top one objs = pm.ls(sl=True) if not objs: return pm.inViewMessage(smg="select object first", pos="midCenterTop", bkc=0x00FF1010, fade=True) pm.select(clear=True) for obj in objs: parent_node = pm.listRelatives(obj, children=True, fullPath=True, allParents=True) if parent_node: final = get_top(obj)[0] else: final = obj # judge the selection is ref or not ref_jud = pm.referenceQuery("%s" % final, isNodeReferenced=True) if ref_jud: file_path = pm.referenceQuery("%s" % final, filename=True) print file_path name_space = pm.referenceQuery("%s" % final, namespace=True) print name_space pm.mel.eval('file -importReference "%s"' % file_path) # remove the namespace pm.mel.eval('namespace -mv "%s" ":" -force' % name_space) # trying to get the shape group(filter of the curve and rig) pm.select(final, add=True) #deal with the samename node after import the reference readonly obj_list = cmds.ls(sl=True, long=True, dag=True) obj_list.sort(key=len, reverse=True) renamedict = {} namelist = [] for obj in obj_list: obj_name = obj.split("|")[-1] print obj_name if not namelist.count(obj_name): namelist.append(obj_name) renamedict[obj_name] = [obj] else: renamedict[obj_name].append(obj) for name in namelist: paths = renamedict[name] paths.sort(key=len, reverse=True) if len(paths) == 1: continue print name, paths index = 1 for path in paths: new_name = "%s_%s" % (name, index) index += 1 cmds.rename(path, new_name) # pm.select(clear=True) # pm.select(final, add=True) objs = pm.ls(sl=True, long=True) geo_list = [] for obj in objs: print obj geo = None children = pm.listRelatives(obj, children=True, fullPath=True) for child in children: print pm.objectType(child) if "geo" in child.name() or "Geo" in child.name(): geo = child geo_list.append(geo) break else: geo = None if not geo: if len(children) == 1 and pm.objectType(children) == "mesh": geo = obj geo_list.append(geo) continue else: for child in children: if get_next(child): geo = child geo_list.append(geo) pm.select(clear=True) pm.select(geo_list, add=True) # use the current filepath as the clue to query the destination current_path = pm.mel.eval("file -q -sn") filename = os.path.basename(current_path) abc_name = os.path.splitext(filename)[0] + ".abc" rp_code = os.path.dirname(current_path).split("/")[-1] dirname = os.path.join( os.path.dirname(current_path)[:-len(rp_code)], "abc") abc_name = os.path.normpath(os.path.join(dirname, abc_name)) sel_frameRange = str(pm.playbackOptions(q=True, minTime=True) - 10) + " " + str( pm.playbackOptions(q=True, maxTime=True) + 10) root_geo = "" for obj in geo_list: root_geo += "-root %s " % obj print root_geo pm.AbcExport( j="-frameRange {frameRange} -uvWrite -worldSpace -writeVisibility -dataFormat ogawa {file} -file {path}" .format(frameRange=sel_frameRange, file=root_geo, path=abc_name))