Exemplo n.º 1
0
def create_time_warp():
    t = nuke.createNode("TimeWarp")
    a = nuke.value(t.name() + ".first_frame")
    e = nuke.value(t.name() + ".last_frame")
    if float(e) <= float(a):
        a = nuke.value("root.first_frame")
        e = nuke.value("root.last_frame")
    cmd = "{curve C x" + a + " " + a + " x" + e + " " + e + "}"
    t.knob("lookup").fromScript(cmd)
Exemplo n.º 2
0
    def _readwrites(blankread, check, threshold, report):

        sn = [n for n in nuke.selectedNodes() if n.Class() == "Write"]

        if sn == [] and blankread == True:
            nuke.createNode("Read", "", True)

        elif sn == [] and blankread == False:
            return None

        elif sn != []:
            for n in sn:

                file = n.knob('file').value()
                proxy = n.knob('proxy').value()
                colorspace = n.knob('colorspace').value()
                premult = n.knob('premultiplied').value()
                rawdata = n.knob('raw').value()
                xpos = n.knob('xpos').value()
                ypos = n.knob('ypos').value()

                firstFrame = nuke.value(n.name() + ".first_frame")
                lastFrame = nuke.value(n.name() + ".last_frame")

                if file == '' and proxy == '':
                    if blankread == True:
                        read = nuke.createNode("Read", "", False)
                        read.knob('xpos').setValue(xpos)
                        read.knob('ypos').setValue(ypos + 80)
                        nuke.inputs(read, 0)
                        continue
                    elif blankread == False:
                        continue

                args = 'file {%s} proxy {%s} first %s last %s colorspace %s premultiplied %s raw %s' % (
                    file, proxy, firstFrame, lastFrame, colorspace, premult,
                    rawdata)

                read = nuke.createNode('Read', args)
                read.knob('xpos').setValue(xpos)
                read.knob('ypos').setValue(ypos + 80)
                nuke.inputs(read, 0)
                if check == True:
                    _checkbadframes(read, report)
                    continue

                else:
                    continue

                return None

        else:
            return None
Exemplo n.º 3
0
def showPopup():

	# Get some Defaults:
	frameStart	= nuke.value('root.first_frame')
	frameEnd	= nuke.value('root.last_frame')

	for node in nuke.selectedNodes():
		try:
			if node["use_limit"].value():
				frameStart	= int(node["first"].value())
				frameEnd	= int(node["last"].value())
		except Exception, e:
			pass
Exemplo n.º 4
0
 def _readwrites(blankread, check, threshold,  report):
     
     sn = [n for n in nuke.selectedNodes() if n.Class() == "Write"]
     
     if sn == [] and blankread == True:
         nuke.createNode("Read", "", True)
         
     elif sn == [] and blankread == False:
         return None
         
     elif sn != []:
         for n in sn:
             
             file = n.knob('file').value()
             proxy = n.knob('proxy').value()
             colorspace = n.knob('colorspace').value()
             premult = n.knob('premultiplied').value()
             rawdata = n.knob('raw').value()
             xpos = n.knob('xpos').value()
             ypos = n.knob('ypos').value()
             
             firstFrame = nuke.value(n.name()+".first_frame")
             lastFrame = nuke.value(n.name()+".last_frame")
             
             if file == '' and proxy == '':
                 if blankread == True:
                     read = nuke.createNode("Read", "", False)
                     read.knob('xpos').setValue(xpos)
                     read.knob('ypos').setValue(ypos + 80)
                     nuke.inputs(read, 0)
                     continue
                 elif blankread == False:
                     continue
             
             args = 'file {%s} proxy {%s} first %s last %s colorspace %s premultiplied %s raw %s' % (file, proxy, firstFrame, lastFrame, colorspace, premult, rawdata)
             
             read = nuke.createNode('Read', args)
             read.knob('xpos').setValue(xpos)
             read.knob('ypos').setValue(ypos + 80)
             nuke.inputs(read, 0)
             if check == True:
                 _checkbadframes(read, report)
                 continue
                 
             else:
                 continue
                 
             return None
             
     else:
         return None 
    def _getOptions(self, nodeToFlipbook):
        options = {}

        try:
            options['pixelAspect'] = float(
                nuke.value(nodeToFlipbook.name() + ".pixel_aspect"))
        except:
            pass

        try:
            f = nodeToFlipbook.format()
            options['dimensions'] = {'width': f.width(), 'height': f.height()}
        except:
            pass

        # LUT
        if not self._burnInLUT.value():
            inputColourspace = "linear"
            outputColourspace = "linear"
            # Check if we have a different than linear input
            if self._node.Class() == "Read" or self._node.Class() == "Write":
                lut = self._node.knob("colorspace").value()
                # Might be in the format of "default (foo)", if so, get at "foo".
                if lut[:7] == "default":
                    lut = lut[9:-1]
                inputColourspace = lut

            # Check our output
            lut = self._getLUT()
            if lut != "None":
                outputColourspace = lut

            if inputColourspace == outputColourspace:
                options["lut"] = inputColourspace
            else:
                options["lut"] = inputColourspace + "-" + outputColourspace
        # AUDIO
        audioTrack = self._getAudio()
        if audioTrack != "":
            options["audio"] = audioTrack

        # ROI
        if self._useRoi.value():
            roi = self._roi.toDict()
            if (roi["r"] - roi["x"] > 0) and (roi["t"] - roi["y"] > 0):
                options["roi"] = bboxToTopLeft(
                    int(
                        nuke.value(nodeToFlipbook.name() +
                                   ".actual_format.height")), roi)

        return options
Exemplo n.º 6
0
 def __init__(self, fileDict, maxThreads=1):
     '''
     Threaded interface for copying files
     fileDict  -  dictionary where key is the name of the sequence (used for progress bar) and value is a list of files to be copied
     '''
     self.fileDict = fileDict
     self.cachePath = nuke.value('preferences.localCachePath')
     self.taskCount = len(self.fileDict)
     self.totalFileCount = sum([len(v) for v in self.fileDict.values()])
     self.progress = 0.0
     self.cachePath = nuke.value('preferences.localCachePath')
     self.finishedThreads = 0
     self.threadLimit = maxThreads
     self.threadLimiter = threading.BoundedSemaphore(self.threadLimit)
Exemplo n.º 7
0
 def __init__(self, fileDict, maxThreads=1):
     '''
     Threaded interface for copying files
     fileDict  -  dictionary where key is the name of the sequence (used for progress bar) and value is a list of files to be copied
     '''
     self.fileDict = fileDict
     self.cachePath = nuke.value('preferences.localCachePath')
     self.taskCount = len(self.fileDict)
     self.totalFileCount = sum([len(v) for v in self.fileDict.values()])
     self.progress = 0.0
     self.cachePath = nuke.value('preferences.localCachePath')
     self.finishedThreads = 0
     self.threadLimit = maxThreads
     self.threadLimiter = threading.BoundedSemaphore(self.threadLimit)
Exemplo n.º 8
0
def _set_filename(n, value):
    try:
        k = (n['file'] if not n['proxy'].value()
             or nuke.value('root.proxy') == 'false' else n['proxy'])
    except NameError:
        k = n['file']
    k.setValue(value.encode('utf-8'))
