Example #1
0
def select_attached(shadow_link=False):
    selection = cmds.ls(dag=1, o=1, s=1, sl=1)
    lights = cmds.ls(selection, type=["light"] + cmds.listNodeTypes("light"))
    selection = cmds.pickWalk(direction='down')

    if not selection and not lights: return "error:no_light_selection"

    attached_objs = []

    if lights:
        for sel in selection:
            attached_objs += cmds.lightlink(query=True,
                                            shadow=shadow_link,
                                            light=sel)
        select_nodes = cmds.ls(attached_objs, type=['mesh', 'nurbsSurface'])
    else:  # MESHES
        for sel in selection:
            attached_objs += cmds.lightlink(query=True,
                                            shadow=shadow_link,
                                            object=selection)
        select_nodes = cmds.ls(attached_objs,
                               type=["light"] + cmds.listNodeTypes("light"))

    if not select_nodes: return
    cmds.select(select_nodes)
    cmds.pickWalk(direction='up')
Example #2
0
    def init_data(self):
        arnold_shaders = cmds.listNodeTypes(
            'rendernode/arnold/shader/surface'
        )
        surface_shaders = ['standardSurface', ]
        if arnold_shaders:
            surface_shaders += arnold_shaders
        self.type_picker.clear()
        for item in surface_shaders:
            self.type_picker.addItem(item)

        _types = cmds.listNodeTypes('rendernode/arnold/shader/volume')
        _types = _types if _types else []
        for item in _types:
            self.type_picker.addItem(item)
Example #3
0
    def noIDs(self):
        sender = self.sender()
        if sender.text() == "Select All Objects Without Object ID":
            attr = "vrayObjectID"
            obj = cmds.ls(ni=True, type=["nurbsSurface", "mesh"])
        else:
            attr = "vrayMaterialId"
            obj = cmds.ls(type=cmds.listNodeTypes("shader"))

        noID = []
        if not obj == []:
            for o in obj:
                if self.selectWithID.checkState() == 0:
                    if not cmds.objExists("%s.%s" % (o, attr)):
                        noID.append(o)
                else:
                    if cmds.objExists("%s.%s" % (o, attr)):
                        ID = int(self.spinbox[0].value())
                        print int(self.spinbox[0].value())
                        print cmds.getAttr("%s.%s" % (o, attr))
                        if cmds.getAttr("%s.%s" % (o, attr)) == ID:
                            noID.append(o)
            if not noID == []:
                cmds.select(noID)
            else:
                cmds.select(d=True)
def findID(states=None):
    if states["objectOrMult"] == 2:
        attribute = "vrayObjectID"
        transforms = cmds.ls(type="transform")
        sel = cmds.listRelatives(transforms, shapes=True, fullPath=True, type=["mesh", "nurbsSurface"])
    if states["objectOrMult"] == 0:
        attribute = "vrayMaterialId"
        sel = cmds.ls(type=cmds.listNodeTypes("shader"))

    if sel:
        startIndex = cmds.getAttr("%s.%s" % (sel[0], attribute))
        endIndex = cmds.getAttr("%s.%s" % (sel[0], attribute))
        ids = []

        for s in sel:
            try:
                ID = cmds.getAttr("%s.%s" % (s, attribute))
                if ID < startIndex:
                    startIndex = ID
                if ID > endIndex:
                    endIndex = ID
                if not ID in ids:
                    ids.append(ID)
            except:
                pass
    return [startIndex, endIndex, ids]
Example #5
0
def export_lightlinks():
    
    raw_name, extension = os.path.splitext(cmds.file(q=True, sn=True, shn=True))
    if raw_name == "":
        filename = "untitled"
    else:
        filename = raw_name
    filepath = "{0}{1}.llink".format(cmds.workspace(q=True, rootDirectory=True),filename)
        
    lights = cmds.ls(type=["light"] + cmds.listNodeTypes("light"))
    
    shapeList = cmds.ls(objectsOnly=True, type="mesh" )
    transformList = cmds.listRelatives(shapeList, parent=True,)
    grouplist = cmds.listRelatives(transformList, parent=True)
    
    lightlinkobjectlist = shapeList + transformList + grouplist + cmds.ls(objectsOnly=True, type="objectSet") + cmds.ls(objectsOnly=True, type="shadingEngine" )
    
    lightlinks = {}
    for light in lights:
        links = cmds.lightlink( query=True, light=light)
        lightlinks.update( {light : list(links)} )
        
        #### breakmap
        lightbreakups = set(lightlinkobjectlist) - set(cmds.lightlink( query=True, light=light)) - {"defaultLightSet", "defaultObjectSet"}
    
        if list(lightbreakups) == []:
            lightbreakups = "none"
            lightlinks.update( {light + "_breakup" : lightbreakups} )
        else:
            lightlinks.update( {light + "_breakup" : list(lightbreakups)} )
          
    with open(filepath, 'w') as json_file:
      json.dump(lightlinks, json_file, indent=4, sort_keys=True)
    print "lightlinks exported to {0}".format(filepath)
Example #6
0
def copy_set_HDR():
    #get project path
    project_dir = mc.workspace(q=1, rd=1)
    print(project_dir)
    #get dome light
    lights = mc.ls(type=mc.listNodeTypes('light'))
    print(lights)
    #get domeTex node
    textureNodes = mc.listConnections(lights[0], type='file')
    print(textureNodes)
    #get HDR file
    texture_file = mc.getAttr(textureNodes[0] + '.fileTextureName')
    print(texture_file)
    file_name = texture_file.split('/')[-1]
    print(file_name)
    #copy file texture to project's sourceimages folder and set path or just set path if file already exists
    if (os.path.isfile(project_dir + '/sourceimages/' + file_name)):
        mc.setAttr(textureNodes[0] + '.fileTextureName',
                   'sourceimages/' + file_name,
                   type='string')
    else:
        shutil.copy(texture_file, project_dir + '/sourceimages/' + file_name)
        mc.setAttr(textureNodes[0] + '.fileTextureName',
                   'sourceimages/' + file_name,
                   type='string')
 def get_shader_node(self,plugins):
 	render_nodes = []
 	shader_nodes = mc.listNodeTypes('shader')
 	nodes = mc.pluginInfo(plugins, dn=1, query=True)
 	for i in shader_nodes:
 		if i in nodes:
 			render_nodes.append(i)
 	return render_nodes
Example #8
0
def create_mdl_list():
    mdllist = []
    for shaders in cmds.listNodeTypes('shader'):
        if 'mdl' in shaders:
            if shaders in mdllist:  # Check for dupe
                mdllist.append(shaders + '_copy')
            else:
                mdllist.append(shaders)
    return mdllist
Example #9
0
def light():
    """ check light
    """
    _lights = cmds.ls(type=cmds.listNodeTypes("light"))

    if _lights:
        info = "场景存在多余灯光节点\n"
        for _light in _lights:
            info += "{}\n".format(_light)
        return False, info
    return True, None
Example #10
0
def selection_light_linking(break_light=False,
                            exclusive="",
                            shadow_link=False):
    selection = cmds.ls(dag=1, o=1, s=1, sl=1)
    lights = cmds.ls(selection, type=["light"] + cmds.listNodeTypes("light"))
    meshes = list(set(selection) - set(lights))

    if not selection or not lights: return "error:no_light_selection"

    if exclusive == "lights":
        scene_lights = cmds.ls(type=["light"] + cmds.listNodeTypes("light"))
        exclude_lights = list(set(scene_lights) - set(lights))
        cmds.lightlink(light=exclude_lights,
                       object=meshes,
                       shadow=shadow_link,
                       b=True)

        LOG.info("exclude_lights: {}".format(exclude_lights))

    elif exclusive == "meshes":
        exclude_meshes = list(set(cmds.ls(dag=1, o=1, s=1)) - set(meshes))
        cmds.lightlink(light=lights,
                       object=exclude_meshes,
                       shadow=shadow_link,
                       b=True)

        LOG.info("exclude_meshes: {}".format(exclude_meshes))

    if not meshes:
        cmds.lightlink(light=lights,
                       object=cmds.ls(dag=1, o=1, s=1),
                       shadow=shadow_link)
        LOG.info("LightLinking: Default for {}".format(lights))
        return

    cmds.lightlink(light=lights,
                   object=meshes,
                   shadow=shadow_link,
                   b=break_light)
    LOG.debug("LightLinking - break:{} - shadow:{}: {} with {}".format(
        break_light, shadow_link, lights, meshes))
def create_mdl_list():
    mdllist = []
    # for shaders in cmds.listNodeTypes('shader'):
    # 	if 'mdl' in shaders:
    # 		if shaders in mdllist: # Check for dupe
    # 			mdllist.append(shaders + '_copy')
    # 		else:
    # 			mdllist.append(shaders)
    for shaders in cmds.listNodeTypes('shader'):
        if 'mdl' in shaders and shaders not in mdllist:
            mdllist.append(shaders)
    return mdllist
Example #12
0
 def get_type_nodes(self, engine, node_type):
     engine_nodes = []
     plugin_nodes = self.get_engine_nodes(engine)
     type_nodes = cmds.listNodeTypes(node_type)
     for node in type_nodes:
         if engine != 'mayaSoftware':
             if node in plugin_nodes:
                 engine_nodes.append(node)
         else:
             if node not in self.all_plugins_nodes:
                 engine_nodes.append(node)
     return engine_nodes
