Example #1
0
 def add_to_render_layer():
     """
     Add the window's selected widgetlist items to the current Render Layer
     :return: None
     """
     try:
         pmc.editRenderLayerMembers(_window.current_render_layer,
                                    get_selected_widgetitems())
     except:
         raise RuntimeError("Cannot change current Render Layer's members")
Example #2
0
    def remove_from_render_layer():
        """
        Removes the window's selected widgetlist items from the Render Layer
        :return: None
        """
        try:
            pmc.editRenderLayerMembers(_window.current_render_layer,
                                       get_selected_widgetitems(),
                                       remove=True)

        except RuntimeError:
            pmc.warning('Cannot change members of the current Render Layer')
 def get_component_data(self):
     component_data = {}
     objects = core.editRenderLayerMembers(self.render_layer, q=True)  
     for object in objects:
         py_node = core.PyNode(object)
         attribute_data = self.get_node_data(py_node) 
         component_data.setdefault(object, attribute_data)
     return component_data    
Example #4
0
    def aw_assimilator(self):
        args=pm.ls(sl=True)
        targets=args[-1:]
        src=args[0]
        obj, curRndrLyr, assShdr, counter ='','','',0
        print "Targets are: %s\nAnd Source is: %s" % (",".join(map(str,targets)),src)
        allRndrLayers=pm.ls(type='renderLayer')

        # get all render layers just in case
        srcShape=str(aw_shaderAss.findShape(src))
        assRndrLayers=[]
        print srcShape
        if srcShape:
			assRndrLayers=pm.listConnections(srcShape, type='renderLayer')
        # get all assigned render layers of the source
        for obj in assRndrLayers:
            curRndrLyr=assRndrLayers[counter]
            # store the current render layer from the list
            for target in targets:
                if curRndrLyr != "defaultRenderLayer":
                    print "Assigning %s to render layer - %s" % (target,curRndrLyr)
                    pm.editRenderLayerGlobals(crl=curRndrLyr)
                    # change the render layer to the current one
                    assSG = self.findSG(aw_shaderAss.findShape(src))
                    # Get the shading group of the source and store
                    pm.editRenderLayerMembers(curRndrLyr,target)
                    # assign the target to the render layer
                    cmds.sets(target, forceElement=assSG[0])
                    # assign the shading group we just received to the target
                    counter+=1
                    
                
                else:
                    print "Master Layer: assigning " + target + "'s shader\n"
                    pm.editRenderLayerGlobals(crl=curRndrLyr)
                    # change the render layer to the current one
                    assSG=self.findSG(self.findShape(src))
                    # Get the shading group of the source and store
                    if pm.objExists(assSG) and pm.objExists(target) and pm.objectType(assSG) =='set':
						cmds.sets(target, forceElement=assSG)
                    # assign the shading group we just received to the target
                    counter+=1
Example #5
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
Example #6
0
    def render_layer_only():
        """
        The 'Show Lights in Current Render Layer' mode has been pressed.
        Hide certain widgetlist items or show them all.
        :return: None
        """
        if _window.render_layer_only:
            # Render Layer Only mode has been deactivated;
            # restore all widgetlist item's display
            _window.render_layer_off()

        else:
            # Render Layer Only mode activated; show only items
            # with the same name as the current Layer's members
            _window.render_layer_on(
                pmc.editRenderLayerMembers(_window.current_render_layer,
                                           query=True))
Example #7
0
def addGroupToLayer( sort_set, layer, rm=False ):
    """ Assign the objects in a sortgroup to a render layer. """
    
    # Get a list of sets to operate on, and bail if it is empty
    all_matching = getMatchingSets(sort_set)
    if all_matching == []:
        return

    # Loop through all the matching sets and add them to their assigned layer
    for sort_set in all_matching:
        try:
            # The nodes / sorting set members that will be assigned to the lyr
            nodes = sort_set.inputs()         
            [pm.editRenderLayerMembers( layer, n, r=rm ) for n in nodes]
        except:
            pm.warning('Sort Control  ERROR {:>25} XX {:<25}'.format(sort_set, layer))
        
        # Print progress repot.
        print 'Sort Control  SORTING {:>25} >> {:<25}'.format(sort_set, layer)