Exemplo n.º 9
0
def BatScriptRenderFull():
    # Save Script
    nuke.scriptSave()
    # Variables of Script
    nukescript = nuke.value("root.name")
    start = nuke.knob("first_frame")
    end = nuke.knob("last_frame")
    path = nukescript + ".bat"
    # Cmd Message
    nuke.tprint("\nBatScriptRender\nSave Script " + nukescript)
    # Bat File Panel
    swt = ['-x', '-X']
    nfr = ['""', ',2', ',5', ',10', ',15', ',20']
    myPanel = nuke.Panel("BatScriptRender - Parameters", 338)
    myPanel.addSingleLineInput("nuke version: ", "nuke5.1")
    myPanel.addEnumerationPulldown("switches: ", ' '.join(swt))
    myPanel.addSingleLineInput("node: ", "")
    myPanel.addSingleLineInput("script: ", nukescript)
    myPanel.addSingleLineInput("start frame: ", start)
    myPanel.addSingleLineInput("end frame: ", end)
    myPanel.addEnumerationPulldown("every n frame: ", ' '.join(nfr))
    myPanel.addSingleLineInput("file path: ", path)
    myPanel.addButton("Quit")
    myPanel.addButton("Create")
    myPanel.addButton("Execute")
    result = myPanel.show()
    # Add Button's action & Cmd Message
    if result == 0:
        nuke.tprint("Bat File don't Create")
    elif result == 1:
        # Create Bat File
        curVersion = myPanel.value("nuke version: ")
        curSwitches = myPanel.value("switches: ")
        curNode = myPanel.value("node: ")
        curScript = myPanel.value("script: ")
        curStart = myPanel.value("start frame: ")
        curEnd = myPanel.value("end frame: ")
        curEvery = myPanel.value("every n frame: ")
        cmdLine = curVersion + " " + curSwitches + " " + curNode + " " + '"' + curScript + '"' + " " + curStart + "," + curEnd + curEvery
        cmdFile = myPanel.value("file path: ")
        file = open(cmdFile, 'w')
        file.write(cmdLine)
        file.close()
        nuke.tprint("Create Bat File " + cmdFile)
    elif result == 2:
        # Execute Bat File
        curVersion = myPanel.value("nuke version: ")
        curSwitches = myPanel.value("switches: ")
        curNode = myPanel.value("node: ")
        curScript = myPanel.value("script: ")
        curStart = myPanel.value("start frame: ")
        curEnd = myPanel.value("end frame: ")
        curEvery = myPanel.value("every n frame: ")
        cmdLine = curVersion + " " + curSwitches + " " + curNode + " " + '"' + curScript + '"' + " " + curStart + "," + curEnd + curEvery
        cmdFile = myPanel.value("file path: ")
        file = open(cmdFile, 'w')
        file.write(cmdLine)
        file.close()
        os.startfile(cmdFile)
        nuke.tprint("Execute Bat File " + cmdFile)
Exemplo n.º 10
0
def _getAutoLableColorspace():
  """
  returns the colorspace-name string to use on auto-labels
  handles defaults, NUKE vs OCIO modes and NUKE UI.
  """
  csKnob = nuke.thisNode().knob("colorspace")
  if not csKnob :
    return ""
  csId = int(csKnob.getValue())
  if not nuke.usingOcio():
    isDefault = (0 == csId)
    if isDefault :
      # maintaining old behaviour, don't show the colorspace in the autolabel
      # in NUKE colorspace mode
      return ""

  # always show non-empty colorspaces
  colorspace = _stripDefaultStrings( csKnob.values()[csId] )

  if not colorspace:
     # fall back to tcl if we don't have a colorspace
     colorspace = _stripDefaultStrings( nuke.value("colorspace") )

  # strip cascading menus prefix
  colorspace = os.path.basename(colorspace)
  assert colorspace != "."
  return colorspace
Exemplo n.º 11
0
def createArtifact():

    nuke.scriptSave()
    script = nuke.value("root.name")
    filename, file_extension = os.path.splitext(script)
    artef = '{}_artifact.{}'.format(filename, file_extension)
    shutil.copyfile(script, artef)
Exemplo n.º 12
0
def _pyblish_action(name, is_reset=True):

    if nuke.value('root.name', None):
        Window.dock()

    window_ = Window.instance
    assert isinstance(window_, Window)
    controller = window_.controller
    assert isinstance(controller, control.Controller)

    start = getattr(window_, name)
    signal = {'publish': controller.was_published,
              'validate': controller.was_validated}[name]

    finish_event = multiprocessing.Event()
    _after_signal(signal, finish_event.set)

    if is_reset:
        # Run after reset finish.
        _after_signal(controller.was_reset, start)
        window_.reset()
    else:
        # Run directly.
        start()

    # Wait finish.
    while (not finish_event.is_set()
           or controller.is_running):
        QApplication.processEvents()
Exemplo n.º 13
0
 def _with_timoffset(sel):
     
     for n in sel:
         for i in sel:
             n.knob('selected').setValue(False)
         n.knob('selected').setValue(True)
         rt = nuke.createNode('TimeOffset', '', False)
         rt.knob('selected').setValue(False)
         sequencer.append(rt)
         
     for rt in sequencer:
         idx = sequencer.index(rt)
         
         if idx == 0:
             idx = idx
             rt.knob('label').setValue("Cut " + str(idx+1))
             continue
         else:
             idx = idx-1
             offset = float(nuke.value(sequencer[idx].name()+".last_frame"))+1.0
             rt.knob('selected').setValue(True)
             rt.knob('time_offset').setValue(offset)
             rt.knob('label').setValue("Cut " + str(idx+2))
             rt.knob('selected').setValue(False)
             continue
    def _getIntermediatePath(self):
        """Get the path for the temporary files. May be filled in using printf syntax."""
        flipbooktmp = ""
        if flipbooktmp == "":
            try:
                flipbooktmp = self._selectedFlipbook().cacheDir()
            except:
                try:
                    flipbooktmp = os.environ["NUKE_DISK_CACHE"]
                except:
                    flipbooktmp = nuke.value("preferences.DiskCachePath")

        if len(self._selectedViews()) > 1:
            flipbookFileNameTemp = "nuke_tmp_flip.%04d.%V." + self._getIntermediateFileType(
            )
        else:
            flipbookFileNameTemp = "nuke_tmp_flip.%04d." + self._getIntermediateFileType(
            )
        flipbooktmpdir = os.path.join(flipbooktmp, "flipbook")
        if not os.path.exists(flipbooktmpdir):
            os.mkdir(flipbooktmpdir)

        if not os.path.isdir(flipbooktmpdir):
            raise RuntimeError(
                "%s already exists and is not a directory, please delete before flipbooking again"
                % flipbooktmpdir)
        flipbooktmp = os.path.join(flipbooktmpdir, flipbookFileNameTemp)

        if nuke.env['WIN32']:
            flipbooktmp = re.sub(r"\\", "/", str(flipbooktmp))
        return flipbooktmp
Exemplo n.º 15
0
def load_read():

    import nuke
    from variables import *
    import os

    nuke_script_path = os.path.abspath(nuke.value("root.name"))

    if not project_name in nuke_script_path.split('\\'):
        raise ValueError('You are not working in the project !')

    vars = nuke_script_path.split('\\')
    vars.remove('compo')
    vars.remove('compo.nk')
    vars.append('master')
    render_dir = '/'.join(vars)
    print(render_dir)
    out_name = 'out_Layer_####.exr'

    render_out = render_dir + '/' + out_name

    read_node = nuke.nodes.Read(file=render_out)

    for channel in channels:
        sh_node = nuke.nodes.Shuffle()
        sh_node.connectInput(0, read_node)
        sh_node.setName(channel)
        sh_node.knob('postage_stamp').setValue(True)
        sh_node.knob('in').setValue(channel)
Exemplo n.º 16
0
    def __init__ (self, sessionDirBase) :
        """
        RV Settings object
        """
        self.settings = {}

        scriptBase = string.join(os.path.basename(nuke.root().name()).split(".")[:-1], ".")

        baseDir = sessionDirBase

        if (not baseDir) :
            baseDir = os.getenv("NUKE_TEMP_DIR")
        if (not baseDir) :
            baseDir = nuke.value("preferences.DiskCachePath")

        self.settings["sessionDir"] = baseDir + "/RvDir/" + scriptBase

        self.settings["outputFileFormat"] = "rgb"
        self.settings["syncSelection"] = True
        self.settings["syncFrameChange"] = True
        self.settings["syncReadChanges"] = True

        #
        #  Override defaults with stored settings
        #
        
        self.updateFromRoot()
Exemplo n.º 17
0
 def process(self, instance):
     filename = instance.data['name']
     if nuke.numvalue('preferences.wlf_send_to_dir', 0.0):
         render_dir = u(nuke.value('preferences.wlf_render_dir'))
         copy(filename, render_dir + '/')
     else:
         self.log.info('因为首选项设置而跳过')
