def get_min_max(src_node, channel='depth.Z'): ''' Return the min and max values of a given node's image as a tuple args: src_node - node to analyse channels - channels to analyse. This can either be a channel or layer name ''' min_color = nuke.nodes.MinColor(channels=channel, target=0, inputs=[src_node]) inv = nuke.nodes.Invert(channels=channel, inputs=[src_node]) max_color = nuke.nodes.MinColor(channels=channel, target=0, inputs=[inv]) cur_frame = nuke.frame() nuke.execute(min_color, cur_frame, cur_frame) min_v = -min_color['pixeldelta'].value() nuke.execute(max_color, cur_frame, cur_frame) max_v = max_color['pixeldelta'].value() + 1 for n in (min_color, max_color, inv): nuke.delete(n) return min_v, max_v
def delMyBackdrops(self): allMyBackdrops = nuke.allNodes('BackdropNode') for myBackdrop in allMyBackdrops: namebackdrop = myBackdrop.knob('name').value() if namebackdrop.find('Lack Frames') >= 0 or namebackdrop.find( 'Wrong Name') >= 0: nuke.delete(myBackdrop)
def nuke_viewerSnapshot(img_path=DEFAULT_PATH): LOG.info("nuke_viewerSnapshot") import nuke viewer = nuke.activeViewer() viewNode = nuke.activeViewer().node() actInput = nuke.ViewerWindow.activeInput(viewer) if actInput < 0: return False selInput = nuke.Node.input(viewNode, actInput) # look up filename based on top read node topName = "[file tail [knob [topnode].file]]" # create writes and define render format write1 = nuke.nodes.Write( file=img_path.replace("\\", "/"), name='writeNode1', file_type=Tank().data_project['EXTENSION']['thumnail']) write1.setInput(0, selInput) # look up current frame curFrame = int(nuke.knob("frame")) # start the render nuke.execute(write1.name(), curFrame, curFrame) # clean up for n in [write1]: nuke.delete(n)
def process(self, context, plugin): # Get the errored instances failed = [] for result in context.data["results"]: if (result["error"] is not None and result["instance"] is not None and result["instance"] not in failed): failed.append(result["instance"]) # Apply pyblish.logic to get the instances for the plug-in instances = pyblish.api.instances_by_plugin(failed, plugin) for instance in instances: data = toml.loads(instance[0]["avalon"].value()) data["xpos"] = instance[0].xpos() data["ypos"] = instance[0].ypos() data["input"] = instance[0].input(0) data["publish"] = instance[0]["publish"].value() data["render"] = instance[0]["render"].value() data["render_farm"] = instance[0]["render_farm"].value() nuke.delete(instance[0]) family = "render{}".format(os.environ["AVALON_TASK"].capitalize()) api.create(data["subset"], data["asset"], family) node = nuke.toNode(data["subset"]) node.setXYpos(data["xpos"], data["ypos"]) node.setInput(0, data["input"]) node["publish"].setValue(data["publish"]) node["render"].setValue(data["render"]) node["render_farm"].setValue(data["render_farm"])
def getCentralPosition(): """ Returns the position of the center of the graph view. """ dd = nuke.createNode("NoOp") x = dd.xpos() y = dd.ypos() nuke.delete(dd) return (x, y)
def check_bounding_box(self, instance): node = instance[0] first_frame = instance.data["frameStart"] last_frame = instance.data["frameEnd"] format_width = node.format().width() format_height = node.format().height() # The trick is that we need to execute() some node every time we go to # a next frame, to update the context. # So we create a CurveTool that we can execute() on every frame. temporary_node = nuke.nodes.CurveTool() bbox_check = True for frame in range(first_frame, last_frame + 1): # Workaround to update the tree nuke.execute(temporary_node, frame, frame) x = node.bbox().x() y = node.bbox().y() w = node.bbox().w() h = node.bbox().h() if x < 0 or (x + w) > format_width: bbox_check = False break if y < 0 or (y + h) > format_height: bbox_check = False break nuke.delete(temporary_node) return bbox_check
def importPngSeqs(imagesPath): import nuke imagesTypes = "png" rule = r'(.*?)(\d+)(\.(?:%s))' % imagesTypes pattern = re.compile(rule) nukeReadSeqs = [] imagesBaseName = [] for root, dirs, files in os.walk(imagesPath): imagesSeq = [x for x in files if x.split('.')[-1] in imagesTypes] if imagesSeq != []: imagesSeq.sort() for f in imagesSeq: print pattern.findall(f) if pattern.findall(f) == []: # nuke.createNode("Read",inpanel=False)["file"].setValue(root+'/'+f) nukeReadSeqs.append([root + '/' + f, 1, 1]) elif pattern.findall(f)[0][0] not in imagesBaseName: firstFrame = int(pattern.findall(f)[0][1]) imagesBaseName.append(pattern.findall(f)[0][0]) nukeReadSeqs.append([root + '/' + pattern.findall(f)[0][0] + '#' * len(pattern.findall(f)[0][1]) + pattern.findall(f)[0][2], firstFrame, firstFrame]) else: nukeReadSeqs[-1][2] += 1 for readSeq in nukeReadSeqs: n = nuke.createNode("Read", inpanel=False) n["file"].setValue(readSeq[0]) n["first"].setValue(readSeq[1]) n["last"].setValue(readSeq[2]) nuke.delete(nuke.thisNode()) return n
def main(): nSel = nuke.selectedNodes() cam = '' first = int(nuke.root()['first_frame'].value()) last = int(nuke.root()['last_frame'].value()) for n in nSel: if n.Class() == 'Camera2': cam = n if not cam: nuke.message('must have a camera in selection') if cam: for n in nSel: if not n.Class() == 'Camera2': #create reconcile and constant c = nuke.nodes.Constant() rec = nuke.nodes.Reconcile3D() rec.setInput(0, c) rec.setInput(1, cam) rec.setInput(2, n) nuke.execute(rec, first, last) tr = nuke.nodes.Transform() tr['name'].setValue('2Doutput_From_' + n.name()) tr['translate'].copyAnimation(0, rec['output'].animation(0)) tr['translate'].copyAnimation(1, rec['output'].animation(1)) tr.setXYpos(n.xpos(), n.ypos() + 200) nuke.delete(c) nuke.delete(rec)
def get_max(node, channel='rgb'): # TODO: Need test. ''' Return themax values of a given node's image at middle frame @parm n: node @parm channel: channel for sample ''' first = node.firstFrame() last = node.lastFrame() middle = (first + last) // 2 ret = 0 n = nuke.nodes.Invert(channels=channel, inputs=[node]) n = nuke.nodes.MinColor(channels=channel, target=0, inputs=[n]) for frame in (middle, first, last): try: nuke.execute(n, frame, frame) except RuntimeError: continue ret = max(ret, n['pixeldelta'].value() + 1) if ret > 0.7: break print(u'getMax({1}, {0}) -> {2}'.format(channel, node.name(), ret)) nuke.delete(n.input(0)) nuke.delete(n) return ret
def gizmo_to_group(gizmo): """Convert given gizmo node to gruop node.""" if not isinstance(gizmo, nuke.Gizmo): return gizmo _selected = gizmo['selected'].value() _group = gizmo.makeGroup() # Set Input. for i in range(gizmo.inputs()): _group.setInput(i, gizmo.input(i)) # Set Output. for n in nuke.allNodes(): for i in range(n.inputs()): if n.input(i) is gizmo: n.setInput(i, _group) # Set position and name. if gizmo.shown(): _group.showControlPanel() _group.setXYpos(gizmo.xpos(), gizmo.ypos()) _name = gizmo['name'].value() nuke.delete(gizmo) _group.setName(_name) _group['selected'].setValue(_selected) return _group
def stampSelectAnchor(): ''' Panel to select a stamp anchor (if there are any) Returns: selected anchor node, or None. ''' # 1.Get position where to make the child... nodeForPos = nuke.createNode("NoOp") childNodePos = [nodeForPos.xpos(), nodeForPos.ypos()] nuke.delete(nodeForPos) # 2.Choose the anchor... anchorList = [ n.name() for n in nuke.allNodes("NoOp") if n.knob("identifier") and n["identifier"].value() == "anchor" ] if not len(anchorList): nuke.message("Please create some stamps first...") return None else: # REDONE ON THE NEXT LINES global select_anchor_panel select_anchor_panel = AnchorSelector() if select_anchor_panel.exec_(): # If user clicks OK chosen_anchor = select_anchor_panel.chosen_anchor #all_anchors_dropdown_list = select_anchor_panel.all_anchors_dropdown_list #TODO if chosen_anchor: return chosen_anchor return None
def convertGizmoToGroup(gizmo): # convert a gizmo to an identical group. # delete the original, reconnect the group in the chain. # rename the group to match the original. inputs = [] for x in range(0, gizmo.maximumInputs()): if gizmo.input(x): # print 'input: %s' % (gizmo.input(x).knob('name').value()) inputs.append(gizmo.input(x)) else: inputs.append(False) origName = gizmo.knob('name').value() origPosX = gizmo.xpos() origPosY = gizmo.ypos() deselectAll() # select knob, then run gizmo.makeGroup() gizmo.knob('selected').setValue(True) newGroup = gizmo.makeGroup() deselectAll() # delete original nuke.delete(gizmo) newGroup.knob('name').setValue(origName) newGroup['xpos'].setValue(origPosX) newGroup['ypos'].setValue(origPosY) # disconnect old inputs # reconnect inputs for x in range(0, newGroup.maximumInputs()): newGroup.setInput(x,None) if inputs[x]: newGroup.connectInput(x, inputs[x]) # print 'connecting output: %s to input: %s' % (inputs[x].knob('name').value(), newGroup.input(x).name()) return newGroup
def end_game(): # Showing the winner userAllRevealed = True for row in coord_objects: for element in row: if element.get_has_boat( USER) and not element.get_is_revealed(USER): userAllRevealed = False if userAllRevealed: nuke.message('<b><font size=5>GAME OVER\n<font color = red>COM WINS') else: nuke.message('<b><font size=5>GAME OVER\n<font color = green>YOU WIN') # Scene restoration nuke.toNode('preferences')['DAGBackColor'].setValue(dagColor) # Deletion of nodes for node in nuke.allNodes(): if "bShip" in node['name'].value() or node.Class() == 'NoOp': nuke.delete(node) nuke.tprint( '\n\n---------------------\n+++++ GAME OVER +++++\n---------------------' )
def delete_unused_nodes(nodes=None, message=False): """Delete all unused nodes.""" if nodes is None: nodes = nuke.allNodes() nodes = sorted(nodes, key=lambda n: (n.ypos(), n.xpos()), reverse=True) # Split disabled nodes. disabled_nodes = [n for n in nodes if _is_disabled_and_no_expression(n)] for n in disabled_nodes: node_name = u(n.name()) core.replace_node(n, n.input(0)) u_print('分离已禁用的节点: {}'.format(node_name)) # Delete unused nodes. is_used_result_cache = {} unused_nodes = [n for n in nodes if not _is_used(n, is_used_result_cache)] for n in unused_nodes: node_name = u(n.name()) nuke.delete(n) u_print('删除节点: {}'.format(node_name)) u_print('删除了 {} 个无用节点.'.format(len(unused_nodes))) if message: nuke.message( '<font size=5>删除了 {} 个未使用的节点。</font>\n' '<i>名称以"_"(下划线)开头的节点及其上游节点将不会被删除</i>'.format( len(unused_nodes)).encode('utf-8'))
def getAvrageColor( frameNumber=[101, 125, 150], frame='/s/prods/captain/sequences/s0300/s0300_p00480/compo/compo_precomp/publish/images/generic/v012/s0300_p00480-s0300_p00480-base-compo_precomp-v012.' ): nodeList = [] numberOfFrame = len(frameNumber) frameNumber = sorted(frameNumber) appendClipNode = nuke.nodes.AppendClip(firstFrame=frameNumber[0]) nodeList.append(appendClipNode) for i in range(numberOfFrame): readFile = frame + str(frameNumber[i]).zfill(4) + '.exr' readNode = nuke.nodes.Read(file=readFile) appendClipNode.setInput(i, readNode) nodeList.append(readNode) curveToolNode = nuke.nodes.CurveTool(name="CurveTool", avgframes=1) curveToolNode['ROI'].setValue([0, 0, 1968, 1080]) curveToolNode.setInput(0, appendClipNode) nuke.execute("CurveTool", frameNumber[0], (frameNumber[0] - 1) + numberOfFrame) nodeList.append(curveToolNode) col = curveToolNode['intensitydata'].value() #clamp the color to a maximum 1 for i in range(len(col)): if col[i] > 1: col[i] = 1 for node in nodeList: nuke.delete(node) return col
def RotoOutputNode(): #Creates a NoOp Placeholder = nuke.createNode("NoOp") #assigns a varriable to the currently selected node OpNo = nuke.selectedNode() #Creates a roto node Roto = nuke.createNode("Roto") #Creates the RotoOutput tool Output = nuke.loadToolset("Ahuge_Tools/Roto_Output.nk") #Sets the first input of the RotoOutput to our NoOp Output.setInput (0, Placeholder) #Sets the second input to the roto node Output.setInput(1, Roto) #Move the Output Node Output.setXpos (Output.xpos() -140) Output.setYpos (Output.ypos() +84) #Move the Roto Node Roto.setXpos (Output.xpos() -220) Roto.setYpos (Output.ypos() +6) #Creates a Input node for the roto to connect to Dummy = nuke.createNode("Input") Roto.setInput(0, Dummy) #Deletes the Input and the NoOp nuke.delete(Dummy) nuke.delete(Placeholder)
def run(self): readNodeFilePathList = {} ReadNodes = nuke.allNodes('Read') for ReadNode in ReadNodes: filePath = ReadNode['file'].value() if filePath in readNodeFilePathList: readNodeFilePathList[filePath].append(ReadNode) else: readNodeFilePathList[filePath] = [ReadNode] for nodeName in nuke.allNodes(): inputsNum = nodeName.inputs() if not inputsNum: continue for id in xrange(inputsNum): inputNodeName = nodeName.input(id) if inputNodeName in ReadNodes: filePath = inputNodeName['file'].value() if len(readNodeFilePathList[filePath]) > 1: nodeName.setInput(id, readNodeFilePathList[filePath][0]) for filePath in readNodeFilePathList: num = len(readNodeFilePathList[filePath]) if num > 1: for id in xrange(1, num): nuke.delete(readNodeFilePathList[filePath][id])
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 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 scanForExtremeBBox(maxTolerance): """ <usage: scanForExtremeBBox(maxTolerance<value between 0.1 to 1)> parses the bbox area of each node in the script to find where bboxes exceed maxTolerance of the root format area will change node colour to the warning colour when positive """ # constant warningColor = 3942580479 # yellow # find the area of the root.format of the scene frameArea = nuke.Root().format().width() * nuke.Root().format().height() maxFrameArea = frameArea + (frameArea * maxTolerance) for node in nuke.allNodes(): # if bboxArea exceeds frameArea + tolerance - flag it by setting the node colour to yellow nodeBBoxArea = node.bbox().w() * node.bbox().h() if nodeBBoxArea > maxFrameArea: # set the node colour to yellow node["tile_color"].setValue(3942580479) elif nodeBBoxArea < maxFrameArea and node["tile_color"].value() == 3942580479: # what if node WAS yellow, but adjustments make the bbox ok? Change back to default colour # get the default colour by quickly creating a node of the same class, getting the tile_color value, # then deleting it tmpNode = nuke.createNode(node.Class()) defaultColour = tmpNode["tile_color"].value() node["tile_color"].setValue(defaultColour) # now delete the temp node nuke.delete(tmpNode) return None
def reinitialise(self): #reset all the panels to default state when reopened self.node = None self.mergeOpValue = self.prev try: with self.context: if not len(nuke.selectedNodes()) > 1: if nuke.selectedNode().Class() == 'Merge2': self.node = nuke.selectedNode() self.mergeOpValue = self.node.knobs( )['operation'].value() except: pass refNode = nuke.nodes.Merge2( ) #cheeky merge to fetch the list of ops (so I don't have to write them) self.mergeOp.lineEdit.setText(self.mergeOpValue) self.mergeOp.lineEdit.updateList(refNode.knobs()['operation'].values()) nuke.delete(refNode) self.mergeOp.lineEdit.setFocus() self.mergeOp.lineEdit.selectAll() self.modifyNodeCheckBox.setChecked(True) self.modifyNodeCheckBox.setVisible(True) self.updateSubtitle()
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 setPath(): tmpWrite = nuke.createNode('WritePrism') tmpWrite.hideControlPanel() tmpWrite.knob('name').setValue('tmp_WP') fullPath = pcore.appPlugin.getOutputPath( nuke.toNode('tmp_WP').node("WritePrismBase"), nuke.selectedNode()) #print fullPath relPath = fullPath.split('01_Workflow')[0] nuke.root()['project_directory'].setValue(relPath) for i in nuke.allNodes(): nodeClass = i.Class() if nodeClass == 'Read': i.knob('selected').setValue(True) filename = i.knob('file').value() oldPath = filename.split('01_Workflow')[0] filename = filename.replace(oldPath, './') i.knob('file').setValue(filename) print "Project path is: \n" + relPath + "\n\nPath changed to relative." nuke.delete(tmpWrite) nuke.selectAll() nuke.invertSelection()
def transformstoMatrix(nodes, mode=0): #mode 0 creates a cornerpin node with the extra-matrix on it #mode 1 returns a matrix based on all the transforms fRange = nuke.FrameRange( '%s-%s' % (nuke.root().firstFrame(), nuke.root().lastFrame())) for node in nodes: if node.Class() not in ('Transform', 'CornerPin2D', 'Tracker4', 'Tracker3'): if nuke.GUI: msg = 'Unsupported node type: ' + node.Class( ) + '.\n Selected Node must be Transform, CornerPin, Tracker' nuke.message(msg) else: raise TypeError, 'Unsupported node type.\n Selected Node must be Transform, CornerPin, Tracker' return node.knob('selected').setValue(False) nodes = checkOrdering(nodes) if mode == 0: newCpin = nuke.createNode('CornerPin2D') newCpin['transform_matrix'].setAnimated() frameProgressBar = nuke.ProgressTask('Iterating frames : ') frameProgress = 100.0 / max(1.0, nuke.root().lastFrame()) for f in fRange: if frameProgressBar.isCancelled(): frameProgressBar.setProgress(100) nuke.delete(newCpin) break frameProgressBar.setProgress(int(f * frameProgress)) frameProgressBar.setMessage( str(f) + '/' + str(nuke.root().lastFrame())) mainMatrix = nuke.math.Matrix4() mainMatrix.makeIdentity() f = float(f) for node in nodes: #[::-1]: if node.Class() in ('Transform', 'Tracker4', 'Tracker3'): mainMatrix = mainMatrix * transform2DtoMatrix(f, node) if node.Class() in ('CornerPin2D'): mainMatrix = mainMatrix * cpintomatrix(f, node) if mode == 0: for n in range(0, len(mainMatrix)): newCpin['transform_matrix'].setValueAt(mainMatrix[n], f, n) frameProgressBar.setProgress(int(f * frameProgress)) frameProgressBar.setMessage( str(f) + '/' + str(nuke.root().lastFrame())) if mode == 0: try: newCpin.knob('selected').setValue(True) except: pass if mode == 1: return mainMatrix
def render_png(nodes, frame=None, show=False): """create png for given @nodes.""" assert isinstance(nodes, (nuke.Node, list, tuple)) assert nuke.value('root.project_directory'), '未设置工程目录' if isinstance(nodes, nuke.Node): nodes = (nodes, ) script_name = os.path.join( os.path.splitext(os.path.basename(nuke.value('root.name')))[0]) if frame is None: frame = nuke.frame() for read_node in nodes: if read_node.hasError() or read_node['disable'].value(): continue name = read_node.name() LOGGER.info('渲染: %s', name) n = nuke.nodes.Write(inputs=[read_node], channels='rgba') n['file'].fromUserText( os.path.join(script_name, '{}.{}.png'.format(name, frame))) nuke.execute(n, frame, frame) nuke.delete(n) if show: webbrowser.open( os.path.join(nuke.value('root.project_directory'), script_name))
def thumb_snap(self): self.check_for_tmp() #lets make sure were snapping for the current shot shot = self.shotcombo.currentText() if os.getenv('SHOT') == shot: viewer = nuke.activeViewer() actInput = nuke.ViewerWindow.activeInput(viewer) viewNode = nuke.activeViewer().node() selInput = nuke.Node.input(viewNode, actInput) reformatNode = nuke.nodes.Reformat( type = "to format", format = "240 135 eight_scaled", resize = 'fill') reformatNode.setInput(0, selInput) self.shot_thumb = os.path.join(jeeves_core.jobsRoot, self.job, 'vfx', 'nuke', self.shot, 'plates', '.tmp', '%s.jpg' % self.shot).replace('\\', '/') writeNode = nuke.nodes.Write( file = self.shot_thumb, name = 'tmpWrite2' , file_type = 'jpg') writeNode.setInput(0,reformatNode) curFrame = int(nuke.knob("frame")) nuke.execute(writeNode.name(), curFrame, curFrame) nuke.delete(writeNode) nuke.delete(reformatNode) self.update_thumb() else: #print 'not snapping for current shot' nuke.message('not snapping for current shot')
def setupCards(): node = nuke.thisNode() min = node['minZ'].value() max = node['maxZ'].value() count = int(node['count'].value()) size = (max - min) / float(count) for n in node.nodes(): print n.name() if not n.Class() == 'Input' and not n.Class() == 'Output': nuke.delete(n) with node: input = nuke.toNode('Input1') output = nuke.toNode('Output1') scene = nuke.nodes.Scene() output.setInput(0, scene) for i in range(count + 1): start = min + (i * size) end = min + (i * size) + size crop = nuke.nodes.DeepCrop() crop['znear'].setValue(start) crop['zfar'].setValue(end) crop['use_bbox'].setValue(0) crop.setInput(0, input) convert = nuke.nodes.DeepToImage() convert.setInput(0, crop) card = nuke.nodes.Card2() card['translate'].setValue([0, 0, -start]) card.setInput(0, convert) card['uniform_scale'].setExpression('parent.scale') scene.setInput(i, card)
def trackRangeForward(): node = nuke.thisNode() size = nuke.thisNode()['size'].value() rootLayer = node.knob("curves").rootLayer curve = node.knob("curves").getSelected()[0] start = int(nuke.root()['frame'].value()) end = int(nuke.root()['last_frame'].value()) task = nuke.ProgressTask('Baking camera from meta data in %s' % node.name()) for i in range(start, end): if task.isCancelled(): nuke.executeInMainThread("") break task.setMessage('processing frame %s' % i) task.setProgress(int((float(i - start) / float(end)) * 100)) temp = nuke.nodes.CurveTool() nuke.execute(temp, i, i) nuke.root()['frame'].setValue(i) for c, point in enumerate(curve): point.center.evaluate(i) pos = point.center.getPosition(i) print pos dx = nuke.sample(node, "red", pos.x, pos.y, size, size) dy = nuke.sample(node, "green", pos.x, pos.y, size, size) print c, dx, dy pos.x = pos.x + dx pos.y = pos.y + dy point.center.addPositionKey(i, pos) node['curves'].changed() nuke.delete(temp)
def copy_knobs(args): g1 = nuke.thisGroup() selNodes = g1.selectedNodes() g2 = nuke.nodes.Group(name="____tempcopyknobgroup__") with g2: nuke.nodePaste(nukescripts.cut_paste_file()) excludedKnobs = ["name", "xpos", "ypos"] nodes = g2.nodes() for i in g2.nodes(): for j in selNodes: k1 = i.knobs() k2 = j.knobs() intersection = dict([ (item, k1[item]) for item in k1.keys() if item not in excludedKnobs and k2.has_key(item) ]) for k in intersection.keys(): x1 = i[k] x2 = j[k] x2.fromScript(x1.toScript()) nuke.delete(g2)
def removePreviousScene(group): ''' clean up the inside of the gizmo if it has been used already ''' with group: nodesToKeep = [] # keep the core nodes for n in nuke.allNodes(): if 'keepOnExecute' in n.knobs().keys(): nodesToKeep.append(n) # keep the inputs for inp in nuke.allNodes('Input'): nodesToKeep.append(inp) print 'keeping nodes: %s\n' % (nodesToKeep) # remove the previous scene nodesDeleted = [] for n in nuke.allNodes(): if n not in nodesToKeep: nodesDeleted.append(n.name()) nuke.delete(n) print 'deleted nodes: %s\n' % (nodesDeleted) # disconnect everything from the scene node scene = nuke.toNode('scene') for i in range(0, scene.inputs()): scene.setInput(i, None)
def deldb(): allReadnodes = nuke.allNodes('Read',group = nuke.root()) for node in allReadnodes: node['premultiplied'].setValue(True) name=node['file'].getValue() if name.find('Thumbs.db')!=-1: nuke.delete(node)
def changeVersion(self, iAObj=None, applicationObject=None): old_gizmo = nuke.toNode(applicationObject) file_path = iAObj.filePath.replace('\\', '/') gizmo_path = os.path.dirname(file_path) nuke.pluginAddPath(gizmo_path) new_gizmo = nuke.createNode(file_path) # connect inputs for i in range(old_gizmo.inputs()): new_gizmo.setInput(i, old_gizmo.input(i)) # connect outputs for d in old_gizmo.dependent(nuke.INPUTS | nuke.HIDDEN_INPUTS): for input in [ i for i in range(d.inputs()) if d.input(i) == old_gizmo ]: d.setInput(input, new_gizmo) # restore ititial position new_gizmo.setXYpos(old_gizmo.xpos(), old_gizmo.ypos()) # swap them over nuke.delete(old_gizmo) new_gizmo['name'].setValue(iAObj.assetName) self.addFTab(new_gizmo) self.setFTab(new_gizmo, iAObj) return True
def replaceGizmos(): """ <usage>: duplicates all gizmos in a script to a group node avoids errors with network processing (ie. rendering on a farm) where the gizmo is stored locally (ie. $HOME/.nuke) preserves existing knob values """ # parse through script #make a list of all gizmos scriptgizmos = [] debugLog("number of gizmos in script is: %d" % len(scriptgizmos)) # print "#debug: number of gizmos in script is: %d" % len(scriptgizmos) #find the gizmos for each in nuke.allNodes(): debugLog("testing node %s and type is: %s" % (each.name(), type(each))) if type(each) is nuke.Gizmo: debugLog("%s is a gizmo." % each.name()) scriptgizmos.append(each) # now we have the gizmos - go through and replace them #TODO: implement a try-catch block here for gizmo in scriptgizmos: convertToGroup(gizmo) #TODO: need to delete the original gizmos here nuke.delete(gizmo) # note - can be fixed with an undo
def convert_node(node, type_convert): """ process node convert and remove old node :param node: Nuke node to process :param type_convert: String class name of new node to create :return: None """ type_current = node.Class() # create convert object cv = helper.create_convert_node(node) if cv is None: return node_convert = nuke.createNode(type_convert) # position converted node node_convert.setXYpos(int(node["xpos"].getValue()), int(node["ypos"].getValue())) node_convert["file"].setValue(node["file"].getValue()) # set values for key in cv.get_vals().keys(): helper.paste_val(node_convert, key, cv.get_vals()[key]) nuke.delete(node)
def createThumbNail(nodeObject): try: #test creating thumbnail reformatNode = nuke.nodes.Reformat() reformatNode['type'].setValue("to box") reformatNode['box_width'].setValue(200.0) reformatNode.setInput(0, nodeObject) w2 = nuke.nodes.Write() w2.setInput(0, reformatNode) thumbNailFilename = 'thumbnail_' + HelpFunctions.getUniqueNumber() + '.png' thumbnailDestination = os.path.join(tempfile.gettempdir(), thumbNailFilename) w2['file'].setValue(Connector.windowsFixPath(thumbnailDestination)) w2['file_type'].setValue('png') curFrame = int(nuke.knob("frame")) nuke.execute(w2, curFrame, curFrame) nuke.delete(reformatNode) nuke.delete(w2) return thumbnailDestination except: import traceback traceback.print_exc(file=sys.stdout) return None
def gizmoToGroup(sel): """ main function all procedures to replace a gizmo with the corresponding group """ sel = sel selName = "" selInputs = [] x = 0 y = 0 for gizmo in sel: if len(sel) > 0: try: type = gizmo.Class().split(".")[1] except: type = None if type == "gizmo": # save name of sel selName = gizmo.name() # get all inputs of gizmo for i in range(0, gizmo.inputs()): selInputs.append(gizmo.input(i)) # make group g = gizmo.makeGroup() # get coordinates x = gizmo.xpos() y = gizmo.ypos() # delete gizmo nuke.delete(gizmo) # rename g["name"].setValue(selName) # reposition g.setXpos(x) g.setYpos(y) # set all inputs back for i in range(0, len(selInputs)): g.setInput(i, selInputs[i]) # selInputs=[] else: if gizmo.Class() == "Group": nuke.message("%s is already a group" % gizmo.name()) else: nuke.message("Please select a gizmo") elif len(sel) == 0: nuke.message("please select a gizmo")
def deleteViewers(): counter = 0 with nuke.root(): for i in nuke.allNodes(recurseGroups=True): if i.Class() == "Viewer": nuke.delete(i) counter+=1 print "DeleteViewers: {0} viewers deleted.".format(counter)
def clear_nodes_by_name(names): """ Removes nodes that match any of the names given. """ nodes = (x for x in nuke.allNodes()) for node in nodes: for name in names: if name in node.name(): nuke.delete(node)
def DeleteThumbsTmp(): all = nuke.allNodes("Read") if all: for read in all: file = read["file"].value() last = file.split("/")[-1] if last == "Thumbs.db" or last[-4:] == ".tmp": nuke.delete(read) else: nuke.message("No read nodes found")
def takeScreenshot(self, fileName): fileName = fileName.replace('\\', '/') viewer = nuke.activeViewer() actInput = nuke.ViewerWindow.activeInput(viewer) viewNode = nuke.activeViewer().node() selInput = nuke.Node.input(viewNode, actInput) write = nuke.nodes.Write(file=fileName, name='tmpWrite', file_type='jpg') write.setInput(0, selInput) curFrame = int(nuke.knob("frame")) nuke.execute(write.name(), curFrame, curFrame) nuke.delete(write)
def after_render(self, cleanup=True): """delete all framecatcher nodes from an artist's comp script.""" if self._enable: # this does cleanup of the framecatchers for fc in self._catchers: fc['monitor_enable'].setValue(False) fc['write_enable'].setValue(False) fc['disable'].setValue(True) if cleanup: nuke.delete(fc)
def _add_callback_on_knob(): node = nuke.thisNode() knob = nuke.thisKnob() if knob.name() == 'cameras': for n in nuke.allNodes(): if 'PanoTool_camera' in n.name(): nuke.delete(n) camerasN = knob.value() print camerasN for i in range(float(camerasN)): initalRotation = int(360/camerasN) createCamera(node, i, i*initalRotation)
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 fixRipple(): g = nuke.thisNode() #delete any viewer nodes inside the group for n in g.nodes(): if n.Class()== 'Viewer': nuke.delete(n) #open the group and connect a new viewer to the Ripple input g.begin() v = nuke.createNode('Viewer') v.setInput(0,nuke.toNode('Ripple')) g.end()
def gizmos_to_groups(nodes): """If the node is a Gizmo, use makeGroup() to turn it into a Group.""" # Deselect all nodes. catch errors for nuke versons that don't support the recurseGroups option. try: node_list = nuke.allNodes(recurseGroups=True) except: node_list = nuke.allNodes() for node in node_list: node.setSelected(False) for node in nodes: if hasattr(node, 'makeGroup') and callable(getattr(node, 'makeGroup')): node.setSelected(True) node.makeGroup() nuke.delete(node)
def sendObjMesh(target_clientID, sender, tabTarget, alembic=False, frames=[0,0]): try: selectedNode = nuke.selectedNode() except ValueError: return False meshOut = {} geoType = ".obj" if alembic: geoType = ".abc" curFrame = int(nuke.knob("frame")) tmpfilePath = tempfile.gettempdir() + "\\hcom_tmp_" + ''.join([random.choice("abcdef0123456789") for n in xrange(5)]) + geoType tmpWriterName = "tmp_geoWriter_" + ''.join([random.choice("abcdef0123456789") for n in xrange(5)]) result = nuke.executeInMainThreadWithResult(_createObjWriter, args=(tmpWriterName, tmpfilePath, selectedNode, curFrame, alembic, frames)) if not result: return False with open(tmpfilePath, 'rb') as f: data = f.read() try: os.remove(tmpfilePath) except: pass meshOut["MESH_TYPE"] = geoType meshOut["MESH_NAME"] = selectedNode.name() meshOut["MESH_DATA"] = data w = nuke.toNode(tmpWriterName) if w: nuke.delete(w) outType = "mesh" if alembic: outType = "alembic" meshOut["NAME"]= selectedNode.name() meshOut["FRAME_RANGE"] = frames meshOut["DATA"]= data result = _sendData(target_clientID, sender, meshOut, outType, tabTarget) return result
def abcDropping( mimeType, text): if text[-4:] == '.abc' and os.path.exists(text): readGeo = nuke.createNode('ReadGeo2', 'file {%s}' % (text)) sceneView = readGeo['scene_view'] allItems = sceneView.getAllItems() if allItems: sceneView.setImportedItems(allItems) sceneView.setSelectedItems(allItems) else: nuke.delete(readGeo) nuke.createNode('Camera2', 'file {%s} read_from_file True' % (text)) return True return False
def alembicMerge(): mainNode = nuke.selectedNode() mainScene = mainNode['scene_view'] mainItems = mainScene.getSelectedItems() items = [] selNodes = nuke.selectedNodes() for node in selNodes: item = node['scene_view'].getSelectedItems() print(item) items.extend(item) mainScene.setSelectedItems(items) delNodes = [n for n in selNodes if n is not mainNode] print(selNodes, delNodes) for d in delNodes: nuke.delete(d)
def saveImage(sel, renderTo, filetype): w = nuke.nodes.Write() w.setInput(0,sel[0]) w.setXpos(sel[0].xpos()) w.setYpos(sel[0].ypos()+150) w.knob("name").setValue("capture") w.knob("use_limit").setValue(True) w.knob("first").setValue(nuke.frame()) w.knob("last").setValue(nuke.frame()) w.knob("file_type").setValue(filetype) w.knob("file").setValue(renderTo+"capture_{time}.{ext}".format(time=getTime(), ext=filetype)) nuke.execute(w,nuke.frame(),nuke.frame()) nuke.delete(w) openFolder(renderTo)
def getRenderElements(self): nd = nuke.createNode('VRayRenderElement',' ',False) k = nd['render_element'] count = 0 ele = [] for val in k.values(): print val if(count != 0): n = nuke.createNode('VRayRenderElement') n['render_element'].setValue(val) ele.append(n['render_element']) count+=1 nuke.delete(nd) return ele
def process(self, context): errors = False for node in nuke.allNodes(): if node.Class() not in ['ReadGeo2', 'ReadGeo']: continue try: basename = os.path.basename(node['file'].value()) version_string = ''.join(self.version_get(basename, 'v')) basename = basename.replace(version_string, 'v[0-9]{3}') f = node['file'].value() versions_path = os.path.abspath(os.path.join(f, '..', '..')) path = self.getFirst(versions_path, basename) new_node = nuke.createNode('ReadGeo2', 'file {%s}' % path) new_node['frame_rate'].setValue(node['frame_rate'].value()) # selecting the same items sceneView = new_node['scene_view'] allItems = sceneView.getAllItems() sceneView.setImportedItems(allItems) sceneView.setSelectedItems(allItems) sceneView.setSelectedItems(node['scene_view'].getSelectedItems()) new_node.setXpos(node.xpos()) new_node.setYpos(node.ypos()) self.swapOutNode(node, new_node) nuke.delete(node) except: errors = True self.log.error(traceback.format_exc()) if errors: message_box(context, 'ReadGeo update completed with errors!', 'Update', warning=True) else: message_box(context, 'ReadGeo update completed successfully!', 'Update', warning=False)
def dupReadDestroy(useSelection=False): ''' Eliminates Read nodes with duplicate paths. Replaces all but the upper-most sibling in the DAG with PostageStamp nodes. Returns a list of the remaining read nodes from the input set. Optional boolean argument specifies whether or not to limit operation to the current node selection. ''' if useSelection: readNodes = nuke.selectedNodes("Read") else: readNodes = nuke.allNodes("Read") if not readNodes: return readPaths = [node['file'].value() for node in readNodes] dupNodes = [] for node in readNodes: dupSet = [] if readPaths.count(node['file'].value()) > 1: dupSet = [i for i in readNodes if i['file'].value() == node['file'].value()] dupNodes.append(dupSet) for dup in dupSet: readNodes.remove(dup) readPaths.remove(dup['file'].value()) if dupNodes: for set in dupNodes: yPos = [node.ypos() for node in set] yPos.sort() keep = [n for n in set if n.ypos() == yPos[0]][0] set.remove(keep) for node in set: node.setSelected(True) ps = nuke.createNode("PostageStamp", "name PStamp_%s label %s hide_input True postage_stamp True xpos %d ypos %d tile_color 3281491967" % (node.name(), node.name(), node.xpos(), node.ypos()), False) ps.setInput(0, keep) ps.setSelected(False) nuke.delete(node) if useSelection: return nuke.selectedNodes("Read") else: return nuke.allNodes("Read")
def batchReset(src,out): print src errFlg = 0 nuke.scriptOpen(src) for node in nuke.allNodes('Read'): if os.path.dirname(node.knob('file').getValue()) != r'S:/LSC/CGI/Asset/lightset/asset_checklight/nukeimages': print os.path.dirname(node.knob('file').getValue()) filelist = scanForFiles(os.path.dirname(node.knob('file').getValue())) print filelist node.knob('file').setValue(os.path.dirname(node.knob('file').getValue())+'/'+filelist[0][0]) node.knob('first').setValue(filelist[0][1]) node.knob('last').setValue(filelist[0][2]) node.knob('origfirst').setValue(filelist[0][1]) node.knob('origlast').setValue(filelist[0][2]) if not errFlg: print 'All selected Read nodes were reset.' nuke.scriptSave(out) for allnode in nuke.allNodes(): nuke.delete(allnode)
def removeShot(self, shot): # try to delete knobs grpS = self.node.knob("grpS_"+shot) grpE = self.node.knob("grpE_"+shot) txt = self.node.knob("txt_"+shot) setButton = self.node.knob('set_'+shot) delButton = self.node.knob('del_'+shot) versiontxt = self.node.knob('version'+shot) shots = self.node.knob('shotList').values() hubButton = self.node.knob('hubViewer_'+shot) try: shots.remove(shot) except: pass # try to delete knobs, cam and grps try: self.removeknob(self.node, grpS) self.removeknob(self.node, grpS) self.removeknob(self.node, grpE) self.removeknob(self.node, txt) self.removeknob(self.node, setButton) self.removeknob(self.node, delButton) self.removeknob(self.node, versiontxt) self.removeknob(self.node, hubButton) try: cam = nuke.toNode(self.job+'_'+shot+'_renderCamera') nuke.delete(cam) except: pass #print 'camera '+shot+' not found...' self.node.knob('shotList').setValues(shots) nuke.callbacks.removeKnobChanged(knobChange, args=(), kwargs={}, nodeClass = 'Group') except: pass
def getMinMax( srcNode, channel='depth.Z' ): ''' Return the min and max values of a given node's image as a tuple args: srcNode - node to analyse channels - channels to analyse. This can either be a channel or layer name ''' MinColor = nuke.nodes.MinColor( channels=channel, target=0, inputs=[srcNode] ) Inv = nuke.nodes.Invert( channels=channel, inputs=[srcNode]) MaxColor = nuke.nodes.MinColor( channels=channel, target=0, inputs=[Inv] ) curFrame = nuke.frame() nuke.execute( MinColor, curFrame, curFrame ) minV = -MinColor['pixeldelta'].value() nuke.execute( MaxColor, curFrame, curFrame ) maxV = MaxColor['pixeldelta'].value() + 1 for n in ( MinColor, MaxColor, Inv ): nuke.delete( n ) return minV, maxV
def verCheck(node=nuke.thisNode()): nodeName = nuke.thisNode().name() message = "Would you like to update the %s to the latest version?" % (nodeName) try: curVer = node['renderNodeVersion'].value() # Checks to see what the current version is. if curVer >= renNodeVer: return "pass" # Load Latest RenderNode Version else: if nuke.ask(message): # Number of inputs of the RenderNode inputNum = 2 renNode = node # Saves original inputs prevInputs = [] for x in range(inputNum): prevInputs.append(renNode.input(x)) # Saves the values of the knobs knobs = ["v_num", "verControl", "curVer", "cropCheck","shotNotes", "lutFile", "lutControl", "format","viewMenu"] knobValues = [] for x in knobs: knobValues.append(renNode[x].value()) xPos = renNode["xpos"].value() yPos = renNode["ypos"].value() # Create updated RenderNode- if you make the node into a gizmo, change nuke.loadToolset into nuke.createNode nuke.root().begin() newNode = nuke.loadToolset(rendernodeFile.replace("\\","/")) newNode.setXYpos(int(xPos), int(yPos)) # Applies values to the new knobs for x in knobs: newNode[x].setValue(knobValues[knobs.index(x)]) # Sets the original inputs for x in range(inputNum): newNode.setInput(x, prevInputs[x]) nuke.root().end() nuke.delete(renNode) return "break" except: pass
def restoreCheckpoint (nukeScript, nodeName, date) : log ("restoreCheckpoint %s %s %s" % (nukeScript, nodeName, date)) # We ask on rv side now, since otherwise dialog can come up behind rv. # # ans = nuke.ask ("Restore checkpoint: %s, %s ?" % (nodeName, date)) # log (" ans %s" % ans) log (" reading checkpoint script") nuke.Undo().begin("Restore %s, %s" % (nodeName, date)) try : nukescripts.misc.clear_selection_recursive() try : v = nuke.activeViewer().node().name() except : v = None if (rvmon) : rvmon.restoreBegin() nodes = nuke.root().nodes() for n in nodes: #log (" deleting %s %s %s" % (n.name(), type(n).__name__, n.Class())) nuke.delete(n) nuke.scriptReadFile (nukeScript) if (v) : n = nuke.toNode(v) if (n) : nuke.show (n) if (rvmon) : rvmon.restoreComplete() log (" checkpoint restore complete") except Exception, msg: nuke.message("Checkpoint restore failed:\n%s" % (msg,))
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 _dupReadDestroy(useSelection=False): """ Eliminates Read nodes with duplicate paths by replacing all but one with Postage Stamp nodes referencing the original. Returns a list of the remaining unique read nodes from the input set. """ if useSelection: readNodes = nuke.selectedNodes("Read") else: readNodes = nuke.allNodes("Read") if not readNodes: return False readPaths = [node['file'].value() for node in readNodes] dupNodes = [] for node in readNodes: dupSet = [] if readPaths.count(node['file'].value()) > 1: dupSet = [i for i in readNodes if i['file'].value() == node['file'].value()] dupNodes.append(dupSet) for dup in dupSet: readNodes.remove(dup) readPaths.remove(dup['file'].value()) if dupNodes: for set in dupNodes: set.sort() for count in range(1,len(set)): pStamp = nuke.nodes.PostageStamp(name = "PStamp_" + set[count].name(), label = set[count].name(), hide_input = True, postage_stamp = True, xpos = set[count].xpos(), ypos = set[count].ypos()) pStamp.setInput(0,set[0]) nuke.delete(set[count]) if useSelection: return nuke.selectedNodes("Read") else: return nuke.allNodes("Read")