Example #1
0
def get_render_image_dir():
    os_type = get_os_type.get_os_type()
    final_dir = None
    try:
        full_path = mc.renderSettings(firstImageName=1, fullPath=1)[0]
        image_dir = full_path.split('images')[0]
        acc_dir = os.path.dirname(full_path.split('images')[1].strip('/'))
        tmp_dir = os.path.join(image_dir, 'images', 'tmp')
        new_image_dir = os.path.join(tmp_dir, acc_dir)
        new_image_dir = new_image_dir.replace('\\', '/')
        if os.path.isdir(new_image_dir):
            final_dir = new_image_dir
        elif os.path.isdir(tmp_dir):
            final_dir = tmp_dir
        elif os.path.isdir(image_dir):
            final_dir = image_dir
    except:
        full_path = mc.renderSettings(firstImageName=1, fullPathTemp=1)[0]
        final_dir = os.path.dirname(full_path)
    print final_dir
    if os.path.isdir(final_dir):
        if os_type == 'windows':
            os.startfile(final_dir)
        if os_type == 'linux':
            os.system('xdg-open %s' % final_dir)
Example #2
0
def SetupCamera():
    cam = cmds.camera()
    cmds.lookThru(cam[0])
    cmds.setAttr(cam[1] + ".renderable", True)
    cmds.setAttr("persp.renderable", False)
    cmds.setAttr("top.renderable", False)
    cmds.setAttr("front.renderable", False)
    cmds.setAttr("side.renderable", False)
    cmds.select(cam[0])
    cmds.rotate(-20.738, 48.547, -0.414)
    cmds.move(24.026, 15.354, 21.047)
    cmds.renderSettings(cam=cam[1])
Example #3
0
    def collect_rendered_images(self, parent_item):
        """Creates items for any rendered images that can be identified by
        render layers in the file.

        Args:
            parent_item (obj): Parent Item instance.
        """
        # iterate over defined render layers and query the render settings for
        # information about a potential render
        for layer in cmds.ls(type="renderLayer"):

            self.logger.info("Processing render layer: %s" % (layer, ))

            # use the render settings api to get a path where the frame number
            # spec is replaced with a '*' which we can use to glob
            (frame_glob, ) = cmds.renderSettings(genericFrameImageName="*",
                                                 fullPath=True,
                                                 layer=layer)

            # see if there are any files on disk that match this pattern
            rendered_paths = glob.glob(frame_glob)

            if rendered_paths:
                # we only need one path to publish, so take the first one and
                # let the base class collector handle it
                item = super(MayaSessionCollector,
                             self)._collect_file(parent_item,
                                                 rendered_paths[0],
                                                 frame_sequence=True)

                # the item has been created. update the display name to include
                # the an indication of what it is and why it was collected
                item.name = "%s (Render Layer: %s)" % (item.name, layer)
Example #4
0
        def __init__(self, assets_path, project, send_mode, render_position):

            self.assets_path = assets_path
            self.project = project
            self.send_mode = send_mode
            self.render_position = render_position

            self.accepted_renderers = ['vray', 'redshift', 'arnold']
            self.image_path = cmds.renderSettings(
                firstImageName=True, fpt=True)[0].rsplit('.', 1)[0] + '.exr'
            self.render_geo = cmds.ls(sl=True, typ="transform")
            self.current_renderer = cmds.getAttr(
                'defaultRenderGlobals.currentRenderer')
            self.render_camera = cmds.modelPanel("modelPanel4",
                                                 query=True,
                                                 camera=True)
            self.render_camera_xforms = cmds.xform(self.render_camera,
                                                   q=True,
                                                   ws=True,
                                                   m=True)

            self.final_path = None

            self.hdri_render_main()
            self.finalise_render()
            self.prepare_image_path()
Example #5
0
    def preview_fname(self, instance):
        """Return outputted filename with #### for padding

        Passing the absolute path to Deadline enables Deadline Monitor
        to provide the user with a Job Output menu option.

        Deadline requires the path to be formatted with # in place of numbers.

        From
            /path/to/render.0000.png
        To
            /path/to/render.####.png

        """

        from maya import cmds

        # We'll need to take tokens into account
        fname = cmds.renderSettings(firstImageName=True,
                                    fullPath=True,
                                    layer=instance.name)[0]

        try:
            # Assume `c:/some/path/filename.0001.exr`
            # TODO(marcus): Bulletproof this, the user may have
            # chosen a different format for the outputted filename.
            fname, padding, suffix = fname.rsplit(".", 2)
            fname = ".".join([fname, "#" * len(padding), suffix])
            self.log.info("Assuming renders end up @ %s" % fname)
        except ValueError:
            fname = ""
            self.log.info("Couldn't figure out where renders go")

        return fname
Example #6
0
    def foolCheckRenderSettings(self, renderLayerList):
        severity = 0

        # get the timeslider range:
        # startFrame = pm.playbackOptions(q=True, minTime=True)
        # endFrame = pm.playbackOptions(q=True, maxTime=True)
        startFrame = cmds.playbackOptions(q=True, minTime=True)
        endFrame = cmds.playbackOptions(q=True, maxTime=True)

        # activeRenderLayer = pm.editRenderLayerGlobals(q=True, currentRenderLayer=True)
        activeRenderLayer = cmds.editRenderLayerGlobals(q=True, currentRenderLayer=True)

        # go through all renderlayers:
        for layer in renderLayerList:
            # pm.editRenderLayerGlobals(currentRenderLayer=layer)
            cmds.editRenderLayerGlobals(currentRenderLayer=layer)

            # get paths
            # comparePath = pm.renderSettings(firstImageName=True, lastImageName=True, fp=True)
            comparePath = cmds.renderSettings(firstImageName=True, lastImageName=True, fp=True)
            filePath, fileBase = os.path.split(comparePath[0])

            ## COmmon for all render engines
            # get the render range
            # animStart = pm.getAttr("defaultRenderGlobals.startFrame")
            animStart = cmds.getAttr("defaultRenderGlobals.startFrame")
            # animEnd = pm.getAttr("defaultRenderGlobals.endFrame")
            animEnd = cmds.getAttr("defaultRenderGlobals.endFrame")
            if animStart != startFrame or animEnd != endFrame:
                # msg = "Timeslider range and render ranges are different in {4}. {0}-{1} >> {2}-{3}".format(startFrame,
                msg = "Timeslider range and Render ranges are different (%s)" %layer
                self.minorProblemNodes.append(
                    ["defaultRenderGlobals", layer, "unifiedRenderGlobalsWindow;", msg])  # RG is for Render Globals
                severity += 1
        return severity
Example #7
0
def get_maya_image_dirpath():
    '''
    Return the "images" directory for the active maya workspace
    '''
    image_filepath = cmds.renderSettings(fullPath=True, genericFrameImageName=True)
    assert len(image_filepath) == 1, image_filepath
    return os.path.dirname(image_filepath[0])
Example #8
0
def path():
    fl = cmds.renderSettings(firstImageName=True)

    folderParts = fl[0].split("/")
    folderParts = folderParts[:-1]
    folderPath = "/".join(folderParts)
    print folderPath
    return folderPath
Example #9
0
def OpenRenderFolder(folderType):
    #path definitions
    workspace = cmds.workspace(q=True, fullName=True)
    imagePath = cmds.renderSettings(fin=True, fp=True)[0]
    tempImagePath = cmds.renderSettings(fin=True, fpt=True)[0]
    sourceimagesPath = '%s/sourceimages/' % (workspace)

    locations = [imagePath, tempImagePath, sourceimagesPath]

    folderPath = locations[folderType].rsplit('/', 1)[0]
    ntfolderPath = folderPath.replace('/', '\\')

    #make folder if it doesn't exist
    if not os.path.exists(ntfolderPath):
        os.makedirs(ntfolderPath)
    try:
        #open folder
        os.startfile(ntfolderPath)
    except:
        cmds.error('Folder does\'t exist and can not be created')
