示例#1
0
    def importFunc(self):
        self.deleteKeys()
        self.fileName = self.displayArea.text()
        # print(self.fileName)
        if self.fileName == '':
            print("Please enter a file to be imported")
        else:
            pm.importFile(self.fileName, usingNamespaces=False, force=True)

            types = [
                'animCurveTA', 'animCurveTT', 'animCurveTL', 'animCurveTU'
            ]

            objList = []
            objs = pm.ls()

            for obj in objs:
                if obj.type() in types:
                    objList.append(obj)

            source = []
            destination = []

            for obj in objList:
                # source.append("{0}_{1}.output".format(fileName,obj.name()))
                source.append("{0}.output".format(obj.name()))
            for obj in objList:
                a, b = obj.name().rsplit('_', 1)
                destination.append("{0}.{1}".format(a, b))

            for i in range(len(destination)):
                if not pm.ls(source[i]):
                    pass
                else:
                    pm.connectAttr(source[i], destination[i])
示例#2
0
 def import_template_files(cls, template_file):
     import pymel.core as pm
     import os
     file_path = os.path.join(os.path.dirname(__file__), 'resources', cls.TEMPLATE_FILES[template_file])
     cls.LOG.info('Importing file %s from anvil/tests dir' % file_path)
     pm.importFile(file_path, ignoreVersion=True)
     cls.LOG.info('Successfully imported file.')
def importAbcFile():
    importFilePath=pm.textField('path_ABC2', q=True, text=True)
    #.abc를 없애준다
    filePathDeletAbc = importFilePath.replace('.abc','')

    pm.importFile( filePathDeletAbc+'.ma' )
    importAbc( filePathDeletAbc+'.abc' )
    connectionsTxtFile_open = open(filePathDeletAbc+'.txt')
    import pickle
    lst = pickle.load(connectionsTxtFile_open)
    print lst
    for geo, shd, aiShd,disShd in lst:
        cmds.select( geo )
        cmds.hyperShade( assign=shd )
        node=pm.ls(geo)[0]
        shape = node.getShape()
        shadingGrps = shape.outputs( type='shadingEngine' )
        print shadingGrps[0]
        shader=pm.ls(aiShd)[0]
        print shader
        try:
            print 'good'
            pm.connectAttr(shader.outColor,shadingGrps[0].aiSurfaceShader) 
        except:
            print 'false'
        try:
            disShader=pm.ls(disShd)[0]
            pm.connectAttr(disShader.outColor,shadingGrps[0]..displacementShader) 
        except:
            print 'no dis'
def run():
    if pm.ls(sl=True):
        for x in pm.ls(sl=True):
            layers = td_tools.which_render_layers(x)
            ref_obj = td_tools.ReferenceObj(x)
            print layers
            ref = pm.FileReference(ref_obj.file)
            proxy_file = get_proxy_for_selected_reference(x)
            ref.remove()
            # import proxy
            dets = pft.PathDetails.parse_path(proxy_file)
            name_space = dets.shot
            try:
                pm.system.namespace(add=name_space)
            except RuntimeError:
                pass
            pm.system.namespace(set=name_space)
            pm.importFile(proxy_file)
            pm.system.namespace(set=':')
            sel = pm.PyNode('%s:ArnoldStandIn' % name_space)
            sel.rename('%s:%s_mdl' % (name_space, name_space))
            # add this to all the render layers.
            print 'trying to add this:  %s:%s_mdl' % (name_space, name_space)
            td_tools.set_render_layers('%s:%s_mdl' % (name_space, name_space),
                                       layers)
    else:
        pm.warning(u'请先选中需要替换的参考内容')
示例#5
0
def import_facialtarget():
    scenedir = pm.sceneName().dirname()
    dir =  scenedir.parent
    bsdir = pm.util.common.path(dir+'/facialtarget/facialtarget.mb')
    pm.importFile(bsdir, defaultNamespace=True)
    bstarget_gp = pm.ls('*_facialtarget')
    if bstarget_gp:
        bstarget_gp = bstarget_gp[0]
        bstarget_gp.setParent(ul.get_node('miscGp'))
        bstargets = bstarget_gp.getChildren()
        pm.select(bstargets,r=True)
        pm.select('jawDeform',add=True)
        pm.select('orig',add=True)
        facebs = pm.blendShape(name='FaceBaseBS', automatic=True)
        facebs[0].jawDeform.set(1)
        for key, value in {'facialGuide':'FaceGuideBS','facial':'FaceDeformBS'}.items():
            pm.select('orig',r=True)
            pm.select(key,add=True)
            pm.blendShape(name=value,w=[(0,1),], automatic=True)
        pm.select('facial',r=True)
        pm.select("*_face_grp_skinDeform",add=True)
        pm.blendShape(name='RootBS',w=[(0,1),], automatic=True, after=True)
        pm.select('eyeDeform',r=True)
        pm.select("*_eye_grp_skinDeform",add=True)
        pm.blendShape(name='EyeDeformBS',w=[(0,1),], automatic=True, after=True)
    connect_Bs_control()
示例#6
0
def assign_mtl_from_resources(obj_names,
                              mtl_name,
                              include_displacement=True,
                              displacement_kw={}):
    if "." in mtl_name:
        mtl_name = mtl_name.split(".")[-2]

    mtl_full_name = "%s:%s" % (MTL_NS, mtl_name)

    if not pm.objExists(mtl_name) and not pm.objExists(mtl_full_name):
        base_dir = get_project_root_dir()
        mtl_path = os.path.join(base_dir, "resources", "%s.ma" % mtl_name)
        print('loading mtl from %s' % mtl_path)
        pm.importFile(mtl_path, namespace=TMP_NS)
        if not pm.system.namespace(exists=MTL_NS):
            pm.system.namespace(addNamespace=MTL_NS)
        mc.namespace(force=True, mv=(':' + TMP_NS, ':' + MTL_NS))
        pm.namespace(removeNamespace=TMP_NS, mergeNamespaceWithRoot=True)

    mtl = pm.PyNode(mtl_full_name)

    print("Assigning shader...")
    for selection_string in obj_names:
        for obj in pm.ls(selection_string, type='transform'):
            name = obj.name()
            plant_sg_name = mtl.shadingGroups()[0].name()
            mc.sets(name, e=True, forceElement=plant_sg_name)
            if include_displacement:
                set_arnold_displacement_attrs(name, **displacement_kw)
