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 select_children(): n = nuke.thisNode() listOfChildren = postal_main.get_child_list(n) nukescripts.clear_selection_recursive() postal_main.set_child_list(n, listOfChildren, True)
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 replaceGizmoWithGroup(node): ### replaceGizmoWithGroup - takes a single node as input and if it is a gizmo, converts it into a group and replaces the old group. ### Preserves the original selection state ### requires nukescripts if isinstance(node, nuke.Gizmo): selection=nuke.selectedNodes() nukescripts.clear_selection_recursive() name=node['name'].getValue() inputs=node node.setSelected(True) group=node.makeGroup() group['xpos'].setValue(node['xpos'].getValue()) group['ypos'].setValue(node['ypos'].getValue()) for i in range (0,node.inputs()): group.setInput(i,node.input(i)) for n in selection: n.setSelected(True) sel=node['selected'].getValue() nuke.delete(node) group['name'].setValue(name) group.setSelected(sel)
def performCustomAction(): node = nuke.thisNode() knob = nuke.thisKnob() fileValue = node["file"].getValue() renderPath = os.path.dirname(fileValue) #reveal in explorer if knob.name() == "reveal in explorer": if renderPath!="": try: if platform.system() == "Windows": os.startfile(renderPath) elif platform.system() == "Darwin": subprocess.Popen(["open", renderPath]) else: subprocess.Popen(["xdg-open", renderPath]) except: nuke.message("couldn't open render path. No such directory") else: nuke.message("Please make sure to set a render path") #create next version if knob.name() == "create next version": if renderPath != "": nukescripts.clear_selection_recursive() node.setSelected(True) nukescripts.version_up() node.setSelected(False) fileValue = node["file"].getValue() renderPath = os.path.dirname(fileValue) if not os.path.isdir(renderPath): os.makedirs(renderPath) nuke.message("successfully versioned up") else: nuke.message("Renderfolder '%s' seems to exist" % renderPath) else: nuke.message("Please make sure to set a render path") #force create directory if knob.name() == "force create directory": if renderPath != "": if not os.path.isdir(renderPath): os.makedirs(renderPath) nuke.message("successfully created render directory at: \n\n%s" % renderPath) else: nuke.message("render directory exists") else: nuke.message("Please make sure to set a render path") #save backup if knob.name() == "save backup": if knob.getValue() == 1.0: node["beforeRender"].setValue("nextVersion.saveBackup('%s')" % node.name()) else: node["beforeRender"].setValue("")
def select_in_nuke(nodes): import nuke import nukescripts nukescripts.clear_selection_recursive() if isinstance(nodes, basestring): nodes = [nodes] for node in nodes: n = nuke.toNode(node) n.knob('selected').setValue(True)
def centerNodeInNodeGraph(node): try: xpos = node["xpos"].value() ypos = node["ypos"].value() factor = 1.0 nukescripts.clear_selection_recursive() node["selected"].setValue(True) nuke.zoom(factor, (xpos, ypos)) except: pass
def performCustomAction(): node = nuke.thisNode() knob = nuke.thisKnob() fileValue = node["file"].getValue() renderPath = os.path.abspath(fileValue) #create test folder if knob.name() == "create test folder": if renderPath != "": renderPath = os.path.join(renderPath ,'', "test_v1") #renderPath = os.path.join(renderPath, "test_v1") if os.path.isdir(renderPath): nuke.message("test folder already created, please version up") else: os.makedirs(renderPath) node.knob('file').setValue(renderPath) nuke.message("successfully created test directory at: \n\n%s" % renderPath) else: nuke.message("please make sure to set a render path") #open in finder if knob.name() == "open in explorer": if renderPath!="": try: if platform.system() == "Windows": os.startfile(renderPath) elif platform.system() == "Darwin": subprocess.Popen(["open", renderPath]) else: subprocess.Popen(["xdg-open", renderPath]) except: nuke.message("couldn't open render path. No such directory") else: nuke.message("please make sure to set a render path") #create next version if knob.name() == "version up": if renderPath != "": nukescripts.clear_selection_recursive() node.setSelected(True) nukescripts.version_up() node.setSelected(False) fileValue = node["file"].getValue() renderPath = os.path.dirname(fileValue) if not os.path.isdir(renderPath): os.makedirs(renderPath) nuke.message("successfully versioned up") else: nuke.message("please set file path with test_vxx at the end or create a test folder first") else: nuke.message("please make sure to set a render path")
def selectAllClassNodes(): nukescripts.clear_selection_recursive() userInput = nuke.getInput( "What type of node do you want to select? \n" + "(Correct capitalization matters!) \n" + "no spaces", "Crop") for node in nuke.allNodes(): if node.Class() == userInput: node.setSelected(True) nuke.message("Selected %d %s nodes." % (len(nuke.selectedNodes()), userInput))
def create_child(parent_node): parentName = parent_node.knob('name').value() parentLabel = parent_node.knob('parentLabel').value() parentXpos = parent_node.knob('xpos').value() parentYpos = parent_node.knob('ypos').value() childName = parentLabel + '_' + str(random.randint(0, 1000000)) prevChildList = parent_node.knob('childList').value() newChildList = prevChildList + childName + '\n' parent_node.knob('childList').setValue(newChildList) nukescripts.clear_selection_recursive() child = nuke.createNode('NoOp', inpanel=False) child.setInput(0, nuke.toNode(parentName)) nuke.toNode(child['name'].value()).setSelected(True) child['hide_input'].setValue( nuke.toNode(parentName).knob('hideInputTracker').value()) child['note_font_size'].setValue(20.0) child['tile_color'].setValue(3511807) child['note_font'].setValue('Verdana Bold Bold Bold') child['xpos'].setValue(parentXpos) child['ypos'].setValue(parentYpos + 50) child['name'].setValue(childName) childTabKnob = nuke.Tab_Knob('postalChild', 'postal child') child.addKnob(childTabKnob) parentIDKnob = nuke.String_Knob('parentID', 'parent ID', parentName) child.addKnob(parentIDKnob) parentLabelKnob = nuke.String_Knob('parentLabel', 'parent label', parentLabel) child.addKnob(parentLabelKnob) CONNECT_TO_PARENT = """ import connect_to_parent connect_to_parent.connect_to_parent(nuke.thisNode()) """ CONNECT_TO_PARENT_TOOLTIP = """ Reconnects this node to its parentID. This button must be pressed to add this child to parent's list of children """ connectToParentButton = nuke.PyScript_Knob('connectToParent', 'connect to parent', CONNECT_TO_PARENT) connectToParentButton.setFlag(0x0000000000001000) connectToParentButton.setTooltip(CONNECT_TO_PARENT_TOOLTIP) child.addKnob(connectToParentButton) nukescripts.clear_selection_recursive() nuke.toNode(child['name'].value()).setSelected(True) child['autolabel'].setValue("nuke.thisNode().knob('parentLabel').value()")
def copyPremult(): n = nuke.createNode('Copy') m = nuke.createNode('Premult') n['selected'].setValue(True) m['selected'].setValue(True) sel = nuke.selectedNodes() for i in sel: nuke.autoplace(i) nukescripts.clear_selection_recursive()
def runner(): if nuke.thisKnob().name() == 'selected': # RANDOM FOR X random.seed(random.random()) randFactX = (random.random() - 0.5) # RANDOM FOR Y random.seed(random.random()) randFactY = (random.random() - 0.5) # RUN AWAY nuke.thisNode().setXpos(nuke.thisNode().xpos() + int(500 * randFactX)) nuke.thisNode().setYpos(nuke.thisNode().xpos() + int(500 * randFactY)) # CLEAR SELECTION nukescripts.clear_selection_recursive()
def selectBackdropContents(backdropNode): '''Select all nodes inside a backdrop. There is a built in method for this on Nuke6.3v5, but this is kept here to expand compatibility to earlier versions ''' bx, by = backdropNode.xpos(), backdropNode.ypos() nukescripts.clear_selection_recursive() backdropNode.setSelected(True) nuke.nodeCopy(nukescripts.cut_paste_file()) nuke.nodeDelete(popupOnError=False) nuke.nodePaste(nukescripts.cut_paste_file()) nuke.selectedNode().setXYpos(bx, by)
def dAutocropFN(): x = 0 #counter for process loop for each in selection: processing = selection[x] if x <= len(selection): x = x+1 #clear selection and prepare a new one for processing nukescripts.clear_selection_recursive() processing.knob("selected").setValue(True) #create tmp deep to image and store it in a tmp variable sSelection = nuke.selectedNode() deeptoimg = nuke.createNode('DeepToImage') #create a crop to get root format and store in variable cropTool = nuke.createNode('Crop') cropTool.setInput(0,deeptoimg) cropBox = cropTool.knob('box').getValue() #create and run curvetool curveNode = nuke.createNode('CurveTool') curveNode.knob('operation').setValue('AutoCrop') curveNode.knob('name').setValue('tmp_AC') curveNode.knob('ROI').setValue(cropBox) nuke.execute(curveNode, nuke.root().firstFrame(), nuke.root().lastFrame()) #create, connect and copy anim to deepcrop cropNode = nuke.nodes.DeepCrop() cropNode.knob('bbox').copyAnimations( curveNode.knob('autocropdata').animations() ) cropNode.setInput(0,sSelection) cropNode.knob('use_znear').setValue(False) cropNode.knob('use_zfar').setValue(False) cropNode.knob('label').setValue('AutoCrop') #remove tmp nodes nuke.delete(deeptoimg) nuke.delete(cropTool) nuke.delete(curveNode) else: #break loop and give succes message break return
def run(self): node = None incs = 1 for i in range(incs): for n, m in self.adult_dict.items(): if not m: nukescripts.clear_selection_recursive() continue node = nuke.createNode("Dot") x = m["pos"][0] y = m["pos"][1] color = m["color"] nuke.executeInMainThreadWithResult(node.setXpos, int(x)) nuke.executeInMainThreadWithResult(node.setYpos, int(y)) nuke.executeInMainThreadWithResult(node["tile_color"].setValue, (int(color)))
def filepathCreateNode(gizmoName): if '.nk' in gizmoName: nukescripts.clear_selection_recursive() nuke.nodePaste(gizmoName) fileNodes = nuke.selectedNodes() else: newGizmo = nuke.createNode(gizmoName) fileNodes = newGizmo.nodes() for i in fileNodes: if i.Class() == "Read" or i.Class() == "DeepRead" or i.Class( ) == "ReadGeo" or i.Class() == "ReadGeo2" or i.Class( ) == "Camera2" or i.Class() == "Axis2": filepath = i.knob("file").getValue() if "<<<replace>>>" in filepath: newFilepath = filepath.replace("<<<replace>>>", NST_FolderPath) i.knob("file").setValue(newFilepath)
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 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 view_edge_node(which): # print "view node: {}".format(get_edge_node(which).name()) viewer_port = 8 edge_node = get_edge_node(which) sel = nuke.selectedNodes() if edge_node is None: return nukescripts.clear_selection_recursive() edge_node.setSelected(True) nukescripts.connect_selected_to_viewer(viewer_port) edge_node.setSelected(False) for node in sel: node.setSelected(True) for node in nuke.allNodes("Viewer"): node.setSelected(False)
def add_cdl(): '''adds cdl group to IP node''' node_cdl = nuke.root().selectedNode() print node_cdl.name() if node_cdl != nuke.thisNode(): node_ip = nuke.thisNode() #node_ip = nuke.toNode('VIEWER_INPUT') with nuke.root(): nuke.nodeCopy('%clipboard%') nukescripts.clear_selection_recursive() # k_cdl = nuke.Boolean_Knob('cdl', "AVID GRADE CDL") # k_cdl.setFlag(nuke.STARTLINE) # node_ip.addKnob(k_cdl) with node_ip: group_input = nuke.toNode('Input') group_input.setSelected(True) node_cdl = nuke.nodePaste('%clipboard%') node_cdl['disable'].setExpression('!parent.cdl')
def add_gizmo(menu_item): if nuke.selectedNode().Class() not in ('Group', 'Gizmo'): nuke.message('You should select a Group or Gizmo node.') return dialog = AddGizmoDialog() if dialog.exec_(): name = dialog.name gizmo = nuke.selectedNode() nukescripts.clear_selection_recursive() gizmo.setSelected(True) if gizmo.name() != name: gizmo.setName('{}1'.format(name)) gizmo_path = path_join(menu_item.path, '{}.gizmo'.format(name)) makedirs(gizmo_path) nuke.nodeCopy(gizmo_path) command = menu_item.add_sub_command( name, "nuke.createNode('{}')".format(name)) if command: command.file_path = gizmo_path command.create()
def build_remove(dict_remove, node): '''rebuild Remove node everytime it's called @dict_remove: (dict of str, int: [str,...]) filtered dict of layers @node: (obj) node object to build ''' CH = ['channels', 'channels2', 'channels3', 'channels4'] with node: for r in nuke.allNodes('Remove'): nuke.delete(r) nukescripts.clear_selection_recursive() nuke.toNode('Input').setSelected(True) for k in dict_remove: node_remove = nuke.createNode('Remove', 'operation remove', inpanel=False) thisGroup = dict_remove[k] node_remove['label'].setValue(', '.join(thisGroup)) for idx, l in enumerate(thisGroup): node_remove[CH[idx]].setValue(l)
def replaceNode(oldNode, newNode): """ Replace an node by new one. Relink the new node. The nodes should have the same inputs/outputs Rename the new node with the old one name """ # TODO make a "clear selection" in pfNukeUtils nukescripts.clear_selection_recursive() # Store name and position oldName = oldNode.name() oldPosition = (oldNode.xpos(), oldNode.ypos()) # Link node to the same inputs for i in range(oldNode.inputs()): newNode.setInput(i, oldNode.input(i)) # Store inputs of dependent nodes inputs = [(n, i) for n in oldNode.dependent() for i in range(n.inputs()) if n.input(i) == oldNode ] # Disconnect for i in range(oldNode.inputs()): oldNode.setInput(i, None) nuke.delete(oldNode) # Reconnect inputs of dependent nodes for n, i in inputs: n.setInput(i, newNode) # Set name newNode.setName(oldName) # Set position newNode.knob("xpos").setValue(oldPosition[0]) newNode.knob("ypos").setValue(oldPosition[1])
def customSave(mode='save'): if mode == 'save': nuke.scriptSave("") elif mode == 'saveAs': nuke.scriptSaveAs("") elif mode == "saveNewVersion": write_list = [ write for write in nuke.allNodes('Write') if script_name( nuke.filename(write)) == script_name(nuke.scriptName()) ] nukescripts.script_and_write_nodes_version_up() if write_list: selectedNodes = nuke.selectedNodes()[:] nukescripts.clear_selection_recursive() for write in write_list: write.setSelected(True) nukescripts.version_up() write.setSelected(False) for node in selectedNodes: node.setSelected(True) nuke.scriptSave("")
def selectObject(applicationObject='', clearSelection=True): if clearSelection: nukescripts.clear_selection_recursive() n = nuke.toNode(HelpFunctions.safeString(applicationObject)) n.knob('selected').setValue(True)
def reset_selection(): """Deselect all selected nodes """ clear_selection_recursive()
def collectFilesPanel(): cp = nuke.Panel("项目打包 by jgcy", 450) cp.addSingleLineInput("输出文件名:", nuke.Root().name().split("/")[-1][:-3]) # addSingleLineInput() 添加文本输入框 dirTemp = list(os.path.split(nuke.root()['name'].getValue()))[0] + "/" cp.addFilenameSearch("输出路径:", dirTemp) cp.addEnumerationPulldown("输出节点方式:", "所有节点 仅打包所选节点") cp.addButton("取消") cp.addButton("打包") result = cp.show() if result == 1: outDir = cp.value("输出路径:") inScriptName = cp.value("输出文件名:") allOrSel = cp.value("输出节点方式:") if allOrSel == "所有节点": doNodes = nuke.allNodes('Read') nuke.selectAll() newPath = outDir + inScriptName + ".nk" # 判断输出路径是否存在 if os.path.exists(outDir): nuke.nodeCopy(newPath) else: os.mkdir(outDir) nuke.nodeCopy(newPath) fmat = nuke.root().format() # 设置项目尺寸与时间帧到新文件中 f = open(newPath, "a") f.write("\n") f.write("Root {\n") f.write("first_frame {0} \n".format( nuke.root()["first_frame"].getValue())) f.write("last_frame {0} \n".format( nuke.root()["last_frame"].getValue())) f.write("fps {0} \n".format(nuke.root()["fps"].getValue())) f.write('format "{0} {1} {2} {3}"\n'.format( fmat.width(), fmat.height(), int(fmat.pixelAspect()), fmat.name())) f.write("}\n") f.close() nukescripts.clear_selection_recursive() return inScriptName, outDir, doNodes else: if nuke.selectedNodes() == []: nuke.message("请选择要输出的节点") doNodes = nuke.selectedNodes('Read') newPath = outDir + inScriptName + ".nk" # 判断输出路径是否存在 if os.path.exists(outDir): nuke.nodeCopy(newPath) else: os.mkdir(outDir) nuke.nodeCopy(newPath) fmat = nuke.root().format() # 设置项目尺寸与时间帧到新文件中 f = open(newPath, "a") f.write("\n") f.write("Root {\n") f.write("first_frame {0} \n".format( nuke.root()["first_frame"].getValue())) f.write("last_frame {0} \n".format( nuke.root()["last_frame"].getValue())) f.write("fps {0} \n".format(nuke.root()["fps"].getValue())) f.write('format "{0} {1} {2} {3}"\n'.format( fmat.width(), fmat.height(), int(fmat.pixelAspect()), fmat.name())) f.write("}\n") f.close() return inScriptName, outDir, doNodes
def create_nodeTree(node): n = node n1, n2, n3 = None, None, None controls = nuke.nodes.NoOp(name='CONTROLS', xpos=n.xpos() + 300, ypos=n.ypos()) texInput = nuke.nodes.Input(name='tex01', xpos=n.xpos() - 34, ypos=250 + n.ypos()) dot = nuke.nodes.Dot(xpos=0 + n.xpos(), ypos=100 + n.ypos(), inputs=[n]) dot1 = nuke.nodes.Dot(xpos=250 + n.xpos(), ypos=100 + n.ypos(), inputs=[dot]) n = dot1 n1 = texInput for l in m_layers: print(str("Adding layer " + l)) x, y = n.xpos(), n.ypos() dot1 = nuke.nodes.Dot(xpos=x + 350, ypos=y + 0, inputs=[n]) shuffle = nuke.nodes.Shuffle(xpos=x - 34, ypos=y + 50, inputs=[n]) shuffle['in'].setValue(str(l)) shuffle['label'].setValue('[value in]') nukescripts.clear_selection_recursive() shuffle['selected'].setValue(True) try: nukescripts.autocrop(layer='a') except: print("oops") return autocrop = shuffle.dependent()[0] acName = autocrop.name() dot2 = nuke.nodes.Dot(xpos=x - 100, ypos=y + 200, inputs=[n1]) transform = nuke.nodes.Transform(xpos=x - 134, ypos=y + 250, inputs=[dot2]) transform['center'].setExpression('width/2', 0) transform['center'].setExpression('height/2', 1) scaleOffset = nuke.Double_Knob('{}_scale'.format(str(l)), '{}_scale'.format(str(l))) rotateOffset = nuke.Double_Knob('{}_rotate'.format(str(l)), '{}_rotate'.format(str(l))) controls.addKnob(scaleOffset) controls.addKnob(rotateOffset) controls['{}_scale'.format(str(l))].setRange(1, 5) controls['{}_scale'.format(str(l))].setValue(1) controls['{}_rotate'.format(str(l))].setRange(0, 360) controls['{}_rotate'.format(str(l))].setValue(0) transform['scale'].setExpression( 'parent.global_scale * CONTROLS.{}_scale'.format(str(l))) transform['rotate'].setExpression( 'parent.global_rotate + CONTROLS.{}_rotate'.format(str(l))) knobList.append('{}.{}_scale'.format(controls.name(), str(l))) knobList.append('{}.{}_rotate'.format(controls.name(), str(l))) cornerpin = nuke.nodes.CornerPin2D(xpos=x - 134, ypos=y + 300, inputs=[transform]) cornerpin['to1'].setExpression('{}.bbox.x'.format(acName), 0) cornerpin['to1'].setExpression('{}.bbox.y'.format(acName), 1) cornerpin['to2'].setExpression('{}.bbox.r'.format(acName), 0) cornerpin['to2'].setExpression('{}.bbox.y'.format(acName), 1) cornerpin['to3'].setExpression('{}.bbox.r'.format(acName), 0) cornerpin['to3'].setExpression('{}.bbox.t'.format(acName), 1) cornerpin['to4'].setExpression('{}.bbox.x'.format(acName), 0) cornerpin['to4'].setExpression('{}.bbox.t'.format(acName), 1) cornerpin['from2'].setExpression('width', 0) cornerpin['from3'].setExpression('width', 0) cornerpin['from3'].setExpression('height', 1) cornerpin['from4'].setExpression('height', 1) copy = nuke.nodes.Copy(xpos=x - 34, ypos=y + 290, inputs=[autocrop, cornerpin]) copy['from0'].setValue('none') copy['to0'].setValue('none') copy['channels'].setValue('rgb') copy['bbox'].setValue('B') premult = nuke.nodes.Premult(xpos=x - 34, ypos=y + 350, inputs=[copy]) if m_layers.index(l) < 1: dot3 = nuke.nodes.Dot(xpos=x, ypos=y + 400, inputs=[premult]) n2 = dot3 elif m_layers.index(l) >= 1: merge = nuke.nodes.Merge2(xpos=x - 34, ypos=y + 400, inputs=[premult, n2]) merge['operation'].setValue('disjoint_over') n2 = merge if m_layers.index(l) == len(m_layers) - 1: shuffle = nuke.nodes.Shuffle(xpos=x - 34, ypos=y + 600, inputs=[n2]) shuffle['alpha'].setValue('red') output = nuke.nodes.Output(xpos=x - 34, ypos=y + 650, inputs=[shuffle]) n = dot1 n1 = dot2
def textureTrackSetup(DIP): # Create variables # DIP = nuke.selectedNode() channels = DIP.channels() global m_layers m_layers = [] # Create sorted list of DIP layers global layers layers = sorted(list(set([c.split('.')[0] for c in channels]))) # Look for layers that have "m_" and append them to m_layers for layer in layers: if "m_" in layer: m_layers.append(layer) print("Added " + str(layer)) if len(m_layers) < 1: nuke.message('No layers starting with "m_" found...') return # Create DIP layer if it's not found if 'DIP' not in nuke.layers(): nuke.Layer('DIP', ['DIP.red', 'DIP.green', 'DIP.blue', 'DIP.alpha']) "DIP layer not found. Creating DIP layer." else: print("DIP layer found.") # Clear selection #nukescripts.clear_selection_recursive() # Create tex01 layer if not found if 'tex01' not in nuke.layers(): nuke.Layer('tex01', ['tex01.red', 'tex01.green', 'tex01.blue', 'tex01.alpha']) nukescripts.clear_selection_recursive() DIP['selected'].setValue(True) grp = nuke.createNode('Group', inpanel=False) grp.setName('TPD_TextureTrack') grp['xpos'].setValue(DIP.xpos()) grp['ypos'].setValue(85 + DIP.ypos()) grp.setInput(0, DIP) print('Created Group node') text = nuke.Text_Knob( 'title', ' ', '<i>TPD_TextureTrack</i></b> {}<br>by Noah Catan<br><br><b>'.format( version)) div1 = nuke.Text_Knob('div', ' ') grp.addKnob(text) grp.addKnob(div1) global_scale = nuke.Double_Knob('global_scale', 'global scale') global_rotate = nuke.Double_Knob('global_rotate', 'global rotate') div = nuke.Text_Knob('div', ' ') grp.addKnob(global_scale) grp.addKnob(global_rotate) grp.addKnob(div) grp['global_scale'].setRange(1, 5) grp['global_scale'].setValue(1) grp['global_rotate'].setRange(0, 360) grp['global_rotate'].setValue(0) with grp: input1 = nuke.nodes.Input() dot = nuke.nodes.Dot(xpos=34 + input1.xpos(), ypos=200 + input1.ypos(), inputs=[input1]) create_nodeTree(dot) '''for transform in transformList: knobTarget = "{}.{}".format(transform.name(), 'scaleOffset') linkedKnobs.append(knobTarget) for knob in linkedKnobs: link_knob = nuke.Link_Knob("{}".format(layers[linkedKnobs.index(knob)])) link_knob.setLink(knob) grp.addKnob(link_knob)''' for knob in knobList: link_knob = nuke.Link_Knob('{}'.format(knob[9:])) link_knob.setLink(knob) grp.addKnob(link_knob)
def knobChanged(self, knob): #update if knob.name() == "update": #reset for btn in nuke.errors_footageBtn: self.removeKnob(btn) nuke.errors_footageBtn = [] errors = [] nuke.errors_nodes = [] nuke.errors_missingFrames = [] with nuke.root(): all = nuke.allNodes() for n in all: if n.Class() != "Read": if n.hasError(): errors.append(n.name()) if n not in nuke.errors_nodes: nuke.errors_nodes.append(n) else: for frame in range(int(n["first"].getValue()), int(n["last"].getValue()) + 1): try: f = nukescripts.replaceHashes( n['file'].value()) % (frame) except: f = "" if not os.path.isfile(f): errors.append(f) if f not in nuke.errors_missingFrames: nuke.errors_missingFrames.append(f) if n not in nuke.errors_nodes: nuke.errors_nodes.append(n) for errorNode in nuke.errors_nodes: self.en = nuke.PyScript_Knob(errorNode.name(), errorNode.name()) self.addKnob(self.en) nuke.errors_footageBtn.append(self.en) nuke.errors_lenErrors = len(errors) if nuke.errors_lenErrors == 0: col = "green" else: col = "red" countErrors = '<span style="color:{col}">{countErr}</span>'.format( col=col, countErr=nuke.errors_lenErrors) self.errorCount.setValue(countErrors) #write if knob.name() == "write": if self.outputPath.getValue() != "": try: script = os.path.basename(nuke.root().name()) output = os.path.dirname(self.outputPath.getValue( )) + "/errorReport_%s" % script.replace(".nk", ".txt") errorOutput = open(output, 'w') date = time.strftime("%d-%m-%Y %H:%M:%S", time.gmtime()) header = "error report \nscript name: {scriptname}\nscript path: {scriptPath}\ndate: {date}\nnumber of errors: {countErrors}\n------------------------------".format( scriptname=script, scriptPath=nuke.root().name(), date=date, countErrors=nuke.errors_lenErrors) errorOutput.write(header) #all read nodes errorOutput.write("\nread nodes\n\n") for n in nuke.errors_nodes: if n.Class() == "Read": errorOutput.write("read node: %s\n" % n.name()) #all missing frames errorOutput.write("\n----------\nmissing frames\n\n") for f in nuke.errors_missingFrames: errorOutput.write("missing frame: %s\n" % f) #all other nodes errorOutput.write("\n----------\nother nodes\n\n") for n in nuke.errors_nodes: if n.Class() != "Read": errorOutput.write("node: %s\n" % n.name()) nuke.message( "successfully written error report to:\n\n%s" % output) except: nuke.message( "some error occured. The report could not be written.") else: nuke.message( "Please enter a output path for the error report.") #all other error nodes else: allNodes = nuke.allNodes() pKnob = knob.name() for n in allNodes: if n.name() == pKnob: nuke.zoom(1, [n.xpos(), n.ypos()]) nukescripts.clear_selection_recursive() n.setSelected(True)
def selectObjects(selection): nukescripts.clear_selection_recursive() for obj in selection: Connector.selectObject(obj, clearSelection=False)
def knobChanged( self, knob ): #update if knob.name()=="update": #reset for btn in nuke.errors_footageBtn: self.removeKnob(btn) nuke.errors_footageBtn=[] errors=[] nuke.errors_nodes=[] nuke.errors_missingFrames=[] with nuke.root(): all = nuke.allNodes() for n in all: if n.Class()!="Read": if n.hasError(): errors.append(n.name()) if n not in nuke.errors_nodes: nuke.errors_nodes.append(n) else: for frame in range(int(n["first"].getValue()), int(n["last"].getValue())+1): try: f = nukescripts.replaceHashes(n['file'].value() ) % (frame) except: f = "" if not os.path.isfile(f): errors.append(f) if f not in nuke.errors_missingFrames: nuke.errors_missingFrames.append(f) if n not in nuke.errors_nodes: nuke.errors_nodes.append(n) for errorNode in nuke.errors_nodes: self.en = nuke.PyScript_Knob(errorNode.name(), errorNode.name()) self.addKnob(self.en) nuke.errors_footageBtn.append(self.en) nuke.errors_lenErrors=len(errors) if nuke.errors_lenErrors==0: col="green" else: col="red" countErrors = '<span style="color:{col}">{countErr}</span>'.format(col=col, countErr=nuke.errors_lenErrors) self.errorCount.setValue(countErrors) #write if knob.name()=="write": if self.outputPath.getValue()!="": try: script = os.path.basename(nuke.root().name()) output= os.path.dirname(self.outputPath.getValue()) + "/errorReport_%s" % script.replace(".nk",".txt") errorOutput = open(output,'w') date = time.strftime("%d-%m-%Y %H:%M:%S", time.gmtime()) header="error report \nscript name: {scriptname}\nscript path: {scriptPath}\ndate: {date}\nnumber of errors: {countErrors}\n------------------------------".format(scriptname=script, scriptPath=nuke.root().name(), date=date, countErrors=nuke.errors_lenErrors) errorOutput.write(header) #all read nodes errorOutput.write("\nread nodes\n\n") for n in nuke.errors_nodes: if n.Class()=="Read": errorOutput.write("read node: %s\n" % n.name()) #all missing frames errorOutput.write("\n----------\nmissing frames\n\n") for f in nuke.errors_missingFrames: errorOutput.write("missing frame: %s\n" % f) #all other nodes errorOutput.write("\n----------\nother nodes\n\n") for n in nuke.errors_nodes: if n.Class()!="Read": errorOutput.write("node: %s\n" % n.name()) nuke.message("successfully written error report to:\n\n%s" % output) except: nuke.message("some error occured. The report could not be written.") else: nuke.message("Please enter a output path for the error report.") #all other error nodes else: allNodes=nuke.allNodes() pKnob=knob.name() for n in allNodes: if n.name() == pKnob: nuke.zoom( 1, [ n.xpos(), n.ypos() ]) nukescripts.clear_selection_recursive() n.setSelected(True)
def multiChannelSplit(): ''' main function split the selected read node in separate channel layers if set create separate folders and write nodes ''' sel = nuke.selectedNode() shuffles = [] renderTo = "" autocropNodeRGB_exists = False cropNode = None dot = None if sel is not None: # Main procedure # Create shuffle, shuffle channel in, curvetool crop # Create cropnode and paste that information in # Delete crop node o = 0 if self.autoCrop.getValue() == 1.0: curveName = 'Autocrop_Master' curveNode = nuke.nodes.CurveTool(name=curveName, inputs=[sel], operation="Auto Crop") curveNode["channels"].setValue("rgba") curveNode.knob("ROI").setValue( [0, 0, sel.width(), sel.height()]) nuke.execute(curveNode, sel.knob("first").value(), sel.knob("last").value()) layersToProcess = [] if self.which.getValue() == 0.0: layersToProcess = uniqueLayers else: for layer in layerCheckboxes: if layer.getValue() is True: layersToProcess.append(layer.name()) if len(layersToProcess) > 0: dot = nuke.createNode("Dot", inpanel=False) for channelLayer in layersToProcess: shuffleName = "Shuffle_" + channelLayer shuffleNode = nuke.nodes.Shuffle(name=shuffleName) shuffles.append(shuffleNode.name()) shuffleNode.knob("in").setValue(channelLayer) shuffleNode["hide_input"].setValue(True) shuffleNode.setInput(0, sel) xpos = sel["xpos"].getValue() + (o * 100) ypos = sel["ypos"].getValue() + 150 shuffleNode["xpos"].setValue(xpos) shuffleNode["ypos"].setValue(ypos) shuffleNode.setInput(0, dot) shuffleNode["postage_stamp"].setValue(True) # Auto crop if selected if self.autoCrop.getValue() == 1.0: if autocropNodeRGB_exists is False: cropNode = nuke.nodes.Crop( name=channelLayer, inputs=[shuffleNode]) cropNode.knob("hide_input").setValue(True) cropNode.knob("box").copyAnimations( curveNode.knob( "autocropdata").animations()) nuke.delete(curveNode) cropNode.knob("postage_stamp").setValue( True) xpos = int(shuffleNode["xpos"].getValue()) ypos = shuffleNode["ypos"].getValue() + 80 ypos = int(ypos) cropNode.setXpos(xpos) cropNode.setYpos(ypos) shuffleNode["hide_input"].setValue(False) cropNode["hide_input"].setValue(True) nukescripts.clear_selection_recursive() cropNode["selected"].setValue(True) nuke.nodeCopy("%clipboard%") autocropNodeRGB_exists = True shuffleNode["postage_stamp"].setValue( False) cropNode["postage_stamp"].setValue(True) else: cropCopy = nuke.nodePaste("%clipboard%") cropCopy["name"].setValue(channelLayer) cropCopy.setInput(0, shuffleNode) xpos = int(shuffleNode["xpos"].getValue()) ypos = shuffleNode["ypos"].getValue() + 80 ypos = int(ypos) cropCopy.setXpos(xpos) cropCopy.setYpos(ypos) # Create folders for all layer and # Create write node for every shuffle if self.outputPath.getValue() != "": renderTo = self.outputPath.getValue() # CreateFolder createFolders(renderTo + "/" + channelLayer) # Create write node write = nuke.nodes.Write() write.knob("file_type").setValue("exr") fileValue = renderTo + channelLayer fileValue += '/' + channelLayer + "_%04d.exr" write.knob("file").setValue(fileValue) cValue = "Zip (16 scanlines)" write.knob("compression").setValue(cValue) write.knob("channels").setValue("rgba") if self.autoCrop.getValue() is True: write.setInput(0, cropNode) else: write.setInput(0, shuffleNode) o += 1 if len(layersToProcess) > 0: nuke.delete(dot) # Hide all created shuffle inputs for shuffleNode in shuffles: if self.autoCrop.getValue() == 1.0: temp = nuke.toNode(shuffleNode) temp.knob("hide_input").setValue(True) temp.knob("postage_stamp").setValue(True) else: pass
def create_lp_nodes(lpass, node): ''' Creates a nodes for a single light pass ''' #clear selection nukescripts.clear_selection_recursive() # Get parent_dot's position parent_dot = node x = parent_dot.xpos() y = parent_dot.ypos() #store nodes in a list nodes_created = [] #node_Dot_2 node_Dot_2 = nuke.nodes.Dot(xpos=0+x,ypos=81+y,inputs=[parent_dot]) node_Dot_2['name'].setValue('DOT2_{}'.format(lpass.upper())) nodes_created.append(node_Dot_2) #node_Shuffle_1 - LIGHT PASS node_Shuffle_1 = nuke.nodes.Shuffle(xpos=-34+x,ypos=157+y,inputs=[node_Dot_2]) node_Shuffle_1['name'].setValue('SHUFFLE_{}'.format(lpass.upper())) node_Shuffle_1['in'].fromScript('LGHT_{}'.format(lpass.upper())) node_Shuffle_1['label'].setValue('[value in]') node_Shuffle_1['red'].fromScript('black') node_Shuffle_1['green'].fromScript('black') node_Shuffle_1['blue'].fromScript('black') nodes_created.append(node_Shuffle_1) #node_Shuffle_2 - DIP ALPHA node_Shuffle_2 = nuke.nodes.Shuffle(xpos=90+x,ypos=72+y,inputs=[node_Dot_2]) node_Shuffle_2['in'].fromScript('DIP') node_Shuffle_2['label'].setValue('[value in]') node_Shuffle_2['red'].fromScript('white') node_Shuffle_2['green'].fromScript('white') node_Shuffle_2['blue'].fromScript('white') nodes_created.append(node_Shuffle_2) #node_Grade_1 LIGHT node_Grade_1 = nuke.nodes.Grade(xpos=182+x,ypos=113+y,inputs=[node_Shuffle_2]) node_Grade_1['name'].setValue('{}_LIGHT'.format(lpass.upper())) node_Grade_1['white'].setValue([0.0, 0.0, 0.0, 0.0]) node_Grade_1['label'].setValue('LIGHT') nodes_created.append(node_Grade_1) #node_Grade_2 SHADOW node_Grade_2 = nuke.nodes.Grade(xpos=90+x,ypos=113+y,inputs=[node_Shuffle_2]) node_Grade_2['name'].setValue('{}_SHADOW'.format(lpass.upper())) if lpass in lightPassesMultiply: node_Grade_2['white'].setValue([1.0,1.0,1.0,1.0]) elif lightPasses.index(lpass)<=0: node_Grade_2['white'].setValue([0.2, 0.2, 0.2, 0.2]) else: node_Grade_2['white'].setValue([0.0, 0.0, 0.0, 0.0]) node_Grade_2['label'].setValue('SHADOW') nodes_created.append(node_Grade_2) #node_Keymix_1 node_Keymix_1 = nuke.nodes.Keymix(xpos=90+x,ypos=157+y,inputs=[node_Grade_2,node_Grade_1,node_Shuffle_1]) node_Keymix_1['name'].setValue('{}_KEYMIX'.format(lpass.upper())) node_Keymix_1['channels'].fromScript('rgb') nodes_created.append(node_Keymix_1) #node_Merge_1 if lightPasses.index(lpass) > 0: node_Merge_1 = nuke.nodes.Merge2(xpos=90+x,ypos=250+y,inputs=[None, node_Keymix_1]) node_Merge_1['name'].setValue('{}_MERGE'.format(lpass.upper())) node_Merge_1['Achannels'].setValue('rgb') node_Merge_1['Bchannels'].setValue('rgb') node_Merge_1['output'].setValue('rgb') if lpass in lightPassesMultiply: node_Merge_1['operation'].setValue('multiply') else: node_Merge_1['operation'].setValue('plus')
def multiChannelSplit(): ''' main function split the selected read node in separate channel layers if set create separate folders and write nodes ''' sel = nuke.selectedNode() shuffles=[] renderTo="" autocropNodeRGB_exists=False cropNode=None dot=None if sel != None: #main procedure #create shuffle, shuffle channel in, curvetool crop, create cropnode and paste that information in, delete crop node o=0; if self.autoCrop.getValue()==1.0: curveNode = nuke.nodes.CurveTool(name="Autocrop_Master", inputs = [sel], operation="Auto Crop") curveNode["channels"].setValue("rgba") curveNode.knob("ROI").setValue([0,0,sel.width(),sel.height()]) nuke.execute(curveNode, sel.knob("first").value(), sel.knob("last").value()) layersToProcess=[] if self.which.getValue()== 0.0: layersToProcess = uniqueLayers else: for layer in layerCheckboxes: if layer.getValue()==True: layersToProcess.append(layer.name()) if len(layersToProcess)>0: dot = nuke.createNode("Dot", inpanel=False) for channelLayer in layersToProcess: shuffleNode = nuke.nodes.Shuffle(name="Shuffle_"+channelLayer) shuffles.append(shuffleNode.name()) shuffleNode.knob("in").setValue(channelLayer) shuffleNode["hide_input"].setValue(True) shuffleNode.setInput(0,sel) shuffleNode["xpos"].setValue(sel["xpos"].getValue()+(o*100)) shuffleNode["ypos"].setValue(sel["ypos"].getValue()+150) shuffleNode.setInput(0,dot) shuffleNode["postage_stamp"].setValue(True) #auto crop if selected if self.autoCrop.getValue()==1.0: if autocropNodeRGB_exists==False: cropNode = nuke.nodes.Crop(name=channelLayer, inputs = [shuffleNode]) cropNode.knob("hide_input").setValue(True) cropNode.knob("box").copyAnimations(curveNode.knob("autocropdata").animations()) nuke.delete(curveNode) cropNode.knob("postage_stamp").setValue(True) cropNode.setXpos(int(shuffleNode["xpos"].getValue())) cropNode.setYpos(int(shuffleNode["ypos"].getValue()+80)) shuffleNode["hide_input"].setValue(False) cropNode["hide_input"].setValue(True) nukescripts.clear_selection_recursive() cropNode["selected"].setValue(True) nuke.nodeCopy("%clipboard%") autocropNodeRGB_exists=True shuffleNode["postage_stamp"].setValue(False) cropNode["postage_stamp"].setValue(True) else: cropCopy = nuke.nodePaste("%clipboard%") cropCopy["name"].setValue(channelLayer) cropCopy.setInput(0,shuffleNode) cropCopy.setXpos(int(shuffleNode["xpos"].getValue())) cropCopy.setYpos(int(shuffleNode["ypos"].getValue()+80)) #create folders for all layer and create write node for every shuffle if self.outputPath.getValue()!="": renderTo = self.outputPath.getValue() #createFolder createFolders(renderTo+"/"+channelLayer) #create write node write = nuke.nodes.Write() write.knob("file_type").setValue("exr") write.knob("file").setValue(renderTo+channelLayer+"/"+channelLayer+"_%04d.exr") write.knob("compression").setValue("Zip (16 scanlines)") write.knob("channels").setValue("rgba") if self.autoCrop.getValue()==True: write.setInput(0,cropNode) else: write.setInput(0,shuffleNode) o+=1 if len(layersToProcess)>0: nuke.delete(dot) #hide all created shuffle inputs for shuffleNode in shuffles: if self.autoCrop.getValue()==1.0: temp = nuke.toNode(shuffleNode) temp.knob("hide_input").setValue(True) temp.knob("postage_stamp").setValue(True) else: pass
def performCustomAction(): node = nuke.thisNode() knob = nuke.thisKnob() fileValue = node["file"].getValue() renderPath = os.path.dirname(fileValue) #reveal in explorer if knob.name() == "reveal in explorer": if renderPath != "": try: if platform.system() == "Windows": os.startfile(renderPath) elif platform.system() == "Darwin": subprocess.Popen(["open", renderPath]) else: subprocess.Popen(["xdg-open", renderPath]) except: nuke.message("couldn't open render path. No such directory") else: nuke.message("Please make sure to set a render path") #create next version if knob.name() == "create next version": if renderPath != "": nukescripts.clear_selection_recursive() node.setSelected(True) nukescripts.version_up() node.setSelected(False) fileValue = node["file"].getValue() renderPath = os.path.dirname(fileValue) if not os.path.isdir(renderPath): os.makedirs(renderPath) nuke.message("successfully versioned up") else: nuke.message("Renderfolder '%s' seems to exist" % renderPath) else: nuke.message("Please make sure to set a render path") #force create directory if knob.name() == "force create directory": if renderPath != "": if not os.path.isdir(renderPath): os.makedirs(renderPath) nuke.message( "successfully created render directory at: \n\n%s" % renderPath) else: nuke.message("render directory exists") else: nuke.message("Please make sure to set a render path") #save backup if knob.name() == "save backup": if knob.getValue() == 1.0: node["beforeRender"].setValue("nextVersion.saveBackup('%s')" % node.name()) else: node["beforeRender"].setValue("")