Example #10
0
	def getFileName(self):
		# Get name of scene file, untitled if not saved
		self.sceneFile = cmds.file(q=True, sceneName=True, shortName=True)
		if len(self.sceneFile) == 0:
			self.sceneFile = 'untitled'
		# Seperate name from extension
		self.sceneName, sep, ext = self.sceneFile.partition('.')
		self.renderFolder = self.outPath + self.sceneName + '/'
		# Find current frame and file output name
		imgName = cmds.renderSettings(fin=True, fp=True)[0]
		curFrame = cmds.currentTime(q=True)
		curPadding = imgName.split('.')[1]
		self.newFile = imgName.replace(curPadding, '%04d' % int(curFrame))
		# Create new name from old
		self.newName = self.newFile.partition("_")[0] + '_' + '%04d' % int(curFrame) + "." + self.newFile.rpartition(".")[2]
Example #11
0
def layerDict(l):
    prefData = []
    #get image path for the render layer
    rendeFilePath = cmds.renderSettings(fin=True,fp=True,cts=True,lyr=l)
    path = rendeFilePath[0].rsplit('/',1)[0]
    filename = rendeFilePath[0].split('/')[-1]

    prefData.append(['img','imgpath','%s/'%path])
    prefData.append(['img','imgname',filename])
    prefData.append(['user','trelloID','name'])
    prefData.append(['user','trelloAddress','name'])
    prefData.append(['user','name',stf_window.mainWidget.lineEdit_name.text()])
    prefData.append(['user','slackID',stf_window.mainWidget.lineEdit_slack.text()])

    IO.writePrefsToFile(prefData,'%s/.data/%s.%s.json'%(getProj.sceneFolder(),getProj.sceneName(),l))
Example #12
0
def get_renderer_variables(renderlayer=None):
    """Retrieve the extension which has been set in the VRay settings

    Will return None if the current renderer is not VRay
    For Maya 2016.5 and up the renderSetup creates renderSetupLayer node which
    start with `rs`. Use the actual node name, do NOT use the `nice name`

    Args:
        renderlayer (str): the node name of the renderlayer.

    Returns:
        dict
    """

    renderer = lib.get_renderer(renderlayer or lib.get_current_renderlayer())
    render_attrs = lib.RENDER_ATTRS.get(renderer, lib.RENDER_ATTRS["default"])

    padding = cmds.getAttr("{}.{}".format(render_attrs["node"],
                                          render_attrs["padding"]))

    filename_0 = cmds.renderSettings(fullPath=True, firstImageName=True)[0]

    if renderer == "vray":
        # Maya's renderSettings function does not return V-Ray file extension
        # so we get the extension from vraySettings
        extension = cmds.getAttr("vraySettings.imageFormatStr")

        # When V-Ray image format has not been switched once from default .png
        # the getAttr command above returns None. As such we explicitly set
        # it to `.png`
        if extension is None:
            extension = "png"

        filename_prefix = "<Scene>/<Scene>_<Layer>/<Layer>"
    else:
        # Get the extension, getAttr defaultRenderGlobals.imageFormat
        # returns an index number.
        filename_base = os.path.basename(filename_0)
        extension = os.path.splitext(filename_base)[-1].strip(".")
        filename_prefix = cmds.getAttr("defaultRenderGlobals.imageFilePrefix")

    return {
        "ext": extension,
        "filename_prefix": filename_prefix,
        "padding": padding,
        "filename_0": filename_0
    }
Example #13
0
    def collect_rendered_images(self, settings, parent_item):
        """
        Creates items for any rendered images that can be identified by
        render layers in the file.

        :param dict settings: Configured settings for this collector
        :param parent_item: Parent Item instance
        :return:
        """
        items = []

        # iterate over defined render layers and query the render settings for
        # information about a potential render
        for layer in cmds.ls(type="renderLayer"):

            self.logger.info("Processing render layer: %s" % (layer,))

            # use the render settings api to get a path where the frame number
            # spec is replaced with a '*' which we can use to glob
            (frame_glob,) = cmds.renderSettings(
                genericFrameImageName="*",
                fullPath=True,
                layer=layer
            )

            # see if there are any files on disk that match this pattern
            rendered_paths = glob.glob(frame_glob)

            if rendered_paths:
                # we only need one path to publish, so take the first one and
                # let the base class collector handle it
                item = self._collect_file(settings, parent_item, rendered_paths[0])
                if not item:
                    continue

                # the item has been created. update the display name to include
                # the an indication of what it is and why it was collected
                item.name = "Render Layer (%s)" % (layer,)

                # Store the layer as the item node
                item.properties.node = layer

                # Add the item to the list
                items.append(item)

        return items
Example #14
0
 def get_current_render_frame_path(self, current_frame):
     if self.renderer == "vray":
         image_dir = get_render_images_dir.get_render_images_dir()
         file_name_prefix = mc.getAttr("vraySettings.fnprx")
         ext = mc.getAttr("vraySettings.imageFormatStr")
         full_path = "%s/%s.%s" % (image_dir, file_name_prefix, ext)
         current_layer = mc.editRenderLayerGlobals(q=1, crl=1)
         version = mc.getAttr("defaultRenderGlobals.rv")
         current_frame_path = full_path.replace("<Layer>", current_layer).replace("<Version>", version)
     else:
         first_image = mc.renderSettings(fin=1, fp=1)[0]
         first_image_list = first_image.split(".")
         prefix = ".".join(first_image_list[:-2])
         frame = str(current_frame).zfill(4)
         ext = first_image_list[-1]
         current_frame_path = ".".join([prefix, frame, ext])
     return current_frame_path
Example #15
0
	def get_image_name ( self ) :
		"""get_image_name
		"""
		pad_str = getPadStr(
			self.job_param['job_padding'],
			self.ass_param['ass_perframe']
		)

		images = cmds.renderSettings(
			fullPath=True,
			genericFrameImageName=('@%s@' % pad_str)
		)

		#imageFileName = ';'.join (images)
		imageFileName = str(images[0])
		( fileName, ext ) = os.path.splitext ( imageFileName )
		imageFileName = fileName + '.' + self.getImageFormat ()
		return fromNativePath(imageFileName)
Example #16
0
        def __init__(self, assets_path, project, send_mode, render_position):

            self.assets_path = assets_path
            self.project = project
            self.send_mode = send_mode
            self.render_position = render_position

            self.accepted_renderers = ['vray', 'redshift', 'arnold']
            self.image_path = cmds.renderSettings(firstImageName=True,  fpt=True)[0].rsplit('.', 1)[0] + '.exr'
            self.render_geo = cmds.ls(sl=True, typ="transform")
            self.current_renderer = cmds.getAttr('defaultRenderGlobals.currentRenderer')
            self.render_camera = cmds.modelPanel("modelPanel4", query=True, camera=True)            # get current cam
            self.render_camera_xforms = cmds.xform(self.render_camera, q=True, ws=True, m=True)     # orig camera pos

            self.final_path = None

            self.hdri_render_main()
            self.finalise_render()
            self.prepare_image_path()
 def rendererChange(self, *args):
     newJobRenderer = cmds.optionMenu('newJobSoftware', q=True, v=True)
     if newJobRenderer == 'maya-mray':
         targetVar = cmds.renderSettings(ign=True)[0]
         cmds.textField('newJobTarget', e=True, tx=str(targetVar))
     elif newJobRenderer == 'maya-vray':
         if cmds.objExists('vraySettings'):
             targetVar = cmds.getAttr('vraySettings.fileNamePrefix', asString=True)
             padding = cmds.getAttr('vraySettings.fileNamePadding', asString=True)
             if cmds.getAttr('vraySettings.imageFormatStr', asString=True) == 'exr (multichannel)':
                 textVar = targetVar+'%'+str(padding)+'n.%e'
             else:
                 textVar = targetVar+'.%'+str(padding)+'n.%e'
             cmds.textField('newJobTarget', e=True, tx=str(textVar))
         else:
             cmds.confirmDialog(icn='warning', t='CR', m='No V-ray setting node exist!', button=['OK'])
             cmds.optionMenu('newJobSoftware', e=True, sl=1)
             cmds.textField('newJobTarget', e=True, tx='')
     return
    def load_aov(self):
        """ Load the selected AOV into the Render View framebuffer.
		"""
        # Get the name of the selected AOV by querying the combo box
        aov = mc.optionMenu("aov_comboBox", query=True, value=True)

        frame_str = str(int(self.frame)).zfill(
            mc.getAttr("defaultRenderGlobals.extensionPadding"))
        img_path = mc.renderSettings(fullPathTemp=True,
                                     leaveUnmatchedTokens=True,
                                     genericFrameImageName=frame_str)

        if self.renderer == "arnold":
            img = img_path[0].replace("<RenderPass>", aov)

        elif self.renderer == "redshift":  # TODO: update this to respect Redshift's AOV name prefix attribute
            if aov == self.default_beauty_aov_name:
                #img = img_path[0].replace( "<RenderPass>", "Beauty" )
                img = img_path[0]
            else:
                #img = img_path[0].replace( "<RenderPass>", "Beauty.%s" %aov )
                layer = mc.editRenderLayerGlobals(query=True,
                                                  currentRenderLayer=True)
                if layer == "defaultRenderLayer":
                    layer = "masterLayer"
                img = img_path[0].replace("%s." % layer,
                                          "%s.%s." % (layer, aov))

        elif self.renderer == "mentalRay":
            if aov == self.default_beauty_aov_name:
                img = img_path[0].replace("<RenderPass>", "MasterBeauty")
            else:
                img = img_path[0].replace("<RenderPass>", aov)

        #img = os.path.normpath(os.path.expandvars(img)).replace("\\", "/")
        #img = os_wrapper.absolutePath(img)
        print(img)

        # Load the image
        rview = mc.getPanel(scriptType="renderWindowPanel")
        mc.renderWindowEditor(rview, edit=True, loadImage=img)