Example #13
0
 def get_shader_node(self,plugins):
     render_nodes = []
     shader_nodes = mc.listNodeTypes('shader')
     nodes = mc.pluginInfo(plugins, dn=1, query=True)
     for i in shader_nodes:
         if i in nodes:
             render_nodes.append(i)
     for j in ignore_shader:
         try:
             render_nodes.remove(j)
         except:
             pass
     return render_nodes
Example #14
0
def getRenderNodes():
    """
    List all valid render nodes in scene
    """
    # Get Node Types
    renderTypes = cmds.listNodeTypes('texture')
    renderTypes.extend(cmds.listNodeTypes('utility'))
    renderTypes.extend(cmds.listNodeTypes('imageplane'))
    renderTypes.extend(cmds.listNodeTypes('shader'))

    # Get Nodes by Type
    renderNodes = cmds.ls(long=True, type=renderTypes)
    if not renderNodes: renderNodes = []
    mrRenderNodes = cmds.lsThroughFilter('DefaultMrNodesFilter')
    if not mrRenderNodes: mrRenderNodes = []
    renderNodes.extend(mrRenderNodes)

    # Remove Duplicates
    renderNodes = list(set(renderNodes))

    # Return Result
    return renderNodes
Example #15
0
def getRenderNodes():
    """
    List all valid render nodes in scene
    """
    # Get Node Types
    renderTypes = cmds.listNodeTypes('texture')
    renderTypes.extend(cmds.listNodeTypes('utility'))
    renderTypes.extend(cmds.listNodeTypes('imageplane'))
    renderTypes.extend(cmds.listNodeTypes('shader'))

    # Get Nodes by Type
    renderNodes = cmds.ls(long=True, type=renderTypes)
    if not renderNodes: renderNodes = []
    mrRenderNodes = cmds.lsThroughFilter('DefaultMrNodesFilter')
    if not mrRenderNodes: mrRenderNodes = []
    renderNodes.extend(mrRenderNodes)

    # Remove Duplicates
    renderNodes = list(set(renderNodes))

    # Return Result
    return renderNodes
def linkedShaders(states, operation=None):
    #Finding All Shaders
    shadersInScene = cmds.ls(type=cmds.listNodeTypes("shader"))
    geoInScene = cmds.ls(ni=True, type=["mesh", "nurbsSurface"])
    sel = cmds.ls(sl=True)
    files = []

    #Find References From Selection
    for s in sel:
        if ":" in s:
            ref = cmds.referenceQuery(s, filename=True)
            if not ref in files:
                files.append(ref)

    #Give The Mattes a Name
    matteName = str(states["matteName"])
    nodes=[]
    i=0

    #Create Render Layer
    if states["createRenderLayer"] == 2:
        for f in files:
            referenceNodes = cmds.referenceQuery(f, nodes=True)
            shaderNodes = list(set(referenceNodes) & set(shadersInScene))
            if ":" in shaderNodes[0]:
                nodes.append(shaderNodes[0].split(":")[0])
        if nodes:
            createRenderlayers(states, nodes)

    #Find Objects or Shaders and set the ID
    for f in files:
        referenceNodes = cmds.referenceQuery(f, nodes=True)
        if states["objectOrMult"] == 2:
            shaderNodes = list(set(referenceNodes) & set(geoInScene))
        if states["objectOrMult"] == 0:
            shaderNodes = list(set(referenceNodes) & set(shadersInScene))

        if shaderNodes:
            if ":" in shaderNodes[0]:
                mattePrefix = shaderNodes[0].split(":")[0]
                states["matteName"] = "%s_%s" % (matteName, mattePrefix)

                #Create ID's
                endID = setVrayID(states, operation, shaderNodes)

                if operation == "singleID":
                    states["startIndex"] = states["startIndex"] + 1
                else:
                    states["startIndex"] = states["startIndex"] + int(endID)
Example #17
0
def light():
    """ clear light

    """
    _lights = cmds.ls(type=cmds.listNodeTypes("light"))

    if _lights:
        for _light in _lights:
            try:
                #if cmds.objExists(_light):
                if cmds.referenceQuery(_light, isNodeReferenced=True) == False:
                    par = cmds.listRelatives(_light, p=True)
                    cmds.delete(par)
            except Exception as e:
                logger.warning(e)
Example #18
0
def lightingOverride(rsLayer):
    try:
        lightColl = rsLayer.createCollection('Lighting') 
        allLights = cmds.ls(type = cmds.listNodeTypes("light"))
        myList = '*;*'.join(allLights)
        lightColl.getSelector().setPattern("*")
        lightingOverride = lightColl.createOverride("LightingOverride", OpenMaya.MTypeId(0x58000378))
        lightColl.getSelector().setFilterType(4)
          
        plug = '%s.intensity' % allLights[0]
        lightingOverride.setAttributeName(plug)
        lightingOverride.finalize(plug)
        lightingOverride.setAttrValue(0)
        print allLights[0]
    except:
        pass
Example #19
0
    def list_lights(self, engine, selected=True, in_render=True):
        if in_render:
            light_types = self.get_type_nodes(engine, 'light')
        else:
            light_types = cmds.listNodeTypes('light')

        if light_types:
            if selected:
                selection = cmds.ls(sl=True)
                selection_shapes = self.get_shapes_from_objects(selection)
                light_shape_names = cmds.ls(selection_shapes, type=light_types)
            else:
                light_shape_names = cmds.ls(type=light_types)
        else:
            light_shape_names = []
        return light_shape_names
Example #20
0
    def list_utilities(self, engine, selected=True, in_render=True):
        if in_render:
            type_list = self.get_type_nodes(engine, 'utility')  # only from specific render engine
        else:
            type_list = cmds.listNodeTypes('utility')  # all utilities

        if selected:
            selection = cmds.ls(sl=True)
            utilities = cmds.ls(selection, type=type_list)
        else:
            utilities = cmds.ls(type=type_list)

        exclude_software = self.get_type_nodes('mayaSoftware', 'utility')
        ignore_utilities = cmds.ls(type=exclude_software)
        correct_utilities = [i for i in utilities if i not in ignore_utilities]

        return correct_utilities
Example #21
0
 def findIn(self, nodeNames, includeSelf=True):
     '''Generator that returns all the collections in that layer that contain at least on of the 
     object in nodeNames. Optionally also returns self (with includeSelf=True) if the object is in the layer.'''
     found = False
     for collection in utils.getCollectionsRecursive(self):
         if next((n for n in nodeNames if n in collection.getSelector().names()), False):
             found = True
             yield collection
     
     if includeSelf:
         if found:
             yield self
         elif not self.hasLightsCollectionInstance():
             lightTypes = cmds.listNodeTypes('light')
             def isLight(name):
                 return next((t for t in lightTypes if cmds.objectType(name, isAType=t)), False)
             if next((n for n in nodeNames if isLight(n)), False):
                 yield self
Example #22
0
    def doCheck(self):

        # Create an empty array for holding each target node found
        #sceneScan = [[0 for x in range(1)] for y in range(1)]
        sceneScan = []
        # Array for carrying existing results
        countHold = 0
        foundHold = ''
        fndMax = 0
        plural = 's'
        formString = ''
        # String to be returned
        enumReport = "This scene has "

        # Array for nodes associated with animation
        #sceneScan[0][0] = "animation"
        sceneScan = cmds.listNodeTypes("camera")

        scanRng = len(sceneScan)

        for i in range(0, scanRng):
            seenIt = []
            for clue in sceneScan:
                if cmds.ls(type=clue):
                    seenIt.extend(cmds.ls(type=clue))

        reduction = set(seenIt)

        if reduction:
            countHold = len(reduction)

        if countHold == 1:
            plural = ''

        formString = str(countHold) + " camera node" + plural + '.'
        enumReport += formString

        if countHold == 0:
            enumReport = ''

        return enumReport
Example #23
0
def export_animation(export_path):
    if not export_path.endswith('.ma'):
        export_path += '.ma'
    # 1: export maya file with anim layers, curves, and blend nodes:
    blend_types = [
        t for t in mc.listNodeTypes('animation') if t.startswith('animBlend')
    ]
    blenders = mc.ls(type=blend_types)
    curves = get_anim_curves()
    layers = mc.ls(type='animLayer')
    mc.select(blenders + curves + layers)
    mc.file(export_path,
            typ='mayaAscii',
            force=True,
            prompt=False,
            exportSelectedStrict=True,
            constructionHistory=False)
    # 2: export list of connections to recover
    source_nodes = curves + blenders
    connections = []
    targets = set(
        mc.listConnections(source_nodes, destination=True, plugs=True))
    for target in targets:
        target_node = target.split('.')[0]
        if target_node in source_nodes:
            # Connections between each other are already in export maya file
            continue
        node_type = mc.nodeType(target_node)
        if node_type == 'animLayer' or 'EditorInfo' in node_type:
            continue
        for source in mc.listConnections(target, source=True, plugs=True):
            source_node = source.split('.')[0]
            if source_node not in source_nodes:
                continue
            connection = (source, target)
            if connection not in connections:
                connections.append(connection)
    with open(export_path + '.json', 'w') as f:
        json.dump(connections, f, indent=4)
Example #24
0
def get_unused_utility_nodes():
    u"""未使用のユーティリティノードのリストを返す

    :return: 未使用のユーティリティノードのリスト
    :rtype: list of unicode
    """
    utility_node_types = cmds.listNodeTypes("utility")
    utility_nodes = []
    for ul in utility_node_types:
        nodes = cmds.ls(type=ul)
        if not nodes:
            continue
        utility_nodes.extend(nodes)

    unused = []
    for u in utility_nodes:
        if not [
                x for x in cmds.listConnections(u)
                if x != "defaultRenderUtilityList1"
        ]:
            unused.append(u)
    return unused
