Ejemplo n.º 1
0
def shaderAssign(args, SG, renderLayer=None):
	for arg in args:
		if renderLayer==None:
			pm.hyperShade(arg, assign=SG)
		else:
			if pm.objExists(renderLayer):
				renderLayer = pm.PyNode(renderLayer)
				print 'Render Layer %s has %d shader assignments' % (renderLayer, len(list(renderLayer.outAdjustments.__iter__())))
				#if the arg's shape node instObjGroups isn't connected to the render layer, make the connection
				adjIndex = queryAttrConnectionIndex(arg.getShape(), 'instObjGroups[0]',renderLayer, 'outAdjustments', outPlug=True) or len(list(renderLayer.outAdjustments.__iter__()))
				dagIndex = queryAttrConnectionIndex( renderLayer, ('outAdjustments['+str(adjIndex)+']'), SG, 'dagSetMembers') or len(list(SG.dagSetMembers.__iter__()))
				dagShpIndex = queryAttrConnectionIndex( arg.getShape(), 'instObjGroups[0]', SG, 'dagSetMembers') or len(list(SG.dagSetMembers.__iter__()))
				print list(SG.dagSetMembers.__iter__())
				print adjIndex,dagIndex,dagShpIndex
				#connect the instObjGroups[0] to the first open .outPlug on the renderLayer
				arg.getShape().instObjGroups[0].connect(renderLayer.outAdjustments[adjIndex].outPlug,f=True)
				# determine if the dagSetMembers is connected to the shape node and the renderLayer
				arg.getShape().instObjGroups[0].connect(SG.dagSetMembers[dagShpIndex],f=True)
				renderLayer.outAdjustments[adjIndex].outValue.connect(SG.dagSetMembers[dagIndex],f=True)

				#if the arg isn't in the render layer, put it in there
				members= pm.editRenderLayerMembers( renderLayer, q=True)
				if members==None:
					pm.editRenderLayerMembers(renderLayer,arg)
				elif not arg in pm.editRenderLayerMembers( renderLayer, q=True ):
					print 'Adding %s to render layer %s' % (arg,renderLayer)
					pm.editRenderLayerMembers(renderLayer, arg)
			else: print 'Render Layer %s does not exist' % renderLayer