Example #19
0
def imageNameParts():
  # 0 baseName
  # 1 version
  # 2 extension

	imageNames = cmds.renderSettings(firstImageName=True)
	parts = imageNames[0].split(".")
	ret = [None,None,None]
	ret[0] = parts[0]

	ret[1] = maya.mel.eval('match "v[0-9][0-9][0-9]" "'+ret[0]+'"')
	if ret[1] == "":
		ret[1] = "v000"

	ret[2] = parts[2]

	r = maya.mel.eval("currentRenderer()")
	if( ret[2] == "sgi" and r == "mentalRay" ): # and int(cmds.about(version=True)) == 8 ):
		ret[2] = "rgb"

	return ret
    def collect_rendered_images(self, parent_item):
        """
        Creates items for any rendered images that can be identified by
        render layers in the file.

        :param parent_item: Parent Item instance
        :return:
        """

        # iterate over defined render layers and query the render settings for
        # information about a potential render
        for layer in cmds.ls(type="renderLayer"):

            self.logger.info("Processing render layer: %s" % (layer,))

            # use the render settings api to get a path where the frame number
            # spec is replaced with a '*' which we can use to glob
            (frame_glob,) = cmds.renderSettings(
                genericFrameImageName="*",
                fullPath=True,
                layer=layer
            )

            # see if there are any files on disk that match this pattern
            rendered_paths = glob.glob(frame_glob)

            if rendered_paths:
                # we only need one path to publish, so take the first one and
                # let the base class collector handle it
                item = super(MayaSessionCollector, self)._collect_file(
                    parent_item,
                    rendered_paths[0],
                    frame_sequence=True
                )

                # the item has been created. update the display name to include
                # the an indication of what it is and why it was collected
                item.name = "%s (Render Layer: %s)" % (item.name, layer)
Example #21
0
    def _copy_sequence(self, input_path, output_path):

        fl = cmds.renderSettings(firstImageName=True, lastImageName=True)

        try:
            fl0_split = fl[0].split('.')
            start_frame = int(fl0_split[len(fl0_split) - 2])
            fr_padding = len(fl0_split[len(fl0_split) - 2])
        except:
            print "<debug>", fl
            raise TankError(
                "Problem with naming convention of render. Render naming convention {name}.{version}.{SEQ}.exr"
            )

        if fl[1] == '':
            end_frame = int(fl0_split[len(fl0_split) - 2])
        else:
            fl1_split = fl[1].split('.')
            end_frame = int(fl1_split[len(fl1_split) - 2])

        # print "<debug>", output_path

        # Make directories based on output path.
        try:
            if not os.path.exists(output_path):
                os.makedirs(output_path)

            # Copy image sequence
            for num in range(start_frame, end_frame + 1):
                input_path_new = re.sub(r'%[0-9]+d',
                                        str(num).zfill(fr_padding), input_path)
                # print "<debug>", input_path_new
                copy(input_path_new, output_path)
        except:
            print "Problem copying files. Check permissions of output path."
            return False

        return True
Example #22
0
def RS_AOVView():
    ### REDSHIFT AOV VIEWER ### Chris Lyne - 2016

    ##SETUP
    #import sys
    #sys.path.append('Z:/Job_3/System/Deployment/mel')

    ##SHELF
    #import RS_AOVView
    #reload(RS_AOVView)
    #RS_AOVView.RS_AOVView()

    ##BUGS
    # Doesn't work with negatives

    renderFrameStr = RenderFrameString()

    #find file paths
    imageRGB = cmds.renderSettings(fpt=True, gin=renderFrameStr)
    imageString = str(unicode(imageRGB[0]))
    basePath = imageString.split('/')
    fullFilename = basePath[len(basePath) - 1]
    fullFilenameSplit = fullFilename.split('.')
    fileName = fullFilenameSplit[0]
    fileNumber = ""
    if cmds.getAttr("defaultRenderGlobals.animation") == 1:
        fileNumber = "." + renderFrameStr
    fileExtention = fullFilenameSplit[len(fullFilenameSplit) - 1]
    basePath.remove(basePath[len(basePath) - 1])
    basePathFolder = ""
    for item in basePath:
        basePathFolder += (item + "/")
    aovs = cmds.ls("*rsAov*")
    refAovs = cmds.ls("*:rsAov*")
    aovs += refAovs

    def printNewMenuItem(item):
        aov = item
        rview = cmds.getPanel(sty='renderWindowPanel')

        fileExtention = fileFormat(aov)  #get file type
        latest_file = (basePathFolder + "/" + AOVPath(aov) + fileNumber + "." +
                       fileExtention)

        splitPath = latest_file.replace('/', '\\')
        splitPath = splitPath.split(os.sep)

        for n, i in enumerate(splitPath):
            if i in aovs or i == 'beauty':
                splitPath[n] = selectedAOV

        splitPath[0] = splitPath[0] + '\\'

        pathToImg = reduce(os.path.join, splitPath)

        print pathToImg
        cmds.renderWindowEditor(rview, e=True, li=pathToImg)

    window = cmds.window(title="RS AOV Viewer", height=200)
    cmds.columnLayout()
    cmds.optionMenu(label='Channel', changeCommand=printNewMenuItem)
    cmds.menuItem(label="beauty")
    for item in aovs:
        isEnabled = cmds.getAttr(item + ".enabled")
        if isEnabled == 1:
            cmds.menuItem(label=item)
    cmds.showWindow(window)
