def buildHairMattes(node): hChans = [] for ch in node.channels(): if ch.startswith("_h_"): hChans.append(ch) prior = node if len(hChans) > 0: expression = "clamp(" for chan in hChans: if not ".alpha" in chan: #A+B(1-a)/b expression += chan + " + " exp = nuke.nodes.Expression() exp['channel0'].setValue('rgba') exp['expr0'].setValue(expression[:-2] + ")") exp.setInput(0, prior) shCopy = nuke.nodes.ShuffleCopy() nuke.tcl('add_layer { _h_all _h_all.red}') shCopy['in'].setValue('rgba') shCopy['in2'].setValue('none') shCopy['out'].setValue('none') shCopy['out2'].setValue('_h_all ') shCopy['black'].setValue('red') shCopy.setInput(0, prior) shCopy.setInput(1, exp) prior = shCopy return prior
def buildAssetMattes(node): channels=[] for ch in node.channels(): if ch.startswith("m_"): channels.append(ch) assets={} for chan in channels: asset=chan.split("_")[1] if not asset in assets.keys(): assets[asset]=[] if asset in chan: assets[asset].append(chan) prior=node for asset in assets.keys(): expression="clamp(" for chan in assets[asset]: if not ".alpha" in chan: #A+B(1-a)/b expression+=chan+" + " exp=nuke.nodes.Expression() exp['channel0'].setValue('rgba') exp['expr0'].setValue(expression[:-2]+")") exp.setInput(0,prior) shCopy=nuke.nodes.ShuffleCopy() nuke.tcl('add_layer { m_'+asset+'_all '+'m_'+asset+'_all'+'.red}') shCopy['in'].setValue('rgba') shCopy['in2'].setValue('none') shCopy['out'].setValue('none') shCopy['out2'].setValue('m_'+asset+'_all ') shCopy['black'].setValue('red') shCopy.setInput(0,prior) shCopy.setInput(1,exp) prior=shCopy return prior
def __call__(self, script): g = nuke.nodes.Group() with g: nuke.tcl(script) for i in range(g.inputs()): g.setInput(0, None) g.autoplace()
def buildRemainderChannel(node): lightChans = [] for ch in node.channels(): ch = ch.split('.')[0] if not ch in lightChans: lightChans.append(ch) nonAdditiveChans = ['diffuse_color', 'beauty', 'startRGBA', 'rgba'] expression = 'COLOR' for ch in lightChans: if not ch in nonAdditiveChans: if not 'light_group' in ch: expression += ' - ' + ch + '.COLOR' #create expression node nuke.tcl( 'add_layer { remainderRGBA remainderRGBA.red remainderRGBA.green remainderRGBA.blue remainderRGBA.alpha }' ) exp = nuke.nodes.Expression() exp['channel0'].setValue( 'remainderRGBA.red -remainderRGBA.green -remainderRGBA.blue') exp['expr0'].setValue(expression.replace('COLOR', 'red')) exp['channel1'].setValue( '-remainderRGBA.red remainderRGBA.green -remainderRGBA.blue') exp['expr1'].setValue(expression.replace('COLOR', 'green')) exp['channel2'].setValue( '-remainderRGBA.red -remainderRGBA.green remainderRGBA.blue') exp['expr2'].setValue(expression.replace('COLOR', 'blue')) exp.setInput(0, node) return exp
def setKey(node, knob, frame, value): ''' work around function to set values at key frames ''' TCL = 'setkey %s.%s %s %s' % (node, knob, str(frame), str(value)) try: nuke.tcl(TCL) except: return 0 return 1
def tcl_file(): try: s = nuke.getFilename("Source Script", "*.tcl;*.nk;*.py", "", "script") (root, ext) = os.path.splitext(s) if ext == ".py": execfile(s) else: nuke.tcl('source', s) except: pass
def insertToNewChannel(sh, chanName, inChannel): nuke.tcl('add_layer { ' + chanName + ' ' + chanName + '.red ' + chanName + '.green ' + chanName + '.blue ' + chanName + '.alpha}') sh['in'].setValue(inChannel) sh['out'].setValue(chanName) sh['red'].setValue('red') sh['green'].setValue('green') sh['blue'].setValue('blue') sh['alpha'].setValue('alpha') sh['label'].setValue('[value out]')
def shuffleCopyNewChannel(sh,newPass): nuke.tcl('add_layer { '+newPass+' '+newPass+'.red '+newPass+'.green '+newPass+'.blue '+newPass+'.alpha}') sh['in'].setValue('rgba') sh['in2'].setValue('none') sh['out'].setValue('none') sh['out2'].setValue(newPass) sh['black'].setValue('red') sh['white'].setValue('green') sh['red2'].setValue('blue') sh['green2'].setValue('alpha') sh['label'].setValue('[value out2]')
def uploadToFtrack(): node = None nukeFile = nuke.scriptName() for write in nuke.allNodes('Write'): if write.name() == 'Write_mov': node = write break if node and node.knob('uploadToFtrack').value() and not \ nukeFile.endswith('.autosave'): print "Submitting to Dailies" outputFile = writeNodeManager.getOutputFile() if 'FTRACK_TASKID' in os.environ: taskid = os.environ['FTRACK_TASKID'] else: taskid = None task = ftrack_utils2.getTask(_session, taskid, nukeFile) node.knob('uploadToFtrack').setValue(False) if task: taskMeta = {'filename': nukeFile} fps = int(task['project']['custom_attributes']['fps']) ftrack_utils2.addMetadata(_session, task, taskMeta) ftrack_utils2.copyToApprovals(outputFile, task['project']) outfilemp4, outfilewebm, thumbnail, metadata = ftrack_utils2.prepMediaFiles( outputFile) print "Starting conversion..." result = ftrack_utils2.convertFiles(outputFile, outfilemp4, outfilewebm, thumbnail) if result: print "File conversion complete. Starting upload." asset = ftrack_utils2.getAsset(_session, task, 'ReviewAsset') status = ftrack_utils2.getStatus(_session, 'Pending Internal Review') ff = int(nuke.tcl('frames first')) lf = int(nuke.tcl('frames last')) try: ftrack_utils2.createAndPublishVersion( _session, task, asset, status, 'Upload for Internal Review', thumbnail, outputFile, outfilemp4, outfilewebm, metadata, ff, lf, fps) print 'cleaning up temporary files...' ftrack_utils2.deleteFiles(outfilemp4, outfilewebm, thumbnail) print 'Upload Complete!' except Exception: print "Error while uploading movie" ftrack_utils2.syncToJHB(outputFile) else: nuke.message( "Error in submitting to ftrack. The project details might be incorrect." )
def getRendererParams(self): renderParams = '' if str(self.frameBox.text()) is not '': frames = str(self.frameBox.text()).replace('-', ',').strip() # remove any whitespaces in the string and replace '-' with ',' frames = ''.join(frames.replace('-',',').split()) else: frames = '%s,%s' % (nuke.tcl('frames first'), nuke.tcl('frames last')) if str(self.frameStepBox.text()) is not '': frames = '%sx%s' % (frames, str(self.frameStepBox.text())) renderParams = '-F %s' % frames renderParams = '%s -X %s' % (renderParams, str(self.writeNodeBox.currentText())) return renderParams
def fileHandler(dropped_data): file_path = dropped_data file_range = '' if not os.path.isfile(file_path): file_path, sep, file_range = file_path.rpartition(' ') file_name, file_ext = os.path.splitext(file_path) file_ext = file_ext.lower() if file_ext.lower() == '.obj': read_node = nuke.createNode("ReadGeo2", inpanel=False) read_node["file"].fromUserText(dropped_data) read_node["selected"].setValue(0) return True elif file_ext.lower() == '.fbx': read_node = nuke.createNode("ReadGeo2", inpanel=False) read_node["file"].fromUserText(dropped_data) read_node["selected"].setValue(0) read_node = nuke.createNode( "Camera2", 'read_from_file 1 file {0}'.format(dropped_data), inpanel=False) read_node["selected"].setValue(0) read_node = nuke.createNode( "Light2", 'read_from_file 1 file {0}'.format(dropped_data), inpanel=False) read_node["selected"].setValue(0) return True elif file_ext.lower() in [ '.3dl', '.blur', '.csp', '.cub', '.cube', '.vf', '.vfz' ]: read_node = nuke.createNode("Vectorfield", inpanel=False) read_node["vfield_file"].setValue(dropped_data) read_node["selected"].setValue(0) return True elif file_ext.lower() == '.chan': read_node = nuke.createNode("Camera2", inpanel=False) nuke.tcl('in {0} {import_chan_file {1} }'.format( read_node.name(), dropped_data)) read_node["selected"].setValue(0) return True else: read_node = nuke.createNode("Read", inpanel=False) read_node["file"].fromUserText(dropped_data) return True
def st_writeFromeReadMeta(custom): # make sure custom param doesnt connect with values ahead of it if custom: custom = "_" + custom # get selected nodes writeNodes = nuke.selectedNodes() for wnode in writeNodes: if wnode.Class() == "Write": # Get top node in chain topnode_name = nuke.tcl("full_name [topnode %s]" % wnode.name()) topnode = nuke.toNode(topnode_name) # Path to read node fullPath = nuke.filename(topnode) pathOnly = os.path.dirname(topnode['file'].value()) writePath = pathOnly + '/' # Focal Length fLength = topnode.metadata()['input/focal_length'] focalSplit = fLength.split('/',1) focal = focalSplit[0] focal = focal + "MM" # Split up "File.jpg" to "File" and ".jpg" fullPathSplit = fullPath.split("/") fileName = fullPathSplit[len(fullPathSplit)-1] fileNameSplit = fileName.split('.') # Define write path and assign to Write Node writePath = (writePath + fileNameSplit[0] + "_" + focal + custom + "." + fileNameSplit[1]) wnode['file'].setValue(writePath) # Print the result print (wnode.name() + " : " + (wnode['file'].getValue()))
def DotLabel(): # get the node node = nuke.thisNode() if node.Class() == "Dot": # user's label input value if node['label'].value() == '': currentVal = node['label'].value() else: currentVal = ('<align=left>' + node['label'].value()) # if dot has input if node.inputs() == 1: # if input is hidden if node['hide_input'].value() == 1: autoLabel = ('<b><i>' + nuke.tcl("value this.input.name") + '</i></b>' + '\n' + currentVal) else: autoLabel = currentVal else: autoLabel = currentVal return autoLabel
def loadMattes_button(): node = nuke.thisNode() first = nuke.thisNode()['first'].value() last = nuke.thisNode()['last'].value() beautyNode = nuke.toNode(nuke.tcl("topnode %s"%node.name())) versionPath = scanPath.getVersionPath(beautyNode['file'].value()) mattes = glob.glob(versionPath + "/*matte*") reads = [] for m in sorted(mattes): seqPath = scanPath.getSeqPathFromPassPath(m) with nuke.root(): r = nuke.createNode("Read", inpanel=False) r['file'].setValue(seqPath) r['first'].setValue(first) r['last'].setValue(last) reads.append(r) #make a grid of matte nodes ydx = 0 xdx = 0 idx = 0 xpos = node['xpos'].value() + 150 ypos = node['ypos'].value() for r in reads: print "idx:", xpos + 150*(xdx%3), ypos + 150*ydx r.setXYpos(xpos + 150*(xdx%3), ypos + 150*ydx) if xdx%3 == 2: ydx += 1 xdx += 1 idx += 1 with nuke.root(): makeBackdrop(reads)
def FrameBaker(): import nuke def FrameB(Froze): n = nuke.selectedNode() label = n['label'].setValue(Froze) u = 'curve' + '(' + Froze + ')' trans = n['translate'] if trans.isAnimated(): n['translate'].setExpression(u) else: return rot = n['rotate'] if rot.isAnimated(): n['rotate'].setExpression(u) else: return foc = n['focal'] if foc.isAnimated(): n['focal'].setExpression(u) else: return n['tile_color'].setValue(65280L) n['gl_color'].setValue(65280L) frame = nuke.tcl('frame') panel = nuke.Panel('Frozen Frame') panel.addSingleLineInput("BakedFrame", frame) panel.show() Froze = panel.value('BakedFrame') print Froze FrameB(Froze)
def bakeGizmo(gizmo): ''' copy gizmo to group and replace it in the tree, so all inputs and outputs use the new group. returns the new group node ''' parent = getParent(gizmo) groupName = nuke.tcl( 'global no_gizmo; set no_gizmo 1; in %s {%s -New} ; return [value [stack 0].name]' % (parent.fullName(), gizmo.Class())) group = nuke.toNode('.'.join((parent.fullName(), groupName))) group.setSelected(False) if getOutputs(gizmo): #RECONNECT OUTPUTS IF THERE ARE ANY for node, pipes in getOutputs(gizmo).iteritems(): for i in pipes: node.setInput(i, group) #RECONNECT INPUTS for i in range(gizmo.inputs()): group.setInput(i, gizmo.input(i)) group.setXYpos(gizmo.xpos(), gizmo.ypos()) # COPY VALUES group.readKnobs(gizmo.writeKnobs(nuke.TO_SCRIPT)) nuke.delete(gizmo) return group
def setProjDir(var): # launch selectNodesPanel first to acquire list of nodes to affect, if any changeNodes = selectNodesPanel() if changeNodes is not None: if var == 0: try: filepath = os.path.dirname( nuke.getFilename('Set Project Directory')) except (TypeError, ValueError): nuke.message('Project directory not set!') elif var == 1: filepath = '[join [lrange [split [file dirname [knob root.name]] "/"] 0 end-0] "/"]' elif var == 2: filepath = '[join [lrange [split [file dirname [knob root.name]] "/"] 0 end-1] "/"]' elif var == 3: filepath = '[join [lrange [split [file dirname [knob root.name]] "/"] 0 end-2] "/"]' elif var == 4: filepath = '[join [lrange [split [file dirname [knob root.name]] "/"] 0 end-3] "/"]' else: filepath = '[join [lrange [split [file dirname [knob root.name]] "/"] 0 end-4] "/"]' newPath = nuke.tcl('return ' + filepath) # replace file paths in list of nodes acquired above to relative file paths for n in changeNodes: searchReplaceProjDir(newPath, n) # set project directory to selected path as above nuke.root().knob("project_directory").setValue(filepath)
def execute(language, command): """Execute the given command using the given language. Args: language (str): Language of the command to execute in. command (str): Command to execute """ try: if language == PY: # The command comes from the current user itself, which makes # running exec in here not so evil. exec command # pylint: disable=exec-used elif language == TCL: nuke.tcl(str(command)) except Exception: raise ValueError
def jopsFileHandler(dropdata): filePath = dropdata fileRange = '' if not os.path.isfile(filePath): filePath, sep, fileRange = filePath.rpartition(' ') fileName, fileExt = os.path.splitext(filePath) if fileExt == '.obj': r = nuke.createNode("ReadGeo2", inpanel=False) r["file"].fromUserText(dropdata) r["selected"].setValue(0) return True if fileExt == '.fbx': r = nuke.createNode("ReadGeo2", inpanel=False) r["file"].fromUserText(dropdata) r["selected"].setValue(0) nuke.tprint(dropdata) r = nuke.createNode("Camera2", 'read_from_file 1 file ' + dropdata, inpanel=False) r["selected"].setValue(0) r = nuke.createNode("Light2", 'read_from_file 1 file ' + dropdata, inpanel=False) r["selected"].setValue(0) return True 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 True 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 True r = nuke.createNode("Read", inpanel=False) r["file"].fromUserText(dropdata) return True
def findTopNode(n=nuke.selectedNode()): ''' Returns a string of the top node ''' topnode_name = nuke.tcl("full_name [topnode %s]" % n.name()) topnode_file = nuke.filename(nuke.toNode(topnode_name)) return topnode_name
def label_readout_creator(self): node_label_value = nuke.value("this.label", "") try: node_label_value = nuke.tcl("subst", node_label_value) except RuntimeError: # TCL execution failed, so just use the label as-is pass if node_label_value != "" and node_label_value is not None: self.lines.append(node_label_value)
def fileHandler(dropped_data): file_path = dropped_data file_range = "" if not os.path.isfile(file_path): file_path, sep, file_range = file_path.rpartition(" ") file_name, file_ext = os.path.splitext(file_path) file_ext = file_ext.lower() if file_ext.lower() == ".obj": read_node = nuke.createNode("ReadGeo2", inpanel=False) read_node["file"].fromUserText(dropped_data) read_node["selected"].setValue(0) return True elif file_ext.lower() == ".fbx": read_node = nuke.createNode("ReadGeo2", inpanel=False) read_node["file"].fromUserText(dropped_data) read_node["selected"].setValue(0) read_node = nuke.createNode("Camera2", "read_from_file 1 file {0}".format(dropped_data), inpanel=False) read_node["selected"].setValue(0) read_node = nuke.createNode("Light2", "read_from_file 1 file {0}".format(dropped_data), inpanel=False) read_node["selected"].setValue(0) return True elif file_ext.lower() in [".3dl", ".blur", ".csp", ".cub", ".cube", ".vf", ".vfz"]: read_node = nuke.createNode("Vectorfield", inpanel=False) read_node["vfield_file"].setValue(dropped_data) read_node["selected"].setValue(0) return True elif file_ext.lower() == ".chan": read_node = nuke.createNode("Camera2", inpanel=False) nuke.tcl("in {0} {import_chan_file {1} }".format(read_node.name(), dropped_data)) read_node["selected"].setValue(0) return True else: read_node = nuke.createNode("Read", inpanel=False) read_node["file"].fromUserText(dropped_data) return True
def jopsFileHandler(dropdata): filePath=dropdata fileRange= '' if not os.path.isfile(filePath): filePath, sep, fileRange = filePath.rpartition(' ') fileName, fileExt = os.path.splitext(filePath) if fileExt == '.obj': r = nuke.createNode("ReadGeo2", inpanel=False) r["file"].fromUserText(dropdata) r["selected"].setValue(0) return True if fileExt == '.fbx': r = nuke.createNode("ReadGeo2", inpanel=False) r["file"].fromUserText(dropdata) r["selected"].setValue(0) nuke.tprint(dropdata) r = nuke.createNode("Camera2", 'read_from_file 1 file '+dropdata, inpanel=False) r["selected"].setValue(0) r = nuke.createNode("Light2", 'read_from_file 1 file '+dropdata, inpanel=False) r["selected"].setValue(0) return True 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 True 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 True r = nuke.createNode("Read", inpanel=False) r["file"].fromUserText(dropdata) return True
def func(cls, *args, **kwargs): ret = cls.orig(*args, **kwargs) if ret is None or not cls.current_options: return ret group = nuke.nodes.Group() with group: nuke.scriptReadFile(cls.current_options['script'].encode('utf-8')) write_nodes = nuke.allNodes('Write') assert write_nodes if len(write_nodes) != 1: nuke.message('注意: 预合成中发现了多个输出节点, 可能导致渲染出错'.encode('utf-8')) precomp_name = cls.current_options['precomp_name'] name = '_'.join(i for i in ('Write', precomp_name.upper().replace(' ', '_'), '1') if i) for n in write_nodes: n.setName(name.encode('utf-8')) # Disable exr hash check # precomp node will change the value # so we need a assert node. assert_node = nuke.nodes.Assert() assert_node['expression'].setExpression( '[knob {}.checkHashOnRead 0]\n' '[return 1]'.format(n.name()).encode('utf-8')) edit.insert_node(assert_node, n.input(0)) nuke.tcl(b"export_as_precomp", cls.current_options['script'].encode('utf-8')) if cls.current_precomp_node: cls.current_precomp_node.reload() else: LOGGER.warning( 'Not found precomp node after `precomp_selected`') nuke.delete(group) cls.current_options = None cls.current_precomp_node = None return ret
def __set(name, value): # in case the knob does not exist, creating it. if name not in nuke.Root().knobs(): if isinstance(value, int): targetKnob = nuke.Int_Knob(name) elif isinstance(value, bool): targetKnob = nuke.Boolean_Knob(name) elif isinstance(value, float): targetKnob = nuke.Double_Knob(name) else: targetKnob = nuke.String_Knob(name) nuke.Root().addKnob(targetKnob) # replacing all escape to forward slashes if isinstance(value, basestring): value = value.replace("\\", "/") # updating knob value nuke.Root()[name].setValue(value) # updating tcl variable nuke.tcl('set {} "{}"'.format(name, value))
def getKnobIndex(): #useful function by Ivan Busquets tclGetAnimIndex = """ set thisanimation [animations] if {[llength $thisanimation] > 1} { return "-1" } else { return [lsearch [in [join [lrange [split [in $thisanimation {animations}] .] 0 end-1] .] {animations}] $thisanimation] } """ return int(nuke.tcl(tclGetAnimIndex))
def stpColor(node_parent): """Find topnode Class and set tile_color""" node_top_name = nuke.tcl("full_name [topnode %s]" % node_parent.name()) node_top_class = nuke.toNode(node_top_name).Class() node_color = 0 if node_top_class.startswith('Roto'): node_color = 1908830719 # system roto class color elif node_top_class.startswith('Deep'): node_color = 24831 # system deep class color else: node_color = 12040191 # pascal cyan return node_color
def filenameFilter(filename): import __main__ list = filenameFilters.get(nuke.thisClass()) if list: for f in list[::-1]: s = f[0](filename, *f[1], **f[2]) if s != None: filename = s list = filenameFilters.get('*') if list: for f in list[::-1]: s = f[0](filename, *f[1], **f[2]) if s != None: filename = s if not len(filenameFilters): # For back-compatibility allow user to define a filenameFix() function: if __main__.__dict__.has_key('filenameFix'): return __main__.__dict__['filenameFix'](filename) # For even further back-compatibility let them define a tcl filename_fix function: return nuke.tcl("filename_fix", filename) return filename
def setRefFrame(): n = nuke.thisGroup() n.begin() nuke.toNode("Switch1")['disable'].setValue(0) nuke.toNode("ScanlineRender1")['disable'].setValue(0) nuke.toNode("StabFrameHold")['first_frame'].setValue(n['refFrame'].value()) if n['S'].value() == 1: n['Stabilize'].execute() n = a.input(1) ss = n.input(1) n.end() topnode_name = nuke.tcl("full_name [topnode %s]" % ss.name()) cam = nuke.toNode(topnode_name) cam['near'].clearAnimated() cam['far'].clearAnimated() cam['near'].setValue(0.01) cam['far'].setValue(10000) ss=n['scene'].value() n.begin() nuke.toNode("NoOp1")['pick'].execute() n['refFrame'].setValue(nuke.frame()) nuke.toNode("Switch")['which'].setValue(0) r=nuke.toNode("Perspective") r.setSelected(False) r.hideControlPanel() r['rotate'].setValue(0) r['translate'].setValue(0) r['scaling'].setValue(1) r['uniform_scale'].setValue(ss) n.end() if n['extraHelper'].value() in [0,1,2]: n['findZ'].clearFlag(1) n['happyGroup'].setFlag(1) n['goGroup'].setFlag(1) if n['extraHelper'].value() in [1,2,5]: n['Adjust'].execute()
def render_panel(_list): nuke.tcl('render this')
def tri_new_setup(): nuke.tprint(" NEW project setup") projectId = os.getenv('TRI_PROJECT_ID') projectPath = os.getenv('TRI_PROJECT_PATH') projectLocalPath = os.getenv('TRI_PROJECT_LOCAL_PATH', "~") projectLocalFlag = os.getenv('TRI_PROJECT_LOCAL_FLAG', "0") path = projectLocalPath if projectLocalFlag == "1" else projectPath path = path + "/" + projectId + ".xml" try: if not os.path.exists(path): nuke.message("Path not found\n" + path) return projectPath = os.path.normpath(path) pData = etree.parse(path) except: nuke.message("Incorrect project setup\n" + path) nuke.tprint(" NEW incorrect project setup\n" + path) return root = nuke.root() if projectId != pData.getroot().get("id"): nuke.message("Incorrect project ID: " + projectId) nuke.tprint(" NEW incorrect project ID" + projectId) return root.addKnob(nuke.Tab_Knob('tri_panel', 'TRIGRAPH')) root.addKnob(nuke.String_Knob('tri_project_id', 'Project ID', pData.getroot().get("id"))) root.addKnob(nuke.Boolean_Knob('tri_project_stereo', 'Stereo3D', False)) root.addKnob(nuke.String_Knob('tri_project_artist', 'Artist', artistName())) root['tri_project_stereo'].clearFlag(nuke.STARTLINE) root.addKnob(nuke.String_Knob('tri_project_name', 'Project Name', pData.findtext("fullname", ""))) root.addKnob(nuke.String_Knob('tri_project_path', 'Project Path', nukenormpath(pData.findtext("path", "")))) root.addKnob(nuke.String_Knob('tri_project_local_path', 'Local Path', nukenormpath(projectLocalPath))) root.addKnob(nuke.Boolean_Knob('tri_project_local_flag', 'work locally', True if projectLocalFlag == "1" else False)) root.addKnob(nuke.String_Knob('tri_comp', 'comps', "_cmp/" + root['tri_project_id'].value())) root.addKnob(nuke.String_Knob('tri_result', 'result', "_res/" + root['tri_project_id'].value())) root['tri_result'].clearFlag(nuke.STARTLINE) root.addKnob(nuke.String_Knob('tri_dailies', 'dailies', "_dailies/_TODAY")) root['tri_dailies'].clearFlag(nuke.STARTLINE) formats = pData.find("formats") output_xml = ''.join([line.strip() for line in etree.tostring(formats).splitlines()]) root.addKnob(nuke.String_Knob('tri_project_xml_formats', '', output_xml)) root['tri_project_xml_formats'].setVisible(False) root['fps'].setValue([formats.findtext("fps")]) # add new Result and Dailies formats size = formats.find("result").find("size") nuke.addFormat(size.get('width') + " " + size.get('height') + " " + size.get('aspect') + projectId + " RESULT") size = formats.find("dailies").find("size") nuke.addFormat(size.get('width') + " " + size.get('height') + " " + size.get('aspect') + projectId + " DAILIES") root['format'].setValue(projectId + " RESULT") # setup stereo flag if formats.findtext("stereo") == "true": if nuke.ask("Init for stereo view?") is True: root['setlr'].execute() root['tri_project_stereo'].setValue(True) # setup additional luts #S-Log LUT #root['luts'].addCurve("S-Log1", "{pow(10.0, ((t - 0.616596 - 0.03) /0.432699)) - 0.037584}") #root['luts'].addCurve("S-Log2", "{pow(10.0, (x - 0.615971) * 2.698893) - 0.037584}") # setup project Scene Id and Shot # pSceneId = "" pShotNumber = "" p = nuke.Panel("PROJECT " + root['tri_project_id'].value()) p.addSingleLineInput("SCENE ID", pSceneId) p.addSingleLineInput("SHOT #", pShotNumber) p.addButton("Cancel") p.addButton("OK") if p.show() == 1: pSceneId = p.value("SCENE ID").upper() pShotNumber = p.value("SHOT #") scene_name = root['tri_project_id'].value() + "-" + pSceneId # GP-AZA shot_name = pSceneId + "-" + pShotNumber # AZA-010 root.addKnob(nuke.String_Knob('tri_project_scene_id', 'Scene ID', pSceneId)) root.addKnob(nuke.String_Knob('tri_project_shot_num', 'Shot #', pShotNumber)) root['tri_project_shot_num'].clearFlag(nuke.STARTLINE) root['tri_comp'].setValue("_cmp/" + scene_name + "/" + shot_name) # _cmp/GP-AZA/AZA-010 root['tri_result'].setValue("_res/" + scene_name + "/" + shot_name) # _res/GP-AZA/AZA-010 #-- setup scripts name mainpath = tri_path() + "/" + root['tri_comp'].value() # TRI_PATH + _cmp/GP-AZA/AZA-010 name = root['tri_project_id'].value() + "-" + shot_name + "_v01.nk" # GP-AZA-010 + _v01.nk root['name'].setValue(nukenormpath(mainpath + "/" + name)) # TRI_PATH/_cmp/GP-AZA/AZA-010 + / + GP-AZA-010_v01.nk # add new Write menu shortcut nuke.menu('Nodes').findItem('Image').addCommand("TriWrite", "nuke.createNode(\"TriWrite\")", "w", icon="Write.png") # add path utilities nuke.tcl('addUserKnob {26 "" +STARTLINE}') root.addKnob(nuke.PyScript_Knob('tri_env2path', " expand filenames ")) root['tri_env2path'].setValue("nodes = nuke.selectedNodes()\nif len(nodes) > 0:\n tri_env2path(nodes)\nelse:\n nodes = nuke.allNodes()\n tri_env2path(nodes)\n") root['tri_env2path'].setFlag(nuke.STARTLINE) root.addKnob(nuke.PyScript_Knob('tri_path2env', " collapse filenames ")) root['tri_path2env'].setValue("nodes = nuke.selectedNodes()\nif len(nodes) > 0:\n tri_path2env(nodes)\nelse:\n nodes = nuke.allNodes()\n tri_path2env(nodes)\n") root.addKnob(nuke.PyScript_Knob('tri_path_check', " check filenames ")) root['tri_path_check'].setValue("nodes = nuke.selectedNodes()\nif len(nodes) > 0:\n tri_path_check(nodes)\nelse:\n nodes = nuke.allNodes()\n tri_path_check(nodes)\n") nuke.tcl('addUserKnob {26 "" +STARTLINE}') path = tri_path() + "/" + root['tri_comp'].value() # TRI_PATH + / + _cmp/GP-AZA/AZA-010 try: if not os.path.exists(path): if nuke.ask("Dir: " + path + " not exists. Create?"): pass os.makedirs(path) except: nuke.message("Cannot create\n" + path) pData = None
def get_topnode(node): # return the topnode of node return nuke.toNode( nuke.tcl('return [value [topnode {0}].name]'.format(node.fullName())))
# -*- coding:utf-8 -*- import os import nuke # create environment variables from anima import utils utils.do_db_setup() # iterate over environment and set it in TCL for key, value in os.environ.iteritems(): try: nuke.tcl("set", str(key), str(value)) except RuntimeError: pass def filter_env_vars_in_filepath(filename): """Expand variables in path such as ``$PROJECT_ROOT``. """ import os expanded_path = os.path.expandvars(filename) return expanded_path # register callback nuke.addFilenameFilter(filter_env_vars_in_filepath)
def _perform(self): """ Perform the task. """ import nuke crawlers = self.crawlers() # loading nuke script nuke.scriptOpen(self.templateOption('scene', crawlers[0])) createdFiles = [] for crawlerGroup in Crawler.group(crawlers): startFrame = crawlerGroup[0].var('frame') endFrame = crawlerGroup[-1].var('frame') # setting up nuke nuke.root()['first_frame'].setValue(startFrame) nuke.root()['last_frame'].setValue(endFrame) # converting the active frame to the frame padding notation sourceFilePath = crawlerGroup[0].var('filePath') sourcePadding = crawlerGroup[0].var('padding') sourceExt = crawlerGroup[0].var('ext') sourceFilePath = '{0}{1}.{2}'.format( sourceFilePath[:(len(sourceExt) + sourcePadding + 1) * -1], "#" * sourcePadding, sourceExt) nuke.tcl('set sourceFile "{}"'.format(sourceFilePath)) nuke.tcl('set targetFile "{}"'.format(self.target( crawlerGroup[0]))) # passing all the options as tcl global variables for optionName in map(str, self.optionNames()): optionValue = self.option(optionName) # resolving template if necessary if isinstance(optionValue, basestring): optionValue = self.templateOption(optionName, crawler) # adding option to as tcl variable nuke.tcl('set {} "{}"'.format(optionName, optionValue)) # executing the write node for writeNode in nuke.allNodes('Write'): # skipping disabled write nodes if writeNode['disable'].value(): continue nuke.execute(writeNode, int(writeNode['first'].value()), int(writeNode['last'].value())) # multiple files (image sequence) currentFile = writeNode['file'].getValue() if "%0" in currentFile: for frame in range(int(writeNode['first'].value()), int(writeNode['last'].value() + 1)): bufferString = StringIO.StringIO() bufferString.write(currentFile % frame) createdFiles.append(bufferString.getvalue()) # single file else: createdFiles.append(currentFile) return list(map(FsPath.createFromPath, createdFiles))
def convertGizmosToGroups(self): ###Node Selections nodeSelection = nuke.allNodes() noGizmoSelection = [] gizmoSelection = [] for n in nodeSelection: if 'gizmo_file' in n.knobs(): gizmoSelection.append(n) else: noGizmoSelection.append(n) groupSelection = [] for n in gizmoSelection: bypassGroup = False ###Current Status Variables nodeName = n.knob('name').value() nodeXPosition = n['xpos'].value() nodeYPosition = n['ypos'].value() nodeHideInput = n.knob('hide_input').value() nodeCached = n.knob('cached').value() nodePostageStamp = n.knob('postage_stamp').value() nodeDisable = n.knob('disable').value() nodeDopeSheet = n.knob('dope_sheet').value() nodeDependencies = n.dependencies() nodeMaxInputs = n.maxInputs() inputsList = [] ###Current Node Isolate Selection for i in nodeSelection: i.knob('selected').setValue(False) n.knob('selected').setValue(True) nuke.tcl('copy_gizmo_to_group [selected_node]') ###Refresh selections groupSelection.append(nuke.selectedNode()) newGroup = nuke.selectedNode() ###Paste Attributes newGroup.knob('xpos').setValue(nodeXPosition) newGroup.knob('ypos').setValue(nodeYPosition) newGroup.knob('hide_input').setValue(nodeHideInput) newGroup.knob('cached').setValue(nodeCached) newGroup.knob('postage_stamp').setValue(nodePostageStamp) newGroup.knob('disable').setValue(nodeDisable) newGroup.knob('dope_sheet').setValue(nodeDopeSheet) ###Connect Inputs for f in range(0, nodeMaxInputs): inputsList.append(n.input(f)) for num, r in enumerate(inputsList): newGroup.setInput(num, None) for num, s in enumerate(inputsList): newGroup.setInput(num, s) n.knob('name').setValue('temp__'+nodeName+'__temp') newGroup.knob('name').setValue(nodeName) newGroup.knob('selected').setValue(False) ###Cleanup (remove gizmos, leave groups) for y in gizmoSelection: y.knob('selected').setValue(True) nukescripts.node_delete(popupOnError=False) for z in groupSelection: z.knob('selected').setValue(True) for w in noGizmoSelection: w.knob('selected').setValue(True)
r['sub_frame'].setValue(1) r['selected'].setValue(0) return except Exception, e: log_('DEBUG: NUKE_VERSION_MAJOR > 7? %s' % e) 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:
continue else: print "Forcing script save." cmdStack.append('script_save {%s}' % saveFile) else: node = getNukeNode(cmd) nodeArgs = ' '.join(args) if args else '' cmdStack.append('%s {%s}' % (node, nodeArgs)) # If we have nodes to execute, append those commands to the end of the stack for node, range in execNodes: if range is not None: cmdStack.append('execute $%s %s' % (node, range)) else: cmdStack.append('execute $%s [value $%s.first]-[value $%s.last]' % (node, node, node)) tclString = ';'.join(cmdStack) + ';' return tclString if __name__ == '__main__': try: parsedCmd = parseCLI(' '.join(sys.argv[1:])) except ValueError: import traceback traceback.print_exc() else: print '\n%s TCL COMMAND STRING %s' % ('='*15, '='*15) print '%s' % parsedCmd print '%s\n' % ('='*50,) nuke.tcl("""%s""" % parsedCmd)
def get_topnode(node): # Get topnode of node return nuke.toNode( nuke.tcl("full_name [topnode {0}]".format(node.name())))
def convertGizmosToGroups(): ###Node Selections nodeSelection = nuke.selectedNodes() noGizmoSelection = [] gizmoSelection = [] for n in nodeSelection: if 'gizmo_file' in n.knobs(): gizmoSelection.append(n) else: noGizmoSelection.append(n) groupSelection = [] for n in gizmoSelection: bypassGroup = False ###Current Status Variables nodeName = n.knob('name').value() nodeXPosition = n['xpos'].value() nodeYPosition = n['ypos'].value() nodeHideInput = n.knob('hide_input').value() nodeCached = n.knob('cached').value() nodePostageStamp = n.knob('postage_stamp').value() nodeDisable = n.knob('disable').value() nodeDopeSheet = n.knob('dope_sheet').value() nodeDependencies = n.dependencies() nodeMaxInputs = n.maxInputs() inputsList = [] ###Current Node Isolate Selection for i in nodeSelection: i.knob('selected').setValue(False) n.knob('selected').setValue(True) nuke.tcl('copy_gizmo_to_group [selected_node]') ###Refresh selections groupSelection.append(nuke.selectedNode()) newGroup = nuke.selectedNode() ###Paste Attributes newGroup.knob('xpos').setValue(nodeXPosition) newGroup.knob('ypos').setValue(nodeYPosition) newGroup.knob('hide_input').setValue(nodeHideInput) newGroup.knob('cached').setValue(nodeCached) newGroup.knob('postage_stamp').setValue(nodePostageStamp) newGroup.knob('disable').setValue(nodeDisable) newGroup.knob('dope_sheet').setValue(nodeDopeSheet) ###Connect Inputs for f in range(0, nodeMaxInputs): inputsList.append(n.input(f)) for num, r in enumerate(inputsList): newGroup.setInput(num, None) for num, s in enumerate(inputsList): newGroup.setInput(num, s) n.knob('name').setValue('temp__' + nodeName + '__temp') newGroup.knob('name').setValue(nodeName) newGroup.knob('selected').setValue(False) ###Cleanup (remove gizmos, leave groups) for y in gizmoSelection: y.knob('selected').setValue(True) nukescripts.node_delete(popupOnError=False) for z in groupSelection: z.knob('selected').setValue(True) for w in noGizmoSelection: w.knob('selected').setValue(True)
def helpButton(): """ open the github page as the help """ nuke.tcl("start", HELP_PAGE)