Ejemplo n.º 2
0
def loadShaders():
    
    print "Following shaders will be loaded and assigned to their saved shape :\n %s" % infos
    
    confirm = pc.confirmDialog( title='Confirm', message='Are you sure?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
    
    # We proceed
    if confirm == "Yes":
        
        # We loop over the different shaders
        for shaderName in infos.keys():
            
            exists = pc.ls(shaderName)
            print "Shader found: %s" % exists
            
            if len(exists) == 1:
                "Shader %s found, proceeding..." % shaderName
                
                # We clear the selection
                pc.select(cl=1)
                
                # We loop over the different shapes
                for shape in infos[str(shaderName)]:
                    pc.select(shape, add=True)
                    
                # Assign shader
                pc.hyperShade(assign=shaderName)
                
                # We clear the selection
                pc.select(cl=1)
Ejemplo n.º 3
0
def rtb_update_high_res_shader(highresListDropdown, *args, **kwargs):
    '''
    '''
    global defaultString

    sel = pm.ls(sl=True)
    high = highresListDropdown.getValue()

    inactiveShader = lcShader.ShaderNode('lcRetopo_Inactive', 'blinn')
    inactiveShader.create()
    inactiveShader.shader.color.set(0.45, 0.45, 0.45)
    inactiveShader.shader.specularColor.set(0.13, 0.3, 0.47)
    inactiveShader.shader.eccentricity.set(0.5)
    inactiveShader.shader.specularRollOff.set(0.7)

    activeShader = lcShader.ShaderNode('lcRetopo_Active', 'blinn')
    activeShader.create()
    activeShader.shader.color.set(0.65, 0.65, 0.65)
    activeShader.shader.specularColor.set(0.25, 0.55, 0.88)
    inactiveShader.shader.eccentricity.set(0.4)
    inactiveShader.shader.specularRollOff.set(0.55)

    for item in highresListDropdown.getItemListLong():
        meshItem = pm.menuItem(item, query=True, label=True)
        if meshItem != defaultString:
            pm.select(meshItem, replace=True)
            if meshItem == high:
                pm.hyperShade(
                    assign=activeShader.shader)  # assign shader to selection
            else:
                pm.hyperShade(
                    assign=inactiveShader.shader)  # assign shader to selection

    pm.select(sel, replace=True)
Ejemplo n.º 4
0
def saveShaders():
    # Prompt user with a string to search shader by names
    dialog = pc.promptDialog(title='Search joker',
                    message='Enter joker to find specific shaders :',
                    button=['OK', 'Cancel'],
                    defaultButton='OK',
                    cancelButton='Cancel',
                    dismissString='Cancel')
    
    joker = pc.promptDialog(query=True, text=True)
    
    # List shaders named that way
    listShaders = pc.ls(joker, exactType='aiStandard')
    
    
    for shader in listShaders:
         
        # This variable will contain all shape that have the current shader assigned
        shapeList = []
        
        # Select shapes with the current shader
        pc.hyperShade(o=shader)
        selectedShapes = pc.ls(sl=1)
        
        # Clear selection, just for clarity
        pc.select(cl=1)
        
        # Append the shape to the list
        for shape in selectedShapes:
            shapeList.append(str(shape))
        
        # Assign the list to the dictionnary with the key set to the shader name
        infos[str(shader)] = shapeList
        
    print "Saved informations :\n %s" % infos
Ejemplo n.º 5
0
 def Maya_replaceMaterial(self, mat1, mat2, *args):
     """Replace current material mat1 by another material mat2"""
     pc.hyperShade(o=mat1)
     test = pc.ls(sl=1)
     
     if len(test) > 0:
         pc.hyperShade(assign=mat2)
Ejemplo n.º 6
0
def rtb_create_retopo_shader():
    ''' '''
    global lct_cfg

    try:
        sel = [
            obj for obj in pm.ls(sl=True)
            if obj.getShape() and obj.getShape().nodeType() == 'mesh'
        ]
        pm.select(sel, replace=True)
    except:
        pm.warning('Please select some geometry')
        return

    retopoShader = lcShader.ShaderNode('lcRetopo', 'lambert')
    retopoShader.create()
    retopoShader.shader.color.set(0, 0, 1)

    retopoShader.shader.color.set(1, 0, 0)
    slider = lct_cfg.get('lcRetopoBasicShader')
    retopoShader.shader.transparency.set(slider, slider, slider)

    if sel:
        pm.select(sel, replace=True)  # grab the stored selection
        pm.hyperShade(
            assign=retopoShader.shaderName)  # assign shader to selection
Ejemplo n.º 7
0
def render(*args):
    global size, material_dir, textures_dir
    size = pm.intSliderGrp("baker_size", q=True, v=True)
    material_dir = pm.textField("baker_mat_dir", q=True, tx=True)
    textures_dir = pm.textField("baker_out_dir", tx=True, q=True)
    redshift_dir = os.path.join(pm.workspace(fn=True), "images")

    os.chdir(textures_dir)
    settings()

    selected = pm.selected(type="transform") or pm.ls(type="transform")
    selected = [sl for sl in selected if sl.listRelatives(type="mesh")]
    names = [mesh.name().split("|")[-1] for mesh in selected]
    pm.showHidden(selected)

    if pm.checkBox("baker_id", q=True, v=True):
        for mesh, mesh_name in zip(selected, names):
            bakeID(mesh, mesh_name + "_id")

    if pm.checkBox("baker_ao", q=True, v=True):
        pm.select(pm.ls(type="mesh"))
        pm.hyperShade(a="ao_material")
        for mesh, mesh_name in zip(selected, names):
            bake(mesh, mesh_name + "_ao.png")

    if pm.checkBox("baker_shadow", q=True, v=True):
        pm.select(pm.ls(type="mesh"))
        pm.hyperShade(a="shadow_material")
        for mesh, mesh_name in zip(selected, names):
            bake(mesh, mesh_name + "_shadow.png")

    if pm.checkBox("baker_mat", q=True, v=True):
        for mesh_name in names:
            bakeMaterials(mesh_name)
    pm.warning("finished")
Ejemplo n.º 8
0
def camera_focus_plane_tool():
    """sets up a focus plane for the selected camera
    """
    camera = pm.ls(sl=1)[0]
    camera_shape = camera.getShape()

    frame = pm.nurbsPlane(
        n='focusPlane#',
        p=(0, 0, 0), ax=(0, 0, 1), w=1, lr=1, d=1, u=1, v=1, ch=0
    )[0]
    frame_shape = frame.getShape()
    pm.parent(frame, camera, r=True)

    #transform the frame surface
    frame.tz.set(-10.0)

    exp = """float $flen = %(camera)s.focalLength;
    float $hfa = %(camera)s.horizontalFilmAperture * 25.4;
    %(frame)s.sx = -%(frame)s.translateZ * $hfa/ $flen;
    %(frame)s.sy = %(frame)s.sx / defaultResolution.deviceAspectRatio;
    %(camera)s.focusDistance = -%(frame)s.tz;
    %(camera)s.aiFocusDistance = %(camera)s.focusDistance;
    %(camera)s.aiApertureSize = %(camera)s.focalLength / %(camera)s.fStop * 0.1;
    """ % {
        'camera': camera_shape.name(),
        'frame': frame.name()
    }
    pm.expression(s=exp, ae=1, uc="all")

    # set material
    surface_shader = pm.shadingNode('surfaceShader', asShader=1)
    pm.select(frame)
    pm.hyperShade(a=surface_shader.name())

    surface_shader.setAttr('outColor', (0.4, 0, 0))
    surface_shader.setAttr('outTransparency', (0.5, 0.5, 0.5))

    # prevent it from being rendered
    frame_shape.setAttr('castsShadows', 0)
    frame_shape.setAttr('receiveShadows', 0)
    frame_shape.setAttr('motionBlur', 0)
    frame_shape.setAttr('primaryVisibility', 0)
    frame_shape.setAttr('smoothShading', 0)
    frame_shape.setAttr('visibleInReflections', 0)
    frame_shape.setAttr('visibleInRefractions', 0)

    # Arnold attributes
    frame_shape.setAttr('aiSelfShadows', 0)
    frame_shape.setAttr('aiVisibleInDiffuse', 0)
    frame_shape.setAttr('aiVisibleInGlossy', 0)

    # hide unnecessary attributes
    frame.setAttr('tx', lock=True, keyable=False)
    frame.setAttr('ty', lock=True, keyable=False)
    frame.setAttr('rx', lock=True, keyable=False)
    frame.setAttr('ry', lock=True, keyable=False)
    frame.setAttr('rz', lock=True, keyable=False)
    frame.setAttr('sx', lock=True, keyable=False)
    frame.setAttr('sy', lock=True, keyable=False)
    frame.setAttr('sz', lock=True, keyable=False)
Ejemplo n.º 9
0
def assignLambert(meshes=None, hueShift = 0.50, hsValue=0.3,rgb=None):
    """ Assigns a random lambert to a piece of geometry

        hueShift will allow divergence from the hsValue
        hsValue 0.0 is dark 0.5 is pastel and higher is ghostlike

    """
    # GET all of teh MESHES or just selected meshes
    objs = meshes or [x.getParent() for x in pm.ls(type="mesh",dag=True,sl=True)]

    # DON't DO ANYTHING IF THERE IS NOTHING SELECTED
    if not objs:
        return

    # GENERATE A RANGE OF COLORS THAT IS PLEASING
    startHueR = random.random() * hsValue + 0.5
    startHueG = random.random() * hsValue + 0.5
    startHueB = random.random() * hsValue + 0.5

    for mesh in objs:
        lamb = pm.shadingNode("lambert", asShader=True,name="tempLambert")
        sg = pm.sets(lamb,renderable=True, noSurfaceShader=True, empty=True, name='%sSG'%lamb)
        if rgb:
            r=rgb[0]
            g=rgb[1]
            b=rgb[2]
        else:
            r = returnNearHue(startHueR,hueShift)
            g = returnNearHue(startHueG,hueShift)
            b = returnNearHue(startHueB,hueShift)
        lamb.color.set(r,g,b)
        pm.select(mesh,r=True)
        pm.hyperShade(assign=lamb)
Ejemplo n.º 10
0
 def create_system(self):
     
     shader = pm.shadingNode('transmat', asShader= True)
     volume = pm.polyCube(name= 'fog_volume', width=40,
                                     height=40, depth=40)[0]
     
     pm.hyperShade(volume, assign= shader)
     
     parti_volume = pm.mel.eval('mrCreateCustomNode -asShader "" parti_volume;')
     pm.setAttr('%s.scatter' % (parti_volume), 1,1,1, type= 'double3' )
     
     pm.setAttr('%s.min_step_len' % (parti_volume), .03)
     pm.setAttr('%s.max_step_len' % (parti_volume), .2)
     
     pm.connectAttr('%s.outValue' % (parti_volume),
                    '%sSG.miVolumeShader' % (shader), force= True)
     
     light_node = pm.shadingNode('%s' % (self.light_types[value]),
                                                 asLight= True)
     light_node.translate.set(0,15,0)
     light_node.rotate.set(-90,0,0)
     light = pm.rename(light_node, 'fog_light')
     
     pm.connectAttr('%s.message' % (light.getShape()),
                             '%s.lights[0]' % (parti_volume), force= True)
     if self.checkBox.getValue() == 1:
         # mrCreateCustomNode -asUtility "" physical_light;
         # // Result: Connected physical_light1.message to fog_lightShape.mentalRayControls.miLightShader. // 
         phys_light = pm.mel.eval('mrCreateCustomNode -asUtility "" physical_light;')
         
         pm.connectAttr('%s.message' % (phys_light),
                  '%s.mentalRayControls.miLightShader' % (light.getShape()))
Ejemplo n.º 11
0
def CleanUpMod(asset):
    pm.select(asset)
    mel.eval('SelectHierarchy;')
    for i in pm.ls(sl=1, type='mesh'):
        for j in pm.listConnections(i, c=1, p=1, s=1):
            try:
                pm.disconnectAttr(j[0], j[1])
            except:
                pass
            try:
                pm.disconnectAttr(j[1], j[0])
            except:
                pass
    for i in pm.ls(sl=1, type='transform'):
        mel.eval('CenterPivot')
    pm.hyperShade(assign='initialParticleSE')

    unknown_plugins = pm.unknownPlugin(q=True, list=True)
    if unknown_plugins:
        for p in unknown_plugins:
            try:
                pm.unknownPlugin(p, r=True)
                print 'remove', p
            except:
                pass
    print 'Clean Done'
Ejemplo n.º 12
0
 def create_and_assign_shader(self):
     materials_type = {1:'mia_material_x', 2:'blinn', 3:'lambert',
                       4:'phong', 5:'rampShader', 6:'anisotropic',
                       7:'phongE', 8:'useBackground'}
     shader_name = self.text_field.getText()
     selected_material = self.option_menu.getSelect()
     
     geometry01 = self.shader_geo_scroll_list.getSelectItem()
     
     geometry02 = self.scene_geo_scroll_list.getSelectItem()
     
     
     
     
     created_shader = pm.shadingNode(materials_type[selected_material],
                             asShader= True, name= shader_name)
     
     
     
     for geometry in geometry01:
         pm.select(geometry)
         pm.hyperShade(geometry, assign='%s' % (created_shader))
         
         
     for geometry in geometry02:
         pm.select(geometry)
         pm.hyperShade(geometry, assign='%s' % (created_shader))
Ejemplo n.º 13
0
	def make_branch(self,h,w):
		print(w)
		i = pm.polyCylinder(height=h,radius=w)
		pm.select(i[0])
		pm.hyperShade(assign=self.branchShader)
		print("Constructed {} {} {}".format(i[0],h,w))
		return i
Ejemplo n.º 14
0
def camera_focus_plane_tool():
    """sets up a focus plane for the selected camera
    """
    camera = pm.ls(sl=1)[0]
    camera_shape = camera.getShape()

    frame = pm.nurbsPlane(
        n='focusPlane#',
        p=(0, 0, 0), ax=(0, 0, 1), w=1, lr=1, d=1, u=1, v=1, ch=0
    )[0]
    frame_shape = frame.getShape()
    pm.parent(frame, camera, r=True)

    #transform the frame surface
    frame.tz.set(-10.0)

    exp = """float $flen = %(camera)s.focalLength;
    float $hfa = %(camera)s.horizontalFilmAperture * 25.4;
    %(frame)s.sx = -%(frame)s.translateZ * $hfa/ $flen;
    %(frame)s.sy = %(frame)s.sx / defaultResolution.deviceAspectRatio;
    %(camera)s.focusDistance = -%(frame)s.tz;
    %(camera)s.aiFocusDistance = %(camera)s.focusDistance;
    %(camera)s.aiApertureSize = %(camera)s.focalLength / %(camera)s.fStop * 0.1;
    """ % {
        'camera': camera_shape.name(),
        'frame': frame.name()
    }
    pm.expression(s=exp, ae=1, uc="all")

    # set material
    surface_shader = pm.shadingNode('surfaceShader', asShader=1)
    pm.select(frame)
    pm.hyperShade(a=surface_shader.name())

    surface_shader.setAttr('outColor', (0.4, 0, 0))
    surface_shader.setAttr('outTransparency', (0.5, 0.5, 0.5))

    # prevent it from being rendered
    frame_shape.setAttr('castsShadows', 0)
    frame_shape.setAttr('receiveShadows', 0)
    frame_shape.setAttr('motionBlur', 0)
    frame_shape.setAttr('primaryVisibility', 0)
    frame_shape.setAttr('smoothShading', 0)
    frame_shape.setAttr('visibleInReflections', 0)
    frame_shape.setAttr('visibleInRefractions', 0)

    # Arnold attributes
    frame_shape.setAttr('aiSelfShadows', 0)
    frame_shape.setAttr('aiVisibleInDiffuse', 0)
    frame_shape.setAttr('aiVisibleInGlossy', 0)

    # hide unnecessary attributes
    frame.setAttr('tx', lock=True, keyable=False)
    frame.setAttr('ty', lock=True, keyable=False)
    frame.setAttr('rx', lock=True, keyable=False)
    frame.setAttr('ry', lock=True, keyable=False)
    frame.setAttr('rz', lock=True, keyable=False)
    frame.setAttr('sx', lock=True, keyable=False)
    frame.setAttr('sy', lock=True, keyable=False)
    frame.setAttr('sz', lock=True, keyable=False)
def rtb_create_retopo_shader():
    ''' '''
    try:
        sel = [
            obj for obj in pm.ls(sl=True)
            if obj.getShape() and obj.getShape().nodeType() == 'mesh'
        ]
    except:
        pm.warning('Please select some geometry')
        return

    shaderName = 'lcRetopo'

    if not pm.objExists(shaderName):
        shader = pm.shadingNode('lambert', asShader=True, name=shaderName)
        SG = shaderName + 'SG'
        if not pm.objExists(SG):
            pm.sets(renderable=True,
                    noSurfaceShader=True,
                    empty=True,
                    name=(shader + 'SG'))
        pm.connectAttr(shader + '.outColor', SG + '.surfaceShader', force=True)

        shader.color.set(1, 0, 0)
        shader.transparency.set(0.5, 0.5, 0.5)

    if sel:
        pm.select(sel, replace=True)  #grab the stored selection
        pm.hyperShade(assign=shaderName)  #assign shader to selection
Ejemplo n.º 16
0
    def create_and_assign_shader(self):
        materials_type = {
            1: 'mia_material_x',
            2: 'blinn',
            3: 'lambert',
            4: 'phong',
            5: 'rampShader',
            6: 'anisotropic',
            7: 'phongE',
            8: 'useBackground'
        }
        shader_name = self.text_field.getText()
        selected_material = self.option_menu.getSelect()

        geometry01 = self.shader_geo_scroll_list.getSelectItem()

        geometry02 = self.scene_geo_scroll_list.getSelectItem()

        created_shader = pm.shadingNode(materials_type[selected_material],
                                        asShader=True,
                                        name=shader_name)

        for geometry in geometry01:
            pm.select(geometry)
            pm.hyperShade(geometry, assign='%s' % (created_shader))

        for geometry in geometry02:
            pm.select(geometry)
            pm.hyperShade(geometry, assign='%s' % (created_shader))
Ejemplo n.º 17
0
def txClean(): # DELETE ALL PREVIEW SHADERS
    previewShaders = pm.select("PREV_*", allDagObjects=False, noExpand=True)
    meshes = pm.hyperShade(objects="")
    pm.hyperShade(assign= 'lambert1' )
    pm.select(cl =1)
    previewShaders = pm.select("PREV_*", allDagObjects=False, noExpand=True)
    pm.delete()     
Ejemplo n.º 18
0
 def assign_shader(self, geo):
     """
     Assign Shader to selected objects
     :param geo: geometry list (list)
     :return:
     """
     pm.select(geo)
     pm.hyperShade(assign=self.shader)
Ejemplo n.º 19
0
    def assignShader(self):
        with open(self.sourceDirPath / self.collection + '_shaders.json',
                  'r') as f:
            shaderAssignInfo = json.load(f)

        for description, shader in shaderAssignInfo.items():
            pm.select(description, r=True)
            pm.hyperShade(assign=shader)
Ejemplo n.º 20
0
 def assignHairShader(self, name, description):
     hairShader = '{0}_{1}_hairShader'.format(self.assetName, name)
     if not pm.objExists(hairShader):
         hairShader = pm.shadingNode('aiStandardHair',
                                     asShader=True,
                                     n=hairShader)
     pm.select(description, r=True)
     pm.hyperShade(assign=hairShader)
Ejemplo n.º 21
0
 def Maya_assignToSelection(self, *args):
     """Assign current shader to selected objects"""
     # Controls if selection is not null
     test = pc.ls(sl=1)
     if len(test) == 0:
         raise Exception("Tried to assign '%s' to the current selection but nothing is selected." % self.selectedShader)
     
     # If everything is ok, assign current shader to selection
     pc.hyperShade(assign=self.selectedShader)
Ejemplo n.º 22
0
def assign_shader(geo, shader):
    """
    Assign Shader to selected objects
    :param geo: geometry list (list)
    :param shader: shader name (string)
    :return:
    """
    pm.select(geo)
    pm.hyperShade(assign=shader)
def assign_killz():
	sel=pm.ls(sl=True)
	#load shaders 
	if not pm.objExists("HELMET"):
		cmds.file("/mpc/mayors1/playstationKillzone4_5402105/pantry/bodies/vsa_infantry_shaders.ma",i=True,type='mayaAscii', ignoreVersion=True, rpr="vsa_infantry_shaders", options='v=0',loadReferenceDepth='all')
	if not pm.objExists("PLASTIC_LIGHT"):
		cmds.file("/mpc/mayors1/playstationKillzone4_5402105/pantry/bodies/hgh_infantry_shaders.ma",i=True,type='mayaAscii', ignoreVersion=True, rpr="hgh_infantry_shaders", options='v=0',loadReferenceDepth='all')
	assignments_keys=[chkObjNs('*vsa_security_trooper_helmet*'),
	                  chkObjNs('*vsa_security_trooper_glasses'),
	                  chkObjNs('*vsa_security_trooper_visor'),
	                  chkObjNs('*VSA_Infantry_Body_L*'),
	                  chkObjNs('*VSA_Infantry_Markers_L*'),
	                  chkObjNs('*VSA_Infantry_Marker_Lights_L*'),
	                  chkObjNs('*head*l*'),
	                  chkObjNs('*head_anthony_trooper_l*'),
	                  chkObjNs('*heads_GEO*'),
	                  chkObjNs('HGH_specOps_class_bodies_GRP'),
	                  chkObjNs('HGH_support_class_bodies_GRP'),
	                  chkObjNs('HGH_specOps_*_GRP'),
	                  chkObjNs('HGH_support_*_GRP'),
	                  chkObjNs('first_layer'),
	                  chkObjNs('second_layer'),
	                  chkObjNs('edges'),
	                  chkObjNs('*eyes_glowing*'),
	                  chkObjNs('*screen_back_L*'),
	                  chkObjNs('*single_led_back*'),
	                  chkObjNs('*Light_L*'),
	                  chkObjNs('*round_gridlights*')]
	assignments={chkObjNs('*vsa_security_trooper_helmet*'):'HELMET',
		 chkObjNs('*vsa_security_trooper_glasses'):'VISOR',
		 chkObjNs('*vsa_security_trooper_visor'):'VISOR',
		 chkObjNs('*VSA_Infantry_Body_L*'):'BODY',
		 chkObjNs('*VSA_Infantry_Markers_L*'):'lambert1',
		 chkObjNs('*VSA_Infantry_Marker_Lights_L*'):'lambert1',
		 chkObjNs('*head*l*'):'FACE',
		 chkObjNs('*head_anthony_trooper_l*'):'FACE',
		 chkObjNs('*heads_GEO*'):'FACE',
		 chkObjNs('HGH_specOps_class_bodies_GRP'):'HGH_SpecOp_BODY',
		 chkObjNs('HGH_support_class_bodies_GRP'):'HGH_Engineer_BODY',
		 chkObjNs('HGH_specOps_*_GRP'):'HGH_SpecOp_BODY',
		 chkObjNs('HGH_support_*_GRP'):'HGH_Engineer_BODY',
		 chkObjNs('first_layer'):'HGH_Engineer_BODY',
		 chkObjNs('second_layer'):'HGH_Engineer_BODY',
		 chkObjNs('edges'):'HGH_Engineer_BODY',
		 chkObjNs('*eyes_glowing*'):'PLASTIC_LIGHT',
		 chkObjNs('*screen_back_L*'):'PLASTIC_LIGHT',
		 chkObjNs('*single_led_back*'):'PLASTIC_LIGHT',
		 chkObjNs('*Light_L*'):'PLASTIC_LIGHT',
		 chkObjNs('*round_gridlights*'):'PLASTIC_LIGHT'}
	print assignments
	for obj in assignments_keys:
		if not obj == "":
			print 'Assigning shader %s to object %s' % ( assignments[obj], obj)
			objs = pm.ls(obj)
			print objs
			pm.select(objs,r=True)
			pm.hyperShade(obj, a=assignments[obj])
def main():
    selectionList = pm.ls(sl=True)


    basicFilter = "Image Files (*.TGA *.tga *.DDS *.dds *.PNG *.png)"
    path = pm.fileDialog2(fileFilter=basicFilter, dialogStyle=2, fm=3)
    files = listdir(path[0])
    ddsFiles = []
    for item in files:
        fileEndings = ('.TGA', '.tga', '.DDS', '.dds', '.PNG', '.png')
        if (item.endswith(fileEndings)):
            ddsFiles.append(item)



    for obj in selectionList:
        shader = pm.shadingNode('phong', n=obj + "Shader", asShader=True)

        pm.select(obj)
        pm.hyperShade(assign=shader)
        if obj.find("_lod") !=-1:
            lodName = obj.split("_")
            shaderConnections(ddsFiles, lodName[0], shader, path)
        else:
            shaderConnections(ddsFiles, obj, shader, path)

        connections = pm.listConnections(shader, destination=False, source=True)
        if len(connections) < 6:

            errorstring = ""

            errorstring += ("# ===============================")
            errorstring += ("\n# %s texture(s) missing:" %str(6-len(connections)))
            errorstring += ("\n# ===============================")

            if len(pm.listConnections(shader+".color", destination=False, source=True)) < 1:
                errorstring += ("\n# - Albedo was not found!")

            if len(pm.listConnections(shader+".ambientColor", destination=False, source=True)) < 1:
                errorstring += ("\n# - Ambient Occlusion was not found!")

            if len(pm.listConnections(shader + ".incandescence", destination=False, source=True)) < 1:
                errorstring += ("\n# - Emissive was not found!")

            if len(pm.listConnections(shader+".normalCamera", destination=False, source=True)) < 1:
                errorstring += ("\n# - Normal Map was not found!")

            if len(pm.listConnections(shader + ".reflectedColor", destination=False, source=True)) < 1:
                errorstring += ("\n# - Metallic was not found!")

            if len(pm.listConnections(shader + ".specularColor", destination=False, source=True)) < 1:
                errorstring += ("\n# - Roughness was not found!")

            pm.confirmDialog(message=errorstring)
        else:
            victorystring = "All textures have been successfully linked!"
            pm.confirmDialog(message=victorystring)
Ejemplo n.º 25
0
	def make_leaf(self):
		i = pm.polyCube(w=.5,d=1.5,h=4,sw=3,sh=3)
		pm.select(i[0].vtx[12:19])
		pm.scale(0.1,0.1,1,r=True)
		pm.select(i[0].vtx[0:3],i[0].vtx[28:31])
		pm.scale(0.1,0.1,1,r=True)
		pm.select(i[0].vtx[4],i[0].vtx[7:8],i[0].vtx[11],i[0].vtx[20],i[0].vtx[23:24],i[0].vtx[27]) 
		pm.scale(0.8,0.8,0.8)
		pm.select(i[0])
		pm.hyperShade(assign=Lsystem.leafShader)
		return i
Ejemplo n.º 26
0
def assignShaderToObj(_obj):
    # assign shader
    mtl = pm.shadingNode("RedshiftArchitectural", asShader=True, name="rsMtl")
    mtlShader = pm.sets(renderable=True,
                        noSurfaceShader=True,
                        empty=True,
                        name="tmp")
    mtl.outColor >> mtlShader.surfaceShader
    pm.sets(mtlShader, edit=True, forceElement=_obj)
    pm.hyperShade("tml", _obj, assign=True)
    return _obj
    print "applied shader? D:\n"
Ejemplo n.º 27
0
def applyMaterial(color, *args):
    """apply id material to selected"""
    try:
        material = nt.Lambert(color + "_id")
    except pm.MayaNodeError:
        selected = pm.selected()
        material = pm.createNode("lambert",
                                 n=color + "_id_material")  # vray node
        color = [c / 255. for c in Default.materials[color]]
        material.setAttr("color", color)
        pm.select(selected)
    pm.hyperShade(a=material)
Ejemplo n.º 28
0
def get_face_shader():
    # Use the hyperShade command "Select Materials From Objects"
    pm.hyperShade(shaderNetworksSelectMaterialNodes=True)

    # Use Classification
    # Classification strings look like file pathnames ("shader/reflective" or "texture/2D", for example)
    for shader in pm.selected(materials=True):
        if [c for c in shader.classification() if 'shader/surface' in c]:
            # lambert1 return : [nt.ShadingEngine(u'initialParticleSE'), nt.ShadingEngine(u'initialShadingGroup')]
            face_shader = pm.listConnections(shader, type='shadingEngine')[-1]

    return face_shader
Ejemplo n.º 29
0
def assignMaterialToObject_old( material, objects ):
    ''' 오브젝트에 쉐이더 어싸인'''
    selected = cmds.ls(sl=True)
    
    pm.select( objects )
    pm.hyperShade( assign= material )# 이부분에서 메세지 발생함
    #cmds.select( cl=True )
    
    if selected:
        cmds.select( selected )
    else:
        cmds.select( cl=True )    
Ejemplo n.º 30
0
def assignMat(*args):
    selected = pm.ls(sl=1,long=1)
    matName= 'master_attr_mat'
    existAttrMat = pm.ls((matName),materials=True)
    masterMat = False
    if (len(existAttrMat) ==0):
        genMat()
        masterMat = (pm.ls((matName),materials=True))[0]
    else:
        masterMat = existAttrMat[0]
    for member in selected:
    	pm.select(member)
        pm.hyperShade(member,assign=masterMat )
Ejemplo n.º 31
0
def copyPasteMaterial(objects):
    source = objects[0]
    target = objects[-1]

    pm.select(source)
    pm.hyperShade(shaderNetworksSelectMaterialNodes=True)
    shaders = pm.ls(
        sl=True)  # all shaders associated with the object (shape, face etc)

    shader = [s for s in shaders if s.type() != 'renderLayer']
    shadingEngine = shader[0].listConnections(type='shadingEngine')

    pm.sets(shadingEngine[0], edit=True, forceElement=target)
Ejemplo n.º 32
0
  def revertToLambert(cls, shader, textureSampler='.diffuseMapSampler', *args, **kwargs):
    """ create lambert copies of all the cgfx shaders and connect the diffuse texture """
    if pm.getAttr(shader+'.shader'):
      diffuseTexNode = pm.connectionInfo(shader+textureSampler, sourceFromDestination=True)
      lambert = pm.shadingNode('lambert', asShader=True, name='L_'+shader )
      lambertSG = pm.sets(renderable=True, noSurfaceShader=True, empty=True, name='L_'+shader+'SG' )
      pm.connectAttr(lambert+'.outColor', lambertSG+'.surfaceShader', force=True)
      if diffuseTexNode:
        pm.connectAttr(diffuseTexNode, lambert+'.color', force=True)

      pm.hyperShade(objects=shader)
      pm.sets(lambertSG, edit=True, forceElement=True)
      pm.select(clear=True)
Ejemplo n.º 33
0
def remove_all_materials():
    """ This removes all materials by first assigning all geometry to Lambert1. It then runs
    the MEL command from the Hypershade to remove unused materials and shading groups. """

    allGeo = [x.getTransform() for x in pm.ls(type=['mesh', 'nurbsSurface'])]
    # restore the user's previous selection after running this.
    # The MEL command requires a selection I think.
    oldSel = pm.selected()
    pm.select(allGeo)
    pm.hyperShade(assign='lambert1')
    #TODO: debug this to make sure it is always "hyperShadePanel1"
    pm.mel.hyperShadePanelMenuCommand("hyperShadePanel1", "deleteUnusedNodes")
    pm.select(oldSel)
Ejemplo n.º 34
0
def getObjects_fromMaterial( material ):
    """ 입력된 shader가 적용된 오브젝트(메쉬,넙스...) 리스트를 리턴 """
    sel = cmds.ls(sl=True)
    
    pm.hyperShade( objects=material ) # 이부분에서 메세지 발생함
    objects = pm.ls(sl=True)
    
    if sel: 
        cmds.select(sel)
    else:
        cmds.select( cl=True )

    return objects
Ejemplo n.º 35
0
def assignMat(*args):
    selected = pm.ls(sl=1, long=1)
    matName = 'master_attr_mat'
    existAttrMat = pm.ls((matName), materials=True)
    masterMat = False
    if (len(existAttrMat) == 0):
        genMat()
        masterMat = (pm.ls((matName), materials=True))[0]
    else:
        masterMat = existAttrMat[0]
    for member in selected:
        pm.select(member)
        pm.hyperShade(member, assign=masterMat)
Ejemplo n.º 36
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)
def CreateShader(iscMenu, shaders, iscpath):
    selobj = pm.ls(sl=True)
    selection = iscMenu.getValue()
    if selection != 'Please Select Shader':
        path = iscpath.getText()
        createme = shaders[selection]
        shader = eval(createme)
        print type(shader)
        if selobj != []:
            pm.select(selobj)
            pm.hyperShade(assign=shader.createdShader[0])
            pm.select(shader.createdShader[0])
        else:
            pm.select(shader.createdShader[0])