Exemplo n.º 18
0
    def __init__(self, sessionDirBase):
        """
        RV Settings object
        """
        self.settings = {}

        scriptBase = string.join(
            os.path.basename(nuke.root().name()).split(".")[:-1], ".")

        baseDir = sessionDirBase

        if (not baseDir):
            baseDir = os.getenv("NUKE_TEMP_DIR")
        if (not baseDir):
            baseDir = nuke.value("preferences.DiskCachePath")

        self.settings["sessionDir"] = baseDir + "/RvDir/" + scriptBase

        self.settings["outputFileFormat"] = "rgb"
        self.settings["syncSelection"] = True
        self.settings["syncFrameChange"] = True
        self.settings["syncReadChanges"] = True

        #
        #  Override defaults with stored settings
        #

        self.updateFromRoot()
Exemplo n.º 19
0
    def process(self, context):
        context.data['comment'] = ''
        assert isinstance(context, pyblish.api.Context)
        filename = nuke.value('root.name')
        if not filename:
            raise ValueError('工程尚未保存.')

        context.create_instance(filename, family='Nuke文件')
Exemplo n.º 20
0
    def setup(self):
        """Add tag knob to read nodes, then set project framerange."""

        if not nuke.value('root.project_directory'):
            nuke.knob(
                "root.project_directory", r"[python {os.path.join("
                r"nuke.value('root.name', ''), '../'"
                r").replace('\\', '/')}]")

        nodes = nuke.allNodes('Read')
        if not nodes:
            raise FootageError('没有读取节点')

        n = None
        root_format = None
        root = nuke.Root()
        first = None
        last = None
        formats = []

        for n in nodes:
            ReadNode(n)
            format_ = n.format()
            assert isinstance(format_, nuke.Format)
            if not n.hasError():
                formats.append((format_.width(), format_.height()))
            n_first, n_last = n.firstFrame(), n.lastFrame()

            # Ignore single frame.
            if n_first == n_last:
                continue

            # Expand frame range.
            if first is None:
                first = n_first
                last = n_last
            else:
                first = min(last, n.firstFrame())
                last = max(last, n.lastFrame())

        if first is None:
            first = last = 1

        root_format = root_format or n.format()

        root['first_frame'].setValue(first)
        root['last_frame'].setValue(last)
        nuke.frame((first + last) / 2)
        root['lock_range'].setValue(True)
        try:
            format_ = sorted([(formats.count(i), i)
                              for i in set(formats)])[-1][1]
            root['format'].setValue(nuke.addFormat('{} {}'.format(*format_)))
        except IndexError:
            root['format'].setValue('HD_1080')
            LOGGER.warning('不能获取工程格式, 使用默认值HD_1080')

        root['fps'].setValue(self.fps)
Exemplo n.º 21
0
def _check_project():
    project_directory = nuke.value('root.project_directory')
    if not project_directory:
        _name = nuke.value('root.name', '')
        if _name:
            _dir = os.path.dirname(_name)
            nuke.knob('root.project_directory', _dir)
            nuke.message(b'工程目录未设置, 已自动设为: {}'.format(_dir))
        else:
            nuke.message(b'工程目录未设置')
    # avoid ValueError of script_directory() when no root.name.
    elif project_directory == r"[python {os.path.abspath(os.path.join("\
        r"'D:/temp', nuke.value('root.name', ''), '../'"\
            r")).replace('\\', '/')}]":
        nuke.knob('root.project_directory',
                  r"[python {os.path.join("
                  r"nuke.value('root.name', ''), '../'"
                  r").replace('\\', '/')}]")
Exemplo n.º 22
0
 def label_readout_creator(self):
     node_label_value = nuke.value("this.label", "")
     try:
         node_label_value = nuke.tcl("subst", node_label_value)
     except RuntimeError:
         # TCL execution failed, so just use the label as-is
         pass
     if node_label_value != "" and node_label_value is not None:
         self.lines.append(node_label_value)
Exemplo n.º 23
0
 def _shuffle():
     channels = dict.fromkeys(['in', 'in2', 'out', 'out2'], '')
     for i in channels.keys():
         channel_value = u(nuke.value('this.' + i))
         if channel_value != 'none':
             channels[i] = channel_value + ' '
     label = (channels['in'] + channels['in2'] + '-> ' + channels['out'] +
              channels['out2']).rstrip(' ')
     ret = _add_to_autolabel(label)
     return ret
Exemplo n.º 24
0
 def _with_retime(sel):
     
     for n in sel:
         for i in sel:
             i.knob('selected').setValue(False)
         n.knob('selected').setValue(True)
         
         start = float(nuke.value(n.name()+".first_frame"))
         end = float(nuke.value(n.name()+".last_frame"))
         
         rt = nuke.createNode('Retime', '', False)
         
         rt.knob('input.first_lock').setValue(True)
         rt.knob('input.last_lock').setValue(True)
         rt.knob('output.first_lock').setValue(True)
         rt.knob('output.last_lock').setValue(True)
         rt.knob('input.first').setValue(start)
         rt.knob('input.last').setValue(end)
         rt.knob('output.first').setValue(start)
         rt.knob('output.last').setValue(end)
         rt.knob('before').setValue('black')
         rt.knob('after').setValue('black')
         rt.knob('selected').setValue(False)
         
         sequencer.append(rt)
         
     for rt in sequencer:
         idx = sequencer.index(rt)
         
         if idx == 0:
             idx = idx
             rt.knob('label').setValue("Cut " + str(idx+1))
             continue
         else:
             idx = idx-1
             newStart = sequencer[idx].knob('output.last').value() + 1
             newEnd = rt.knob('output.last').value() + sequencer[idx].knob('output.last').value()
             rt.knob('selected').setValue(True)
             rt.knob('output.first').setValue(newStart)
             rt.knob('output.last').setValue(newEnd)
             rt.knob('label').setValue("Cut " + str(idx+2))
             rt.knob('selected').setValue(False)
             continue 
Exemplo n.º 25
0
def showPopup():
    # Create Popup
    p = nuke.Panel("Batch Render Threads")
    p.addSingleLineInput("First Frame:", nuke.value('root.first_frame'))
    p.addSingleLineInput("Last Frame:", nuke.value('root.last_frame'))
    p.addSingleLineInput("Threads:", "8")

    p.addButton("Cancel")
    p.addButton("OK")
    p.setWidth(200)
    result = p.show()

    if result == 1:
        frameStart = p.value("First Frame:")
        frameEnd = p.value("Last Frame:")
        numThreads = p.value("Threads:")
        createThreads(frameStart, frameEnd, numThreads)
    else:
        print "Canceled!"
Exemplo n.º 26
0
def _add_root_info():
    """add info to root.  """

    artist = nuke.value('preferences.wlf_artist', '')
    if not artist:
        return
    if not nuke.exists('root.wlf'):
        n = nuke.Root()
        k = nuke.Tab_Knob('wlf', b'吾立方')
        k.setFlag(nuke.STARTLINE)
        n.addKnob(k)

        k = nuke.String_Knob('wlf_artist', b'制作人')
        k.setFlag(nuke.STARTLINE)
        k.setValue(artist)
        n.addKnob(k)
    else:
        if nuke.exists('root.wlf_artist') and not nuke.value('root.wlf_artist', ''):
            nuke.knob('root.wlf_artist', artist)
Exemplo n.º 27
0
def createArtifact():

    if nuke.GUI == True:

        filepath = nuke.value("root.name")
        nukescript = filepath[:-3]
        nuke.selectAll()
        nuke.nodeCopy(nukescript + '_artifact.nk')
        nukescripts.clear_selection_recursive()

    return
Exemplo n.º 28
0
def _on_precomp_name_changed(self, knob):
    rootpath = PurePath(u(nuke.value('root.name')))
    name = u(knob.value()) or 'precomp1'
    script_path = (rootpath.parent /
                   ''.join([rootpath.stem] + ['.{}'.format(name)] +
                           rootpath.suffixes)).as_posix()
    render_path = 'precomp/{0}/{0}.%04d.exr'.format(
        ''.join([rootpath.stem] + ['.{}'.format(name)] +
                [i for i in rootpath.suffixes if i != '.nk']))
    self.scriptPath.setValue(script_path.encode('utf-8'))
    self.renderPath.setValue(render_path.encode('utf-8'))