Example #8
0
    def create(self):
        """ Create the render layer.  This will generate the colors for
        each namespace, create flat shaders for each of these colors per
        namespace. A namespace render layer is also generated in maya.
        """
        # Query for the shading group set
        assigned = pm.sets("initialShadingGroup", query=True)
        if assigned:
            # Create new lambert shader
            default_lambert = pm.shadingNode("lambert", asShader=True)
            attrs = default_lambert.listAttr(scalar=True,
                                             read=True,
                                             settable=True,
                                             keyable=True)
            for attr in attrs:
                num_child_attrs = pm.attributeQuery(
                    attr.name(includeNode=False),
                    node="lambert1",
                    numberOfChildren=True)
                plug = attr.listConnections(plugs=True,
                                            destination=False,
                                            source=True)

                if plug:
                    attr.connectAttr(plug[0])

                elif num_child_attrs:
                    attr_val = pm.getAttr('lambert1.{0}'.format(attr))
                    default_lambert.setAttr(attr_val)
                    # Add parent attribute if there are any
                    parent_attr = pm.attributeQuery(attr,
                                                    lp=True,
                                                    n="lambert1")
                    if parent_attr and parent_attr[0] not in attrs:
                        attrs.append(parent_attr[0])

            shading_group = pm.sets(renderable=True, noSurfaceShader=True)
            default_lambert.connectAttr('outColor',
                                        '{0}.surfaceShader'.format(
                                            shading_group.name()),
                                        f=True)
            for item in assigned:
                is_object = pm.ls(item, o=True)
                if is_object:
                    try:
                        shade_remove = pm.sets(item.name(),
                                               rm='initialShadingGroup',
                                               e=True)
                        pm.sets(item, e=True, fe=shading_group)
                    except RuntimeError:
                        shade_remove = None
                        print "Problem removing " + str(
                            item) + " from the initialShadingGroup"
        # Get namespaces and generate colors based on those namespaces
        self.get_namespaces()
        self.get_namespace_colors()
        # Must replace with internal object function
        # _getNamespaceInfoFromStructureFile(self.struc, self.namespaces,
        #                                    [], [], [], [], [])

        # _getColors(self.namespaces, self.colors)
        old_namespace = pm.namespaceInfo(currentNamespace=True)
        old_render_layer = pm.editRenderLayerGlobals(q=True,
                                                     currentRenderLayer=True)
        layer = ""
        for i, cur_namespace in enumerate(self.namespaces):
            # Will probably need to remove
            if cur_namespace == 'stereoCam':
                continue

            if layer == '':
                layer = pm.createRenderLayer(makeCurrent=True,
                                             name="namespaceLayer")

            if not pm.namespace(set=(":" + str(cur_namespace))):
                continue

            (red, green, blue) = self.colors[i]
            dag_namespace = pm.namespaceInfo(dp=1, lod=True)
            pm.select(dag_namespace, replace=True)
            geom = pm.ls(visible=True,
                         type=['mesh', 'nurbsSurface'],
                         dag=True,
                         ni=True,
                         selection=True)
            gpu_mesh = []
            if pm.objectType(tagFromType="rfxAlembicMeshGpuCache"):
                gpu_mesh = pm.ls(selection=True,
                                 visible=True,
                                 dag=True,
                                 noIntermediate=True,
                                 type="rfxAlembicMeshGpuCache",
                                 long=True)

            pm.select(clear=True)
            if len(geom) > 0:
                material = str(shadingNode('surfaceShader', asShader=True))
                setAttr((material + ".outColor"),
                        red,
                        green,
                        blue,
                        type='double3')
                shader = str(
                    cmds.sets(renderable=True,
                              noSurfaceShader=True,
                              empty=True))
                connectAttr((material + ".outColor"),
                            (shader + ".surfaceShader"),
                            f=True)
                for j in range(0, len(geom)):
                    existingShaders = listConnections(geom[j],
                                                      source=False,
                                                      plugs=False,
                                                      destination=True,
                                                      type="shadingEngine")
                    if len(existingShaders) > 0:
                        editRenderLayerMembers(layer, geom[j])
                        retry = 0
                        # first try to set the shader in object mode
                        retry = 1
                        # Use shading group hijack method for everything...
                        #if (catch(`sets -noWarnings -forceElement $shader $geom[$j]`)) {
                        #    $retry = 1;
                        #}
                        if retry == 1:
                            # Couldn't assign shader. Various alternative approaches to assigning the shader have not worked 100% of the time.
                            # So add a couple of extra attributes to the shadingGroup - defaultShader and namespaceShader, and connect the respective
                            # shaders to these. During pushRenderLayer (PlayblastTool), check for the existence of the namespaceShader, and if present,
                            # find it's connection and plug it into the surfaceShader attribute, thus "hijacking" the shading group. During popRenderLayer,
                            # connect the attribute plugged into defaultShader and plug this back into the surfaceShader attribute. This is messy, but it
                            # sidesteps material assignment alltogether.
                            for k in range(0, len(existingShaders)):
                                if not objExists(existingShaders[k] +
                                                 ".defaultShader"):
                                    addAttr(existingShaders[k],
                                            ln="defaultShader",
                                            at="message")
                                    defaultMat = listConnections(
                                        (existingShaders[k] +
                                         ".surfaceShader"),
                                        s=1,
                                        d=0)
                                    if len(defaultMat):
                                        connectAttr(
                                            (defaultMat[0] + ".message"),
                                            (existingShaders[k] +
                                             ".defaultShader"))

                                    addAttr(existingShaders[k],
                                            ln="namespaceShader",
                                            at="message")
                                    connectAttr((material + ".message"),
                                                (existingShaders[k] +
                                                 ".namespaceShader"))

                            retry = 0
                            # temp until we feel confident retiring the next section of code

                        if retry == 1:
                            print "Using alternate shader assignment strategy on " + geom[
                                j] + "\n"
                            # couldn't assign shader. Emergency fall-back: Switch back to defaultRenderLayer, unassign and re-assign the existing shaders, then
                            # switch back to namespace layer and try again.
                            existingShaders = self.stringArrayReverse(
                                existingShaders)
                            """
                            To-do: Add an explanation about why reversing the shaders array is necessary once we've confirmed that we are good. -HM
                            """
                            # store the existing material assignments
                            comps = []
                            indices = []
                            for k in range(1, len(existingShaders)):
                                indices[k - 1] = len(comps)
                                assigned = cmds.sets(existingShaders[k], q=1)
                                for m in range(0, len(assigned)):
                                    obj = ls(o=assigned[m])
                                    if obj[0] == geom[j]:
                                        comps.append(assigned[m])

                            # unassign the existing materials
                            for k in range(0, len(existingShaders)):
                                cmds.sets(geom[j], rm=existingShaders[k], e=1)

                            if catch(lambda: cmds.sets(geom[j],
                                                       noWarnings=1,
                                                       forceElement=shader)):
                                mel.warning("Couldn't "
                                            "assign namespace shader to " +
                                            geom[j])
                                continue

                            else:
                                print(
                                    "DeepPlayblastUtilities: Alternate "
                                    "shader assignment worked for " + geom[j] +
                                    ".\n")

                            editRenderLayerGlobals(
                                currentRenderLayer="defaultRenderLayer")
                            # switch back to defaultRenderLayer
                            # and re-assign (assign first shader to whole
                            # object, then component assign subsequent shaders)
                            cmds.sets(geom[j], e=1, fe=existingShaders[0])
                            for k in range(0, len(indices)):
                                end = (int(
                                    (k < len(indices) - 1) and indices[k + 1]
                                    or (len(comps))))
                                for m in range(indices[k], end):
                                    cmds.sets(comps[m],
                                              e=1,
                                              fe=existingShaders[k + 1])

                            # switch to namespace layer
                            editRenderLayerGlobals(currentRenderLayer=layer)

            if len(gpu_mesh) > 0:
                # end if size($existingShaders)
                for j in range(0, len(gpu_mesh)):
                    pm.editRenderLayerMembers(layer, gpu_mesh[j])
                    pm.setAttr((gpu_mesh[j] + ".defaultColor"),
                               red,
                               green,
                               blue,
                               type='double3')
                    pm.setAttr((gpu_mesh[j] + ".colorsMode"), 0)
                    self.gpu_meshes.append(gpu_mesh[j])

        if layer != "":
            pm.namespace(set=old_namespace)
            pm.editRenderLayerGlobals(currentRenderLayer=old_render_layer)

        self.layer = layer
        self.gpu_meshes = list(set(self.gpu_meshes))