Ejemplo n.º 38
0
def getMaterials_fromObject( objects ):
    """ 입력된 오브젝트들의 shader 리스트를 리턴 """
    sel = cmds.ls(sl=True)

    pm.select( objects )
    pm.hyperShade( smn=True )
    shaders = cmds.ls(sl=True)
    
    if sel: 
        cmds.select(sel)
    else:
        cmds.select( cl=True )

    return shaders
Ejemplo n.º 39
0
    def assign_to_geometry(self):
        material = self.shader_scroll_list02.getSelectItem()[0]

        geometry01 = self.shader_geo_scroll_list.getSelectItem()

        geometry02 = self.scene_geo_scroll_list.getSelectItem()

        for geometry in geometry01:
            pm.select(geometry)
            pm.hyperShade(geometry, assign='%s' % (material))

        for geometry in geometry02:
            pm.select(geometry)
            pm.hyperShade(geometry, assign='%s' % (material))
 def _get_shaders(self):
     """
     Gets a dictionary with the used materials for each description
     :return: Dictionary with the shader --> description mapping
     """
     import pymel.core as pm
     material_dict = dict()
     for description in xg.descriptions(str(self.collection_name)):
         pm.select(description)
         pm.hyperShade(shaderNetworksSelectMaterialNodes=True)
         for shd in pm.selected(materials=True):
             if [c for c in shd.classification() if 'shader/surface' in c]:
                 material_dict[description] = shd.name()
     return material_dict