Exemplo n.º 29
0
def showPopup():
	# Create Popup
	p = nuke.Panel("Batch Render Threads")
	p.addSingleLineInput("First Frame:",	nuke.value('root.first_frame'))
	p.addSingleLineInput("Last Frame:",		nuke.value('root.last_frame'))
	p.addSingleLineInput("Threads:",		"8")

	p.addButton("Cancel")
	p.addButton("OK")
	p.setWidth(200)
	result = p.show()


	if result == 1:
		frameStart	= p.value("First Frame:")
		frameEnd	= p.value("Last Frame:")
		numThreads	= p.value("Threads:")
		createThreads(frameStart, frameEnd, numThreads)
	else:
		print "Canceled!"
Exemplo n.º 30
0
def launchSubmit():
	print("nukeStub(): launch submitter dialog")
	submitCmd = "/drd/software/int/bin/launcher.sh -p %s -d %s --launchBlocking farm -o EPA_CMDLINE python2.5 --arg '$ABSUBMIT/nukesubmit/nuke2AB.py'" % (os.environ['DRD_JOB'], os.environ['DRD_DEPT'])
	# root.name holds the path to the nuke script
	submitCmd += " %s" % nuke.value("root.name")
	submitCmd += " %s" % nuke.Root.firstFrame(nuke.root())
	submitCmd += " %s" % nuke.Root.lastFrame(nuke.root())
	writeNodes = [i for i in nuke.allNodes() if i.Class() == "Write"]
	for i in writeNodes:
		submitCmd += " %s %s" % (i['name'].value(), nuke.filename(i))

	print( "nukeStub(): %s" % submitCmd )
	os.system(submitCmd)
Exemplo n.º 31
0
def use_relative_path(nodes):
    """Convert given nodes's file knob to relative path."""

    if isinstance(nodes, nuke.Node):
        nodes = [nodes]

    proj_dir = PurePath(nuke.value('root.project_directory'))
    for n in nodes:
        try:
            path = PurePath(n['file'].value())
            n['file'].setValue(utf8(path.relative_to(proj_dir).as_posix()))
        except NameError:
            continue
Exemplo n.º 32
0
def launchSubmit():
    print("nukeStub(): launch submitter dialog")
    submitCmd = "/drd/software/int/bin/launcher.sh -p %s -d %s --launchBlocking farm -o EPA_CMDLINE python2.5 --arg '$ABSUBMIT/nukesubmit/nuke2AB.py'" % (
        os.environ['DRD_JOB'], os.environ['DRD_DEPT'])
    # root.name holds the path to the nuke script
    submitCmd += " %s" % nuke.value("root.name")
    submitCmd += " %s" % nuke.Root.firstFrame(nuke.root())
    submitCmd += " %s" % nuke.Root.lastFrame(nuke.root())
    writeNodes = [i for i in nuke.allNodes() if i.Class() == "Write"]
    for i in writeNodes:
        submitCmd += " %s %s" % (i['name'].value(), nuke.filename(i))

    print("nukeStub(): %s" % submitCmd)
    os.system(submitCmd)
Exemplo n.º 33
0
    def get_nodes_by_tags(cls, tags):
        """Return nodes that match given tags."""
        ret = []
        if isinstance(tags, (str, unicode)):
            tags = [tags]
        tags = tuple(unicode(i).upper() for i in tags)

        for n in nuke.allNodes('Read'):
            knob_name = '{}.{}'.format(n.name(), ReadNode.tag_knob_name)
            tag = nuke.value(knob_name, '')
            if tag.partition('_')[0] in tags:
                ret.append(n)

        ret.sort(key=cls._nodes_order, reverse=True)
        return ret
Exemplo n.º 34
0
	def __init__(self):
		### Init the panel with a name
		nukescripts.PythonPanel.__init__(self, "hQueue Nuke render submission panel")
		### Gets the absolute file path for the currently open Nuke script, if nothing open then defaults to install directory
		self.absoluteFilePath = os.path.abspath(nuke.value("root.name"))
		### Setup a text box for the server address to be input into
		self.serverAddress = nuke.String_Knob('serverAddress', 'Server Address: ')
		self.addKnob(self.serverAddress)
		### Setup a button to test the server address which will reveal the Connection Successful text
		self.addressTest = nuke.PyScript_Knob("addressTest", "Test the server address", "")
		self.addKnob(self.addressTest)
		### Create addressSuccessFlag flag that is hidden until the server is successfully pinged
		self.addressSuccessFlag = nuke.Text_Knob('addressSuccessFlag', '', '<span style="color:green">Connection Successful</span>')
		self.addressSuccessFlag.setFlag(nuke.STARTLINE)
		self.addressSuccessFlag.setVisible(False)
		self.addKnob(self.addressSuccessFlag)
		### Get the filepath from self.absoluteFilePath and put it into a text box
		self.filePath = nuke.String_Knob('filePath', 'File Path: ', self.absoluteFilePath)
		self.addKnob(self.filePath)
		### Create a button that will test the file path for an nuke script
		self.filePathCheck = nuke.PyScript_Knob("filePathCheck", "Test the File Path", "")
		self.addKnob(self.filePathCheck)
		### Create pathSuccessFlag flag that is hidden until the file path is verified
		self.pathSuccessFlag = nuke.Text_Knob('pathSuccessFlag', '', '<span style="color:green">Connection Successful</span>')
		self.pathSuccessFlag.setFlag(nuke.STARTLINE)
		self.pathSuccessFlag.setVisible(False)
		self.addKnob(self.pathSuccessFlag)
		### Setup the get client list button, which will use hqrop functions
		self.clientGet = nuke.PyScript_Knob("clientGet", "Get client list", "")
		self.addKnob(self.clientGet)
		### Setup the get client groups button, which will use hqrop functions
		self.clientGroupGet = nuke.PyScript_Knob("clientGroupGet", "Get client groups", "")
		self.addKnob(self.clientGroupGet)
		### Setup a save client selection button, this hides the client list and itself
		self.clientSelect = nuke.PyScript_Knob("clientSelect", "Save client selection", "")
		self.clientSelect.setVisible(False)
		self.addKnob(self.clientSelect)
		### Setup a multiline client list that appears when clientGet is run
		self.clientList = nuke.Multiline_Eval_String_Knob('clientList', 'Client List: ')
		self.clientList.setFlag(nuke.STARTLINE)
		self.clientList.setVisible(False)
		self.addKnob(self.clientList)
		### Setup a frame range with the default frame range of the scene
		self.fRange = nuke.String_Knob('fRange', 'Track Range', '%s-%s' % (nuke.root().firstFrame(), nuke.root().lastFrame()))
		self.addKnob(self.fRange)
		
		### Set the minimum size of the python panel
		self.setMinimumSize(500, 600)
Exemplo n.º 35
0
def pdplayer_this( path, node, start, end, incr, view ):

  filename = nuke.filename( node )

  if filename is None or filename == "":
    raise RuntimeError( "Pdplayer cannot be executed on '%s', expected to find a filename and there was none." % (node.fullName(),) )

  os.path.normpath( filename )

  pa = nuke.value( node.name() + ".actual_format.pixel_aspect" )

  args = []
  args.append( quote_fn( path ) )

  if len( view ) > 1:

    (lfn, subs) = re.subn( "%V", view[0], filename );
    (lfn, subs) = re.subn( "%v", view[0][0], lfn );
    args.append( quote_fn( lfn ) );
    args.append( "--range=" + str(start) + "-" + str(end) + "/" + str(incr) )
    args.append( "--pixel_aspect=" + pa )
    args.append( "--target_view=left" );

    (rfn, subs) = re.subn( "%V", view[1], filename );
    (rfn, subs) = re.subn( "%v", view[1][0], rfn );
    args.append( quote_fn( rfn ) );
    args.append( "--range=" + str(start) + "-" + str(end) + "/" + str(incr) )
    args.append( "--pixel_aspect=" + pa )
    args.append( "--target_view=right" );

    args.append( "--stereo_view=both" )

  elif len( view ) == 1:

    (lfn, subs) = re.subn( "%V", view[0], filename );
    (lfn, subs) = re.subn( "%v", view[0][0], lfn );
    args.append( quote_fn( lfn ) );
    args.append( "--range=" + str(start) + "-" + str(end) + "/" + str(incr) )
    args.append( "--pixel_aspect=" + pa )

  else:

    args.append( quote_fn( filename ) );
    args.append( "--range=" + str(start) + "-" + str(end) + "/" + str(incr) )
    args.append( "--pixel_aspect=" + pa )

  os.spawnv( os.P_NOWAITO, path, args )