Example #9
0
    def light_setup(self, fields, tk, ctx):
        '''
        This script is errorring, but once it runs through everything is setup correctly
        so the errorr has ben put on hold. 
        Error:  Message: There was a problem starting the Tank Engine.
                Please contact [email protected]
                Exception: <class 'tank.errors.TankError'> - Key '<Tank StringKey Step>' in template '<Tank TemplatePath asset_work_area_maya: assets/{sg_asset_type}/{Asset}/work/{Step}/>' 
                could not be populated by context 'Asset arnoldTemplate' because the context does not contain a shotgun entity of type 'Step'!
        
        ------------------------------------
        
        Might need extra part at the end, which assigns objects to render layers. We haven't decided whether this needs to be implemented or not. 
       
        '''

        #cmds.file(newFile=True, force=True)

        print('Communicating with shotgun, please wait!')

        temp_file = tk.templates['light_setup_temp']
        #fields_temp=ctx.as_template_fields(temp_file)
        #tempPath = temp_file.apply_fields(fields_temp)

        tk.templates['maya_shot_work']

        dst = temp_file.apply_fields(fields)

        pm.loadPlugin('mtoa.mll', quiet=True)
        pm.loadPlugin('AbcExport.mll', quiet=True)
        pm.loadPlugin('AbcImport.mll', quiet=True)

        #Open Arnold Renders Settings template
        arnoldSetup = "M:/00719_grandpa/assets/Environments/arnoldTemplate/publish/arnoldTemplate.rend.v004.ma"

        #print str(arnoldSetup)
        shutil.copyfile(arnoldSetup, dst)

        pm.system.openFile(dst, force=True)

        print('getting latest shot assets')
        #reference light setup scene
        lightSetup = su.getLatestShotAssets(tk,
                                            ctx,
                                            publishedType='Maya Lighting')
        print lightSetup

        shadowLayer = pm.PyNode('setExtras')
        beautyLayer = pm.PyNode('beauty')
        workLayer = pm.PyNode('defaultRenderLayer')

        for asset in lightSetup:
            print('loading reference: ' +
                  (asset['path']['local_path_windows']))
            setNodes = mu.referenceAsset(asset['path']['local_path_windows'])

        workLayer.setCurrent()

        #referencing latest camera file
        print('getting latest cameras')
        camData = su.getLatestShotFile(tk, ctx, publishedType='Maya Camera')

        maya_work = tk.templates['shot_work_area']
        fields = ctx.as_template_fields(maya_work)

        low_plate = tk.templates['low_res_proxy_plate_path']
        plateDir = low_plate.parent.apply_fields(fields)

        qt_plate = tk.templates['quicktime_proxy_plate_path']
        qtplateDir = qt_plate.parent.apply_fields(fields)

        if len(os.listdir(qtplateDir)) > 0:
            firstMovie = os.listdir(qtplateDir)[0]
            print('moviePlate: ' + firstMovie)
            moviePath = qtplateDir + '/' + firstMovie

        if len(os.listdir(plateDir)) > 0:
            firstImage = os.listdir(plateDir)[0]
            print('imagePlate: ' + firstImage)
            imagePath = plateDir + '/' + firstImage

        full_plate = tk.templates['full_res_proxy_plate_path']
        fullPlateDir = full_plate.parent.apply_fields(fields)

        try:
            firstImage = os.listdir(fullPlateDir)[0]
            imagePath = fullPlateDir + '/' + firstImage
            pm.PyNode('backplate').fileTextureName.set(imagePath)
        except:
            pass

        #Checks if shot camera exists. If not tries to find asset camera related to the shot.
        print('referencing camera')
        try:
            for cam in camData:
                print('camera is: ' + cam['path']['local_path_windows'])
                camNodes = mu.referenceAsset(cam['path']['local_path_windows'])

            print('connecting camera to projection')

            for node in camNodes:
                if pm.nodeType(node) == 'camera':
                    cam = pm.PyNode(node)
                    print cam
                    projection = pm.PyNode('projection')
                    cam.message >> projection.linkedCamera
                    #try for image planes---
                    try:
                        IP = pm.PyNode(mu.imagePlane(cam, imagePath))
                        #mu.imagePlane(cam, imagePath)
                        IP.depth.set(1500)
                        IP.fit.set(0)
                        IP.width.set(960)
                        IP.height.set(540)
                        IP.sizeY.set(0.797)
                        IP.sizeX.set(1.417)
                    except:
                        print('Backplate not found!!!')

        except:
            print('Camera Trouble!!!')

        #assign backplate to shadowcatcher material

        #import alembic files and reference shaded assets
        shotAssets = su.getLatestShotAssets(tk,
                                            ctx,
                                            publishedType='Maya Shaded Model')

        animCaches = []
        animCaches = su.getLatestShotFile(tk,
                                          ctx,
                                          publishedType='Alembic Animation')

        simCaches = []
        simCaches = su.getLatestShotFile(tk,
                                         ctx,
                                         publishedType='Alembic Simulation')

        cachedAssets = []
        for cache in animCaches:
            cachedAssets.append(cache['name'])

        simmedAssets = []
        for cache in simCaches:
            simmedAssets.append(cache['name'])

        abc_template = tk.templates['cache_alembic']

        #for cache in animCaches:
        try:
            input_path = animCaches[0]['path']['local_path_windows']
            fields = abc_template.get_fields(input_path)
            for f in animCaches:
                print('cache path: ' + f['path']['local_path_windows'])
                print f['name']
            print fields
        except:
            print('Cache file not found!!!')

        importedCaches = []
        failedNodes = []
        #grp = pm.group( em=True, name='cache' )
        for asset in shotAssets:
            try:
                print('loading reference for' + asset['assetName'])
                refNodes = mu.referenceAsset(
                    asset['path']['local_path_windows'],
                    namespace=(asset['assetName'] + 'Shaded'))
                print(asset['assetName'] + ' referenced')
                #make temporary namespace
                nspaceAnim = (asset['assetName'] + 'Anim')
                pm.namespace(add=nspaceAnim)
                pm.namespace(set=nspaceAnim)
                #import alembic cache for current asset
                if asset['assetName'] in cachedAssets:
                    print('Loading alembic cache for ' + asset['assetName'])
                    for cache in animCaches:
                        if cache['name'] == asset['assetName']:
                            print('Abc File: ' +
                                  cache['path']['local_path_windows'])
                            #mu.alembicImport(cache['path']['local_path_windows'], 'parent', parent=grp)
                            abcNodes = mu.referenceAsset(
                                cache['path']['local_path_windows'],
                                namespace=nspaceAnim)
                            importedCaches.append(
                                cache['path']['local_path_windows'])
                            print 'done'
                        else:
                            print cache['name']
                else:
                    print('Cache not found: ' + asset['assetName'])

                nspaceSim = (asset['assetName'] + 'Sim')
                pm.namespace(add=nspaceSim)
                pm.namespace(set=nspaceSim)
                #import alembic cache for current asset
                if asset['assetName'] in simmedAssets:
                    print('Loading alembic cache for ' + asset['assetName'])
                    for cache in simCaches:
                        if cache['name'] == asset['assetName']:
                            print('Abc File: ' +
                                  cache['path']['local_path_windows'])
                            #mu.alembicImport(cache['path']['local_path_windows'], 'parent', parent=grp)
                            abcNodes = mu.referenceAsset(
                                cache['path']['local_path_windows'],
                                namespace=nspaceSim)
                            importedCaches.append(
                                cache['path']['local_path_windows'])
                            print 'done'
                        else:
                            print cache['name']

            except:
                print('Something went wrong with ' + asset['assetName'])

            transformNodes = []
            print('transfering shaders for: ' + asset['assetName'])
            for node in refNodes:
                #collect all transform nodes
                if pm.nodeType(node) == 'transform':
                    transformNodes.append(pm.PyNode(node))
                try:
                    if pm.nodeType(node) == 'transform' and pm.PyNode(
                            node).hasAttr('asset'):
                        source = pm.PyNode(node)
                        shadingEngine = source.getShape().connections()
                        SG = str(shadingEngine[0].shortName())
                        target = pm.PyNode(
                            source.swapNamespace(nspaceAnim)).getShape()
                        pm.sets(SG, e=True, forceElement=target)
                        target.aiOpaque.set(source.getShape().aiOpaque.get())
                        target.aiSubdivType.set(
                            source.getShape().aiSubdivType.get())
                        target.aiSubdivIterations.set(
                            source.getShape().aiSubdivIterations.get())
                        target.aiTraceSets.set('cast')
                        try:
                            if source.swapNamespace(nspaceSim).hasAttr('sim'):
                                targetSim = pm.PyNode(
                                    source.swapNamespace(
                                        nspaceSim)).getShape()
                                pm.sets(SG, e=True, forceElement=targetSim)
                                targetSim.aiOpaque.set(
                                    source.getShape().aiOpaque.get())
                                targetSim.aiSubdivType.set(
                                    source.getShape().aiSubdivType.get())
                                targetSim.aiSubdivIterations.set(
                                    source.getShape().aiSubdivIterations.get())
                                targetSim.aiTraceSets.set('cast')
                                source.visibility.set(0)
                            else:
                                source.swapNamespace(nspaceSim).visibility.set(
                                    0)
                        except:
                            pass

                except:
                    failedNodes.append(str(pm.PyNode(node).shortName()))
                    pass

            #print('These objects couldn\'t be resolved: ' + str(failedNodes))

            #hide referenced asset
            transformNodes[0].visibility.set(0)

            pm.namespace(set=':')

        #copy objects from master layer to shadow layer
        renderNodes = pm.editRenderLayerMembers(workLayer,
                                                query=True,
                                                fullNames=True)
        renderPyNodes = []
        for node in renderNodes:
            renderPyNodes.append(pm.PyNode(node))

        try:
            pm.editRenderLayerMembers(shadowLayer, renderNodes)
            pm.editRenderLayerMembers(beautyLayer, renderNodes)
        except:
            print 'couldn\' copy objects to shadow layer'

        #make sure we are in the Default render layer
        workLayer.setCurrent()
        print 'Setting main render attributes'
        #set parameters on members
        for node in renderPyNodes:
            if node.nodeType() == 'transform':
                try:
                    mesh = node.getShape()
                except:
                    pass
            if node.nodeType() == 'transform' and node.hasAttr('asset'):
                try:
                    mesh.primaryVisibility.set(1)
                    mesh.aiTraceSets.set('cast')
                except:
                    pass
            elif node.nodeType() == 'transform' and mesh != None:
                if mesh.nodeType() == 'mesh':
                    mesh.primaryVisibility.set(1)
                    mesh.castsShadows.set(1)
                    mesh.aiSelfShadows.set(1)
                    mesh.aiOpaque.set(1)
                    mesh.aiTraceSets.set('shadow')
                    ProjectionSG = 'projection_matSG'
                    pm.sets(ProjectionSG, e=True, forceElement=mesh)

        #switch to Beauty render layer
        beautyLayer.setCurrent()
        print 'Setting overrides for Beauty Layer'
        # Apply layer overrides for shadows catchers and assets
        for node in renderPyNodes:
            if node.nodeType() == 'transform':
                try:
                    mesh = node.getShape()
                except:
                    pass
            if pm.nodeType(node) == 'transform' and node.hasAttr('asset'):
                mesh.primaryVisibility.set(1)
            elif node.nodeType() == 'transform' and node.getShape() != None:
                if mesh.nodeType() == 'mesh':
                    mel.eval(
                        'editRenderLayerAdjustment "%s.primaryVisibility";' %
                        mesh)
                    mesh.primaryVisibility.set(0)
            else:
                pass

        #switch to Shadow render layer
        shadowLayer.setCurrent()
        print 'Setting overrides for Shadow Layer'
        # Apply layer overrides for shadows catchers and assets
        for node in renderPyNodes:
            if node.nodeType() == 'transform':
                try:
                    mesh = node.getShape()
                except:
                    pass
            if pm.nodeType(node) == 'transform' and node.hasAttr('asset'):
                mel.eval('editRenderLayerAdjustment "%s.primaryVisibility";' %
                         mesh)
                mesh.primaryVisibility.set(0)
            elif node.nodeType() == 'transform' and node.getShape() != None:
                if mesh.nodeType() == 'mesh':
                    mel.eval(
                        'editRenderLayerAdjustment "%s.primaryVisibility";' %
                        mesh)
                    mesh.primaryVisibility.set(1)
                    # NAME OF SHADOW CATCHER IS HARDCODED HERE FOR NOW#
                    ShadowCatcherSG = 'ShadowCatcher_matSG'
                    pm.sets(ShadowCatcherSG, e=True, forceElement=mesh)
            else:
                pass

        workLayer.setCurrent()

        pm.confirmDialog(
            title='Report',
            message=
            ('New scene was created. These objects couldn\'t have shaders applied: )'
             + str(failedNodes)),
            button=['Ok', 'No'],
            defaultButton='Yes',
            cancelButton='No',
            dismissString='No')