Example #23
0
def compose_render_filename(layer, renderpass="", camera="", on_frame=None):
    """
    """
    renderer = get_renderer_by_layer(layer)
    prefix = get_render_filename_prefix(layer) or ""
    multi_render_cams = len(lib.ls_renderable_cameras(layer)) > 1
    has_renderlayers = lib.ls_renderable_layers() != ["defaultRenderLayer"]
    is_animated = cmds.getAttr("defaultRenderGlobals.animation")
    padding_str = "#" * get_render_padding(renderer)
    scene_name = cmds.file(query=True, sceneName=True,
                           shortName=True).rsplit(".", 1)[0]

    # (NOTE) There's another *Deep EXR* in both VRay("exr (deep)") and
    #   Arnold("deepexr"), it's not being handled here since it's a rarely
    #   used format.
    #
    # (NOTE) Arnold's "deepexr" has been handled below.
    #

    if renderer == "vray":
        from . import vray

        if not cmds.objExists("vraySettings"):
            vray.utils.create_vray_settings()

        ext, is_multichannel_exr = vray.utils.get_vray_output_image_format()

        separate_folders = cmds.getAttr("vraySettings"
                                        ".relements_separateFolders")
        separate_rgba = cmds.getAttr("vraySettings" ".relements_separateRGBA")

        prefix = prefix or scene_name

        if renderpass and separate_folders:
            head, tail = os.path.split(prefix)
            prefix = "/".join([head, renderpass, tail])

        elif not renderpass and separate_folders and separate_rgba:
            head, tail = os.path.split(prefix)
            prefix = "/".join([head, "rgba", tail])

        # Put <Camera> tag if having multiple renderable cameras and
        # <Camera> tag not in prefix
        if (multi_render_cams
                and not any(t in prefix
                            for t in ["<Camera>", "<camera>", "%c"])):
            prefix = "/".join(["<Camera>", prefix])

        # Put <Layer> tag if having multiple renderlayers and
        # <Layer> tag not in prefix
        if (has_renderlayers
                and not any(t in prefix
                            for t in ["<Layer>", "<layer>", "%l"])):
            prefix = "/".join(["<Layer>", prefix])

        # Don't transform if the prefix is blank, so we can just default to
        # the scene file name.
        if prefix:
            for tag in ("<Layer>", "<layer>", "%l"):
                # We need to replace renderlayer tag by ourself if we don't
                # switch renderlayer.
                prefix = prefix.replace(tag, lib.pretty_layer_name(layer))
            prefix = mel.eval("vrayTransformFilename("
                              "\"{0}\", \"{1}\", \"{2}\", 0, 0, 0)"
                              "".format(prefix, camera, scene_name))

        pass_sep = cmds.getAttr("vraySettings"
                                ".fileNameRenderElementSeparator")
        if renderpass and not is_multichannel_exr:
            prefix = prefix + pass_sep + renderpass

        elif (not renderpass and separate_folders and separate_rgba
              and not is_multichannel_exr):
            prefix = prefix + pass_sep + "rgba"

        if is_animated:
            # When rendering to a non-raw format, vray places a period before
            # the padding, even though it doesn't show up in the render
            # globals filename.
            if ext == "vrimg":
                output_prefix = prefix + padding_str + "." + ext
            else:
                output_prefix = prefix + "." + padding_str + "." + ext
        else:
            output_prefix = prefix + "." + ext

    else:
        # Not VRay

        current_prefix = prefix
        prefix = prefix or scene_name

        if renderer == "arnold" and "<RenderPass>" not in prefix:
            from . import arnold
            aov_names = arnold.utils.get_arnold_aov_names(layer)
            if aov_names:
                prefix = "/".join(["<RenderPass>", prefix])

        # Put <Camera> tag if having multiple renderable cameras and
        # <Camera> tag not in prefix
        if (multi_render_cams
                and not any(t in prefix for t in ["<Camera>", "%c"])):
            prefix = "/".join(["<Camera>", prefix])

        # Put <RenderLayer> tag if having multiple renderlayers and
        # <RenderLayer> tag not in prefix
        if (has_renderlayers
                and not any(t in prefix
                            for t in ["<RenderLayer>", "<Layer>", "%l"])):
            prefix = "/".join(["<RenderLayer>", prefix])

        with capsule.maintained_modification():
            cmds.setAttr("defaultRenderGlobals.imageFilePrefix",
                         prefix,
                         type="string")

            output_prefix = cmds.renderSettings(
                genericFrameImageName=padding_str,
                layer=layer,
                camera=camera,
                customTokenString="RenderPass="******"defaultRenderGlobals.imageFilePrefix",
                         current_prefix,
                         type="string")

        filename, ext = os.path.splitext(output_prefix)
        if ext == ".deepexr":
            output_prefix = filename + ".exr"

    if is_animated and on_frame is not None:
        frame_str = "%%0%dd" % len(padding_str) % on_frame
        output_prefix = output_prefix.replace(padding_str, frame_str)

    return output_prefix
Example #24
0
def name():
    fl = cmds.renderSettings(firstImageName=True)
    folderParts = fl[0].split("/")
    fileParts = folderParts[-1].split(".")
    return fileParts[0]
Example #25
0
    def getImageOut2009(self):
        maya.mel.eval('renderSettings -fin -lyr "' + self.name +
                      '";')  # workaround for batch mode to load command
        RenderOut = cmds.renderSettings(ign=True, lyr=self.name)
        RenderOut = RenderOut[0]
        RenderOut = RenderOut.replace("\\", "/")
        FNsplitter = ""
        if (RenderOut.find("%0n") >= 0):
            FNsplitter = "%0n"
            self.imageFramePadding = 1
        if (RenderOut.find("%1n") >= 0):
            FNsplitter = "%1n"
            self.imageFramePadding = 1
        if (RenderOut.find("%2n") >= 0):
            FNsplitter = "%2n"
            self.imageFramePadding = 2
        if (RenderOut.find("%3n") >= 0):
            FNsplitter = "%3n"
            self.imageFramePadding = 3
        if (RenderOut.find("%4n") >= 0):
            FNsplitter = "%4n"
            self.imageFramePadding = 4
        if (RenderOut.find("%5n") >= 0):
            FNsplitter = "%5n"
            self.imageFramePadding = 5
        if (RenderOut.find("%6n") >= 0):
            FNsplitter = "%6n"
            self.imageFramePadding = 6
        if (RenderOut.find("%7n") >= 0):
            FNsplitter = "%7n"
            self.imageFramePadding = 7
        if (RenderOut.find("%8n") >= 0):
            FNsplitter = "%8n"
            self.imageFramePadding = 8
        if (RenderOut.find("%9n") >= 0):
            FNsplitter = "%9n"
            self.imageFramePadding = 9

        if (len(FNsplitter) > 0):
            Splitted = RenderOut.split(FNsplitter, 1)
            self.imageFileName = Splitted[0]
            self.imageExtension = Splitted[1]
            if ((self.renderer == "renderMan")
                    and (self.imagePreNumberLetter == "_")):
                if (self.name == "masterLayer"):
                    self.imageFileName += "__"
                else:
                    self.imageFileName += "_"
        else:
            self.imageFileName = RenderOut
            self.imageExtension = ""

        self.imageFileName = self.imageFileName.replace("%/l", "<Layer>/")
        self.imageFileName = self.imageFileName.replace("%l", "<Layer>")
        self.imageFileName = self.imageFileName.replace(
            "<RenderLayer>", "<Layer>")
        self.imageFileName = self.imageFileName.replace("%/c", "<Camera>/")
        self.imageFileName = self.imageFileName.replace("%c", "<Camera>")
        self.imageFileName = self.imageFileName.replace("%/s", "<SceneFile>/")
        self.imageFileName = self.imageFileName.replace("%s", "<SceneFile>")
        self.imageFileName = self.imageFileName.replace(
            "<Scene>", "<SceneFile>")
        self.imageFileName = self.imageFileName.replace(
            "<RenderPass>", "<Channel>")
        self.imageFileName = self.imageFileName.replace(
            "<Version>", self.tempVersionTag)

        if ((self.name == "masterLayer") and (self.renderer == "renderMan")):
            self.imageFileName = self.imageFileName.replace("<Layer>", "")
        self.imageFileName = self.imageFileName.replace("//", "/")

        if (self.imageFileName.find("<Channel>") >= 0):
            if (self.renderer != "mentalRay"):
                self.imageFileName = self.imageFileName.replace(
                    "<Channel>", "")
            else:
                self.channelName = "MasterBeauty"
        self.imageFileName = self.imageFileName.replace(
            "%e", self.tempImageExtension)
        self.imageExtension = self.imageExtension.replace(
            "%e", self.tempImageExtension)
        self.imageFileName = self.imageFileName.replace(
            "<Extension>", self.tempImageExtension)
        self.imageExtension = self.imageExtension.replace(
            "<Extension>", self.tempImageExtension)