Exemplo n.º 36
0
 def interface(self):
     # set up the new script name
     scriptName = os.path.basename(nuke.value('root.name'))
     date = datetime.date.today()
     formattedDate = '%s%02d%02d' % (date.year, int(date.month), int(date.day))
     archivePath = 'z:/job/after_earth/prod/io/archive/%s/%s/' % (formattedDate, scriptName.replace('.nk',''))
     self.panel = nukescripts.PythonPanel('Archive script 1.01')
     self.file = nuke.File_Knob('Output','Output folder:')
     self.file.setValue(archivePath)
     self.panel.addKnob(self.file)
     self.scriptName = nuke.String_Knob('name','Script name:',scriptName)
     self.panel.addKnob(self.scriptName)
     self.log = nuke.Boolean_Knob('log','Generate log:',True)
     self.panel.addKnob(self.log)
     self.comment = nuke.Multiline_Eval_String_Knob('comment','Comments:')
     self.panel.addKnob(self.comment)
     result = self.panel.showModalDialog()
     self.scriptInfo = nukescripts.get_script_data()
     if result:
         self.convertGizmosToGroups()
         self.action()
Exemplo n.º 37
0
def iFilter03(filter, steps, previousAmount):
##########
##asigne el node actual a la variable "a"

  a = nuke.thisNode ()

##########
##lectura dels knobs

  steps = int (steps)
  stepVal = float (1/float (steps))

  diler = float (nuke.value ("Amount"))
  dilerDiv = float (diler/steps)

  filter = nuke.Enumeration_Knob.value(a.knob ("Filter"))

##########
##empythonament dels nodes que fan falta

  inMask = nuke.toNode ("puntazoMask")
  inImage = nuke.toNode ("puntazo")

##empythonament dels nodes que fan falta
##########


##########
##Borra els nodes existents
  id = int(previousAmount)
  idKill = 0
  for i in range (id):
      idKill = idKill+1
####Expressions
      nomExpr = "idilerExpr" + str (idKill)
      killExpr = nuke.toNode (nomExpr)
      nuke.delete (killExpr)
####Blurs
      nomBlr = "idilerBlur" + str (idKill)
      killBlr = nuke.toNode (nomBlr)
      nuke.delete (killBlr)
####Erodes
      nomEro = "idilerErode" + str (idKill)
      killEro = nuke.toNode (nomEro)
      nuke.delete (killEro)
####Keymixes
      nomKey = "idilerKeymix" + str (idKill)
      killKey = nuke.toNode (nomKey)
      nuke.delete (killKey)
####BlurBlurs
      nomKey = "idilerErode" + str (idKill)
      killKey = nuke.toNode (nomKey)
      nuke.delete (killKey)
####Defocus
      nomKey = "idilerErode" + str (idKill)
      killKey = nuke.toNode (nomKey)
      nuke.delete (killKey)
  primerKey = nuke.toNode ("KeymixInicik")
  nuke.delete (primerKey)

##########
##Amaga ensenya knobs
  if filter == "dilerFast":
    a.knob('iFilterFilter').setFlag(1024)
    a.knob('iFilterBlur').setFlag(1024)
    a.knob('iFilterQuality').setFlag(1024)
    a.knob('iFilterBlurFilter').setFlag(1024)
    a.knob('iFilterBlurQuality').setFlag(1024)
    a.knob('iFilterDefAspect').setFlag(1024)
    a.knob('iFilterDefScaling').setFlag(1024)
    a.knob('iFilterDefQuality').setFlag(1024)
    a.knob('iFilterDefMethod').setFlag(1024)
    a.knob('previousAmount').setFlag(1024)

  elif filter == "dilerFilter":
    a.knob('iFilterFilter').clearFlag(1024)
    a.knob('iFilterBlur').setFlag(1024)
    a.knob('iFilterQuality').setFlag(1024)
    a.knob('iFilterBlurFilter').setFlag(1024)
    a.knob('iFilterBlurQuality').setFlag(1024)
    a.knob('iFilterDefAspect').setFlag(1024)
    a.knob('iFilterDefScaling').setFlag(1024)
    a.knob('iFilterDefQuality').setFlag(1024)
    a.knob('iFilterDefMethod').setFlag(1024)
    a.knob('previousAmount').setFlag(1024)

  elif filter == "dilerBlur":
    a.knob('iFilterFilter').setFlag(1024)
    a.knob('iFilterBlur').clearFlag(1024)
    a.knob('iFilterQuality').clearFlag(1024)
    a.knob('iFilterBlurFilter').setFlag(1024)
    a.knob('iFilterBlurQuality').setFlag(1024)
    a.knob('iFilterDefAspect').setFlag(1024)
    a.knob('iFilterDefScaling').setFlag(1024)
    a.knob('iFilterDefQuality').setFlag(1024)
    a.knob('iFilterDefMethod').setFlag(1024)
    a.knob('previousAmount').setFlag(1024)

  elif filter == "blur":
    a.knob('iFilterFilter').setFlag(1024)
    a.knob('iFilterBlur').setFlag(1024)
    a.knob('iFilterQuality').setFlag(1024)
    a.knob('iFilterBlurFilter').clearFlag(1024)
    a.knob('iFilterBlurQuality').clearFlag(1024)
    a.knob('iFilterDefAspect').setFlag(1024)
    a.knob('iFilterDefScaling').setFlag(1024)
    a.knob('iFilterDefQuality').setFlag(1024)
    a.knob('iFilterDefMethod').setFlag(1024)
    a.knob('previousAmount').setFlag(1024)

  elif filter == "defocus":
    a.knob('iFilterFilter').setFlag(1024)
    a.knob('iFilterBlur').setFlag(1024)
    a.knob('iFilterQuality').setFlag(1024)
    a.knob('iFilterBlurFilter').setFlag(1024)
    a.knob('iFilterBlurQuality').setFlag(1024)
    a.knob('iFilterDefAspect').clearFlag(1024)
    a.knob('iFilterDefScaling').clearFlag(1024)
    a.knob('iFilterDefQuality').clearFlag(1024)
    a.knob('iFilterDefMethod').clearFlag(1024)
    a.knob('previousAmount').setFlag(1024)

##########
##Creacio dels nodes

  xXpresionPos = 100
  ide = 0


  for i in range (steps) :
      ide = ide + 1
####Expressions
      nom = "idilerExpr" + str (ide)
      b = "name " + nom + " temp_name0 r" + str (ide) + " temp_expr0 step(r," + str (stepVal*ide) + ")" +" expr0 r" + str (ide) + " xpos " + str (xXpresionPos*ide) + " ypos 100"
      nom = nuke.createNode ("Expression", b, False)
      nom.setInput (0, inMask)

####Blurs
      nomBlur = "idilerBlur" + str (ide)
      bl = "name " + nomBlur + " size parent.Soften" + " xpos " + str (xXpresionPos*ide) + " ypos 150"
      blr = nuke.createNode ("Blur", bl, False)
      blr.setInput (0, nom)