Example #25
0
def isExistingClassification(t):
    try: return t and cmds.listNodeTypes(t) is not None
    except: return False
Example #26
0
def get_all_lights():
    all_lights = [node for node in cmds.ls(type=["light"] + cmds.listNodeTypes("light"))]
    return all_lights
Example #27
0
    def getMembers(self):
        """ Get the names of the layer's DAG node members.

            The layer's members are DAG nodes selected by the layer's
            collections, based on whether a collection is enabled or solo'ed. 
            
            @rtype: list
            @return: list of node names. Empty if none found.
        """

        with profiler.ProfilerMgr('RenderLayer::getMembers'):

            # Collection membership has the following properties:
            #
            # o The union of top-level collection members defines the
            #   render layer membership.
            # o Sub-collections filter their parent's objects, so they are
            #   always subsets of their parents.
            # o Collections exclude objects when disabled, and include
            #   objects when enabled.
            # o Explicitly including / excluding a DAG parent
            #   includes / excludes its children.
            # o Collections are processed in depth-first order, lowest
            #   priority to highest priority.  Later, higher-priority
            #   collection exclusions or inclusions replace earlier,
            #   lower-priority ones.
            #
            # Collection membership is also determined by a collection's
            # isolate select boolean flag.  Conceptually, isolate select is
            # a mode where only isolate selected collections are considered
            # when determining render layer membership.  Isolate select
            # mode is on when one or more collections are isolate
            # selected.  Isolate select has the following additional
            # properties:
            # 
            # o All ancestor collections of an isolate selected collections
            #   are enabled.  They do not contribute to render layer
            #   membership, but their overrides will be applied.  This is
            #   to support use cases where ancestor collections modify a
            #   child collection's transform: keeping the ancestors of that
            #   child enabled keeps the parent transform of the child
            #   collection's objects unchanged.
            # o All descendant collections of an isolate selected
            #   collection are enabled, and contribute to render layer
            #   membership.  Conceptually, isolate selecting a collection
            #   includes that collection's subtree into the render layer.
            #
            # The algorithm for determining membership proceeds
            # sequentially on the depth-first ordering of collections,
            # adding in members from enabled collections, and excluding
            # members from disabled collections.
            #
            # There is one important complexity that stems from the fact
            # that setting a DAG parent as member implicitly makes its
            # children members as well.  If only a subset of its children
            # must be excluded, we cannot make the parent member of the
            # layer.

            members = memberSet.MemberSet()
            
            if not self.hasLightsCollectionInstance():
                lights = itertools.ifilter(None, (commonUtils.nameToDagPath(name) for name in cmds.ls(type=cmds.listNodeTypes('light'))))
                reduce(lambda memberset,path: members.include(path), lights, members)
            
            isolateSelectMode = not cmds.about(batch=True) and (self.getNumIsolatedChildren() > 0)
            
            for c in traverse.depthFirst(self, memberTraversal):
                if not isinstance(c, collection.Collection):
                    continue

                # In isolate select mode, if a collection isn't isolate selected and
                # has no isolate selected ancestors, it's ignored.
                hasNoIsolatedAncestors = (c.getNumIsolatedAncestors() == 0)
                if isolateSelectMode and not c.isIsolateSelected() and hasNoIsolatedAncestors and \
                    not isinstance(c, collection.LightsCollection) and not isinstance(c, collection.LightsChildCollection):
                    # Lights cannot be isolate selected.  The following ensures they're visible when other collections are isolate selected.  
                    # MAYA-70684: a more maintainable solution should be found.
                    continue

                # The collection selector has a cache, which will always be hit once on
                # layer switching (to apply overrides).  Therefore, there is no need to
                # cache or be lazy in accessing the collection's members.
                nodes = [n for n in c.getSelector().getAbsoluteNames() if n.startswith('|')]
                paths = itertools.ifilter(None, (commonUtils.nameToDagPath(path) for path in nodes)) 
                
                mtd = memberSet.MemberSet.include if c.isEnabled() else memberSet.MemberSet.exclude
                reduce(lambda memberset,path: mtd(members, path), paths, members)
            
            included = set(p.fullPathName() for p in members.paths())

            return included
Example #28
0
    def init_data(self):
        self.beginResetModel()

        arnold_shaders = cmds.listNodeTypes(
            'rendernode/arnold/shader/surface'
        )
        surface_shaders = ['standardSurface', ]
        if arnold_shaders:
            surface_shaders += arnold_shaders

        self.internal_data = {}
        for node in cmds.ls(type='shadingEngine'):
            for attr in cmds.listAttr(node):
                if '.' in attr:
                    continue
                if cmds.attributeQuery(attr, node=node, internal=True):
                    continue
                if not cmds.attributeQuery(attr, node=node, writable=True):
                    continue
                if cmds.attributeQuery(attr, node=node, listParent=True):
                    continue
                _type = cmds.getAttr(f'{node}.{attr}', type=True)
                if _type not in ('float3', 'float', 'Tdata'):
                    continue
                if any(f in attr for f in ('Camera', 'Id', 'Matte', 'Direction')):
                    continue

                if cmds.connectionInfo(f'{node}.{attr}', isDestination=True):
                    source = cmds.connectionInfo(
                        f'{node}.{attr}', sourceFromDestination=True
                    )
                    shader = source.split('.')[0]

                    if cmds.objectType(shader) not in surface_shaders:
                        continue

                    if not re.match(r'.*[a-zA-Z0-9]+_[a-zA-Z0-9]+_shader$', shader):
                        continue

                    attrs = get_attrs(shader)
                    cnxs = [
                        a for a in attrs if
                        cmds.connectionInfo(f'{shader}.{a}', id=True)
                    ]

                    item_data = {
                        QtCore.Qt.DisplayRole: shader,
                        'shader': shader,
                        'type': cmds.objectType(shader),
                        'shadingEngine': node,
                        'attributes': attrs,
                        'connections': cnxs,
                        'shapes': []
                    }

                    nodes = cmds.sets(node, query=True)
                    nodes = nodes if nodes else []

                    for _node in nodes:
                        for n in cmds.ls(_node, long=True):
                            item_data['shapes'].append(n)
                    item_data['shapes'] = sorted(item_data['shapes'])
                    self.internal_data[len(self.internal_data)] = item_data

        self.endResetModel()
def isAMaterial(node):
    """Returns true if the given node is a type of material node"""
    return cmds.nodeType(node) in cmds.listNodeTypes("shader")
Example #30
0
def isATexture(node):
    """Returns true if the given node is a type of texture node"""
    return cmds.nodeType(node) in cmds.listNodeTypes("texture")
def isATexture(node):
    """Returns true if the given node is a type of texture node"""
    return cmds.nodeType(node) in cmds.listNodeTypes("texture")
Example #32
0
def reverse_light_linking(meshes, lights):
    selection = cmds.ls(dag=1,o=1,s=1,sl=1)
    lights    = cmds.ls(selection, type=["light"] + cmds.listNodeTypes("light"))
    meshes    = list(set(selection) - set(lights))
