예제 #1
0
파일: notify.py 프로젝트: tws0002/Nuke-2
def throtted_warning(msg):
    """Only show each warning message once.  """

    msg = u(msg)
    if msg not in SHOWED_WARNING:
        nuke.warning(utf8(msg))
        SHOWED_WARNING.append(msg)
예제 #2
0
def multiple_contexts(contexts):
    """
    Given a list of contextmanagers, sequentially enter all contextmanagers,
    raise :class:`Exception` in case errors occur in contexts.

    **Deprecated**. Use :func:`contextlib.nested(*contexts)`.

    :param contexts: List of contextmanagers
    :type contexts: list
    """
    msg = ('nukecontexts.ctx.multiple_contexts() is deprecated. '
           'Use contextlib.nested(*contexts)')
    nuke.warning(msg)

    for ctx in contexts:
        ctx.__enter__()

    err = None
    exc_info = (None, None, None)
    try:
        yield
    except Exception as err:
        exc_info = sys.exc_info()

    # exc_info gets passed to each subsequent ctx.__exit__
    # unless one of them suppresses the exception by returning True
    for ctx in reversed(contexts):
        if ctx.__exit__(*exc_info):
            err = False
            exc_info = (None, None, None)
    if err:
        raise err
예제 #3
0
def collect_node(node_tuple, collect_folder_path):
    node = node_tuple[0]
    knob_name = node_tuple[1]
    if is_node_class_of(node, "Read", "DeepRead"):
        collect_read_node(node, collect_folder_path)
        return
    if is_node_class_of(node, "Write", "DeepWrite"):
        collect_write_node(node, collect_folder_path)
        return
    if node[knob_name].value() == "":
        return
    file_name_full_path = get_abs_path(node[knob_name].value())
    folder_name = node["name"].getValue()
    file_name_with_ext = os.path.split(file_name_full_path)[1]

    if is_sequence_filename(file_name_with_ext):
        footage_folder_path = make_folder(os.path.join(collect_folder_path, folder_name))
        dst_file_path_value = copy_files(file_name_full_path, footage_folder_path, folder_name)
        if dst_file_path_value:
            node[knob_name].setValue(get_rel_path(dst_file_path_value))
        return
    else:
        if os.path.isdir(file_name_full_path):
            nuke.warning(file_name_with_ext + " is directory")
        elif os.path.lexists(file_name_full_path):
            footage_folder_path = make_folder(os.path.join(collect_folder_path, folder_name))
            shutil.copy(file_name_full_path, footage_folder_path)
            dst_file_path_value = os.path.join(footage_folder_path, file_name_with_ext)
            node[knob_name].setValue(get_rel_path(dst_file_path_value))
        else:
            nuke.warning(file_name_with_ext + " is missing")
    return
예제 #4
0
    def _emit_log_message(self, handler, record):
        """
        Emits a log to Nuke's Script Editor and Error Console.

        :param handler: Log handler that this message was dispatched from
        :type handler: :class:`~python.logging.LogHandler`
        :param record: Std python logging record
        :type record: :class:`~python.logging.LogRecord`
        """
        msg = handler.format(record)

        # Sends the message to error console of the DCC
        if self.hiero_enabled:
            import hiero
            if record.levelno >= logging.ERROR:
                hiero.core.log.error(msg)
            elif record.levelno >= logging.WARNING:
                hiero.core.log.info(msg)
            elif record.levelno >= logging.INFO:
                hiero.core.log.info(msg)
            else:
                hiero.core.log.setLogLevel(hiero.core.log.kDebug)
                hiero.core.log.debug(msg)
        else:
            if record.levelno >= logging.CRITICAL:
                nuke.critical("Shotgun Critical: %s" % msg)
            elif record.levelno >= logging.ERROR:
                nuke.error("Shotgun Error: %s" % msg)
            elif record.levelno >= logging.WARNING:
                nuke.warning("Shotgun Warning: %s" % msg)

        # Sends the message to the script editor.
        print msg
예제 #5
0
def bootstrap_tank():

    try:
        import tank
    except Exception, e:
        nuke.warning("Shotgun: Could not import sgtk! Disabling for now: %s" % e)
        return