####Filtres

      if filter == "dilerFast":
          nomErode = "idilerErode" + str(ide)
          valDiler = float (dilerDiv*ide)
          siz = "parent.Amount/" + str(steps) + "*" + str(ide)
          er = "name " + nomErode + " channels all " +  " size " + siz + " xpos " + str (xXpresionPos*ide) + " ypos 500"
          ero = nuke.createNode ("Dilate", er, False)
          ero.setInput (0, inImage)

      elif filter == "dilerFilter":
          nomErode = "idilerErode" + str (ide)
          valDiler = float (dilerDiv*ide)
          siz = "parent.Amount/" + str(steps) + "*" + str(ide)
          er = "name " + nomErode + " channels all " +  " size " + siz + " filter {{parent.iFilterFilter}} xpos " + str (xXpresionPos*ide) + " ypos 500"
          ero = nuke.createNode ("FilterErode", er, False)
          ero.setInput (0, inImage)

      elif filter == "dilerBlur":
          nomErode = "idilerErode" + str (ide)
          valDiler = float (dilerDiv*ide)
          siz = "parent.Amount/" + str(steps) + "*" + str(ide)
          er = "name " + nomErode + " channels all " +  " size " + siz + " blur {{parent.iFilterBlur}} quality {{parent.iFilterQuality}} xpos " + str (xXpresionPos*ide) + " ypos 500"
          ero = nuke.createNode ("Erode", er, False)
          ero.setInput (0, inImage)

      elif filter == "blur":
          nomErode = "idilerErode" + str (ide)
          valDiler = float (dilerDiv*ide)
          siz = "parent.Amount/" + str(steps) + "*" + str(ide)
          er = "name " + nomErode + " channels all " +  " size " + siz + " filter {{parent.iFilterBlurFilter}} quality {{parent.iFilterBlurQuality}} xpos " + str (xXpresionPos*ide) + " ypos 500"
          ero = nuke.createNode ("Blur", er, False)
          ero.setInput (0, inImage)

      elif filter == "defocus":
          nomErode = "idilerErode" + str (ide)
          valDiler = float (dilerDiv*ide)
          siz = "parent.Amount/" + str(steps) + "*" + str(ide)
          er = "name " + nomErode + " channels all " +  " defocus " + siz + " ratio {{parent.iFilterDefAspect}} scale {{parent.iFilterDefScaling}} quality {{parent.iFilterDefQuality}} method {{iFilterDefMethod}} xpos " + str (xXpresionPos*ide) + " ypos 500"
          ero = nuke.createNode ("Defocus", er, False)
          ero.setInput (0, inImage)

####Keymix
  ide = 0
  for i in range (steps):
      ide = ide + 1
      bl = nuke.toNode ("idilerBlur" + str(ide-1))
      er = nuke.toNode ("idilerErode" + str (ide))
      ke = "name idilerKeymix" + str (ide) + " maskChannel rgba.red xpos " + str (xXpresionPos*ide) + " ypos 550"
      creaKey = nuke.createNode ( "Keymix", ke, False)
      creaKey.setInput (2, bl)
      creaKey.setInput (0, er)

      creaKeyMenysU = "idilerKeymix" + str (ide-1)
      creaKeyAnterior = nuke.toNode (creaKeyMenysU)
      creaKey.setInput (1, creaKeyAnterior)
########Primer Keymix
  km1 = nuke.toNode ("idilerKeymix1")
  er1 = nuke.toNode ("idilerErode1")
  km1.setInput (0, er1)
  km1.setInput (1, inImage)
  km1.setInput (2, blr)

####conect l'output i el switch al ultim keymix
  out = nuke.toNode ("iFilterFinalMerge")
  iFilterSwitch = nuke.toNode ('iFilterSwitch')
  out.setInput (1, creaKey)
  iFilterSwitch.setInput (0, creaKey)
    
####Fora del loop reposiciono els ultims nodes d'expressio i de Blur pa posar-los al comensament i que els cables no es creuin
  nom.knob("xpos").setValue (-10)
  nom.knob("ypos").setValue (100)

  blr.knob("xpos").setValue (-10)
  blr.knob("ypos").setValue (150)

####info
  a.knob("info").setValue (".:  Current filter: "+str(filter)+" with "+str(int(float(steps)))+" steps  (Click button to update ...) :.")
Exemplo n.º 38
0
def create_product_before_render(node=None):

    if not node:
        node = nuke.thisNode()

    if not node.knob('product_name') or not node.knob('product_desc'):
        raise Exception("The supplied node is not a WriteProduct node.")

    print "Creating product for write node... " + str(node)

    ptask_area = PTaskArea.current()
    ptask = PTask.get(ptask_area.spec)

    if ptask_area.version:
        ptask_version = ptask.version(ptask_area.version)
    else:
        ptask_version = ptask.latest_version

    category = 'imgseq'

    file_type = node['file_type'].value()
    if not file_type:
        file_type = 'exr'

    product_name = node['product_name'].value()
    product_desc = node['product_desc'].value()
    product_ver_note = node['product_ver_note'].value()

    if not product_desc:
        raise Exception("Please enter a product description.")

    width = nuke.value(node.name() + '.width')
    height = nuke.value(node.name() + '.height')
    resolution = width + 'x' + height
        
    create_action_cls = ActionRegistry().get_action('create', 'product')
    if not create_action_cls:
        raise Exception("Unable to find product creation action.")

    create_action = create_action_cls(
        product=product_name,
        ptask=ptask.spec,
        version=ptask_version.number,
        category=category,
        description=product_desc,
        file_type=file_type,
        resolution=resolution,
        note=product_ver_note,
    )

    try:
        create_action()
    except ActionError as e:
        raise Exception("Unable to create product: " + str(e))

    out_path = os.path.join(create_action.product_repr.area.path,
        product_name + '.####.' + file_type)

    node['file'].setValue(out_path)

    return create_action.product_repr
Exemplo n.º 39
0
def launch_nukes(nodes=[]):
    """
    Launch single-core command-line Nuke renderers from inside the Nuke UI.
    """

    if nuke.root().knob('name').value() == '':
        nuke.message('This script is not named. Please save it and try again.')
        return
    
    # Select Write nodes.
    nodelist = ''
    if nodes != []:
        nodelist = ','.join([n.name() for n in nodes if "Write" in n.Class()])
    
    start = int(nuke.knob("first_frame"))
    end = int(nuke.knob("last_frame"))
    instances = nuke.env['numCPUs']
    framerange = str(start) + "-" + str(end)
    p = nuke.Panel("Launch Nukes")
    p.addSingleLineInput("Frames to execute:", framerange)
    p.addSingleLineInput("Node(s) to execute:", nodelist)
    p.addSingleLineInput("Number of background procs:", instances)
    p.addButton("Cancel")
    p.addButton("OK")
    result = p.show()
    
    if not result: return
    framerange = p.value("Frames to execute:")
    nodelist = p.value("Node(s) to execute:").replace(' ', '')
    inst = int(p.value("Number of background procs:"))
    if framerange is None: 
        return
    if inst is None: 
        return

    (scriptpath, scriptname) = os.path.split(nuke.value("root.name"))
    flags = "-ixm 1"
    if nodelist != '': flags += " -X " + nodelist
    
    r = nuke.FrameRanges()
    r.add(framerange)
    r.compact()
    frame_list = r.toFrameList()
    print frame_list
    
    # Create lists of frames to render for each instance.
    inst_frame_list = []
    for i in range(inst): inst_frame_list.append([])
    print inst_frame_list
    cnt = 0
    for frame in frame_list:
        inst_frame_list[cnt].append(str(frame))
        cnt += 1
        if cnt == inst: cnt = 0
    print inst_frame_list
    
    print ">>> launching", inst, "nuke instances"
    
    # Launch each renderer
    logs = []
    for i in range(inst):
        instRange = ' '.join(inst_frame_list[i])

        print ">>> frame list for instance", i, "is:", instRange
        
        logFile = "%s/%s_log%02d.log" % (scriptpath, scriptname, i)
        logs.append(logFile)
        
        cmd = " ".join([nuke.env['ExecutablePath'], flags, '-F', '"' + instRange + '"', nuke.value("root.name"), '&>', logFile])
        print ">>> starting instance %d" % (i, )
        print "command: " + cmd
        subprocess.Popen(cmd, shell=True)
    
    nuke.message(str(inst) + ' renderers launched in the background.\nLog files: ' + ', '.join(logs))