def downgradeShaders():
    """
    Initially cleans the shadingGroups to remove duplicates to circumvent a maya bug, when you create a shader using 'Create New Material'
    Then creates a simplified lambert shader that gets connected to the surfaceShader slot of the shadingGroup
    Then force disconnect the material info node to render the lambert instead. 
    Assign all texture paths to point to their 256x256px counterparts.    
    """
    log(app = None, method = 'downgradeShaders', message = 'DowngradeShaders now...', printToLog = False, verbose = configCONST.DEBUGGING)
    ## Get all the shading groups assigned to the shapes in the scene
    SGused = []
    for shape in cmds.ls(shapes = True):
        dest = cmds.listConnections(shape, destination = True, source = False, plugs = False, type = 'shadingEngine')
        if dest:
            SGused.append(dest[0])

    log(app = None, method = 'downgradeShaders', message = 'SGused: %s' % SGused, printToLog = False, verbose = configCONST.DEBUGGING)

    ## FIX MESSAGE CONNECTIONS TO SGs
    ## Fix for incorrect shadingGroup Connection to material...for some reason I had message instead of outValue..this will fix all shaders. 
    listShaders = cmds.ls(materials = True)
    for shader in listShaders:
        listSG = cmds.listConnections(shader, source = False, destination = True, connections = True, plugs = True, type = 'shadingEngine')
        if listSG:
            for conn in listSG:
                if conn.endswith('Shader'):
                    connInfo = cmds.connectionInfo(conn, sourceFromDestination= True)
                    if '.message' in connInfo:
                        shader = connInfo.split('.')[0]
                        cmds.disconnectAttr(connInfo, conn)
                        cmds.connectAttr('%s.outValue' % shader, conn)

                        ## Get the core shading connections now
    connectedShaders = []
    listCoreShaders = cmds.ls(type = ('core_mia_material', 'core_material','core_surface_shader'))
    for shader in listCoreShaders:
        getConnection, getDiff, getColour, getDiffFile, getDiffColour, getShadingEngine, SG, matInfo = [],[],[],[],[],[],[],[]
        getIncandColour, getColourFile = [],[]
        getConnection =  cmds.listConnections(shader, connections = True, plugs = True)
        ## Now check for file connections into diffuse or color
        getDiff = [i for i in getConnection if '.diffuse' in i if not '.diffuseA' in i]
        getColour = [i for i in getConnection if '.colour' in i if not '.colourA' in i]
        if getDiff:
            getDiffFile = cmds.connectionInfo(getDiff[0], sourceFromDestination= True)
        else:
            getDiffColour = cmds.getAttr('%s.diffuse' % shader)

        if getColour:
            getColourFile = cmds.connectionInfo(getColour[0], sourceFromDestination= True)
        else:
            try:
                getIncandColour = cmds.getAttr('%s.colour' % shader)
            except ValueError:
                pass

        ## Now find the shading engine for the shader
        getShadingEngine = cmds.listConnections(shader, destination = True, source = False, plugs  = True, type = 'shadingEngine')
        if not getShadingEngine:
            SG = cmds.listConnections(shader, destination = True, source = False)
        else:
            for listSG in getShadingEngine:
                SG = listSG.split('.')
                SG = SG[0]
                ## Now get the materialInfo used by the SG
        if SG:
            matInfo = cmds.listConnections(SG, type = 'materialInfo')
            ## Now build the new lambert                
            newMaterial = cmds.shadingNode('lambert', asShader = True, name = ('_DGS_%s' % shader) )
            if isinstance(getDiffFile, unicode) or isinstance(getColourFile, unicode):
                try:
                    cmds.connectAttr(getDiffFile, '%s.color' % newMaterial, force = True)
                except:
                    cmds.connectAttr(getColourFile, '%s.color' % newMaterial, force = True)
            else:
                if getDiffColour:
                    cmds.setAttr('%s.color' % newMaterial, getDiffColour[0][0], getDiffColour[0][1], getDiffColour[0][2], type = 'double3')
                else:
                    cmds.setAttr('%s.incandescence' % newMaterial, getIncandColour[0][0], getIncandColour[0][1], getIncandColour[0][2], type = 'double3')
            try:
                cmds.connectAttr(newMaterial + '.outColor', SG + '.surfaceShader', force = True)
                cmds.disconnectAttr(newMaterial + '.outColor', SG + '.surfaceShader')
                cmds.connectAttr(newMaterial + '.outColor', SG + '.surfaceShader', force = True)
            except TypeError:
                print 'ERROR: Skipping %s due to issue with concatenation...' % newMaterial
            if matInfo != None:
                textureChannel = cmds.listConnections(matInfo[0] + '.texture',connections = True, shapes = True, plugs = True)
                if textureChannel != None:
                    for texture in textureChannel:
                        if 'texture[' in texture:
                            try:cmds.disconnectAttr(getDiffFile[:-9] + '.message', texture)
                            except:pass
                    try:cmds.connectAttr(getDiffFile[:-9] + '.message', matInfo[0] + '.texture[0]')
                    except:pass
            else:
                continue

    ## Now delete all the core shaders
    try:
        cmds.delete(listCoreShaders)
    except TypeError:
        pass

    ## Now clean up any core globals from the scene
    coreLens = cmds.ls(type = 'core_lens')
    coreGlobals = cmds.ls(type = 'core_globals')
    for each in coreLens:
        cmds.lockNode(each, lock = False)
        cmds.delete(each)
    for each in coreGlobals:
        cmds.lockNode(each, lock = False)
        cmds.delete(each)

    ## Rename SG's to their materials name_SG
    shaderTypes = ['blinn', 'lambert', 'phong', 'phongE', 'core_material']
    for eachType in shaderTypes:
        for each in cmds.ls(type = eachType):
            getConnections = cmds.listConnections(each, type = 'shadingEngine')
            if 'initial' not in getConnections[0]:
                cmds.rename(getConnections, '%s_SG' % each)

    ## now do a quick disconnect and reconnect to force shaders to show properly in viewport
    listShaders = cmds.ls(materials = True)
    log(app = None, method = 'downgradeShaders', message = 'listShaders: %s' % listShaders, printToLog = False, verbose = configCONST.DEBUGGING)
    for shader in listShaders:
        listSG = cmds.listConnections(shader, source = False, destination = True, connections = True, plugs = True, type = 'shadingEngine')
        log(app = None, method = 'downgradeShaders', message = 'listSG: %s' % listSG, printToLog = False, verbose = configCONST.DEBUGGING)
        try:
            cmds.disconnectAttr(listSG[0], listSG[1])
            cmds.connectAttr(listSG[0], listSG[1])
        except TypeError:
            cmds.warning('FAILED to disconnect and reconnect shader!')


    ## SEARCH FOR EXISTING CORE NODES
    ## IF OBJS STILL ATTACHED TO A CORE NODE SEARCH THROUGH THE SHADING HEIRACHY
    ## GET THE SWATCH COLOR AND DISCONNECT THE DIFFUSE FILE AND REPLACE WITH THE COLOUR
    badNodes,getTexture = [],[]
    listMRnodes = cmds.listNodeTypes( 'rendernode/mentalray')
    listShader  = cmds.listNodeTypes( 'shader')
    for eachNode in listMRnodes:
        if 'core_' in eachNode:
            objs = cmds.ls(type = eachNode)
            if objs != []:
                badNodes.append(objs[0])

    if badNodes != []:
        for bad in badNodes:
            for each in cmds.listHistory( bad, allFuture = True):
                if cmds.nodeType(each) == 'file':
                    getTexture.append(each)
            for each in cmds.listHistory( bad, future = True):
                for shader in listShader:
                    if cmds.nodeType(each) == shader:
                        if getTexture != []:
                            cmds.connectAttr('%s.outColor' % getTexture[0], '%s.color' % each, force = True)
                        else:
                            getTempColour = cmds.getAttr('%s.color' % each)
                            getColourFile = cmds.listConnections('%s.color' % each, connections = True, plugs = True)
                            cmds.disconnectAttr(getColourFile[1], getColourFile[0])
                            cmds.setAttr('%s.color' % each, getTempColour[0][0], getTempColour[0][1], getTempColour[0][2], type = 'double3')
        print 'Fixed existing core nodes ruinifying the viewport display, potentially crashing viewport!'

    ## Now double check all the file in nodes and make sure their paths are to the publish 256 folder
    ## If not fix them accordingly!
    listAllFileNodes = cmds.ls(type = 'file') + cmds.ls(type = "mentalrayTexture")
    for eachFileNode in listAllFileNodes:
        newTexturePath = ''
        origTexturePath = cmds.getAttr(eachFileNode + '.fileTextureName')
        print origTexturePath
        (filepath, nameOnly) = os.path.split(origTexturePath)
        if not nameOnly.endswith('.png'):
            nameOnly = '%s.png' % nameOnly.split('.')[0]
            cmds.setAttr('%s.colorProfile' % eachFileNode, 3)
        if '256' not in origTexturePath:
            newTexturePath = '%s/256/%s' % (filepath, nameOnly)

        if not newTexturePath:
            newTexturePath = '%s/%s' % (filepath, nameOnly)

        if 'publish' not in origTexturePath:
            print 'Fixing work to publish ...'
            newTexturePath = newTexturePath.replace('work', 'publish').replace('maya/', '')

        print newTexturePath
        print
        cmds.setAttr('%s.fileTextureName' % eachFileNode, newTexturePath, type = 'string')

    mel.eval("MLdeleteUnused();")
    fixResolution()