示例#7
0
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.')
示例#8
0
def createEyelashesShader():
    '''
    Creates the eyelashes shader, will be the only shader with a png file assigned to it 
    '''
    shaderFile = 'shader_eyelashes_' + DEFAULT_SHADERS['eyelashes'] + '.ma'
    shaderFile = os.path.join(pm.workspace.name, 'renderData', shaderFile)
    try:
        pm.importFile(shaderFile,
                      ra=1,
                      mergeNamespacesOnClash=0,
                      namespace="cgfx")
    except:
        pm.error("Didnt find eyelashes file")
        return

    cgfxShader = pm.ls('cgfx:*', type='cgfxShader')[0]
    cgfxSG = pm.ls('cgfx:*', type='shadingEngine')[0]

    eyelashes = pm.ls('*Eyelashes')[0]
    pm.select(eyelashes)
    command = "sets -e -forceElement " + cgfxSG
    pm.mel.eval(command)

    #pm.sets( e=True, forceElement= cgfxSG )

    removeNamespace()
示例#9
0
    def importFile(self):
        ''' 리그파일 임포트 '''
        # 씬에 이미 원하는 노드가 존재하는지 검사
        if self.isExists():
            raise AttributeError(u"씬에 이미 노드가 존재합니다.")

        # 변수 간단화
        filePath = self.getFilePath()
        prefix = self.getPrefix()

        # 파일 존재유무 검사
        if not os.path.exists(filePath):
            raise AttributeError(u'%s 파일이 존재하지 않아요 : ' + filePath)

        # 파일 임포트
        if prefix:
            pm.importFile(filePath,
                          returnNewNodes=True,
                          renameAll=True,
                          renamingPrefix=prefix)
        else:
            pm.importFile(filePath, returnNewNodes=True)

        # 임포트된 노드 등록
        self.registNode()
示例#10
0
def loadTranslationControl(root_joint, module_name, container, module_control_grp, control_type = "translation", color = [1, 0, 0]):
    """ loads translation control onto the root_joint """

    path = os.path.join(environ.ControlObjectsPath, "translation_control.ma")
    pm.importFile(path, renameAll = True, loadReferenceDepth = "all", namespace =":")  # renamePrefix == namespace

    # rename default module
    translation_control = pm.rename("translation_control", module_name + ":" + root_joint.stripNamespace() + "_translation_control", ignoreShape = False)
    translation_control_grp = pm.group(translation_control, name = module_name + ":" + root_joint.stripNamespace() + "_translation_controlGrp")

    # move control to root root_joint
    pm.delete(pm.pointConstraint(root_joint, translation_control_grp, maintainOffset=False))

    translation_control_grp.setParent(module_control_grp)

    pm.addAttr(translation_control, longName="ControlType", dataType="string", keyable=False)
    pm.addAttr(translation_control, longName="ParentObject", at="message", multi = True)
    translation_control.ControlType.set(control_type, type = "string", lock = True)


    utils.addNodeToContainer(container, [translation_control, translation_control_grp], ihb = True, includeNetwork = True)
    pm.container(container, edit=True, publishAndBind=[translation_control + ".rotate", translation_control.stripNamespace() + "_rotate"])
    pm.container(container, edit=True, publishAndBind=[translation_control + ".translate", translation_control.stripNamespace() + "_translate"])

    return translation_control, translation_control_grp
示例#11
0
    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)
示例#12
0
	def bdImportFile(self,objFile):
		print 'Importing'
		objPath = os.path.join(self.path,objFile )
		pm.importFile(objPath ,namespace= 'tempObj')
		mesh = pm.ls('tempObj:*',type='mesh')[0].getParent()
		print mesh
		mesh.rename(objFile.split('.')[0])
		removeNamespace()
示例#13
0
def ImportFixScene(Path):
    pm.importFile(Path,
                  ignoreVersion=True,
                  ra=True,
                  mergeNamespacesOnClash=True,
                  namespace=":",
                  importFrameRate=False,
                  f=True)
示例#14
0
 def importCgfxShader(self):
     shaderFile = os.path.join(pm.workspace.name, 'scenes/cgfxShader.ma')
     pm.importFile(shaderFile,
                   ra=1,
                   mergeNamespacesOnClash=0,
                   namespace="cgfx")
     removeNamespace()
     cgfxShader = pm.ls('cgfx_*')[0]
     return cgfxShader
示例#15
0
 def load_model(self, model=Model()):
     """
     imports the model into maya using the model's path attribute
     """
     # check if model is member of list, check if present in path
     if model in self.model_list and os.path.exists(model.path):
         pmc.importFile(model.path)
     else:
         pmc.displayWarning('Model is not a member of model list...')
示例#16
0
    def menuItemClicked_import(self):
        """
        import to maya
        Returns:

        """
        file_path = str(self.listWidget.currentItem().toolTip())
        # print file_path
        pm.importFile(file_path)
示例#17
0
def import_range_of_motion(main_net):
    pymel.select(main_net.getLimbCtrls())

    path = os.path.join(siteCustomize.ROOT_DIR, 'animations', 'rom.atom')
    try:

        pymel.importFile(path, type='atomImport')
    except:
        pass