Exemplo n.º 40
0
def render(argv):


    ## Parse arguments
    optparser = optparse.OptionParser()
    optparser.add_option("--jobPriority", dest="pbias",
            type="float", default=1.0)
    optparser.add_option("--engine", dest="engine",
            type="string", default="tractor-engine:80")
    optparser.add_option("--ff", dest="ff",
            type="int", default=int(nuke.value('first_frame')))
    optparser.add_option("--lf", dest="lf",
            type="int", default=int(nuke.value('last_frame')))
    optparser.add_option("--dir", dest="dire",
            type="string", default=os.getcwd())
    optparser.add_option("--style", dest="style",
            type="string", default="Cmd")
    optparser.add_option("--paused", dest="paused",
            action="store_true")
    optparser.add_option("--delJobScripts", dest="delJob",
            action="store_true")
    optparser.add_option("--jobServerAttributes", dest="jobServerAttributes",
            type="string", default='')
    optparser.add_option("--jobCmdTags", dest="jobCmdTags",
            type="string", default='')
    optparser.add_option("--envkey", dest="envkey",
            type="string", default='')
    optparser.add_option("--jobDoneCmd", dest="jobDoneCmd",
            type="string", default='')
    optparser.add_option("--jobErrorCmd", dest="jobErrorCmd",
            type="string", default='')
    optparser.add_option("--crews", dest="crews",
            type="string", default='')
    optparser.add_option("--extraJobOptions", dest="extraJobOptions",
            type="string", default='')
    optparser.add_option("--selected_only", dest="selected_only",
            action="store_true")
    optparser.add_option("--debug", dest="debug",
            action="store_true")
    optparser.add_option("--nukeX", dest="nukeX",
            action="store_true")
    optparser.add_option("--script", dest="script",
            type="string", default=nuke.root().name())
    optparser.add_option("--threads", dest="threads",
            type="int", default=1)
    optparser.add_option("--ram", dest="RAM",
            type="int", default=0)

    (opts, args) = optparser.parse_args( argv )
    
    # nodes to render
    nodes = None
    if opts.selected_only:
        nodes = nuke.selectedNodes()
    else:
        nodes = nuke.root().nodes()
            
    #look for Write nodes
    if opts.debug: print 'Scanning %d nodes'%len(nodes)
    write_nodes = list()
    for node in nodes:
        if opts.debug: print node.fullName()+' '+str(node.Class())
        if node.Class() == 'Write':
             write_nodes.append(node)
             continue
        try:
            for subnode in node.nodes():
                #I think this is fully recursive
                if subnode.Class() == 'Write':
                    write_nodes.append(subnode)
        except AttributeError:
            #thrown by nodes() on non-group or gizmo
            pass            

    print ''
    if (len(write_nodes) < 1):
        print 'tractorNuke: No renderable nodes selected'
        return
                
    #for each write node, get its name for the -X arg of nuke              
    write_node_names = list()
    for node in write_nodes: 
            write_node_names.append(node.fullName())

    #for each write node, compute the frame name for each frame
    #this accounts for expressions, offsets, etc    
    image_names = dict()
    for frame in range(opts.ff, opts.lf+1):
        #nuke.Root.setFrame(frame)
        nuke.frame(frame) #deprecated but seems to work better than using Root
        image_names[frame] = list()
        for node in write_nodes:      
                filename = nuke.filename(node,nuke.REPLACE)           
                print filename
                image_names[frame].append(filename)
 
    if opts.debug:
        print 'Submitting:'
        print opts.script
        print write_node_names
        print image_names

    only_nodes_cmd = '' #this will remain empty if all nodes are to be rendered
    if write_node_names:
         only_nodes_cmd = ' -X '+','.join(write_node_names)

    ## Open file for writing and write the Job file
    currentTime = time.strftime('%a, %d %b %Y %H:%M:%S +0000', time.gmtime())
    fnm = ''
    fnm = opts.dire.replace('\\', '/') + '/tmpNuke_' + str(time.time()) + '.alf'
    jobFile = open(fnm, 'w')

    cmdtail = '-service { ' + opts.jobServerAttributes + '} -envkey { ' 
    cmdtail = cmdtail + ' ' + opts.envkey + '}'
    
    jobFile.write('##AlfredToDo 3.0\n')
    jobFile.write('##\n')
    jobFile.write('## Generated: ' + str(currentTime) +'\n')
    jobFile.write('## Nuke Script: ' + opts.script + '\n')
    jobFile.write('##\n\n')

    jobFile.write('Job -title {' + opts.script + '}')
    jobFile.write(' -pbias ' + str(opts.pbias) + '')
    jobFile.write(' -tags { ' + opts.jobCmdTags + '}')
    jobFile.write(' -service {' + opts.jobServerAttributes + '}')
    jobFile.write(' -crews {' + opts.crews + '}')
    jobFile.write(' -envkey {' + opts.envkey + '}')
    jobFile.write(' -whendone {' + opts.jobDoneCmd + '}')
    jobFile.write(' -whenerror {' + opts.jobErrorCmd + '}')
    jobFile.write(' ' + opts.extraJobOptions + ' ')
    jobFile.write('-subtasks {\n')

    jobFile.write('Task -title {Job} -serialsubtasks 0 -subtasks {\n')

    ##---------------------------------------------------------------------

    ## Query for the path to Nuke's executable.
    ## If sites are running different OS's, they should uncomment the second
    ## line so that the command only contains the Nuke executable. 
    ## Then, they should add an evironment key that includes the Nuke version
    ## For example:
    ##  nuke6.3v1
    ##
    nuke_exe = nuke.env['ExecutablePath']
    nuke_exe = os.path.basename(nuke_exe)

    ##--------------------------------------------------------------------

    for frame in range(opts.ff, opts.lf+1): 

        title = ''
        title = 'Frame ' + str(frame)

        jobFile.write('   Task -title {' + title + '} -cmds {\n')
        cmd = '"' + nuke_exe + '" -F %d -m %d -t %s '%(frame, opts.threads, only_nodes_cmd)
        if opts.RAM != 0:
            cmd = cmd + ' -c %dM'%(opts.RAM)
        if opts.nukeX:
            cmd = cmd + ' --nukex '
        cmd = cmd + ' -x "%s"'%(opts.script)
        jobFile.write( '        ' + opts.style + ' {' + cmd + '} ' + cmdtail + '\n')
        jobFile.write('   }\n')

    jobFile.write('} -cleanup {\n')
    if opts.delJob:
        jobFile.write('     File delete "' + fnm + '"\n')
    jobFile.write('}\n')
    jobFile.write('}\n')
    jobFile.close()

    args = []
    args.append('--engine=' + opts.engine)
    if opts.paused:
        args.append('--paused')
    args.append(fnm)
    
    ## Spool job
    Spool(args)