Example #34
0
    def _createAllLights(self, XMLPath = '', Namespace = '' , Root = ''):
        debug(app = self, method = '_createAllLights', message = '_createAllLights...', verbose = False)
        
        # If the namespace doesn't exist, the objects wont get named correctly create the namespace
        if Namespace != "" and Namespace != ":":
            if not cmds.namespace( exists= Namespace[:-1] ):
                cmds.namespace( add = Namespace[:-1])

        typeShader      = cmds.listNodeTypes( 'shader' ) or []
        typeTexture     = cmds.listNodeTypes( 'texture' ) or []
        typeUtility     = cmds.listNodeTypes( 'utility' ) or []
        typeMRTexture   = cmds.listNodeTypes( 'rendernode/mentalray/texture' ) or []
        typeMRDisp      = cmds.listNodeTypes( 'rendernode/mentalray/displace' ) or []
        typeMREnv       = cmds.listNodeTypes( 'rendernode/mentalray/environment' ) or []
        typeMRLightMaps = cmds.listNodeTypes( 'rendernode/mentalray/lightmap' ) or []
        typeMRMisc      = cmds.listNodeTypes( 'rendernode/mentalray/misc' ) or []
        typeMRConv      = cmds.listNodeTypes( 'rendernode/mentalray/conversion') or []
        typeMRInternal  = cmds.listNodeTypes( 'rendernode/mentalray/internal') or []
        typeMRGeometry  = cmds.listNodeTypes( 'rendernode/mentalray/geometry') or []
    
        typeLights      = cmds.listNodeTypes( 'light' ) or []
        typeMRLights    = cmds.listNodeTypes( 'rendernode/mentalray/light' ) or []
        typeMRLens      = cmds.listNodeTypes( 'rendernode/mentalray/lens' ) or []
    
        debug(app = self, method = '_createAllLights', message = 'Processed lists...', verbose = False)
        # get the root of the XMLPath argument
        root = xml.parse(XMLPath).getroot()
    
        # Create an iterator based on the the root argument
        shaderIterator = root.getiterator(Root)
        # Iterate on shader level
        for levelOne in shaderIterator:
            # Iterate on parent tag level
            if levelOne.getchildren():
                for levelTwo in levelOne:
                    if levelTwo.tag == 'Nodes':
                        debug(app = self, method = '_createAllLights', message = 'Building Nodes...', verbose = False)

                        for levelThree in levelTwo.getchildren():
                            node_name = levelThree.tag
                            debug(app = self, method = '_createAllLights', message = 'node_name:%s' % node_name, verbose = False)

                            if '_cCc_' in node_name:
                                node_name = node_name.replace('_cCc_', ':')
                            node_name = Namespace + node_name
                            node_type = levelThree.attrib['value']
                            debug(app = self, method = '_createAllLights', message = 'node_type:%s' % node_type, verbose = False)
    
                            # Create all node types and sort them into correct hypershade tabs
                            try:
                                if node_type in typeLights or node_type in typeMRLights:
                                    debug(app = self, method = '_createAllLights', message = 'node_type:%s is in typeLights or typeMRLights' % node_type, verbose = False)
                                    if not self.doesAssetAlreadyExistInScene(node_name):
                                        cmds.shadingNode(node_type, asLight = True , name = node_name)
                            except:
                                pass
    
                            try:
                                if node_type in typeTexture or node_type in typeMRTexture:
                                    debug(app = self, method = '_createAllLights', message = 'node_type:%s is in typeTexture or typeMRTexture' % node_type, verbose = False)
                                    if not self.doesAssetAlreadyExistInScene(node_name):
                                        cmds.shadingNode(node_type, asTexture = True , name = node_name)
                            except:
                                pass
    
                            try:
                                if node_type in typeUtility:
                                    debug(app = self, method = '_createAllLights', message = 'node_type:%s is in typeUtility' % node_type, verbose = False)
                                    if not self.doesAssetAlreadyExistInScene(node_name):
                                        cmds.shadingNode(node_type, asUtility = True , name = node_name)
                            except:
                                pass
    
                            try:
                                if node_type in typeMREnv or node_type in typeMRLightMaps or node_type in typeMRMisc or node_type in typeMRConv or node_type in typeMRDisp or node_type in typeMRInternal or node_type in typeMRGeometry or node_type in typeMRLens:
                                    debug(app = self, method = '_createAllLights', message = 'node_type:%s is in typeMREnv, typeMRLightMaps, typeMRMisc, typeMRConv, typeMRDisp, typeMRInternal, typeMRGeometry, typeMRLens' % node_type, verbose = False)
                                    if not self.doesAssetAlreadyExistInScene(node_name):
                                        cmds.createNode( node_type, ss=True, name = node_name)
                            except:
                                pass
    
    
                    if levelTwo.tag == 'Attributes':
                        debug(app = self, method = '_createAllLights', message = 'levelTwo.tag: Assigning Attributes...', verbose = False)

                        for attributes in levelTwo.getchildren():
                            attrNode = attributes.tag
                            attrNode = Namespace + attrNode
                            if '_aAa_' in attrNode:
                                attrNode = attrNode.replace('_aAa_', '[')
                                attrNode = attrNode.replace('_zZz_', ']')
                            if '_cCc_' in attrNode:
                                attrNode = attrNode.replace('_cCc_', ':')
                            if '_tTt_' in attrNode:
                                attrNode = attrNode.replace('_tTt_', '+')
                            if '_mMm_' in attrNode:
                                attrNode = attrNode.replace('_mMm_', '-')
                            attrValue =  attributes.attrib['value']
    
                            if '.illuminatesDefault' in attrNode:
                                if attrValue == '0.0':
                                    lightName = attrNode.split('.')
                                    lightName = lightName[0]
                                    lightParent = cmds.listRelatives(lightName, parent = True)
                                    lightParent = lightParent[0]
                                    for x in range(30):
                                        try:
                                            cmds.disconnectAttr(lightParent + '.instObjGroups[0]','defaultLightSet.dagSetMembers[%i]' %x)
                                        except:
                                            pass
    
    
                            try:
                                cmds.setAttr(attrNode, float(attrValue), lock = False)
                            except:
                                pass
                            try:
                                cmds.setAttr(attrNode, str(attrValue), type = 'string', lock = False)
                            except:
                                pass
                            try:
                                cmds.setAttr(attrNode, str(attrValue), type = 'double3', lock = False)
                            except:
                                pass
    
                    if levelTwo.tag == 'LightLinking':
                        debug(app = self, method = '_createAllLights', message = 'levelTwo.tag: Light Linking Objects...', verbose = False)

                        cmds.select(clear = True)
                        for levelThree in levelTwo.getchildren():
                            set_name = levelThree.tag
                            cmds.select(clear = True)
                            createSet = cmds.sets( name = set_name )
                            LightName = set_name.split('LightLink_')
                            LightName = LightName[1]
                            for levelFour in levelThree.getchildren():
                                objectName = levelFour.tag
                                objectName = objectName.replace('_cCc_', ':')
                                try:
                                    cmds.select(objectName, replace = True)
                                    cmds.sets(objectName, edit = True, addElement = createSet)
                                except:
                                    debug(app = self, method = '_createAllLights', message = 'MISSING OBJECT: %s' % objectName, verbose = False)
#                                     cmds.warning('\nSome objects not present in the scene, cannot light link.\n')
#                                     print '* Missing Object * : \t' + objectName
                                    pass
                            cmds.select(clear = True)
                            cmds.select(LightName, createSet, noExpand = True, replace = True)
                            cmds.lightlink(make = True, useActiveLights = True, useActiveObjects = True)
                            debug(app = self, method = '_createAllLights', message = 'Success light linking something...', verbose = False)
        debug(app = self, method = '_createAllLights', message = 'FINISHED', verbose = False)
