def hlink_paste(): nuke.nodePaste('%clipboard%') for node in hidden_inputs_in_selection(nuke.selectedNodes()): if 'hlink_node' in node.knobs(): target = nuke.toNode(node['hlink_node'].getValue()) if target: node.setInput(0, target)
def importAsset(self, iAObj=None): start, end = HelpFunctions.getFileSequenceStartEnd(iAObj.filePath) nuke.nodePaste(iAObj.filePath % start) if iAObj.options["importSettings"]: component = ftrack.Component(iAObj.componentId) parent = component.getVersion().getAsset().getParent() # Setup fps nuke.root()['fps'].setValue(parent.get('fps')) # Setup frame range nuke.root()['first_frame'].setValue(parent.get('fstart')) nuke.root()['last_frame'].setValue(parent.get('fend')) # Setup resolution width = parent.get("width") height = parent.get("height") fmt = None for f in nuke.formats(): if f.width() == width and f.height() == height: fmt = f if fmt: nuke.root()['format'].setValue(fmt.name()) return
def netPaste(): # Define temp directory on the network. filePath = '/data/share/nuke/netCopy/' fileList = nuke.getFileNameList(filePath) # Opens dialog box with pulldown choice of username. result = nuke.choice("NetPaste", "Pick Username", fileList) # If nothing is selected, do nothing. if result is None: return # Otherwise, select username and move to next step choice = fileList[result] # Define user file directory filePath2 = (os.path.join(filePath, choice)) fileList2 = nuke.getFileNameList(filePath2) # Opens dialog box with pulldown choice. result2 = nuke.choice("NetPaste", "Pick NetCopy", fileList2) # If the Cancel button is pressed, do nothing. if result is None or result2 is None: return # Otherwise, import script of selected username. choice2 = fileList2[result2] nuke.nodePaste(os.path.join(filePath2, choice2)) # Run cleanup cleanup(60, '/data/share/nuke/netCopy/')
def pv2_createGizmo(nuke): #create 2 scene nodes and select epScene = nuke.createNode("Scene") epScene.setName("Emitters") epScene.setXpos(0) epScene.setYpos(-100) #now create gizmo to have it auto connect nuke.nodePaste("~/.nuke/Particular3DGroup.nk") nuke.extractSelected() gizmo = nuke.selectedNode() gizmo.setXpos(0) gizmo.setYpos(0) gizmo.setInput(1,epScene) nuke.show(gizmo) #add version check if nuke.NUKE_VERSION_MINOR < 1 : #change cam values to work with translate values only gizmoParticularPath = "%s.Particular v2_1" % gizmo.name() camExpressionX = "p_cam.translate.x * parent.pv2_camXMultiplier" camExpressionY = "p_cam.translate.y * parent.pv2_camYMultiplier" camExpressionZ = "p_cam.translate.z" print "Camera cannot be parented to Axis node" nuke.toNode(gizmoParticularPath)['CameraPos'].setExpression(camExpressionX, 0) nuke.toNode(gizmoParticularPath)['CameraPos'].setExpression(camExpressionY, 1) nuke.toNode(gizmoParticularPath)['CameraPos'].setExpression(camExpressionZ, 2)
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 create_node(self): """ Creates a quick dailies node """ nk_file = os.path.join(self.disk_location, "resources", "quickdailynode.nk") nk_file = nk_file.replace(os.sep, "/") nuke.nodePaste(nk_file)
def get_view_process_node(self): # Select only the target node if nuke.selectedNodes(): [n.setSelected(False) for n in nuke.selectedNodes()] ipn_orig = None for v in [n for n in nuke.allNodes() if "Viewer" in n.Class()]: ip = v['input_process'].getValue() ipn = v['input_process_node'].getValue() if "VIEWER_INPUT" not in ipn and ip: ipn_orig = nuke.toNode(ipn) ipn_orig.setSelected(True) if ipn_orig: nuke.nodeCopy('%clipboard%') [n.setSelected(False) for n in nuke.selectedNodes()] # Deselect all nuke.nodePaste('%clipboard%') ipn = nuke.selectedNode() return ipn
def paste_knobs(checkboxes=False): # Override of the ctrl+alt+v shortcut which allows pasting of only specified knob values to selected nodes # Only a single source node is supported unlike the original # Based on nukescripts.misc.copy_knobs() # If not checkboxes, all knobs or a single knob can be chosen # If checkboxes, an arbitrary selection of knobs can be chosen grp = nuke.thisGroup() dst_nodes = grp.selectedNodes() copy_grp = nuke.nodes.Group(name='____tempcopyknobgroup__') with copy_grp: nuke.nodePaste('%clipboard%') src_nodes = copy_grp.nodes() if src_nodes: src_node = src_nodes[-1] excluded_knobs = ['name', 'xpos', 'ypos', 'selected'] try: intersect_knobs = dict() for dst_node in dst_nodes: src_knobs = src_node.knobs() dst_knobs = dst_node.knobs() intersection = dict( [(item, src_knobs[item]) for item in src_knobs.keys() \ if item not in excluded_knobs and dst_knobs.has_key(item)] ) intersect_knobs.update(intersection) knobs = intersect_knobs.keys() panel = nuke.Panel('Choose Knobs') panel.setWidth(250) if checkboxes: # Checkboxes for each knob for k in knobs: panel.addBooleanCheckBox(k, 0) else: panel.addEnumerationPulldown('knob', ' '.join(knobs)) panel.addBooleanCheckBox('paste all', 0) if not panel.show(): return chosen_knobs = list() if checkboxes: for k in knobs: if panel.value(k): chosen_knobs.append(k) else: paste_all = panel.value('paste all') if paste_all: chosen_knobs = knobs else: chosen_knobs.append(panel.value('knob')) for dst_node in dst_nodes: dst_knobs = dst_node.knobs() for knob in chosen_knobs: print 'pasting src {0} to dst {1}'.format(knob, dst_node.name()) src = src_knobs[knob] dst = dst_knobs[knob] dst.fromScript(src.toScript()) except Exception as e: nuke.delete(copy_grp) raise e nuke.delete(copy_grp)
def go(): print "Start copy" project = Project() proDir = project.get_project_dir() path = os.path.join(proDir, 'byu-pipeline-tools', 'nuke-tools', 'templates', 'grendel_general_template.nk') print path nuke.nodePaste(path) print "Finsih Copy"
def create_node(self): """ Creates a quick review node """ nk_file = os.path.join(self.disk_location, "resources", "tk_nuke_quickreview.nk") nk_file = nk_file.replace(os.sep, "/") nuke.nodePaste(nk_file)
def review(): new = nuke.toNode("Review") if new: nuke.show(new) else: nuke.nodePaste(UserDir + '/Folders/NukeScripts/review.nk') new = nuke.toNode("Review") nuke.show(new)
def template_results(self, files): for file in files: try: path = os.path.join(self.templates_dir, file) name, ext = os.path.splitext(file) nuke.nodePaste(path) except Exception as e: qd.warning(str(e))
def addFromMenu(project=''): if not project: group = nuke.nodePaste( '/Volumes/resources/tool_archive/internal/nuke/python/lutselect/LUT_Select_1.2.nk' ) elif project == 'Emma': group_path = '/Volumes/resources/tool_archive/internal/nuke/python/lutselect/LUT_Select_' + project + '.nk' group = nuke.nodePaste(group_path) setup(node=group, project='')
def paste_string(node_string): """ Pastes a given string and restore the previous clipboard""" clip = QApp.clipboard() bkp_txt = clip.text() clip.setText(node_string) nuke.nodePaste(r'%clipboard%') # restore previous clipboard clip.setText(bkp_txt)
def load(self, context, name, namespace, data): # get main variables version = context['version'] version_data = version.get("data", {}) vname = version.get("name", None) first = version_data.get("frameStart", None) last = version_data.get("frameEnd", None) fps = version_data.get("fps") or nuke.root()["fps"].getValue() namespace = namespace or context['asset']['name'] object_name = "{}_{}".format(name, namespace) # prepare data for imprinting # add additional metadata from the version to imprint to Avalon knob add_keys = ["source", "author", "fps"] data_imprint = { "frameStart": first, "frameEnd": last, "version": vname, "objectName": object_name } for k in add_keys: data_imprint.update({k: version_data[k]}) # getting file path file = self.fname.replace("\\", "/") with anlib.maintained_selection(): camera_node = nuke.createNode( "Camera2", "name {} file {} read_from_file True".format( object_name, file), inpanel=False) camera_node.forceValidate() camera_node["frame_rate"].setValue(float(fps)) # workaround because nuke's bug is not adding # animation keys properly xpos = camera_node.xpos() ypos = camera_node.ypos() nuke.nodeCopy("%clipboard%") nuke.delete(camera_node) nuke.nodePaste("%clipboard%") camera_node = nuke.toNode(object_name) camera_node.setXYpos(xpos, ypos) # color node by correct color by actual version self.node_version_color(version, camera_node) return containerise(node=camera_node, name=name, namespace=namespace, context=context, loader=self.__class__.__name__, data=data_imprint)
def toolsetLoader(fullFileName): if FILE_FILTER != None: data = fileFilter(fullFileName, FILE_FILTER) #TODO: find better way to paste filtred script QApplication.clipboard().setText(data) nuke.nodePaste("%clipboard%") # paste into nuke DAG else: nuke.loadToolset(fullFileName) return True
def import_script(): try: if nuke.env['nc']: spec = "*.nk; *.nknc; *.gizmo; *.gznc" else: spec = "*.nk; *.gizmo" s = nuke.getFilename("Import Script", spec, "", "script") nuke.nodePaste(s) except: pass
def buildCompScript(layerOrderFile, compScriptFile, isRunningFromScript): # kept here if script is run from the comp itself if not os.path.isfile(layerOrderFile): print "Could not find layer_order.yml in " + shotDir sys.exit() if not isRunningFromScript: nuke.scriptClear() # get nuke script to build nuke.scriptOpen(compScriptFile) nuke.selectAll() [nuke.delete(node) for node in nuke.selectedNodes()] # arrange templates in the given nuke script in vertical order templates = getTemplateList(layerOrderFile) for i, template in enumerate(templates): nuke.nodePaste(template) bdNodes = nuke.selectedNodes() node = nuke.selectedNodes("BackdropNode")[0] dotNode = nuke.selectedNodes('Dot')[0] if i > 0: bdNodes.remove(node) nodePrevX = node.xpos() nodePrevY = node.ypos() node.setYpos(previousNode.ypos() + 500) node.setXpos(previousNode.xpos()) for n in bdNodes: if n.ypos() > nodePrevY: n.setYpos(node.ypos() + (n.ypos() - nodePrevY)) else: n.setYpos(node.ypos() + (n.ypos() + nodePrevY)) if n.xpos() > nodePrevX: n.setXpos(node.xpos() + (n.xpos() - nodePrevX)) else: n.setXpos(node.xpos() + (n.xpos() + nodePrevX)) if i > 1: dotNode.setInput(0, previousDotNode.dependent()[0]) else: dotNode.setInput(0, previousDotNode) previousNode = node previousDotNode = dotNode if not isRunningFromScript: # save nuke script nuke.scriptSave(compScriptFile) # avoid opening GUI and getting extra nodes from previous script nuke.scriptClose() # remove temp files [os.remove(template) for template in templates if "temp" in template]
def load_scene(self): import nuke current_scene_version = self.current_scene_version path = current_scene_version.getComponent(name='nukescript').getFilesystemPath() if not path or not os.path.exists(path): self.header.setMessage('file %s does not exist!', 'error') return nuke.nodePaste(path) asset_name = current_scene_version.getParent().getName() asset_version = current_scene_version.get('version') self.header.setMessage('Asset %s version %s loaded.' % (asset_name, asset_version) , 'info')
def reduce_selected_brush_stroke(withDefaults=False): #------------------------ # SETTINGS #------------------------ epsilon = 10 #Your threshold frame = nuke.frame() #The frame to reference... rpNode = nuke.selectedNode() #The node to process makeCopy = False #Since nuke.Undo is broken, we want to make a backup if not withDefaults: #Make a little fancy menu p = nuke.Panel('Reduce Brush Strokes :: Settings') p.addSingleLineInput('Epsilon', '10') p.addBooleanCheckBox('Make Copy of Node?', False) ret = p.show() epsilon = float(p.value('Epsilon')) makeCopy = p.value('Make Copy') if makeCopy: #Make a copy of the selected node. originalNode = rpNode nuke.nodeCopy('%clipboard%') nuke.nodePaste('%clipboard%') rpNode = nuke.selectedNode() rpNode.setInput(0,originalNode.input(0)) solver = DPAlgorithm() #The algorithm object cKnob= rpNode['curves'] selectedShapes = cKnob.getSelected() task = nuke.ProgressTask('Reducing Roto...') task.setProgress(0) for i,shape in enumerate(selectedShapes) : thisShape = [] alen = float(len(selectedShapes)) #Used to calculate progress try: for x,p in enumerate(shape) : #Get a list of all the points in the roto shape tempPosition = p.getPosition(frame) thisShape.append([tempPosition[0],tempPosition[1],x]) reducedShape = solver.rdp(thisShape,epsilon) #Magic happens here.. reduce the shape for x,p in reversed( list( enumerate( shape) ) ) : #Go through all of the points in reversed order and remove the ones that are not in the reduced list slen=float(len(shape)) #Used to calculate progress tempPosition = p.getPosition(frame) #LAZY!!! if not [tempPosition[0],tempPosition[1],x] in reducedShape : shape.remove(x) #Damn, this thing is slow! (could be threaded!?) task.setProgress(int(((float(i)/alen)+((float(slen-x)/slen)/alen))*100.0)) #Update the progress bar task.setMessage("Processing point %s in brush %s (yes, this is slow)" %(x,i)) except: pass #Not a supported item task.setProgress(100)
def _import_script(self, path, sg_data): """ Import contents of the given file into the scene. :param path: Path to file. :param sg_data: Shotgun data dictionary with all the standard publish fields. """ import nuke if not os.path.exists(path): raise Exception("File not found on disk - '%s'" % path) nuke.nodePaste(path)
def _import_script(self, path, sg_publish_data): """ Import contents of the given file into the scene. :param path: Path to file. :param sg_publish_data: Shotgun data dictionary with all the standard publish fields. """ import nuke if not os.path.exists(path): raise Exception("File not found on disk - '%s'" % path) nuke.nodePaste(path)
def paste_nodes(self, user): """ Select from a list generated from the current users that have added to directory, once the selection has been made added selected script to current nuke script... """ path_to_paste = os.path.join(SAVED_SCRIPT_DIR, user + '.nk') nuke.nodePaste(path_to_paste) self.set_pref(user) return 1
def _import_script(self, new_script_path): """ Import contents of the given file into the scene. :param path: Path to file. :param sg_publish_data: Shotgun data dictionary with all the standard publish fields. """ # first we look at the current read nodes in the scene (they've been updated to their latest version already) preloaded_nodes = nuke.allNodes('Read') # We import the new nodes into the scene # if not os.path.exists(new_path): # raise Exception("File not found on disk - '%s'" % new_path) nuke.nodePaste(new_script_path) node = nuke.toNode('Published Data') node['text'].setValue(new_script_path) # Compare the new nodes with the old ones and delete the duplicates new_nodes = [item for item in nuke.allNodes('Read') if item not in preloaded_nodes] # Initialise the tank tk = sgtk.sgtk_from_path(new_script_path) # Get the maya render template maya_render_template = tk.templates["maya_shot_render"] cleanup_list = [] # Iterate through all the node for new_node in new_nodes: new_path = new_node['file'].value() # Is it a published render if maya_render_template.validate(new_path): new_fields = maya_render_template.get_fields(new_path) # Iterate through all the pre loaded node for old_node in preloaded_nodes: old_path = old_node['file'].value() # Is it a published node if maya_render_template.validate(old_path): old_fields = maya_render_template.get_fields(old_path) # Compare the fields if (new_fields['Shot'] == old_fields['Shot'] and new_fields['render_layer'] == old_fields['render_layer'] and new_fields['version'] > old_fields['version']): old_node["file"].setValue(new_path) cleanup_list.append(new_node) self.color_updated_read_node(old_node) #Delete any redundents nodes for node in list(set(cleanup_list)): nuke.delete(node )
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(1) nuke.nodePaste('%clipboard%') node['selected'].setValue(0) for node in selection: toggleSelection(node)
def paste_to_selected(): nodes = nuke.selectedNodes() all_nodes = nuke.allNodes() unselect() for node in nodes: node.setSelected(True) nuke.nodePaste('%clipboard') unselect() if not nodes: nuke.nodePaste('%clipboard') # Select pasted nodes select(all_nodes) nuke.invertSelection()
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 importScript(): """import exported nuke script from maya""" crosswalkFile = 'mayaToNuke.info' if os.path.exists(crosswalkFile): fileInfo = open(crosswalkFile, 'r') text = fileInfo.readlines() dic = eval(text[-1]) nkFile = dic.get('file') if os.path.exists(nkFile): print 'importing: '+nkFile nuke.nodePaste(nkFile) else: print 'nuke script not found...'
def run(node): clipboard = QtGui.QApplication.clipboard() filename = node['file'].evaluate() filesplit = filename.rsplit('.',-2) filesplit[1] = '%0'+str(len(filesplit[1]))+'d' filep = '.'.join(filesplit) filenameFrame = nuke.getFileNameList(os.path.dirname(filep))[0].rsplit(' ',-1)[1] clipboard.setText(( filep+" "+filenameFrame)) nuke.nodePaste("%clipboard%")
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 importBaseScene(self): """Imports the scene at cursor position""" logger.debug("Func: importBaseScene") relSceneFile = self._currentSceneInfo["Versions"][ self._currentVersionIndex - 1]["RelativePath"] absSceneFile = os.path.join(self.projectDir, relSceneFile) if os.path.isfile(absSceneFile): # cmds.file(absSceneFile, i=True) nuke.nodePaste(absSceneFile) return 0 else: msg = "File in Scene Manager database doesnt exist" self._exception(210, msg) return -1, msg
def _import_script(self, path, sg_publish_data): """ Import contents of the given file into the scene. :param path: Path to file. :param sg_publish_data: Shotgun data dictionary with all the standard publish fields. """ import nuke # must use unicode otherwise path won't be found if not os.path.exists(six.ensure_str(path)): raise Exception("File not found on disk - '%s'" % path) nuke.nodePaste(path)
def _import_script(self, path, sg_publish_data): """ Import contents of the given file into the scene. :param path: Path to file. :param sg_publish_data: Shotgun data dictionary with all the standard publish fields. """ import nuke if not os.path.exists(path): raise Exception("File not found on disk - '%s'" % path) nuke.nodePaste(path) # Pritish Modification Tracking our published nuke scripts self._create_DO_NOT_TOUCH_NODE(path, sg_publish_data)
def copy_viewer_input(node=None): """ :param node: viewerInput :return: copy of current Viewer input """ orig = nuke.selectedNodes() [x.setSelected(False) for x in nuke.selectedNodes()] node.setSelected(True) nuke.nodeCopy("%clipboard%") node.setSelected(False) nuke.nodePaste("%clipboard%") new_node = nuke.selectedNode() [x.setSelected(False) for x in nuke.selectedNodes()] [x.setSelected(True) for x in orig] return new_node
def getFilesAndVerify(self): ''' get user inputs and find a better way of compacting if below ''' sw1 = 0 if (self.getfbxCam() == 0): if (self.getfbxGroup() == 0): if (self.getNkFile() == 0): for each in range(0,len(self.nkFile)): self.groupNode.append(nuke.nodePaste(self.nkFile[each])) print 'self.nkFile[each]',self.nkFile else: print '3names not matching ... get them to match then come here ... ' sw1 = 1 else: print '2names not matching ... get them to match then come here ... ' sw1 = 1 else: print '1names not matching ... get them to match then come here ... ' sw1 = 1 ''' verify that no group object is nonetype ''' for a in self.groupNode: if isinstance(a,NoneType): sw1 = 1 return sw1
def levelDistinction(self): ''' create scene and camera node ''' swch = 0 self.camera = nuke.createNode('Camera2', 'read_from_file true file %s' % self.fbxCamFile,inpanel=False) self.camera.forceValidate() self.camera.setXYpos( -77 , -1282 ) self.bDropA = nuke.createNode('BackdropNode', inpanel=False) self.bDropA['label'].setValue('Cam imported from Maya') self.bDropA.setXYpos( -149 , -1360 ) self.bDropA['bdwidth'].setValue(180) self.bDropA['bdheight'].setValue(260) self.scene = nuke.createNode('Scene',inpanel=False) self.scene.setXYpos( -100 , -70) ''' from within each of fg mg and bg read sub levels , call createNodeSet for each of them ''' for single in self.nkNodeList: copiedNode = nuke.nodePaste(single) self.SceneIncr = self.SceneIncr + 1 retv = self.createNodeSet(copiedNode,self.SceneIncr) return swch
def testDefaultExpression( self ) : # create opholder and check the default expression we asked for works fnOH = IECoreNuke.FnOpHolder.create( "op", "add", 1 ) self.assertEqual( fnOH.node().knob( "parm_a" ).toScript(), '{"frame * 2"}' ) self.failUnless( fnOH.node().knob( "parm_a" ).isAnimated() ) self.assertEqual( nuke.frame(), 1 ) self.assertEqual( fnOH.node().knob( "parm_a" ).getValue(), 2 ) # remove the expression, cut and paste the node, and make sure # it doesn't reappear fnOH.node().knob( "parm_a" ).clearAnimated() self.failIf( fnOH.node().knob( "parm_a" ).isAnimated() ) nuke.nodeCopy( "test/IECoreNuke/parameterisedHolder.nk" ) nuke.scriptClear() n = nuke.nodePaste( "test/IECoreNuke/parameterisedHolder.nk" ) fnOH = IECoreNuke.FnOpHolder( n ) self.assertEqual( fnOH.node().knob( "parm_a" ).toScript(), "2" )
def testDefaultExpression(self): # create opholder and check the default expression we asked for works fnOH = IECoreNuke.FnOpHolder.create("op", "add", 1) self.assertEqual(fnOH.node().knob("parm_a").toScript(), '{"frame * 2"}') self.failUnless(fnOH.node().knob("parm_a").isAnimated()) self.assertEqual(nuke.frame(), 1) self.assertEqual(fnOH.node().knob("parm_a").getValue(), 2) # remove the expression, cut and paste the node, and make sure # it doesn't reappear fnOH.node().knob("parm_a").clearAnimated() self.failIf(fnOH.node().knob("parm_a").isAnimated()) nuke.nodeCopy("test/IECoreNuke/parameterisedHolder.nk") nuke.scriptClear() n = nuke.nodePaste("test/IECoreNuke/parameterisedHolder.nk") fnOH = IECoreNuke.FnOpHolder(n) self.assertEqual(fnOH.node().knob("parm_a").toScript(), "2")
def main(): grp=nuke.thisNode() for n in nuke.allNodes(): try: path=n.filename() if 'gizmo' in path: name=n.name() nodeInputs=[] for i in range(n.inputs()): nodeInputs.append(n.input(i)) nPos=[n.xpos(),n.ypos()] nName=n.name() c = n.makeGroup() c.setSelected(1) nuke.nodeCopy('%clipboard%') nuke.delete(c) with grp: n.setSelected(1) c=nuke.nodePaste('%clipboard%') nuke.delete(n) c.setXYpos(nPos[0],nPos[1]) c.setName(nName) for i in range(len(nodeInputs)): c.setInput(i,nodeInputs[i]) except: pass
def copyNode(self): nuke.nodeCopy('%clipboard%') copied = nuke.nodePaste('%clipboard%') copied.setInput(0, None) # remove dependencies if len(copied.dependent()) > 0: copied.dependent()[0].setInput(0, None) return copied
def add_lens_to_nuke(self, file_path, shotgun_data, publish_record): """ Import a lens node script to the current scene """ import nuke # get the slashes right file_path = file_path.replace(os.path.sep, "/") (path, ext) = os.path.splitext(file_path) file_name = "%s_%s_v%03d" % (publish_record['entity']['name'], publish_record['name'], publish_record['version_number']) if ext == ".nk": # import the nodes print "Adding nodes from %s" % file_path nuke.nodePaste(file_path) else: self.parent.log_error("Lens is not a nuke script! I don't know how to import")
def copySpecial(): """copy selection, paste and reconnect (just one node)""" depNode = nuke.dependencies(nuke.selectedNode()) dependNode = nuke.dependentNodes(nuke.INPUTS or nuke.HIDDEN_INPUTS or nuke.EXPRESSIONS, [nuke.selectedNode()]) i = 0 if dependNode[0].Class() in ['Scene', 'MergeGeo']: i = nuke.inputs(dependNode[0])+1 nuke.nodeCopy(nukescripts.cut_paste_file()) for node in nuke.allNodes(): node['selected'].setValue(0) nuke.nodePaste(nukescripts.cut_paste_file()) newNode = nuke.selectedNode() newNode.setInput(0, depNode[0]) dependNode[0].setInput(i+1, newNode)
def testCopyPasteNoValue( self ) : n = nuke.createNode( "ieObject" ) self.assertEqual( nuke.selectedNodes(), [ n ] ) nuke.nodeCopy( "test/IECoreNuke/objectKnob.nk" ) nuke.scriptClear() n2 = nuke.nodePaste( "test/IECoreNuke/objectKnob.nk" ) self.assertEqual( n2.knob( "object" ).getValue(), None )
def duplicateNode(node): # Store selection orig_selection = nuke.selectedNodes() # Select only the target node [n.setSelected(False) for n in nuke.selectedNodes()] node.setSelected(True) # Copy the selected node and clear selection again nuke.nodeCopy("%clipboard%") node.setSelected(False) nuke.nodePaste("%clipboard%") duplicated_node = nuke.selectedNode() # Restore original selection [n.setSelected(False) for n in nuke.selectedNodes()] # Deselect all [n.setSelected(True) for n in orig_selection] # Select originally selected return duplicated_node
def duplicate_node(self, node, to_file=None): """Slightly convoluted but reliable(?) way duplicate a node, using the same functionality as the regular copy and paste. Could almost be done tidily by doing: for knobname in src_node.knobs(): value = src_node[knobname].toScript() new_node[knobname].fromScript(value) ..but this lacks some subtly like handling custom knobs to_file can be set to a string, and the node will be written to a file instead of duplicated in the tree """ import nuke # Store selection orig_selection = nuke.selectedNodes() # Select only the target node [n["selected"].setValue(False) for n in nuke.selectedNodes()] node["selected"].setValue(True) # If writing to a file, do that, restore the selection and return if to_file is not None: nuke.nodeCopy(to_file) [n["selected"].setValue(False) for n in orig_selection] return # Copy the selected node and clear selection again nuke.nodeCopy("%clipboard%") node["selected"].setValue(False) if to_file is None: # If not writing to a file, call paste function, and the new node # becomes the selected nuke.nodePaste("%clipboard%") new_node = nuke.selectedNode() # Restore original selection [n["selected"].setValue(False) for n in nuke.selectedNodes()] [n["selected"].setValue(True) for n in orig_selection] return new_node
def runTool(self, toolPath, call): toolPath = os.path.join(rootPath, os.path.split(toolPath)[1]) self.toolData = getData(toolPath).gotData if os.path.splitext(os.path.split(toolPath)[1])[1]==".nk": print os.path.splitext(os.path.split(toolPath)[1])[1] clipboard = QtGui.QApplication.clipboard() clipboard.setText(self.toolData) if len(nuke.selectedNodes()): sn = nuke.selectedNode() np=nuke.nodePaste("%clipboard%") g=nuke.selectedNode() g.setInput(0, sn) g.setXpos(sn.xpos()) g.setYpos(sn.ypos()+ 60) else: nuke.nodePaste("%clipboard%") elif os.path.splitext(os.path.split(toolPath)[1])[1]==".py": print call #code_obj = compile(self.toolData, '<string>, 'exec') #exec(code_obj) in globals(), locals() #exec(call) exec(self.toolData+'\n'+call)
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 testCopyPaste(self): fnPH = IECoreNuke.FnProceduralHolder.create("procedural", "read", 1) nuke.nodeCopy("test/IECoreNuke/parameterisedHolder.nk") nuke.scriptClear() n = nuke.nodePaste("test/IECoreNuke/parameterisedHolder.nk") fnPH = IECoreNuke.FnProceduralHolder(n) p = fnPH.getParameterised() self.assertEqual(p[1], "read") self.failUnless(isinstance(p[2], int)) self.assertEqual(p[2], 1) self.assertEqual(p[3], "IECORE_PROCEDURAL_PATHS")
def testClassParameterSetClassAndValues( self ) : fnOH = IECoreNuke.FnOpHolder.create( "test", "classParameterTest", 1 ) with fnOH.parameterModificationContext() as parameterised : parameterised["cp"].setClass( "maths/multiply", 2 ) parameterised["cp"]["a"].setNumericValue( 10 ) parameterised["cp"]["a"].setNumericValue( 20 ) self.__checkParameterKnobs( parameterised.parameters(), fnOH.node() ) nuke.nodeCopy( "test/IECoreNuke/parameterisedHolder.nk" ) nuke.scriptClear() n = nuke.nodePaste( "test/IECoreNuke/parameterisedHolder.nk" ) fnOH = IECoreNuke.FnOpHolder( n ) parameterised2 = fnOH.getParameterised()[0] self.assertEqual( parameterised.parameters().getValue(), parameterised2.parameters().getValue() )
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 nodePaste(*args): args = cleanArgs(args) file = args[0] nuke.nodePaste(file)
def import_(self, version): """the import action for nuke environment """ nuke.nodePaste(version.full_path) return True
def convertSequence(input_folder, category_name, thread_count=0, done_callback=None): if not os.path.exists("W:\\Categories\\" + category_name): print( "Invalid category name ", category_name) return None if not os.path.exists(input_folder): print("Invalid input folder ", input_folder) return None if thread_count == 0: thread_count = multiprocessing.cpu_count() # potential sequence files unsorted_files = filter(lambda f: os.path.isfile(os.path.join(input_folder, f)) and (os.path.splitext(f)[1][1:] in valid_extensions), os.listdir(input_folder)) # Sort by extension first to avoid the following failure case in the sequence-finding code below: # foo.0001.exr # foo.0001.jpg in same folder files = sorted(unsorted_files, key=lambda f: os.path.splitext(f)[::-1]) print "Found ", len(files), " movie/image files" # Find all sequences. sequences = [] last_prefix = None last_ext = None seq_start = 0 seq_end = 0 counter = len(files) for file in files: components = file.split(".") ext = os.path.splitext(file)[1][1:] new_seq = False is_movie = False is_img = False if len(components) >= 3 and ext in image_extensions: prefix = ".".join(components[0:-2]) is_img = True elif len(components) == 2 and ext in mov_extensions: prefix = components[0] is_movie = True # new sequence start => insert the last sequence if prefix != last_prefix or ext != last_ext: if not (last_prefix is None): sequences.append(SequenceImg(last_prefix, seq_start, seq_end, last_ext)) new_seq = True # handle the current file if is_movie: # movies are treated as single-file sequences prefix = components[0] sequences.append(SequenceMov(prefix,ext)) elif is_img: frame = components[-2] if new_seq: seq_start = int(frame) last_prefix = prefix last_ext = ext seq_end = int(frame) if counter == 1: # last file sequences.append(SequenceImg(last_prefix, seq_start, seq_end, last_ext)) counter -= 1 print("Found sequences: ") for seq in sequences: print seq # conversion nuke.nodePaste("converter.nk") reader = nuke.toNode("Read1") source_writer = nuke.toNode("Write_Source") proxy_writer = nuke.toNode("Write_Proxy") thumb_writer = nuke.toNode("Write_Thumb") thumb_retime = nuke.toNode("Thumb_Retime") thumb_reformat = nuke.toNode("Reformat_Thumb") tempfiles = [] tempdir = tempfile.mkdtemp() print ("tempdir is ", tempdir) # contains metadata from conversion process results = [] # Generate Nuke scripts with the correct paths etc in a temporary directory nxttmpfile = 0 for seq in sequences: cur_metadata = {} reader['file'].fromUserText(os.path.join(input_folder, seq.inputpath())) # determine info from Read node input_dims = (int(reader.format().width()), int(reader.format().height())) aspect_ratio = input_dims[0] / float(input_dims[1]) thumb_height = int(thumb_width / aspect_ratio) input_range = (int(nuke.toNode("Read1")['first'].getValue()), int(nuke.toNode("Read1")['last'].getValue())) cur_metadata["name"] = seq.basename() cur_metadata["width"] = input_dims[0] cur_metadata["height"] = input_dims[1] cur_metadata["startFrame"] = input_range[0] cur_metadata["numOfFrames"] = input_range[1] - input_range[0] nuke_metadata = nuke.toNode("Read1").metadata() cur_metadata["fps"] = int(nuke_metadata['input/frame_rate']) cur_metadata["extra_metadata"] = nuke_metadata # Set thumbnail retiming thumb_retime['input.first'].setValue(input_range[0]) thumb_retime['input.last'].setValue(input_range[1]) thumb_count = int(thumb_retime['output.last'].value()) # Set thumbnail format thumb_reformat['format'].setValue(nuke.addFormat(str(thumb_width) + " " + str(thumb_height) + " 1")) # Generate output dirs out_root = os.path.join(outputpath, category_name, seq.basename()) dirs = (os.path.join(out_root, "Source"), os.path.join(out_root, "Proxy"), os.path.join(out_root, "Thumbnails")) for dir in dirs: if not os.path.exists(dir): os.makedirs(dir) (source_dir, proxy_dir, thumb_dir) = dirs # Set output names source_writer['file'].fromUserText(os.path.join(source_dir, seq.basename() + ".####." + "exr")) proxy_writer['file'].fromUserText(os.path.join(proxy_dir, seq.basename() + ".####." + "jpg")) thumb_writer['file'].fromUserText(os.path.join(thumb_dir, seq.basename() + ".####." + "jpg")) # proxyWriter('_jpeg_quality').setValue(0.9) # not needed since we do this kind of thing in the predefined nuke script itself filepath = os.path.join(tempdir, str(nxttmpfile) + ".nk") nuke.scriptSaveAs(filepath) tempfiles.append((filepath, "Write_Thumb", 1, thumb_count)) tempfiles.append((filepath, "Write_Proxy", input_range[0], input_range[1])) tempfiles.append((filepath, "Write_Source", input_range[0], input_range[1])) nxttmpfile += 1 results.append(cur_metadata) print "Starting conversion..." do_conversion(tempfiles, tempdir, thread_count) print "Finished conversion" return results
if fileExt == '.3dl' or fileExt == '.blur' or fileExt == '.csp' or fileExt == '.cub' or fileExt == '.cube' or fileExt == '.vf' or fileExt == '.vfz': r = nuke.createNode('Vectorfield', inpanel=False) r['vfield_file'].setValue(dropdata) r['selected'].setValue(0) return if fileExt == '.chan': r = nuke.createNode('Camera2', inpanel=False) nuke.tcl('in %s {import_chan_file %s}' %(r.name(), dropdata)) r['selected'].setValue(0) return if fileExt == '.nk': try: r = nuke.nodePaste(dropdata) except Exception, e: log_('Error %s' % e) pass return if fileExt == '.py': try: r = nuke.load(dropdata) except Exception, e: log_('Error %s' % e) pass return if fileExt in (None, False, '', '.db', '.sni', '.ma', '.mb', '.hip', '.sfx', '.xml', '.pkl', '.tmp', 'otl'): log_('Ignore')
def render_movie_in_nuke(self, path, output_path, width, height, first_frame, last_frame, version, name, color_space): """ Use Nuke to render a movie. This assumes we're running _inside_ Nuke. :param path: Path to the input frames for the movie :param output_path: Path to the output movie that will be rendered :param width: Width of the output movie :param height: Height of the output movie :param first_frame: Start frame for the output movie :param last_frame: End frame for the output movie :param version: Version number to use for the output movie slate and burn-in :param name: Name to use in the slate for the output movie :param color_space: Colorspace of the input frames """ output_node = None ctx = self.__app.context # create group where everything happens group = nuke.nodes.Group() # now operate inside this group group.begin() try: # create read node read = nuke.nodes.Read(name="source", file=path.replace(os.sep, "/")) read["on_error"].setValue("black") read["first"].setValue(first_frame) read["last"].setValue(last_frame) if color_space: read["colorspace"].setValue(color_space) # now create the slate/burnin node burn = nuke.nodePaste(self._burnin_nk) burn.setInput(0, read) # set the fonts for all text fields burn.node("top_left_text")["font"].setValue(self._font) burn.node("top_right_text")["font"].setValue(self._font) burn.node("bottom_left_text")["font"].setValue(self._font) burn.node("framecounter")["font"].setValue(self._font) burn.node("slate_info")["font"].setValue(self._font) # add the logo burn.node("logo")["file"].setValue(self._logo) # format the burnins version_padding_format = "%%0%dd" % self.__app.get_setting("version_number_padding") version_str = version_padding_format % version if ctx.task: version_label = "%s, v%s" % (ctx.task["name"], version_str) elif ctx.step: version_label = "%s, v%s" % (ctx.step["name"], version_str) else: version_label = "v%s" % version_str burn.node("top_left_text")["message"].setValue(ctx.project["name"]) burn.node("top_right_text")["message"].setValue(ctx.entity["name"]) burn.node("bottom_left_text")["message"].setValue(version_label) # and the slate slate_str = "Project: %s\n" % ctx.project["name"] slate_str += "%s: %s\n" % (ctx.entity["type"], ctx.entity["name"]) slate_str += "Name: %s\n" % name.capitalize() slate_str += "Version: %s\n" % version_str if ctx.task: slate_str += "Task: %s\n" % ctx.task["name"] elif ctx.step: slate_str += "Step: %s\n" % ctx.step["name"] slate_str += "Frames: %s - %s\n" % (first_frame, last_frame) burn.node("slate_info")["message"].setValue(slate_str) # create a scale node scale = self.__create_scale_node(width, height) scale.setInput(0, burn) # Create the output node output_node = self.__create_output_node(output_path) output_node.setInput(0, scale) finally: group.end() if output_node: # Make sure the output folder exists output_folder = os.path.dirname(output_path) self.__app.ensure_folder_exists(output_folder) # Render the outputs, first view only nuke.executeMultiple([output_node], ([first_frame-1, last_frame, 1],), [nuke.views()[0]]) # Cleanup after ourselves nuke.delete(group)
def setLocal(): # path variables repo = '/mnt/karramba' home = '/home/tfx/job.local' # clears the selection if smth was selected for node in nuke.allNodes(): node.setSelected(False) # copies footage to local machine readList = [node.knob('file').value() for node in nuke.allNodes('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]] newPath = home + path.rsplit(os.sep, 1)[0].split(repo)[-1] + os.sep if not os.path.exists(newPath): os.makedirs(newPath) for img in fileDirList: if not os.path.isdir(img): shutil.copy(img, newPath) #creates new read nodes and controller to switch controller between local and network for node in nuke.allNodes('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) n = nuke.createNode('NoOp') n.setName('locController') k = nuke.Double_Knob('location', 'location') k.setRange(0, 1) n.addKnob(k) n.knob('hide_input').setValue(True) n.setXpos(nuke.toNode(findHighestRead()).xpos() + 500) n.setYpos(nuke.toNode(findHighestRead()).ypos()) n.setSelected(False) st = nuke.createNode('StickyNote', inpanel=False) st.setName('status') st.setXpos(n.xpos()) st.setYpos(n.ypos()-50) st.knob('label').setValue('LOCAL') st.knob('note_font_size').setValue(35) nuke.addKnobChanged(switchStatus, nodeClass='NoOp')