示例#18
0
    def createRig(self):
        # 이미 리그가 존재하는지 확인
        if self.isRigExists():
            raise AttributeError(u"조인트가 이미 존재합니다.")

        # 존재하지 않으면 파일 임포트, PyNode로 리턴됨
        #nodes = pm.importFile( self.rigFile, returnNewNodes = True )
        #pm.importFile( self.rigFile, returnNewNodes = True, renameAll = True, renamingPrefix = "eyeL" )
        pm.importFile(self.rigFile, returnNewNodes=True)
示例#19
0
    def addObjMorphs(self):
        morphPath = os.path.join(
            os.path.split(self.fbxFile)[0], 'blendshapes/')
        morphFiles = [
            f for f in os.listdir(morphPath)
            if f.endswith('.obj') and 'default' not in f
        ]
        meshesVtxCount = {}
        meshes = pm.ls(type='mesh')
        for m in meshes:
            if 'Orig' not in m.name() and 'rg' not in m.name():
                meshesVtxCount[m.name()] = pm.polyEvaluate(m, v=1)
        print meshesVtxCount

        if morphFiles:
            self.hasMorphs = 1
            bsNode = ''
            bsCreated = 0
            bsEntry = 0

            for obj in morphFiles:
                speakName = obj.split('.')[0]
                speakName = 'speak_' + speakName
                pm.importFile(morphPath + obj, namespace='morph')
                morph = pm.ls('morph:*', type='mesh')[0]
                morph.rename(speakName)
                morphVtxCount = pm.polyEvaluate(morph, v=1)

                for mesh, count in meshesVtxCount.iteritems():
                    print mesh, count
                    if count == morphVtxCount:
                        rigMesh = [pm.ls(mesh, type='mesh')[0].getParent()]
                        skinCls = pm.listConnections('%s.inMesh' %
                                                     rigMesh[0].getShape())[0]

                        if not bsCreated:
                            print 'creating blendshape'
                            bsNode = pm.blendShape(rigMesh,
                                                   name='speak_BS')[0].name()
                            pm.reorderDeformers(skinCls.name(), bsNode,
                                                rigMesh[0].name())
                            pm.blendShape(bsNode,
                                          e=1,
                                          t=(rigMesh[0].name(), bsEntry,
                                             morph.name(), 1))
                            bsCreated = 1
                        else:
                            print 'adding blendshape'
                            pm.blendShape(bsNode,
                                          e=1,
                                          t=(rigMesh[0].name(), bsEntry,
                                             morph.name(), 1))
                pm.delete(morph)
                bsEntry += 1

                removeNamespace()
示例#20
0
    def import_maya(self):
        ma_file = self.parent.assets_data["MAPath"]
        mb_file = self.parent.assets_data["MBPath"]
        maya_file = ma_file
        if not maya_file:
            maya_file = mb_file

        self.close()
        pm.importFile(os.path.join(self.parent.parent.root_path, maya_file))
        dy.MMessage.success("import success!", self.parent.parent)
示例#21
0
    def import_(self, version):
        """Imports the content of the given Version instance to the current
        scene.

        :param version: The desired
          :class:`~oyProjectManager.models.version.Version` to be imported
        """
        pm.importFile(version.full_path)

        return True
示例#22
0
def importCamera(*a):
    cam_path = getAnimPath('Fbx', '', 0, 1, override_name='cam')

    fbx_file = pm.fileDialog2(fm=1, dir=cam_path)[0]
    
    if fbx_file:
        pm.importFile(fbx_file, defaultNamespace=True)
        return
    else:
        return
示例#23
0
    def import_(self, version):
        """Imports the content of the given Version instance to the current
        scene.

        :param version: The desired
          :class:`~oyProjectManager.models.version.Version` to be imported
        """
        pm.importFile(version.full_path)

        return True
示例#24
0
def loadAdvancedShaders():
    '''
    '''
    # check if shader already loaded
    # check SHADER namespace or shading_layer
    removeAdvancedShaders()
    # delete if already loaded

    # load shader file
    # import shaders
    filepath = pm.fileDialog2(
        fm=1,
        cap='Choose advanced shader file',
        ff='mathilda_advanced_shaders.ma (mathilda_advanced_shaders.ma)')
    if filepath is None:
        pm.error('Shader file not provided.')
    pm.importFile(filepath[0], i=True, ns='SHADERS')

    # create renderlayer
    allGeoShapes = []
    bodyGeoGrp = pm.PyNode('RIG:GEO' + ':' + 'CT_geo_grp')
    faceGeoGrp = pm.PyNode('RIG:FACE:CT_mouth_geo_grp')
    for shape in bodyGeoGrp.getChildren(ad=True, s=True):
        if 'simple' not in shape.name():
            allGeoShapes.append(shape)
    for shape in faceGeoGrp.getChildren(ad=True, s=True):
        allGeoShapes.append(shape)
    allGeoShapes.append('RIG:frontHair_pfx')
    allGeoShapes.append('RIG:backHair_pfx')
    layer = pm.createRenderLayer(allGeoShapes, n='advanced_shading')
    pm.editRenderLayerGlobals(crl=layer)

    # get all advanced shaders
    allSGs = pm.ls(type='shadingEngine')
    advSGs = filter(lambda sg: 'SHADERS' in sg.namespaceList(), allSGs)

    # transfer SGs on masterLayer first
    masterLyr = pm.PyNode('defaultRenderLayer')
    for sg in advSGs:
        transferSG(sg, 'SHADERS' + ':', 'RIG:', masterLyr, layer)

    # transfer SGs on advanced_shading
    # this should override masterLayer
    advLyr = pm.PyNode('SHADERS' + ':' + 'advanced_shading')
    for sg in advSGs:
        transferSG(sg, 'SHADERS' + ':', 'RIG:', advLyr, layer)

    # clean up imported data
    importedGeo = pm.PyNode('SHADERS' + ':' + 'CT_shaders_geo_grp')
    pm.delete(importedGeo)
    pm.delete(advLyr)

    # add subdivApprox node
    approxNode = createSubdivApproxNode()
    assignApproxNode(approxNode, [bodyGeoGrp, faceGeoGrp])
