def gdReadSel(): #Filter out selected Read and NoOp (GLOBAL_DIRECTORY) nodes rNode = nuke.selectedNodes("Read") gdNode = nuke.selectedNodes("NoOp") #Begin Association... if not rNode or not gdNode: #If no Read or NoOp nodes are selected, error message nuke.message( "Must select at least one GLOBAL_DIRECTORY \nnode and one Read node!" ) elif "GLOBAL_DIRECTORY" not in gdNode[0]['name'].value(): #If no NoOp node selected is a "GLOBAL_DIRECTORY" node, error message nuke.message( "Must select an existing \nGLOBAL_DIRECTORY node!" ) elif len(gdNode) > 1: #If more than one "GLOBAL_DIRECTORY" node is selected, error message nuke.message( "Must select only one \nGLOBAL_DIRECTORY node!" ) else: #Retrieve GLOBAL_DIRECTORY directory and name, then create injection code for Read file directory gdDir = gdNode[0]['projDir'].value() gdName = gdNode[0]['name'].value() gdInject = "[value " + gdName + ".projDir]" if gdDir == "": #If the GLOBAL_DIRECTORY directory is empty, error message nuke.message( "GLOBAL_DIRECTORY node directory is empty.\n\nCannot associate Read files with no directory specified." ) else: #If no errors, send information to _associateFiles to generate connections and show progress numNode = len( rNode ) fixFiles= associateFiles( gdDir, gdName, gdInject, rNode, numNode )
def nk_align_vert(): """ V Align """ positions = [t.ypos() for t in nuke.selectedNodes()] mid = (min(positions)+max(positions))/2 [t.setYpos(mid) for t in nuke.selectedNodes()]
def pStamp(nodes,posX,posY): #create postage stamp inputNodes = [] inputNodes.append(nodes) for a in inputNodes: if a.Class()=='Read': namer = a.knob('file').getValue() col=2570627072 else: namer=a.knob('name').getValue() col=2993684480 namer= namer.split('/')[-1].split('.')[0] namer=namer+'_001' nukescripts.clear_selection_recursive() nuke.createNode('PostageStamp').setXYpos(posX,posY) for i in nuke.selectedNodes(): i.setInput(0,a) i['tile_color'].setValue(col) verList=[] for i in nuke.allNodes(): if i.Class()=='PostageStamp': if i.knob('name').getValue()[:-2]==namer[:-2]: nVer = i.knob('name').getValue()[-1] verList.append(nVer) while namer[-1] in verList: ver=int(namer[-1]) ver=str(int(ver)+1) namer=namer[:-1]+ver for a in nuke.selectedNodes(): if a.Class()=='PostageStamp': a.knob('hide_input').setValue(True) a.knob('name').setValue(namer) nukescripts.clear_selection_recursive() return namer
def bakeExpressions(startFrame = nuke.root().firstFrame(), endFrame = nuke.root().lastFrame()): ''' Bakes all expression-driven knobs/knob components to keyframes over given input range To Do: - Add support for multiple views ''' if not nuke.selectedNodes(): return for node in nuke.selectedNodes(): for knob in node.knobs().values(): if knob.hasExpression(): if knob.singleValue(): aSize = 1 else: aSize = knob.arraySize() for index in range(aSize): if knob.hasExpression(index): anim = knob.animation(index) f = startFrame while f <= endFrame: knob.setValueAt(anim.evaluate(f), f, index) f += 1 knob.setExpression("curve", index) if knob.animation(index).constant(): knob.clearAnimated(index)
def sb_onOff(): sn = nuke.selectedNodes() if len(sn) == 0: nuke.message("Select a node.") return frame = int(nuke.frame()) p = nuke.Panel( "sb_onoff" ) p.addSingleLineInput( "first frame:", "") p.addSingleLineInput( "last frame:", "") result = p.show() if result: ff = int(p.value("first frame:")) lf = int(p.value("last frame:")) for i in nuke.selectedNodes(): m = nuke.createNode("Multiply", inpanel = False) m["channels"].setValue("all") val = m["value"] val.setAnimated() val.setValueAt(1, ff) val.setValueAt(1, lf) val.setValueAt(0, ff-1) val.setValueAt(0, lf+1) m.setInput(0, i) m["xpos"].setValue(i["xpos"].value()) m["ypos"].setValue(i["ypos"].value() + 75) m["selected"].setValue(False) i["selected"].setValue(False)
def PasteToSelected(): # put selection in variable and find out if nodes are valid original_selection = nuke.selectedNodes() for node in original_selection: if node.Class() == "Viewer" or node.name() == "VIEWER_INPUT": node.knob("selected").setValue(False) valid_selection = nuke.selectedNodes() for a in nuke.allNodes(): a.knob("selected").setValue(False) # create dict for new nodes so they can be selected later new_nodes = [] # go through selection and paste from clipboard to each for b in valid_selection: b.knob("selected").setValue(True) nuke.nodePaste(nukescripts.cut_paste_file()) new_nodes += nuke.selectedNodes() for pasted in nuke.selectedNodes(): pasted.knob("selected").setValue(False) # re-select original nodes for c in new_nodes: c.knob("selected").setValue(True) if len(valid_selection) is not len(original_selection): nuke.message("Some Viewer or VIEWER_LUT nodes were ignored. Rad.")
def sb_revealInFileBrowser(): n = nuke.selectedNodes("Read") + nuke.selectedNodes("Write") if len(n) == 0: nuke.message("Select at least one Read or Write node.") return if len(n) > 3: makeSure = nuke.ask("Are you sure you want to open {0} file browser windows?".format(len(n))) if not makeSure: return for i in n: try: getPath = i["file"].evaluate().split("/")[:-1] folderPath = "/".join(getPath) if platform.system() == "Windows": subprocess.Popen('explorer "{0}"'.format(folderPath.replace("/", "\\"))) elif platform.system() == "Darwin": subprocess.Popen(["open", folderPath]) elif platform.system() == "Linux": subprocess.Popen(["xdg-open", folderPath]) except: continue
def autoShuffleReads(nodes): import re import nuke nuke.Undo().name("organize and split") nuke.Undo().begin() readList = [] yPosAvg = 0 xPosAvg = 0 count = 0 try: nodes # does a exist in the current namespace except NameError: nodes = nuke.selectedNodes() for curNode in nodes: if curNode.Class() == "Read": readList.append({"file": nuke.filename(curNode), "node": curNode}) yPosAvg = yPosAvg + curNode["ypos"].value() xPosAvg = xPosAvg + curNode["xpos"].value() count += 1 readListSorted = sorted(readList, key=lambda k: k["file"]) xPosAvg = int(xPosAvg / count) yPosAvg = int(yPosAvg / count) count = 0 for readNode in readListSorted: readNode["node"]["xpos"].setValue(xPosAvg - 110 * count) readNode["node"]["ypos"].setValue(yPosAvg) readNode["node"]["selected"].setValue(True) count += 1 for n in nuke.selectedNodes(): n.autoplace() prevNode = nuke.nodes.Dot() originalDot = prevNode for curNode in nuke.selectedNodes(): if curNode.Class() == "Read": count += 1 filename = nuke.filename(curNode) passName = filename.split(".")[1] if re.match(r"^[A-Za-z0-9_]+$", passName): newLayer = nuke.Layer(passName, [passName + ".red", passName + ".green", passName + ".blue"]) shuffle = nuke.nodes.Shuffle(label=passName, inputs=[curNode]) shuffle["out"].setValue(passName) dotNode = nuke.nodes.Dot(inputs=[shuffle]) copyNode = nuke.nodes.Copy(inputs=[prevNode, dotNode], channels=passName, selected=True) prevNode = copyNode else: masterNode = curNode if count % 2 == 0: curNode["ypos"].setValue(curNode["ypos"].value() + 110) originalDot.setInput(0, masterNode) backdrop = nukescripts.autoBackdrop() backdrop.knob("tile_color").setValue(2139062271) nuke.Undo().end()
def LabelShuffle(): if nuke.selectedNodes() != []: selected = nuke.selectedNodes("Shuffle") if selected != []: for r in selected: inv = r.knob("in").value() r.knob("label").setValue(inv) else: nuke.message("Shuffle node(s) not found in selection") else: nuke.message("No nodes selected")
def _smart_nodelist_expand(nodes=None): """Be smart about filling in a list of nodes. If no nodes are specified, try the selected nodes. If no nodes are selected, use all nodes in the script.""" if nodes is None: if len(nuke.selectedNodes()) != 0: nodes = nuke.selectedNodes() else: nodes = nuke.allNodes() # Recursively find nodes in groups nodes = _all_nodes_in_groups(nodes) return nodes
def pasteToSelected(): if not nuke.selectedNodes(): nuke.nodePaste('%clipboard%') return selection = nuke.selectedNodes() for node in selection: toggleSelection(node) for node in selection: node['selected'].setValue(True) nuke.nodePaste('%clipboard%') node['selected'].setValue(False) for node in selection: toggleSelection(node)
def __init__(self): if not nuke.selectedNodes(): nuke.nodePaste('%clipboard%') return selection = nuke.selectedNodes() for self.node in selection: self.toggleSelection() for self.node in selection: self.node['selected'].setValue(1) nuke.nodePaste('%clipboard%') self.node['selected'].setValue(0) for self.node in selection: self.toggleSelection()
def getWriteNodes(): # Check Selection if len(nuke.selectedNodes()) == 0 : nodes = nuke.allNodes() else: nodes = nuke.selectedNodes() writeNodes = [] for oNode in nodes: if oNode.Class() in WRITENODES and (False == oNode["disable"].value()): writeNodes += [oNode.name()] return writeNodes
def addLocal(): # path variables repo = '/mnt/karramba' home = '/home/tfx/job.local' # copies footage to local machine readList = [node.knob('file').value() for node in nuke.selectedNodes('Read')] for path in readList: fileDirList =[path.rsplit(os.sep,1)[0] + os.sep + img for img in os.listdir(path.rsplit(os.sep,1)[0]) if img[:len(path.rsplit(os.sep,1)[1].split('%')[0])] == path.rsplit(os.sep,1)[1].split('%')[0]] for img in fileDirList: newPath = home + img.rsplit(os.sep, 1)[0].split(repo)[-1] + os.sep if not os.path.exists(newPath): os.makedirs(newPath) shutil.copy(img, newPath) #creates new read nodes and controller to switch controller between local and network for node in nuke.selectedNodes('Read'): node.setSelected(True) sw = nuke.createNode('Switch', inpanel=False) sw.setSelected(False) sw.knob('which').setExpression('locController.location') node.setSelected(True) nuke.nodeCopy('%context%') c = nuke.nodePaste('%context%') sw.setInput(0, c) sw.setInput(1, node) node.setYpos(node.ypos()-90) c.setYpos(node.ypos()) c.setXpos(node.xpos()-150) c.setName(c.name() + 'Local') node.setName(node.name() + 'Network') c.knob('file').setValue(home + node.knob('file').value().split(repo)[-1]) node.setSelected(False) c.setSelected(False)
def multiselectCallback(): global multiSelect if multiSelect: n = nuke.thisNode() k = nuke.thisKnob() nodes = nuke.selectedNodes() dontbother=['selected','xpos','ypos'] # might need to add to this list if (not(k.name() in dontbother) and (n in nodes)): # node is selected, and knob is not in ignored list # this is nice for debugging: # print str(k.name()) +' : '+ str(k.value()) for node in nuke.selectedNodes(): if node is not n: if k.name() in node.knobs().keys(): node.knob(k.name()).setValue(k.value())
def F_AlignUY(): if len(nuke.selectedNodes()) > 1: nodeList = [] for n in nuke.selectedNodes(): if n.Class() != "BackdropNode" and n.Class() != "Viewer": nodeList.append(n) if len(nodeList) > 1: sn = len(nodeList) nodeList.sort(F_CmpY) underY = nodeList[sn-1].ypos() + nodeList[sn-1].screenHeight() / 2 for n in range(0, sn): sizeGap = nodeList[n].screenHeight() / 2 nodeList[n].setYpos(underY - sizeGap)
def F_AlignRX(): if len(nuke.selectedNodes()) > 1: nodeList = [] for n in nuke.selectedNodes(): if n.Class() != "BackdropNode" and n.Class() != "Viewer": nodeList.append(n) if len(nodeList) > 1: sn = len(nodeList) nodeList.sort(F_CmpX) rightX = nodeList[sn-1].xpos() + nodeList[sn-1].screenWidth() / 2 for n in range(0, sn): sizeGap = nodeList[n].screenWidth() / 2 nodeList[n].setXpos(rightX - sizeGap)
def autoBackdropCustom(): # Copyright (c) 2009 The Foundry Visionmongers Ltd. All Rights Reserved. ''' Automatically puts a backdrop behind the selected nodes. The backdrop will be just big enough to fit all the select nodes in, with room at the top for some text in a large font. ''' selNodes = nuke.selectedNodes() if not selNodes: return nuke.nodes.BackdropNode() # Calculate bounds for the backdrop node. bdX = min([node.xpos() for node in selNodes]) bdY = min([node.ypos() for node in selNodes]) bdW = max([node.xpos() + node.screenWidth() for node in selNodes]) - bdX bdH = max([node.ypos() + node.screenHeight() for node in selNodes]) - bdY # Expand the bounds to leave a little border. Elements are offsets for left, top, right and bottom edges respectively left, top, right, bottom = (-10, -80, 10, 10) bdX += left bdY += top bdW += (right - left) bdH += (bottom - top) n = nuke.nodes.BackdropNode(xpos = bdX, bdwidth = bdW, ypos = bdY, bdheight = bdH, tile_color = int((random.random()*(16 - 10))) + 10, note_font_size=42) '''Code Above is written by The Foundry'''
def __init__(self): nukescripts.PythonPanel.__init__(self, 'Backdrop Manager', 'com.ohufx.Backdrop') # DEFINE DICTIONARIES/LIST self.elements = [] self.key = {} self.fontset = {} self.fontsize = {} self.fontcol = {} self.nodes = False # CREATE KNOBS self.srcNodes = { 'All': nuke.allNodes(), 'Selected': nuke.selectedNodes() } self.nodesChoice = nuke.Enumeration_Knob( 'nodes', 'Source Nodes', ['All', 'Selected'] ) self.label = nuke.Enumeration_Knob( 'backdrop', 'Backdrop Label', self.comeon() ) self.cv = nuke.Multiline_Eval_String_Knob( 'newlabel', 'New Label' ) self.warning = nuke.Text_Knob( 'warning', '<span style="color:red">No Backdrops Selected</span>' ) self.warning.setVisible( False ) self.warning.clearFlag( nuke.STARTLINE ) self.size = nuke.Int_Knob( 'fontsize', '' ) self.size.setValue( 20 ) self.size.clearFlag( nuke.STARTLINE ) self.size.setValue( self.fontsize[self.key[self.label.value()]] ) self.font = nuke.Font_Knob( 'font', 'Font' ) self.font.setValue(self.fontset[self.key[ self.label.value()]] ) self.fontcolor = nuke.ColorChip_Knob( 'fontcolor', 'color' ) self.fontcolor.setValue(self.fontcol[ self.key[self.label.value()]] ) self.backcolor = nuke.ColorChip_Knob( 'backcolor', 'backcolor' ) self.backcolor.setValue( self.key[self.key[self.label.value()]] ) self.cv.setValue( self.label.value() ) bnode = self.key[self.label.value()] if self.cv.value() == bnode.knob( 'name' ).value(): self.cv.setValue( '' ) # ADD KNOBS for k in ( self.nodesChoice, self.label, self.warning, self.cv, self.backcolor, self.font, self.size, self.fontcolor): self.addKnob( k )
def replaceGizmoWithGroup(): """ replace the selected gizmos with the corresponding groups """ sel = nuke.selectedNodes() if len(sel) == 1: gizmoToGroup(nuke.selectedNodes()) elif len(sel) > 1: for n in sel: nukescripts.clear_selection_recursive() if "gizmo" in n.Class(): n.setSelected(True) gizmoToGroup(nuke.selectedNodes()) else: pass
def readFromWrite(): nodes = nuke.selectedNodes() if len(nodes) < 1: print('No nodes selected') else : foundWrites = False writeNodes = [] for node in nodes: if node.Class() == 'Write': writeNodes.append(node) foundWrites = True if foundWrites == True: # we found some writes for node in writeNodes: nodeRead = nuke.nodes.Read() # create a read node nodeRead['file'].setValue(nuke.filename(node)) #set the filename if node['use_limit'].getValue() == 1: #check to see if there is a range and set the values in the read node nodeRead['first'].setValue(int(node['first'].getValue())) nodeRead['last'].setValue(int(node['last'].getValue())) else: # no range on the write? take a stab at using the range from the script value nodeRead['first'].setValue(int(nuke.root()['first_frame'].getValue())) nodeRead['last'].setValue(int(nuke.root()['last_frame'].getValue())) nodeRead.setXpos(node.xpos()) #let's set the position nodeRead.setYpos(node.ypos()+50) nodeRead['premultiplied'].setValue(node['premultiplied'].getValue()) # use premult if checked nodeRead['raw'].setValue(node['raw'].getValue()) # use raw if checked else: print('No Writes Found in Node Selection')
def openTerminal(): """open a gnome-terminal from a read or a write node in selection""" nodes = nuke.selectedNodes() if nodes: for node in nodes: if node.Class() in ['Read', 'Write']: if 'views' in node.knobs().keys(): path = os.path.dirname(node['file'].evaluate()) if os.path.exists(path): view = node['views'].value().split(' ')[0] command = ['gnome-terminal', '--working-directory=%s/' % path] print runCommand(command) #subprocess.Popen(['gnome-terminal', '--working-directory=%s/' % path]) else: raise UserWarning("No such file or directory") else: path = os.path.dirname(node['file'].evaluate()) if os.path.exists(path): command = ['gnome-terminal', '--working-directory=%s/' % path] print runCommand(command) #subprocess.Popen(['gnome-terminal', '--working-directory=%s/' % path]) else: raise UserWarning("No such file or directory") else: raise UserWarning("No node to explore") else: raise UserWarning("No node to explore")
def set_to_sequence(): sl_nodes = nuke.selectedNodes() sl = nuke.Panel('Set Sequence') sl.addSingleLineInput('Start', '') sl.addSingleLineInput('End', '') ret = sl.show() if not ret: return False start = sl.value('Start') if ('.' in start): i_start = string.atof(start) else: i_start = string.atoi(start) end = sl.value("End") if ('.' in end): i_end = string.atof(end) else: i_end = string.atoi(end) for node in sl_nodes: source_file = node['file'].getValue() dir_name = os.path.dirname(source_file) base_name = os.path.basename(source_file) name_list = base_name.split('.') name_list[-2] = '#' * len(name_list[-2]) new_name = os.path.join(dir_name, '.'.join(name_list)) node['file'].setValue(new_name.replace('\\', '/')) node['first'].setValue(i_start) node['last'].setValue(i_end) node['on_error'].setValue(1) return True
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 reloadReadNodes(): """hit the reload button if possible""" for node in nuke.selectedNodes(): try: node['reload'].execute() except: pass
def comeon(self): # SHOW ERROR IF NO BACKDROPS FOUND if any(n.Class() == 'BackdropNode' for n in nuke.allNodes()): pass else: nuke.message('No Backdrops Found!') raise KeyError, 'No Backdrops Found!' # CHECKING IF ANY OF THE SELECTED NODES ARE BACKDROPS for b in nuke.selectedNodes(): if b.Class() == 'BackdropNode': self.nodes = True # RESETS LIST BY DELETING THE CURRENT ONE del self.elements[:] for a in self.srcNodes[self.nodesChoice.value()]: if a.Class() == 'BackdropNode': # IF BACKDROP IS BLANK THEN TEMPORARILY CHANGE IT TO ITS NAME if a.knob('label').value() == '': a.knob('label').setValue(a.knob('name').value()) # ALLOCATING BACKDROP VALUES TO DICTIONARIES self.key[a.knob('label').value()] = a self.key[a] = a.knob('tile_color').value() self.fontset[a] = a.knob('note_font').value() self.fontsize[a] = int(a.knob('note_font_size').value()) self.fontcol[a] = a.knob('note_font_color').value() g = a.knob('label').value() self.elements.append(g) # CHANGE TEMPORARILY BACKDROPS BACK TO BLANK for b in self.srcNodes[self.nodesChoice.value()]: if b.knob('label').value() == b.knob('name').value(): b.knob('label').setValue('') return self.elements
def alignHorizontally(): yresult = None for n in nuke.selectedNodes(): if yresult is None: yresult = n.ypos() else: n.setYpos(yresult)
def shakeClone(): EXCLUSION_LIST = ["xpos","ypos","help","hide_input","note_font_color","onCreate","updateUI","knobChanged","note_font","tile_color","selected","autolabel","process_mask","label","onDestroy","inject","indicators","maskFrom","maskChannelMask","maskChannelInput","Mask","postage_stamp", "postage_stamp_frame","disable","maskChannelMask", "panel", "maskFromFlag","name","cached","fringe", "maskChannelInput" , "note_font_size" , "filter", "gl_color","transform", "dope_sheet"] originals = nuke.selectedNodes() [ n['selected'].setValue(False) for n in nuke.allNodes() ] for original in originals: new = nuke.createNode(original.Class()) for i in original.knobs(): if i not in EXCLUSION_LIST: # Try to set the expression on the knob new.knob(i).setExpression("%s.%s" % (original.name(), original.knob(i).name())) # This will fail if the knob is an Array Knob...use setSingleValue to compensate # Thanks Hugh! if isinstance(new.knob(i), nuke.Array_Knob): new.knob(i).setSingleValue(original.knob(i).singleValue()) # This will fail if the knob is a String Knob...use a TCL expression link to compensate # Thanks Michael! elif isinstance(new.knob(i), nuke.String_Knob): new.knob(i).setValue("[value %s.%s]" % (original.name(), original.knob(i).name())) new['selected'].setValue(False) [ n['selected'].setValue(True) for n in originals ]
def swapOutNode(self, targetNode, newNode): ''' Mostly mimics the Ctrl + Shift + drag-and-drop node functionality in Nuke. 'targetNode': The node (or node name) to be replaced. 'newNode': The node (or node name) that will replace it. ''' if isinstance(targetNode, basestring): targetNode = nuke.toNode(targetNode) if isinstance(newNode, basestring): newNode = nuke.toNode(newNode) if not (isinstance(targetNode, nuke.Node) and isinstance(newNode, nuke.Node)): return sourcePos = (newNode.xpos(), newNode.ypos()) targetPos = (targetNode.xpos(), targetNode.ypos()) oldSel = nuke.selectedNodes() inputNodes, outputNodes = self.getConnectedNodes(targetNode) nukescripts.clear_selection_recursive() targetNode.setSelected(True) nuke.extractSelected() targetNode.setSelected(False) newNode.setXYpos(*targetPos) targetNode.setXYpos(*sourcePos) for inNode in inputNodes: newNode.setInput(*inNode) for index, node in outputNodes: node.setInput(index, newNode) for node in oldSel: node.setSelected(True) return True
def flopViewer(): """input process to flop the viewer""" allV = nuke.allNodes('Viewer') pV = allV[0] List = nuke.selectedNodes() nuke.selectAll() nuke.invertSelection() try: n = nuke.toNode('VIEWER_INPUT') if n.Class() == 'Mirror': n['Vertical'].setValue(not n['Vertical'].value()) for i in allV: i['input_process'].setValue(not n['Vertical'].value() + n['Horizontal'].value() == 0) if n['Vertical'].value() + n['Horizontal'].value() == 0: nuke.delete(n) nuke.selectAll() nuke.invertSelection() else: nuke.message("Another Viewer Input already exists.\nAborting to avoid conflict") except: n = nuke.Node('Mirror',inpanel=False) n['xpos'].setValue(pV.xpos()+150) n['ypos'].setValue(pV.ypos()) n['name'].setValue('VIEWER_INPUT') n['hide_input'].setValue(1) n['Vertical'].setValue(not n['Vertical'].value()) nuke.selectAll() nuke.invertSelection() for i in List: i['selected'].setValue(True) for i in List: i['selected'].setValue(True)
def create_auto_crop_writer(): """creates a write node for every selected node, and sets the autocrop flag to auto crop the output for fast reading """ # get selected nodes and deselect them nodes = nuke.selectedNodes() [node.setSelected(False) for node in nodes] write_nodes = [] for node in nodes: write_node = nuke.createNode('Write') file_path = node['file'].value() filename_with_number_seq, ext = os.path.splitext(file_path) filename, number_seq = os.path.splitext(filename_with_number_seq) write_node['file'].setValue( filename + '_auto_cropped' + number_seq + ext ) write_node['channels'].setValue('all') write_node['autocrop'].setValue(True) write_node.setXpos(node.xpos() + 100) write_node.setYpos(node.ypos()) # connect it to the original node write_node.setInput(0, node) write_node.setSelected(False) # store the write node write_nodes.append(write_node) # connect the write nodes to afanasy if afanasy exists try: afanasy = nuke.createNode('afanasy') for i, node in enumerate(write_nodes): afanasy.setInput(i, node) except RuntimeError: pass
def filterSelectedNodes(): selectedNodes = nuke.selectedNodes() if selectedNodes: if selectedNodes[-1].Class() == "BackdropNode": oldBd = selectedNodes[-1] #ignore oldBd selectedNodes = selectedNodes[:-2] nukescripts.clear_selection_recursive() map(lambda node: node['selected'].setValue('True'), selectedNodes) #filter viewer nodes if selected viewerNodes = filter(lambda viewer: viewer.Class() == "Viewer", selectedNodes) #if viewer nodes are selected then deselect it if viewerNodes: selectedNodes = filter( lambda viewer: not viewer.Class() == "Viewer", selectedNodes) #print [node.name() for node in selectedNodes] nukescripts.clear_selection_recursive() map(lambda node: node['selected'].setValue('True'), selectedNodes) else: nuke.message("Please select valid nodes!")
def hlink_create(): # Creates an hlink node for each selected node nodes = nuke.selectedNodes() unselect() hlinks = [] for node in nodes: hlink = nuke.createNode('Dot', 'hide_input 1 note_font_size 18', inpanel=False) hlinks.append(hlink) hlink.setInput(0, node) target_name = node.fullName() set_hlink_knobs([hlink]) hlink['hlink_node'].setValue(target_name) label = hlink['label'] target_label = node['label'].getValue() if node.Class() == 'Read': label.setValue(' | ' + node['label'].getValue() + '\n' + os.path.basename(node['file'].getValue())) elif target_label: label.setValue(' | ' + target_label) else: label.setValue(' | ' + target_name) hlink.setXYpos(node.xpos() - grid[0]*2, node.ypos()-grid[1]*0) nuke.autoplaceSnap(hlink) _ = [n.setSelected(True) for n in hlinks]
def addgeotab(): """Get the selected nodes in the DAG""" selnodes = nuke.selectedNodes() """ Run for each selected node """ for i in selnodes: """Retrives node Class""" _class = i.Class() """Check node Class and add tab and knobs if successful""" if _class == "Bezier": geoTab = nuke.Tab_Knob("geotab", "Geo") gList = nuke.Enumeration_Knob( "shapelist", "Shape", ["circle", "square", "oval", "rectangle", "triangle"]) gSet = nuke.Script_Knob("set_geo", "Set Shape", "BezierGeoProc [knob this.shapelist]") i.addKnob(geoTab) i.addKnob(gList) i.addKnob(gSet) else: """If no Bezier is found, do nothing""" pass
def reconstruct_alembic(self): """ Reconstruct Alembic nodes from read nodes with exr input file """ try: #get selected nodes nodes_list = nuke.selectedNodes() #check if node selected if not (len(nodes_list)): print('No nodes selected') return False #iterate selected nodes and rebuild all passes for node in nodes_list: #reconstruct reconstruct_alembic.reconstruct_alembic(node) except: #status print('Error reconstructing Alembic files')
def getNodeList(): node_list = nuke.selectedNodes("Read") node_info = [] # check if read nodes are selected if len(node_list) > 0: for node in node_list: # make a read node dict for each node rnd = {} rnd['node'] = node rnd['node_name'] = node['name'].value() fpn = node['file'].evaluate() rnd['fd'] = os.path.split(fpn)[0] rnd['fn'] = os.path.split(fpn)[1] fileData = rnd['fn'].split('_') rnd['display_name'] = "Displayname" # "%s_%s_%s_%s_%s_%s" % (fileData[1], fileData[2], fileData[3], fileData[4], fileData[5], fileData[-1][0:-9]) # get base and ext for AOV rnd['base_fn'] = rnd['fn'].split('.')[0] rnd['ext'] = rnd['fn'].split('.')[-1] # first and last frame of beauty rnd['first_frame'] = '%05d' % (node['first'].value()) rnd['last_frame'] = '%05d' % (node['last'].value()) node_info.append(rnd) else: nuke.message('Please select one or more read nodes, to load AOVs.') return return node_info
def getCamera(): cameraClasses = ['Camera', 'Camera2'] redDotColor = 3070231295 allCamsInScript = [] for n in nuke.allNodes(): if n.Class() in cameraClasses: allCamsInScript.append(n.name()) # by selection ... for n in nuke.selectedNodes(): if n.Class() in cameraClasses: cam = n print 'got camera by selection:', cam.name() return cam # by label ... for d in nuke.allNodes(): names = ['MainCam', 'main_cam', 'MasterCam', 'master_cam'] for one in names: if d['label'].value() == one: cam = d print 'got camera by label:', cam.name() return cam # by dropdown ... camListPrint = '' for c in allCamsInScript: camListPrint = camListPrint + c + ' ' p = nuke.Panel('select camera') p.addEnumerationPulldown('camera', camListPrint) p.show() if p.value('camera'): # ok pressed cam = nuke.toNode(p.value('camera')) print 'got camera by dropdown:', cam.name() return cam