Example #26
0
    def getImageOut2009(self):
        maya.mel.eval('renderSettings -fin -lyr "'+self.name+'";') # workaround for batch mode to load command
        RenderOut=cmds.renderSettings(ign=True,lyr=self.name)        
        RenderOut=RenderOut[0]
        RenderOut=RenderOut.replace("\\","/")
        FNsplitter=""
        if (RenderOut.find("%0n")>=0):
            FNsplitter="%0n"
            self.imageFramePadding=1
        if (RenderOut.find("%1n")>=0):
            FNsplitter="%1n"
            self.imageFramePadding=1
        if (RenderOut.find("%2n")>=0):
            FNsplitter="%2n"
            self.imageFramePadding=2
        if (RenderOut.find("%3n")>=0):
            FNsplitter="%3n"
            self.imageFramePadding=3
        if (RenderOut.find("%4n")>=0):
            FNsplitter="%4n"
            self.imageFramePadding=4
        if (RenderOut.find("%5n")>=0):
            FNsplitter="%5n"
            self.imageFramePadding=5
        if (RenderOut.find("%6n")>=0):
            FNsplitter="%6n"
            self.imageFramePadding=6
        if (RenderOut.find("%7n")>=0):
            FNsplitter="%7n"
            self.imageFramePadding=7
        if (RenderOut.find("%8n")>=0):
            FNsplitter="%8n"
            self.imageFramePadding=8
        if (RenderOut.find("%9n")>=0):
            FNsplitter="%9n"
            self.imageFramePadding=9
            
        if (len(FNsplitter)>0):
            Splitted=RenderOut.split(FNsplitter,1)
            self.imageFileName=Splitted[0]
            self.imageExtension=Splitted[1]
            if ((self.renderer=="renderMan") and (self.imagePreNumberLetter=="_")):
                if (self.name=="masterLayer"):
                    self.imageFileName+="__"
                else:
                    self.imageFileName+="_"
        else:
            self.imageFileName=RenderOut
            self.imageExtension=""

        self.imageFileName=self.imageFileName.replace("%/l","<Layer>/")
        self.imageFileName=self.imageFileName.replace("%l","<Layer>")
        self.imageFileName=self.imageFileName.replace("<RenderLayer>","<Layer>")        
        self.imageFileName=self.imageFileName.replace("%/c","<Camera>/")
        self.imageFileName=self.imageFileName.replace("%c","<Camera>")
        self.imageFileName=self.imageFileName.replace("%/s","<SceneFile>/")
        self.imageFileName=self.imageFileName.replace("%s","<SceneFile>")
        self.imageFileName=self.imageFileName.replace("<Scene>","<SceneFile>")
        self.imageFileName=self.imageFileName.replace("<RenderPass>","<Channel>")        
        self.imageFileName=self.imageFileName.replace("<Version>",self.tempVersionTag)

        if ((self.name=="masterLayer") and (self.renderer=="renderMan")):
            self.imageFileName=self.imageFileName.replace("<Layer>","")
        self.imageFileName=self.imageFileName.replace("//","/")
                
        if (self.imageFileName.find("<Channel>")>=0):
            if (self.renderer!="mentalRay"):
                self.imageFileName=self.imageFileName.replace("<Channel>","")
            else:
                self.channelName="MasterBeauty"
        self.imageFileName=self.imageFileName.replace("%e",self.tempImageExtension)
        self.imageExtension=self.imageExtension.replace("%e",self.tempImageExtension)
        self.imageFileName=self.imageFileName.replace("<Extension>",self.tempImageExtension)
        self.imageExtension=self.imageExtension.replace("<Extension>",self.tempImageExtension)
Example #27
0
    def collect_rendered_images(self, parent_item):
        """
        Creates items for any rendered images that can be identified by
        render layers in the file.

        :param parent_item: Parent Item instance
        :return:
        """
        scene = cmds.file(q=True, sn=True)
        basename = os.path.basename(scene)
        _name, ext = os.path.splitext(basename)
        work_dir = cmds.workspace(q=True, sn=True)
        image_dir = work_dir + '/images'

        # get a list of render layers not defined in the file
        render_layers = []
        _render = cmds.getAttr("defaultRenderGlobals.currentRenderer")
        # _prefix = cmds.getAttr("vraySettings.fileNamePrefix")
        for layer_node in cmds.ls(type="renderLayer"):
            try:
                # if this succeeds, the layer is defined in a referenced file
                cmds.referenceQuery(layer_node, filename=True)
            except RuntimeError:
                # runtime error means the layer is defined in this session
                render_layers.append(layer_node)

        # iterate over defined render layers and query the render settings for
        # information about a potential render
        for layer in render_layers:

            self.logger.info("Processing render layer: %s" % (layer, ))

            # use the render settings api to get a path where the frame number
            # spec is replaced with a '*' which we can use to glob
            (frame_glob, ) = cmds.renderSettings(genericFrameImageName="*",
                                                 fullPath=True,
                                                 layer=layer)
            if _render == "vray":
                try:

                    mel.eval("unifiedRenderGlobalsWindow;")
                    cmds.workspaceControl("unifiedRenderGlobalsWindow",
                                          e=True,
                                          vis=0,
                                          r=True)
                    fileprefix = cmds.getAttr('vraySettings.fileNamePrefix')
                    _image_format = cmds.getAttr("vraySettings.imageFormatStr")
                    if fileprefix == '<Scene>/<Layer>/<Scene>':
                        image_file = image_dir + '/' + _name + '/' + layer + '/' + _name + '*.%s' % _image_format
                        frame_glob = image_file
                except:
                    pass
            # see if there are any files on disk that match this pattern
            rendered_paths = glob.glob(frame_glob)
            self.logger.debug("rendered_paths: ----%s----" % rendered_paths)
            if rendered_paths:
                # we only need one path to publish, so take the first one and
                # let the base class collector handle it
                item = super(MayaSessionCollector,
                             self)._collect_file(parent_item,
                                                 rendered_paths[0],
                                                 frame_sequence=True)

                # the item has been created. update the display name to include
                # the an indication of what it is and why it was collected
                item.name = "%s (Render Layer: %s)" % (item.name, layer)
                item._expanded = False
                item._active = False
Example #28
0
	def prefix(self):
		return cmds.renderSettings(firstImageName=True, leaveUnmatchedTokens=True, customTokenString="<Scene>/<RenderLayer>/<RenderPass>/<frame>/<Scene>_<RenderLayer>.<RenderPass>")[0]
Example #29
0
	def imageFileSuffix(self): return  ''.join(mc.renderSettings(fin=1,lut=1))#masterLayer/<RenderPass>/masterLayer.0001.png
	def imageFilePath(self): return  ''.join(mc.renderSettings(fin=1,lut=1,fp=1))#PROJECT/IMAGES/masterLayer/<RenderPass>/masterLayer.0001.png