Exemplo n.º 41
0
def renderPanel(debug=False):
    panel = nuke.Panel("Tractor Spool")
    dire = ''
    
    ## Get .nuke directory
    if not 'HOME' in os.environ.keys():
        dire = os.environ['USERPROFILE']
    else:
        dire = os.environ['HOME']
    dire += '/.nuke/tractorNuke'
    if not os.path.exists(dire):
        os.makedirs(dire)

    script = nuke.root().name() 

    iniFile = dire + '/tractorNuke.ini'

    engine = 'tractor-engine'
    port = 80
    if 'TRACTOR_ENGINE' in os.environ.keys():
        name = os.environ['TRACTOR_ENGINE']
        engine,n,p = name.partition(":")
        if p: 
            port = p

    style = 'Local Remote'
    startPaused = False
    delJobScript = False
    jobPriority = 1
    nthreads = 1
    RAM = '0' 
    jobServerAttributes = 'NukeRender'
    jobCmdTags = ''
    envKey = ''
    jobDoneCmd = ''
    jobErrorCmd = ''
    crews = ''
    extraJobOptions = ''
    ff = nuke.value('first_frame')
    lf = nuke.value('last_frame')
    nukeX = False
    selected_only = False
    saveBeforeRender = True

    Config = ConfigParser.ConfigParser()

    ## Get values from ini file, tractorNuke.ini, if it exists
    if os.path.exists(iniFile):
        Config.read(iniFile)
        if Config.has_option('Options', 'Engine'):
            engine = Config.get('Options', 'Engine')
        if Config.has_option('Options', 'Port'):
            port = Config.getint('Options', 'Port')
        if Config.has_option('Options', 'Start Paused'):
            startPaused = Config.getboolean('Options', 'Start Paused')
        if Config.has_option('Options', 'Delete Job'):
            delJobScript = Config.getboolean('Options', 'Delete Job')
        if Config.has_option('Options', 'Priority'):
            jobPriority = Config.getfloat('Options', 'Priority')
        if Config.has_option('Options', 'Threads'):
            nthreads = Config.getint('Options', 'Threads')
        if Config.has_option('Options', 'Max RAM'):
            RAM = Config.get('Options', 'Max RAM')
        if Config.has_option('Options', 'Job Server Attributes'):
            jobServerAttributes = Config.get('Options', 'Job Server Attributes')
        if Config.has_option('Options', 'Job Cmd Tags'):
            jobCmdTags = Config.get('Options', 'Job Cmd Tags')
        if Config.has_option('Options', 'Env Key'):
            envKey = Config.get('Options', 'Env Key')
        if Config.has_option('Options', 'Job Done Cmd'):
            jobDoneCmd = Config.get('Options', 'Job Done Cmd')
        if Config.has_option('Options', 'Job Error Cmd'):
            jobErrorCmd = Config.get('Options', 'Job Error Cmd')
        if Config.has_option('Options', 'Crews'):
            crews = Config.get('Options', 'Crews')
        if Config.has_option('Options', 'Extra Job Options'):
            extraJobOptions = Config.get('Options', 'Extra Job Options')
        if Config.has_option('Options', 'Render with NukeX'):
            nukeX = Config.getboolean('Options', 'Render with NukeX')
        if Config.has_option('Options', 'Selected Only'):
            selected_only = Config.getboolean('Options', 'Selected Only')
        if Config.has_option('Options', 'Save Before Render'):
            saveBeforeRender = Config.getboolean('Options', 'Save Before Render')


    panel.addSingleLineInput('Tractor Engine', engine)
    panel.addSingleLineInput('Port', port)
    panel.addSingleLineInput('Threads', nthreads)
    panel.addSingleLineInput('Max RAM Usage (in MB, 0 for default)', RAM)
    panel.addSingleLineInput('Script',script)
    panel.addEnumerationPulldown('Style', style)
    panel.addBooleanCheckBox('Start Paused', startPaused)
    panel.addBooleanCheckBox('Delete Job Script', delJobScript)
    panel.addSingleLineInput('Job Priority', jobPriority)
    panel.addSingleLineInput('Job Server Attributes', jobServerAttributes)
    panel.addSingleLineInput('Job Cmd Tags', jobCmdTags)
    panel.addSingleLineInput('Environment Key', envKey)
    panel.addSingleLineInput('Job Done Command', jobDoneCmd)
    panel.addSingleLineInput('Job Error Command', jobErrorCmd)
    panel.addSingleLineInput('Crews', crews)
    panel.addSingleLineInput('Extra Job Options', extraJobOptions)
    panel.addSingleLineInput('First Frame',  ff)
    panel.addSingleLineInput('Last Frame',  lf)
    panel.addBooleanCheckBox('Render with NukeX', nukeX)
    panel.addBooleanCheckBox('Selected Only', selected_only)
    panel.addBooleanCheckBox('Save before Render', saveBeforeRender)
    panel.addButton('Cancel')
    panel.addButton('Spool Job')
    result = panel.show()
   
    if debug: print 'result:'+str(result)

    saveBeforeRender = panel.value('Save before Render')
    
    if saveBeforeRender:
            print 'Saving script before Render '+script
            nuke.scriptSave()
            
    selected_only = panel.value('Selected Only')    
    ff = int(panel.value('First Frame'))
    lf = int(panel.value('Last Frame'))
    engine = panel.value('Tractor Engine')
    port = int(panel.value('Port'))
    style = panel.value('Style')
    startPaused = panel.value('Start Paused')
    delJobScript = panel.value('Delete Job Script')
    jobPriority = float(panel.value('Job Priority'))
    jobServerAttributes = panel.value('Job Server Attributes')
    jobCmdTags = panel.value('Job Cmd Tags')
    envKey = panel.value('Environment Key')
    jobDoneCmd = panel.value('Job Done Command')
    jobErrorCmd = panel.value('Job Error Command')
    crews = panel.value('Crews')
    extraJobOptions = panel.value('Extra Job Options')
    nukeX = panel.value('Render with NukeX')
    nthreads = int(panel.value('Threads'))
    RAM = int(panel.value('Max RAM Usage (in MB, 0 for default)'))

    if style == 'Local':
        style = 'Cmd'
    else:
        style = 'RemoteCmd'

    if result == 0:
        return

    ## Write to ini file
    if not 'Options' in Config.sections():
        Config.add_section('Options')
    Config.set('Options', 'Engine', engine)
    Config.set('Options', 'Port', port)
    Config.set('Options', 'Start Paused', startPaused)
    Config.set('Options', 'Delete Job', delJobScript)
    Config.set('Options', 'Priority', jobPriority)
    Config.set('Options', 'Threads', nthreads)
    Config.set('Options', 'Max RAM', RAM)
    Config.set('Options', 'Job Server Attributes', jobServerAttributes)
    Config.set('Options', 'Job Cmd Tags', jobCmdTags)
    Config.set('Options', 'Env Key', envKey)
    Config.set('Options', 'Job Done Cmd', jobDoneCmd)
    Config.set('Options', 'Job Error Cmd', jobErrorCmd)
    Config.set('Options', 'Crews', crews)
    Config.set('Options', 'Extra Job Options', extraJobOptions)
    Config.set('Options', 'Render with NukeX', nukeX)
    Config.set('Options', 'Selected Only', selected_only)
    Config.set('Options', 'Save Before Render', saveBeforeRender)
    newiniFile = open(iniFile, 'w')
    Config.write(newiniFile)
    newiniFile.close()
    ## write frame range to project settings
    nuke.root().knob('first_frame').setValue(ff)
    nuke.root().knob('last_frame').setValue(lf)

    args = []
    args.append('--engine=' + engine + ':' + str(port))
    args.append('--style='+style)
    if startPaused:
        args.append('--paused')
    if delJobScript:
        args.append('--delJobScript')
    args.append('--jobPriority='+str(jobPriority))
    args.append('--jobServerAttributes='+str(jobServerAttributes))
    args.append('--jobCmdTags='+str(jobCmdTags))
    args.append('--envkey='+str(envKey))
    args.append('--jobDoneCmd='+str(jobDoneCmd))
    args.append('--jobErrorCmd='+str(jobErrorCmd))
    args.append('--crews='+str(crews))
    args.append('--extraJobOptions='+str(extraJobOptions))
    args.append('--dir='+str(dire))
    args.append('--ff='+str(ff))
    args.append('--lf='+str(lf))
    if selected_only:
        args.append('--selected_only')
    if debug:
        args.append('--debug')
    if nukeX:
        args.append('--nukeX')
    args.append('--script='+str(script))
    args.append('--threads='+str(nthreads))
    args.append('--ram='+str(RAM))

    render(args)
Exemplo n.º 42
0
def launch_nukes(): 
    a = nuke.knob("first_frame")
    b = nuke.knob("last_frame")
    start = int(a)
    end = int(b)
    incr = 1
    instances = 1
    _range = a+","+b
    p = nuke.Panel("Launch Nukes")
    p.addSingleLineInput("Frames to execute:", _range)
    p.addSingleLineInput("Number of background procs:", instances)
    p.addButton("Cancel")
    p.addButton("OK")
    result = p.show()
    
    r = p.value("Frames to execute:")
    s = p.value("Number of background procs:")
    if r is None: 
        return
    if s is None: 
        return
    # this is the requested frame range
    frames = r
    # this is the number of instances to launch
    inst = int(s)

    (scriptpath, scriptname) = os.path.split(nuke.value("root.name"))
    flags = "-ixfm 1"
    
    print ">>> launching %s nuke instances" % inst
    
    # create a frame range string for each renderer
    for i in range(inst):
        print ">>> generating range for instance %d" % i
        instRange = ""
    
        # separate ranges at spaces
        f = frames.split(" ")
        
        # separate individual start, end, and increment values
        for p in f:
            c = p.split(",")
            incr = 1
            if len(c) > 0:
                start = int(c[0])
                end = start
            if len(c) > 1: end = int(c[1])
            if len(c) > 2: incr = int(c[2])
            
            # re-jigger this range for this instance of the renderer
            st = start + ( i * incr )
            en = end
            inc = incr * inst
            new = "%d,%d,%d" % (st, en, inc)
            if inc == 1:
                new = "%d,%d" % (st, en)
            if en == st:
                new = "%d" % st
            if st > en:
                new = ""
            else:
                # add the re-jiggered range to the instances range string
                instRange = instRange + " " + new
                
        print ">>> range for instance %d is: %s" % (i, instRange)
        
        logFile = "%s/%s_log%02d.log" % (scriptpath, scriptname, i)
        
        cmd = "%s %s %s/%s %s > %s &" % (nuke.EXE_PATH, flags, scriptpath, scriptname, instRange, logFile)
        print ">>> starting instance %d" % (i, )
        print "command: " + cmd
        os.system(cmd)