def run_scale_nodes(): if len(nuke.selectedNodes()) == 0: nuke.message('Select some nodes dumby') elif len(nuke.selectedNodes()) == 1: nuke.message('You gotta select more than one node dumby') else: x = nuke.getInput('x scale', '2') y = nuke.getInput('y scale', '2') scale_nodes(float(x), float(y))
def add_btn_clicked(self): current_node = nuke.selectedNodes() existItem = False if len(current_node) > 0: if len(current_node) == 1: tool_name = nuke.getInput(u'请输入预设名字:', current_node[0].name()[:-1]) else: tool_name = nuke.getInput(u'请输入预设名字:') if tool_name: if self.tool_list.count() == 0: existItem = True else: for list_num in xrange(self.tool_list.count()): if self.tool_list.item(list_num).text() == tool_name: QtGui.QMessageBox.information( self, u"提示", u"您选的节点已添加过了,请不要重复添加") existItem = False break else: existItem = True if existItem: tool_item = QtGui.QListWidgetItem(tool_name) tool_item.setTextAlignment( QtCore.Qt.AlignCenter) # 设置item居中 tool_item.setSizeHint( QtCore.QSize(tool_item.sizeHint().width(), 25)) # 设置item高度 self.tool_list.addItem(tool_item) # 保存成预设文件 toolset_path = os.path.join(config_dir, "%s.nk" % tool_name) nuke.nodeCopy(toolset_path.encode("gbk")) # 写入json tools_list = read_json() current_tool = { "name": tool_name, "type": "tool_set", "command": toolset_path.replace("\\", "/") } tools_list.append(current_tool) write_json(tools_list) else: QtGui.QMessageBox.information(self, u"提示", u"请选择节点")
def label_dialog(): # Opens a quick dialog to edit the label of a node label = '' nodes = nuke.selectedNodes() if len(nodes) == 1: label = nodes[0].knob('label').getValue() name = nodes[0].name() txt = nuke.getInput('Change %s label' % name, label) else: txt = nuke.getInput('Change node labels', label) if txt: for n in nuke.selectedNodes(): n['label'].setValue(txt)
def nk_multithreadedRender(): """ Multithreaded Render """ threads = nuke.env["threads"] - 2 c = nuke.getInput("Number of threads (default %i)" % threads) if c: threads = int(c) THREADCOUNT = threads nuke.scriptSave() renderNode = nuke.selectedNode() use_limit = renderNode["use_limit"].value() first = renderNode["first"].value() if use_limit else nuke.root().firstFrame() last = renderNode["last"].value() if use_limit else nuke.root().lastFrame() frames = [i for i in range(first, last + 1)] threads = [[] for i in range(0, THREADCOUNT)] [threads[i % THREADCOUNT].append(frame) for (i, frame) in enumerate(frames)] THREAD_FRAMES = {} def render(frameList): _maxCache = str(max(nuke.memory("max_usage") / 1097152, 16) * 4) + "M" try: t = nuke.executeBackgroundNuke( nuke.EXE_PATH, [renderNode], nuke.FrameRanges(frameList), nuke.views(), {"maxThreads": 1, "maxCache": _maxCache}, ) THREAD_FRAMES[t] = frameList except Exception as e: print e [render(frameList) for frameList in threads]
def __data(self): # nuke.message("File better be jpg file") path = nuke.getFilename("File better be jpg file") limit = nuke.getInput("set the width to scale") if not int(limit): nuke.message("Wrong Type") self.adult_dict = {} img = QImage(path) img = img.scaledToWidth(int(limit)) width, height = img.width(), img.height() scale = 255 id = 0 for y in range(0, height): for x in range(0, width): id += 1 c = img.pixel(x, y) r, g, b, a = QColor(c).getRgbF() r, g, b, a = r * scale, g * scale, b * scale, a * scale color = int('%02x%02x%02x%02x' % (r, g, b, a), 16) xa = x * 10 ya = y * 10 self.adult_dict[id] = {"pos": (xa, ya), "color": color} id = id + 1 self.adult_dict[id] = None print(self.adult_dict)
def saveStore( node, store, maxStores, excludeKnobs=[] ): ''' Save the current node values in the specified store. If stores dont exist yet they will be created. args: node - node object to operate on store - knob name of store to save values to excludeKnobs - knobs to exculde from being saved in a store ''' if not 'Stores' in node.knobs().keys(): addStores( node, maxStores ) sKnob = node[ store ] # GET VALUES AND WRITE THEM TO REQUESTED STORE knobValues = node.writeKnobs( nuke.TO_SCRIPT ) # MANUALLY EXCLUDE KNOBS FROM BEING RECORDED exclude = [k for k in node.knobs() if k.startswith( 'store' )] + excludeKnobs for e in exclude: knobValues = re.sub( r'%s\s.+\n?' % e, '', knobValues ) print 'saving to store %s:\n%s' % ( store, knobValues ) code = 'nuke.thisNode().readKnobs( \'\'\'%s\'\'\' )' % knobValues sKnob.setValue( code ) # SET TOOLTIP TO USER DESCRIPTION curTip = sKnob.tooltip() defaultTip = curTip[ curTip.find('>')+1 : curTip.rfind('<') ] toolTip = nuke.getInput('tooltip for ' +store, defaultTip) sKnob.setTooltip( '<b>%s</b>\n%s' % (toolTip, knobValues) ) # UPDATE LABEL FORMAT cleanLabel = sKnob.label()[sKnob.label().rindex('>')+1:] sKnob.setLabel( '<b>'+cleanLabel )
def parentLabelFromUser(parentUpstreamNode): txt = nuke.getInput('Parent name', parentUpstreamNode['name'].value()) if not txt: nuke.message(ERROR_MESSAGE.format('failed to get label')) return False else: return txt
def _get_frange(): """Open a dialog to request a Nuke-style frame range Args: N/A Returns: <nuke.FrameRange> Returns a FrameRange object if valid frange is entered, or none. Raises: N/A """ first_frame = int(nuke.numvalue('root.first_frame')) last_frame = int(nuke.numvalue('root.last_frame')) step = 1 default_frange = str(nuke.FrameRange(first_frame, last_frame, step)) frange = nuke.getInput('Enter Frame Range:', default_frange) if not frange: return None else: try: return nuke.FrameRange(frange) except: # TODO: Determine exact exception nuke.message('Invalid frame range') return None
def saveVersion(): scriptsdir = os.path.join(jeeves_core.jobsRoot, os.getenv('JOB'), 'vfx', 'nuke', os.getenv('SHOT'), 'scripts', jeeves_core.user) if os.path.isdir(scriptsdir): print 'dir exists' else: print 'need to create dir' jeeves_core.make.nuke_user(jeeves_core.user) print 'done' # strip white space from user input description description = nuke.getInput( 'script description', 'slapcomp' ).replace( ' ', '_' ) job = os.environ['JOB'].rsplit('_', 1)[-1] fileSaved = False version = int(1) while not fileSaved: scriptName = '%s_%s_%s_v%02d.nk' % ( os.getenv('SHOT'), description, jeeves_core.getVars.get_initial(), version ) fullPath = os.path.join( scriptsdir, scriptName ) # if file exists, we version up if os.path.isfile(fullPath): version += 1 continue # save the script nuke.scriptSaveAs( fullPath ) fileSaved = True freshLables()
def add_preset(): '''create preset buttons adds data to tooltip''' node = nuke.thisNode() node_viewer = nuke.activeViewer().node() # Get knob values dict_knobs = {} dict_knobs['lut'] = node_viewer['viewerProcess'].value() dict_knobs['cdl'] = node['cdl'].value() if 'cdl' in node.knobs() else None ls_knobs = ['exp', 'y', 'sat', 'd_exp', 'd_y', 'd_sat'] for k in ls_knobs: dict_knobs[k] = node[k].value() # Build knob for this preset this_preset_idx = preset_idx() preset_latest = PRESET_STR + str(this_preset_idx) ## Label input this_preset_label = nuke.getInput( 'Preset Label (keep it short)', preset_latest.replace(PRESET_STR, PRESET_STR + ': ')) if this_preset_label: cmd = "mod_IP.apply_preset()" k_preset = nuke.PyScript_Knob(preset_latest, this_preset_label, cmd) k_preset.setTooltip(str(dict_knobs)) # if this_preset_idx > 1: # k_preset.clearFlag(nuke.STARTLINE) node.addKnob(k_preset) k_preset.setFlag(nuke.STARTLINE)
def getENV(): ''' get the enviroment variable file_config: _config_TMDataset.json net/tjiang/.nuke/TimelineMarker ''' data_folder = os.path.join(os.getenv('HOME'), '.nuke','TimelineMarker') file_config_name = '_config_TMDataset.json' file_config = os.path.join(data_folder, '_config_TMDataset.json') if not os.path.isdir(data_folder): os.makedirs(data_folder) try: #config file exist with open(file_config, 'r') as f: thisENV = json.load(f)[0] env_show = thisENV['SHOW'] env_shot = thisENV['SHOT'] except: #config file doens't exist try: thisENV = nuke.getInput("'ENV variable name (SHOW, SHOT; saperated by ',')") if thisENV: env_show = thisENV.split(',')[0].strip() env_shot = thisENV.split(',')[1].strip() with open(file_config, 'w') as f: f.write(json.dumps([{'SHOW': env_show, 'SHOT': env_shot}])) except: env_show = None env_shot = None return {'SHOW': env_show, 'SHOT': env_shot}
def copy_label(): p = nuke.selectedNode() firstInput = p.input(0) if firstInput.Class() != 'Read': d = nuke.selectedNode().name() l = p['label'].getValue() txt = nuke.getInput('Change label', 'SB_POS_STMP_') print if l == "": for n in nuke.selectedNodes(): n['label'].setValue(txt) else: n['label'].setValue(l + txt) if firstInput.Class() == 'Blur': p['label'].setValue('Blur size= [value this.input0.size]' + "__" + txt) if firstInput.Class() == 'Merge2': p['label'].setValue('Merge Mix= [value this.input0.mix]' + "__" + txt) if firstInput.Class() == 'Switch': p['label'].setValue('Switch input= [value this.input0.which]' + "__" + txt) if firstInput.Class() == 'TimeOffset': p['label'].setValue('TimeOffset= [value this.input0.time_offset]' + "__" + txt) if firstInput.Class() == 'Defocus': p['label'].setValue('defocus amount= [value this.input0.defocus]' + "__" + txt) if firstInput.Class() == 'AdjBBox': p['label'].setValue('amount= [value this.input0.numpixels]' + "__" + txt) if firstInput.Class() == 'Tracker4': p['label'].setValue('amount= [value this.input0.transform]' + "__" + txt) if firstInput.Class() == 'Reformat': p['label'].setValue('reformat= [value this.input0.format]' + "__" + txt)
def allMerge(): sels = nuke.selectedNodes() sels = sorted(sels, key=lambda s: s.xpos()) n = nuke.getInput('number of items in a group', '0') try: n = int(n) except: print('wrong input') raise if n == 0 or n > len(sels): n = len(sels) if n == 1: for s in sels: merge = nuke.createNode('Merge') merge.setInput(0, s) merge.setInput(1, None) return selGroup=zip(*[sels[i::n] for i in range(n)]) for group in selGroup: A = None for B in group: if not A: A = B else: merge = nuke.createNode('Merge') merge.setInput(0, A) merge.setInput(1, B) A = merge
def easySave(): nkDir = nukeDir() # GET DESCRIPTION FROM USER BUT STRIP ALL WHITE SPACES description = nuke.getInput('script description', 'bashComp').replace(' ', '') fileSaved = False version = 1 while not fileSaved: # CONSTRUCT FILE NAME if seq == None: nkName = '%s_%s_%s_v%02d.nk' % (job, shot, description, version) else: nkName = '%s_%s_%s_%s_v%02d.nk' % (job, seq, shot, description, version) # JOIN DIRECTORY AND NAME TO FORM FULL FILE PATH nkPath = os.path.join(nkDir, nkName) # IF FILE EXISTS VERSION UP if os.path.isfile(nkPath): version += 1 continue # SAVE NUKE SCRIPT nuke.scriptSaveAs(nkPath) fileSaved = True return nkPath
def add_driver(knobtype): """Add a set driver knobs @knobtype: (str) Nuke Knob Type """ try: dr_no = int(max([find_digit(k) for k in nuke.thisNode().knobs() if k.startswith('dr')]) + 1) except Exception as e: nuke.warning(e) dr_no = 0 label = nuke.getInput('Label this Driver') if label: k_this_name = 'dr%02d_%s' % (dr_no, label) k_this = eval("nuke.{}('')".format(knobtype)) k_this.setName(k_this_name) k_this.setLabel(label) k_this.setFlag(nuke.STARTLINE) k_set_driven = nuke.PyScript_Knob('dr%02ddriven' % dr_no, STR_SETDRIVEN) k_set_driven.setCommand(STR_CMD_SETUP.format("set_driven('%s')" % k_this_name)) k_set_driven.setTooltip(k_this_name) k_set_driven.clearFlag(nuke.STARTLINE) k_list_driven = nuke.PyScript_Knob('dr%02dlist' % dr_no, STR_LISTDRIVEN) k_list_driven.clearFlag(nuke.STARTLINE) k_list_driven.setCommand(STR_CMD_SETUP.format("show_list_driven('%s')" % k_this_name)) k_list_driven.setTooltip(k_this_name) n = nuke.thisNode() n.addKnob(k_this) n.addKnob(k_set_driven) n.addKnob(k_list_driven)
def RenderSpecificFrames(): sRanges = nuke.getInput( "Enter frames ranges, separated by spaces. Ex: 4 10,20 100,150,2") print sRanges lRanges = sRanges.split() lNukeRanges = [] for sRange in lRanges: lRange = sRange.split(',') lRange = [int(i) for i in lRange] if len(lRange) == 0: continue elif len( lRange ) == 1: # Only start frame. Add end frame (same as start frame) and step (1). lRange.extend([lRange[0], 1]) elif len(lRange) == 2: # Start frame and End Frame. Add step (1) lRange.extend([1]) elif len(lRange) > 3: # 4 Elements. Error. nuke.message("Wrong format: %s. Cannot process 4 elements" % str(lRange)) return False lNukeRanges.append(lRange) print lNukeRanges nuke.executeMultiple(nuke.selectedNodes(), lNukeRanges)
def setConfig(self): '''set config file''' thisENV = nuke.getInput("'ENV variable name (SHOW, SHOT; saperated by ',')", "%s,%s" % (self.SHOW, self.SHOT)) if thisENV: env_show = thisENV.split(',')[0].strip() env_shot = thisENV.split(',')[1].strip() with open(file_config, 'w') as f: f.write(json.dumps([{'SHOW': env_show, 'SHOT': env_shot}]))
def openComp(): pfmt = PartialFormatter() sn = nuke.getInput('open .nk from mono shotname:').upper() if sn: shot_dict = parse_shotname(sn) path = pfmt.format(os.environ['IH_RAW_PATH_NUKE'], **shot_dict) scripts = glob.glob(path) print sorted(scripts) nuke.scriptOpen(sorted(scripts)[-1])
def nk_batchChangeSelected(): """ Batch change """ input = nuke.getInput("""Eg. translate=[0,1,3] / rotate=90.0 / label="some text" """) try: param,value = input.split("=") [n[param].setValue(eval(value)) for n in nuke.selectedNodes()] except Exception: pass
def _create_shared_toolsets(): if not nuke.selectedNodes(): nuke.message('未选中任何节点,不能创建工具集'.encode('utf-8')) return toolset_name = nuke.getInput('ToolSet name') if toolset_name: nuke.createToolset(filename='Shared/{}'.format(toolset_name), rootPath=filetools.plugin_folder_path()) nukescripts.toolsets.refreshToolsetsMenu()
def labelChange(): prevLabel = nuke.selectedNode()['label'].getValue() newLabel = nuke.getInput('Change Node Label', prevLabel) # Change Values for n in nuke.selectedNodes(): n['name'].getValue() n['label'].setValue(newLabel)
def bm_NodeComment(): selectedNode = nuke.selectedNode() oldComment = selectedNode.knob('label').value() newComment = nuke.getInput('Node comment', oldComment) # If the user has hit 'Cancel', use the previous comment rather than wiping it if newComment == None: selectedNode.knob('label').setValue(oldComment) else: selectedNode.knob('label').setValue(newComment)
def selectRandom(): theSelectedNodes = nuke.selectedNodes() for aNode in nuke.allNodes(): aNode['selected'].setValue(False) theValue = float(nuke.getInput("ratio?")) for aNode in theSelectedNodes: if random.random() < theValue: aNode['selected'].setValue(True)
def autowritePreRender(): loadRoot = easyRenderRoot() prName = nuke.getInput('PreRender Name:', 'PreRender01') writeMagic = nuke.createNode("Write") writeMagic['channels'].setValue("rgba") writeMagic.knob('colorspace').setValue(12) writeMagic.knob('file').setValue( easyRenderRoot() + '[string range [file tail [knob root.name]] 0 6]/04 PRERENDERS/{}/{}_####.exr' .format(prName, prName)) writeMagic.knob('create_directories').setValue(True)
def renamenodes(): sn = nuke.selectedNodes() sn.reverse() if sn != []: newname = nuke.getInput("New name:") for index, n in enumerate(sn): n.knob('name').setValue(newname.replace(' ', '_') + str(index+1)) else: nuke.message("Rename Nodes:\nSelect at least one node")
def CreateBackdrop(): import random for i in nuke.selectedNodes(): if i.Class() == "BackdropNode": i['tile_color'].setValue(int(random.randint(100000,699999999))) break else: FaceBook = nuke.getInput('Name?') autoBackdropCustom() nuke.selectedNode()['label'].setValue(FaceBook) break
def main(): n = nuke.selectedNode() coords = nuke.getInput('set x and y position:', '0,0') x, y = coords.split(',') found = [] for ch in n.channels(): if ch.startswith('_m_') and not 'alpha' in ch and not 'all' in ch: result = ch, nuke.sample(n, ch, int(x), int(y)) if result[1] == 1: found.append(result[0]) nuke.message(found)
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 CreateBackdrop(): import random for i in nuke.selectedNodes(): if i.Class() == "BackdropNode": fColour = [random.random(), random.random(), random.random(), random.random()] hColour = int('%02x%02x%02x%02x' % (fColour[0]*255,fColour[1]*255,fColour[2]*255,fColour[3]),16) i['tile_color'].setValue(hColour) break else: FaceBook = nuke.getInput('Name?') autoBackdropCustom() nuke.selectedNode()['label'].setValue(FaceBook) break
def autoWrite(): currentNode = nuke.createNode('Write', inpanel=False) currentNode.knob("name").setValue("AutoWrite") selNode = nuke.root().name() if selNode != "Root": splitPath = selNode.split('/')[:-1] splitPath = ('/').join(splitPath) custom = nuke.Tab_Knob('Tab Fragments') currentNode.addKnob(custom) currentNode.addKnob( nuke.EvalString_Knob( 'script', 'Script Name', '[file rootname [file tail [value root.name] ] ]')) feedback = """ [value file] [value this.input.name] """ currentNode.knob('label').setValue(feedback) OutputFile = splitPath + ".%04d." + nuke.getInput("data Type") newFile = OutputFile.split('/')[-1:] newFile = newFile[0].split('.')[-1] currentNode['file'].setValue(OutputFile) currentNode['file_type'].setValue(newFile) s = nuke.ask("Shall i execute?") if s == True: nuke.execute(currentNode, start=1, end=int(nuke.getInput("Enter Last Frame"))) else: nuke.message("Please save the file")
def setFPS(): import hiero.core, hiero.ui # import hiero modules - importing outisde the function will return errors! view = hiero.ui.activeView() sel = view.getSelection() framerate = nuke.getInput('New Framerate') # ask user for new framerate with input box x = 0 for each in sel: if x < len(sel): sel[x].activeItem().setFramerate(framerate) #apply framerate x = x+1 return
def cmd_add(n): ''' command to call when Add button is pressed 1. find new version 2. save nuke preset 2. ask for descrition 3. create NodeVersion knobs 4. Change Cur Version knob ''' # n = nuke.thisNode() new_ver = findNV(n)['new'] # Preseting preset_name = "%s.%s.v%s" % (n.Class(), n.name(), new_ver) nuke.saveUserPreset(n, preset_name) print preset_name # Short description tip = nuke.getInput('Give a Short Version Description', '%s' % preset_name) # Knobs k_rm = nuke.PyScript_Knob( 'nv_rm_v%s' % new_ver, '<b>−', "import nuke;import dft_NodeVersion as nv;nv.cmd_remove(nuke.thisNode(), nuke.thisKnob())" ) k_load = nuke.PyScript_Knob( 'nv_load_v%s' % new_ver, '<b>load v%s' % new_ver, "import nuke;import dft_NodeVersion as nv;nv.cmd_load(nuke.thisNode(), nuke.thisKnob())" ) k_tip = nuke.Text_Knob('nv_tip_v%s' % new_ver, ': %s' % tip, "\s") #FLAG k_load.clearFlag(nuke.STARTLINE) k_tip.clearFlag(nuke.STARTLINE) # Add knobs n.addKnob(k_rm) n.addKnob(k_load) n.addKnob(k_tip) # Change current version try: n.knob('tx_preset').setValue('<b>%s.v%s' % (n.name(), new_ver.zfill(2))) except: pass #Console print "%s added NodeVersion: v%s" % (n.name(), str(new_ver).zfill(2))
def getShowTreeShotQT(): sn = string.upper( nuke.getInput('read highest v qt from _vfx shot_tree shotname:')) print sn path = '/Volumes/monovfx/_vfx/SHOT_TREE/%s/%s/output/*_vfx.mov' % (sn[:3], sn) print path qts = glob.glob(path) print qts qt = sorted(qts)[-1] if os.path.exists(qt): n = nuke.createNode("Read") n['file'].fromUserText(qt) else: return 'Shot Not Found'
def readShot(): import shotgun shotcode = nuke.getInput('Shot Code') s = shotgun.getShotData(shotcode, ['Source clip', 'Cut In', 'Cut Out']) (clipName, crc) = s['Source clip'].strip().split(':') results = nuke.spotlight(clipName) if results: for readPath in results: if sha1(open(readPath).read()).hexdigest() == crc: readPath = nuke.pacify(readPath) nuke.createNode('Read','file %s' % readPath) rangeStr = 'first_frame %s last_frame %i' % (s['Cut In'],int(s['Cut Out']-1)) nuke.createNode('FrameRange',rangeStr) else: nuke.message('Cannot locate clip %s' % clipName)
def wildcard_selection(): node = nuke.selectedNode() from cryptomatte_utilities import CryptomatteInfo current_layer = CryptomatteInfo(node).selection wildcard = nuke.getInput( "Please enter wildcard (name of the object,just copy it):", "*") in_list = [] manifest = json.loads( node.metadata("exr/cryptomatte/{0}/manifest".format(current_layer))) for m in manifest.keys(): if str(m).find(wildcard.rstrip("*")) != -1: if str(m) not in in_list: in_list.append(str(m)) out_list = ", ".join(in_list) node.knob("matteList").setValue(out_list)
def setReadFrameRange(): """set nuke frame range according to a read node""" readNodes = nuke.selectedNodes("Read") rawInput = nuke.getInput("StartFrame-EndFrame:",str(int(nuke.root()['first_frame'].getValue()))+"-"+str(int(nuke.root()['last_frame'].getValue()))) if rawInput: try: firstFrame = str(rawInput).split("-")[0] endFrame = str(rawInput).split("-")[1] except: nuke.message("Error in the typing...\nTry like this: 1001-1100") if readNodes and firstFrame and endFrame: for n in readNodes: n['first'].setValue(int(firstFrame)) n['last'].setValue(int(endFrame)) print "Read node '"+n.name()+"' is set to: "+str(firstFrame)+"-"+str(endFrame)
def createProjector(nodes=[]): if not nodes: nuke.message('ERROR: No node(s) selected.') return for node in nodes: deselectAllNodes() if node.Class() in [ "Camera2", "Camera"]: node_name = node.name() frame = nuke.getInput("Frame to Project for {0}?".format(node_name)) try: int(frame) except ValueError: nuke.message("You must enter a frame number!") return 0 node['selected'].setValue(True) copyPaste() new_camera = nuke.selectedNode() new_camera.addKnob(nuke.Int_Knob('ref_frame', 'Reference Frame')) new_camera['ref_frame'].setValue(int(frame)) new_camera['label'].setValue("Projection at frame: [value ref_frame]") new_camera['tile_color'].setValue(123863) new_camera['gl_color'].setValue(123863) for knob in new_camera.knobs().values(): if knob.hasExpression(): if knob.arraySize() ==1: chan_name = "{0}.{1}".format(new_camera.name(), knob.name()) first = "{0}".format(nuke.root().firstFrame()) last = "{0}".format(nuke.root().lastFrame()) knob_name = "{0}".format(knob.name()) nuke.animation( chan_name, "generate", (first, last, "1", "y", knob_name)) else: i = knob.arraySize() - 1 while i > -1: chan_name = "{0}.{1}.{2}".format(new_camera.name(), knob.name(), i) first = "{0}".format(nuke.root().firstFrame()) last = "{0}".format(nuke.root().lastFrame()) knob_name = "{0}".format(knob.name()) nuke.animation( chan_name, "generate", first, last, "1", "y", knob_name)) i-=1 for knob in new_camera.knobs().values(): if knob.isAnimated(): knob.setExpression('curve(ref_frame)')
def renameNodes(): '''Renames the selected nodes sequentially''' sn = nuke.selectedNodes() sn.reverse() if sn: newName = nuke.getInput( 'New name:' ) if newName: if newName[0].isdigit(): newName = '_' + newName if newName[-1].isdigit(): newName += '_' pat = re.compile( '[\s\W]' ) newName = pat.sub( '_', newName ) for n in sn: n.setName( newName )
def createProjector(): selectedNodes = nuke.selectedNodes() for cameraNode in nuke.selectedNodes(): if cameraNode.Class() in [ "Camera2", "Camera"]: cameraNodeName = cameraNode.name() frame = nuke.getInput("Frame to Project for {0}?".format(cameraNode.name())) try: int(frame) except ValueError: nuke.message("You must enter a frame number!") return 0 copy_paste() selectedCamera = nuke.selectedNode() selectedCamera.addKnob(nuke.Int_Knob('referenceFrame', 'Reference Frame')) selectedCamera['referenceFrame'].setValue(int(frame)) selectedCamera['label'].setValue("Projection at frame: [value referenceFrame]") selectedCamera['tile_color'].setValue(123863) selectedCamera['gl_color'].setValue(123863) for knob in selectedCamera.knobs().values(): if knob.hasExpression(): if knob.arraySize() ==1: nuke.animation( \ "{0}.{1}".format(selectedCamera.name(), knob.name()), \ "generate", \ ("{0}".format(nuke.root().firstFrame()), \ "{0}".format(nuke.root().lastFrame()), \ "1", "y", "{0}".format(knob.name()) \ )) else: i = knob.arraySize() -1 while i > -1: nuke.animation( \ "{0}.{1}.{2}".format(selectedCamera.name(), knob.name(), i), \ "generate", \ ("{0}".format(nuke.root().firstFrame()), \ "{0}".format(nuke.root().lastFrame()), \ "1", "y", "{0}".format(knob.name()) \ )) i = i-1 for knob in selectedCamera.knobs().values(): if knob.isAnimated(): knob.setExpression('curve(referenceFrame)')
def getFrameRange(): '''Open a dialog to request a Nuke-style frame range @return: a frameRange object if a valid frame range is entered None if frame range is invalid or dialog is cancelled ''' firstFrame = int(nuke.numvalue('root.first_frame')) lastFrame = int(nuke.numvalue('root.last_frame')) step = 1 _range = str(nuke.FrameRange(firstFrame,lastFrame,step)) r = nuke.getInput('Enter Frame Range:', _range) try: if not r: return None else: return nuke.FrameRange(r) except: nuke.message('Invalid frame range') return None
def easySave(): nkDir = nukeDir() # GET DESCRIPTION FROM USER BUT STRIP ALL WHITE SPACES description = nuke.getInput( 'script description', 'Your Comp name' ).replace( ' ', '' ) fileSaved = False version = 1 while not fileSaved: # CONSTRUCT FILE NAME nkName = '%s_%s_%03d.nk' % (SHOT,description, version) # JOIN DIRECTORY AND NAME TO FORM FULL FILE PATH nkPath = os.path.join( nkDir, nkName ) # IF FILE EXISTS VERSION UP if os.path.isfile( nkPath ): version += 1 continue # SAVE NUKE SCRIPT nuke.scriptSaveAs( nkPath ) fileSaved = True return nkPath
def easySave(): nkDir = nukeDir() # GET DESCRIPTION FROM USER BUT STRIP ALL WHITE SPACES - EASYSAVE description = nuke.getInput( 'script description: ', 'init comp' ).replace( ' ', '') fileSaved = False version = 1 while not fileSaved: # CONSTRUCT FILENAME t = os.getenv('SHOW') t = str(t) t = t.replace(' ', '') nkName = '%s_%s_%s_%s_v%02d.nk' % ( t, 'scene' + os.getenv('SCENE'), 'shot' + os.getenv('SHOT'), description, version ) # JOIN DIRECTORY AND NAME TO FORM FULL FILE PATH nkPath = os.path.join( nkDir, nkName ) # IF FILE EXISTS VERSION UP if os.path.isfile( nkPath ): version += 1 continue # SAVE NUKE SCRIPT nuke.scriptSaveAs( nkPath ) fileSaved = True return nkPath
start = int(nuke.numvalue("root.first_frame")) end = int(nuke.numvalue("root.last_frame")) incr = 1 if start < 1: nuke.message("Start frame number cannot be less than 1") return try: _range = str(nuke.FrameRange(start, end, incr)) except ValueError,e: # In this case we have to extract from the error message the # correct frame range format string representation. # I'm expecting to have an error like: "Frame Range invalid (-1722942,-1722942)" msg = e. __str__() _range = msg[msg.index("(")+1: msg.index(")")] r = nuke.getInput("Frames to render:", _range) if r is not None: frame_ranges = nuke.FrameRanges(r) if nuke.thisNode()['slate'].value() is True: frame_ranges.add(nuke.FrameRange(start - 1, start - 1, 1)) frame_ranges.compact() nuke.tprint(frame_ranges) try: nuke.executeMultiple(_list, frame_ranges) except RuntimeError, e: if exceptOnError or e.message[0:9] != "Cancelled": # TO DO: change this to an exception type raise
def searchFor(): checkFor( nuke.getInput("Search String?") )
'wbu':'\\\\bcastvfxraid\\RAID\\CURRENT_PROJECTS\\j28777_worlds_busiest', 'ign':'\\\\bcastvfxraid\\RAID\\CURRENT_PROJECTS\\j28973_ignition'} if SHOWsn in SHOWS_dict: SHOWln = SHOWS_dict[SHOWsn] return SHOWln else: return 0 #Create Asset Management and Shot Selection Panel myPanel = nuke.Panel("ShotSetup") myPanel.addSingleLineInput("Shot: ", "") userInput = nuke.getInput( 'Setup: ', 'Your Shot name' ).replace( ' ', '') if userInput: for n in nuke.selectedNodes(): n['value'] = 0 pass else: parts = userInput.split('_') def newParts(): SHOWsn = (parts[0]) SHOWln = (shows(SHOWsn)) if SHOWln == 0: EP = ""