Example #30
0
def QuantituRender_zwz():
    inPlayoption = int(
        mc.textScrollList('myplayoptions', q=True, selectItem=True)[0])
    inshowoption = int(
        mc.textScrollList('myshowoptions', q=True, selectItem=True)[0])
    mc.setAttr("defaultRenderGlobals.imageFilePrefix",
               "<Scene>/<RenderLayer>/<Camera>/<Camera>",
               type="string")
    allLayers = mc.listConnections('renderLayerManager.renderLayerId')
    myAllLayers = []
    AllCameras = []
    if allLayers:
        for Layer in allLayers:
            if mc.getAttr('%s.renderable' % Layer):
                myAllLayers.append(Layer)
    AllCameras = mc.listCameras(p=True)
    tmp = mc.workspace("images", query=True, renderTypeEntry=True)
    fullPath = mc.workspace(expandName=tmp)
    FramePadding = mc.getAttr("defaultRenderGlobals.extensionPadding")
    try:
        mm.eval("RenderViewWindow;")
    except:
        pass
    mm.eval('setNamedPanelLayout "Single Perspective View"; updateToolbox();')
    activePlane = ''
    i = 1
    while (i):
        try:
            tmp = mc.modelEditor('modelPanel%d' % i, q=True, av=True)
        except:
            pass
        else:
            if tmp:
                activePlane = 'modelPanel%d' % i
                break
        i += 1
    if inshowoption == 1:
        mc.modelEditor(activePlane, e=True, allObjects=0)
    temp = mc.getAttr('defaultRenderGlobals.currentRenderer')
    mc.setAttr('defaultRenderGlobals.currentRenderer', temp, type='string')
    for myLayer in myAllLayers:
        mc.editRenderLayerGlobals(currentRenderLayer=myLayer)
        StartFrame = EndFrame = 0
        StartFrame = int(mc.getAttr("defaultRenderGlobals.startFrame"))
        EndFrame = int(mc.getAttr("defaultRenderGlobals.endFrame"))
        mc.currentTime(StartFrame, update=True)
        mc.pause(sec=3)
        LayerType = mc.getAttr('defaultRenderGlobals.currentRenderer')
        if LayerType.find('vray') >= 0 or LayerType.find('arnold') >= 0:
            sys.stdout.write('%s can`t Render;\n' % LayerType)
            continue
        currentRenderLayer = mc.editRenderLayerGlobals(query=True,
                                                       currentRenderLayer=True)
        if currentRenderLayer != myLayer:
            mc.editRenderLayerGlobals(currentRenderLayer=myLayer)
        myAllCameras = []
        CameraShape = ''
        if AllCameras:
            for Camera in AllCameras:
                try:
                    CameraShape = mc.listRelatives(Camera, s=True)[0]
                except:
                    pass
                else:
                    if mc.getAttr('%s.renderable' % CameraShape):
                        myAllCameras.append(Camera)
        mc.progressWindow(title=u'批渲染器',
                          progress=0,
                          status=u'即将开始',
                          min=StartFrame,
                          max=EndFrame,
                          isInterruptable=True)
        imagePath = mc.renderSettings(firstImageName=True)[0]
        Layerpath = imagePath.split('/')
        myLayerName = '/'.join(Layerpath[:2])
        mytypeName = imagePath.split('.')[-1]
        mytypeV = 0
        if mytypeName.find('iff') >= 0:
            mytypeV = 1
        elif mytypeName.find('tif') >= 0:
            mytypeV = 2
        elif mytypeName.find('png') >= 0:
            mytypeV = 3
        for i in xrange(StartFrame, EndFrame + 1):
            mc.currentTime(StartFrame, update=True)
            mc.progressWindow(edit=True,
                              progress=i,
                              status="RenerLayer: %s  / Frame: %s" %
                              (myLayer, i))
            for myCamera in myAllCameras:
                finallyPath = (fullPath + '/' + myLayerName + '/%s/%s.' %
                               (myCamera, myCamera) +
                               str(i).zfill(FramePadding) + '.' + mytypeName)
                if inPlayoption == 1:
                    mc.lookThru(myCamera, myactivePlane)
                    mc.currentTime(StartFrame, update=True)
                mm.eval('updateModelPanelBar %s;' % activePlane)
                #mm.eval('RenderIntoNewWindow;')
                mm.eval('renderWindowRenderCamera render renderView "%s";' %
                        myCamera)
                if mc.progressWindow(q=True,
                                     isCancelled=True) or mc.progressWindow(
                                         q=True, progress=True) > EndFrame + 1:
                    mc.progressWindow(endProgress=True)
                    return False
                mc.setAttr('defaultRenderGlobals.imfkey', "", type="string")
                if mc.file(finallyPath, q=True, exists=True):
                    mc.sysFile(finallyPath, delete=True)
                if mytypeV == 1:
                    mm.eval(
                        'renderWindowSaveImageCallback "renderView" "%s" "Maya IFF";'
                        % finallyPath)
                elif mytypeV == 2:
                    mm.eval(
                        'renderWindowSaveImageCallback "renderView" "%s" "Tiff";'
                        % finallyPath)
                elif mytypeV == 3:
                    mm.eval(
                        'renderWindowSaveImageCallback "renderView" "%s" "PNG";'
                        % finallyPath)
                print "RenerLayer: %s  / Frame: %s" % (myLayer, i)
        mc.progressWindow(endProgress=True)
    return True
Example #31
0
    def collect_rendered_images(self, parent_item):
        """
        Creates items for any rendered images that can be identified by
        render layers in the file.

        :param parent_item: Parent Item instance
        :return:
        """

        # iterate over defined render layers and query the render settings for
        # information about a potential render
        for layer in cmds.ls(type="renderLayer"):

            self.logger.info("Processing render layer: %s" % (layer, ))

            # use the render settings api to get a path where the frame number
            # spec is replaced with a '*' which we can use to glob
            (frame_glob, ) = cmds.renderSettings(genericFrameImageName="*",
                                                 fullPath=True,
                                                 layer=layer)

            # see if there are any files on disk that match this pattern
            rendered_paths = glob.glob(frame_glob)

            try:

                path = rfm2.api.displays.get_displays(as_json=False)
                filepath = cmds.file(q=True, sn=True)
                filename = os.path.basename(filepath)
                directory = os.path.dirname(filepath)

                raw_name, extension = os.path.splitext(filename)
                cams = cmds.ls(cameras=True)

                frame = cmds.getAttr('defaultRenderGlobals.startFrame')
                frame = int(frame)
                frame = str(frame)
                frame = frame.zfill(4)

                rendered_paths = list()

                for cam in cams:
                    if cmds.getAttr(cam + ".renderable"):
                        rndcam = cam

                path2 = path["displays"]
                for key in path2.keys():
                    path3 = path2[key]
                    for key2 in path3.keys():
                        if key2 == "filePath":
                            final = path3["filePath"].replace("<aov>", key)
                            final = final.replace("<layer>", "")
                            final = final.replace("<scene>", raw_name)
                            final = final.replace("<ws>", directory)
                            final = final.replace("<version>", "001")
                            final = final.replace("<take>", "01")
                            final = final.replace("<ext>", "exr")
                            final = final.replace("<f4>", frame)
                            final = final.replace("<camera>", rndcam)
                            rendered_paths = final
                            if os.path.isfile(rendered_paths):

                                # we only need one path to publish, so take the first one and
                                # let the base class collector handle it
                                item = super(MayaSessionCollector,
                                             self)._collect_file(
                                                 parent_item,
                                                 rendered_paths,
                                                 frame_sequence=True)

                                # the item has been created. update the display name to include
                                # the an indication of what it is and why it was collected
                                item.name = "%s (Render Layer: %s)" % (
                                    item.name, layer)

            except:
                print "No Renderman frame found"
    def execute(self, **kwargs):
        """
        Main hook entry point
        :returns:       A list of any items that were found to be published.  
                        Each item in the list should be a dictionary containing 
                        the following keys:
                        {
                            type:   String
                                    This should match a scene_item_type defined in
                                    one of the outputs in the configuration and is 
                                    used to determine the outputs that should be 
                                    published for the item
                                    
                            name:   String
                                    Name to use for the item in the UI
                            
                            description:    String
                                            Description of the item to use in the UI
                                            
                            selected:       Bool
                                            Initial selected state of item in the UI.  
                                            Items are selected by default.
                                            
                            required:       Bool
                                            Required state of item in the UI.  If True then
                                            item will not be deselectable.  Items are not
                                            required by default.
                                            
                            other_params:   Dictionary
                                            Optional dictionary that will be passed to the
                                            pre-publish and publish hooks
                        }
        """

        items = []

        # get the main scene:
        scene_name = cmds.file(query=True, sn=True)
        if not scene_name:
            raise TankError("Please Save your file before Publishing")

        scene_path = os.path.abspath(scene_name)
        name = os.path.basename(scene_path)

        # create the primary item - this will match the primary output 'scene_item_type':
        items.append({"type": "work_file", "name": name})

        # get a list of any cameras in the scene
        all_persp_cameras = cmds.listCameras(perspective=True)
        for camera in all_persp_cameras:
            if not camera == 'persp':
                print '<scan-scene> found camera %s' % camera
                items.append({
                    "type": "camera",
                    "name": camera,
                    "description": "scene renderable camera",
                    "selected": True,
                })

        # look for root level groups that have meshes as children:
        for grp in cmds.ls(assemblies=True):
            if cmds.ls(grp, dag=True, type="mesh"):
                # Include this group as a 'mesh_group' type. Once we find one
                # we will return, as we're taking the simple approach and exporting
                # a single abc for all meshes in the scene.
                items.append(dict(
                    type="mesh_group",
                    name=grp,
                ))

        fl = cmds.renderSettings(firstImageName=True, lastImageName=True)

        # if in shot context check for renders to publish
        if 'assets' not in scene_path.lower() and not fl[1] == '':
            # we'll use the engine to get the templates
            engine = current_engine()

            # get the "maya_shot_work" template to grab some info from the current
            # work file. get_fields will pull out the version number for us.
            work_template = engine.tank.templates.get("maya_shot_work")
            work_template_fields = work_template.get_fields(scene_name)
            version = work_template_fields["version"]

            # now grab the render template to match against.
            render_template = engine.tank.templates.get("maya_shot_render")

            fields = {
                'Sequence': work_template_fields['Sequence'],
                'Shot': work_template_fields['Shot'],
                'Step': work_template_fields['Step'],
                'name': work_template_fields['name'],
                'version': work_template_fields['version']
            }

            # match existing paths against the render template
            paths = engine.tank.abstract_paths_from_template(
                render_template, fields)

            # no render sequence found
            if paths == []:
                return items

            try:
                fl0_split = fl[0].split('.')
                ren_start = int(fl0_split[len(fl0_split) - 2])
                frame_padding = len(fl0_split[len(fl0_split) - 2])
                frame_path = re.sub(r'%[0-9]+d',
                                    str(ren_start).zfill(frame_padding),
                                    paths[0])
                # print "<debug>", frame_path
            except:
                # print "<debug>", paths
                # print "<debug>", fl
                raise TankError(
                    "Problem with naming convention of render. Render naming convention {name}.{version}.{SEQ}.exr"
                )

            # if there's a match, add an item to the render
            if os.path.exists(frame_path):
                render_name = os.path.basename(paths[0])
                fl1_split = fl[1].split('.')
                ren_end = int(fl1_split[len(fl1_split) - 2])

                items.append({
                    "type": "rendered_image",
                    "name": render_name,

                    # since we already know the path, pass it along for
                    # publish hook to use
                    "other_params": {
                        'path': paths[0],
                        'start': ren_start,
                        'end': ren_end,
                        'fr_padding': frame_padding
                    }
                })

        return items