示例#25
0
    def menuItemClicked_import(self):
        """
        import to maya
        Returns:

        """
        file_path = str(self.listWidget.currentItem().toolTip())
        print(file_path)
        self.playblast_filename = file_path
        # self.playblast_picture()
        pm.importFile(file_path)
示例#26
0
 def addToScene(self):
     """
     Import the camera to the scene
     :return:
     """
     item = self.getItem()
     componentPath = item.getPublishPath()
     pm.namespace(add=':cam')
     pm.importFile(componentPath, ns='cam')
     self.wrapData()
     self.renameToScene()
示例#27
0
 def import_fbx(self, nothing):
     """Import a FBX
     """
     fbx_filter = "FBX (*.fbx)"
     fbx = pm.fileDialog2(fileFilter=fbx_filter,
                          caption='Import FBX',
                          okCaption='Import',
                          fileMode=1)
     if fbx:
         pm.displayInfo("Importing: {fbx}".format(fbx=fbx))
         pm.importFile(fbx[0])
示例#28
0
 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"
     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)
示例#29
0
    def importMa(self):

        selectItem = self.listFilewg.selectedItems()[0]
        path = os.path.dirname(str(self.outPathLineEditer.text()))
        mafile = path + '/' + selectItem.text() + '.ma'
        if os.path.isfile(mafile):
            pm.importFile(str(mafile))
            inputText = 'import ma file\n' + mafile
            self.logLabel.setText(inputText)
        else:
            inputText = 'import ma file\nma file ??????'
            self.logLabel.setText(inputText)
示例#30
0
 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"
     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)
示例#31
0
 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
示例#32
0
def create_curve(name=None, typ=None, scale=None,
                 color=None, reg_node=None):
    '''Create a control curve

    Attributes:
        name -- PRefix name to be used
        typ -- Type of control: circle, pointed_circle, square, cube. Str
        scale -- Float
        color -- Name of color to use
        reg_node -- Reg node to use instead of creating one
    '''
    general.check_type(name, 'name', [str])
    general.check_type(typ, 'typ', [str])
    general.check_type(scale, 'scale', [float])
    general.check_type(color, 'color', [str])
    if reg_node:
        general.check_type(reg_node, 'reg_node', [pm.nt.Transform])

    if typ not in types:
        errors.InputError('typ', typ, [types])

    if color not in colors.keys():
        errors.InputError('color', color, colors.keys())

    try:
        f = os.path.dirname(__file__) +\
            os.path.sep + 'maya_files' + os.path.sep + '%s.ma' % typ
        pm.importFile(f, defaultNamespace=True)
    except:
        raise errors.BuildError('create_curve', 'Failed to open: %s' % f)

    try:
        pm.select('%s' % typ, r=True)
        cnt = pm.ls(sl=1)[0]
    except:
        raise errors.BuildError('create_curve', 'Failed to select control')

    for s in cnt.getShapes():
        s.overrideEnabled.set(1)
        s.overrideColor.set(colors[color])
    cnt.scale.set([scale, scale, scale])
    cnt.rename(name)

    if not reg_node:
        try:
            pm.select('%s_reg_node' % name, r=1)
            reg_node = pm.ls(sl=1)[0]
        except:
            reg_node = create_register_node(name)

    register_object(reg_node, name, cnt)

    return reg_node, cnt
示例#33
0
def loadAdvancedShaders():
    '''
    '''
    # check if shader already loaded
    # check SHADER namespace or shading_layer
    removeAdvancedShaders()
    # delete if already loaded
    
    # load shader file
    # import shaders
    filepath = pm.fileDialog2(fm=1, cap='Choose advanced shader file', ff='mathilda_advanced_shaders.ma (mathilda_advanced_shaders.ma)')
    if filepath is None:
        pm.error('Shader file not provided.')
    pm.importFile(filepath[0], i=True, ns='SHADERS')
    
    # create renderlayer
    allGeoShapes = []
    bodyGeoGrp = pm.PyNode('RIG:GEO'+':'+'CT_geo_grp')
    faceGeoGrp = pm.PyNode('RIG:FACE:CT_mouth_geo_grp')
    for shape in bodyGeoGrp.getChildren(ad=True, s=True):
        if 'simple' not in shape.name():
            allGeoShapes.append(shape)
    for shape in faceGeoGrp.getChildren(ad=True, s=True):
        allGeoShapes.append(shape)
    allGeoShapes.append('RIG:frontHair_pfx')
    allGeoShapes.append('RIG:backHair_pfx')
    layer = pm.createRenderLayer(allGeoShapes, n='advanced_shading')
    pm.editRenderLayerGlobals(crl=layer)
    
    # get all advanced shaders
    allSGs = pm.ls(type='shadingEngine')
    advSGs = filter(lambda sg: 'SHADERS' in sg.namespaceList(), allSGs)
    
    # transfer SGs on masterLayer first
    masterLyr = pm.PyNode('defaultRenderLayer')
    for sg in advSGs:
        transferSG(sg, 'SHADERS'+':', 'RIG:', masterLyr, layer)
        
    # transfer SGs on advanced_shading
    # this should override masterLayer
    advLyr = pm.PyNode('SHADERS'+':'+'advanced_shading')
    for sg in advSGs:
        transferSG(sg, 'SHADERS'+':', 'RIG:', advLyr, layer)
        
    # clean up imported data
    importedGeo = pm.PyNode('SHADERS'+':'+'CT_shaders_geo_grp')
    pm.delete(importedGeo)
    pm.delete(advLyr)
    
    # add subdivApprox node
    approxNode = createSubdivApproxNode()
    assignApproxNode(approxNode, [bodyGeoGrp, faceGeoGrp])