예제 #6
0
파일: footage.py 프로젝트: tws0002/Nuke-2
    def _update_missing_frame(self):
        ret = FrameRanges([])
        checked = set()
        frames = self.frame_ranges.toFrameList()

        def _check(frame):
            try:
                path = Path(self.filename.with_frame(frame))
                if path in checked:
                    return
                if not path.is_file():
                    ret.add([frame])
                checked.add(path)
            except OSError as ex:
                LOGGER.error(os.strerror(ex.errno), exc_info=True)

        pool = multiprocessing.Pool()
        pool.map(_check, frames)
        pool.close()
        pool.join()

        ret.compact()
        self._missing_frames = CachedMissingFrames(ret, time.time())
        if ret:
            msg = '{} 缺帧: {}'.format(self, ret)
            nuke.warning(utf8(msg))
        return ret
예제 #7
0
def main():
    images = nuke.getFilename("Select Images",
                              '*.png *.jpg *.jpeg',
                              multiple=True)

    length = len(images)
    if length < 2:
        nuke.warning("At least 2 images required to create the effect")
        nuke.message("At least 2 images required to create the effect")
        return

    merge = manipulate_node(images[0], 0)
    i = 1

    while i < length:
        node = manipulate_node(images[i], i)
        merge = nuke.nodes.Merge(inputs=[merge, node])
        i += 1

    # A generic touch to make it similar to the original one,
    # a trick which really makes difference, have to play with
    # the shutter samples for more accuracy
    motionblur = nuke.nodes.MotionBlur()
    motionblur.setInput(0, merge)

    # For keeping track of the nodegraph if you have too many pictures
    motionblur.setSelected(True)
예제 #8
0
def add_driver(knobtype):
	"""Add a set driver knobs
	@knobtype: (str) Nuke Knob Type
	"""
	try:	
		dr_no = int(max([find_digit(k) for k in nuke.thisNode().knobs() if k.startswith('dr')]) + 1)
	except Exception as e:
		nuke.warning(e)
		dr_no = 0

	label = nuke.getInput('Label this Driver')	
	if label: 
		k_this_name = 'dr%02d_%s' % (dr_no, label)
		k_this = eval("nuke.{}('')".format(knobtype))
		k_this.setName(k_this_name)
		k_this.setLabel(label)
		k_this.setFlag(nuke.STARTLINE)

		k_set_driven = nuke.PyScript_Knob('dr%02ddriven' % dr_no, STR_SETDRIVEN)
		k_set_driven.setCommand(STR_CMD_SETUP.format("set_driven('%s')" % k_this_name))
		k_set_driven.setTooltip(k_this_name)
		k_set_driven.clearFlag(nuke.STARTLINE)
		k_list_driven = nuke.PyScript_Knob('dr%02dlist' % dr_no, STR_LISTDRIVEN)
		k_list_driven.clearFlag(nuke.STARTLINE)
		k_list_driven.setCommand(STR_CMD_SETUP.format("show_list_driven('%s')" % k_this_name))
		k_list_driven.setTooltip(k_this_name)

		n = nuke.thisNode()
		n.addKnob(k_this)
		n.addKnob(k_set_driven)
		n.addKnob(k_list_driven)
예제 #9
0
 def log_warning(self, msg):
     msg = "Shotgun Warning: %s" % msg
     # We will log it via the API, as well as print normally,
     # which should make its way to the scripting console.
     if self.hiero_enabled:
         import hiero
         hiero.core.log.info(msg)
     else:
         nuke.warning(msg)
     print msg
예제 #10
0
def _restore_overrides(overrides):
    for item, key in overrides.items():
        menu_name, _, path = item.partition("/")
        m = nuke.menu(menu_name)
        item = m.findItem(path)
        if item is None:
            nuke.warning("WARNING: %r (menu: %r) does not exist?" %
                         (path, menu_name))
        else:
            item.setShortcut(key)
예제 #11
0
 def log_warning(self, msg):
     msg = "Shotgun Warning: %s" % msg
     # We will log it via the API, as well as print normally,
     # which should make its way to the scripting console.
     if self.hiero_enabled:
         import hiero
         hiero.core.log.info(msg)
     else:
         nuke.warning(msg)
     print msg
