def setup_cryptomatte(): nuke.addKnobChanged(lambda: cryptomatte_knob_changed_event( nuke.thisNode(), nuke.thisKnob()), nodeClass='Cryptomatte') nuke.addKnobChanged(lambda: encryptomatte_knob_changed_event( nuke.thisNode(), nuke.thisKnob()), nodeClass='Encryptomatte') nuke.addOnCreate(lambda: encryptomatte_on_create_event( nuke.thisNode(), nuke.thisKnob()), nodeClass='Encryptomatte')
def clear_muted(node=None): """clear any layers which are currently disabled in the interface""" rmbs = [r for r in nuke.thisNode().knobs() if '_rmb' in r] for r in rmbs: disable_chk = r[:-4] + '_disable_lnk' if node[disable_chk].getValue(): nuke.thisNode()[r].execute()
def render(): cn = nuke.thisNode() setCommentPath() frameStart = int(cn["frameStart"].getValue()) frameEnd = int(cn["frameEnd"].getValue()) if cn["submit"].getValue() == 0.0: threads = int(cn["threads"].getValue()) from plugins.vuRenderThreads.plugin_nuke import plugin_nuke plugin_nuke.createThreads(frameStart, frameEnd, threads, [cn.name()]) LOG.info("END : RENDERTHREADS : " + cn["exrPathComment"].getValue()) elif cn["submit"].getValue() == 1.0: import rrenderSubmit nuke.load('rrenderSubmit') rrenderSubmit.rrSubmit_Nuke_Node(cn, frameStart, frameEnd) LOG.info("END : RRSUBMIT : " + cn["exrPathComment"].getValue()) else: try: nuke.execute(nuke.thisNode(), start=frameStart, end=frameEnd, incr=1) LOG.info("END : LOCAL : " + cn["exrPathComment"].getValue()) except: print "END : LOCAL : Execution failed" LOG.error("END : LOCAL : " + cn["exrPathComment"].getValue(), exc_info=True)
def center_chromatik(): try: node_format = nuke.selectedNode() except ValueError: node_format = nuke.root()['format'].value() nuke.thisNode()['center'].setValue( (node_format.width() / 2, node_format.height() / 2))
def insert_pt(): max_pts = int(nuke.thisNode().knob('Max PTS').value()) MAX_POINTS = int(nuke.thisNode().knob('Max Limit').value()) if max_pts >= MAX_POINTS: nuke.message('Maximum %i points' % (MAX_POINTS)) return pt_num = int(nuke.thisKnob().name()[6:]) node = nuke.thisNode() # Shuffle values upwards for pt in xrange(max_pts, pt_num, -1): knob_name = 'pt' + str(pt) prev_knob = 'pt' + str(pt - 1) prev_value = node.knob(prev_knob).value() node.knob(knob_name).setValue(prev_value) # Set new position to midpoint of adjacent points if pt_num > 1: ptA = node.knob('pt' + str(pt_num - 1)).value() else: ptA = node.knob('Start').value() ptB = node.knob('pt' + str(pt_num + 1)).value() midpoint = [sum(x) / 2 for x in zip(ptA, ptB)] node.knob('pt' + str(pt_num)).setValue(midpoint) # Reveal next row for name in ('pt', 'delete', 'insert'): node.knobs()[name + str(max_pts)].setVisible(True) node.knob('Max PTS').setValue(max_pts + 1)
def insert_pt(): max_pts = int(nuke.thisNode().knob('Max PTS').value()) MAX_POINTS = int(nuke.thisNode().knob('Max Limit').value()) if max_pts >= MAX_POINTS: nuke.message('Maximum %i points' % (MAX_POINTS)) return pt_num = int(nuke.thisKnob().name()[6:]) node = nuke.thisNode() # Shuffle values upwards for pt in range(max_pts, pt_num, -1): knob_name = 'pt' + str(pt) prev_knob = 'pt' + str(pt - 1) node[knob_name].fromScript(node[prev_knob].toScript()) # Set new position to midpoint of adjacent points if pt_num > 1: ptA = node.knob('pt' + str(pt_num - 1)).value() else: ptA = node.knob('Start').value() ptB = node.knob('pt' + str(pt_num + 1)).value() midpoint = [sum(x) / 2 for x in zip(ptA, ptB)] node.knob('pt' + str(pt_num)).clearAnimated() node.knob('pt' + str(pt_num)).setValue(midpoint) # Reveal next row for name in ('pt', 'delete', 'insert'): node.knobs()[name + str(max_pts)].setVisible(True) node.knob('Max PTS').setValue(max_pts + 1)
def hide_panel(): # Always hide control panels on node creation if node not in exceptions node = nuke.thisNode() exceptions = ['Roto', 'RotoPaint'] if node.Class() not in exceptions: nuke.thisNode().showControlPanel() nuke.thisNode().hideControlPanel()
def make_dir_path(): file = "" # are we being called interactively, by the user hitting Ctrl+F8? if nuke.thisNode() == nuke.root(): sel = None try: sel = nuke.selectedNodes()[0] except: print "WARNING: No nodes selected." return file = nuke.filename(sel) else: # nuke.filename(nuke.thisNode()) occasionally throws a RuntimeError exception when ran from the addBeforeRender() callback. # catch the exception and do not proceed when the exception is thrown. # added by Ned, 2016-01-27 try: file = nuke.filename(nuke.thisNode()) except RuntimeError as re: return except ValueError as ve: return dir = os.path.dirname(file) osdir = nuke.callbacks.filenameFilter(dir) if not os.path.exists(osdir): print "INFO: Creating directory at: %s" % osdir try: os.makedirs(osdir) except OSError as e: print "ERROR: os.makedirs() threw exception: %d" % e.errno print "ERROR: Filename: %s" % e.filename print "ERROR: Error String: %s" % e.strerror
def loadMattes_button(): node = nuke.thisNode() first = nuke.thisNode()['first'].value() last = nuke.thisNode()['last'].value() beautyNode = nuke.toNode(nuke.tcl("topnode %s"%node.name())) versionPath = scanPath.getVersionPath(beautyNode['file'].value()) mattes = glob.glob(versionPath + "/*matte*") reads = [] for m in sorted(mattes): seqPath = scanPath.getSeqPathFromPassPath(m) with nuke.root(): r = nuke.createNode("Read", inpanel=False) r['file'].setValue(seqPath) r['first'].setValue(first) r['last'].setValue(last) reads.append(r) #make a grid of matte nodes ydx = 0 xdx = 0 idx = 0 xpos = node['xpos'].value() + 150 ypos = node['ypos'].value() for r in reads: print "idx:", xpos + 150*(xdx%3), ypos + 150*ydx r.setXYpos(xpos + 150*(xdx%3), ypos + 150*ydx) if xdx%3 == 2: ydx += 1 xdx += 1 idx += 1 with nuke.root(): makeBackdrop(reads)
def pv2_UIKnobChanged(): import nuke knobName = nuke.thisKnob().name() if knobName in [ 'pv2_getCameraList', 'pv2_cameraList', 'pv2_refreshEmitterList', 'pv2_addSelectedObj', 'pv2_emitterList', 'pv2_lockCardToDropDown' ]: workingNode = nuke.thisNode() workingNodeName = nuke.thisNode().name() if knobName == 'pv2_getCameraList': pv2_getCamerasPress(knobName, workingNode, workingNodeName) elif knobName == 'pv2_cameraList': pv2_setCam(knobName, workingNode, workingNodeName) elif knobName == 'pv2_refreshEmitterList': pv2_emitterListRefresh(knobName, workingNode, workingNodeName) elif knobName == 'pv2_addSelectedObj': pv2_addSelectedNodeToEmitters(knobName, workingNode, workingNodeName) elif knobName == 'pv2_emitterList': pv2_emitterObjSelect(knobName, workingNode, workingNodeName) elif knobName == 'pv2_lockCardToDropDown': pv2_cardLockTo(knobName, workingNode, workingNodeName)
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)
def onUserCreateCallback(): """ Populate defaults on creation of a DA_WriteMovieSlices node. """ if (nuke.thisNode().Class().endswith('DA_WriteMovieSlices')): nuke.thisNode().knob('first').setValue(nuke.root().knob('first_frame').value()) nuke.thisNode().knob('last').setValue(nuke.root().knob('last_frame').value())
def Solve2DTracker(_node): #Define Variables solve_method = int(nuke.thisNode().knob( "AssistType").getValue()) #0 = Local, 1 = Median, 2 = Average frameForRef = nuke.frame() StartFrame = int(nuke.thisNode().knob("InputFrom").value()) EndFrame = int(nuke.thisNode().knob("InputTo").value()) #Grap the number of trackers. n_tracks = int(_node["tracks"].toScript().split(" ")[3]) #Constants etc. numColumns = 31 colTrackX = 2 colTrackY = 3 RefPointList = [] for x in range(0, n_tracks): track_a = [ float(_node.knob("tracks").getValue(numColumns * x + colTrackX)), float(_node.knob("tracks").getValue(numColumns * x + colTrackY)) ] RefPointList.append(track_a) print "the ref point list:", RefPointList #Grap data from the camera tracker and convert it into a format we can use. PointData = GrabListData() print "--Initializing Main Loop--" trackIdx = 0 for item in RefPointList: temp_pos = item #-------------------------- #Resolve backwards [<-----] for frame in reversed(range(StartFrame, frameForRef)): RefPointList = GetAnimtionList(PointData[0], PointData[1], frame, True) _xy = CalculatePositionDelta(solve_method, RefPointList, temp_pos) temp_pos = [ temp_pos[0] + _xy[0], temp_pos[1] + _xy[1] ] #Add our calculated motion delta to the current position _node.knob("tracks").setValueAt(temp_pos[0], frame, numColumns * trackIdx + colTrackX) _node.knob("tracks").setValueAt(temp_pos[1], frame, numColumns * trackIdx + colTrackY) #------------------------- #Resolve forwards [----->] temp_pos = item for frame in range(frameForRef, EndFrame): RefPointList = GetAnimtionList(PointData[0], PointData[1], frame) _xy = CalculatePositionDelta(solve_method, RefPointList, temp_pos) temp_pos = [ temp_pos[0] + _xy[0], temp_pos[1] + _xy[1] ] #Add our calculated motion delta to the current position _node.knob("tracks").setValueAt(temp_pos[0], frame + 1, numColumns * trackIdx + colTrackX) _node.knob("tracks").setValueAt(temp_pos[1], frame + 1, numColumns * trackIdx + colTrackY) trackIdx += 1
def trackRangeForward(): node = nuke.thisNode() size = nuke.thisNode()['size'].value() rootLayer = node.knob("curves").rootLayer curve = node.knob("curves").getSelected()[0] start = int(nuke.root()['frame'].value()) end = int(nuke.root()['last_frame'].value()) task = nuke.ProgressTask('Baking camera from meta data in %s' % node.name()) for i in range(start, end): if task.isCancelled(): nuke.executeInMainThread("") break task.setMessage('processing frame %s' % i) task.setProgress(int((float(i - start) / float(end)) * 100)) temp = nuke.nodes.CurveTool() nuke.execute(temp, i, i) nuke.root()['frame'].setValue(i) for c, point in enumerate(curve): point.center.evaluate(i) pos = point.center.getPosition(i) print pos dx = nuke.sample(node, "red", pos.x, pos.y, size, size) dy = nuke.sample(node, "green", pos.x, pos.y, size, size) print c, dx, dy pos.x = pos.x + dx pos.y = pos.y + dy point.center.addPositionKey(i, pos) node['curves'].changed() nuke.delete(temp)
def from_script_to_precomp_path(): script_path_norm = os.path.normpath(nuke.root()["name"].value()) precomp_path = script_path_norm.replace("work", "renders") try: seq_name = precomp_path.split("\\")[8] shot_name = precomp_path.split("\\")[9] shot = seq_name + "_" + shot_name padding = 6 * "#" n = nuke.thisNode() name = n["fname"].value() extension = n["fformat"].value() if n["version_1"].value() == "": n["version_1"].setValue(str(1)) version = int(n["version_1"].value()) final_path = ("\\").join( precomp_path.split("\\") [:11]) + "\\" + "precomp" + "\\" + shot + "_" + name + "v" + str( version) + "\\" + shot + "_" + name + "v" + str( version) + "." + padding + "." + extension final_path1 = final_path.replace("\\", "/") nuke.thisNode()["file"].setValue(final_path1) nuke.thisNode()["version_1"].setValue(str(version + 1)) #nuke.message("you are welcome") return final_path1 except: nuke.message( "This guy will only work if you render from a BB Nuke Script, sorry." )
def showMeta(): metakeys = nuke.thisNode().metadata().keys() metavalues = nuke.thisNode().metadata().values() metaData = '' numKeys = len(metakeys) for i in range(numKeys): metaData = metaData + metakeys[i] + ': ' + str(metavalues[i]) + '\n' return metaData
def knobChanged(): if nuke.thisNode().Class() == 'Read': knob = nuke.thisNode().knob('file') pf = PublishedFile.fromPath(knob.value()) if pf: nkutils.updateReadWithElementInfo(nuke.thisNode(), Element.fromPk(pf.elementId), pf)
def deleteKnobs(pCount): n = nuke.thisNode() if pCount>0 : for i in range(int(pCount)): for j in ['p%03d_color' % (i + 1), 'p%03d' % (i + 1), 'p%03d_add' % (i + 1), 'p%03d_remove' % (i + 1)]: n.removeKnob(n[j]) for i in ['end_color', 'end', 'end_add', 'end_remove']: nuke.thisNode().removeKnob(n[i])
def writeNoOverwrite(): """ Automatically create directories in Write path if path doesn't exists. """ if nuke.thisNode()['no_overwrite'].value(): file_to_be_rendered = nuke.filename(nuke.thisNode(), nuke.REPLACE) if os.path.exists(file_to_be_rendered): msg = "File already exists: %s" % file_to_be_rendered try: raise RuntimeError(msg) except RuntimeError as e: print e
def lutCheck(): lutPath = outputPath(lutDestFolder) try: lutDest = nuke.getFilename('Select Latest LUT', default= lutPath) if isinstance(lutDest, str) is True: nuke.thisNode()['lutFile'].setValue(lutDest) except TypeError: pass
def lutCheck(): lutPath = outputPath(lutDestFolder) try: lutDest = nuke.getFilename('Select Latest LUT', default=lutPath) if isinstance(lutDest, str) is True: nuke.thisNode()['lutFile'].setValue(lutDest) except TypeError: pass
def decryptomatte_button(node): if "." in nuke.thisNode().fullName(): parent_name = ".".join(nuke.thisNode().fullName().split(".")[:-1]) with nuke.toNode(parent_name): decryptomatte_nodes([node], False) return with nuke.root(): decryptomatte_nodes([node], False)
def SolveCornerpin(_node): #Define Variables solve_method = int(nuke.thisNode().knob( "AssistType").getValue()) #0 = Local, 1 = Median, 2 = Average frameForRef = nuke.frame() StartFrame = int(nuke.thisNode().knob("InputFrom").value()) EndFrame = int(nuke.thisNode().knob("InputTo").value()) myNode = _node myKnob = myNode.knob("translate") myKnobCenter = myNode.knob("center") #Set some initial defaults init_pos = [0, 0] center_pos = [0, 0] temp_pos = [0, 0] _xy = [0, 0] #Read data from the knobs knobs = [myNode['to1'], myNode['to2'], myNode['to3'], myNode['to4']] RefPointList = [] for myKnob in knobs: init_pos = myKnob.getValue() RefPointList.append([init_pos, myKnob]) myKnob.clearAnimated() #Only if overwrite!! myKnob.setAnimated(0) myKnob.setAnimated(1) myKnob.setValueAt(init_pos[0], frameForRef, 0) myKnob.setValueAt(init_pos[1], frameForRef, 1) PointData = GrabListData() for item in RefPointList: temp_pos = item[0] myKnob = item[1] #-------------------------- #Resolve backwards [<-----] for frame in reversed(range(StartFrame, frameForRef)): RefPointList = GetAnimtionList(PointData[0], PointData[1], frame, True) _xy = CalculatePositionDelta(solve_method, RefPointList, temp_pos) temp_pos = [ temp_pos[0] + _xy[0], temp_pos[1] + _xy[1] ] #Add our calculated motion delta to the current position myKnob.setValueAt(temp_pos[0] - center_pos[0], frame, 0) #Add a keyframe with the values myKnob.setValueAt(temp_pos[1] - center_pos[1], frame, 1) #------------------------- #Resolve forwards [----->] temp_pos = item[0] for frame in range(frameForRef, EndFrame): RefPointList = GetAnimtionList(PointData[0], PointData[1], frame) _xy = CalculatePositionDelta(solve_method, RefPointList, temp_pos) temp_pos = [ temp_pos[0] + _xy[0], temp_pos[1] + _xy[1] ] #Add our calculated motion delta to the current position myKnob.setValueAt(temp_pos[0] - center_pos[0], frame + 1, 0) myKnob.setValueAt(temp_pos[1] - center_pos[1], frame + 1, 1)
def setupCameraOffset(): cam=nuke.thisNode()['camera'].value() cam=nuke.toNode(cam) thisNode=nuke.thisNode() if cam: with thisNode: fCam=nuke.toNode('offsetCam') for lk in linkKnobs: fCam[lk].setExpression('parent.parent.'+cam.name()+'.'+lk+"(frame+offset)")
def onCreate (self) : log ("onCreate %s" % nuke.thisNode().name()) node = nuke.thisNode() if (not node or type(node).__name__ != "Node") : return if (self.syncReadChanges and (str(node.Class()) == "Read" or str(node.Class()) == "Write")) : self.queueCommand ("self.viewReadsInRv([\"%s\"])" % node.name())
def cryptoUpdate(n=nuke.thisNode()): try: import cryptomatte_utilities as cu cu.update_cryptomatte_gizmo(nuke.thisNode(), True) except Exception, err: import traceback nuke.message( '''Unable to run Cryptomatte Gizmo update script. This script is necessary for the Cryptomatte system to work properly. %s''' % traceback.format_exc())
def update_pulldown(): """ Updating the node pulldown from the key values of the preference sheet... """ data = json_read(CC_DATA_FILE) nuke.thisNode()['TimeOfDay'].setValues(sorted(data.keys())) return 1
def createRead_button(path): first = nuke.thisNode()['first'].value() last = nuke.thisNode()['last'].value() with nuke.root(): r = nuke.createNode("Read", inpanel=False) r['file'].setValue(path) r['first'].setValue(first) r['last'].setValue(last)
def StickIT(): #Define Variables frameForRef = int(nuke.thisNode().knob("RefrenceFrameInput").value()) StartFrame = int(nuke.thisNode().knob("InputFrom").value()) EndFrame = int(nuke.thisNode().knob("InputTo").value()) if frameForRef > EndFrame or frameForRef < StartFrame: nuke.message("You must set a reference frame inside the active range") else: taskB = nuke.ProgressTask('Calculating Solve, please wait...') NodePin = nuke.toNode("si_sw") #change this to your tracker node! #Grap data from the camera tracker and convert it into a format we can use. PointData = GrabListData() #03: Get a set of reference points. This is the points we want to move. RefPointList = GetAnimtionList(PointData[0], PointData[1], frameForRef, False, True) #04: Go through all of the frames and triangulate best points to move the refpoints with. start = time.clock() finalAnimation = [] for item in RefPointList: zx = item[0][1] zy = item[0][2] tempAnimation = [] tempAnimation.append([frameForRef, item[0][1], item[0][2] ]) #Add a keyframe on the reference frame #Now start from the ref frame and move back for frame in reversed(range(StartFrame, frameForRef)): newOffset = GetNearestPoints( item[0], GetAnimtionList(PointData[0], PointData[1], frame, True)) tempAnimation.append([ frame, item[0][1] + newOffset[0], item[0][2] + newOffset[1] ]) item[0][1] = item[0][1] + newOffset[0] item[0][2] = item[0][2] + newOffset[1] #Now start from the ref frame and move forward for frame in range(frameForRef, EndFrame): newOffset = GetNearestPoints([0, zx, zy], GetAnimtionList( PointData[0], PointData[1], frame)) tempAnimation.append( [frame + 1, zx + newOffset[0], zy + newOffset[1]]) zx = zx + newOffset[0] zy = zy + newOffset[1] #Now add the animation created to the animation list finalAnimation.append(sorted(tempAnimation)) #print finalAnimation end = time.clock() print "%.2gs" % (end - start) CreateWarpPinPair(NodePin, finalAnimation, frameForRef) del (taskB)
def run(): node = nuke.thisNode().input(0) this_node = nuke.thisNode() samples = channels.field_samples(node=node, channels=['Z.red', 'rgba.alpha']) non_zero_samples = [z for z, a in samples if a != 0.0] min_z = min(non_zero_samples) max_z = max(non_zero_samples) this_node['near'].setValue(min_z) this_node['far'].setValue(max_z)
def onCreate(self): log("onCreate %s" % nuke.thisNode().name()) node = nuke.thisNode() if (not node or type(node).__name__ != "Node"): return if (self.syncReadChanges and (str(node.Class()) == "Read" or str(node.Class()) == "Write")): self.queueCommand("self.viewReadsInRv([\"%s\"])" % node.name())
def PlusRFW(): x = ((nuke.thisNode()['file']).value()) xps = ((nuke.thisNode()['xpos']).value()) yps = ((nuke.thisNode()['ypos']).value()) print "\nCreating read from " + x target = nuke.nodes.Read(file=x, xpos=xps + 100, ypos=yps) target['first'].setValue(int(nuke.root()['first_frame'].value())) target['origfirst'].setValue(int(nuke.root()['first_frame'].value())) target['last'].setValue(int(nuke.root()['last_frame'].value())) target['origlast'].setValue(int(nuke.root()['last_frame'].value()))
def modify_writegeo_node(): # Setting the file path file_path = ("[python {nuke.script_directory()}]/workspace/[python " "{os.path.splitext(os.path.basename(nuke.scriptName()))[0]}]_" "[python {nuke.thisNode().name()}].abc") nuke.thisNode()["file"].setValue(file_path) # Setting the file type nuke.thisNode()["file_type"].setValue("abc")
def updatedPassesVersion(): import re pattern = re.compile('v[0-9]{2,6}') result = pattern.findall(nuke.thisNode()['file'].value()) with nuke.thisNode(): for read in nuke.allNodes("Read"): path = read['file'].value() foundVersions = pattern.findall(path) for f in foundVersions: path = path.replace(f, result[0]) print "updated:", path read['file'].setValue(path)
def createWriteDir(): print "createDir" if not nuke.thisNode()['disable'].value(): file = nuke.filename(nuke.thisNode()) dir = os.path.dirname( file ) osdir = nuke.callbacks.filenameFilter( dir ) # cope with the directory existing already by ignoring that exception try: os.makedirs( osdir ) except OSError, e: if e.errno != errno.EEXIST: raise
def render(): this_node = nuke.thisNode() frameStart = int(this_node["frameStart"].getValue()) frameEnd = int(this_node["frameEnd"].getValue()) LOG.info('{}-{}'.format(frameStart, frameEnd)) notice_status = { 'RENDERTHREADS': 'multi process rendering is started', 'RR SUBMIT': 'scene was submit to RR', 'LOCAL': 'local rendering was started', 'NO JOB': 'process seems to be broken' } tmp_job = 'NO JOB' # RENDERTHREADS if this_node["submit"].getValue() == 0.0: from plugins.vuRenderThreads.plugin_nuke import plugin_nuke threads = int(this_node["threads"].getValue()) plugin_nuke.createThreads(frameStart, frameEnd, threads, [this_node.name()]) LOG.info("END : RENDERTHREADS : " + this_node["exrPath"].getValue()) tmp_job = 'RENDERTHREADS' # RENDERFARM elif this_node["submit"].getValue() == 1.0: import rrenderSubmit nuke.load('rrenderSubmit') rrenderSubmit.rrSubmit_Nuke_Node(this_node, frameStart, frameEnd) LOG.info("END : RRSUBMIT : " + this_node["exrPath"].getValue()) tmp_job = 'RR SUBMIT' # LOCAL else: try: nuke.execute(nuke.thisNode(), start=frameStart, end=frameEnd, incr=1) tmp_job = 'LOCAL' except: LOG.error("END : LOCAL : " + this_node["exrPath"].getValue(), exc_info=True) note = arNotice.Notice( title=os.path.basename(nuke.root().name()).split('.')[0], msg=notice_status[tmp_job], func=tmp_job, img='lbl/lblNuke131' if tmp_job != 'NO JOB' else 'lbl/lblWarning131', img_link='') arNotice.ArNotice(note)
def add_pt(): max_pts = int(nuke.thisNode().knob('Max PTS').value()) MAX_POINTS = int(nuke.thisNode().knob('Max Limit').value()) if max_pts >= MAX_POINTS: nuke.message('Maximum %i points' % (MAX_POINTS)) return node = nuke.thisNode() for name in ('pt', 'delete', 'insert'): node.knobs()[name + str(max_pts)].setVisible(True) node.knob('Max PTS').setValue(max_pts + 1)
def sendToAvconv(codec = 'dnxhd'): # Configuration renderSlug = False vcodec = { 'x264' : 'libx264 -pre baseline', 'dnxhd' : 'dnxhd -b 36M', } extension = '.mov' # set some variables fps = nuke.root().knob('fps').value() firstFrame = nuke.root().knob('first_frame').value() ss = 0 if renderSlug == True else secondsToStr(firstFrame/fps) # grabs the write node's file value and makes sure the path uses printf style filenames imgSeqPath = nukescripts.replaceHashes(nuke.filename(nuke.thisNode())) # generate mov path base, ext = os.path.splitext(os.path.basename(imgSeqPath)) movPath = os.path.dirname(os.path.dirname(imgSeqPath)) + '/' + re.sub('\.?%0\d+d$', '', base) + extension # make shell command enc = 'avconv -y -r %s -i \'%s\' -s \'hd1080\' -an -ss %s -vcodec %s -threads 0 \'%s\'' % (fps, imgSeqPath, ss, vcodec[codec], movPath) #print enc subprocess.Popen(shlex.split(enc), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def exportCDLButton(): """entry function from J_3Way on Export button push. Not yet implemented, please feel free. """ # Grab the parent nodes current file string cdlfilename=nuke.thisNode().knob("cdlfile").getValue() # Check file exists, ask if ok to overwrite then call relevant parsing modules dependant on selected # file's extension. if os.path.exists(cdlfilename) == True: cdlfileext=os.path.splitext(cdlfilename)[1].lstrip('.') # TODO: pop up panel to check overwrite ok if cdlfileext == 'ccc': # Simple colour correction container import J_Ops.J_3Way.parseCCC pass #J_Ops.J_3Way.exportCCC().parse(cdlfilename) elif cdlfileext == 'cdl': # Colour decision list import J_Ops.J_3Way.parseCDL pass #J_Ops.J_3Way.exportCDL().parse(cdlfilename) # Implement others here. else: nuke.message("Parser does not yet exist for filetype: " + cdlfileext + ".\n" "Check out the manual for information on implementing a parser inside the J_3Way framework") return
def onCreateCallback(self, *arg): n = nuke.thisNode() for a in arg:print a print 'wwwwwwww' print 'name', n.name() if n.Class() == "Write": n.setName(n.name())
def getUeConstant(): n = nuke.thisNode() spec = ueSpec.Spec(n.knob("proj").value(), n.knob("grp").value(), n.knob("asst").value(), n.knob("elclass").value(), n.knob("eltype").value(), n.knob("elname").value(), n.knob("vers").value()) if not spec.proj == "" and not spec.grp == "" and \ not spec.asst == "" and not spec.elclass == "" and \ not spec.eltype == "" and not spec.elname == "" and \ not spec.vers == "": versions = ueAssetUtils.getVersions(spec) if int(spec.vers) > len(versions): return v = versions[int(spec.vers)-1] if v: layerFile = os.path.join(v["path"], "%s.col" % v["file_path"]) if os.path.exists(layerFile): f = open(layerFile) palette = json.loads(layerfile.read()) f.close() if spec.elname in palette: colour.knob("color").setValue(palette[spec.elname][0], 0) colour.knob("color").setValue(palette[spec.elname][1], 1) colour.knob("color").setValue(palette[spec.elname][2], 2) colour.knob("color").setValue(1.0, 3)
def createWriteDirs(): """ Automatically create directories in Write path if path doesn't exists. """ f = nuke.filename(nuke.thisNode()) dirr = os.path.dirname(f) if not os.path.exists(dirr): osdir = nuke.callbacks.filenameFilter(dirr) os.makedirs(osdir)
def dpxNoAlpha(): """ Do not allow DPX files to be written with alpha """ n = nuke.thisNode() if nuke.filename(n).endswith("dpx"): n['channels'].setValue("rgb")
def renderDPX(node=nuke.thisNode()): verCheck(node) if verCheck(node) == "pass" and dpxPath(node) != 'break': # Assign values renDPX = nuke.toNode("Final_RenderNode") renderNode = node xPos = renderNode['xpos'].value() yPos = renderNode['ypos'].value() renFolder = os.path.dirname(dpxPath(node)) # If a previous render exists, asks the user whether they would like to delete the files if os.path.exists(renFolder): if nuke.ask("Would you like to remove the previously rendered files?"): shutil.rmtree(renFolder) # Render the comp """ This part needs a callback to stop the function if the render is canceled """ renDPX['Render'].execute() # Create the read node nuke.root().begin() if renderNode.input(1): readNode = renderNode.input(1) readNode['file'].fromUserText(dpxPath(node) + ".####.exr" + ' ' + str(nuke.root().firstFrame() - startFrame) + '-' + str(nuke.root().lastFrame())) readNode['reload'].execute() nuke.root().end() else: readNode = nuke.nodes.Read(colorspace = dpxImportColor) readNode['file'].fromUserText(dpxPath(node) + ".####.exr" + ' ' + str(nuke.root().firstFrame() - startFrame) + '-' + str(nuke.root().lastFrame())) # Place the read node readNode.setXYpos(int(xPos - 170), int(yPos - 36)) # nuke.autoplaceSnap(readNode) renderNode.setInput(1, readNode) nuke.root().end() else: pass
def setDefaultReadValues(): node = nuke.thisNode() if node.Class() in ['Read', 'Group']: if node.knob('before'): node.knob('before').setValue('loop') if node.knob('after'): node.knob('after').setValue('loop')
def viewerSettings(): """set some default values on the viewer""" node = nuke.thisNode() node.knob('near').setValue(100) node.knob('far').setValue(500000) node.knob('grid_display').setValue(False) node.knob('gl_lighting').setValue(1)
def attach_file_operations(*args): n = nuke.thisNode() if "fileops" not in n.knobs().keys(): n.addKnob(nuke.Text_Knob("fileops", "File Operations")) n.addKnob(nuke.PyScript_Knob("copyBtn", "Copy", "nuke.fileop(0)")) n.addKnob(nuke.PyScript_Knob("moveBtn", "Move", "nuke.fileop(1)")) return n
def hkSetNodes () : node = nuke.thisNode() #Get path from node filepath = hkGetPath ( node ) if node.Class () == "Read": path, rang = getFileSeq ( filepath ).split() first,last = rang.split ( '-' ) node['file'].setValue( path ) node['first'].setValue( int ( first ) ) node['last'].setValue( int ( last ) ) elif node.Class () == "Write": node['file'].setValue ( filepath ) node['first'].setValue( 1 ) node['last'].setValue( 1 ) elif node.Class () == "ReadGeo2": path, rang = getFileSeq ( filepath ).split() first,last = rang.split ( '-' ) node['geofile'].setValue( path ) elif node.Class () == "Camera2": path, rang = getFileSeq ( filepath ).split() first,last = rang.split ( '-' ) node['file'].setValue( path )
def getReadGeoPath(): n = nuke.thisNode() spec = ueSpec.Spec(n.knob("proj").value(), n.knob("grp").value(), n.knob("asst").value(), n.knob("elclass").value(), n.knob("eltype").value(), n.knob("elname").value(), n.knob("vers").value()) p = os.path.join(os.getenv("UE_PATH"), "lib", "placeholders", "nuke.obj") if not spec.proj == "" and not spec.grp == "" and \ not spec.asst == "" and not spec.elclass == "" and \ not spec.eltype == "" and not spec.elname == "" and \ not spec.vers == "": versions = ueAssetUtils.getVersions(spec) if int(spec.vers) > len(versions): return p v = versions[int(spec.vers)-1] if v: files = glob.glob(os.path.join(v["path"], v["file_name"]+"*.obj")) if len(files) < 1: return p ext = files[0].split(".")[-1] if len(files) == 1: p = os.path.join(v["path"], v["file_name"]+"."+ext) else: p = os.path.join(v["path"], v["file_name"]+".%04d."+ext) # p = os.path.join(v["path"], elpassDir, # v["file_name"]+elpassFile+".%04d."+ext) return p
def setBoundingBox(): ''' Sets the bounding box dimensions for the particles at the current frame Applies an offset to the particles to keep them everything centered on origin ''' # Calculate the particle bounds pos_node = nuke.toNode('Position_Checker') x = getMinMax( pos_node, 'rgba.red' ) y = getMinMax( pos_node, 'rgba.green' ) z = getMinMax( pos_node, 'rgba.blue' ) cube = nuke.toNode('BoundingBox') # Centerpoint of Bounds mid_x = ( x[1] - x[0] ) / 2.0 + x[0] mid_y = ( y[1] - y[0] ) / 2.0 + y[0] mid_z = ( z[1] - z[0] ) / 2.0 + z[0] # Set cube size centered on origin cube['cube'].setValue( [ x[0] - mid_x, y[0] - mid_y, z[0] - mid_z, x[1] - mid_x, y[1] - mid_y, z[1] - mid_z ] ) if nuke.thisNode()['center_pivot'].value(): # Grade offset to particle positions to center on origin offset = nuke.toNode('Offset') offset['value'].setValue( -mid_x, 0 ) offset['value'].setValue( -mid_y, 1 ) offset['value'].setValue( -mid_z, 2 )
def createWriteDir(): ''' This function creates a write directory automatically so the user does not have to do it. Supports stereo notation with %v and %V ''' import nuke, os curnode = nuke.thisNode() originalFileName = nuke.filename(curnode) allViews = curnode.knob('views').value() # look for views in the write node allViews = allViews.split() # split them out outputFilename = [] for view in allViews: fileName = originalFileName # check for the standard nuke view parameters if '%v' in fileName : outputFilename.append(fileName.replace('%v',view[:1])) if '%V' in fileName : outputFilename.append(fileName.replace('%V',view)) print outputFilename if len(outputFilename) < 1: outputFilename.append(originalFileName) for fileName in outputFilename: dir = os.path.dirname( fileName ) osdir = nuke.callbacks.filenameFilter( dir ) if not os.path.exists( osdir ): os.makedirs( osdir ) print 'Created : %s' % (osdir)
def texConvert(): """ converts an exr to tex """ node = nuke.thisNode() convert = node.knob('texConvertCheckbox').value() if convert == True: currentFrame = nuke.frame() fileIn = node.knob('file').getValue().replace('.####.','.%s.' %currentFrame).replace('.%4d.','.%s.' %currentFrame) ext = fileIn.split('.')[-1] fileOut = fileIn.replace('/%s/' %ext,'/tex/').replace('.%s' %ext,'.tex').replace('.####.','.%s.' %currentFrame).replace('.%4d.','.%s.' %currentFrame) mode = node.knob('mode').value() pattern = node.knob('pattern').value() format = node.knob('format').value() resize = node.knob('resize').value() filterValue = node.knob('filter').value() mipfilter = node.knob('mipfilter').value() otherFlags = node.knob('otherFlags').value() #if resize == 'none': # command = 'txmake -verbose -float -pattern %s -mode %s -resize %s %s %s %s\n' %(pattern, format, mode, resize, otherFlags, fileIn, fileOut) #else: command = 'txmake -verbose -float -pattern %s -mode %s -format %s -resize %s -filter %s -mipfilter %s %s %s %s\n' %(pattern, mode, format, resize, filterValue, mipfilter, otherFlags, fileIn, fileOut) print '> converting tex...' print command popObj = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = popObj.communicate() print out[0]
def changeEverySelectedKnobs(): node = nuke.thisNode() if node not in nuke.Root().nodes(): # there are many nodes that we can't see, cull them. return if node.Class() == "BackdropNode": # I will not treat Backdrop as a Normal Node. return knob = nuke.thisKnob() kname, kval = knob.name(), knob.value() if kname in [ "xpos", "ypos", "selected", "name", "hidePanel", "showPanel", "label", "scene_view", "note_font_size", "inputChange", "bdwidth", "bdheight", ]: return print("command node : {0}".format(node.name())) print("{0} : {1}".format(kname, kval)) for n in nuke.selectedNodes(): n[kname].setValue(kval)
def refreshTab(): node = nuke.thisNode() knob = nuke.thisKnob() if knob: # to do when the file knob is changed if knob.name(): texExists, texFile = checkTex() if texExists and texFile and node['texConvertCheckbox'].getValue(): text = 'Tex file found - will be replaced' node.knob('checkTex').setValue("<FONT COLOR=\"green\">"+text+"<\FONT>") if texExists and texFile and not node['texConvertCheckbox'].getValue(): text = 'Tex file found' node.knob('checkTex').setValue("<FONT COLOR=\"green\">"+text+"<\FONT>") if not texExists and texFile: text = 'Tex file NOT found' node.knob('checkTex').setValue("<FONT COLOR=\"red\">"+text+"<\FONT>") if not texExists and texFile and node['texConvertCheckbox'].getValue(): text = 'Tex file NOT found - will be created' node.knob('checkTex').setValue("<FONT COLOR=\"red\">"+text+"<\FONT>") if not texExists and not texFile: text = 'Tex file NOT found - please fill the file knob' node.knob('checkTex').setValue("<FONT COLOR=\"red\">"+text+"<\FONT>") else: text = '[file not set]' node.knob('checkTex').setValue("<FONT COLOR=\"black\">"+text+"<\FONT>")
def removeItem(id, dicValues,pCount): n = nuke.thisNode() dicValues.pop(id-1) n['pCounter'].setValue(int(pCount-1)) if n['pCounter'].value() < 0: n['pCounter'].setValue(0) return dicValues
def knobChanged(): n = nuke.thisNode() k = nuke.thisKnob() if k.name() == 'opt_knob': if k.value() == 'text': n.begin() nuke.toNode('watermark_image')['file'].setValue('') n.end() n['w_text_knob'].setEnabled(True) n['wm_file'].setEnabled(False) n['tiles'].setValue(7.4) n['translate'].setValue([nuke.Root().width()/2, -nuke.Root().height()/2]) n['rotate'].setValue(34) n['scale'].setValue(6.3) elif k.value() == 'image': n.begin() nuke.toNode('watermark_image')['file'].fromScript('[value parent.wm_file]') n.end() n['w_text_knob'].setEnabled(False) n['wm_file'].setEnabled(True) n['tiles'].setValue(7.4) n['translate'].setValue([0, 0]) n['rotate'].setValue(0) n['scale'].setValue(1)
def encryptomatte_add_manifest_id(deserialize = False): node = nuke.thisNode() parent = nuke.thisParent() name = parent.knob('matteName').value() id_hex = parent.knob('idHex').value() manifest_key = parent.knob('manifestKey').value() metadata = node.metadata() manifest = metadata.get(manifest_key + 'manifest', "{}") if deserialize: import json d = json.loads(manifest) d[name] = hex_id new_manifest = json.dumps(d) return new_manifest else: last_item = '"{name}":"{id_hex}"'.format(name=name, id_hex=id_hex) last_item += '}' last_bracket_pos = manifest.rfind('}') existing_items = manifest[:last_bracket_pos].rstrip() if not existing_items.endswith(',') and not existing_items.endswith('{'): return existing_items + ',' + last_item else: return existing_items + last_item
def output_to_h264(write_node=None): """an after render function which converts the input to h264 """ # get the file name if not write_node: write_node = nuke.thisNode() file_full_path = nuke.filename(write_node) # add the _h264 extension to the filename file_name = os.path.basename(file_full_path) path = file_full_path[:-len(file_name)] file_name_wo_ext, ext = os.path.splitext(file_name) # split any '.' (ex: a.%04d -> [a, %04d]) file_name_wo_ext = file_name_wo_ext.split('.')[0] # add _h264 output_file_name = file_name_wo_ext + '_h264.mov' output_full_path = os.path.join(path, output_file_name) # TODO: if it is a sequence of images rename them by creating temp soft # links to each frame and then use the sequence format in ffmpeg # run ffmpeg in a seperate thread t = threading.Timer( 1.0, convert_to_h264, args=[file_full_path, output_full_path] ) t.start()