示例#34
0
 def importFile(self):
     namespaces = self.namespaces_LE.text()
     project = self.project_comboBox.currentText()
     char = self.characters_LW.currentItem().text()
     setup = self.expSetups_LW.currentItem().text()
     path = setupPathRoot + '\\' + project + '\\' + char + '\\' + setup
     if not os.path.exists(path):
         raise RuntimeError('{0} path is dose not exist'.format(self.path))
     pm.importFile(path,
                   type="mayaAscii",
                   pr=True,
                   namespace=namespaces[:-1],
                   mergeNamespacesOnClash=False)
示例#35
0
def applyShaders(shader_file='C:/Users/Darrick/Documents/Maya/projects/_UE4-Chars/assets/G8_MATS.ma'):

    if not pm.ls('MAT_Skin'):
        pm.importFile(shader_file)

    shader_map = {
        'MAT_Skin': pm.ls('Mesh', recursive=True),
        'MAT_Eyelash': pm.ls('FacEyelash', recursive=True)[0].members(),
        'MAT_EyeSurf': pm.ls('FacEyeSurf', recursive=True)[0].members()
    }

    for shader, faces in shader_map.items():
        pm.select(faces)
        pm.hyperShade(assign=shader)
示例#36
0
    def addSliderSurface(self, name, parent, position=None):
        """pass."""
        if name not in self.tra.keys():
            self.tra[name] = transform.getTransformFromPos(position)

        pm.importFile(
            os.path.join(os.path.dirname(__file__), "assets", "surface.ma"))
        sliding_surface = pm.PyNode("sliding_surface")
        pm.rename(sliding_surface, self.getName("sliding_surface"))

        sliding_surface.setTransformation(self.tra[name])
        pm.parent(sliding_surface, parent)

        return sliding_surface
def importAbcFile():
    importFilePath=pm.textField('path_ABC2', q=True, text=True)
    #.abc를 없애준다
    filePathDeletAbc = importFilePath.replace('.abc','')

    pm.importFile( filePathDeletAbc+'.ma' )
    importAbc( filePathDeletAbc+'.abc' )
    connectionsTxtFile_open = open(filePathDeletAbc+'.txt')
    import pickle
    lst = pickle.load(connectionsTxtFile_open)
    print lst
    for geo, shd in lst:
        cmds.select( geo )
        cmds.hyperShade( assign=shd )
示例#38
0
def biped():
    ''' 조인트 템플릿을 로드함 '''
    # \\alfredstorage\Alfred_asset\Maya_Shared_Environment\scripts_Python\alfredRig\file\
    #
    # RigTemplate_biped_Michael6HD.ma
    # RigTemplate_biped_Victoria6HD.ma
    # RigTemplate_biped_dazGen2.ma

    p = __file__.split('\\')
    p = p[:-1] + ['file/RigTemplate_biped_Michael6HD.ma']
    ma = '/'.join(p)
    
    print ma.replace('/','\\')
    
    pm.importFile(ma)
示例#39
0
 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)
示例#40
0
def load_geofile(filepath):
    try:
        imported_nodes = pm.importFile(filepath, i=True, returnNewNodes=True)
        # print imported_nodes
    
        relevant_nodes = []
        trash = []
        for node in imported_nodes:
            print node, 'TYPE', node.type()
            if node.type() == 'mesh' or node.type() == 'transform':
                relevant_nodes.append(node)
                print '> append', node
            else:
                trash.append(str(node.name()))
                
        # seems like a bug in pymel, materials et al must be
        # explicitly deleted by string name with cmds
        for item in trash:
            try:
                cmds.delete(item)
            except ValueError:
                pass 
            
        for node in relevant_nodes:
            if node.getParent() is None:
                return node 
                
    except RuntimeError:
        print "> unreadable:", filepath
        return False
 def CreateTemporaryGroupRepresentation(self):
     #controlGrpFile = "%s/ControlObjects/Blueprint/controlGroup_control.ma" %self.directory
     controlGrpFile = "%s/ControlObjects/Blueprint/controlGroup_control.ma" %os.environ["RIGGING_TOOL_ROOT"]
     
     pm.importFile(controlGrpFile)
     
     self.tempGroupTransform = pm.rename("controlGroup_control", "Group__tempGroupTransform__")
     
     pm.connectAttr("%s.scaleY" %self.tempGroupTransform, "%s.scaleX" %self.tempGroupTransform)
     pm.connectAttr("%s.scaleY" %self.tempGroupTransform, "%s.scaleZ" %self.tempGroupTransform)
     
     for attr in ['scaleX', 'scaleZ', 'visibility']:
         pm.setAttr("%s.%s" %(self.tempGroupTransform, attr), lock = True, keyable = False)
     
     
     pm.aliasAttr('globalScale', "%s.scaleY" %self.tempGroupTransform)
示例#42
0
 def import_face_cam(self, *args):
     self.log.insertText("  %s" %("Import face cam".ljust(40,'.')))
     
     if not pm.objExists('Face_Cam') and not pm.objExists("FaceCam"):
         face_cam_file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'planes_face_cam.ma'))        
         pm.importFile(face_cam_file_path)
         
         self.face_cam = pm.PyNode("Face_Cam")
         
         grp = self.face_cam.getParent()
         pm.parent(grp, "Body", r=True)
         grp.translateZ.set(15)
         
         self.log.insertText("OK\n")
     else:
         self.log.insertText("EXISTS\n")