Example #35
0
    def _createAllShaders(self, XMLPath = '', Namespace = '', Root = 'MaterialNodes', inprogressBar = ''):
        debug(app = self, method = '_createAllShaders', message = 'XMLPath... %s' % XMLPath, verbose = False)
        debug(app = self, method = '_createAllShaders', message = 'Namespace... %s' % Namespace, verbose = False)
        debug(app = self, method = '_createAllShaders', message = 'Root... %s' % Root, verbose = False)

        # If the namespace doesn't exist, the objects wont get named correctly
        # create the namespace
        if Namespace != "" and Namespace != ":":
            if not cmds.namespace( exists= Namespace[:-1] ):
                cmds.namespace( add = Namespace[:-1])
    
        debug(app = self, method = '_createAllShaders', message = 'Namespace check successful...', verbose = False)
        
        typeShader      = cmds.listNodeTypes( 'shader' ) or []
        typeTexture     = cmds.listNodeTypes( 'texture' )  or []
        typeUtility     = cmds.listNodeTypes( 'utility' )  or []
        typeMRTexture   = cmds.listNodeTypes( 'rendernode/mentalray/texture' )  or []
        typeMRDisp      = cmds.listNodeTypes( 'rendernode/mentalray/displace' )  or []
        typeMREnv       = cmds.listNodeTypes( 'rendernode/mentalray/environment' )  or []
        typeMRLightMaps = cmds.listNodeTypes( 'rendernode/mentalray/lightmap' )  or []
        typeMRMisc      = cmds.listNodeTypes( 'rendernode/mentalray/misc' )  or []
        typeMRConv      = cmds.listNodeTypes( 'rendernode/mentalray/conversion') or []
        typeMRInternal  = cmds.listNodeTypes( 'rendernode/mentalray/internal')  or []

        debug(app = self, method = '_createAllShaders', message = 'typeShader %s' % typeShader, verbose = False)
        debug(app = self, method = '_createAllShaders', message = 'typeTexture %s' % typeTexture, verbose = False)
        debug(app = self, method = '_createAllShaders', message = 'typeUtility %s' % typeUtility, verbose = False)
        debug(app = self, method = '_createAllShaders', message = 'typeMRTexture %s' % typeMRTexture, verbose = False)
        debug(app = self, method = '_createAllShaders', message = 'typeMRDisp %s' % typeMRDisp, verbose = False)
        debug(app = self, method = '_createAllShaders', message = 'typeMREnv %s' % typeMREnv, verbose = False)
        debug(app = self, method = '_createAllShaders', message = 'typeMRLightMaps %s' % typeMRLightMaps, verbose = False)
        debug(app = self, method = '_createAllShaders', message = 'typeMRMisc %s' % typeMRMisc, verbose = False)
        debug(app = self, method = '_createAllShaders', message = 'typeMRConv %s' % typeMRConv, verbose = False)
        debug(app = self, method = '_createAllShaders', message = 'typeMRInternal %s' % typeMRInternal, verbose = False)

        # get the root of the XMLPath argument
        debug(app = self, method = '_createAllShaders', message = 'XMLPath...%s' % XMLPath, verbose = False)
        root = xml.parse(XMLPath).getroot()
        debug(app = self, method = '_createAllShaders', message = 'Root XML.parse successful...', verbose = False)
        
        # Create an iterator based on the the root argument
        shaderIterator = root.getiterator(Root)
        # Iterate on shader level
        for levelOne in shaderIterator:
            debug(app = self, method = '_createAllShaders', message = 'Entering levelOne in shaderIterator...', verbose = False)
            # Iterate on parent tag level
            if levelOne.getchildren():
                for levelTwo in levelOne:
                    if levelTwo.tag == 'Nodes':
                        debug(app = self, method = '_createAllShaders', message = 'Processing Nodes...', verbose = False)
                        for levelThree in levelTwo.getchildren():
                            node_name = levelThree.tag
                            if '_cCc_' in node_name:
                                node_name = node_name.replace('_cCc_', ':')
                            node_name = '%s%s' % (Namespace, node_name)
                            node_type = levelThree.attrib['value']
                            
                            debug(app = self, method = '_createAllShaders', message = 'Creating all node types and sorting them into correct hypershade tabs...', verbose = False)
                            # Create all node types and sort them into correct hypershade tabs
                            if node_type in typeShader or node_type in typeMRInternal:
                                if not self.doesAssetAlreadyExistInScene(node_name):
                                    cmds.shadingNode(node_type, asShader = True , name = node_name)
                            if node_type in typeTexture or node_type in typeMRInternal:
                                if not self.doesAssetAlreadyExistInScene(node_name):
                                    cmds.shadingNode(node_type, asTexture = True , name = node_name)
                            if node_type in typeUtility or node_type in typeMRTexture or node_type in typeMREnv or node_type in typeMRLightMaps or node_type in typeMRMisc or node_type in typeMRConv or node_type in typeMRDisp or node_type in typeMRInternal:
                                if not self.doesAssetAlreadyExistInScene(node_name):
                                    cmds.shadingNode(node_type, asUtility = True , name = node_name)
    
                    if levelTwo.tag == 'ShadingEngine':
                        debug(app = self, method = '_createAllShaders', message = 'Processing ShadingEngine...', verbose = False)
                        for levelThree in levelTwo.getchildren():
                            node_name  = levelThree.tag
                            if '_cCc_' in node_name:
                                node_name = node_name.replace('_cCc_', ':')
                            node_type  = levelThree.attrib['value']
                            node_split = node_type.split(', ')
                            node_name  = node_split[0]
                            node_name  = Namespace + node_name
                            node_type  = node_split[1]
    
                            if node_type == 'shadingEngine':
                                if not self.doesAssetAlreadyExistInScene(node_name):
                                    cmds.sets(renderable = True, noSurfaceShader = True, empty = True, name = node_name)
        
                    if levelTwo.tag == 'Attributes':
                        debug(app = self, method = '_createAllShaders', message = 'Processing Attributes...', verbose = False)
                        for attributes in levelTwo.getchildren():
                            attrNode = attributes.tag
                            attrNode = Namespace + attrNode
                            if '_aAa_' in attrNode:
                                attrNode = attrNode.replace('_aAa_', '[')
                                attrNode = attrNode.replace('_zZz_', ']')
                            if '_cCc_' in attrNode:
                                attrNode = attrNode.replace('_cCc_', ':')
    
                            attrValue =  attributes.attrib['value']
                            if not attrValue.startswith('[('):
                                try:
                                    cmds.setAttr(attrNode, float(attrValue), lock = False)
                                except:
                                    pass
                                try:
                                    cmds.setAttr(attrNode, str(attrValue), type = 'string', lock = False)
                                except:
                                    pass
                                try:
                                    cmds.setAttr(attrNode, str(attrValue), type = 'double3', lock = False)
                                except:
                                    pass
                        for attributes in levelTwo.getchildren():
                            attrNode = attributes.tag
                            attrNode = Namespace + attrNode
                            if '_aAa_' in attrNode:
                                attrNode = attrNode.replace('_aAa_', '[')
                                attrNode = attrNode.replace('_zZz_', ']')
                            if '_cCc_' in attrNode:
                                attrNode = attrNode.replace('_cCc_', ':')
    
                            attrValue =  attributes.attrib['value']
                            if attrValue.startswith('[('):
                                #convert to list
                                evalList = eval(attrValue)
                                evalList = evalList[0]
                                if len(evalList) == 2:
                                    try:
                                        cmds.setAttr(attrNode, evalList[0], evalList[1], type = 'double2', lock = False)
                                    except:
                                        debug(app = self, method = '_createAllShaders', message = '%s failed..' % attrNode, verbose = False)
    
                                if len(evalList) == 3:
                                    try:
                                        cmds.setAttr(attrNode, evalList[0], evalList[1], evalList[2], type = 'double3', lock = False)
                                    except:
                                        debug(app = self, method = '_createAllShaders', message = '%s failed..' % attrNode, verbose = False)
        
        debug(app = self, method = 'createAll', message = 'FINSHED for %s...' % XMLPath, verbose = False)
Example #36
0
    def _createAllShaders(self,
                          XMLPath='',
                          Namespace='',
                          Root='MaterialNodes',
                          inprogressBar=''):
        debug(app=self,
              method='_createAllShaders',
              message='XMLPath... %s' % XMLPath,
              verbose=False)
        debug(app=self,
              method='_createAllShaders',
              message='Namespace... %s' % Namespace,
              verbose=False)
        debug(app=self,
              method='_createAllShaders',
              message='Root... %s' % Root,
              verbose=False)

        # If the namespace doesn't exist, the objects wont get named correctly
        # create the namespace
        if Namespace != "" and Namespace != ":":
            if not cmds.namespace(exists=Namespace[:-1]):
                cmds.namespace(add=Namespace[:-1])

        debug(app=self,
              method='_createAllShaders',
              message='Namespace check successful...',
              verbose=False)

        typeShader = cmds.listNodeTypes('shader') or []
        typeTexture = cmds.listNodeTypes('texture') or []
        typeUtility = cmds.listNodeTypes('utility') or []
        typeMRTexture = cmds.listNodeTypes(
            'rendernode/mentalray/texture') or []
        typeMRDisp = cmds.listNodeTypes('rendernode/mentalray/displace') or []
        typeMREnv = cmds.listNodeTypes(
            'rendernode/mentalray/environment') or []
        typeMRLightMaps = cmds.listNodeTypes(
            'rendernode/mentalray/lightmap') or []
        typeMRMisc = cmds.listNodeTypes('rendernode/mentalray/misc') or []
        typeMRConv = cmds.listNodeTypes(
            'rendernode/mentalray/conversion') or []
        typeMRInternal = cmds.listNodeTypes(
            'rendernode/mentalray/internal') or []

        debug(app=self,
              method='_createAllShaders',
              message='typeShader %s' % typeShader,
              verbose=False)
        debug(app=self,
              method='_createAllShaders',
              message='typeTexture %s' % typeTexture,
              verbose=False)
        debug(app=self,
              method='_createAllShaders',
              message='typeUtility %s' % typeUtility,
              verbose=False)
        debug(app=self,
              method='_createAllShaders',
              message='typeMRTexture %s' % typeMRTexture,
              verbose=False)
        debug(app=self,
              method='_createAllShaders',
              message='typeMRDisp %s' % typeMRDisp,
              verbose=False)
        debug(app=self,
              method='_createAllShaders',
              message='typeMREnv %s' % typeMREnv,
              verbose=False)
        debug(app=self,
              method='_createAllShaders',
              message='typeMRLightMaps %s' % typeMRLightMaps,
              verbose=False)
        debug(app=self,
              method='_createAllShaders',
              message='typeMRMisc %s' % typeMRMisc,
              verbose=False)
        debug(app=self,
              method='_createAllShaders',
              message='typeMRConv %s' % typeMRConv,
              verbose=False)
        debug(app=self,
              method='_createAllShaders',
              message='typeMRInternal %s' % typeMRInternal,
              verbose=False)

        # get the root of the XMLPath argument
        debug(app=self,
              method='_createAllShaders',
              message='XMLPath...%s' % XMLPath,
              verbose=False)
        root = xml.parse(XMLPath).getroot()
        debug(app=self,
              method='_createAllShaders',
              message='Root XML.parse successful...',
              verbose=False)

        # Create an iterator based on the the root argument
        shaderIterator = root.getiterator(Root)
        # Iterate on shader level
        for levelOne in shaderIterator:
            debug(app=self,
                  method='_createAllShaders',
                  message='Entering levelOne in shaderIterator...',
                  verbose=False)
            # Iterate on parent tag level
            if levelOne.getchildren():
                for levelTwo in levelOne:
                    if levelTwo.tag == 'Nodes':
                        debug(app=self,
                              method='_createAllShaders',
                              message='Processing Nodes...',
                              verbose=False)
                        for levelThree in levelTwo.getchildren():
                            node_name = levelThree.tag
                            if '_cCc_' in node_name:
                                node_name = node_name.replace('_cCc_', ':')
                            node_name = '%s%s' % (Namespace, node_name)
                            node_type = levelThree.attrib['value']

                            debug(
                                app=self,
                                method='_createAllShaders',
                                message=
                                'Creating all node types and sorting them into correct hypershade tabs...',
                                verbose=False)
                            # Create all node types and sort them into correct hypershade tabs
                            if node_type in typeShader or node_type in typeMRInternal:
                                if not self.doesAssetAlreadyExistInScene(
                                        node_name):
                                    cmds.shadingNode(node_type,
                                                     asShader=True,
                                                     name=node_name)
                            if node_type in typeTexture or node_type in typeMRInternal:
                                if not self.doesAssetAlreadyExistInScene(
                                        node_name):
                                    cmds.shadingNode(node_type,
                                                     asTexture=True,
                                                     name=node_name)
                            if node_type in typeUtility or node_type in typeMRTexture or node_type in typeMREnv or node_type in typeMRLightMaps or node_type in typeMRMisc or node_type in typeMRConv or node_type in typeMRDisp or node_type in typeMRInternal:
                                if not self.doesAssetAlreadyExistInScene(
                                        node_name):
                                    cmds.shadingNode(node_type,
                                                     asUtility=True,
                                                     name=node_name)

                    if levelTwo.tag == 'ShadingEngine':
                        debug(app=self,
                              method='_createAllShaders',
                              message='Processing ShadingEngine...',
                              verbose=False)
                        for levelThree in levelTwo.getchildren():
                            node_name = levelThree.tag
                            if '_cCc_' in node_name:
                                node_name = node_name.replace('_cCc_', ':')
                            node_type = levelThree.attrib['value']
                            node_split = node_type.split(', ')
                            node_name = node_split[0]
                            node_name = Namespace + node_name
                            node_type = node_split[1]

                            if node_type == 'shadingEngine':
                                if not self.doesAssetAlreadyExistInScene(
                                        node_name):
                                    cmds.sets(renderable=True,
                                              noSurfaceShader=True,
                                              empty=True,
                                              name=node_name)

                    if levelTwo.tag == 'Attributes':
                        debug(app=self,
                              method='_createAllShaders',
                              message='Processing Attributes...',
                              verbose=False)
                        for attributes in levelTwo.getchildren():
                            attrNode = attributes.tag
                            attrNode = Namespace + attrNode
                            if '_aAa_' in attrNode:
                                attrNode = attrNode.replace('_aAa_', '[')
                                attrNode = attrNode.replace('_zZz_', ']')
                            if '_cCc_' in attrNode:
                                attrNode = attrNode.replace('_cCc_', ':')

                            attrValue = attributes.attrib['value']
                            if not attrValue.startswith('[('):
                                try:
                                    cmds.setAttr(attrNode,
                                                 float(attrValue),
                                                 lock=False)
                                except:
                                    pass
                                try:
                                    cmds.setAttr(attrNode,
                                                 str(attrValue),
                                                 type='string',
                                                 lock=False)
                                except:
                                    pass
                                try:
                                    cmds.setAttr(attrNode,
                                                 str(attrValue),
                                                 type='double3',
                                                 lock=False)
                                except:
                                    pass
                        for attributes in levelTwo.getchildren():
                            attrNode = attributes.tag
                            attrNode = Namespace + attrNode
                            if '_aAa_' in attrNode:
                                attrNode = attrNode.replace('_aAa_', '[')
                                attrNode = attrNode.replace('_zZz_', ']')
                            if '_cCc_' in attrNode:
                                attrNode = attrNode.replace('_cCc_', ':')

                            attrValue = attributes.attrib['value']
                            if attrValue.startswith('[('):
                                #convert to list
                                evalList = eval(attrValue)
                                evalList = evalList[0]
                                if len(evalList) == 2:
                                    try:
                                        cmds.setAttr(attrNode,
                                                     evalList[0],
                                                     evalList[1],
                                                     type='double2',
                                                     lock=False)
                                    except:
                                        debug(app=self,
                                              method='_createAllShaders',
                                              message='%s failed..' % attrNode,
                                              verbose=False)

                                if len(evalList) == 3:
                                    try:
                                        cmds.setAttr(attrNode,
                                                     evalList[0],
                                                     evalList[1],
                                                     evalList[2],
                                                     type='double3',
                                                     lock=False)
                                    except:
                                        debug(app=self,
                                              method='_createAllShaders',
                                              message='%s failed..' % attrNode,
                                              verbose=False)

        debug(app=self,
              method='createAll',
              message='FINSHED for %s...' % XMLPath,
              verbose=False)