def CleanUpMod():
    mel.eval('SelectHierarchy;')
    for i in pm.ls(sl=1, type='mesh'):
        for j in pm.listConnections(i, c=1, p=1, s=1):
            try:
                pm.disconnectAttr(j[0], j[1])
            except:
                pass
            try:
                pm.disconnectAttr(j[1], j[0])
            except:
                pass
    for i in pm.ls(sl=1, type='transform'):
        mel.eval('CenterPivot')
    pm.hyperShade(assign='initialParticleSE')
Ejemplo n.º 42
0
def apply_material(objects, material, **kwargs):
    """
    Apply a material to an object

    Returns 0
    """
    freeze_bool = kwargs.setdefault('freeze', False)
    py.select(objects)
    py.hyperShade(assign=material)
    if freeze_bool is True:
        py.delete(ch=True)
        py.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
        py.select(cl=True)

    return 0
Ejemplo n.º 43
0
 def assign_to_geometry(self):
     material = self.shader_scroll_list02.getSelectItem()[0]
     
     geometry01 = self.shader_geo_scroll_list.getSelectItem()
     
     geometry02 = self.scene_geo_scroll_list.getSelectItem()
     
     for geometry in geometry01:
         pm.select(geometry)
         pm.hyperShade(geometry, assign='%s' % (material))
         
         
     for geometry in geometry02:
         pm.select(geometry)
         pm.hyperShade(geometry, assign='%s' % (material))