示例#43
0
 def addObjMorphs(self):
     morphPath = os.path.join(os.path.split(self.fbxFile)[0], 'blendshapes/')
     morphFiles = [f for f in os.listdir(morphPath) if f.endswith('.obj') and 'default' not in f ]
     meshesVtxCount = {}
     meshes = pm.ls(type='mesh')
     for m in meshes:
         if 'Orig' not in m.name() and 'rg' not in m.name():
             meshesVtxCount[m.name()] = pm.polyEvaluate(m,v=1)
     print meshesVtxCount
     
     if morphFiles:
         self.hasMorphs = 1
         bsNode = ''
         bsCreated = 0
         bsEntry =0
         
         for obj in morphFiles:
             speakName = obj.split('.')[0]
             speakName = 'speak_' + speakName
             pm.importFile(morphPath + obj,namespace= 'morph')
             morph = pm.ls('morph:*',type='mesh')[0]
             morph.rename(speakName)
             morphVtxCount = pm.polyEvaluate(morph,v=1)
             
             
             for mesh, count in meshesVtxCount.iteritems():
                 print mesh, count
                 if count == morphVtxCount:
                     rigMesh = [pm.ls(mesh,type='mesh')[0].getParent()]
                     skinCls = pm.listConnections('%s.inMesh'%rigMesh[0].getShape())[0]
 
                     
                     if not bsCreated:
                         print 'creating blendshape'
                         bsNode = pm.blendShape(rigMesh,name='speak_BS')[0].name()
                         pm.reorderDeformers(skinCls.name(),bsNode,rigMesh[0].name())
                         pm.blendShape(bsNode,e=1,t=(rigMesh[0].name(), bsEntry , morph.name(), 1))
                         bsCreated = 1
                     else:
                         print 'adding blendshape'
                         pm.blendShape(bsNode,e=1,t=(rigMesh[0].name(), bsEntry , morph.name(), 1))
             pm.delete(morph)
             bsEntry += 1
 
 
 
             removeNamespace()
示例#44
0
def importCgfxShader(material):
    '''
    Based on the material name , the proper cgfx material is imported with the desired version ( default version is 01)
    
    Add more entries for if elif in case more parts are added
    '''
    print material
    shaderFile = ''
    if 'body' in material.name().lower():
        shaderFile = 'shader_skin_' + DEFAULT_SHADERS['skin'] + '.ma'
    elif 'hair' in material.name().lower():
        shaderFile = 'shader_hair_' + DEFAULT_SHADERS['hair'] + '.ma'
    elif 'bottom' in material.name().lower():
        shaderFile = 'shader_cloth_' + DEFAULT_SHADERS['cloth'] + '.ma'
    elif 'glove' in material.name().lower():
        shaderFile = 'shader_cloth_' + DEFAULT_SHADERS['cloth'] + '.ma'
    elif 'hat' in material.name().lower():
        shaderFile = 'shader_cloth_' + DEFAULT_SHADERS['cloth'] + '.ma'
    elif 'shoes' in material.name().lower():
        shaderFile = 'shader_cloth_' + DEFAULT_SHADERS['cloth'] + '.ma'
    elif 'top' in material.name().lower():
        shaderFile = 'shader_cloth_' + DEFAULT_SHADERS['cloth'] + '.ma'
    elif 'eyes' in material.name().lower():
        shaderFile = 'shader_eyes_' + DEFAULT_SHADERS['eyes'] + '.ma'
    elif 'eyewear' in material.name().lower():
        shaderFile = 'shader_cloth_' + DEFAULT_SHADERS['cloth'] + '.ma'

    shaderFile = os.path.join(pm.workspace.name,'renderData',shaderFile)
    print shaderFile
    try:
        pm.importFile(shaderFile,ra=1,mergeNamespacesOnClash=0,namespace="cgfx")
    except:
        pm.error("Didn't find the shader file, aborting")
        return
    

    cgfxShader = pm.ls('cgfx:*',type = 'cgfxShader')[0]

    cgfxSG = pm.ls('cgfx:*',type = 'shadingEngine')[0]
    pm.delete (cgfxSG )
    #cgfxSG.rename(material.name().lower().replace('mat', '_cgfx_SG'))
    
    cgfxShader.rename(material.name().lower().replace('mat', '_shd'))

    removeNamespace()
    return cgfxShader 
示例#45
0
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
示例#46
0
def importCurve(crvName):
    ''' Import curve '''
    pymelLogger.debug('Starting: importCurve()...')
    
    # checkfile exists
    # import file into scene
    path = templates + crvName + '.ma'
    if os.path.exists( path ): 
        pm.importFile( path ) 
        # return crv pm obj
        crv = pm.ls(crvName,r=1)[0]
        pymelLogger.debug('End: importCurve()...')
        return crv
    else: return invalidFile
        
    

    
    
示例#47
0
def lcObj_importMultiple(*args, **kwargs):
  ''' select multiple .obj's and import them into the scene with best settings '''

  path = pm.textField(prefix+'_textField_export_path', query=True, text=True)
  filter = "Wavefront Obj (*.obj)"
  files = pm.fileDialog2(ds=1, caption="Choose one or more Obj's to import", dir=path, fileFilter=filter, fileMode=4)
  if files:
    for obj in files:
      name = obj.split('/')[-1].split('.')[0]
      importedObj = pm.importFile(obj, type='OBJ', options='mo=0')