Example #37
0
    def _createAllLights(self, XMLPath='', Namespace='', Root=''):
        debug(app=self,
              method='_createAllLights',
              message='_createAllLights...',
              verbose=False)

        # If the namespace doesn't exist, the objects wont get named correctly create the namespace
        if Namespace != "" and Namespace != ":":
            if not cmds.namespace(exists=Namespace[:-1]):
                cmds.namespace(add=Namespace[:-1])

        typeShader = cmds.listNodeTypes('shader') or []
        typeTexture = cmds.listNodeTypes('texture') or []
        typeUtility = cmds.listNodeTypes('utility') or []
        typeMRTexture = cmds.listNodeTypes(
            'rendernode/mentalray/texture') or []
        typeMRDisp = cmds.listNodeTypes('rendernode/mentalray/displace') or []
        typeMREnv = cmds.listNodeTypes(
            'rendernode/mentalray/environment') or []
        typeMRLightMaps = cmds.listNodeTypes(
            'rendernode/mentalray/lightmap') or []
        typeMRMisc = cmds.listNodeTypes('rendernode/mentalray/misc') or []
        typeMRConv = cmds.listNodeTypes(
            'rendernode/mentalray/conversion') or []
        typeMRInternal = cmds.listNodeTypes(
            'rendernode/mentalray/internal') or []
        typeMRGeometry = cmds.listNodeTypes(
            'rendernode/mentalray/geometry') or []

        typeLights = cmds.listNodeTypes('light') or []
        typeMRLights = cmds.listNodeTypes('rendernode/mentalray/light') or []
        typeMRLens = cmds.listNodeTypes('rendernode/mentalray/lens') or []

        debug(app=self,
              method='_createAllLights',
              message='Processed lists...',
              verbose=False)
        # get the root of the XMLPath argument
        root = xml.parse(XMLPath).getroot()

        # Create an iterator based on the the root argument
        shaderIterator = root.getiterator(Root)
        # Iterate on shader level
        for levelOne in shaderIterator:
            # Iterate on parent tag level
            if levelOne.getchildren():
                for levelTwo in levelOne:
                    if levelTwo.tag == 'Nodes':
                        debug(app=self,
                              method='_createAllLights',
                              message='Building Nodes...',
                              verbose=False)

                        for levelThree in levelTwo.getchildren():
                            node_name = levelThree.tag
                            debug(app=self,
                                  method='_createAllLights',
                                  message='node_name:%s' % node_name,
                                  verbose=False)

                            if '_cCc_' in node_name:
                                node_name = node_name.replace('_cCc_', ':')
                            node_name = Namespace + node_name
                            node_type = levelThree.attrib['value']
                            debug(app=self,
                                  method='_createAllLights',
                                  message='node_type:%s' % node_type,
                                  verbose=False)

                            # Create all node types and sort them into correct hypershade tabs
                            try:
                                if node_type in typeLights or node_type in typeMRLights:
                                    debug(
                                        app=self,
                                        method='_createAllLights',
                                        message=
                                        'node_type:%s is in typeLights or typeMRLights'
                                        % node_type,
                                        verbose=False)
                                    if not self.doesAssetAlreadyExistInScene(
                                            node_name):
                                        cmds.shadingNode(node_type,
                                                         asLight=True,
                                                         name=node_name)
                            except:
                                pass

                            try:
                                if node_type in typeTexture or node_type in typeMRTexture:
                                    debug(
                                        app=self,
                                        method='_createAllLights',
                                        message=
                                        'node_type:%s is in typeTexture or typeMRTexture'
                                        % node_type,
                                        verbose=False)
                                    if not self.doesAssetAlreadyExistInScene(
                                            node_name):
                                        cmds.shadingNode(node_type,
                                                         asTexture=True,
                                                         name=node_name)
                            except:
                                pass

                            try:
                                if node_type in typeUtility:
                                    debug(
                                        app=self,
                                        method='_createAllLights',
                                        message='node_type:%s is in typeUtility'
                                        % node_type,
                                        verbose=False)
                                    if not self.doesAssetAlreadyExistInScene(
                                            node_name):
                                        cmds.shadingNode(node_type,
                                                         asUtility=True,
                                                         name=node_name)
                            except:
                                pass

                            try:
                                if node_type in typeMREnv or node_type in typeMRLightMaps or node_type in typeMRMisc or node_type in typeMRConv or node_type in typeMRDisp or node_type in typeMRInternal or node_type in typeMRGeometry or node_type in typeMRLens:
                                    debug(
                                        app=self,
                                        method='_createAllLights',
                                        message=
                                        'node_type:%s is in typeMREnv, typeMRLightMaps, typeMRMisc, typeMRConv, typeMRDisp, typeMRInternal, typeMRGeometry, typeMRLens'
                                        % node_type,
                                        verbose=False)
                                    if not self.doesAssetAlreadyExistInScene(
                                            node_name):
                                        cmds.createNode(node_type,
                                                        ss=True,
                                                        name=node_name)
                            except:
                                pass

                    if levelTwo.tag == 'Attributes':
                        debug(app=self,
                              method='_createAllLights',
                              message='levelTwo.tag: Assigning Attributes...',
                              verbose=False)

                        for attributes in levelTwo.getchildren():
                            attrNode = attributes.tag
                            attrNode = Namespace + attrNode
                            if '_aAa_' in attrNode:
                                attrNode = attrNode.replace('_aAa_', '[')
                                attrNode = attrNode.replace('_zZz_', ']')
                            if '_cCc_' in attrNode:
                                attrNode = attrNode.replace('_cCc_', ':')
                            if '_tTt_' in attrNode:
                                attrNode = attrNode.replace('_tTt_', '+')
                            if '_mMm_' in attrNode:
                                attrNode = attrNode.replace('_mMm_', '-')
                            attrValue = attributes.attrib['value']

                            if '.illuminatesDefault' in attrNode:
                                if attrValue == '0.0':
                                    lightName = attrNode.split('.')
                                    lightName = lightName[0]
                                    lightParent = cmds.listRelatives(
                                        lightName, parent=True)
                                    lightParent = lightParent[0]
                                    for x in range(30):
                                        try:
                                            cmds.disconnectAttr(
                                                lightParent +
                                                '.instObjGroups[0]',
                                                'defaultLightSet.dagSetMembers[%i]'
                                                % x)
                                        except:
                                            pass

                            try:
                                cmds.setAttr(attrNode,
                                             float(attrValue),
                                             lock=False)
                            except:
                                pass
                            try:
                                cmds.setAttr(attrNode,
                                             str(attrValue),
                                             type='string',
                                             lock=False)
                            except:
                                pass
                            try:
                                cmds.setAttr(attrNode,
                                             str(attrValue),
                                             type='double3',
                                             lock=False)
                            except:
                                pass

                    if levelTwo.tag == 'LightLinking':
                        debug(app=self,
                              method='_createAllLights',
                              message='levelTwo.tag: Light Linking Objects...',
                              verbose=False)

                        cmds.select(clear=True)
                        for levelThree in levelTwo.getchildren():
                            set_name = levelThree.tag
                            cmds.select(clear=True)
                            createSet = cmds.sets(name=set_name)
                            LightName = set_name.split('LightLink_')
                            LightName = LightName[1]
                            for levelFour in levelThree.getchildren():
                                objectName = levelFour.tag
                                objectName = objectName.replace('_cCc_', ':')
                                try:
                                    cmds.select(objectName, replace=True)
                                    cmds.sets(objectName,
                                              edit=True,
                                              addElement=createSet)
                                except:
                                    debug(app=self,
                                          method='_createAllLights',
                                          message='MISSING OBJECT: %s' %
                                          objectName,
                                          verbose=False)
                                    #                                     cmds.warning('\nSome objects not present in the scene, cannot light link.\n')
                                    #                                     print '* Missing Object * : \t' + objectName
                                    pass
                            cmds.select(clear=True)
                            cmds.select(LightName,
                                        createSet,
                                        noExpand=True,
                                        replace=True)
                            cmds.lightlink(make=True,
                                           useActiveLights=True,
                                           useActiveObjects=True)
                            debug(app=self,
                                  method='_createAllLights',
                                  message='Success light linking something...',
                                  verbose=False)
        debug(app=self,
              method='_createAllLights',
              message='FINISHED',
              verbose=False)