Ejemplo n.º 44
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)
Ejemplo n.º 45
0
    def setMaterials(*args):
        if len(State._selectedObjects) == 0:
            ErrorDialog.show('No objects selected!')
        elif len(State._selectedMaterials) == 0:
            ErrorDialog.show('No naterials selected!')
        elif State._wnd.getSelectedPattern == 'N Materials' and State.getIntValue(State._wnd.rN) > len(State._selectedMaterials):
            ErrorDialog.show('N is higher than selected material count!')
        else:
            State.dump()

            Pattern.rNum = -1
            Pattern.rArr = []
            
            for obj in State._selectedObjects:
                pm.select(obj)
                pm.hyperShade(assign=State._randNextMaterial())
Ejemplo n.º 46
0
def importShader(*args):
    """
	"""
    result = pm.fileDialog2(cap='Select Exported Shading File',
                            fm=1,
                            okc='Select')
    if not result:
        return
    else:
        shaderNetFile = result[0]
    shaderNetName = shaderNetFile.split('__shaderNet.ma')[0]
    shaderMapFile = shaderNetName + '__shaderMap.json'
    # import shading network
    namespace = Path(shaderNetFile).namebase.replace('.', '_')
    pm.createReference(shaderNetFile, ns=namespace)
    # Remap shader
    shaderMap = {}
    with open(shaderMapFile) as jsonFile:
        shaderMap = json.load(jsonFile)
    for shader in shaderMap:
        impShad = namespace + ':' + shader
        if pm.objExists(impShad):
            pm.select(cl=1)
            for mesh in shaderMap[shader]:
                meshFace = ''
                if '.f' in mesh:
                    meshFace = '.f' + mesh.split('.f')[1]
                    mesh = mesh.split('.f')[0]
                print '? ' * 10
                print mesh
                print '? ' * 10
                for realMesh in pm.ls(mesh, r=1):
                    if realMesh.intermediateObject.get():
                        realMesh = pm.listRelatives(realMesh.getParent(),
                                                    ni=True,
                                                    typ='mesh',
                                                    s=1)[0]
                    if meshFace and realMesh:
                        realMesh = pm.ls(realMesh.name() + meshFace)
                    pm.select(realMesh, add=1)
            print '- + ' * 10
            print shader
            print pm.ls(sl=1)
            print '- + ' * 10
            pm.hyperShade(a=impShad)
        else:
            pm.warning('Shader Not Found !  ' + impShad)