示例#48
0
	def bdImportController(self,n):
		con = self.conList[n]
		animConName = self.bdGetConName()
		overrideColor = self.conColors[str(self.inputConSide.currentText())]
		conSize = self.inputConSize.text()
		
		selection = pm.ls(sl = True)
		selPos = [0,0,0]
		selRot = [0,0,0]
		
		
		if selection:
			selPos = selection[0].getTranslation(space='world')
			selRot = selection[0].getRotation(space='world')		

		if not conSize:
			conSize=1		
		
		
		if animConName != '':		
			scriptPath = os.path.dirname(__file__)
			conFile = scriptPath + '/controllers/' + con + '.ma'
			conTransform = [f for f in pm.importFile(conFile,returnNewNodes=True,namespace='temp') if f.type()=='transform'][0]
			#conTransform = pm.importFile( conFile,returnNewNodes=True,namespace='temp') 
			sceneNS = pm.namespaceInfo(lon=True,r=True)
			importNS = []
			for ns in sceneNS:
				if 'temp' in ns:
					importNS.append(ns)
			importNS.reverse()
			
			for ns in importNS:
				pm.namespace( rm = ns,mergeNamespaceWithRoot=True) 			
			
			print conTransform 
			
			conTransform.rename(animConName)
			conTransformChidlren = conTransform.getChildren(ad=True,type='transform')
			
			for child in conTransformChidlren :
				child.rename(str(self.inputConSide.currentText()) + child.name())
				
			scaleVector = om.MVector(1,1,1) * float(conSize)
			conTransform.setScale([scaleVector.x,scaleVector.y,scaleVector.z])
			pm.makeIdentity(conTransform,apply=True,t=0,r=0,s=1)
			
			for shape in conTransform.getChildren():
				shape.overrideEnabled.set(1)
				shape.overrideColor.set(overrideColor)
				
			conTransformGrp = pm.group(conTransform,name=conTransform.name() + '_GRP')
			conTransformGrp.setPivots([0,0,0])
			
			conTransformGrp.setTranslation(selPos,space='world')
			conTransformGrp.setRotation(selRot,space='world')
示例#49
0
 def switchToStandIn(renderGeometry):
     rndGeoName = (pm.ls(sl = 1)[0]).split('_Geo')
     rndAssName = str(rndGeoName[0]) + '_Ass'
     assList = []
     for geo in list: #export ass from selected group 
         
         assName = geo + assVer
         assExport = os.path.join(sPath, assDir, assName ).replace('\\' , '/')
         mayaSmoothOff(geo)
         pm.select(geo)
         pm.hyperShade(assign= 'lambert1' )
         pm.exportSelected(assExport, force = 1)
         pm.importFile(assExport) #import ass and rename
         standIn = pm.PyNode('ArnoldStandIn')
         
         standIn.rename('ASS_' + geo)
         standIn.mode.set(0) #set standIn display mode
         copyMTOAAttr(geo,standIn) # copy mtoa attributes from render geo to standIn
         assList.append(standIn)
         standIn.translate.lock() # lock TRANSFORM for STANDIN
         standIn.rotate.lock()
     standInGRP = pm.group(assList, n = rndAssName)
     standInGRP.translate.lock()
     standInGRP.rotate.lock()
     pm.parent(standInGRP,asset)
     pm.parent(rndGeo, w=1) #Unparent Render geo
     pm.select(asset)
     if os.path.exists(SI(asset, siVer)):
         confirm = pm.confirmDialog ( title='File exists!', message = str(SI(asset, siVer)).split('/')[-1], 
                                      button=['OVERWRITE', 'CANCEL'],
                                      defaultButton= 'OVERWRITE',
                                      cancelButton= 'CANCEL',
                                      dismissString= 'CANCEL' )
         if confirm == 'OVERWRITE':
             siExport = pm.exportSelected(SI(asset, siVer), force = 1) #export SI file
             print 'ASSET OVERWRITEN TO: ' + str(siExport)
         else:
             print 'CANCELED!'
             sys.exit()
     else:
         siExport = pm.exportSelected(SI(asset, siVer), force = 1) #export SI file
         print 'ASSET CONVERTED TO: ' + str(siExport)
示例#50
0
    def replaceGeometry(self):

        fbxPath = os.path.split(self.fbxFile)[0]
        defaultMeshPath = os.path.join(fbxPath,'blendshapes/')

        meshes = pm.ls(type='mesh')
        meshesShaders = {}

        for m in meshes:
            if 'Orig' not in m.name():
                shader = pm.listConnections(m.name(),s=1,d=1,type = 'shadingEngine')
                if shader:
                    meshesShaders[str(m.name())] = str(shader[0].name())

        print meshesShaders

        morphFiles = [f for f in os.listdir(defaultMeshPath) if f.endswith('.obj')]
        print morphFiles 
        if 'default.obj' in morphFiles:
            print 'Found default'

            pm.importFile(defaultMeshPath + 'default.obj',namespace= 'tpose')
            importMeshes = pm.ls('tpose:*',type='mesh')

            for m in importMeshes:
                if 'Orig' not in m.name():
                    sourceMesh = m.name().split(':')[1]
                    pm.select(m)
                    pm.mel.eval('sets -e -forceElement ' + meshesShaders[sourceMesh])
                    pm.substituteGeometry(sourceMesh,m)


            removeNamespace()

        meshes = pm.ls(type='mesh')

        for m in meshes:
            if 'Orig' not in m.name():
                skinCls = pm.listConnections('%s.inMesh'%m)
                if len(skinCls)==0:
                    print m
                    pm.rename(m.getParent(),'rg_' + m.getParent().name())
示例#51
0
def attachToBody():
    '''
    Connect a head to a body. Run inside the body rig.
    
    Example:
        import sys
        path = '/Users/3mo/Documents/repos/artpipeline/maya/RigBuilder/modules'
        if path not in sys.path:
            sys.path.insert(0, path)
        
        import Head as head
        reload( head )
        
        head.attachToBody()
    '''
    # Get head rig file from user, Import file
    try:
        pm.importFile( pm.fileDialog(t='Select Head Rig file') )
    except Exception,e:
        raise Exception(e)
示例#52
0
def alphaCmd(*arg):
    select_mesh=pm.selected()
    
    print pm.objExists('aiMatteSet:Matte' )

    if pm.objExists('aiMatteSet:Matte' )==False:
        #pm.namespace(rm='aiMatteSet',deleteNamespaceContent =True)
        print "improt file"
        pm.importFile( "//ALFREDSTORAGE/Alfred_asset/Maya_Shared_Environment/scripts_Python_old/aiMatte.ma", type = "mayaAscii",namespace="aiMatteSet")
    else:
        pass
    nodes=pm.select(select_mesh)
    for node in select_mesh:
        shape = node.getShape()
        cmds.sets(addElement=shape,add='aiMatteSet:Matte')

    for i in range(0,100):
        if pm.namespace(exists='aiMatteSet'+str(i)):
            pm.namespace(rm='aiMatteSet'+str(i),deleteNamespaceContent =True)
        else:
            pass