예제 #12
0
    def emit(self, record):

        # Formated message:
        msg = self.format(record)

        if record.funcName == "warning":
            nuke.warning(msg)

        elif record.funcName in ["critical", "fatal"]:
            nuke.error(msg)
            nuke.message(record.message)

        else:
            sys.stdout.write(msg)
 def importCameraData(self, *args):
     fileLocation = nuke.getFilename('Import kCamera', '*.kCamera')
     
     try:
         f = open(fileLocation, 'rb')
     except TypeError:
         nuke.warning("No file selected..")
         return
     
     kCamData = []
     
     for i in range(2):
         kCamData.append(cPickle.load(f))
     f.close()    
     
     self.buildCamera(kCamData)
예제 #14
0
def KuViewer(mode='restore'):
    '''set and restore viewer input pipes with options
	mode='restore': restore set inputs
	mode='set': record exsisting inputs
	'''

    nuke_pref_check()

    node_viewer = nuke.activeViewer().node()
    node_viewer.setName('KuViewer')
    data_knob = None

    if PREF_NODE[PREF_NAME].value() == "Viewer Label":
        data_knob = node_viewer.knob('label')
        LOG.debug("Pref: Viewer Label")
    elif PREF_NODE[PREF_NAME].value() == "StickyNote Node":
        sticky_node = nuke.toNode("KuViewerInputs")
        if not sticky_node:
            sticky_node = nuke.createNode("StickyNote", "name KuViewerInputs")
        data_knob = sticky_node.knob('label')
        LOG.debug("Pref: StickyNote")
    else:
        nuke.warning("Preferences 'viewerinputs' value note valide")
        LOG.warning("No data_knob found")

    if data_knob:
        if mode == 'set':
            num_inputs = node_viewer.inputs()
            data = ''
            for i in range(num_inputs):
                node_thisInput = node_viewer.input(
                    i).name() if node_viewer.input(i) else None
                data += "%s:%s\n" % (i + 1, node_thisInput)
            data_knob.setValue(data)
            LOG.debug("Set Viewer Inputs")

        if mode == 'restore':
            data = data_knob.value()
            ls_restore = [i.split(':') for i in data.split('\n')[:-1]]

            for n in ls_restore:
                node_viewer.setInput(int(n[0]) - 1, nuke.toNode(n[1]))
                LOG.info("%s:%s" % (n[0], n[1]))
예제 #15
0
    def restore(self):
        """Load the settings from disc, and update Nuke
        """
        settings = _load_yaml(path=self.settings_path)

        # Default
        self.overrides = {}

        if settings is None:
            return

        elif int(settings['version']) == 1:
            self.overrides = settings['overrides']
            _restore_overrides(self.overrides)

        else:
            nuke.warning(
                "Wrong version of shortcut, nothing loaded (version was %s expected 1), path was %r"
                % (int(settings['version']), self.settings_path))
            return
예제 #16
0
def bootstrap_tank():

    try:
        import tank
    except Exception as e:
        nuke.warning("Shotgun: Could not import sgtk! Disabling for now: %s" %
                     e)
        return

    if not "TANK_ENGINE" in os.environ:
        # key environment missing. This is usually when someone has done a file->new
        # and this menu.py is triggered but the env vars have been removed
        # because the boot strap is handled by the engine's callback system
        # rather than this startup script.
        return

    engine_name = os.environ.get("TANK_ENGINE")
    try:
        context = tank.context.deserialize(os.environ.get("TANK_CONTEXT"))
    except Exception as e:
        nuke.warning(
            "Shotgun: Could not create context! Shotgun Pipeline Toolkit will be disabled. Details: %s"
            % e)
        return

    try:
        engine = tank.platform.start_engine(engine_name, context.tank, context)
    except Exception as e:
        nuke.warning("Shotgun: Could not start engine: %s" % e)
        return

    # clean up temp env vars
    for var in ["TANK_ENGINE", "TANK_CONTEXT", "TANK_FILE_TO_OPEN"]:
        if var in os.environ:
            del os.environ[var]