Example #10
0
    def maya_light_setup(self, fields, tk, ctx):
        '''
        This script is errorring, but once it runs through everything is setup correctly
        so the errorr has ben put on hold. 
        Error:  Message: There was a problem starting the Tank Engine.
                Please contact [email protected]
                Exception: <class 'tank.errors.TankError'> - Key '<Tank StringKey Step>' in template '<Tank TemplatePath asset_work_area_maya: assets/{sg_asset_type}/{Asset}/work/{Step}/>' 
                could not be populated by context 'Asset arnoldTemplate' because the context does not contain a shotgun entity of type 'Step'!
        
        ------------------------------------
        
        Might need extra part at the end, which assigns objects to render layers. We haven't decided whether this needs to be implemented or not. 
       
        '''

        cmds.file(newFile=True, force=True)

        print('Communicating with shotgun, please wait!')

        temp_file = tk.templates['light_setup_temp']
        #fields_temp=ctx.as_template_fields(temp_file)
        #tempPath = temp_file.apply_fields(fields_temp)

        work_template = tk.templates['maya_shot_work']

        dst = temp_file.apply_fields(fields)

        try:
            pm.loadPlugin('mtoa.mll')
        except:
            pass

        #Open Arnold Renders Settings template

        arnoldSetup = "M:/00719_grandpa/assets/Environments/arnoldTemplate/publish/arnoldTemplate.rend.v001.ma"
        #print str(arnoldSetup)
        shutil.copyfile(arnoldSetup, dst)
        '''  
        arnoldSetup=su.getLatestShotAssets(self,'rend') 
        for file in arnoldSetup:
            #pm.system.openFile(file['path']['local_path_windows'], force=True)
            shutil.copyfile(file['path']['local_path_windows'], dst)
        '''

        pm.system.openFile(dst, force=True)

        #print ('path is' + tempPath)
        #pm.system.saveAs(tempPath)

        #scene_path = os.path.abspath(cmds.file(query=True, sn=True))
        #print scene_path

        print('getting latest shot assets')
        #reference light setup scene
        lightSetup = su.getLatestShotAssets(self, 'light')
        print lightSetup

        for asset in lightSetup:
            print('loading reference: ' +
                  (asset['path']['local_path_windows']))
            setNodes = mu.referenceAsset(asset['path']['local_path_windows'])

            for node in setNodes:
                #print ('node is: ' + node)
                if pm.nodeType(node) == 'mesh':
                    mesh = pm.PyNode(node)
                    #print ('mesh is: ' + mesh)
                    mesh.aiSelfShadows.set(0)
                    mesh.aiOpaque.set(0)
                    # NAME OF SHADOW CATCHER IS HARDCODED HERE FOR NOW#
                    ShadowCatcherSG = 'ShadowCatcher_matSG'
                    pm.sets(ShadowCatcherSG, e=True, forceElement=mesh)

        #referencing latest camera file
        print('getting latest cameras')
        camData = su.getLatestShotFile(tk, ctx, filetag='cam')

        #Checks if shot camera exists. If not tries to find asset camera related to the shot.
        print('referencing camera')
        for cam in camData:
            print('camera is: ' + cam['path']['local_path_windows'])
            camNodes = mu.referenceAsset(cam['path']['local_path_windows'])

        #connect camera to projection
        print('connecting camera to projection')
        for node in camNodes:
            if pm.nodeType(node) == 'camera':
                cam = pm.PyNode(node)
                print cam
                projection = pm.PyNode('projection')
                cam.message >> projection.linkedCamera

        #assign backplate to shadowcatcher material
        #tk=self.parent.tank

        #ctx=self.parent.context
        maya_work = tk.templates['shot_work_area']
        fields = ctx.as_template_fields(maya_work)

        low_plate = tk.templates['low_res_proxy_plate_path']
        plateDir = low_plate.parent.apply_fields(fields)
        print('plates: ' + plateDir)

        try:
            firstFile = os.listdir(plateDir)[0]
            imagePath = plateDir + '/' + firstFile
            pm.PyNode('backplate').fileTextureName.set(imagePath)
        except:
            pass

        #set Arnold DOF attribute on the camera
        cam.aiEnableDOF.set(1)

        #import alembic files and reference shaded assets
        shotAssets = su.getLatestShotAssets(self, 'shaded')
        print shotAssets

        shotCaches = su.getLatestShotFile(tk,
                                          ctx,
                                          publishedType='Alembic Cache')
        print shotCaches

        abc_template = tk.templates['cache_alembic']

        #for cache in shotCaches:
        input_path = shotCaches[0]['path']['local_path_windows']
        fields = abc_template.get_fields(input_path)
        for file in shotCaches:
            print('cache path: ' + file['path']['local_path_windows'])
            print file['name']
        print fields

        failedNodes = []
        for asset in shotAssets:
            try:
                print('loading reference for' + asset['assetName'])
                refNodes = mu.referenceAsset(
                    asset['path']['local_path_windows'])
                print refNodes
                fields['Asset'] = asset['assetName']
                abcFile = abc_template.apply_fields(fields)
                #make temporary namespace
                pm.namespace(add='temp')
                pm.namespace(set='temp')
                #import alembic cache for current asset
                grp = pm.group(em=True, name=asset['assetName'])
                print('loading alembic cache for' + asset['assetName'])
                mu.alembicImport(abcFile, 'parent', parent=grp)
                print('transfering shaders for' + asset['assetName'])
            except:
                print('asset wasn')

            transformNodes = []
            for node in refNodes:
                #collect all transform nodes
                if pm.nodeType(node) == 'transform':
                    transformNodes.append(pm.PyNode(node))

                try:
                    if pm.nodeType(node) == 'transform' and pm.PyNode(
                            node).hasAttr('asset'):
                        source = pm.PyNode(node)
                        shadingEngine = source.getShape().connections()
                        SG = str(shadingEngine[0].shortName())
                        target = pm.PyNode(
                            source.swapNamespace('temp')).getShape()
                        pm.sets(SG, e=True, forceElement=target)
                except:
                    failedNodes.append(str(pm.PyNode(node).shortName()))
                    pass

            print('These objects couldn\'t be resolved: ' + str(failedNodes))

            #hide referenced asset
            transformNodes[0].visibility.set(0)

            #clear the temp namespace
            pm.namespace(set=':')
            pm.namespace(mv=('temp', ':'))
            pm.namespace(rm='temp')

        #set rendertime subdivision on all meshes to catclark, 2 iterations
        meshes = pm.ls(type='mesh')

        shadowLayer = pm.PyNode('shadowLayer')
        masterLayer = pm.PyNode('defaultRenderLayer')

        #copy objects from master layer to shadow layer
        renderNodes = pm.editRenderLayerMembers(masterLayer, query=True)
        print
        try:
            pm.editRenderLayerMembers(shadowLayer, renderNodes)
        except:
            print 'couldn\' copy objects to shadow layer'

        #make sure we are in the Default render layer
        masterLayer.setCurrent()
        #set parameters on members
        for node in renderNodes:
            if pm.nodeType(node) == 'transform' and pm.PyNode(node).hasAttr(
                    'asset'):
                mesh = pm.PyNode(node).getShape()
                mesh.primaryVisibility.set(1)
                mesh.aiSubdivType.set(1)
                mesh.aiSubdivIterations.set(2)
            elif pm.nodeType(node) == 'transform':
                try:
                    mesh = pm.PyNode(node).getShape()
                    mesh.primaryVisibility.set(0)
                    mesh.aiSelfShadows.set(0)
                    mesh.aiOpaque.set(0)
                except:
                    print('This node is not a mesh: ' + node)
            else:
                pass

        #switch to Shadow render layer
        shadowLayer.setCurrent()
        # Apply layer overrides for shadows catchers and assets
        for node in renderNodes:
            if pm.nodeType(node) == 'transform' and pm.PyNode(node).hasAttr(
                    'asset'):
                mesh = pm.PyNode(node).getShape()
                mel.eval('editRenderLayerAdjustment "%s.primaryVisibility";' %
                         mesh)
                mesh.primaryVisibility.set(0)
            elif pm.nodeType(node) == 'transform':
                try:
                    mesh = pm.PyNode(node).getShape()
                    mel.eval(
                        'editRenderLayerAdjustment "%s.primaryVisibility";' %
                        mesh)
                    mesh.primaryVisibility.set(1)
                except:
                    print('This node is not a mesh: ' + node)
            else:
                pass
                #mesh.aiSelfShadows.set(0)
                #mesh.aiOpaque.set(0)

        pm.confirmDialog(
            title='Report',
            message=
            ('New scene was created. These objects couldn\'t have shaders applied: )'
             + str(failedNodes)),
            button=['Ok', 'No'],
            defaultButton='Yes',
            cancelButton='No',
            dismissString='No')