Ejemplo n.º 47
0
 def redshift_on_clicked_create(self,*argv):
     main_file_path = cmds.textField(self.path_text,q=1,tx=1)
     shade_tex_name = cmds.optionMenu(self.shade_name,q=1,v=1)
     
     if cmds.checkBox(self.all_shader,q=1,v=1):
         for name in self.get_file_name_number(self.global_path):
             
             self.link_redshift_shader(name,main_file_path,self.global_path)
     else:
         sel_obj = cmds.ls(sl=1)
         if sel_obj:
             self.link_redshift_shader(shade_tex_name, main_file_path, self.global_path)
             name = rs_shader[0].getName()
             pmel.select(sel_obj)
             pmel.hyperShade(assign=name)
         else:
             self.link_redshift_shader(shade_tex_name, main_file_path, self.global_path)
Ejemplo n.º 48
0
def assign_shader(faces, udim):
    """ Assigns given faces a shader named after the udim number
    Args:
        faces [pm.general.MeshFace]: Given faces to assign a shader to
        udim (int): number from 1001-1099 that represents a udim
    Returns (pm.nodetypes.Blinn): shader created
    """
    material = mat_name%udim
    if not pm.objExists(material):
        pm.scriptEditorInfo(suppressInfo=True, suppressWarnings=True)
        
        lambert = pm.shadingNode('blinn', n=material, asShader=True)
        lambert.color.set([random.random(), random.random(), random.random()])
        pm.select(faces,r=True)
        pm.hyperShade(a=lambert)
        
        pm.scriptEditorInfo(suppressInfo=False, suppressWarnings=False)
    return pm.PyNode(material)
Ejemplo n.º 49
0
def hookup_shaders(meshes=None, shaders=None):

    # hookup_prefix = "SHADER_HOOKUP_"
    shader_hookups = {}

    if not shaders:
        shaders = pm.ls(materials=True)

    # get all shaders
    for shader in shaders:
        #filter out shaders with defaultAssignment
        if not shader.hasAttr('defaultAssignment'):
            continue

        attr = shader.defaultAssignment.get()
        defaultAssignment = attrToPy(attr)
        mesh_name = defaultAssignment['mesh']
        obj_pattern = "^" + mesh_name + "\d*$"

        shader_hookups[obj_pattern] = shader

    print 'shaders to Hookup: {}'.format(shader_hookups)

    # Apply collected shaders to meshes
    if not meshes:
        meshes = pm.ls(type='mesh')
    # meshnodes = cmds.referenceQuery(reference_node, nodes=True):

    for node in meshes:
        node = pm.listRelatives(node, type='transform', p=True)[0]
        for (obj_pattern, shader) in shader_hookups.iteritems():
            if re.match(obj_pattern, node.name(), re.IGNORECASE):
                # assign the shader to the object
                # cmds.file(unloadReference=reference_node, force=True)
                # cmds.setAttr(reference_node + ".locked", False)
                # cmds.file(loadReference=reference_node)
                pm.select(node, replace=True)
                pm.hyperShade(assign=shader)
                # cmds.file(unloadReference=reference_node)
                # cmds.setAttr(reference_node + ".locked", True)
                # cmds.file(loadReference=reference_node)
            else:
                print "NODE: " + node + " doesn't match " + obj_pattern
Ejemplo n.º 50
0
    def renderAO(self, *args):
        """AO and SHADOW"""

        self.settings()
        selected = pm.selected(type="transform") or getMeshes()
        selected.sort(key=lambda x: x.name())
        textures_dir = self.out_folder.getText()
        self.progress.setMaxValue(len(selected))
        self.progress.setProgress(0)
        self.out_field.setPlainText("")

        for mesh in selected:

            mesh_name = mesh.name()
            mesh_full_name = os.path.join(textures_dir, mesh_name, mesh_name)
            mesh_full_dir = os.path.join(textures_dir, mesh_name)
            if not os.path.exists(mesh_full_dir):
                os.makedirs(mesh_full_dir)

            try:
                if self.ao.getValue():
                    t = time.time()
                    pm.select(mesh)
                    pm.hyperShade(a="ao_material")
                    result = self.bakeAO(mesh, mesh_full_name + "_ao.png")
                    self.out_field.append("%s: %s_ao, %s" %
                                          (result, mesh_name, time.time() - t))

                if self.shadow.getValue():
                    t = time.time()
                    pm.select(selected)
                    pm.hyperShade(a="shadow_material")
                    result = self.bakeAO(mesh, mesh_full_name + "_shadow.png",
                                         self.auto_levels.getValue())
                    self.out_field.append("%s: %s_shadow, %s" %
                                          (result, mesh_name, time.time() - t))

            except IndexError:
                self.out.field("render was forcefully stopped")
                break
            self.progress.step(1)
        self.progress.setProgress(0)
Ejemplo n.º 51
0
def bdPlayblastFolderVP2(folder,outFolder,codec, cleanName=0):
	animDir = folder
	animFiles = [os.path.splitext(f)[0] for f in sorted(os.listdir(animDir)) if f.endswith('.mb')]
	if not cleanName:
		lastVersions = []
		temp = []
		for f in animFiles:
			if '_v' in f:
				fileName = f[:-4]
				temp.append(fileName)
		
		temp1 = list(set(temp[:]))
		
		for t in temp1:
			lastVersions.append(t + '_v0' + str(temp.count(t)))
		
		animFiles = lastVersions
	for f in sorted(animFiles):
		pathFile = animDir + f + '.mb'
		if outFolder == '':
			pathMovie = 'movies/' + f
		else:
			pathMovie = outFolder + f
			
		if os.path.isfile(pathFile):
			print pathFile
		else:
			print 'no file'
		#checkFileCallbackId = OM.MSceneMessage.addCheckFileCallback(OM.MSceneMessage.kBeforeReferenceCheck, bdReplaceRig)
		pm.mel.eval('ActivateViewport20')
		pm.openFile(pathFile,f=1)
		pm.mel.eval('setCameraNamesVisibility 0')
		pm.select('zoo:body')
		pm.hyperShade(assign = 'zoo:cat_body_linkSHD')
		pm.select(cl=1)
		
		pm.setAttr("defaultResolution.width",1280) 
		pm.setAttr("defaultResolution.height",720) 
		
		bdSetCameraVP2('cam:cameraShape1')

		pm.playblast(format = 'avi', filename = pathMovie,forceOverwrite=1,sequenceTime=0,clearCache=0,viewer=0,showOrnaments=1,fp=4,percent = 100,compression=codec, quality=100, widthHeight= [1280, 720])
