def process(self): from nukescripts import autoBackdrop nodes = list() if (self.options or {}).get("useSelection"): nodes = self.nodes if len(nodes) >= 1: anlib.select_nodes(nodes) bckd_node = autoBackdrop() bckd_node["name"].setValue("{}_BDN".format(self.name)) bckd_node["tile_color"].setValue(int(self.node_color, 16)) bckd_node["note_font_size"].setValue(24) bckd_node["label"].setValue("[{}]".format(self.name)) # add avalon knobs instance = anlib.imprint(bckd_node, self.data) return instance else: msg = str("Please select nodes you " "wish to add to a container") self.log.error(msg) nuke.message(msg) return else: bckd_node = autoBackdrop() bckd_node["name"].setValue("{}_BDN".format(self.name)) bckd_node["tile_color"].setValue(int(self.node_color, 16)) bckd_node["note_font_size"].setValue(24) bckd_node["label"].setValue("[{}]".format(self.name)) # add avalon knobs instance = anlib.imprint(bckd_node, self.data) return instance
def custom_backdrop(txt,fontsize,align,color,times,axis,spacing): #CREATING BACKDROP node = nukescripts.autoBackdrop() #DEFINING COLORS colors = {"green":int(93950720.0), "pink":int(3596850175.0), "dark":int(68228863.0), "yellow":int(4293503743.0), "grey":int(2846468607.0), "random":int(2846468607.0)} #CLEARING SELECTION prev_sel = nuke.selectedNodes() for i in prev_sel: i['selected'].setValue(False) node['selected'].setValue(True) #SETTING BACKDROP'S VARIOUS KNOBS node['label'].setValue('<'+align+'>'+txt) node['note_font_size'].setValue(fontsize) node['tile_color'].setValue(colors[color]) #CREATING DOTS dots = create_dots(node,axis) #REPLICATE BACKDROP BASED ON CONDITION if times == 0: pass elif times > 0: [replicate_backdrop(axis,dots,i,spacing) for i in range(times)]
def bakeProjection(mb): """Create a projection setup for the current frame.""" if mb.Class() != "ModelBuilder": return clearNodeSelection() srcCam = mb.input(1) if not srcCam: return w = mb.screenWidth() h = mb.screenHeight() src = mb.input(0) frame = nuke.frame() if (mb['textureType'].getValue() > 0): frame = mb['textureFrame'].getValue() label = '(frame ' + str(frame) + ')' srcdot = nuke.createNode('Dot', '', False) srcdot.setInput(0, src) srchold = nuke.createNode('FrameHold', '', False) stamp = nuke.createNode('PostageStamp', '', False) project = nuke.createNode('Project3D', '', False) apply = nuke.createNode('ApplyMaterial', '', False) cam = copyCamera(srcCam) camhold = nuke.clone(srchold, '', False) camdot = nuke.createNode('Dot', '', False) project.setInput(1, camdot) srcdot.setXYpos(int(mb.xpos() + w * 3.5), int(mb.ypos())) srchold.setXYpos(int(srchold.xpos()), int(srcdot.ypos() + w)) stamp.setXYpos(int(stamp.xpos()), int(stamp.ypos() + srchold.screenHeight() + h * 2)) cam.setXYpos( int(srchold.xpos() - w * 1.5), int(srchold.ypos() + srchold.screenHeight() / 2 - cam.screenHeight() / 2)) camhold.setXYpos( int(cam.xpos() + cam.screenWidth() / 2 - srchold.screenWidth() / 2), int(stamp.ypos() + h)) project.setXYpos(int(stamp.xpos()), int(stamp.ypos() + stamp.screenHeight() + h * 2)) camdot.setXYpos( int(camdot.xpos()), int(project.ypos() + project.screenHeight() / 2 - camdot.screenHeight() / 2)) apply.setXYpos(int(stamp.xpos()), int(apply.ypos() + w)) srchold.knob('first_frame').setValue(frame) srcdot.setSelected(True) srchold.setSelected(True) stamp.setSelected(True) project.setSelected(True) apply.setSelected(True) cam.setSelected(True) camhold.setSelected(True) camdot.setSelected(True) bd = nukescripts.autoBackdrop() bd['label'].setValue('Frame %d' % frame)
def nuke_backdrop(input=None): import nukescripts bd = nukescripts.autoBackdrop() bd['tile_color'].setValue(int(input)) return 'lime', 'Backdrop node created'
def process(self): from nukescripts import autoBackdrop instance = None if (self.options or {}).get("useSelection"): nodes = nuke.selectedNodes() if not nodes: nuke.message("Please select nodes that you " "wish to add to a container") return elif len(nodes) == 1: # only one node is selected instance = nodes[0] if not instance: # Not using selection or multiple nodes selected bckd_node = autoBackdrop() bckd_node["tile_color"].setValue(int(self.node_color, 16)) bckd_node["note_font_size"].setValue(24) bckd_node["label"].setValue("[{}]".format(self.name)) instance = bckd_node # add avalon knobs lib.set_avalon_knob_data(instance, self.data) lib.add_publish_knob(instance) return instance
def autoShuffleReads(nodes): import re import nuke nuke.Undo().name("organize and split") nuke.Undo().begin() readList = [] yPosAvg = 0 xPosAvg = 0 count = 0 try: nodes # does a exist in the current namespace except NameError: nodes = nuke.selectedNodes() for curNode in nodes: if curNode.Class() == "Read": readList.append({"file": nuke.filename(curNode), "node": curNode}) yPosAvg = yPosAvg + curNode["ypos"].value() xPosAvg = xPosAvg + curNode["xpos"].value() count += 1 readListSorted = sorted(readList, key=lambda k: k["file"]) xPosAvg = int(xPosAvg / count) yPosAvg = int(yPosAvg / count) count = 0 for readNode in readListSorted: readNode["node"]["xpos"].setValue(xPosAvg - 110 * count) readNode["node"]["ypos"].setValue(yPosAvg) readNode["node"]["selected"].setValue(True) count += 1 for n in nuke.selectedNodes(): n.autoplace() prevNode = nuke.nodes.Dot() originalDot = prevNode for curNode in nuke.selectedNodes(): if curNode.Class() == "Read": count += 1 filename = nuke.filename(curNode) passName = filename.split(".")[1] if re.match(r"^[A-Za-z0-9_]+$", passName): newLayer = nuke.Layer(passName, [passName + ".red", passName + ".green", passName + ".blue"]) shuffle = nuke.nodes.Shuffle(label=passName, inputs=[curNode]) shuffle["out"].setValue(passName) dotNode = nuke.nodes.Dot(inputs=[shuffle]) copyNode = nuke.nodes.Copy(inputs=[prevNode, dotNode], channels=passName, selected=True) prevNode = copyNode else: masterNode = curNode if count % 2 == 0: curNode["ypos"].setValue(curNode["ypos"].value() + 110) originalDot.setInput(0, masterNode) backdrop = nukescripts.autoBackdrop() backdrop.knob("tile_color").setValue(2139062271) nuke.Undo().end()
def createBackdrop(self, nodesList, hexColor): #deselect all self.deselectAll() #Select nodesList in viewport for node in nodesList: node.setSelected(True) #nukescripts autobackdrop backdrop = nukescripts.autoBackdrop() backdrop['tile_color'].setValue(hexColor) return backdrop
def replicate_backdrop(axis,sel,count,spacing): #CATCHING NUKE OBJECT source = nuke.selectedNode() source['selected'].setValue(False) #QUERYING & PROCCESSING NUKE'S OBJECT'S COORDINATES w = int(source.knob("bdwidth").getValue()) h = int(source.knob("bdheight").getValue()) #QUERYING & PROCCESSING NUKE'S OBJECT'S COLOR AND LABEL color = int(source["tile_color"].getValue()) txt = str(source['label'].getValue()) txt1 = bytearray(txt) del txt1[0:] txt = str(txt1) #QUERYING NUKE'S OBJECT'S COLOR AND LABEL size = int(source['note_font_size'].getValue()) #CREATING BACKDROP REPLICA node = nukescripts.autoBackdrop() #SETTING NEW BACKDROP SIZE if axis == "horizontal": node.setYpos(source.ypos()) node.setXpos(source.xpos() + (w+spacing)) dot = nuke.createNode("Dot") if count == 0 : dot.setInput(0,sel) dot.setYpos(source.ypos() + (h/2) ) dot.setXpos(source.xpos() + (w+spacing/2)) elif axis == "vertical": node.setXpos(source.xpos()) node.setYpos(source.ypos() + (h+spacing/2)) dot = nuke.createNode("Dot") if count == 0 : dot.setInput(0,sel) dot.setYpos(source.ypos() + (h+spacing/6)) dot.setXpos(source.xpos() - ((w/2))) node.knob("bdwidth").setValue(w) node.knob("bdheight").setValue(h) #SETTING NEW BACKDROP'S VARIOUS KNOBS node['tile_color'].setValue(color) node['label'].setValue(txt + str(count+1)) txt = "" node['note_font_size'].setValue(size) node['selected'].setValue(True)
def myCheckFileName(self): self.delMyBackdrops() errorNameList = [] self.myFileLastNameDict.clear() self.myReadsNameDict.clear() if self.myReads: for read in self.myReads: readFilePath = read['file'].value() if readFilePath: self.myReadsNameDict.update({read: readFilePath}) if self.myReadsNameDict: j = 1 for myReadD in self.myReadsNameDict: myFileFullName = self.myReadsNameDict[myReadD] pathSplit = myFileFullName.split('/') if pathSplit: findFlag = False pathSplitR = list(pathSplit) pathSplitR.reverse() for i, myPath in enumerate(pathSplitR): #print myPath if i > 1: myPathSplit = myPath.split('_') numMyPathSplit = len(myPathSplit) if numMyPathSplit > 2: serProjectPath = os.path.join( PROJECT_PATH, myPathSplit[0], r'Project\scenes\animation', myPathSplit[1], myPathSplit[2]) if os.path.isdir(serProjectPath): findFlag = True break if findFlag: lastPath = '\\'.join(pathSplit[-i - 1::]) self.myFileLastNameDict.update({myReadD: lastPath}) findFlag = False else: self.setSelecteNone() myReadD.setSelected(True) myBackdrop = nukescripts.autoBackdrop() myBackdrop.knob('tile_color').setValue(4278255615L) myBackdrop.knob('name').setValue('Wrong Name %s' % j) myBackdrop.knob('label').setValue( '\xe9\x94\x99\xe8\xaf\xaf') errorNameList.append(myReadD.name() + ": " + myFileFullName) j += 1 return errorNameList
def create_backdrop(nodesList, hexColor): """Create backdrop for nodesList with hexColor""" #deselect all deselect_all() #Select nodesList in viewport for node in nodesList: node.setSelected(True) #nukescripts autobackdrop backdrop = nukescripts.autoBackdrop() backdrop['tile_color'].setValue(hexColor) return backdrop
def process(self): from nukescripts import autoBackdrop nodes = list() if (self.options or {}).get("useSelection"): nodes = nuke.selectedNodes() if len(nodes) == 1: # only one node is selected node = nodes[0] instance = lib.imprint(node, self.data) return instance elif len(nodes) >= 2: bckd_node = autoBackdrop() bckd_node["name"].setValue("{}_BDN".format(self.name)) bckd_node["tile_color"].setValue(int(self.node_color, 16)) bckd_node["note_font_size"].setValue(24) bckd_node["label"].setValue("[{}]".format(self.name)) # add avalon knobs instance = lib.imprint(bckd_node, self.data) return instance else: nuke.message("Please select nodes you " "wish to add to a container") return else: bckd_node = autoBackdrop() bckd_node["name"].setValue("{}_BDN".format(self.name)) bckd_node["tile_color"].setValue(int(self.node_color, 16)) bckd_node["note_font_size"].setValue(24) bckd_node["label"].setValue("[{}]".format(self.name)) # add avalon knobs instance = lib.imprint(bckd_node, self.data) return instance
def create_basic_match_grade_setup(): Grade1 = nuke.nodes.Grade(black_clamp=False) Grade2 = nuke.nodes.Grade(inputs=[Grade1], black_clamp=False) Grade3 = nuke.nodes.Grade(inputs=[Grade2]) for i in nuke.selectedNodes(): i['selected'].setValue(False) Grade1['selected'].setValue(True) Grade2['selected'].setValue(True) Grade3['selected'].setValue(True) backdrop = nukescripts.autoBackdrop() backdrop['label'].setValue('Basic Match Grade') backdrop['note_font_size'].setValue(20)
def autoComper(node): p = autoComperPanel(node) if p.showModalDialog(): nuke.Undo().name('auto comp') nuke.Undo().begin() global allNodes allNodes = [] dotParent = nuke.nodes.Dot(inputs=[node], ypos = node['ypos'].value(), xpos = node['xpos'].value()+200 ) unPremultNode = nuke.nodes.Unpremult(inputs=[dotParent],channels='all') allNodes.append(unPremultNode) diffNode = shuffleLayer( unPremultNode, p.diff.value() ) giNode = shuffleLayer( unPremultNode, p.gi.value() ) specNode = shuffleLayer( unPremultNode, p.spec.value() ) reflectNode = shuffleLayer( unPremultNode, p.refl.value() ) refractNode = shuffleLayer( unPremultNode, p.refr.value() ) sssNode = shuffleLayer( unPremultNode, p.sss.value() ) selfIllumNode = shuffleLayer( unPremultNode, p.selfIllum.value() ) depthNode = shuffleLayer( dotParent, p.depth.value() ) mergeNode = mergeLayers(diffNode, giNode) mergeNode = mergeLayers(mergeNode, specNode) mergeNode = mergeLayers(mergeNode, reflectNode) mergeNode = mergeLayers(mergeNode, refractNode) mergeNode = mergeLayers(mergeNode, sssNode) mergeNode = mergeLayers(mergeNode, selfIllumNode) copyNode = nuke.nodes.Copy(from0='rgba.alpha',to0='rgba.alpha',inputs=[mergeNode,node]) if p.depthNormal.value() == True: black, white = fxpipenukescripts.getMinMax( node, p.depth.value() ) normNode = nuke.nodes.Grade( channels=p.depth.value(), blackpoint=black, whitepoint=white, white_clamp=True, label='normalize depth', inputs=[copyNode] ) copyNode = nuke.nodes.Invert( channels=p.depth.value(), disable=True, inputs=[normNode]) allNodes.append(nuke.nodes.Premult(channels='rgba',inputs=[copyNode])) for n in allNodes: n.setSelected(True) node.setSelected(False) backdrop = nukescripts.autoBackdrop() backdrop['label'].setValue('Auto Comp') backdrop['tile_color'].setValue(2139062271) nuke.Undo.end()
def autoBackdrop(): name = nuke.getInput("Label?") selNodes = nuke.selectedNodes() if not selNodes: return nuke.nodes.BackdropNode(label=name) n = nukescripts.autoBackdrop() n.knob("label").setValue(name) xmin = n["xpos"].value() xmax = xmin + n["bdwidth"].value() ymin = n["ypos"].value() ymax = ymin + n["bdheight"].value() for node in nuke.selectedNodes(): x, y = node["xpos"].value(), node["ypos"].value() if x > xmin and x < xmax and y > ymin and y < ymax and node.Class( ) == "BackdropNode": new = nuke.clone(node) nuke.delete(node) new["xpos"].setValue(x) new["ypos"].setValue(y)
def autoLayoutNodes(self): Psdutils().unselectAll() Psdutils().selectAdd(self.readnodes) try: Psdutils().selectAdd(self.unpremultnodes0) except: pass Psdutils().selectAdd(self.unpremultnodes) Psdutils().selectAdd(self.premultnodes) Psdutils().selectAdd(self.autocropnodes) Psdutils().selectAdd(self.transforms) Psdutils().selectAdd(self.mergenodes) try: _autoplace() except: Psdutils().autoplace(nuke.selectedNodes()) backdrop2d = nukescripts.autoBackdrop() backdrop2d.setName('toto') return backdrop2d
def ueAutoBackdrop(name, colour, fontsize=144): backdrop = nukescripts.autoBackdrop() backdrop["label"].setValue(name) backdrop["note_font_size"].setValue(fontsize) backdrop["tile_color"].setValue(int("%02x%02x%02x%02x" % colour, 16))
def generateAX(frameST, frameED, mode): root = nuke.root() root.begin() bksel = [] for node in nuke.allNodes(): if node['selected'].getValue(True): bksel.append(node) node['selected'].setValue(False) ct_hack = nuke.nodes.CurveTool() vtx = {} axnode_ls = [] progBar = nuke.ProgressTask('Sampling vertex') jobCount = 0 jobTotal = frameED - frameST for ctime in xrange(frameST, frameED, 1): nuke.execute(ct_hack, ctime, ctime) ### progress bar jobCount += 1 progShow = int(jobCount / jobTotal * 100) if progBar.isCancelled(): break progBar.setProgress(progShow) ################# for i in nukescripts.snap3d.selectedVertexInfos(): vtx[str(i.objnum) + '_' + str(i.index)] = i.position if ctime == frameST: for key, value in vtx.items(): ax = nuke.nodes.Axis() if mode == 1: ax['translate'].setAnimated() for i in range(3): ax['translate'].setValue(value[i], i) axid = nuke.Text_Knob('axid', 'axid', key) ax.addKnob(axid) axnode_ls.append(ax) else: for key, value in vtx.items(): for ax in axnode_ls: if ax['axid'].value() == key: for i in range(3): ax['translate'].setValue(value[i], i) nuke.delete(ct_hack) del progBar del ctime for ctime in xrange(frameST, frameED, 1): for ax in axnode_ls: tr = ax['translate'].getValueAt(ctime) ax['translate'].setValueAt(tr[0], ctime, 0) ax['translate'].setValueAt(tr[1], ctime, 1) ax['translate'].setValueAt(tr[2], ctime, 2) scene = nuke.nodes.Scene() for i in range(len(axnode_ls)): axnode_ls[i]['selected'].setValue(True) scene.setInput(i, axnode_ls[i]) if i == 0: scene.setXYpos( int(axnode_ls[i].xpos()), int(axnode_ls[i].ypos() + nuke.toNode('preferences')['GridWidth'].getValue())) nukescripts.autoBackdrop() for ax in axnode_ls: ax['selected'].setValue(False) for revertsel in bksel: revertsel['selected'].setValue(True) root.end()
def sb_backdrop(): # Create the panel. p = nuke.Panel("sb_backdrop") p.addSingleLineInput('Backdrop name', '') p.addSingleLineInput('Font size', '44') result = p.show() if not result: return bd_name = p.value("Backdrop name") font_size = p.value("Font size") if not font_size.isdigit(): font_size = 44 else: font_size = int(font_size) ok_colors = [ 726945023, 758728703, 1194668799, 1161185279, 658977535, 1145521407, 1095189759, 942753791, 994522623 ] ran_num = random.randrange(0, len(ok_colors)) color = ok_colors[ran_num] selNodes = nuke.selectedNodes() if not selNodes: n = nuke.createNode("BackdropNode", inpanel=False) n["tile_color"].setValue(color) n["note_font_size"].setValue(font_size) n["label"].setValue(bd_name) return # Calculate bounds for the backdrop node. bdX = min([node.xpos() for node in selNodes]) bdY = min([node.ypos() for node in selNodes]) bdW = max([node.xpos() + node.screenWidth() for node in selNodes]) - bdX bdH = max([node.ypos() + node.screenHeight() for node in selNodes]) - bdY # enclosedbd = [] # for node in selNodes: # if node.Class() == "BackdropNode": # enclosedbd.append(node) # if enclosedbd: # bd_order = min([node.knob("z_order").getValue() for node in enclosedbd])-1 # else: # bd_order = 0 # Expand the bounds to leave a little border. Elements are offsets for left, top, right and bottom edges respectively left, top, right, bottom = (-50, -100, 50, 50) bdX += left bdY += top bdW += (right - left) bdH += (bottom - top) n = nukescripts.autoBackdrop() n.hideControlPanel() n["xpos"].setValue(bdX) n["bdwidth"].setValue(bdW) n["ypos"].setValue(bdY) n["bdheight"].setValue(bdH) n["tile_color"].setValue(color) n["note_font_size"].setValue(font_size) n["label"].setValue(bd_name) # n["z_order"].setValue(bd_order) # revert to previous selection n['selected'].setValue(False) for node in selNodes: node['selected'].setValue(True) return n
def myCheckFrames(self): self.delMyBackdrops() self.myReadsNameDict.clear() self.myReadsStartDict.clear() self.myReadsLastDict.clear() j = 1 addBackdropFlag = False noFileList = {} if self.myReads: for read in self.myReads: readFilePath = read['file'].value() if readFilePath: fileType = os.path.splitext(readFilePath)[-1] readFileStart = read['first'].value() readFileLast = read['last'].value() self.myReadsNameDict.update({read: readFilePath}) self.myReadsStartDict.update({read: readFileStart}) self.myReadsLastDict.update({read: readFileLast}) #查询位数 #numPlaces = len('%d' % readFileLast) numPlaces = int( readFilePath.split("/")[-1].split(".")[1].split("%0") [-1].split('d')[0]) if fileType != '.mov' and readFileStart != readFileLast: k = [] pathSplit = readFilePath.split('/') joinPath = '/'.join(pathSplit[0:-1]) sequences = pyseq.getSequences(joinPath) #k=sequences[0].missing() for i in range(readFileStart, readFileLast + self.selectFrame, self.selectFrame): checkPath = readFilePath.replace( ('.%' + '0%dd' % numPlaces), (('.%' + '0%dd' % numPlaces) % i)) print checkPath if not os.path.isfile(checkPath): print "aaa\n" k.append(i) if k: sortNum = self.mySortNum(k) numTT = '' lenNum = len(sortNum) for nn in sortNum: if str(type(nn)).find('int') >= 0: numTT += '%s,' % nn else: numTT += '%s-%s,' % (nn[0], nn[1]) tmpText = readFilePath + '\n' + numTT[:-1] if not tmpText in noFileList.values(): noFileList.update({read.name(): tmpText}) addBackdropFlag = True else: if not os.path.isfile(readFilePath): if not readFilePath in noFileList.values(): noFileList.update({read.name(): readFilePath}) addBackdropFlag = True if addBackdropFlag: self.setSelecteNone() read.setSelected(True) myBackdrop = nukescripts.autoBackdrop() myBackdrop.knob('tile_color').setValue(4278190335L) myBackdrop.knob('name').setValue('Lack Frames %s' % j) myBackdrop.knob('label').setValue( '\xe7\xbc\xba\xe5\xb8\xa7') addBackdropFlag = False j = j + 1 self.setSelecteNone() return noFileList
def backdrop_nodes(nodes_list, name): select_nodes(nodes_list) backdrop = nukescripts.autoBackdrop() backdrop['name'].setValue(name)
def AutoProjectSettings(): print print('.............................') print('... Starting Auto Project ...') print('.............................') ####################### # Create a Dialog Box # # Input variables readFile = '/groups/cenote/BYU_anm_pipeline/production/shots/' startAt = 'Force Start at Frame 1001' exportAt = 'Export at Original Frame Range' localizer = 'Localization Policy' TCL = 'Use TCL command on Write node' saveFolder = '/groups/cenote/' scriptName = 'Script Name' addFolder = 'scripts, render' z = nuke.Panel('New comp from shot layers') z.addFilenameSearch('Read File', readFile) z.addBooleanCheckBox(startAt, 'True') z.addBooleanCheckBox(exportAt, 'False') z.addBooleanCheckBox(localizer, 'False') z.addBooleanCheckBox(TCL, 'True') z.addFilenameSearch('Save Folder', saveFolder) z.addSingleLineInput('Script Name', scriptName) z.addSingleLineInput('Additional Folders', addFolder) z.addButton('Cancel') z.addButton('OK') z.setWidth(600) result = z.show() # End of Dialog Box # ##################### if result == 0: pass # If hit 'Cancel', pass else: #files = glob.glob(readFile, recursive=True) #print(files) # Get values readFile = z.value(readFile) startAt = z.value(startAt) exportAt = z.value(exportAt) localizer = z.value(localizer) TCL = z.value(TCL) saveFolder = z.value(saveFolder) scriptName = z.value(scriptName) addFolder = z.value('Additional Folders') # Internal variables createFolder = False versionUp = False createScriptFolder = False createExportFolder = False if (readFile == ('Read File')) or ( readFile == ('') ): # If Read file keep with the original value or is empty, the process will not run print('Nothing to do here!') pass else: task = nuke.ProgressTask('Creating script...') if (saveFolder == '') or (saveFolder == 'Master Folder'): createFolder = False print print('No folder structure created ') else: ########################### # Create Folder Structure # createFolder = True shotFolder = (os.path.join(saveFolder, scriptName)) print print('Create folder structure at') print(saveFolder) try: os.mkdir(shotFolder) print print('-> Shot folder created: ' + shotFolder) task.setMessage('Creating: %s' % (shotFolder)) except: print print('-> Main folder already exist!\n%s' % (shotFolder)) if (addFolder == ''): #createFolder = False print print("--> Don't create any sub-folders") pass else: folderList = [] for i in addFolder.split(', '): folderList.append(i) # Create sub-directories for i in folderList: folderName = (os.path.join(shotFolder, i)) folderName = folderName.replace('\\', '/') task.setMessage('Creating: %s' % (folderName)) try: os.mkdir(folderName) print print('--> Created sub-directory: ' + folderName) except: print print('--> Folder already exist!\n%s' % (folderName)) versionUp = True if folderList.index(i) == 0: scriptFolder = folderName # Get the first folder name to save the Script createScriptFolder = True if folderList.index(i) == 1: exportFolder = folderName # Get the second folder name to set the Write node createExportFolder = True print print('++++++++++++++++++++++++++++++++++') # End of Folder Creator # ##################### ############### # Create Read # filelist = [readFile] if filelist != None: for f in filelist: newRead = nuke.createNode("Read", "file {" + f + "}", inpanel=True) inPoint = newRead['first'].getValue() outPoint = newRead['last'].getValue() newRead['before'].setValue('black') newRead['after'].setValue('black') newRead.hideControlPanel() inPoint = int(inPoint) outPoint = int(outPoint) print print('Read Node created: ' + newRead.name()) print('--> ' + f) task.setMessage('Creating: %s' % (newRead.name())) if localizer == True: newRead['localizationPolicy'].setValue('on') # Get Read infos width = (newRead.width()) height = (newRead.height()) frameRate = (newRead.metadata('input/frame_rate')) xPos = newRead['xpos'].getValue() yPos = newRead['ypos'].getValue() readFormat = newRead.knob('format').value().name() redAspect = False aspectRatio = (newRead.metadata('exr/pixelAspectRatio')) if aspectRatio == None: try: aspectRatio = (newRead.metadata('r3d/pixel_aspect_ratio')) redAspect = True except: aspectRatio = (newRead.metadata('input/pixel_aspect')) print('Input aspect Ratio') # End Create Read # ################### ################### # Create Timeclip # tclip = nuke.createNode('TimeClip') tclip['first'].setValue(int(inPoint)) tclip['last'].setValue(int(outPoint)) tclip['before'].setValue('black') tclip['after'].setValue('black') tclip['frame_mode'].setValue('start at') print print('Timeclip Node created: ' + tclip.name()) task.setMessage('Creating: %s' % (tclip.name())) if exportAt == True: origInPoint = inPoint origOutPoint = outPoint if startAt == True: outPoint = (outPoint - inPoint) + 1001 inPoint = 1001 tclip['frame'].setValue(str(inPoint)) tclip.setInput(0, newRead) tclip.hideControlPanel() tclip['xpos'].setValue(xPos) tclip['ypos'].setValue(yPos + 100) tclip['selected'].setValue(False) # End Timeclip # ################ ############## # Create Dot # nDot = nuke.createNode('Dot') nDot['name'].setValue('FinalOutput') nDot['label'].setValue('Final Output') nDot.setInput(0, tclip) nDot.hideControlPanel() nDot['xpos'].setValue(xPos + 34) nDot['ypos'].setValue(yPos + 650) nDot['selected'].setValue(False) # End Dot # ########### ################# # Create Viewer # v = 0 for i in nuke.allNodes(): if i.Class() in ('Viewer'): v = v + 1 if v == 0: nViewer = nuke.createNode('Viewer') nViewer.setInput(0, nDot) nViewer['xpos'].setValue(xPos + 200) nViewer['ypos'].setValue(yPos + 650) nViewer['selected'].setValue(False) if startAt == True: nuke.frame(1001) else: nuke.frame(int(inPoint)) # End Viewer # ############## #################################### # Create Backdrop for Read Session # newRead['selected'].setValue(True) sel = nuke.selectedNode() Xw = sel['xpos'].getValue() Yw = sel['ypos'].getValue() if exportAt == True: rLabel = ( '<center><img src = "' "Read.png" '" >Read File\n<font size = 1>Frame Range: %d - %d\nOriginal Frame Range: %d - %d' % ((inPoint), (outPoint), int(origInPoint), int(origOutPoint))) else: rLabel = ('<center><img src = "' "Read.png" '" >Read File\n<font size = 1>Frame Range: %s - %s' % (inPoint, outPoint)) bk = nukescripts.autoBackdrop() bk['label'].setValue(rLabel) bk['bdwidth'].setValue(500) bk['bdheight'].setValue(500) bk['xpos'].setValue(Xw - 225) bk['ypos'].setValue(Yw - 200) print print('Backdrop created: ' + bk.name()) print print('++++++++++++++++++++++++++++++++++') task.setMessage('Creating: %s' % (bk.name())) # End of create Backdrop # ########################## ########################## # Setup Project Settings # print print('Project Settings') task.setMessage('Project Settings...') sel = nuke.selectedNode() nkRoot = nuke.root() if frameRate == None: nkRoot['fps'].setValue(24) else: nkRoot['fps'].setValue(frameRate) if aspectRatio == None: aspectRatio = 1 nkRoot['first_frame'].setValue(inPoint) nkRoot['last_frame'].setValue(outPoint) nkRoot['lock_range'].setValue(True) print print('Set Frame Range to %s:%s' % (str(inPoint), str(outPoint))) if readFormat == None: newFormatName = ('%s_Resolution' % (newRead.name())) nuke.addFormat('%d %d %d %s' % (width, height, aspectRatio, newFormatName)) nkRoot['format'].setValue(newFormatName) newRead['format'].setValue(newFormatName) print print( 'Set Format to %s %sx%s, and aspect ratio to %s' % (newFormatName, str(width), str(height), str(aspectRatio))) else: for each in (nuke.formats()): if (each.name()) == readFormat: nkRoot['format'].setValue(each.name()) print print( 'Set Format to %s %sx%s, and aspect ratio to %s' % (str(each.name()), str(width), str(height), str(aspectRatio))) pass print print('++++++++++++++++++++++++++++++++++') # End of Project Settings # ########################### ################################################## # Create Timeclip to set to original plate range # if exportAt == True: newRead['selected'].setValue(False) exclip = nuke.createNode('TimeClip') exclip['first'].setValue(int(inPoint)) exclip['last'].setValue(int(outPoint)) exclip['before'].setValue('black') exclip['after'].setValue('black') exclip.hideControlPanel() exclip['xpos'].setValue(xPos) exclip['ypos'].setValue(yPos + 910) exclip.setInput(0, nDot) exclip['selected'].setValue(False) exclip['frame_mode'].setValue('start at') exclip['frame'].setValue(str(origInPoint)) task.setMessage('Creating: %s' % (exclip.name())) print print('Timeclip Node created: ' + exclip.name()) # End Timeclip Reverse # ######################## #################### #Create Write node # newRead['selected'].setValue(False) nWrite = nuke.createNode('Write') nWrite['name'].setValue('Write_Output') nWrite['channels'].setValue('rgb') nWrite['file_type'].setValue('exr') nWrite['create_directories'].setValue(True) task.setMessage('Creating: %s' % (nWrite.name())) frHash = '####' if (createExportFolder == True): if TCL == True: folderTCL = '[lindex [split [lindex [split [value root.name] /] end] .] 0]' scriptTCL = '[lindex [split [lindex [split [value root.name] /] end] .] 0].%05d.exr' writeFile = ('%s/%s/%s' % (exportFolder, folderTCL, scriptTCL)) else: writeFile = ( '%s/%s_v001/%s_v001.%s.exr' % (exportFolder, scriptName, scriptName, frHash)) nWrite['file'].setValue(writeFile) nWrite['xpos'].setValue(xPos) nWrite['ypos'].setValue(yPos + 1000) print print('Write Node created: ' + nWrite.name()) if exportAt == True: nWrite.setInput(0, exclip) else: nWrite.setInput(0, nDot) nWrite.hideControlPanel() nWrite['selected'].setValue(True) sel = nuke.selectedNode() Xw = sel['xpos'].getValue() Yw = sel['ypos'].getValue() # End Write # ############# ################################ #Create Backdrod to Write Area # if exportAt == True: wLabel = ( '<center><img src = "' "Write.png" '" >Output\n<font size = 1>Frame Range: %d - %d\nOriginal Frame Range: %d - %d' % ((inPoint), (outPoint), int(origInPoint), int(origOutPoint))) else: wLabel = ('<center><img src = "' "Write.png" '" >Output\n<font size = 1>Frame Range: %d - %d' % (inPoint, outPoint)) bk = nukescripts.autoBackdrop() bk['label'].setValue(wLabel) bk['bdwidth'].setValue(500) bk['bdheight'].setValue(400) bk['xpos'].setValue(Xw - 225) bk['ypos'].setValue(Yw - 300) task.setMessage('Creating: %s' % (bk.name())) print print('Backdrop created: ' + bk.name()) print print('++++++++++++++++++++++++++++++++++') # End Backdrop # ################ ###################################################### # Save project at first folder name from user's list # message = False version = 'v001' try: path, dirs, files = next(os.walk(scriptFolder)) if (len(files) >= 1): a = len(files) + 1 version = 'v00' + str(a) + '_avoidOverwrite' message = True except: print print('No script Folder') pass # Get name from clip clipname = os.path.basename(readFile) nameList = [] for a in clipname.split('.'): nameList.append(a) newName = nameList[0] newName = newName.replace('#', '') if (createScriptFolder == True): task.setMessage('Saving...') if scriptName == '': nukeFile = os.path.join(scriptFolder, ('%s_%s.nk' % (newName, version))) else: nukeFile = os.path.join( scriptFolder, ('%s_%s.nk' % (scriptName, version))) nukeFile = nukeFile.replace('\\', '/') if (message == True): nuke.message( 'Saved as\n%s\nto avoid overwrite other script!\nPlease, save comp with new name.' % (nukeFile)) nuke.scriptSaveAs(nukeFile) print print('Script saved at: ' + nukeFile) print print('++++++++++++++++++++++++++++++++++') print elif (createFolder == True): task.setMessage('Saving...') if scriptName == '': nukeFile = os.path.join(shotFolder, ('%s_%s.nk' % (newName, version))) else: nukeFile = os.path.join( shotFolder, ('%s_%s.nk' % (scriptName, version))) nukeFile = nukeFile.replace('\\', '/') if (message == True): nuke.message( 'Saved as\n%s\nto avoid overwrite other script!\nPlease, save comp with new name.' % (nukeFile)) nuke.scriptSaveAs(nukeFile) print print('Script saved at: ' + nukeFile) print print('++++++++++++++++++++++++++++++++++') print else: nuke.message( '<font size = "4" color = "red"><center><b>ATENTION!</b></font>\nScript unsaved! Please, do it!' ) print print('######### ATENTION! ##########') print('Script unsaved! Please, do it!') print print('++++++++++++++++++++++++++++++++++') print print('++++++++++++++++++++++++++++++++++') print('..................................') print
def load(self, context, name, namespace, data): """ Loading function to import .nk file into script and wrap it on backdrop Arguments: context (dict): context of version name (str): name of the version namespace (str): asset name data (dict): compulsory attribute > not used Returns: nuke node: containerised nuke node object """ # get main variables version = context['version'] version_data = version.get("data", {}) vname = version.get("name", None) first = version_data.get("frameStart", None) last = version_data.get("frameEnd", None) namespace = namespace or context['asset']['name'] colorspace = version_data.get("colorspace", None) object_name = "{}_{}".format(name, namespace) # prepare data for imprinting # add additional metadata from the version to imprint to Avalon knob add_keys = [ "frameStart", "frameEnd", "handleStart", "handleEnd", "source", "author", "fps" ] data_imprint = { "frameStart": first, "frameEnd": last, "version": vname, "colorspaceInput": colorspace, "objectName": object_name } for k in add_keys: data_imprint.update({k: version_data[k]}) # getting file path file = self.fname.replace("\\", "/") # adding nodes to node graph # just in case we are in group lets jump out of it nuke.endGroup() # Get mouse position n = nuke.createNode("NoOp") xcursor, ycursor = (n.xpos(), n.ypos()) anlib.reset_selection() nuke.delete(n) bdn_frame = 50 with anlib.maintained_selection(): # add group from nk nuke.nodePaste(file) # get all pasted nodes new_nodes = list() nodes = nuke.selectedNodes() # get pointer position in DAG xpointer, ypointer = pnlib.find_free_space_to_paste_nodes( nodes, direction="right", offset=200 + bdn_frame) # reset position to all nodes and replace inputs and output for n in nodes: anlib.reset_selection() xpos = (n.xpos() - xcursor) + xpointer ypos = (n.ypos() - ycursor) + ypointer n.setXYpos(xpos, ypos) # replace Input nodes for dots if n.Class() in "Input": dot = nuke.createNode("Dot") new_name = n.name().replace("INP", "DOT") dot.setName(new_name) dot["label"].setValue(new_name) dot.setXYpos(xpos, ypos) new_nodes.append(dot) # rewire dep = n.dependent() for d in dep: index = next( (i for i, dpcy in enumerate(d.dependencies()) if n is dpcy), 0) d.setInput(index, dot) # remove Input node anlib.reset_selection() nuke.delete(n) continue # replace Input nodes for dots elif n.Class() in "Output": dot = nuke.createNode("Dot") new_name = n.name() + "_DOT" dot.setName(new_name) dot["label"].setValue(new_name) dot.setXYpos(xpos, ypos) new_nodes.append(dot) # rewire dep = next((d for d in n.dependencies()), None) if dep: dot.setInput(0, dep) # remove Input node anlib.reset_selection() nuke.delete(n) continue else: new_nodes.append(n) # reselect nodes with new Dot instead of Inputs and Output anlib.reset_selection() anlib.select_nodes(new_nodes) # place on backdrop bdn = nukescripts.autoBackdrop() # add frame offset xpos = bdn.xpos() - bdn_frame ypos = bdn.ypos() - bdn_frame bdwidth = bdn["bdwidth"].value() + (bdn_frame * 2) bdheight = bdn["bdheight"].value() + (bdn_frame * 2) bdn["xpos"].setValue(xpos) bdn["ypos"].setValue(ypos) bdn["bdwidth"].setValue(bdwidth) bdn["bdheight"].setValue(bdheight) bdn["name"].setValue(object_name) bdn["label"].setValue( "Version tracked frame: \n`{}`\n\nPLEASE DO NOT REMOVE OR MOVE \nANYTHING FROM THIS FRAME!" .format(object_name)) bdn["note_font_size"].setValue(20) return containerise(node=bdn, name=name, namespace=namespace, context=context, loader=self.__class__.__name__, data=data_imprint)
def harding_backdrop(): bc = 1079406079 b = nukescripts.autoBackdrop() b['note_font_size'].setValue(40) b['tile_color'].setValue(bc) b['label'].setValue(nuke.getInput('Backdrop Label'))
def create_assets(self): # plan_dir = self.assets_dir + r'/S03_P17' # plans = os.listdir(self.assets_dir) plan_items = self.plan_lst.selectedItems() for plan in plan_items: _frames = 0 layers = "" names = "" persons = "" aovs = "" # print plan plan_dir = self.assets_dir + r'/' + plan.text() layers = os.listdir(plan_dir) for layer in layers: read_nodes_list = [] bd_color = 0xffffff11 new_nodes = [] backdrop_nodes = [] # print "\t" + layer name_dir = plan_dir + r'/' + layer names = os.listdir(name_dir) if layer == 'Characters' or layer == 'Environment' or layer == 'Props': if layer == 'Characters': for name in names: # print "\t\t" + name persons_dir = name_dir + r'/' + name persons = os.listdir(persons_dir) for person in persons: # print "\t\t\t" + person aovs_dir = persons_dir + r'/' + person aovs = os.listdir(aovs_dir) if _frames == 0: _frames = len(aovs) # import files as read file file_path = aovs_dir + r'/' + \ aovs[0].replace('0000', '####') readed_file = nuke.createNode('Read') readed_file.knob('file').setValue(file_path) readed_file.knob('origfirst').setValue(0) readed_file.knob('origlast').setValue(_frames - 1) readed_file.knob('first').setValue(0) readed_file.knob('last').setValue(_frames - 1) readed_file.knob('format').setValue('HD_720') file_name = layer + '_' + name + '_' + person readed_file.knob('name').setValue(file_name) read_nodes_list.append( readed_file.knob('name').getValue()) bd_color = colors.colors_dict[name.lower()] else: for name in names: # print "\t\t" + name aovs_dir = name_dir + r'/' + name aovs = os.listdir(aovs_dir) if _frames == 0: _frames = len(aovs) # import files as read file file_path = aovs_dir + r'/' + \ aovs[0].replace('0000', '####') readed_file = nuke.createNode('Read') readed_file.knob('file').setValue(file_path) readed_file.knob('origfirst').setValue(0) readed_file.knob('origlast').setValue(_frames - 1) readed_file.knob('first').setValue(0) readed_file.knob('last').setValue(_frames - 1) readed_file.knob('format').setValue('HD_720') file_name = layer + '_' + name readed_file.knob('name').setValue(file_name) read_nodes_list.append( readed_file.knob('name').getValue()) bd_color = colors.colors_dict[layer.lower()] else: aovs = os.listdir(name_dir) if _frames == 0: _frames = len(aovs) # import files as read file file_path = name_dir + r'/' + \ aovs[0].replace('0000', '####') readed_file = nuke.createNode('Read') readed_file.knob('file').setValue(file_path) readed_file.knob('origfirst').setValue(0) readed_file.knob('origlast').setValue(_frames - 1) readed_file.knob('first').setValue(0) readed_file.knob('last').setValue(_frames - 1) readed_file.knob('format').setValue('HD_720') file_name = layer readed_file.knob('name').setValue(file_name) read_nodes_list.append(readed_file.knob('name').getValue()) bd_color = colors.colors_dict[layer.lower()] # create merge nodes and connect them for node in read_nodes_list: backdrop_nodes.append(node) if node.find('beauty') != -1: continue else: new_nodes.append(node) if len(new_nodes) > 1: for i in range(1, len(new_nodes)): m = nuke.createNode('Merge2') m.knob('name').setValue('MERGE_' + layer + '_' + str(i)) m.knob('operation').setValue('plus') backdrop_nodes.append(m.knob('name').getValue()) for i in range(len(new_nodes)): if i == 0: n1 = nuke.toNode(new_nodes[i]) n2 = nuke.toNode(new_nodes[i + 1]) m = nuke.toNode('MERGE_' + layer + '_' + str(i + 1)) m.setInput(0, n1) m.setInput(1, n2) elif i >= 2: n = nuke.toNode(new_nodes[i]) m = nuke.toNode('MERGE_' + layer + '_' + str(i)) m.setInput(0, n) # print '-' * 30 # n = nuke.toNode("Props_direct_specular") # n.knob('selected').setValue(True) # nuke.selectConnectedNodes() # print backdrop_nodes for bn in backdrop_nodes: n = nuke.toNode(bn) n.knob('selected').setValue(True) nuke.autoplace(n) bd = nukescripts.autoBackdrop() bd.knob('name').setValue('BD_' + layer) bd.knob('label').setValue('layer: ' + layer) bd.knob('note_font_size').setValue(13) # 0xRRGGBB00 bd.knob('tile_color').setValue(bd_color) self.plan_lst.removeItemWidget(plan) '''
def autoShuffleReads(nodes): import re import nuke nuke.Undo().name('organize and split') nuke.Undo().begin() readList = [] yPosAvg = 0 xPosAvg = 0 count = 0 try: nodes # does a exist in the current namespace except NameError: nodes = nuke.selectedNodes() for curNode in nodes: if curNode.Class() == 'Read': readList.append({'file': nuke.filename(curNode), 'node': curNode}) yPosAvg = yPosAvg + curNode['ypos'].value() xPosAvg = xPosAvg + curNode['xpos'].value() count += 1 readListSorted = sorted(readList, key=lambda k: k['file']) xPosAvg = int(xPosAvg / count) yPosAvg = int(yPosAvg / count) count = 0 for readNode in readListSorted: readNode['node']['xpos'].setValue(xPosAvg - 110 * count) readNode['node']['ypos'].setValue(yPosAvg) readNode['node']['selected'].setValue(True) count += 1 for n in nuke.selectedNodes(): n.autoplace() prevNode = nuke.nodes.Dot() originalDot = prevNode for curNode in nuke.selectedNodes(): if curNode.Class() == 'Read': count += 1 filename = nuke.filename(curNode) passName = filename.split('.')[1] if re.match(r'^[A-Za-z0-9_]+$', passName): newLayer = nuke.Layer(passName, [ passName + '.red', passName + '.green', passName + '.blue' ]) shuffle = nuke.nodes.Shuffle(label=passName, inputs=[curNode]) shuffle['out'].setValue(passName) dotNode = nuke.nodes.Dot(inputs=[shuffle]) copyNode = nuke.nodes.Copy(inputs=[prevNode, dotNode], channels=passName, selected=True) prevNode = copyNode else: masterNode = curNode if count % 2 == 0: curNode['ypos'].setValue(curNode['ypos'].value() + 110) originalDot.setInput(0, masterNode) backdrop = nukescripts.autoBackdrop() backdrop.knob('tile_color').setValue(2139062271) nuke.Undo().end()