Example #33
0
	def render(self):
		"""docstring for render"""
		curFile = mfl.currentFile()
		if self.autoSave_chb.isChecked():
			curFile.newVersion()
			curFile.save()
		dead       = dl.Deadline()
		group      = str(self.groups_cmb.currentText())
		pool       = str(self.pools_cmb.currentText())
		comments   = str( self.comments_te.text())
		priority   = str( self.priority_spb.value() )
		taskSize   = str( self.taskSize_spb.value() )
		projPath   = str( self.projectPath_le.text() )
		settings = sti.Settings()
		gen = settings.General
		if self.useServerPaths_chb.isChecked(): #IF USE PATH FROM SERVER... WE NEED TO CHANGE INTERNAL PATHS SO MATCH SERVER
			curFile = mfl.mayaFile( curFile.copy( dead.userHomeDirectory + '/' + curFile.fullName ).path )
			if gen:
				basePath = gen[ "basepath" ]
				if basePath:
					if basePath.endswith( '\\' ):
						basePath = basePath[:-1]
					basePath = basePath.replace( '\\', '/' )
				serverPath = gen[ "serverpath" ]
				curFile.changePathsBrutForce( srchAndRep =  [ basePath, serverPath ] )

		#fix for xgen =)
		curFile.changeXgens( newDir = curFile.dirPath )
		InitialStatus = "Active"
		if self.submitSuspended_chb.isChecked():
			InitialStatus = "Suspended"
		whiteList = ''
		deRenGlob = mn.Node( 'defaultRenderGlobals' )
		pad = deRenGlob.a.extensionPadding.v
		#deRenGlob.a.imageFilePrefix.v = str(self.filePath_le.text())
		if self.renderLocal_chb.isChecked():
			whiteList = socket.gethostname()
			print 'rendering in local', whiteList
		plugin = 'MayaBatch'
		if mc.getAttr( "defaultRenderGlobals.ren" ) == 'mentalRay':
			plugin = 'MayaCmd'
		#MAIL
		mails = ''
		mailNoti = 'false'
		if gen[ "sendmail" ] == 'True':
			mails = ','.join( ml.getUsersInDepartments( ['lighting', 'production'], gen[ "departmentspath" ] ) )
			mailNoti = 'true'
		for w in self._getLayersWidgets():
			filePrefix = self.getFilePrefixFromTags( str(self.filePath_le.text()), self.assOrShot )
			frames   = str(self.frameRange_le.text())
			if not w.renderMe_chb.isChecked():
				continue
			if w.overFrameRange_chb.isChecked():
				frames =  str( w.frameRange_le.text() )
			filename = mc.renderSettings( lyr = w.layer.name, gin = ('?'*pad) )[0]
			print filename
			if not mc.getAttr( "defaultRenderGlobals.ren" ) == 'mentalRay':
				filePrefix = filePrefix.replace( '<RenderLayer>', w.layer.name.replace( ':', '_' ) )
				#get version number
				if '<RenderLayerVersion>' in filePrefix:
					versionNumber = self._getVersionNumber( filePrefix.split( '<RenderLayerVersion>' )[0] )
					filePrefix = filePrefix.replace( '<RenderLayerVersion>', 'v' + str(versionNumber).zfill( 4 ) )
				filename = filePrefix + '.' + ('?'*pad) + os.path.splitext( filename )[1]
			print 'RENDERING', filename, w.layer.name
			#filename = filename.replace( ':', '_' )
			name = ''
			if self._project:
				name = self._project + ' - '
			Job = dl.Job( w.layer.name.replace( ':', '_' ),
					{		'Plugin'          : plugin,
							'Group'           : group,
							'Pool'            : pool,
							'Frames'          : frames,
							'Comment'         : comments,
							'InitialStatus'   : InitialStatus,
							'UserName'        : os.getenv('username'),
							'Whitelist'       : whiteList,
							'Name'            : name + curFile.name + ' - ' + w.layer.name,
							'OutputFilename0' : filename,
							'Priority'        : priority,
							'ChunkSize'       : taskSize,
							'OutputDirectory0': filename,
							'NotificationEmails': mails,
							'OverrideNotificationMethod': 'true',
							'EmailNotification': mailNoti
							},{'CommandLineOptions' : '-rl ' + w.layer.name + ' -mr:art ',
								'UsingRenderLayers' : 1,
								#'ProjectPath'       : projPath,
								'RenderLayer'       : w.layer.name,
								'OutputFilePrefix'  : filePrefix,
								'OutputPath'        : filename
							}, curFile )
			Job.write()
			dead.runMayaJob( Job )
Example #34
0
	def imageFilePath(self): return  ''.join(mc.renderSettings(fin=1,lut=1,fp=1))#PROJECT/IMAGES/masterLayer/<RenderPass>/masterLayer.0001.png
	def outputLayers(self): return self.renderOutput()[0]