Example #38
0
import maya.cmds as cmds

# Create a list of MDLs that can be found in Hypershade

mdllist = []
for shaders in cmds.listNodeTypes('shader'):
    if 'mdl' in shaders:
        if shaders in mdllist:
            mdllist.append(shaders + '_copy')
        else:
            mdllist.append(shaders)

print(mdllist)
def bakeDiffuseToVertexColor(**kwargs):

    bOnRefs = kwargs.pop("onReferences", kwargs.pop("onRefs", False))
    fAmbient = kwargs.pop("ambient", 1.0)

    sCamShape = ""
    if mc.about(batch=True):
        sCamShape = kwargs["camera"]

    if "meshes" not in kwargs:
        sMeshList = lsNodes(sl=True, dag=True, ni=True, type="mesh",
                            not_referencedNodes=not bOnRefs, nodeNames=True)
        if not sMeshList:
            logMsg("No meshes found in selection !" , warning=True)
            return False
    else:
        sMeshList = kwargs.pop("meshes")
        if not sMeshList:
            return False

    mc.polyOptions(sMeshList, colorShadedDisplay=False)

    sLightList = tuple(sLight for sLight in mc.ls(type=mc.listNodeTypes('light'))
                                    if myapi.getDagPath(sLight).isVisible())
    for sLight in sLightList:
        try:
            mc.setAttr(sLight + ".visibility", False)
        except RuntimeError as e:
            pm.displayWarning(e)

    ambLight = pm.shadingNode("ambientLight", asLight=True)
    ambLight.setAttr("intensity", fAmbient)
    ambLight.setAmbientShade(0.0)
    ambLight.setAttr("color", (1.0, 1.0, 1.0))
    ambLight.setAttr("shadowColor", (0.0, 0.0, 0.0))
    ambLight.setAttr("useRayTraceShadows", False)

    pm.refresh()

    ##Storing if exist, reflectivity connection or value before applying the bakeTexture,
    ##as it could affects the "rendering/baking" aspect of the object.
    ##After bake, reapply the value.
    oReflDct = {}
    for oMat in lsNodes(type=mc.listNodeTypes('shader', ex="texture"), not_referencedNodes=not bOnRefs):
        if oMat.hasAttr("reflectivity"):
            oReflAttr = oMat.attr("reflectivity")
            oInputs = oReflAttr.inputs(sourceFirst=True, c=True, plugs=True)
            if oInputs:
                oReflDct[oMat] = dict(oInputs)
                pm.disconnectAttr(*oInputs)
            else:
                try:
                    value = oReflAttr.get()
                except RuntimeError as e:
                    pm.displayInfo(u"{}: {}".format(e.message.strip(), oReflAttr))
                    continue
                oReflDct[oMat] = value

            oReflAttr.set(0.0)


    if sCamShape:
        sMeshList.append(sCamShape)

    try:
        mc.polyGeoSampler(sMeshList,
                          ignoreDoubleSided=True,
                          scaleFactor=1.0,
                          shareUV=True,
                          colorDisplayOption=True,
                          colorBlend="overwrite",
                          alphaBlend="overwrite",
                          flatShading=False,
                          lightingOnly=False,
                          averageColor=True,
                          clampAlphaMin=1.0,
                          clampAlphaMax=1.0)

        mc.polyOptions(sMeshList, colorMaterialChannel="ambientDiffuse")

    finally:

        for sLight in sLightList:
            try:
                mc.setAttr(sLight + ".visibility", True)
            except RuntimeError as e:
                pm.displayWarning(e)

        for oMat, oValues in oReflDct.items():
            if isinstance(oValues, dict):
                for k, v in oValues.items():
                    pm.connectAttr(k, v)
            else:
                oMat.setAttr("reflectivity", oValues)

        if ambLight:
            pm.delete(ambLight)

    return True
def setVrayID(states=None, operation=None, shaders=None):
    if states:
        if operation:
            renderLayerOK=True
            if cmds.editRenderLayerGlobals(query=True, currentRenderLayer=True) == "defaultRenderLayer":
                renderLayerOK=False
            if states["override"] == 0:
                renderLayerOK=True

            if renderLayerOK:
                if shaders:
                    sel = shaders
                else:
                    if states["allShaders"] == 0:
                        if states["objectOrMult"] == 2:
                            transforms = cmds.ls(sl=True, type="transform")
                            print "1"
                            sel = cmds.listRelatives(transforms, shapes=True, fullPath=True, ni=True, type=["mesh", "nurbsSurface"])
                        if states["objectOrMult"] == 0:
                            print "2"
                            sel = cmds.ls(sl=True, type=cmds.listNodeTypes("shader"))
                    if states["allShaders"] == 2:
                        if states["objectOrMult"] == 2:
                            print "3"
                            sel = cmds.ls(ni=True, type=["nurbsSurface", "mesh"])
                        if states["objectOrMult"] == 0:
                            print "4"
                            sel = cmds.ls(type=cmds.listNodeTypes("shader"))


                if states["objectOrMult"] == 2:
                    attribute = "vrayObjectID"
                if states["objectOrMult"] == 0:
                    attribute = "vrayMaterialId"

                print sel
                if sel:
                    index = states["startIndex"]
                    for s in sel:
                        if not cmds.objExists("%s.%s" % (s, attribute)):
                            print s
                            try:
                                if states["objectOrMult"] == 2:
                                    mel.eval('vrayAddAttr %s vrayObjectID;' % s)
                                if states["objectOrMult"] == 0:
                                    mel.eval('vrayAddAttr %s vrayColorId;vrayAddAttr %s vrayMaterialId;' % (s,s))
                            except:
                                pass
                        try:
                            try:
                                if states["override"] == 2:
                                    mel.eval('editRenderLayerAdjustment %s.%s;' % (s, attribute))
                            except:
                                pass
                            cmds.setAttr("%s.%s" % (s, attribute), index)

                            if operation == "unikID":
                                index = index+1
                        except:
                            pass

                    #Set MultiMattes
                    if states["multiMattes"] == 2:
                        states["endIndex"] = index
                        setVrayMult(states)
                    return index
            else:
                print "Can't add render override on default renderlayer"
Example #41
0
import time
import random as rand

try:
    import maya.cmds as cmds
    import maya.OpenMaya as om
    import maya.mel as mel
except:
    pass

from multi_key_dict import multi_key_dict

uAll_NODES = cmds.allNodeTypes()

uALL_SHADING_NODES = cmds.listNodeTypes('shader') + \
                     cmds.listNodeTypes('texture') + \
                     cmds.listNodeTypes('light') + \
                     cmds.listNodeTypes('postProcess') + \
                     cmds.listNodeTypes('utility')
                     
UNPACK_TYPES = [u'short2', u'short3', u'long2', u'long3', u'float2', u'float3',
                u'double2', u'double3', u'matrix', u'pointArray', 
                u'vectorArray', u'stringArray', u'cone', u'reflectanceRGB', 
                u'spectrumRGB', u'componentList']

PACKED_TYPES = [u'Int32Array', u'doubleArray', u'attributeAlias']

TIME_VALS = ['hour','min','sec','millisec','game','film',
             'pal','ntsc','show','palf','ntscf']
Example #42
0
def isAMaterial(node):
    """Returns true if the given node is a type of material node"""
    return cmds.nodeType(node) in cmds.listNodeTypes("shader")