Example #11
0
 def setRenderLayer(self, layer, objects):
     pm.editRenderLayerMembers(layer, objects)
    def light_setup(self, fields, tk, ctx):       
        
        '''
        This script is errorring, but once it runs through everything is setup correctly
        so the errorr has ben put on hold. 
        Error:  Message: There was a problem starting the Tank Engine.
                Please contact [email protected]
                Exception: <class 'tank.errors.TankError'> - Key '<Tank StringKey Step>' in template '<Tank TemplatePath asset_work_area_maya: assets/{sg_asset_type}/{Asset}/work/{Step}/>' 
                could not be populated by context 'Asset arnoldTemplate' because the context does not contain a shotgun entity of type 'Step'!
        
        ------------------------------------
        
        Might need extra part at the end, which assigns objects to render layers. We haven't decided whether this needs to be implemented or not. 
       
        '''
        
        #cmds.file(newFile=True, force=True)
        
        print ('Communicating with shotgun, please wait!')
                        
         
        temp_file=tk.templates['light_setup_temp']
        #fields_temp=ctx.as_template_fields(temp_file)
        #tempPath = temp_file.apply_fields(fields_temp)
        
        tk.templates['maya_shot_work']
        
        dst=temp_file.apply_fields(fields)

        pm.loadPlugin('mtoa.mll',quiet=True)
        pm.loadPlugin('AbcExport.mll', quiet=True)  
        pm.loadPlugin('AbcImport.mll', quiet=True)         


        #Open Arnold Renders Settings template   
        arnoldSetup="M:/00719_grandpa/assets/Environments/arnoldTemplate/publish/arnoldTemplate.rend.v004.ma"
        
        #print str(arnoldSetup)
        shutil.copyfile(arnoldSetup, dst) 
              
        pm.system.openFile(dst, force=True)    
              
        print ('getting latest shot assets')
        #reference light setup scene 
        lightSetup=su.getLatestShotAssets(tk, ctx, publishedType='Maya Lighting')
        print lightSetup
        
        shadowLayer = pm.PyNode('setExtras')
        beautyLayer = pm.PyNode('beauty')
        workLayer = pm.PyNode('defaultRenderLayer')
        
        for asset in lightSetup: 
            print ('loading reference: ' + (asset['path']['local_path_windows']))      
            setNodes = mu.referenceAsset(asset['path']['local_path_windows'])

        workLayer.setCurrent()
            
        #referencing latest camera file 
        print ('getting latest cameras')
        camData=su.getLatestShotFile(tk, ctx, publishedType='Maya Camera')        
        
        maya_work=tk.templates['shot_work_area']        
        fields=ctx.as_template_fields(maya_work)
        
        low_plate=tk.templates['low_res_proxy_plate_path']
        plateDir=low_plate.parent.apply_fields(fields)
        
        qt_plate=tk.templates['quicktime_proxy_plate_path']
        qtplateDir=qt_plate.parent.apply_fields(fields)
        
        if len(os.listdir(qtplateDir)) > 0:
            firstMovie=os.listdir(qtplateDir)[0]       
            print ('moviePlate: ' + firstMovie)     
            moviePath=qtplateDir+'/'+firstMovie
        
        if len(os.listdir(plateDir)) > 0:  
            firstImage=os.listdir(plateDir)[0]    
            print ('imagePlate: ' + firstImage)        
            imagePath=plateDir+'/'+firstImage
        
        full_plate=tk.templates['full_res_proxy_plate_path']
        fullPlateDir=full_plate.parent.apply_fields(fields)
               
        try:
            firstImage=os.listdir(fullPlateDir)[0] 
            imagePath=fullPlateDir+'/'+firstImage
            pm.PyNode('backplate').fileTextureName.set(imagePath)    
        except:
            pass
               
        
        #Checks if shot camera exists. If not tries to find asset camera related to the shot.
        print ('referencing camera')
        try:
            for cam in camData:
                print ('camera is: ' + cam['path']['local_path_windows'])
                camNodes=mu.referenceAsset(cam['path']['local_path_windows'])
            
            print ('connecting camera to projection')      
             
            for node in camNodes:      
                if pm.nodeType(node) == 'camera':
                    cam=pm.PyNode(node)
                    print cam
                    projection = pm.PyNode('projection')
                    cam.message >> projection.linkedCamera                                      
                    #try for image planes---
                    try: 
                        IP = pm.PyNode(mu.imagePlane(cam, imagePath))
                        #mu.imagePlane(cam, imagePath)
                        IP.depth.set(1500)
                        IP.fit.set(0)
                        IP.width.set(960)
                        IP.height.set(540)
                        IP.sizeY.set(0.797)
                        IP.sizeX.set(1.417)
                    except:
                        print ('Backplate not found!!!')                             
                                                                                                  
        except:
            print ('Camera Trouble!!!')

              
        #assign backplate to shadowcatcher material

        
                   
        

        #import alembic files and reference shaded assets
        shotAssets=su.getLatestShotAssets(tk, ctx, publishedType='Maya Shaded Model') 
        
        animCaches=[] 
        animCaches= su.getLatestShotFile(tk, ctx, publishedType='Alembic Animation') 
        
        simCaches=[] 
        simCaches= su.getLatestShotFile(tk, ctx, publishedType='Alembic Simulation') 
        
        cachedAssets=[]
        for cache in animCaches:
            cachedAssets.append(cache['name'])
            
        simmedAssets=[]
        for cache in simCaches:
            simmedAssets.append(cache['name'])
        
        
        abc_template=tk.templates['cache_alembic']
        
            
        #for cache in animCaches:
        try:
            input_path=animCaches[0]['path']['local_path_windows']
            fields=abc_template.get_fields(input_path)   
            for f in animCaches:
                print ('cache path: ' + f['path']['local_path_windows'])
                print f['name']     
            print fields
        except:
            print ('Cache file not found!!!')
        
        importedCaches= []
        failedNodes= []
        #grp = pm.group( em=True, name='cache' )
        for asset in shotAssets:
            try:           
                print ('loading reference for' + asset['assetName']) 
                refNodes = mu.referenceAsset(asset['path']['local_path_windows'], namespace=(asset['assetName'] + 'Shaded'))
                print (asset['assetName'] + ' referenced')
                #make temporary namespace 
                nspaceAnim = (asset['assetName'] + 'Anim')
                pm.namespace( add=nspaceAnim)
                pm.namespace( set=nspaceAnim )
                #import alembic cache for current asset
                if asset['assetName'] in cachedAssets:
                    print ('Loading alembic cache for ' + asset['assetName'])
                    for cache in animCaches:
                        if cache['name'] == asset['assetName']:
                            print ('Abc File: ' + cache['path']['local_path_windows'])
                            #mu.alembicImport(cache['path']['local_path_windows'], 'parent', parent=grp)
                            abcNodes = mu.referenceAsset(cache['path']['local_path_windows'], namespace=nspaceAnim)
                            importedCaches.append(cache['path']['local_path_windows'])
                            print 'done'
                        else:
                            print cache['name']
                else:
                    print ('Cache not found: ' + asset['assetName'])
                   
                nspaceSim = (asset['assetName'] + 'Sim')
                pm.namespace( add=nspaceSim)
                pm.namespace( set=nspaceSim )
                #import alembic cache for current asset
                if asset['assetName'] in simmedAssets:
                    print ('Loading alembic cache for ' + asset['assetName'])
                    for cache in simCaches:
                        if cache['name'] == asset['assetName']:
                            print ('Abc File: ' + cache['path']['local_path_windows'])
                            #mu.alembicImport(cache['path']['local_path_windows'], 'parent', parent=grp)
                            abcNodes = mu.referenceAsset(cache['path']['local_path_windows'], namespace=nspaceSim)
                            importedCaches.append(cache['path']['local_path_windows'])
                            print 'done'
                        else:
                            print cache['name']
                
            except:
                print ('Something went wrong with ' + asset['assetName'])
            
            transformNodes = []
            print ('transfering shaders for: ' + asset['assetName'])
            for node in refNodes:
                #collect all transform nodes
                if pm.nodeType(node)=='transform':
                    transformNodes.append(pm.PyNode(node))         
                try:
                    if pm.nodeType(node) == 'transform' and pm.PyNode(node).hasAttr('asset'): 
                        source = pm.PyNode(node)
                        shadingEngine = source.getShape().connections()
                        SG = str(shadingEngine[0].shortName())
                        target = pm.PyNode(source.swapNamespace(nspaceAnim)).getShape() 
                        pm.sets(SG, e=True, forceElement=target)                                                
                        target.aiOpaque.set(source.getShape().aiOpaque.get())
                        target.aiSubdivType.set(source.getShape().aiSubdivType.get())
                        target.aiSubdivIterations.set(source.getShape().aiSubdivIterations.get()) 
                        target.aiTraceSets.set('cast') 
                        try:
                            if source.swapNamespace(nspaceSim).hasAttr('sim'):
                                targetSim = pm.PyNode(source.swapNamespace(nspaceSim)).getShape()   
                                pm.sets(SG, e=True, forceElement=targetSim)                                                
                                targetSim.aiOpaque.set(source.getShape().aiOpaque.get())
                                targetSim.aiSubdivType.set(source.getShape().aiSubdivType.get())
                                targetSim.aiSubdivIterations.set(source.getShape().aiSubdivIterations.get()) 
                                targetSim.aiTraceSets.set('cast')   
                                source.visibility.set(0)
                            else:
                                source.swapNamespace(nspaceSim).visibility.set(0)
                        except:
                            pass    
                                          
                except:
                    failedNodes.append(str(pm.PyNode(node).shortName()))
                    pass 
                                                    
            #print('These objects couldn\'t be resolved: ' + str(failedNodes))   
            
            #hide referenced asset
            transformNodes[0].visibility.set(0)

            pm.namespace( set=':' )

        #copy objects from master layer to shadow layer
        renderNodes = pm.editRenderLayerMembers(workLayer, query=True, fullNames=True)
        renderPyNodes =[]
        for node in renderNodes:
            renderPyNodes.append(pm.PyNode(node))
        
        try:
            pm.editRenderLayerMembers(shadowLayer, renderNodes)
            pm.editRenderLayerMembers(beautyLayer, renderNodes)
        except:
            print 'couldn\' copy objects to shadow layer'
          
        #make sure we are in the Default render layer    
        workLayer.setCurrent() 
        print 'Setting main render attributes'
        #set parameters on members 
        for node in renderPyNodes:
            if  node.nodeType() == 'transform':
                try:
                    mesh = node.getShape()
                except:
                    pass    
            if  node.nodeType() == 'transform' and node.hasAttr('asset') :
                try:            
                    mesh.primaryVisibility.set(1)
                    mesh.aiTraceSets.set('cast')  
                except:
                    pass
            elif node.nodeType() == 'transform' and mesh!=None:
                if mesh.nodeType() == 'mesh':
                    mesh.primaryVisibility.set(1)
                    mesh.castsShadows.set(1)
                    mesh.aiSelfShadows.set(1)
                    mesh.aiOpaque.set(1)
                    mesh.aiTraceSets.set('shadow')  
                    ProjectionSG = 'projection_matSG'
                    pm.sets(ProjectionSG, e=True, forceElement=mesh)         
        
        #switch to Beauty render layer        
        beautyLayer.setCurrent()    
        print 'Setting overrides for Beauty Layer'
        # Apply layer overrides for shadows catchers and assets    
        for node in renderPyNodes:
            if  node.nodeType() == 'transform':
                try:
                    mesh = node.getShape()
                except:
                    pass  
            if  pm.nodeType(node) == 'transform' and node.hasAttr('asset'):            
                mesh.primaryVisibility.set(1)
            elif node.nodeType() == 'transform' and node.getShape()!=None:
                if mesh.nodeType() == 'mesh':
                    mel.eval('editRenderLayerAdjustment "%s.primaryVisibility";' % mesh)
                    mesh.primaryVisibility.set(0)
            else:
                pass
                
        #switch to Shadow render layer        
        shadowLayer.setCurrent() 
        print 'Setting overrides for Shadow Layer'   
        # Apply layer overrides for shadows catchers and assets    
        for node in renderPyNodes:
            if  node.nodeType() == 'transform':
                try:
                    mesh = node.getShape()
                except:
                    pass  
            if  pm.nodeType(node) == 'transform' and node.hasAttr('asset'):
                mel.eval('editRenderLayerAdjustment "%s.primaryVisibility";' % mesh)
                mesh.primaryVisibility.set(0)
            elif node.nodeType() == 'transform' and node.getShape()!=None:
                if mesh.nodeType() == 'mesh':
                    mel.eval('editRenderLayerAdjustment "%s.primaryVisibility";' % mesh)
                    mesh.primaryVisibility.set(1)                 
                    # NAME OF SHADOW CATCHER IS HARDCODED HERE FOR NOW#                    
                    ShadowCatcherSG = 'ShadowCatcher_matSG'
                    pm.sets(ShadowCatcherSG, e=True, forceElement=mesh)
            else:
                pass

        workLayer.setCurrent() 

        
        pm.confirmDialog( title='Report', message=('New scene was created. These objects couldn\'t have shaders applied: )' + str(failedNodes)), button=['Ok', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
        
Example #13
0
    def create(self):
        """ Create the render layer.  This will generate the colors for
        each namespace, create flat shaders for each of these colors per
        namespace. A namespace render layer is also generated in maya.
        """
        # Query for the shading group set
        assigned = pm.sets("initialShadingGroup", query=True)
        if assigned:
            # Create new lambert shader
            default_lambert = pm.shadingNode("lambert", asShader=True)
            attrs = default_lambert.listAttr(scalar=True, read=True, settable=True, keyable=True)
            for attr in attrs:
                num_child_attrs = pm.attributeQuery(
                    attr.name(includeNode=False),
                    node="lambert1",
                    numberOfChildren=True
                )
                plug = attr.listConnections(plugs=True, destination=False, source=True)

                if plug:
                    attr.connectAttr(plug[0])

                elif num_child_attrs:
                    attr_val = pm.getAttr('lambert1.{0}'.format(attr))
                    default_lambert.setAttr(attr_val)
                    # Add parent attribute if there are any
                    parent_attr = pm.attributeQuery(attr, lp=True, n="lambert1")
                    if parent_attr and parent_attr[0] not in attrs:
                        attrs.append(parent_attr[0])

            shading_group = pm.sets(renderable=True, noSurfaceShader=True)
            default_lambert.connectAttr(
                'outColor',
                '{0}.surfaceShader'.format(shading_group.name()),
                f=True
            )
            for item in assigned:
                is_object = pm.ls(item, o=True)
                if is_object:
                    try:
                        shade_remove = pm.sets(item.name(),
                                               rm='initialShadingGroup',
                                               e=True)
                        pm.sets(item, e=True, fe=shading_group)
                    except RuntimeError:
                        shade_remove = None
                        print "Problem removing " + str(item) + " from the initialShadingGroup"
        # Get namespaces and generate colors based on those namespaces
        self.get_namespaces()
        self.get_namespace_colors()
        # Must replace with internal object function
        # _getNamespaceInfoFromStructureFile(self.struc, self.namespaces,
        #                                    [], [], [], [], [])

        # _getColors(self.namespaces, self.colors)
        old_namespace = pm.namespaceInfo(currentNamespace=True)
        old_render_layer = pm.editRenderLayerGlobals(q=True, currentRenderLayer=True)
        layer = ""
        for i, cur_namespace in enumerate(self.namespaces):
            # Will probably need to remove
            if cur_namespace == 'stereoCam':
                continue

            if layer == '':
                layer = pm.createRenderLayer(makeCurrent=True, name="namespaceLayer")

            if not pm.namespace(set=(":" + str(cur_namespace))):
                continue

            (red, green, blue) = self.colors[i]
            dag_namespace = pm.namespaceInfo(dp=1, lod=True)
            pm.select(dag_namespace, replace=True)
            geom = pm.ls(visible=True, type=['mesh', 'nurbsSurface'], dag=True, ni=True, selection=True)
            gpu_mesh = []
            if pm.objectType(tagFromType="rfxAlembicMeshGpuCache"):
                gpu_mesh = pm.ls(selection=True, visible=True, dag=True, noIntermediate=True,
                                 type="rfxAlembicMeshGpuCache", long=True)

            pm.select(clear=True)
            if len(geom)>0:
                material=str(shadingNode('surfaceShader', asShader=True))
                setAttr((material + ".outColor"),
                    red,green,blue,
                    type='double3')
                shader=str(cmds.sets(renderable=True,
                                     noSurfaceShader=True, empty=True))
                connectAttr((material + ".outColor"),(shader + ".surfaceShader"),
                    f=True)
                for j in range(0,len(geom)):
                    existingShaders=listConnections(geom[j],
                        source=False,
                        plugs=False,
                        destination=True,
                        type="shadingEngine")
                    if len(existingShaders)>0:
                        editRenderLayerMembers(layer,geom[j])
                        retry=0
                        # first try to set the shader in object mode
                        retry=1
                        # Use shading group hijack method for everything...
                        #if (catch(`sets -noWarnings -forceElement $shader $geom[$j]`)) {
                        #    $retry = 1;
                        #}
                        if retry == 1:
                            # Couldn't assign shader. Various alternative approaches to assigning the shader have not worked 100% of the time.
                            # So add a couple of extra attributes to the shadingGroup - defaultShader and namespaceShader, and connect the respective
                            # shaders to these. During pushRenderLayer (PlayblastTool), check for the existence of the namespaceShader, and if present,
                            # find it's connection and plug it into the surfaceShader attribute, thus "hijacking" the shading group. During popRenderLayer,
                            # connect the attribute plugged into defaultShader and plug this back into the surfaceShader attribute. This is messy, but it
                            # sidesteps material assignment alltogether.
                            for k in range(0,len(existingShaders)):
                                if not objExists(existingShaders[k] + ".defaultShader"):
                                    addAttr(existingShaders[k],
                                        ln="defaultShader",at="message")
                                    defaultMat=listConnections((existingShaders[k] + ".surfaceShader"),
                                        s=1,d=0)
                                    if len(defaultMat):
                                        connectAttr((defaultMat[0] + ".message"),(existingShaders[k] + ".defaultShader"))

                                    addAttr(existingShaders[k],
                                        ln="namespaceShader",at="message")
                                    connectAttr((material + ".message"),(existingShaders[k] + ".namespaceShader"))


                            retry=0
                            # temp until we feel confident retiring the next section of code

                        if retry == 1:
                            print "Using alternate shader assignment strategy on " + geom[j] + "\n"
                            # couldn't assign shader. Emergency fall-back: Switch back to defaultRenderLayer, unassign and re-assign the existing shaders, then
                            # switch back to namespace layer and try again.
                            existingShaders = self.stringArrayReverse(existingShaders)
                            """
                            To-do: Add an explanation about why reversing the shaders array is necessary once we've confirmed that we are good. -HM
                            """
                            # store the existing material assignments
                            comps=[]
                            indices=[]
                            for k in range(1,len(existingShaders)):
                                indices[k - 1]=len(comps)
                                assigned=cmds.sets(existingShaders[k],
                                    q=1)
                                for m in range(0,len(assigned)):
                                    obj=ls(o=assigned[m])
                                    if obj[0] == geom[j]:
                                        comps.append(assigned[m])



                            # unassign the existing materials
                            for k in range(0,len(existingShaders)):
                                cmds.sets(geom[j],
                                    rm=existingShaders[k],e=1)

                            if catch( lambda: cmds.sets(geom[j],
                                noWarnings=1,forceElement=shader) ):
                                mel.warning("Couldn't "
                                            "assign namespace shader to " + geom[j])
                                continue


                            else:
                                print ("DeepPlayblastUtilities: Alternate "
                                       "shader assignment worked for " +
                                       geom[j] + ".\n")

                            editRenderLayerGlobals(currentRenderLayer="defaultRenderLayer")
                            # switch back to defaultRenderLayer
                            # and re-assign (assign first shader to whole
                            # object, then component assign subsequent shaders)
                            cmds.sets(geom[j],
                                e=1,fe=existingShaders[0])
                            for k in range(0,len(indices)):
                                end = (int((k<len(indices) - 1) and
                                           indices[k + 1] or (len(comps))))
                                for m in range(indices[k],end):
                                    cmds.sets(comps[m],
                                        e=1,fe=existingShaders[k + 1])


                            # switch to namespace layer
                            editRenderLayerGlobals(currentRenderLayer=layer)

            if len(gpu_mesh)>0:
                # end if size($existingShaders)
                for j in range(0,len(gpu_mesh)):
                    pm.editRenderLayerMembers(layer,gpu_mesh[j])
                    pm.setAttr((gpu_mesh[j] + ".defaultColor"),
                        red,green,blue,
                        type='double3')
                    pm.setAttr((gpu_mesh[j] + ".colorsMode"), 0)
                    self.gpu_meshes.append(gpu_mesh[j])



        if layer != "":
            pm.namespace(set=old_namespace)
            pm.editRenderLayerGlobals(currentRenderLayer=old_render_layer)

        self.layer = layer
        self.gpu_meshes = list(set(self.gpu_meshes))
    def maya_light_setup(self, fields, tk, ctx):       
        
        '''
        This script is errorring, but once it runs through everything is setup correctly
        so the errorr has ben put on hold. 
        Error:  Message: There was a problem starting the Tank Engine.
                Please contact [email protected]
                Exception: <class 'tank.errors.TankError'> - Key '<Tank StringKey Step>' in template '<Tank TemplatePath asset_work_area_maya: assets/{sg_asset_type}/{Asset}/work/{Step}/>' 
                could not be populated by context 'Asset arnoldTemplate' because the context does not contain a shotgun entity of type 'Step'!
        
        ------------------------------------
        
        Might need extra part at the end, which assigns objects to render layers. We haven't decided whether this needs to be implemented or not. 
       
        '''        
        
        cmds.file(newFile=True, force=True)
        
        print ('Communicating with shotgun, please wait!')
                        
         
        temp_file=tk.templates['light_setup_temp']
        #fields_temp=ctx.as_template_fields(temp_file)
        #tempPath = temp_file.apply_fields(fields_temp)
        
        work_template=tk.templates['maya_shot_work']
        
        dst=temp_file.apply_fields(fields)

        
        try:
            pm.loadPlugin('mtoa.mll')           
        except:
            pass

        
        #Open Arnold Renders Settings template
        
        arnoldSetup="M:/00719_grandpa/assets/Environments/arnoldTemplate/publish/arnoldTemplate.rend.v001.ma"
        #print str(arnoldSetup)
        shutil.copyfile(arnoldSetup, dst) 
        
        '''  
        arnoldSetup=su.getLatestShotAssets(self,'rend') 
        for file in arnoldSetup:
            #pm.system.openFile(file['path']['local_path_windows'], force=True)
            shutil.copyfile(file['path']['local_path_windows'], dst)
        ''' 
        
        pm.system.openFile(dst, force=True)    
        
        
        #print ('path is' + tempPath)
        #pm.system.saveAs(tempPath)
        
        
        #scene_path = os.path.abspath(cmds.file(query=True, sn=True))
        #print scene_path

        
        
        
        print ('getting latest shot assets')
        #reference light setup scene 
        lightSetup=su.getLatestShotAssets(self,'light')
        print lightSetup
    
        for asset in lightSetup: 
            print ('loading reference: ' + (asset['path']['local_path_windows']))      
            setNodes = mu.referenceAsset(asset['path']['local_path_windows'])
            
            for node in setNodes:
                #print ('node is: ' + node)
                if pm.nodeType(node) == 'mesh':
                    mesh = pm.PyNode(node)
                    #print ('mesh is: ' + mesh)       
                    mesh.aiSelfShadows.set(0)
                    mesh.aiOpaque.set(0)   
                    # NAME OF SHADOW CATCHER IS HARDCODED HERE FOR NOW#                    
                    ShadowCatcherSG = 'ShadowCatcher_matSG'
                    pm.sets(ShadowCatcherSG, e=True, forceElement=mesh)
                    
        
        #referencing latest camera file 
        print ('getting latest cameras')
        camData=su.getLatestShotFile(tk,ctx, filetag='cam')        
        
        #Checks if shot camera exists. If not tries to find asset camera related to the shot.
        print ('referencing camera')
        for cam in camData:
            print ('camera is: ' + cam['path']['local_path_windows'])
            camNodes=mu.referenceAsset(cam['path']['local_path_windows'])
        
        
                
        #connect camera to projection
        print ('connecting camera to projection')        
        for node in camNodes:       
            if pm.nodeType(node) == 'camera':
                cam=pm.PyNode(node)
                print cam
                projection = pm.PyNode('projection')
                cam.message >> projection.linkedCamera
              
        #assign backplate to shadowcatcher material
            #tk=self.parent.tank
            
            #ctx=self.parent.context
        maya_work=tk.templates['shot_work_area']        
        fields=ctx.as_template_fields(maya_work)
                   
        low_plate=tk.templates['low_res_proxy_plate_path']
        plateDir=low_plate.parent.apply_fields(fields)
        print ('plates: ' + plateDir)
        
        try:
            firstFile=os.listdir(plateDir)[0]
            imagePath=plateDir+'/'+firstFile
            pm.PyNode('backplate').fileTextureName.set(imagePath)    
        except:
            pass
               
        #set Arnold DOF attribute on the camera        
        cam.aiEnableDOF.set(1)

        
        #import alembic files and reference shaded assets
        shotAssets=su.getLatestShotAssets(self,'shaded') 
        print shotAssets
        
        shotCaches= su.getLatestShotFile(tk, ctx, publishedType = 'Alembic Cache') 
        print shotCaches
        
        abc_template=tk.templates['cache_alembic']
             
        #for cache in shotCaches:
        input_path=shotCaches[0]['path']['local_path_windows']
        fields=abc_template.get_fields(input_path)   
        for file in shotCaches:
            print ('cache path: ' + file['path']['local_path_windows'])
            print file['name']     
        print fields
        
        failedNodes= []
        for asset in shotAssets:
            try:           
                print ('loading reference for' + asset['assetName']) 
                refNodes = mu.referenceAsset(asset['path']['local_path_windows'])
                print refNodes
                fields['Asset']=asset['assetName']
                abcFile = abc_template.apply_fields(fields)
                #make temporary namespace
                pm.namespace(add='temp')
                pm.namespace(set='temp')
                #import alembic cache for current asset
                grp = pm.group( em=True, name=asset['assetName'] )
                print ('loading alembic cache for' + asset['assetName'])
                mu.alembicImport(abcFile, 'parent', parent=grp)
                print ('transfering shaders for' + asset['assetName'])
            except:
                print ('asset wasn')
            
            transformNodes = []
            for node in refNodes:
                #collect all transform nodes
                if pm.nodeType(node)=='transform':
                    transformNodes.append(pm.PyNode(node))
                    
                try:
                    if pm.nodeType(node) == 'transform' and pm.PyNode(node).hasAttr('asset'): 
                         source = pm.PyNode(node)
                         shadingEngine = source.getShape().connections()
                         SG = str(shadingEngine[0].shortName())
                         target = pm.PyNode(source.swapNamespace('temp')).getShape()
                         pm.sets(SG, e=True, forceElement=target)                       
                except:
                    failedNodes.append(str(pm.PyNode(node).shortName()))
                    pass 
                                         
            print('These objects couldn\'t be resolved: ' + str(failedNodes))   
            
            #hide referenced asset
            transformNodes[0].visibility.set(0)
            
            #clear the temp namespace  
            pm.namespace( set=':' )
            pm.namespace(mv=('temp', ':'))
            pm.namespace(rm='temp')
        
        
        #set rendertime subdivision on all meshes to catclark, 2 iterations
        meshes = pm.ls(type='mesh')
        
        shadowLayer = pm.PyNode('shadowLayer')
        masterLayer = pm.PyNode('defaultRenderLayer')
        
        #copy objects from master layer to shadow layer
        renderNodes = pm.editRenderLayerMembers(masterLayer, query=True )
        print
        try:
            pm.editRenderLayerMembers(shadowLayer, renderNodes)
        except:
            print 'couldn\' copy objects to shadow layer'
          
        #make sure we are in the Default render layer    
        masterLayer.setCurrent() 
        #set parameters on members 
        for node in renderNodes:
            if  pm.nodeType(node) == 'transform' and pm.PyNode(node).hasAttr('asset'):
                mesh = pm.PyNode(node).getShape()
                mesh.primaryVisibility.set(1)
                mesh.aiSubdivType.set(1);
                mesh.aiSubdivIterations.set(2);
            elif pm.nodeType(node) == 'transform':
                try:
                    mesh = pm.PyNode(node).getShape()
                    mesh.primaryVisibility.set(0)
                    mesh.aiSelfShadows.set(0)
                    mesh.aiOpaque.set(0)
                except:
                    print ('This node is not a mesh: ' + node)
            else:
                pass
                
                
                
        #switch to Shadow render layer        
        shadowLayer.setCurrent()    
        # Apply layer overrides for shadows catchers and assets    
        for node in renderNodes:
            if  pm.nodeType(node) == 'transform' and pm.PyNode(node).hasAttr('asset'):
                mesh = pm.PyNode(node).getShape()
                mel.eval('editRenderLayerAdjustment "%s.primaryVisibility";' % mesh)
                mesh.primaryVisibility.set(0)
            elif pm.nodeType(node) == 'transform':
                try:
                    mesh = pm.PyNode(node).getShape()
                    mel.eval('editRenderLayerAdjustment "%s.primaryVisibility";' % mesh)
                    mesh.primaryVisibility.set(1)
                except:
                    print ('This node is not a mesh: ' + node)
            else:
                pass
                #mesh.aiSelfShadows.set(0)
                #mesh.aiOpaque.set(0)
        
        pm.confirmDialog( title='Report', message=('New scene was created. These objects couldn\'t have shaders applied: )' + str(failedNodes)), button=['Ok', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No' )