Ejemplo n.º 52
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)
Ejemplo n.º 53
0
def createCamSolidBG( camera=None ):
    '''
    카메라 백으로 사용할 솔리드한 Plane을 세움,
    카메라 이름을 명시하거나, 모델패털을 포커스한 상태에서 실행.

    Version : 2015-02-24
    
    >>> camSolidBG()
    (nt.Transform(u'persp_camSolidBG_grp'), nt.Transform(u'persp_camSolidBG_mesh'), nt.SurfaceShader(u'persp_camSolidBG_surfaceShader'), nt.ShadingEngine(u'persp_camSolidBG_SG'))
    
    >>> camSolidBG( camera='side' )
    (nt.Transform(u'side_camSolidBG_grp'), nt.Transform(u'side_camSolidBG_mesh'), nt.SurfaceShader(u'side_camSolidBG_surfaceShader'), nt.ShadingEngine(u'side_camSolidBG_SG'))
    '''
    if not camera:
        camera = pm.modelPanel( pm.playblast(activeEditor=True).split('|')[-1], q=True, camera=True )

    mesh = pm.polyPlane(sh=1, sw=1, ch=False)[0]
    grp  = pm.group()
    
    pm.parentConstraint(camera, grp)
    mesh.t.set(0,0,-500)
    mesh.r.set(90,0,0)
    mesh.s.set(150,150,150)
    
    shader, SG = pm.createSurfaceShader('surfaceShader')
    shader.outColor.set(0.5,0.5,0.5)
    pm.select(mesh)
    pm.hyperShade(assign=shader)
    
    mesh.castsShadows.set(False)
    mesh.receiveShadows.set(False)
    mesh.motionBlur.set(False)
    mesh.smoothShading.set(False)
    mesh.visibleInReflections.set(False)
    mesh.visibleInRefractions.set(False)
    
    grp.   rename('%s_camSolidBG_grp' % camera)
    mesh.  rename('%s_camSolidBG_mesh' % camera)
    shader.rename('%s_camSolidBG_surfaceShader' % camera)
    SG.    rename('%s_camSolidBG_SG' % camera)
    
    return grp, mesh, shader, SG
Ejemplo n.º 54
0
def arnoldspshmaker(path, meshName, texSets, fileType, autocbvalue, mattype):
    pm.arnoldFlushCache(textures=True)
    udimvial = [
        "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009",
        "1011", "1012", "1013", "1014", "1015", "1016", "1017", "1018", "1019"
    ]
    udimlists = list(set(texSets) & set(udimvial))
    if udimlists == []:
        for texSet in texSets:
            if pm.objExists(texSet) == True:
                shader = pm.listConnections(texSet + ".aiSurfaceShader", d=0)
                if shader == []:
                    shader = pm.listConnections(texSet + ".surfaceShader", d=0)
                pm.hyperShade(o=shader[0])
                mesh = pm.ls(sl=1, r=1)
                if mattype.find("ARNOLD4(aistandard)") != -1:
                    Aishaderfunc(path, meshName, texSet, "." + fileType,
                                 autocbvalue, mesh)
                elif mattype.find("Arnold4(AlSurface)") != -1:
                    Alshaderfunc(path, meshName, texSet, "." + fileType,
                                 autocbvalue, mesh)
            else:
                mesh = []
                if mattype.find("ARNOLD4(aistandard)") != -1:
                    Aishaderfunc(path, meshName, texSet, "." + fileType,
                                 autocbvalue, mesh)
                elif mattype.find("Arnold4(AlSurface)") != -1:
                    Alshaderfunc(path, meshName, texSet, "." + fileType,
                                 autocbvalue, mesh)
    else:
        sel = pm.ls(sl=1, type="transform")
        if sel != []:
            mesh = [a for a in sel if pm.nodeType(a.getShape()) == "mesh"]
            if mesh != []:
                if mattype.find("ARNOLD4(aistandard)") != -1:
                    Aishaderfunc(path, meshName, texSets[0], "." + fileType,
                                 autocbvalue, mesh)
                elif mattype.find("Arnold4(AlSurface)") != -1:
                    Alshaderfunc(path, meshName, texSets[0], "." + fileType,
                                 autocbvalue, mesh)
            else:
                pm.warning("请选择模型!!")
Ejemplo n.º 55
0
def assignColorAxisShader( geo, axis ):
    br = .5 # 밝기
    if   axis == 'x':
        axisColor = (1,br,br)
    elif axis == 'y':
        axisColor = (br,1,br)
    elif axis == 'z':
        axisColor = (br,br,1)

    shaderName = 'axisLambert_'+axis

    shader = None
    if pm.objExists( shaderName ):
        shader = pm.PyNode(shaderName)
    else:
        shader = pm.shadingNode( 'lambert', asShader=True,  n=shaderName )
        shader.color.set( axisColor )

    pm.select(geo)
    pm.hyperShade( assign = shader)
Ejemplo n.º 56
0
def shaderTransform():
    global nameSpaceInput,PATH
    nameSpaceInput = mc.textFieldGrp('nameSpaceInput',text = 1,q=1)
    PATH = mc.textFieldGrp('PATH',text = 1,q=1)   
    impShader = pm.importFile(PATH,i = 1,typ = 'mayaAscii',iv = 1,
                              ra = 1,mnc = 0,ns = nameSpaceInput,op = 'v=0;p=17;f=0',pr = 1)
    impFiles = mc.ls(nameSpaceInput + ':*')
    impFileList = [] #which include some unmaterial List#
    repeatShadedList = [] #temp Trash List #
    shadedList = [] #objectShaded in the old file#
    oldMaterialList = [] #objectShaded material in the old file#
    newMaterialList = [] #new material which use for the old file#
    
    for impFileString in impFiles:
        impFile = impFileString.split(':')
        impFileList.append(impFile[1])
    
    for impFile in impFileList:   
        pm.hyperShade(objects=impFile)
        shadedObjShape = pm.ls(sl = 1)[0]
        shadedObj = shadedObjShape.getParent()
        repeatShadedList.append(shadedObj)
    
    shadedList = list(set(repeatShadedList))
    
    for shadedObj in shadedList:
        shadingEngine = pm.listConnections(shadedObj.getShape(),type = 'shadingEngine')
        if pm.connectionInfo(shadingEngine[0] + '.surfaceShader',isDestination=True):
            oldMaterial =  pm.connectionInfo(shadingEngine[0] + '.surfaceShader',sourceFromDestination=True) 
            oldMaterialList.append(oldMaterial.split('.')[0])
          
    for oldMaterial in oldMaterialList:
        newPreShadedMaterial = nameSpaceInput + ':' + oldMaterial
        newMaterialList.append(newPreShadedMaterial)
        
    for num,newMaterial in enumerate(newMaterialList):
        pm.select(shadedList[num])
        SG= mc.sets(renderable=True,noSurfaceShader=True,empty=True,n = newMaterial + 'SG')
        mc.connectAttr('%s.outColor' %newMaterial ,'%s.surfaceShader' %SG)
        mc.sets(e = 1, fe = SG)