def get_renderer_variables(renderlayer, root):
    """Retrieve the extension which has been set in the VRay settings.

    Will return None if the current renderer is not VRay
    For Maya 2016.5 and up the renderSetup creates renderSetupLayer node which
    start with `rs`. Use the actual node name, do NOT use the `nice name`

    Args:
        renderlayer (str): the node name of the renderlayer.
        root (str): base path to render

    Returns:
        dict

    """
    renderer = lib.get_renderer(renderlayer or lib.get_current_renderlayer())
    render_attrs = lib.RENDER_ATTRS.get(renderer, lib.RENDER_ATTRS["default"])

    padding = cmds.getAttr("{}.{}".format(render_attrs["node"],
                                          render_attrs["padding"]))

    filename_0 = cmds.renderSettings(fullPath=True,
                                     gin="#" * int(padding),
                                     lut=True,
                                     layer=renderlayer
                                     or lib.get_current_renderlayer())[0]
    filename_0 = re.sub('_<RenderPass>',
                        '_beauty',
                        filename_0,
                        flags=re.IGNORECASE)
    prefix_attr = "defaultRenderGlobals.imageFilePrefix"
    if renderer == "vray":
        renderlayer = renderlayer.split("_")[-1]
        # Maya's renderSettings function does not return V-Ray file extension
        # so we get the extension from vraySettings
        extension = cmds.getAttr("vraySettings.imageFormatStr")

        # When V-Ray image format has not been switched once from default .png
        # the getAttr command above returns None. As such we explicitly set
        # it to `.png`
        if extension is None:
            extension = "png"

        if extension == "exr (multichannel)" or extension == "exr (deep)":
            extension = "exr"

        prefix_attr = "vraySettings.fileNamePrefix"
        filename_prefix = cmds.getAttr(prefix_attr)
        # we need to determine path for vray as maya `renderSettings` query
        # does not work for vray.
        scene = cmds.file(query=True, sceneName=True)
        scene, _ = os.path.splitext(os.path.basename(scene))
        filename_0 = re.sub('<Scene>',
                            scene,
                            filename_prefix,
                            flags=re.IGNORECASE)  # noqa: E501
        filename_0 = re.sub('<Layer>',
                            renderlayer,
                            filename_0,
                            flags=re.IGNORECASE)  # noqa: E501
        filename_0 = "{}.{}.{}".format(filename_0, "#" * int(padding),
                                       extension)
        filename_0 = os.path.normpath(os.path.join(root, filename_0))
    elif renderer == "renderman":
        prefix_attr = "rmanGlobals.imageFileFormat"
    elif renderer == "redshift":
        # mapping redshift extension dropdown values to strings
        ext_mapping = ["iff", "exr", "tif", "png", "tga", "jpg"]
        extension = ext_mapping[cmds.getAttr("redshiftOptions.imageFormat")]
    else:
        # Get the extension, getAttr defaultRenderGlobals.imageFormat
        # returns an index number.
        filename_base = os.path.basename(filename_0)
        extension = os.path.splitext(filename_base)[-1].strip(".")

    filename_prefix = cmds.getAttr(prefix_attr)
    return {
        "ext": extension,
        "filename_prefix": filename_prefix,
        "padding": padding,
        "filename_0": filename_0
    }
Example #36
0
def QuantituRender_zwz(eachL):
    try:
        mc.deleteUI("hyperShadePanel1Window")
    except:
        pass
    #for eachL in fileLists:
    #读取工程目录名字
    inPlayoption = fixFrameList_zwz[eachL][4]
    inshowoption = fixFrameList_zwz[eachL][5]
    mayaversions = mc.about(v=True)
    if mayaversions.find('2009') >= 0:
        tmp = mc.workspace("images", query=True, renderTypeEntry=True)
    else:
        tmp = mc.workspace("images", query=True, fileRuleEntry=True)
    fullPath = mc.workspace(expandName=tmp)
    FramePadding = mc.getAttr("defaultRenderGlobals.extensionPadding")
    try:
        mm.eval("RenderViewWindow;")
    except:
        pass
    mm.eval('setNamedPanelLayout "Single Perspective View"; updateToolbox();')
    myactivePlane = ''
    i = 1
    while (i):
        try:
            tmp = mc.modelEditor('modelPanel%d' % i, q=True, av=True)
        except:
            pass
        else:
            if tmp:
                myactivePlane = 'modelPanel%d' % i
                break
        i += 1
    if inshowoption == 1:
        mc.modelEditor(myactivePlane, e=True, allObjects=False)

    mc.setAttr("defaultRenderGlobals.imageFilePrefix",
               "<Scene>/<RenderLayer>/<Camera>/<Camera>",
               type="string")
    #读取渲染层,摄像机
    myAllCameras = []
    myOkCameras = []
    AllCameras = mc.listCameras(p=True)
    temp = fixFrameList_zwz[eachL][2]
    tempG = temp.split(' ')
    for tmp in tempG:
        if tmp:
            myAllCameras.append(tmp)
    for each in myAllCameras:
        if each in AllCameras:
            myOkCameras.append(each)

    myOkLayer = ''
    myLayer = u'%s' % fixFrameList_zwz[eachL][1]
    myLayer = myLayer.strip()
    if myLayer == 'masterLayer':
        myOkLayer = 'defaultRenderLayer'
    else:
        allLayers = mc.listConnections('renderLayerManager.renderLayerId')
        if myLayer in allLayers:
            myOkLayer = myLayer
    #读取渲染帧数组:

    temp = mc.getAttr('defaultRenderGlobals.currentRenderer')
    mc.setAttr('defaultRenderGlobals.currentRenderer', temp, type='string')

    #设置渲染为当前层
    currentRenderLayer = mc.editRenderLayerGlobals(query=True,
                                                   currentRenderLayer=True)
    if currentRenderLayer != myOkLayer:
        mc.editRenderLayerGlobals(currentRenderLayer=myLayer)
    StartFrame = EndFrame = 0
    StartFrame = int(mc.getAttr("defaultRenderGlobals.startFrame"))
    EndFrame = int(mc.getAttr("defaultRenderGlobals.endFrame"))
    mc.currentTime(StartFrame, update=True)
    mc.pause(sec=3)

    LayerType = mc.getAttr('defaultRenderGlobals.currentRenderer')
    if LayerType.find('vray') >= 0 or LayerType.find('arnold') >= 0:
        sys.stdout.write('%s can`t Render;\n' % LayerType)
        return

    imagePath = mc.renderSettings(firstImageName=True)[0]
    Layerpath = imagePath.split('/')
    myLayerName = '/'.join(Layerpath[:2])
    mytypeName = imagePath.split('.')[-1]
    mytypeV = 0
    if mytypeName.find('iff') >= 0:
        mytypeV = 1
    elif mytypeName.find('tif') >= 0:
        mytypeV = 2
    elif mytypeName.find('png') >= 0:
        mytypeV = 3

    myOkFrames = fixFrameList_zwz[eachL][3]
    lenOkFreames = len(myOkFrames)
    mc.progressWindow(title=u'渲染层:%s' % myOkLayer,
                      progress=0,
                      status=u'即将开始',
                      min=0,
                      max=lenOkFreames,
                      isInterruptable=True)
    i = 0
    for myFrames in myOkFrames:
        i += 1
        if str(type(myFrames)).find('int') >= 0:
            StartFrame = myFrames
            EndFrame = myFrames
        else:
            myListFrames = myFrames.split('-')
            StartFrame = int(myListFrames[0])
            EndFrame = int(myListFrames[1])
        while (StartFrame < EndFrame + 1):
            mc.currentTime(StartFrame, update=True)
            for myCamera in myOkCameras:
                finallyPath = (fullPath + '/' + myLayerName + '/%s/%s.' %
                               (myCamera, myCamera) +
                               str(StartFrame).zfill(FramePadding) + '.' +
                               mytypeName)
                if inPlayoption == 1:
                    mc.lookThru(myCamera, myactivePlane)
                    mc.currentTime(StartFrame, update=True)
                mm.eval('updateModelPanelBar %s;' % myactivePlane)
                mm.eval('renderWindowRenderCamera render renderView "%s";' %
                        myCamera)
                mc.progressWindow(edit=True,
                                  progress=i,
                                  status=u"帧数包:\" %s \"  第  %s  帧  \n摄像机:%s" %
                                  (myFrames, StartFrame, myCamera))
                if mc.progressWindow(q=True,
                                     isCancelled=True) or mc.progressWindow(
                                         q=True, progress=True) > EndFrame + 1:
                    mc.progressWindow(endProgress=True)
                    return False
                mc.setAttr('defaultRenderGlobals.imfkey', "", type="string")
                if mc.file(finallyPath, q=True, exists=True):
                    mc.sysFile(finallyPath, delete=True)
                if mytypeV == 1:
                    mm.eval(
                        'renderWindowSaveImageCallback "renderView" "%s" "Maya IFF";'
                        % finallyPath)
                elif mytypeV == 2:
                    mm.eval(
                        'renderWindowSaveImageCallback "renderView" "%s" "Tiff";'
                        % finallyPath)
                elif mytypeV == 3:
                    mm.eval(
                        'renderWindowSaveImageCallback "renderView" "%s" "PNG";'
                        % finallyPath)
                sys.stdout.write(
                    "RenerLayer: %s  / Camera: %s  / Frame: %s\n" %
                    (myOkLayer, myCamera, StartFrame))
            StartFrame += 1
    mc.progressWindow(endProgress=True)
    return True