示例#53
0
def file_importer(file, *args):
	'''Imports a file cleanly and returns the top-level transform nodes from the file
	Args:
		file (string): filepath
	Returns (boolean): top-level transforms from the file if success, None if file not found
	Usage:
		file_importer('/jobs/deltaSafetyVideo2015_5402704/build/charBaby/release/work/rigSkeleton/evianBaby/vLatest/deltaSafetyVideo2015_5402704_build_charBaby_rigSkeleton_evianBaby_vLatest.ma') 
	'''
	if os.path.exists(file):
		filename, extension = os.path.splitext(file)
		extension_lt = {'.ma':'mayaAscii',
						'.mb':'mayaBinary'}
		pm.importFile(file, type=extension_lt[extension], i=True, rpr="clashNode_", gr=True,
					  groupName='tmp_GRP',options='v=0',pr=True, loadReferenceDepth='all')
		tmpGrp = pm.PyNode('tmp_GRP')
		topGroups = tmpGrp.listRelatives(c=True,type='transform')
		for topGroup in topGroups:
			topGroup.setParent(world=True)
		pm.delete(tmpGrp)
		return topGroups
	else:
		return None
def importLight(path="Z:/Proj/SENBA/Senba_link/Render/chr_light/chr_light.mb"):
    # chr_color层需要导入默认灯光
    #
    # 参数path: 要导入的文件的路径
    #
    # 返回值是导入的对象列表
    kx = kxTool.KXTool()
    kx.getSceneName()
    kx.analyzeSceneName()
    if kx.projectName:
        path = kx.chr_light_pathDic[kx.projectName]
    importNode = pm.importFile(path, returnNewNodes=1)
    return importNode
示例#55
0
def loadModuleControl(root_joint, module_name, container, control_type = "module"):
    """ loads module control onto the root root_joint """


    path = os.path.join(environ.ControlObjectsPath, "module_control-01.ma")
    pm.importFile(path, renameAll = True, loadReferenceDepth = "all", namespace =":")  # renamePrefix == namespace

    # rename default module
    module_control = pm.rename("module_control", module_name + ":module_control", ignoreShape = False)
    # move control to root root_joint
    pm.delete(pm.pointConstraint(root_joint, module_control, maintainOffset=False))


    # connect scaleX and scaleZ to scaleY
    pm.connectAttr(module_control + ".sy", module_control + ".sx")
    pm.connectAttr(module_control + ".sy", module_control + ".sz")

    # rename module control scale y to global scale
    pm.aliasAttr("GlobalScale", module_control + ".sy")
    # lock scale x and z
    module_control.setAttr("sx", lock=True, keyable=False, channelBox=False)
    module_control.setAttr("sz", lock=True, keyable=False, channelBox=False)


    pm.addAttr(module_control, longName="ControlType", dataType="string", keyable=False)
    module_control.ControlType.set(control_type, type = "string", lock = True)


    '''
    utils.addNodeToContainer(container, module_control, ihb = True)
    pm.container(container, edit=True, publishAndBind=[module_control + ".translate", module_control.stripNamespace() + "_translate"])
    pm.container(container, edit=True, publishAndBind=[module_control + ".rotate", module_control.stripNamespace() + "_rotate"])
    pm.container(container, edit=True, publishAndBind=[module_control + ".scale", module_control.stripNamespace() + "_globalScale"])
    '''


    return module_control
示例#56
0
def createEyelashesShader():
    '''
    Creates the eyelashes shader, will be the only shader with a png file assigned to it 
    '''
    shaderFile = 'shader_eyelashes_' + DEFAULT_SHADERS['eyelashes'] + '.ma'
    shaderFile = os.path.join(pm.workspace.name,'renderData',shaderFile)
    try:
        pm.importFile(shaderFile,ra=1,mergeNamespacesOnClash=0,namespace="cgfx")
    except:
        pm.error("Didnt find eyelashes file")
        return

    cgfxShader = pm.ls('cgfx:*',type = 'cgfxShader')[0]
    cgfxSG = pm.ls('cgfx:*',type = 'shadingEngine')[0]

    
    eyelashes = pm.ls('*Eyelashes')[0]
    pm.select(eyelashes)
    command = "sets -e -forceElement " + cgfxSG;
    pm.mel.eval(command)

    #pm.sets( e=True, forceElement= cgfxSG )
    
    removeNamespace()
示例#57
0
文件: test.py 项目: loichuss/maya
 def importFiles(self, i=-1):
     """Proceed the importation"""
    
     # check if user choose a group
     if self._grp:
         if pmc.objExists(self._grp.name()):
             hasGrp = True
     else:
         hasGrp = False
        
    
     # set namespace if need
     currentNamespace = pmc.namespaceInfo(currentNamespace=True)
     if self._nameSpace:
         pmc.namespace(set=self._nameSpace)
    
     # import each file
     if i>-1:
         fil = [self._files[i]]
     else:
         fil = self._files
        
     for f in fil:
         objs = pmc.importFile(f, groupReference=hasGrp, returnNewNodes=True)
        
         if objs:
             if self.verbose:
                 print '\tINFO: Import file %s Done' % f
         else:
             if self.verbose:
                 print '\tERROR: Could not import file %s' % f
             continue
                
         if not self._grp:
             continue
        
         # parenting
         for child in objs[0].getChildren():
             child.setParent(self._grp)
        
         # delete main group
         pmc.delete(objs[0])
    
    
     # reset to previous namespace
     pmc.namespace(set=currentNamespace)