예제 #17
0
def selectLogoRender(tricode):
    # figure out which project this scene is in
    proj_name = getProject()
    logo_path = cfb.ANIMATION_PROJECT_DIR + proj_name + "/render_3d/LOGOS/" + tricode + "/"

    for r in logo_read_nodes:
        pass_path = ""
        try:
            # get the read node
            rn = nuke.toNode(r)
            # figure out the file names on this node
            pass_path = rn.knob('file').getValue().split('/')
            if len(pass_path) == 1:
                pass_path = rn.knob('file').getValue().split('/')
            # getting layerName/layerName.#.ext
            pass_path = pass_path[len(pass_path) -
                                  2] + "/" + pass_path[len(pass_path) - 1]
            # replace the path prefix with the correct project/team logo version
            rn.knob('file').setValue(logo_path + pass_path)
            #print logo_path + pass_path
        except:
            nuke.warning('Error finding replacement for: ' + r)
예제 #18
0
def readSelected():
    node = None

    try:
        node = nuke.selectedNode()
    except ValueError:
        nuke.warning('Please select a node')
        return

    if not node:
        nuke.warning('Please select a node')
        return

    if node.Class() != 'Write':
        nuke.warning('Must select a Write node')
        return

    fp = node.knob('file').getValue()
    read = nuke.nodes.Read()

    read.knob('file').setValue(fp)

    nuke.activeViewer().node().setInput(0, read)
예제 #19
0
    except Exception, e:
        nuke.warning("Shotgun: Could not import sgtk! Disabling for now: %s" % e)
        return
    
    if not "TANK_ENGINE" in os.environ:
        # key environment missing. This is usually when someone has done a file->new
        # and this menu.py is triggered but the env vars have been removed
        # because the boot strap is handled by the engine's callback system
        # rather than this startup script.
        return
    
    engine_name = os.environ.get("TANK_ENGINE")
    try:
        context = tank.context.deserialize(os.environ.get("TANK_CONTEXT"))
    except Exception, e:
        nuke.warning("Shotgun: Could not create context! Shotgun Pipeline Toolkit will be disabled. Details: %s" % e)
        return

    try:    
        engine = tank.platform.start_engine(engine_name, context.tank, context)
    except Exception, e:
        nuke.warning("Shotgun: Could not start engine: %s" % e)
        return
    
    # clean up temp env vars
    for var in ["TANK_ENGINE", "TANK_CONTEXT", "TANK_FILE_TO_OPEN"]:
        if var in os.environ:
            del os.environ[var]


bootstrap_tank()
예제 #20
0
 def log_warning(self, msg):
     msg = "Shotgun Warning: %s" % msg
     # print it in the nuke error console
     nuke.warning(msg)
     # also print it in the nuke script console
     print msg