Ejemplo n.º 57
0
def rtb_create_retopo_shader():
  ''' '''
  try:
    sel = [ obj for obj in pm.ls(sl=True) if obj.getShape() and obj.getShape().nodeType() == 'mesh' ]
  except:
    pm.warning('Please select some geometry')
    return

  shaderName = 'lcRetopo'

  if not pm.objExists(shaderName):
    shader = pm.shadingNode('lambert', asShader=True, name=shaderName )
    SG = shaderName+'SG'
    if not pm.objExists(SG):
      pm.sets(renderable=True, noSurfaceShader=True, empty=True, name=(shader+'SG') )
    pm.connectAttr(shader+'.outColor', SG+'.surfaceShader', force=True)

    shader.color.set(1,0,0)
    shader.transparency.set(0.5,0.5,0.5)

  if sel:
    pm.select(sel, replace=True)  #grab the stored selection
    pm.hyperShade(assign=shaderName)    #assign shader to selection
Ejemplo n.º 58
0
def creatAll(*arg):
    # depth에 필요한 세더를 만든다.
    Mysshdr = cmds.shadingNode("surfaceShader", asShader=True)
    cmds.rename(Mysshdr, "An_XYZ")

    Mysampler = cmds.shadingNode("samplerInfo", asUtility=True)
    cmds.rename(Mysampler, "An_sampler")

    Myrange = cmds.shadingNode("setRange", asUtility=True)
    cmds.rename(Myrange, "An_range")

    Mymltipl = cmds.shadingNode("multiplyDivide", asUtility=True)
    cmds.rename(Mymltipl, "An_multy")

    cmds.connectAttr("An_sampler.pointCameraX", "An_multy.input1X", force=True)
    cmds.connectAttr("An_sampler.pointCameraY", "An_multy.input1Y", force=True)
    cmds.connectAttr("An_sampler.pointCameraZ", "An_multy.input1Z", force=True)
    cmds.setAttr("An_multy.input2X", 1)
    cmds.setAttr("An_multy.input2Y", 1)
    cmds.setAttr("An_multy.input2Z", 1)

    cmds.connectAttr(" An_multy.outputX", "An_range.valueX", force=True)
    cmds.connectAttr(" An_multy.outputY", "An_range.valueY", force=True)
    cmds.connectAttr(" An_multy.outputZ", "An_range.valueZ", force=True)
    cmds.setAttr("An_range.minX", 1)
    cmds.setAttr("An_range.minY", 1)
    cmds.setAttr("An_range.minZ", 1)

    cmds.connectAttr(" An_range.outValue.outValueX", "An_XYZ.outColorR", force=True)
    cmds.connectAttr(" An_range.outValue.outValueY", "An_XYZ.outColorG", force=True)
    cmds.connectAttr(" An_range.outValue.outValueZ", "An_XYZ.outColorB", force=True)

    # 혹시 aov에 쓸수 있으니깐 aov를 만들어 준다.
    import mtoa.aovs as aovs

    aovs.AOVInterface().addAOV("XYZ")
    cmds.connectAttr("An_XYZ.outColor", "aiAOV_XYZ.defaultValue", force=True)

    # viewport에서 지오메트리리 쉐프만 선택한다.
    # select_shape = cmds.ls( geometry=True,v=True )
    select_shape = pm.ls(type="mesh")

    get_invert_list = []

    for shape_str in select_shape:
        # shape_str은 스트링으로 출력되서 PyNode를 사용하여 shape_str를 캐스팅해준다고 한다.
        # 스트링으로된 이름을 노드로 타입바꿔주는것 같다.
        shape = pm.PyNode(shape_str)
        SG = shape.outputs(type="shadingEngine")[0]
        shader = SG.surfaceShader.inputs()
        print SG.displacementShader.connections()
        if len(SG.displacementShader.connections()) == True and len(shader[0].opacity.connections()) == True:
            print "displacement and opacity"

            opacity_file = shader[0].opacity.inputs()

            dis_file = SG.displacementShader.inputs()

            XYZdepth_op_dis = pm.shadingNode(
                "surfaceShader", asShader=True, name="XYZdepth_op_dis_" + shape.name() + "_"
            )
            XYZdepth_op_dis.outColor.set([1, 0, 0])
            # invert node 를 만들어 준다.

            XYZdepth_reverse = pm.shadingNode("reverse", asShader=True, name="XYZdepth_reverse_" + shape.name() + "_")

            pm.connectAttr(XYZdepth_reverse.output, XYZdepth_op_dis.outTransparency)
            pm.connectAttr(opacity_file[0].outColor, XYZdepth_reverse.input)

            pm.select(shape)
            pm.hyperShade(a="XYZdepth_op_dis_" + shape.name() + "_")

            # depth의 컬러 값을 surface shader에 연결해준다.
            pm.connectAttr("An_range.outValue", XYZdepth_op_dis.outColor)
            # 오퍼시티를     XYZdepth_op_dis의 오퍼시티에 넣어주면 알파가 안 뽑힌다.
            # pm.connectAttr(opacity_file[0].outColor,XYZdepth_op_dis.outTransparency)
            # 오퍼시티가 Transparency매트로 가면서 맵을 인버트해줘야 된다.

            # get_invert = opacity_file[0].invert.get()
            # get_invert_list.append(not get_invert)
            # print get_invert_list

            # XYZdepth_op_dis.outTransparency.inputs()[0].invert.set(get_invert_list[0])
            # print XYZdepth_op_dis.outTransparency.inputs()[0].invert.get()

            new_SG = shape.outputs(type="shadingEngine")[0]
            pm.connectAttr(dis_file[0].displacement, new_SG.displacementShader)

            pm.select(clear=True)

        elif len(SG.displacementShader.connections()) == True and len(shader[0].opacity.connections()) == False:
            print "only displacement"
            dis_file = SG.displacementShader.inputs()

            XYZdepth_dis = pm.shadingNode("surfaceShader", asShader=True, name="XYZdepth_dis_" + shape.name() + "_")
            XYZdepth_dis.outColor.set([1, 0, 0])

            pm.select(shape)
            pm.hyperShade(a="XYZdepth_dis_" + shape.name() + "_")
            # depth의 컬러 값을 surface shader에 연결해준다.
            pm.connectAttr("An_range.outValue", XYZdepth_dis.outColor)

            new_SG = shape.outputs(type="shadingEngine")[0]
            pm.connectAttr(dis_file[0].displacement, new_SG.displacementShader)

            pm.select(clear=True)

        elif len(SG.displacementShader.connections()) == False and len(shader[0].opacity.connections()) == True:
            print "only opacity"
            opacity_file = shader[0].opacity.inputs()

            XYZdepth_op = pm.shadingNode("surfaceShader", asShader=True, name="XYZdepth_op_" + shape.name() + "_")
            XYZdepth_op.outColor.set([1, 0, 0])

            # invert node 를 만들어 준다.
            XYZdepth_reverse = pm.shadingNode("reverse", asShader=True, name="XYZdepth_op_" + shape.name() + "_")
            pm.connectAttr(XYZdepth_reverse.output, XYZdepth_op.outTransparency)
            pm.connectAttr(opacity_file[0].outColor, XYZdepth_reverse.input)

            pm.select(shape)
            pm.hyperShade(a="XYZdepth_op_" + shape.name() + "_")
            # depth의 컬러 값을 surface shader에 연결해준다.
            pm.connectAttr("An_range.outValue", XYZdepth_op.outColor)

            pm.select(clear=True)

        else:
            print "no opacity and no displacement"
            pm.select(shape)
            pm.hyperShade(a="An_XYZ")
            pm.select(clear=True)
Ejemplo n.º 59
0
def setShader(shader):
    py.hyperShade(a=shader)