import os,sys,logging,re
import cPickle as pickle
import bplatform.path
import bplatform.user
import bpipeline.context
import brender.render_utility
import brender.qube_submit
import maya.OpenMaya as OpenMaya
import maya.cmds as cmds
from layTools_2 import assemblyInfo
from shaderLink import _shaderEdit
import lsObject
reload(lsObject)
reload(assemblyInfo)
#-----------------------------------in batch--------------------------------------------
#---------------------------------------------------------------------------------------
_BATCH = False
try:
import maya.standalone
maya.standalone.initialize()
_BATCH = True
except:
_BATCH = False
#---------------------------------------------------------------------------------------
#-----------------------------------load Alembic----------------------------------------
#---------------------------------------------------------------------------------------
for _p in ('AbcImport', 'AbcExport','sceneAssembly'):
if not cmds.pluginInfo(_p, q=True, l=True):
cmds.loadPlugin('%s.so' % _p)
logging.info( '# Force load Alembic plugin: %s ...' % _p )
#---------------------------------------------------------------------------------------
def _deepSetAssemblyActive(names,fiterText = None,type = 'Scene'):
names = cmds.ls(names,type = 'assemblyReference')
for i in names:
assemblyInfo.setActive(name = i,fiterText = fiterText,type = type)
children = lsObject.lsObject(i,type = 'assemblyReference',filterName = None)[:-1]
if children:
_deepSetAssemblyActive(names = children,fiterText = fiterText,type = type)
def _group(objectName):
group_name = objectName.split('|')[-1].split(':')[-1]
cmds.ls(objectName,long = True)[0]
root = cmds.ls(objectName,long = True)[0].rsplit('|',1)[0]
if root:
children = cmds.listRelatives(root,
children = True,fullPath = True)
else:
children = cmds.ls(assemblies = True,long = True)
v = 1
children = [i.split('|')[-1].split(':')[-1] for i in children]
while '%s_%s' %(group_name,str(v)) in children:
v += 1
try:
group_name = cmds.group(objectName,name = '%s_%s' %(group_name,str(v)))
return cmds.ls(group_name,long = True)[0]
except:
raise Exception('can not group %s' % objectName)
return cmds.ls(objectName,long = True)[0]
def _getUseShader(shader,*attributes):
atts_dict = _shaderEdit.getShaderFileNode(shader)
for i in atts_dict:
atts_dict[i] = {'typ':'string',
'value':';'.join(
[bplatform.path.toLinux(cmds.getAttr('%s.fileTextureName' % f))
for f in atts_dict[i]])}
atts_dict['name'] = {'typ':'string','value':shader}
atts_dict['type'] = {'typ':'string','value':cmds.ls(shader,st = True)[-1]}
for i in attributes:
all_attributes = cmds.listAttr(shader,w = True)
all_attributes += cmds.listAttr(shader,shortNames = True,w = True)
if not atts_dict.has_key(i) and i in all_attributes:
value = cmds.getAttr('%s.%s' %(shader,i))
if isinstance(value,list):
atts_dict[i] = {'typ':'double3','value':value[-1]}
else:
atts_dict[i] = {'typ':'float','value':value}
return atts_dict
def _addAttr(obj,info):
for i in info:
if info[i].get('typ') == 'string':
name = 'material%s' % i.title()
if not cmds.listAttr(obj,string = name):
cmds.addAttr(obj,ln = name,dt = 'string')
cmds.setAttr('%s.%s' %(obj,name),info[i].get('value')
,type = 'string')
elif info[i].get('typ') == 'float':
name = 'material%s' % i.title()
if not cmds.listAttr(obj,string = name):
cmds.addAttr(obj,ln = name,at = 'double')
cmds.setAttr('%s.%s' %(obj,name),info[i].get('value'))
elif info[i].get('typ') == 'double3':
name = 'material%s' % i.title()
if not cmds.listAttr(obj,string = name):
cmds.addAttr(obj,ln = name,at = 'double3')
cmds.addAttr(obj,ln = '%sX' % name,at = 'double',p = name)
cmds.addAttr(obj,ln = '%sY' % name,at = 'double',p = name)
cmds.addAttr(obj,ln = '%sZ' % name,at = 'double',p = name)
cmds.setAttr('%s.%sX' %(obj,name),info[i].get('value')[0])
cmds.setAttr('%s.%sY' %(obj,name),info[i].get('value')[1])
cmds.setAttr('%s.%sZ' %(obj,name),info[i].get('value')[2])
def export(fileName,roots,**kwargs):
'''
onQube: Submit to qube if it is int, it is priority on Qube(bool or int)
type: export shape type (sting list)
frameRange frame range (int list)
uvWrite write uv with object default is True (bool)
step frame distance (int)
eulerFilter: Euler filter while sampling rotations, default is True (bool)
writeVisibility: write visibility with object, default is True (bool)
stripNamespaces split spacesNames (bool)
userAttr user attr (string list)
onlyTransform: only export transform (bool)
withShader: bake shader attributes (bool)
shaderAttribute: if withShader is True,bake shaderAttributes (string list)
writeFaceSets: write faceSets (bool)
faceSetName: write faceSet with name (sting list)
filterName: only export object which fullPathName has filterName (string list)
expandAssembly: expand AssemblyNode in batch model default is True (bool)
assemblyName: expand Assembly named default is ['HIGHT','full'] (string list)
can not be used:
selection
'''
#----------------------------------chick scene--------------------------------------
#-----------------------------------------------------------------------------------
unUsed = ['sl','selection']
for i in kwargs:
if i in unUsed:
kwargs.pop(i)
fileName = bplatform.path.toCurrent(fileName,True)
bake_sel = cmds.ls(sl=True)
if not cmds.ls(roots):
raise Exception('can not find roots')
if not fileName.endswith('.abc'):
raise Exception('file type is error')
#-----------------------------------------------------------------------------------
#----------------------------------Submit to qube-----------------------------------
#-----------------------------------------------------------------------------------
if kwargs.get('onQube'):
priority = kwargs.get('onQube')
kwargs.pop('onQube')
if isinstance(priority,bool):
priority = 1
elif isinstance(priority,basestring):
try:
priority = int(float(priority))
except:
priority = 1
else:
priority = int(priority)
dgmodified = cmds.dgmodified()
if dgmodified:
#-----------------------------------------------
#save file
filter_m = ['|persp','|top','|front','|side',
'|top|topShape','|front|frontShape',
'|side|sideShape','|persp|perspShape',
u'TurtleRenderOptions',u'TurtleUIOptions',
u'TurtleBakeLayerManager', u'TurtleDefaultBakeLayer']
if [i for i in dgmodified if i not in filter_m]:
logging.info('save file ')
cmds.file(save = True,f = True,ignoreVersion = True)
scene_path_new = brender.render_utility.genRenderTemp(cmds.file(q= True,sn = True))
kwargs['fileName'] = fileName
kwargs['roots'] = roots
data_path = os.path.join(os.path.dirname(scene_path_new),'AbcExportInfo')
logging.info('write info to %s ......' % data_path)
data_file = open(data_path,'wb')
pickle.dump(kwargs,data_file)
data_file.close()
logging.info('Submit scene to qube ......')
version = cmds.about(v=True)
cmd = ''
if os.name == 'nt':
cmd += '"S:/ple/studio/tool/gene/applauncher/bin/applauncher.bat" mayapy -pt tool --v %s --appargs' % str(version)
cmd += ' %s %s' %(bplatform.path.toWin(__file__,True),bplatform.path.toWin(scene_path_new,True))
else:
cmd += 'applauncher mayapy -pt tool --v %s --appargs' % str(version)
cmd += ' %s %s' %(bplatform.path.toLinux(__file__,True),bplatform.path.toLinux(scene_path_new,True))
show = bpipeline.context.getEnv().get('show')
if not show:
show = 'TST'
name = 'Maya%s (%s) %s export Alembic %s' %(str(version),show,bplatform.user.GET_LOCAL_USER(),os.path.basename(fileName))
logging.info('cmd is %s' % cmd)
cmd = str(cmd)
return brender.qube_submit.submitQubeCmdline(name = name,cmdline = cmd,priority = priority)
#-----------------------------------------------------------------------------------
#------------------------------------gather info------------------------------------
#-----------------------------------------------------------------------------------
used = {'type':None,'onlyTransform':None,
'withShader':None,'shaderAttribute':list(),
'filterName':list(),'expandAssembly':_BATCH,
'assemblyName' : ['HIGHT','full','(?!LOW)'],
'writeVisibility': not kwargs.get('writeVisibility')}
for i in used:
if i in kwargs:
used[i] = kwargs.get(i)
kwargs.pop(i)
for i in ['shaderAttribute','filterName','assemblyName']:
if not isinstance(used.get(i),(list,tuple)):
used[i] = [used.get(i)]
used['assemblyName'].append('')
for i in ['faceSetName','userAttr']:
if kwargs.has_key(i):
if not isinstance(kwargs.get(i),(list,tuple)):
kwargs[i] = [kwargs.get(i)]
#-----------------------------------------------------------------------------------
#------------------------------------edit scene-------------------------------------
#-----------------------------------------------------------------------------------
roots = lsObject.clearRoots(roots)
if used.get('expandAssembly'):
logging.info('expandAssembly...')
ass_ref = lsObject.lsObject(roots,type = 'assemblyReference',filterName = None)
_deepSetAssemblyActive(ass_ref,fiterText = [ i for i in used.get('assemblyName')],type = 'Scene')
if kwargs.get('sn') or kwargs.get('stripNamespaces'):
logging.info('stripNamespaces...')
objects = lsObject.lsObject(roots = roots,type = 'transform',filterName = used.get('filterName'))
pro_objects = lsObject.findSameName(*objects)
pro_M_objects = list()
for i in pro_objects:
pro_M_objects += lsObject.toMObject(*i)
for i in pro_M_objects:
path = lsObject.tofullPath(i)[0]
group = _group(path)
if path in roots:
roots.pop(roots.index(path))
roots.append(group)
objects = lsObject.lsObject(roots = roots,type = used.get('type'),
filterName = used.get('filterName'),
fiterVisibility = not used.get('writeVisibility'))
if used.get('onlyTransform'):
objects_1 = cmds.listRelatives(objects,parent = True,
fullPath = True,
type = 'transform')
objects_2 = cmds.ls(objects,long = True,
type = 'transform')
if not objects_1:
objects_1 = list()
if not objects_2:
objects_2 = list()
objects = objects_1 + objects_2
shader_info = dict()
attr_info = dict()
if used.get('withShader'):
logging.info('get shader attribute...')
shapes1 = cmds.ls(objects,shapes = True,type = 'mesh',long = True)
shapes2 = cmds.listRelatives(objects,shapes = True,fullPath = True,type = 'mesh')
if not shapes1:
shapes1 = list()
if not shapes2:
shapes2 = list()
shapes_all = list(set(shapes1+shapes2))
object_info = dict()
for i in shapes_all:
shader = _shaderEdit.getObjectShader(i)
if shader:
if not shader_info.has_key(shader[0]):
shader_info[shader[0]] = _getUseShader(shader[0],*used.get('shaderAttribute'))
object_info[shader[0]] = list()
object_info[shader[0]].append(i)
for i in object_info:
for o in object_info[i]:
node = None
if o in shapes1:
node = o
_addAttr(node,shader_info.get(i))
elif o in shapes2:
node = cmds.listRelatives(o,parent = True,fullPath = True)
if node:
node = node[0]
_addAttr(node,shader_info.get(i))
else:
continue
else:
continue
if not attr_info.has_key(i):
attr_info[i] = list()
attr_info[i].append(node)
all_attributes = list()
for i in shader_info:
for a in shader_info[i]:
name = 'material%s' % a.title()
if not name in all_attributes:
all_attributes.append(name)
for i in used.get('shaderAttribute'):
name = 'material%s' % i.title()
if not name in all_attributes:
all_attributes.append(name)
if not kwargs.has_key('userAttr'):
kwargs['userAttr'] = list()
elif not isinstance(kwargs.get('userAttr'),(list,tuple)):
kwargs['userAttr'] = [kwargs.get('userAttr')]
for i in all_attributes:
kwargs['userAttr'].append(i)
if kwargs.get('wfs') or kwargs.get('writeFaceSets'):
logging.info('get faceSet...')
if not kwargs.has_key('faceSetName'):
kwargs['faceSetName'] = [i for i in cmds.ls(type = 'objectSet')
if not i in cmds.ls(type = 'shadingEngine')
and not re.match('.*[Dd]efault.*',i)]
if _BATCH:
logging.info('set initialShading')
for i in objects:
try:
cmds.sets(i,e = True,forceElement = 'initialShadingGroup')
except:
pass
#-----------------------------------------------------------------------------------
#------------------------------------clear cmds-------------------------------------
#-----------------------------------------------------------------------------------
fileName = bplatform.path.toCurrent(fileName,True)
if not kwargs.has_key('frameRange') and not kwargs.has_key('fr'):
kwargs['frameRange'] = [cmds.currentTime(q=True),cmds.currentTime(q=True)]
defaultTrue = {'eulerFilter':'ef','writeVisibility':'wv','uvWrite':'uv'}
for i in defaultTrue:
if not kwargs.has_key(i) and not kwargs.has_key(defaultTrue.get(i)):
kwargs[i] = True
#---------------------------------------------------------------------------
#-----------------------------------cmd edit--------------------------------
#---------------------------------------------------------------------------
cmd = '-sl -wv '
for i in roots:
cmd += '-root %s ' % i
for i in kwargs:
if i in ['frameRange','fr']:
cmd += '-%s %i %i ' %(i,int(kwargs[i][0]),int(kwargs[i][1]))
elif isinstance(kwargs[i],(list,tuple)):
for n in kwargs[i]:
cmd += '-%s %s ' %(str(i),str(n))
elif isinstance(kwargs[i],bool):
if kwargs[i]:
cmd += '-%s ' % i
elif isinstance(kwargs[i],(basestring,int,float)):
cmd += '-%s %s ' %(str(i),str(kwargs[i]))
cmd += '-file %s ' % fileName
cmds.select(objects,r = True)
logging.info('AbcExport -j %s' % cmd)
cmds.AbcExport(j= cmd)
#---------------------------------------------------------------------------
#--------------------------------revert scene-------------------------------
#---------------------------------------------------------------------------
if not _BATCH:
logging.info('delte attribute...')
for i in attr_info:
for o in attr_info[i]:
if shader_info.get(i):
for a in shader_info[i]:
obj_attributes = cmds.listAttr(o)
obj_attributes += cmds.listAttr(o,shortNames = True)
name = 'material%s' % a.title()
if name in obj_attributes:
try:
cmds.deleteAttr('%s.%s' % (o,name))
except:
pass
#if bake_sel:
cmds.select(bake_sel, r = True)
logging.info('execution successful, file path is %s' % fileName)
return fileName
#---------------------------------------------------------------------------
if __name__ == '__main__':
if sys.argv[1]:
scene_path = bplatform.path.toCurrent(sys.argv[1])
info_path = os.path.join(os.path.dirname(scene_path),'AbcExportInfo')
if os.path.isfile(scene_path) and os.path.isfile(info_path):
logging.info('read info...')
info_path = open(info_path,'rb')
info = pickle.load(info_path)
info_path.close()
logging.info('open scene: %s' % scene_path)
cmds.file(scene_path,open = True,f = True,ignoreVersion = True)
export(**info)
logging.info('close scene: %s' % scene_path)
os._exit(0)
else:
raise Exception('can not find info file: %s or scene file: %s, Please chick it' %(info_path,scene_path))
alembicTool_alembicExport
最新推荐文章于 2021-07-06 11:04:28 发布