예제 #21
0
    def createThumbnail(self, useCursorPosition=False, dbPath = None, versionInt = None):
        """
        Creates the thumbnail file.
        :param databaseDir: (String) If defined, this folder will be used to store the created database.
        :param version: (integer) if defined this version number will be used instead currently open scene version.
        :return: (String) Relative path of the thumbnail file
        """
        logger.debug("Func: createThumbnail")
        projectPath = self.projectDir
        if useCursorPosition:
            versionInt = self.currentVersionIndex
            dbPath = self.currentDatabasePath
        else:
            if not dbPath or not versionInt:
                msg = "Both dbPath and version must be defined if useCursorPosition=False"
                raise Exception ([360, msg])

        versionStr = "v%s" % (str(versionInt).zfill(3))
        dbDir, shotNameWithExt = os.path.split(dbPath)
        shotName = os.path.splitext(shotNameWithExt)[0]

        thumbPath = "{0}_{1}_thumb.jpg".format(os.path.join(dbDir, shotName), versionStr)
        relThumbPath = os.path.relpath(thumbPath, projectPath)

        # create a thumbnail
        thumbDir = os.path.split(thumbPath)[0]
        try:
            #############################################
            # get the node attached to the current viewer
            activeNode = nuke.activeViewer().node().input(0)

            # create reformat node
            reformatNode = nuke.createNode("Reformat")
            reformatNode["type"].setValue(1)
            reformatNode["box_fixed"].setValue(1)
            reformatNode["box_width"].setValue(221)
            reformatNode["box_height"].setValue(124)
            reformatNode["black_outside"].setValue(1)
            reformatNode.setInput(0, activeNode)

            # create a write node
            writeNode = nuke.createNode("Write")
            writeNode.setName("tik_tempWrite")
            writeNode['file'].setValue(thumbPath.replace("\\", "/"))
            writeNode["use_limit"].setValue(True)
            frame = self._getCurrentFrame()
            writeNode['first'].setValue(frame)
            writeNode['last'].setValue(frame)
            # writeNode['_jpeg_quality'].setValue(1)
            # writeNode['_jpeg_sub_sampling'].setValue(2)

            # execute & cleanup
            nuke.execute(writeNode, frame, frame)
            nuke.delete(writeNode)
            nuke.delete(reformatNode)
            ####################################################


            # # frame = pm.currentTime(query=True)
            # frame = cmds.currentTime(query=True)
            # # store = pm.getAttr("defaultRenderGlobals.imageFormat")
            # store = cmds.getAttr("defaultRenderGlobals.imageFormat")
            # # pm.setAttr("defaultRenderGlobals.imageFormat", 8)  # This is the value for jpeg
            # cmds.setAttr("defaultRenderGlobals.imageFormat", 8)  # This is the value for jpeg
            # # pm.playblast(completeFilename=thumbPath, forceOverwrite=True, format='image', width=221, height=124, showOrnaments=False, frame=[frame], viewer=False, percent=100)
            # cmds.playblast(completeFilename=thumbPath, forceOverwrite=True, format='image', width=221, height=124, showOrnaments=False, frame=[frame], viewer=False, percent=100)
            # # pm.setAttr("defaultRenderGlobals.imageFormat", store) #take it back
            # cmds.setAttr("defaultRenderGlobals.imageFormat", store) #take it back
        except:
            # pm.warning("something went wrong with thumbnail. Skipping thumbnail")
            nuke.warning("something went wrong with thumbnail. Skipping thumbnail")
            return ""
        # return thumbPath
        return relThumbPath



        #############################################
        # get the node attached to the current viewer
        activeNode = nuke.activeViewer().node().input(0)

        # create a write node
        writeNode = nuke.createNode("Write")
        writeNode.setName("tik_tempWrite")
        writeNode['file'].setValue("TEST.jpg")
        # writeNode['_jpeg_quality'].setValue(1)
        # writeNode['_jpeg_sub_sampling'].setValue(2)
        r = nuke.createNode("Reformat")

        # create reformat node
        reformatNode = nuke.createNode("Reformat")
        reformatNode["type"].setValue(1)
        reformatNode["box_width"].setValue(123)
        reformatNode["box_height"].setValue(123)
        reformatNode["black_outside"].setValue(1)
        reformatNode["box_fixed"].setValue(1)

        # make Connections
        writeNode.setInput(0, reformatNode)
        reformatNode.setInput(0, activeNode)
예제 #22
0
 def log_warning(self, msg):
     msg = "Shotgun Warning: %s" % msg
     # print it in the nuke error console
     nuke.warning(msg)
     # also print it in the nuke script console
     print msg
예제 #23
0
def splitAOVs():
    node = None

    try:
        node = nuke.selectedNode()
    except ValueError:
        nuke.warning('Please select a node')
        return

    if not node:
        nuke.warning('Please select a node')
        return

    if node.Class() != 'Read':
        nuke.warning('Must select a Read node')
        return

    dialog = AOVSplitterDialog(node)

    ret = dialog.exec_()

    return

    if ret != QDialog.Accepted:
        return

    channels = list(set([c.split('.')[0] for c in node.channels()]))
    ignore = ['rgba']
    shuffles = []

    for ch in channels:
        if ch in ignore:
            continue

        shuffle = nuke.nodes.Shuffle(name=ch)

        shuffle.knob('in').setValue(ch)
        shuffle.knob('postage_stamp').setValue(True)
        shuffle.setInput(0, node)

        shuffles.append(shuffle)

    return  # TODO re-implement plus merging

    if shuffles and len(shuffles) >= 2:
        shuf1 = shuffles.pop()
        shuf2 = shuffles.pop()
        merge = nuke.nodes.Merge()

        merge.knob('operation').setValue('plus')

        merge.setInput(0, shuf1)
        merge.setInput(1, shuf2)

        while shuffles:
            newMerge = nuke.nodes.Merge()

            newMerge.knob('operation').setValue('plus')

            newMerge.setInput(0, merge)
            newMerge.setInput(1, shuffles.pop())

            merge = newMerge

        nuke.activeViewer().node().setInput(0, merge)