def pv2_createGizmo(nuke): #create 2 scene nodes and select epScene = nuke.createNode("Scene") epScene.setName("Emitters") epScene.setXpos(0) epScene.setYpos(-100) #now create gizmo to have it auto connect nuke.nodePaste("~/.nuke/Particular3DGroup.nk") nuke.extractSelected() gizmo = nuke.selectedNode() gizmo.setXpos(0) gizmo.setYpos(0) gizmo.setInput(1,epScene) nuke.show(gizmo) #add version check if nuke.NUKE_VERSION_MINOR < 1 : #change cam values to work with translate values only gizmoParticularPath = "%s.Particular v2_1" % gizmo.name() camExpressionX = "p_cam.translate.x * parent.pv2_camXMultiplier" camExpressionY = "p_cam.translate.y * parent.pv2_camYMultiplier" camExpressionZ = "p_cam.translate.z" print "Camera cannot be parented to Axis node" nuke.toNode(gizmoParticularPath)['CameraPos'].setExpression(camExpressionX, 0) nuke.toNode(gizmoParticularPath)['CameraPos'].setExpression(camExpressionY, 1) nuke.toNode(gizmoParticularPath)['CameraPos'].setExpression(camExpressionZ, 2)
def openBaseNode(openFloat = True): nodeList = [] nodes = nuke.selectedNodes() for sn in nodes: for knob in sn.knobs(): curKnob = sn['%s'%knob] if curKnob.hasExpression(): knobValue = curKnob.getValue() knobType = type(knobValue) if knobType is float: curFloatExpression = curKnob.animation(0).expression() foundNodesFloat = findAllNodes(curFloatExpression) nodeList.extend(foundNodesFloat) if knobType is list: for i in range(0, len(knobValue)): try: curListExpression = curKnob.animation(i).expression() foundNodesList = findAllNodes(curListExpression) nodeList.extend(foundNodesList) except: pass nodeList = list(set(nodeList)) for node in nodeList: n = nuke.toNode('%s'%node) nuke.show(n, forceFloat = openFloat)
def listbookmarks(): bm=[] zoomBy=1 #find bookmark nodes for n in nuke.allNodes(): n['selected'].setValue( False ) if n['icon'].value() == 'bookmark.png': n['selected'].setValue( True ) #select nodes for clarity bmLabel=nuke.selectedNode()['label'].value() if bmLabel: bm_name='"'+bmLabel+'"' # '"'<-lets it list correctly else: bm_name='"'+n.name()+'"' # '"'<-allows it to be sorted correctly with above bm.append(bm_name) if 0==len(bm): nuke.message('no bookmarks found') else: bookmarkList=str(sorted(bm)) #clean up list name pattern = re.compile('[\[\]\']') bookmarkList = pattern.sub('', bookmarkList) pattern = re.compile('[\,]') bookmarkList = pattern.sub(' ', bookmarkList) #let user choose bookmark panel = nuke.Panel ('BookMarks',200) panel.addEnumerationPulldown('go to',bookmarkList) panel.addSingleLineInput('zoom',zoomBy) panel.addBooleanCheckBox('also open node', False) panel.addButton("Cancel") panel.addButton("Zoom to") panel.addButton("Open") result=panel.show() if result: goto= panel.value('go to') zoomf= panel.value('zoom') alwaysOpen= panel.value('also open node') #select only relevent node for n in nuke.allNodes(): if goto == n.name() or goto == n['label'].value(): n['selected'].setValue( True ) else: n['selected'].setValue( False ) #set nuke to highlight chosen node, get xy pos and zoom into area and open if selected. if result ==1: nuke.zoom(float(zoomf),(nuke.selectedNode().xpos(),nuke.selectedNode().ypos())) if alwaysOpen: nuke.show(nuke.selectedNode()) elif result ==2: nuke.show(nuke.selectedNode()) else: pass
def shuffleNameCollect(): nodes = nuke.selectedNodes() info = [] if nodes == []: pass elif nodes != []: for node in nodes: if node.Class() == "Shuffle1" or node.Class() == "Shuffle": info.append(node.knob("in").value()) if info != []: node = nuke.selectedNode() path = node.metadata('input/filename') spliteado = (os.path.splitext( os.path.basename(path))[0]).split("_") killframes = spliteado.pop() newfilename = ("_").join(spliteado) sticky = nuke.nodes.StickyNote( label='#########' + newfilename + '#########' + '\n' + (', ' '\n'.join(info)), note_font_size=80, ) nuke.show(sticky) nuke.zoom(0.5, [sticky.xpos(), sticky.ypos()]) else: nuke.message("please select a shuffle node")
def review(): new = nuke.toNode("Review") if new: nuke.show(new) else: nuke.nodePaste(UserDir + '/Folders/NukeScripts/review.nk') new = nuke.toNode("Review") nuke.show(new)
def reloadAllBlinks(): ''' Reload all blinkScript nodes ''' nodes = [node for node in nuke.allNodes(recurseGroups = True) if node.Class() == 'BlinkScript'] for node in nodes: nuke.show(node) node.knob('reloadKernelSourceFile').execute() node.hideControlPanel()
def track_to_roto_in(): panel=nuke.Panel("roto name") panel.addSingleLineInput("name","") panel.addBooleanCheckBox('create RotoPaint', False) panel.show() name = panel.value("name") kind = panel.value("create RotoPaint") track = nuke.selectedNode() if kind == 1: roto = nuke.nodes.RotoPaint() else: roto = nuke.nodes.Roto() x = track['xpos'].value() y = track['ypos'].value() roto.setXYpos(x,y+100) #roto['label'].setValue(track['label'].value()) first = nuke.Root().knob('first_frame').getValue() first = int(first) last = nuke.Root().knob('last_frame').getValue() last = int(last)+1 frame = first Knobs = roto['curves'] root=Knobs.rootLayer transform = root.getTransform() roto['name'].setValue(name) roto.setSelected(True) nuke.show(roto) track.setSelected(False) while frame<last: r = track['rotate'].getValueAt(frame,0) rr = transform.getRotationAnimCurve(2) rr.addKey(frame,r) tx = track['translate'].getValueAt(frame,0) translx = transform.getTranslationAnimCurve(0) translx.addKey(frame,tx) ty = track['translate'].getValueAt(frame,1) transly = transform.getTranslationAnimCurve(1) transly.addKey(frame,ty) sx = track['scale'].getValueAt(frame,0) ssx = transform.getScaleAnimCurve(0) ssx.addKey(frame,sx) sy = track['scale'].getValueAt(frame,1) ssy = transform.getScaleAnimCurve(1) ssy.addKey(frame,sy) cx = track['center'].getValueAt(frame,0) ccx = transform.getPivotPointAnimCurve(0) ccx.addKey(frame,cx) cy = track['center'].getValueAt(frame,1) ccy = transform.getPivotPointAnimCurve(1) ccy.addKey(frame,cy) frame = frame+1
def Lines(): import nuke new = nuke.toNode("Lines") nuke.show(new) w = nuke.allNodes("Viewer") for one in w: one['input_process_node'].setValue('Lines') val = one['input_process'].value() if val == 0: one['input_process'].setValue(1) else: one['input_process'].setValue(0)
def scan_node_for_keyframes(node, allow_knobs=None, exclude_knobs=None, boundary_in=None, boundary_out=None): """ Args: node (Nuke Node): Nuke Node object allow_knobs (list, optional): list of specific knobs names which to scan for keyframes exclude_knobs (list, optional): list of knobs names which to ignore when scanning for keyframes boundary_in (int, optional): any keyframes on the timeline below this number will not be factored when finding the largest gap boundary_out (int, optional): any keyframes on the timeline above this number will not be factored when finding the largest gap Return: list: all key frame numbers for the node """ ctrl_panel_open = node.shown() if not ctrl_panel_open: # This is necessary to be able to see keyframes on knobs. nuke.show(node) all_knobs = node.knobs() if allow_knobs: all_knobs = dict([(k, v) for k, v in all_knobs.items() if k in allow_knobs]) if exclude_knobs: all_knobs = dict([(k, v) for k, v in all_knobs.items() if k not in exclude_knobs]) all_keys = set() for knob in all_knobs.values(): key_list = knob.getKeyList() if all( isinstance(obj, NUM_TYPES) for obj in (boundary_in, boundary_out)): key_list = [k for k in key_list if boundary_in < k < boundary_out] all_keys.update(key_list) if not ctrl_panel_open: # If node's Properties were closed to be begin with, close them again. node.hideControlPanel() return sorted(all_keys)
def Create_TPD_Roto(): ''' Creates the TPD_Roto node ''' # Create TPD_Roto n = nuke.createNode('TPD_Roto') # Check if previous connection is another TPD_Roto. If yes, set lightPass to the same value if n.inputs() > 0: if n.input(0).knob('lightPass'): n.knob('lightPass').setValue( int(n.input(0).knob('lightPass').getValue())) Open_Close_Roto(n) n.knob('selected').setValue(True) nuke.show(n)
def LoadCamera(cameraName): cam1 = nuke.nodes.Camera2(name="cam1") cam2 = nuke.nodes.Camera2(name="cam2") nuke.show(cam1) cam1['read_from_file'].setValue(True) cam1['file'].setValue(cameraName) cam1['read_from_file'].setValue(False) cam2['focal'].setExpression("cam1.focal") cam2['haperture'].setExpression("cam1.haperture") cam2['vaperture'].setExpression("cam1.vaperture") cam2['near'].setExpression("cam1.near") cam2['far'].setExpression("cam1.far") cam2['rotate'].setExpression("cam1.rotate.z", 0) cam2['rotate'].setExpression("(cam1.rotate.y)-90", 1) cam2['rotate'].setExpression("-(cam1.rotate.x)", 2) cam2['translate'].copyAnimations(cam1['translate'].animations()) return [cam1, cam2]
def restoreCheckpoint(nukeScript, nodeName, date): log("restoreCheckpoint %s %s %s" % (nukeScript, nodeName, date)) # We ask on rv side now, since otherwise dialog can come up behind rv. # # ans = nuke.ask ("Restore checkpoint: %s, %s ?" % (nodeName, date)) # log (" ans %s" % ans) log(" reading checkpoint script") nuke.Undo().begin("Restore %s, %s" % (nodeName, date)) try: nukescripts.misc.clear_selection_recursive() try: v = nuke.activeViewer().node().name() except: v = None if (rvmon): rvmon.restoreBegin() nodes = nuke.root().nodes() for n in nodes: #log (" deleting %s %s %s" % (n.name(), type(n).__name__, n.Class())) nuke.delete(n) nuke.scriptReadFile(nukeScript) if (v): n = nuke.toNode(v) if (n): nuke.show(n) if (rvmon): rvmon.restoreComplete() log(" checkpoint restore complete") except Exception, msg: nuke.message("Checkpoint restore failed:\n%s" % (msg, ))
def restoreCheckpoint (nukeScript, nodeName, date) : log ("restoreCheckpoint %s %s %s" % (nukeScript, nodeName, date)) # We ask on rv side now, since otherwise dialog can come up behind rv. # # ans = nuke.ask ("Restore checkpoint: %s, %s ?" % (nodeName, date)) # log (" ans %s" % ans) log (" reading checkpoint script") nuke.Undo().begin("Restore %s, %s" % (nodeName, date)) try : nukescripts.misc.clear_selection_recursive() try : v = nuke.activeViewer().node().name() except : v = None if (rvmon) : rvmon.restoreBegin() nodes = nuke.root().nodes() for n in nodes: #log (" deleting %s %s %s" % (n.name(), type(n).__name__, n.Class())) nuke.delete(n) nuke.scriptReadFile (nukeScript) if (v) : n = nuke.toNode(v) if (n) : nuke.show (n) if (rvmon) : rvmon.restoreComplete() log (" checkpoint restore complete") except Exception, msg: nuke.message("Checkpoint restore failed:\n%s" % (msg,))
def Open_Close_Roto(TPDRotoNode): ''' Opens and closes TPD_Roto node, to fix the weird bug that hides the roto transform box ''' # Open the group TPDRotoNode.begin() roto = nuke.toNode('TPD_ROTO_IN_GRP') # Find the 'maxPanels' value from the Preferences tab and add 1 prefs = nuke.toNode('preferences').knob('maxPanels') prefs.setValue(prefs.value() + 1) # Open and close the roto node nuke.show(roto) roto.hideControlPanel() # Set the 'maxPanels' value back to normal prefs.setValue(prefs.value() - 1) # Close the group TPDRotoNode.end()
def progress_bar(): nodes = nuke.selectedNodes() if not nodes == []: for node in nodes: count = 1 name = node['name'].value() task = nuke.ProgressTask(name) task.setMessage('Running') if node.Class() == 'Roto': nuke.show(node) shape_in_layers = node['curves'].rootLayer num_of_shapes = len(shape_in_layers) for shapes in shape_in_layers: if task.isCancelled(): break count = count + 1 change_selection(node, shapes) task.setProgress(int((count / num_of_shapes) * 100)) node.hideControlPanel() if task.isCancelled(): break else: nuke.message('Select Roto Nodes')
def singleClick(): global currentRow currentRow = widget.ui.nuke_write_table.currentRow() n = widget.ui.nuke_write_table.currentItem() nodename = widget.ui.nuke_write_table.item(currentRow, 1).text() print nodename deselect() nuke.toNode(nodename)['selected'].setValue(True) node = nuke.selectedNode() nuke.zoom(1, [node.xpos(), node.ypos()]) nuke.show(node) if widget.ui.nuke_write_table.currentColumn() == 0: disable = QtGui.QTableWidgetItem() if n.text() == "on": disable.setIcon(nukecrossicon) disable.setText("off") nuke.toNode(nodename)['disable'].setValue(True) elif n.text() == "off": disable.setIcon(nukecheckicon) disable.setText("on") nuke.toNode(nodename)['disable'].setValue(False) widget.ui.nuke_write_table.setItem(currentRow, 0, disable) elif widget.ui.nuke_write_table.currentColumn() == 1: global previousName previousName = widget.ui.nuke_write_table.currentItem().text() elif widget.ui.nuke_write_table.currentColumn() == 2: filename = widget.ui.job_name.text() pathname = widget.ui.image_folder.text() nodepath = pathname + "/" + nodename nodepath = nodepath.replace("/", "\\") if os.path.isdir(nodepath) is False: os.makedirs(nodepath)
kDivider = nuke.Text_Knob('divider', '') nStickyMain.addKnob(kDivider) # Information knob: tells the user how the gameplay develops kInfo = nuke.Text_Knob('Z_info', '', "<b>Information") nStickyMain.addKnob(kInfo) nStickyMain['User'].setName('Gameplay') # Framing the main node for n in nuke.allNodes(): n.setSelected(False) nStickyMain.setSelected(True) nuke.zoomToFitSelected() nuke.show(nStickyMain) nStickyMain.setSelected(False) # Creation of board and coord objects # ------------------------------------------------------------ board_creation() coord_objects = coord_objects_creation() # Setting the boats on the board # ------------------------------------------------------------ showUserAllBoats = nuke.ask( '<b><font size=4>Do you wish to see where your own boats are?') set_board()
def IBKMy(): nuke.nodePaste(UserDir+"/GeneralSetups/IBK.nk") a = nuke.selectedNode() print a nuke.show(a)
def C2T(dialog): # classes cameraClasses = ['Camera', 'Camera2'] cardClasses = ['Card', 'Card2'] #card card = None for n in nuke.selectedNodes(): if n.Class() in cardClasses: card = n break if card == None: nuke.message('no card selected?') return # initialize tool values for auto-creation label = card['label'].value() ref = int(nuke.frame()) first = int(nuke.Root().knob('first_frame').getValue()) last = int(nuke.Root().knob('last_frame').getValue()) bg = BGdetect() cam = getCamera() rootAspect = nuke.Root()['format'].value().pixelAspect() x = card.xpos() y = card.ypos() bg.setXYpos(x, y + 50) if dialog == True: # ask for tool values # all cams allCamsInScript = [] for n in nuke.allNodes(): if n.Class() in cameraClasses: allCamsInScript.append(n.name()) allCamsInScript.remove(cam.name()) # remove best camera ... allCamsInScript.insert(0, cam.name()) # ... and insert at beginning camListPrint = '' for c in allCamsInScript: camListPrint = camListPrint + c + ' ' camListPrint = camListPrint[:-1] #bg, info only. will be determined by selected node - if any .. #formatPrint = form #panel panel = nuke.Panel("C2T") panel.addSingleLineInput("label:", card['label'].value()) panel.addSingleLineInput("range:", str(first) + "-" + str(last)) panel.addSingleLineInput("ref frame:", str(ref)) panel.addEnumerationPulldown("camera:", camListPrint) #panel.addSingleLineInput("format:", formatPrint) if label == '': panel.addBooleanCheckBox('reverse label', True) #panel.show() if panel.show(): first = int(panel.value("range:").split("-")[0]) last = int(panel.value("range:").split("-")[1]) ref = int(panel.value("ref frame:")) cam = nuke.toNode(panel.value("camera:")) label = panel.value("label:") # reverse label if panel.value("reverse label") == True: card['label'].setValue(panel.value("label:")) else: nuke.message('canceled') nuke.delete(bg) # clean the mess up return else: print 'no dialog, use auto-created input values' # labels are usefull!! if label == '': panel = nuke.Panel("C2T label") panel.addSingleLineInput("label:", '') panel.addBooleanCheckBox('reverse label', True) if panel.show(): label = panel.value("label:") if panel.value("reverse label") == True: card['label'].setValue(panel.value("label:")) else: nuke.message('no label - no roto!') nuke.delete(bg) # clean the mess up return else: return print '########' print 'first', first print 'last', last print 'ref', ref #print 'bg', form print 'cam', cam.name() print 'card', card.name() print 'label', label print '########' # create master axis and corner slaves aM = nuke.nodes.Axis2(name='aM', xform_order=3, xpos=x, ypos=y + 50) uscale = card['uniform_scale'].value() scalex = card['scaling'].value(0) scaley = card['scaling'].value(1) if card['translate'].isAnimated() is True: aM['translate'].copyAnimations(card['translate'].animations()) else: aM['translate'].setValue(card['translate'].value()) if card['rotate'].isAnimated() is True: aM['rotate'].copyAnimations(card['rotate'].animations()) else: aM['rotate'].setValue(card['rotate'].value()) # slaves a1 = nuke.nodes.Axis2(name='a1', xform_order=1, xpos=x, ypos=y + 50) a2 = nuke.nodes.Axis2(name='a2', xform_order=1, xpos=x, ypos=y + 50) a3 = nuke.nodes.Axis2(name='a3', xform_order=1, xpos=x, ypos=y + 50) a4 = nuke.nodes.Axis2(name='a4', xform_order=1, xpos=x, ypos=y + 50) a1['translate'].setValue( [-0.5 * uscale * scalex, rootAspect * -0.5 * uscale * scaley, 0]) a2['translate'].setValue( [0.5 * uscale * scalex, rootAspect * -0.5 * uscale * scaley, 0]) a3['translate'].setValue( [0.5 * uscale * scalex, rootAspect * 0.5 * uscale * scaley, 0]) a4['translate'].setValue( [-0.5 * uscale * scalex, rootAspect * 0.5 * uscale * scaley, 0]) aL = [a1, a2, a3, a4] for a in aL: a.setInput(0, aM) # reconcile r1 = nuke.nodes.Reconcile3D(name='r1', xpos=x, ypos=y + 50) r2 = nuke.nodes.Reconcile3D(name='r2', xpos=x, ypos=y + 50) r3 = nuke.nodes.Reconcile3D(name='r3', xpos=x, ypos=y + 50) r4 = nuke.nodes.Reconcile3D(name='r4', xpos=x, ypos=y + 50) rL = [r1, r2, r3, r4] for r in rL: r.setInput(2, aL[rL.index(r)]) r.setInput(1, cam) r.setInput(0, bg) # run with threading global stop_event stop_event = threading.Event() threading.Thread(target=execRC, kwargs=dict(first=first, last=last)).start() while not stop_event.is_set(): time.sleep(0.1) # corner pin normal try: cp = nuke.nodes.CProject(xpos=x + 110, ypos=y) cp['camera'].setValue(cam.name()) cp['translate'].setValue(card['translate'].value()) cp['rotation'].setValue(card['rotate'].value()) cp['element'].setValue(label) cp['name'].setValue(cp['name'].value().replace('CProject', 'CP') + "_" + label) cp['refFrame'].setValue(str(ref)) except: cp = nuke.nodes.CornerPin2D(label=label + ' (' + str(ref) + ')', xpos=x + 110, ypos=y) cp['to1'].copyAnimations(r1['output'].animations()) cp['to2'].copyAnimations(r2['output'].animations()) cp['to3'].copyAnimations(r3['output'].animations()) cp['to4'].copyAnimations(r4['output'].animations()) cp['from1'].setValue(r1['output'].getValueAt(ref)) cp['from2'].setValue(r2['output'].getValueAt(ref)) cp['from3'].setValue(r3['output'].getValueAt(ref)) cp['from4'].setValue(r4['output'].getValueAt(ref)) # corner pin matrix & roto cpm = nuke.nodes.CornerPin2D(label=label + ' matrix (' + str(ref) + ')', xpos=x + 220, ypos=y) roto = nuke.nodes.Roto(xpos=x + 330, ypos=y) roto['name'].setValue(roto['name'].value().replace('Roto', 'R') + "_" + label) nuke.show(roto) roto_transform = roto['curves'].rootLayer.getTransform( ) # transform of root layer in roto cpm['transform_matrix'].setAnimated() projectionMatrixTo = nuke.math.Matrix4() projectionMatrixFrom = nuke.math.Matrix4() frame = first while frame < last + 1: to1x = cp['to1'].valueAt(frame)[0] to1y = cp['to1'].valueAt(frame)[1] to2x = cp['to2'].valueAt(frame)[0] to2y = cp['to2'].valueAt(frame)[1] to3x = cp['to3'].valueAt(frame)[0] to3y = cp['to3'].valueAt(frame)[1] to4x = cp['to4'].valueAt(frame)[0] to4y = cp['to4'].valueAt(frame)[1] from1x = cp['from1'].valueAt(frame)[0] from1y = cp['from1'].valueAt(frame)[1] from2x = cp['from2'].valueAt(frame)[0] from2y = cp['from2'].valueAt(frame)[1] from3x = cp['from3'].valueAt(frame)[0] from3y = cp['from3'].valueAt(frame)[1] from4x = cp['from4'].valueAt(frame)[0] from4y = cp['from4'].valueAt(frame)[1] projectionMatrixTo.mapUnitSquareToQuad(to1x, to1y, to2x, to2y, to3x, to3y, to4x, to4y) projectionMatrixFrom.mapUnitSquareToQuad(from1x, from1y, from2x, from2y, from3x, from3y, from4x, from4y) theCornerpinAsMatrix = projectionMatrixTo * projectionMatrixFrom.inverse( ) theCornerpinAsMatrix.transpose() for i in range(0, 16): cpm['transform_matrix'].setValueAt(theCornerpinAsMatrix[i], frame, i) for i in range(0, 16): roto_transform.getExtraMatrixAnimCurve(0, i).addKey( frame, cpm['transform_matrix'].getValueAt(frame, i)) frame = frame + 1 roto['curves'].changed() # check for turnover k = cp['to1'] vals = [] valSort = [] for i in range(first, last + 1): vals.append(k.valueAt(i, 0)) valSort.append(k.valueAt(i, 0)) valSort.sort() min = valSort[0] max = valSort[-1] warning = '' if math.fabs(vals.index(max) - vals.index(min)) == 1: warning = 'Warning: perspective problem detected' #clean up rmL = [r1, r2, r3, r4, a1, a2, a3, a4, aM] for i in rmL: nuke.delete(i) nuke.delete(bg) if dialog == False: roto.setXYpos(x + 100, y) #remove all non roto nodes nuke.delete(cp) nuke.delete(cpm) # show warning if any if warning != '': nuke.message(warning) print 'C2T done.'
def freezeWarp_v2(): try: node = nuke.selectedNode() if node.Class() not in ('SplineWarp3'): if nuke.GUI: nuke.message( 'Unsupported node type. Node must be SplineWarp' ) return except: if nuke.GUI: nuke.message('Select a SplineWarp Node') return shapeList = [] curves = node['curves'] nodeRoot = curves.rootLayer shapeList = fws_walker(nodeRoot, shapeList) #=========================================================================== # panel setup #=========================================================================== p = nukescripts.panels.PythonPanel("Freeze Splinewarp") k = nuke.Int_Knob("freezeframe","Freezeframe") k.setFlag(nuke.STARTLINE) k.setTooltip("Set the frame to freeze the shapes positions") p.addKnob(k) k.setValue(nuke.root().firstFrame()) k = nuke.Enumeration_Knob( 'outputcurve', 'Curves to Freeze', ['A', 'B']) k.setFlag(nuke.STARTLINE) k.setTooltip("Freeze all the curves on the A or B output") p.addKnob(k) k = nuke.Boolean_Knob("mt", "MultiThread") k.setFlag(nuke.STARTLINE) k.setTooltip("This will speed up the script but without an accurate progress bar") p.addKnob(k) k.setValue(True) k = nuke.Boolean_Knob("exp", "Use Expression to Freeze") k.setFlag(nuke.STARTLINE) k.setTooltip("Instead of deleting keyframes, it will use expressions on the shapes and also add a frame control on the node") p.addKnob(k) k.setValue(True) k = nuke.Boolean_Knob("fh", "Create FrameHold") k.setFlag(nuke.STARTLINE) k.setTooltip("This will create a Framehold Node and set it to the Freezeframe value, if you use expressions mode it will be linked") p.addKnob(k) k.setValue(True) k = nuke.Boolean_Knob("stb", "Stabilize Setup") k.setFlag(nuke.STARTLINE) k.setTooltip("This will create a handy warp stabilization setup") p.addKnob(k) k.setValue(False) if not checkAB(shapeList): p.addKnob( nuke.Text_Knob("","",'\n<b><font color="red">WARNING: your node has only<br>curves on A or B outputs</font></b>\n')) #=========================================================================== # end of panel setup #=========================================================================== result = p.showModalDialog() if result == 0: return # Canceled freezeFrame = p.knobs()["freezeframe"].value() ab = 1.0 if p.knobs()["outputcurve"].value() == "A" else 2.0 exp = p.knobs()["exp"].value() mt = p.knobs()["mt"].value() if nuke.NUKE_VERSION_MAJOR > 6: #======================================================================= # task setup #======================================================================= global cancel cancel = False task = nuke.ProgressTask( 'Freeze SplineWarp' ) n = 0 #======================================================================= # task end #======================================================================= if exp: names = [] for i in node.allKnobs(): names.append(i.name()) if "FreezeFrame" not in names: #avoid creating the pane if it already exists tab = nuke.Tab_Knob('FreezeFrame') node.addKnob(tab) ff = nuke.Int_Knob('fframe',"Freeze Frame") node.addKnob(ff) try: ff.setValue(freezeFrame) except: pass for shape in shapeList: if cancel: return task.setMessage('Processing ' + shape.name) task.setProgress((int(n/len(shapeList)*100))) if mt and nuke.NUKE_VERSION_MAJOR != 11: threading.Thread(None,expressionLock, args=(shape,ab,freezeFrame,node,task)).start() else: expressionLock(shape,ab,freezeFrame,node,task) n+=1 else: for shape in shapeList: if cancel: return task.setMessage('Processing ' + shape.name) task.setProgress((int(n/len(shapeList)*100))) if mt: threading.Thread(None,keyFreeze, args=(shape,ab,freezeFrame,task)).start() else: keyFreeze(shape,ab,freezeFrame,task) n+=1 #=========================================================================== # join existing threads (to wait completion before continue) #=========================================================================== if mt and nuke.NUKE_VERSION_MAJOR != 11: main_thread = threading.currentThread() for t in threading.enumerate(): if t is main_thread: continue t.join() curves.changed() else: nuke.message( 'This version is for Nuke v7, use v1.1 with Nuke v6.3 from Nukepedia' ) #=========================================================================== # framehold creation #=========================================================================== fh = p.knobs()["fh"].value() if fh: framehold = nuke.nodes.FrameHold() if exp: framehold["first_frame"].setExpression(node.name() + ".fframe") else: framehold.knob("first_frame").setValue(freezeFrame) #======================================================================= # some layout beautyfication #======================================================================= framehold["xpos"].setValue(node["xpos"].getValue() - 100) framehold["ypos"].setValue(node["ypos"].getValue() - 80) dot = nuke.nodes.Dot() dot["xpos"].setValue(node["xpos"].getValue()+35) dot["ypos"].setValue(framehold["ypos"].getValue()+11) set_inputs(node,dot) set_inputs(dot,framehold) #======================================================================= # stabilization setup #======================================================================= stb = p.knobs()["stb"].value() if stb: nukescripts.node_copypaste() b_input = nuke.selectedNode() nukescripts.node_copypaste() a_input = nuke.selectedNode() b_input["mix"].setValue(1) dot = nuke.nodes.Dot() dot["label"].setValue("Stabilization") set_inputs(a_input,b_input) set_inputs(b_input,dot) nukescripts.swapAB(b_input) dot["xpos"].setValue(node["xpos"].getValue()+135) dot["ypos"].setValue(framehold["ypos"].getValue()+11) b_input["xpos"].setValue(node["xpos"].getValue()+135) b_input["ypos"].setValue(dot["ypos"].getValue()+80) a_input["xpos"].setValue(node["xpos"].getValue()+135) a_input["ypos"].setValue(dot["ypos"].getValue()+160) #======================================================================= # workaround.... if node is not show on properties tab the "root warp" attribute will not change! #======================================================================= b_input.knob('selected').setValue(True) nuke.show(nuke.selectedNode()) nuke.selectedNode()["root_warp"].setValue(0) label = "FreezeF: [value fframe]" if exp else "FreezeF:" + str(freezeFrame) node.knob('label').setValue(label) node.knob('filter').setValue('Mitchell') #less smoother than cubic print "FreezeSplineWarp Finished,", len(shapeList), "shape(s) at frame", freezeFrame
"\n if source is not None and 'translate' in source.knobs().keys() and target is not None and 'translate' in target.knobs().keys():" "\n distance = math.sqrt(((source['translate'].getValue()[0] - target['translate'].getValue()[0])**2)+((source['translate'].getValue()[1] - target['translate'].getValue()[1])**2)+((source['translate'].getValue()[2] - target['translate'].getValue()[2])**2))" "\n knob.setValue('<font color =lime>'+str(round(distance,3)).zfill(10))" "\n else:" "\n knob.setValue('000000.000')" "\nret=0}]") sticky_note.addKnob(format2_knob) format2_knob.setFlag(0x00000400) format3_knob = nuke.Int_Knob('format3', '') format3_knob.setExpression("[python -execlocal {for knob in nuke.thisNode().allKnobs():" "\n if 'source_row_' in knob.name() and nuke.toNode(knob.value()) is not None:" "\n if 'translate' not in nuke.toNode(knob.value()).knobs().keys():" "\n knob.setValue('')" "\n if 'target_row_' in knob.name() and nuke.toNode(knob.value()) is not None:" "\n if 'translate' not in nuke.toNode(knob.value()).knobs().keys():" "\n knob.setValue('')" "\nret=0}]") sticky_note.addKnob(format3_knob) format3_knob.setFlag(0x00000400) # -------------------------------- FRAMING -------------------------------- # sticky_note.setSelected(True) nuke.show(sticky_note) nuke.zoomToFitSelected() for n in nuke.allNodes(): n.setSelected(False)
def createNukeCornerPinNode(coordinatesArray): global frameHeight global frameOffset cornerPinNode = nuke.nodes.CornerPin2D(label='imported_Mocha-AE_Track') cornerPinNode['enable1'].setValue('true') cornerPinNode['enable2'].setValue('true') cornerPinNode['enable3'].setValue('true') cornerPinNode['enable4'].setValue('true') # LOWER LEFT track1 = cornerPinNode['to1'] track1.setAnimated() track1keysX = [] track1keysY = [] for j in coordinatesArray[0]: tFrame = int(j[0]) + frameOffset tX = float(j[1]) tY = frameHeight - float(j[2]) track1keysX.append( (tFrame,tX) ) track1keysY.append( (tFrame,tY) ) #print "track1keysX: %s" % len(track1keysX) #print "track1keysY: %s" % len(track1keysY) # LOWER RIGHT track2 = cornerPinNode['to2'] track2.setAnimated() track2keysX = [] track2keysY = [] for j in coordinatesArray[1]: tFrame = int(j[0]) + frameOffset tX = float(j[1]) tY = frameHeight - float(j[2]) track2keysX.append( (tFrame,tX) ) track2keysY.append( (tFrame,tY) ) #print "track2keysX: %s" % len(track1keysX) #print "track2keysY: %s" % len(track1keysY) # UPPER RIGHT track3 = cornerPinNode['to3'] track3.setAnimated() track3keysX = [] track3keysY = [] for j in coordinatesArray[3]: tFrame = int(j[0]) + frameOffset tX = float(j[1]) tY = frameHeight - float(j[2]) track3keysX.append( (tFrame,tX) ) track3keysY.append( (tFrame,tY) ) #print "track3keysX: %s" % len(track3keysX) #print "track3keysY: %s" % len(track3keysY) # UPPER LEFT track4 = cornerPinNode['to4'] track4.setAnimated() track4keysX = [] track4keysY = [] for j in coordinatesArray[2]: tFrame = int(j[0]) + frameOffset tX = float(j[1]) tY = frameHeight - float(j[2]) track4keysX.append( (tFrame,tX) ) track4keysY.append( (tFrame,tY) ) #print "track4keysX: %s" % len(track4keysX) #print "track4keysY: %s" % len(track4keysY) track1animX = track1.animation(0) track1animX.addKey([nuke.AnimationKey(frame, value) for (frame,value) in track1keysX]) track1animY = track1.animation(1) track1animY.addKey([nuke.AnimationKey(frame, value) for (frame,value) in track1keysY]) track2animX = track2.animation(0) track2animX.addKey([nuke.AnimationKey(frame, value) for (frame,value) in track2keysX]) track2animY = track2.animation(1) track2animY.addKey([nuke.AnimationKey(frame, value) for (frame,value) in track2keysY]) track3animX = track3.animation(0) track3animX.addKey([nuke.AnimationKey(frame, value) for (frame,value) in track3keysX]) track3animY = track3.animation(1) track3animY.addKey([nuke.AnimationKey(frame, value) for (frame,value) in track3keysY]) track4animX = track4.animation(0) track4animX.addKey([nuke.AnimationKey(frame, value) for (frame,value) in track4keysX]) track4animY = track4.animation(1) track4animY.addKey([nuke.AnimationKey(frame, value) for (frame,value) in track4keysY]) nuke.show(cornerPinNode) nuke.zoom(1, (cornerPinNode.xpos(), cornerPinNode.ypos() ) ) return
def main(): for grp in nuke.allNodes('Group'): if 'addAssetGizmos' in grp.knobs(): with grp: d = nuke.toNode('ml_AtmosControl') nuke.show(d, 1)
def Roto_to_WarpSpline_v2(): try: rotoNode = nuke.selectedNode() if rotoNode.Class() not in ('Roto', 'RotoPaint'): if nuke.GUI: nuke.message( 'Unsupported node type. Selected Node must be Roto or RotoPaint' ) return except: if nuke.GUI: nuke.message('Select a Roto or RotoPaint Node') return #=========================================================================== # panel setup #=========================================================================== p = nukescripts.panels.PythonPanel("RotoPaint to Splinewarp") k = nuke.String_Knob("framerange","FrameRange") k.setFlag(nuke.STARTLINE) k.setTooltip("Set the framerange to bake the shapes, by default its the project start-end. Example: 10-20") p.addKnob(k) k.setValue("%s-%s" % (nuke.root().firstFrame(), nuke.root().lastFrame())) k = nuke.Boolean_Knob("pin", "Break into Pin Points") k.setFlag(nuke.STARTLINE) k.setTooltip("This will break all the shapes into single points") p.addKnob(k) k = nuke.Boolean_Knob("mt", "MultiThread") k.setFlag(nuke.STARTLINE) k.setTooltip("This will speed up the script but without an accurate progress bar") p.addKnob(k) k.setValue(True) result = p.showModalDialog() if result == 0: return # Canceled try: fRange = nuke.FrameRange(p.knobs()["framerange"].getText()) except: if nuke.GUI: nuke.message( 'Framerange format is not correct, use startframe-endframe i.e.: 0-200' ) return breakintopin = p.knobs()["pin"].value() multi = p.knobs()["mt"].value() #=========================================================================== # end of panel #=========================================================================== start_time = time.time() # task = nuke.ProgressTask('Roto to SplineWarp') rptsw_shapeList = [] global cancel cancel = False if nuke.NUKE_VERSION_MAJOR > 6: # global cancel rptsw_shapeList = [] nukescripts.node_copypaste() rotoNode = nuke.selectedNode() warpNode = nuke.createNode('SplineWarp3') warpNode.setName(rotoNode.name()+ "_" + warpNode.name()) warpCurve = warpNode['curves'] warpRoot = warpCurve.rootLayer rotoCurve = rotoNode['curves'] rotoRoot = rotoCurve.rootLayer rptsw_shapeList = rptsw_walker(rotoRoot, rptsw_shapeList) if breakintopin: breakshapesintoPin(rotoNode,fRange) rptsw_shapeList = [] rptsw_shapeList = rptsw_walker(rotoRoot, rptsw_shapeList) if cancel: return threadlist =[] n=0 task = nuke.ProgressTask( 'Roto to SplineWarp' ) bar = len(rptsw_shapeList) + 1 for shape in rptsw_shapeList: if isinstance(shape[0], nuke.rotopaint.Shape): if multi and nuke.NUKE_VERSION_MAJOR != 11: task.setMessage( 'Processing' + shape[0].name ) task.setProgress((int(n/bar*100))) threading.Thread(None, bakeShapes, args=(shape, warpNode, fRange, rotoRoot, rptsw_shapeList, task)).start() else: bakeShapes(shape, warpNode,fRange, rotoRoot, rptsw_shapeList,task) n+=1 #=========================================================================== # join existing threads (to wait completion before continue) #=========================================================================== if multi and nuke.NUKE_VERSION_MAJOR != 11: main_thread = threading.currentThread() for t in threading.enumerate(): if t is main_thread: continue t.join() warpCurve.changed() warpNode.knob('toolbar_output_ab').setValue(1) warpNode.knob('boundary_bbox').setValue(0) #======================================================================= # theres a bug on Nuke 8 where the splinewarpnode UI do not update correctly with python created curves # this is a workaround #======================================================================= nukescripts.node_copypaste() nuke.show(nuke.selectedNode()) nuke.selectedNode().knob('selected').setValue(False) #======================================================================= # end of workaround - #======================================================================= rptsw_shapeList = [] nuke.delete(rotoNode) nuke.delete(warpNode) else: nuke.message( 'This version is for Nuke v7, use v1.1 with Nuke v6.3 from Nukepedia' ) rptsw_shapeList = [] if cancel: nuke.undo() print "Time elapsed:",time.time() - start_time, "seconds"
def CreateOnSelection(_kind): #If the viewer is connected to a node we will use input 0 for ref. Else we just use the viewer itself. if nuke.activeViewer().node().input(0): myNode = nuke.activeViewer().node().input(0) if not nuke.selectedNodes( ): #Trying to be smart by assuming that you don't want to add a node to nothing. myNode.setSelected(1) else: myNode = nuke.activeViewer().node() bboxinfo = nuke.activeViewer().node()['colour_sample_bbox'].value( ) #Get the position info from the colour sample bbox aspect = float(myNode.width() * myNode.pixelAspect()) / float( myNode.height() ) #Calcualte the aspect (thanks Tom van Dop for notifying and Jelmen Palsterman for the correction!) cornerA = [ (bboxinfo[0] * 0.5 + 0.5) * myNode.width(), (((bboxinfo[1] * 0.5) + (0.5 / aspect)) * aspect) * myNode.height() ] #Get the button left corner cornerB = [ (bboxinfo[2] * 0.5 + 0.5) * myNode.width(), (((bboxinfo[3] * 0.5) + (0.5 / aspect)) * aspect) * myNode.height() ] #Get the top right corner area_WH = [cornerB[0] - cornerA[0], cornerB[1] - cornerA[1]] #Get the width and height of the bbox area_Mid = [cornerA[0] + (area_WH[0] / 2), cornerA[1] + (area_WH[1] / 2)] #Get the center of the bbox if _kind == 'Crop': #-----Crop Node----- newNode = nuke.Node("Crop") newNode['box'].setValue( [cornerA[0], cornerA[1], cornerB[0], cornerB[1]]) elif _kind == 'ROI': #-----ROI----- nuke.activeViewer().node()["roi"].setValue(bboxinfo) elif _kind == 'Transform': #-----Tranform Node----- newNode = nuke.Node("Transform") newNode['center'].setValue([area_Mid[0], area_Mid[1]]) elif _kind == 'GridWarp': #-----GridWarp Node----- newNode = nuke.Node("GridWarp3") gridwarpLayout = gridWarpBaseStruct for x in range( 0, 5 ): #Remap placeholder values to x and y coordinates split up to 5 subdevisions gridwarpLayout = gridwarpLayout.replace( "_x%s" % x, "%.0f" % (cornerA[0] + ((area_WH[0] / 4) * x))) gridwarpLayout = gridwarpLayout.replace( "_y%s" % x, "%.0f" % (cornerA[1] + ((area_WH[1] / 4) * x))) gridwarpLayout = gridwarpLayout.replace( "_tx0", "%.3f" % (area_WH[0] / 12)) #Remap tangent's gridwarpLayout = gridwarpLayout.replace( "_ty0", "%.3f" % (area_WH[1] / 12)) #Remap tangent's newNode['source_grid_col'].fromScript(gridwarpLayout) #Set Source Grid newNode['destination_grid_col'].fromScript( gridwarpLayout) #Set Destination Grid if _kind == 'Text': newNode = nuke.Node("Text2") newNode['box'].setValue( [cornerA[0], cornerA[1], cornerB[0], cornerB[1]]) elif _kind == 'Radial': newNode = nuke.Node("Radial") newNode['area'].setValue( [cornerA[0], cornerA[1], cornerB[0], cornerB[1]]) elif _kind == 'Keylight': newNode = nuke.Node("OFXuk.co.thefoundry.keylight.keylight_v201") ColorR = myNode.sample(1, area_Mid[0], area_Mid[1], area_WH[0], area_WH[1]) ColorG = myNode.sample(2, area_Mid[0], area_Mid[1], area_WH[0], area_WH[1]) ColorB = myNode.sample(3, area_Mid[0], area_Mid[1], area_WH[0], area_WH[1]) newNode['screenColour'].setValue([ColorR, ColorG, ColorB]) elif _kind == 'Tracker': #If we allready have a tracker selexted then append tracks to exsisting tracker node. if myNode.Class() == "Tracker4": newNode = myNode nuke.show(newNode) else: #Creat a new tracker node newNode = nuke.Node("Tracker4") numColumns = 31 colTrackX = 2 colTrackY = 3 colRelTrack = 12 trackIdx = int(newNode["tracks"].toScript().split(" ")[3]) newNode['add_track'].execute() newNode.knob("tracks").setValue(area_Mid[0], numColumns * trackIdx + colTrackX) newNode.knob("tracks").setValue(area_Mid[1], numColumns * trackIdx + colTrackY) newNode.knob("tracks").setValue(-area_WH[0] / 2, numColumns * trackIdx + colRelTrack) newNode.knob("tracks").setValue( -area_WH[1] / 2, numColumns * trackIdx + colRelTrack + 1) newNode.knob("tracks").setValue( area_WH[0] / 2, numColumns * trackIdx + colRelTrack + 2) newNode.knob("tracks").setValue( area_WH[1] / 2, numColumns * trackIdx + colRelTrack + 3) elif _kind == 'CornerpinFrom': newNode = nuke.Node("CornerPin2D") newNode['from1'].setValue([cornerA[0], cornerA[1]]) newNode['from2'].setValue([cornerB[0], cornerA[1]]) newNode['from3'].setValue([cornerB[0], cornerB[1]]) newNode['from4'].setValue([cornerA[0], cornerB[1]]) elif _kind == 'CornerpinTo': newNode = nuke.Node("CornerPin2D") newNode['to1'].setValue([cornerA[0], cornerA[1]]) newNode['to2'].setValue([cornerB[0], cornerA[1]]) newNode['to3'].setValue([cornerB[0], cornerB[1]]) newNode['to4'].setValue([cornerA[0], cornerB[1]]) elif _kind == 'CornerpinFromTo': newNode = nuke.Node("CornerPin2D") newNode['to1'].setValue([cornerA[0], cornerA[1]]) newNode['to2'].setValue([cornerB[0], cornerA[1]]) newNode['to3'].setValue([cornerB[0], cornerB[1]]) newNode['to4'].setValue([cornerA[0], cornerB[1]]) newNode['from1'].setValue([cornerA[0], cornerA[1]]) newNode['from2'].setValue([cornerB[0], cornerA[1]]) newNode['from3'].setValue([cornerB[0], cornerB[1]]) newNode['from4'].setValue([cornerA[0], cornerB[1]]) elif _kind == 'Constant': newNode = nuke.Node("Constant", inpanel=False) ColorR = myNode.sample(1, area_Mid[0], area_Mid[1], area_WH[0], area_WH[1]) ColorG = myNode.sample(2, area_Mid[0], area_Mid[1], area_WH[0], area_WH[1]) ColorB = myNode.sample(3, area_Mid[0], area_Mid[1], area_WH[0], area_WH[1]) newNode['color'].setValue([ColorR, ColorG, ColorB, 1])
def animatedCP2MTX(): try: input = nuke.selectedNode() #---------------------------------------------------------------------------------------------------------- if input.Class() == 'CornerPin2D': node_in = input.input(0) cp = nuke.nodes.CornerPin2D( name = 'CornerPin_to_Matrix') xpos = input['xpos'].value() ypos = input['ypos'].value() cp_width = cp.screenWidth() cp_height = cp.screenHeight() cp.setXYpos(int(xpos) + int(cp_width) + 25 , int(ypos)) cp.knob('extra matrix').setValue(True) cp.setInput(0, node_in) nuke.show(cp) cp_em = cp.knob('transform_matrix') #--------------------------------------------------------------------------------------- # conversion cp_to_mtx def getAnimatedCPasMTX(cornerpin, iterator): i = iterator cp = cornerpin pmTo = nuke.math.Matrix4() pmFrom = nuke.math.Matrix4() imageWidth = float(cp.width()) imageHeight = float(cp.height()) to1x = cp['to1'].getValueAt(i)[0] to1y = cp['to1'].getValueAt(i)[1] to2x = cp['to2'].getValueAt(i)[0] to2y = cp['to2'].getValueAt(i)[1] to3x = cp['to3'].getValueAt(i)[0] to3y = cp['to3'].getValueAt(i)[1] to4x = cp['to4'].getValueAt(i)[0] to4y = cp['to4'].getValueAt(i)[1] from1x = cp['from1'].getValueAt(i)[0] from1y = cp['from1'].getValueAt(i)[1] from2x = cp['from2'].getValueAt(i)[0] from2y = cp['from2'].getValueAt(i)[1] from3x = cp['from3'].getValueAt(i)[0] from3y = cp['from3'].getValueAt(i)[1] from4x = cp['from4'].getValueAt(i)[0] from4y = cp['from4'].getValueAt(i)[1] pmTo.mapUnitSquareToQuad(to1x,to1y,to2x,to2y,to3x,to3y,to4x,to4y) pmFrom.mapUnitSquareToQuad(from1x,from1y,from2x,from2y,from3x,from3y,from4x,from4y) mtx = pmTo*pmFrom.inverse() mtx.transpose() return mtx #--------------------------------------------------------------------------------------- #--------------------------------''' Define Frame Range'''--------------------------------- frames = nuke.getFramesAndViews('get FrameRange', '%s-%s' % (nuke.root().firstFrame(), nuke.root().lastFrame())) frame_range = nuke.FrameRange( frames[0] ) #--------------------------------------------------------------------------------------- for i in frame_range: mtx = getAnimatedCPasMTX(input, i) #------------------------------------------------------------------------------ #apply values cp_em.setAnimated() for j in range(16): cp_em.setValueAt(mtx[j], i, j ) #----------------------------------------------------------------------------------------------- else: nuke.message('please select a CornerPin node') except: nuke.message('please select a CornerPin node')
def listbookmarks(): bm = [] zoomBy = 1 #find bookmark nodes for n in nuke.allNodes(): n['selected'].setValue(False) if n['icon'].value() == 'bookmark.png': n['selected'].setValue(True) #select nodes for clarity bmLabel = nuke.selectedNode()['label'].value() if bmLabel: bm_name = '"' + bmLabel + '"' # '"'<-lets it list correctly else: bm_name = '"' + n.name( ) + '"' # '"'<-allows it to be sorted correctly with above bm.append(bm_name) if 0 == len(bm): nuke.message('no bookmarks found') else: bookmarkList = str(sorted(bm)) #clean up list name pattern = re.compile('[\[\]\']') bookmarkList = pattern.sub('', bookmarkList) pattern = re.compile('[\,]') bookmarkList = pattern.sub(' ', bookmarkList) #let user choose bookmark panel = nuke.Panel('BookMarks', 200) panel.addEnumerationPulldown('go to', bookmarkList) panel.addSingleLineInput('zoom', zoomBy) panel.addBooleanCheckBox('also open node', False) panel.addButton("Cancel") panel.addButton("Zoom to") panel.addButton("Open") result = panel.show() if result: goto = panel.value('go to') zoomf = panel.value('zoom') alwaysOpen = panel.value('also open node') #select only relevent node for n in nuke.allNodes(): if goto == n.name() or goto == n['label'].value(): n['selected'].setValue(True) else: n['selected'].setValue(False) #set nuke to highlight chosen node, get xy pos and zoom into area and open if selected. if result == 1: nuke.zoom( float(zoomf), (nuke.selectedNode().xpos(), nuke.selectedNode().ypos())) if alwaysOpen: nuke.show(nuke.selectedNode()) elif result == 2: nuke.show(nuke.selectedNode()) else: pass
def ColorCode(): '''main function''' # Symbols and Color blk = '█' hex_group = { 'CG': ['CCC0C0', '5C3737', '7D5F5F'], 'Key/Roto': ['C2CCC0', '3E5C37', '657d5f'], 'Precomp': ['CAC0CC', '55375C', '775f7d'], 'EndComp': ['CCCCCC', '5C5C5C', '7D7D7D'], 'LensFX': ['C2C0CC', '3E375C', '655f7d'], 'Transform': ['CCC7C0', '5C4625', '7D6B51'], 'Despill': ['C0CCC5', '2E5C40', '587d66'], 'Grade': ['C0CCCC', '2E5C5C', '587d7d'], 'Elem2D': ['CACCC0', '535C2E', '757d58'], 'Plate': ['BFC5CC', '2E405C', '58667d'], '*Random': [] } # Main Function sel_class = [] exclude_class = ['Dot', 'Merge2'] for c in nuke.selectedNodes(): if c.Class() not in exclude_class: sel_class.append(c.Class()) try: most_class = max(set(sel_class), key=sel_class.count) except: most_class = 'NewBackdrop' bd = ku_autoBackdrop() if bd: p = nuke.Panel('ColorCode It') p.addEnumerationPulldown('Type: ', ' '.join(sorted(hex_group.keys()))) p.addSingleLineInput('Label: ', most_class) p.addEnumerationPulldown('Font Size: ', 'h3 h2 h1') p.addBooleanCheckBox('center', False) if p.show(): bd_type = p.value('Type: ') bd_label = p.value('Label: ') bd_font = p.value('Font Size: ') bd_center = p.value('center') dir_font = {'h1': 200, 'h2': 96, 'h1': 48} colorButtons(bd, hex_group, blk) # Execute a button on default if bd_type == '*Random': import random, math rand_h = random.randrange(0, 360, 10) rand_r, rand_g, rand_b = hsv2rgb(rand_h, .25, .36) bd.knob('tile_color').setValue( nukeColor(rand_r, rand_g, rand_b)) bd.knob('note_font_size').setValue(dir_font[bd_font]) bd.knob('note_font_color').setValue( nukeColor(int(rand_r * 2), int(rand_g * 2), int(rand_b * 2))) setLabel = "<center>%s" % bd_label if bd_center == True else bd_label bd.knob('label').setValue(setLabel) else: bd.knob('bt_%s' % bd_type).execute() setLabel = "<center>%s" % bd_label if bd_center == True else bd_label bd.knob('label').setValue(setLabel) nuke.show(bd) else: nuke.delete(bd) print "Operation Cancelled"
def show_node_property(node_name): nuke.show(nuke.toNode(node_name))
def wiredShowAnchor(): n = nuke.thisNode() if n.inputs(): nuke.show(n.input(0))
def createNukeCornerPinNode(coordinatesArray): global frameHeight global frameOffset cornerPinNode = nuke.nodes.CornerPin2D(label='imported_Mocha-AE_Track') cornerPinNode['enable1'].setValue('true') cornerPinNode['enable2'].setValue('true') cornerPinNode['enable3'].setValue('true') cornerPinNode['enable4'].setValue('true') # LOWER LEFT track1 = cornerPinNode['to1'] track1.setAnimated() track1keysX = [] track1keysY = [] for j in coordinatesArray[0]: tFrame = int(j[0]) + frameOffset tX = float(j[1]) tY = frameHeight - float(j[2]) track1keysX.append((tFrame, tX)) track1keysY.append((tFrame, tY)) #print "track1keysX: %s" % len(track1keysX) #print "track1keysY: %s" % len(track1keysY) # LOWER RIGHT track2 = cornerPinNode['to2'] track2.setAnimated() track2keysX = [] track2keysY = [] for j in coordinatesArray[1]: tFrame = int(j[0]) + frameOffset tX = float(j[1]) tY = frameHeight - float(j[2]) track2keysX.append((tFrame, tX)) track2keysY.append((tFrame, tY)) #print "track2keysX: %s" % len(track1keysX) #print "track2keysY: %s" % len(track1keysY) # UPPER RIGHT track3 = cornerPinNode['to3'] track3.setAnimated() track3keysX = [] track3keysY = [] for j in coordinatesArray[3]: tFrame = int(j[0]) + frameOffset tX = float(j[1]) tY = frameHeight - float(j[2]) track3keysX.append((tFrame, tX)) track3keysY.append((tFrame, tY)) #print "track3keysX: %s" % len(track3keysX) #print "track3keysY: %s" % len(track3keysY) # UPPER LEFT track4 = cornerPinNode['to4'] track4.setAnimated() track4keysX = [] track4keysY = [] for j in coordinatesArray[2]: tFrame = int(j[0]) + frameOffset tX = float(j[1]) tY = frameHeight - float(j[2]) track4keysX.append((tFrame, tX)) track4keysY.append((tFrame, tY)) #print "track4keysX: %s" % len(track4keysX) #print "track4keysY: %s" % len(track4keysY) track1animX = track1.animation(0) track1animX.addKey( [nuke.AnimationKey(frame, value) for (frame, value) in track1keysX]) track1animY = track1.animation(1) track1animY.addKey( [nuke.AnimationKey(frame, value) for (frame, value) in track1keysY]) track2animX = track2.animation(0) track2animX.addKey( [nuke.AnimationKey(frame, value) for (frame, value) in track2keysX]) track2animY = track2.animation(1) track2animY.addKey( [nuke.AnimationKey(frame, value) for (frame, value) in track2keysY]) track3animX = track3.animation(0) track3animX.addKey( [nuke.AnimationKey(frame, value) for (frame, value) in track3keysX]) track3animY = track3.animation(1) track3animY.addKey( [nuke.AnimationKey(frame, value) for (frame, value) in track3keysY]) track4animX = track4.animation(0) track4animX.addKey( [nuke.AnimationKey(frame, value) for (frame, value) in track4keysX]) track4animY = track4.animation(1) track4animY.addKey( [nuke.AnimationKey(frame, value) for (frame, value) in track4keysY]) nuke.show(cornerPinNode) nuke.zoom(1, (cornerPinNode.xpos(), cornerPinNode.ypos())) return
def C2T(dialog): #card card = None for n in nuke.selectedNodes(): if "Card" in n.Class() or "Axis" in n.Class(): card = n break if card == None: nuke.message('no card selected?') return # initialize tool values for auto-creation label = card['label'].value() ref = int(nuke.frame()) first = first_frame_v last = last_frame_v bg = BGdetect() cam = getCamera() rootAspect = nuke.Root()['format'].value().pixelAspect() x = card.xpos() y = card.ypos() bg.setXYpos(x,y+50) if dialog == True: #panel panel = nuke.Panel("C2T") panel.addSingleLineInput("label:", card['label'].value()) panel.addSingleLineInput("firstFrame:", str(first)) panel.addSingleLineInput("lastFrame:", str(last)) panel.addSingleLineInput("ref frame:", str(ref)) if panel.show(): first = int(panel.value("firstFrame:")) last = int(panel.value("lastFrame:")) ref = int(panel.value("ref frame:")) if ref>last or ref<first: ref = first label = panel.value("label:") else: nuke.message('canceled') nuke.delete(bg) # clean the mess up return else: print ('no dialog, use auto-created input values') # create master axis and corner slaves aM = nuke.nodes.Axis2(name = 'aM', xform_order = 3, xpos = x, ypos = y+50) uscale = card['uniform_scale'].value() scalex = card['scaling'].value(0) scaley = card['scaling'].value(1) if card['translate'].isAnimated() is True: aM['translate'].copyAnimations(card['translate'].animations()) else: aM['translate'].setValue(card['translate'].value()) if card['rotate'].isAnimated() is True: aM['rotate'].copyAnimations(card['rotate'].animations()) else: aM['rotate'].setValue(card['rotate'].value()) # slaves a1 = nuke.nodes.Axis2(name = 'a1', xform_order = 1, xpos = x, ypos = y+50) a2 = nuke.nodes.Axis2(name = 'a2', xform_order = 1, xpos = x, ypos = y+50) a3 = nuke.nodes.Axis2(name = 'a3', xform_order = 1, xpos = x, ypos = y+50) a4 = nuke.nodes.Axis2(name = 'a4', xform_order = 1, xpos = x, ypos = y+50) a1['translate'].setValue([-0.5*uscale*scalex,rootAspect*-0.5*uscale*scaley,0]) a2['translate'].setValue([0.5*uscale*scalex,rootAspect*-0.5*uscale*scaley,0]) a3['translate'].setValue([0.5*uscale*scalex,rootAspect*0.5*uscale*scaley,0]) a4['translate'].setValue([-0.5*uscale*scalex,rootAspect*0.5*uscale*scaley,0]) aL = [a1,a2,a3,a4] for a in aL: a.setInput(0,aM) # reconcile r1 = nuke.nodes.Reconcile3D(name = 'r1', xpos = x, ypos = y+50) r2 = nuke.nodes.Reconcile3D(name = 'r2', xpos = x, ypos = y+50) r3 = nuke.nodes.Reconcile3D(name = 'r3', xpos = x, ypos = y+50) r4 = nuke.nodes.Reconcile3D(name = 'r4', xpos = x, ypos = y+50) rL = [r1,r2,r3,r4] for r in rL: r.setInput(2,aL[rL.index(r)]) r.setInput(1,cam) r.setInput(0,bg) # run with threading global stop_event stop_event = threading.Event() threading.Thread(target=execRC, kwargs=dict(first=first,last=last)).start() while not stop_event.is_set(): time.sleep(0.1) problem = 0 import math timeline = ["beginning","end"]#######looping to fix stuff before and after ref frame for side in timeline:##########################################################################################################: Fixing the curve############################### if side == "beginning": firstT = first lastT = ref if side == "end": firstT = ref lastT = last for one in rL:########fixing stuff curveXUp = 0 curveXDown = 0 curveYUp = 0 curveYDown = 0 fuckedFrames = [] k = one["output"] valsx = [];valSortx =[] valsy = [];valSorty =[] for i in range(firstT,lastT+1): valsx.append(k.valueAt(i,0)) valSortx.append(k.valueAt(i,0)) valsy.append(k.valueAt(i,1)) valSorty.append(k.valueAt(i,1)) valSortx.sort() valSorty.sort() minX = valSortx[0] maxX = valSortx[-1] minY = valSorty[0] maxY = valSorty[-1] if math.fabs(valsx.index(maxX)-valsx.index(minX)) == 1: problem = 1 if problem == 1: if nuke.ask("Perspective problem detected! would you like to fix it? \n your card did pass the Camera center, this causes the track to break, i will try to fix the problem. if my fix will not succeed you should use a bit smaller card so corners of the card will not cross the camera so fast."): problem = 0 import math timeline = ["beginning","end"]#######looping to fix stuff before and after ref frame lastB = last firstB = first for side in timeline:##########################################################################################################: Fixing the curve############################### if side == "beginning": last = ref if side == "end": first = ref last = lastB for one in rL:########fixing stuff curveXUp = 0 curveXDown = 0 curveYUp = 0 curveYDown = 0 fuckedFrames = [] k = one["output"] valsx = [];valSortx =[] valsy = [];valSorty =[] for i in range(first,last+1): valsx.append(k.valueAt(i,0)) valSortx.append(k.valueAt(i,0)) valsy.append(k.valueAt(i,1)) valSorty.append(k.valueAt(i,1)) valSortx.sort() valSorty.sort() minX = valSortx[0] maxX = valSortx[-1] minY = valSorty[0] maxY = valSorty[-1] if math.fabs(valsx.index(maxX)-valsx.index(minX)) == 1: problem = 1 if valsx.index(maxX)-valsx.index(minX) < 0: ###############checking if the curve going up or down curveXUp = 1 else: curveXDown = 1 if valsy.index(maxY)-valsy.index(minY) < 0: ###############checking if the curve going up or down curveYUp = 1 else: curveYDown = 1 if valsx.index(maxX)+first > ref: ##### kill tail X if curveXDown == 1: ##### curve X is going down####################################################################################FIXEDforEnd lastGoodX= k.valueAt(valsx.index(minX)+first,0) prelastGoodX= k.valueAt(valsx.index(minX)+first-1,0) diffX= abs(lastGoodX) - abs(prelastGoodX) offsetX = abs(lastGoodX)+maxX+diffX*2 for i in range(valsx.index(maxX)+first,last+1): val = k.valueAt(i)[0] k.setValueAt(val-offsetX,i,0) if curveXUp == 1: ##### curve X is going up####################################################################################FIXEDforEnd lastGoodX = k.valueAt(valsx.index(maxX)+first,0) prelastGoodX= k.valueAt(valsx.index(maxX)+first-1,0) diffX= abs(lastGoodX)- abs(prelastGoodX) offsetX= maxX+abs(minX)+diffX*2 for i in range(valsx.index(minX)+first,last+1): val = k.valueAt(i)[0] k.setValueAt(val+offsetX,i,0) if valsy.index(maxY)+first > ref: ##### kill tail Y if curveYDown == 1: ##### curve Y is going down#####################################################################################FIXEDforEnd lastGoodY= k.valueAt(valsy.index(minY)+first,1) prelastGoodY= k.valueAt(valsy.index(minY)+first-1,1) diffY= abs(lastGoodY) - abs(prelastGoodY) offsetY = abs(lastGoodY)+maxY+diffY*2 for i in range(valsy.index(maxY)+first,last+1): val = k.valueAt(i)[1] k.setValueAt(val-offsetY,i,1) if curveYUp == 1: ##### curve Y is going up####################################################################################FIXEDforEnd lastGoodY = k.valueAt(valsy.index(maxY)+first,1) prelastGoodY= k.valueAt(valsy.index(maxY)+first-1,1) diffY=abs(lastGoodY) - abs(prelastGoodY) offsetY= maxY+abs(minY)+diffY*2 for i in range(valsy.index(minY)+first,last+1): val = k.valueAt(i)[1] k.setValueAt(val+offsetY,i,1) if valsx.index(maxX)+first < ref: ##### kill head X------------------------------------------------------------------------------------- if curveXDown == 1: ##### curve X is going down#####################################################################################FIXEDforBeginning firstGoodX= k.valueAt(valsx.index(maxX)+first,0) prefirstGoodX= k.valueAt(valsx.index(maxX)+first+1,0) diffX= abs(firstGoodX) - abs(prefirstGoodX) offsetX = abs(firstGoodX)+abs(minX)+diffX*2 for i in range(first,valsx.index(maxX)+first): val = k.valueAt(i)[0] k.setValueAt(val+offsetX,i,0) if curveXUp == 1: ##### curve X is going up#####################################################################################FIXEDforBeginning firstGoodX = k.valueAt(valsx.index(minX)+first,0) prefirstGoodX= k.valueAt(valsx.index(minX)+first+1,0) diffX= abs(firstGoodX) - abs(prefirstGoodX) offsetX= abs(firstGoodX)+maxX+diffX*2 for i in range(first,valsx.index(minX)+first): val = k.valueAt(i)[0] k.setValueAt(val-offsetX,i,0) if valsy.index(maxY)+first < ref: ##### kill head Y if curveYDown == 1: ##### curve Y is going down#####################################################################################FIXEDforBeginning firstGoodY = k.valueAt(valsy.index(maxY)+first,1) prefirstGoodY = k.valueAt(valsy.index(maxY)+first+1,1) diffY = abs(firstGoodY) - abs(prefirstGoodY) offsetY = abs(firstGoodY)+abs(minY)+diffY*2 for i in range(first,valsy.index(maxY)+first): val = k.valueAt(i)[1] k.setValueAt(val+offsetY,i,1) if curveYUp == 1: ##### curve Y is going up#####################################################################################FIXEDforBeginning firstGoodY = k.valueAt(valsy.index(minY)+first,1) prefirstGoodY = k.valueAt(valsy.index(minY)+first+1,1) diffY = abs(firstGoodY) - abs(prefirstGoodY) offsetY = abs(firstGoodY)+maxY+diffY*2 for i in range(first,valsy.index(minY)+first): val = k.valueAt(i)[1] k.setValueAt(val-offsetY,i,1) last = lastB first = firstB else: pass # corner pin normal or Cproject try : cp = nuke.nodes.CProject(xpos = x+110, ypos = y) cp['camera'].setValue(cam.name()) cp['translate'].setValue(card['translate'].value()) cp['rotation'].setValue(card['rotate'].value()) cp['element'].setValue(label) cp.setName("CP_"+label) cp['refFrame'].setValue(ref) except: cp = nuke.nodes.CornerPin2D(label = label +' ('+str(ref)+')', xpos = x+110, ypos = y) cp['to1'].copyAnimations(r1['output'].animations()) cp['to2'].copyAnimations(r2['output'].animations()) cp['to3'].copyAnimations(r3['output'].animations()) cp['to4'].copyAnimations(r4['output'].animations()) cp['from1'].setValue(r1['output'].getValueAt(ref)) cp['from2'].setValue(r2['output'].getValueAt(ref)) cp['from3'].setValue(r3['output'].getValueAt(ref)) cp['from4'].setValue(r4['output'].getValueAt(ref)) #transform normal or Tproject try: tr = nuke.nodes.TProject(xpos = x+330, ypos = y) tr.setName("TP_"+label) tr['translate'].setAnimated() except: tr = nuke.nodes.Transform(label = label+' transform ('+str(ref)+')',xpos = x+330, ypos = y) tr['translate'].setAnimated() # corner pin matrix & roto & transform if C2Tgroup["Matrix"].value() == True or C2Tgroup["Roto"].value() == True or C2Tgroup["Transform"].value() == True: cpm = nuke.nodes.CornerPin2D(label = label+' matrix ('+str(ref)+')', xpos = x+440, ypos = y) cpm['transform_matrix'].setAnimated() roto = nuke.nodes.Roto( xpos = x+220, ypos = y) roto.setName(roto['name'].value().replace('Roto','R')+"_"+label) roto_transform = roto['curves'].rootLayer.getTransform() # transform of root layer in roto nuke.show(roto) projectionMatrixTo = nuke.math.Matrix4() projectionMatrixFrom = nuke.math.Matrix4() frame = first while frame<last+1: to1x = cp['to1'].valueAt(frame)[0] to1y = cp['to1'].valueAt(frame)[1] to2x = cp['to2'].valueAt(frame)[0] to2y = cp['to2'].valueAt(frame)[1] to3x = cp['to3'].valueAt(frame)[0] to3y = cp['to3'].valueAt(frame)[1] to4x = cp['to4'].valueAt(frame)[0] to4y = cp['to4'].valueAt(frame)[1] from1x = cp['from1'].valueAt(frame)[0] from1y = cp['from1'].valueAt(frame)[1] from2x = cp['from2'].valueAt(frame)[0] from2y = cp['from2'].valueAt(frame)[1] from3x = cp['from3'].valueAt(frame)[0] from3y = cp['from3'].valueAt(frame)[1] from4x = cp['from4'].valueAt(frame)[0] from4y = cp['from4'].valueAt(frame)[1] projectionMatrixTo.mapUnitSquareToQuad(to1x,to1y,to2x,to2y,to3x,to3y,to4x,to4y) projectionMatrixFrom.mapUnitSquareToQuad(from1x,from1y,from2x,from2y,from3x,from3y,from4x,from4y) theCornerpinAsMatrix = projectionMatrixTo*projectionMatrixFrom.inverse() theCornerpinAsMatrix.transpose() for i in range(0,16): if C2Tgroup["Matrix"].value() == True: cpm['transform_matrix'].setValueAt(theCornerpinAsMatrix[i],frame,i) if C2Tgroup["Roto"].value() == True: if C2Tgroup["Matrix"].value() == False: cpm['transform_matrix'].setValueAt(theCornerpinAsMatrix[i],frame,i) roto_transform.getExtraMatrixAnimCurve(0,i).addKey(frame,cpm['transform_matrix'].getValueAt(frame,i)) if C2Tgroup["Transform"].value() == True: tr['translate'].setValueAt((to1x+to2x+to3x+to4x)/4-bg.width()/2,frame,0) tr['translate'].setValueAt((to1y+to2y+to3y+to4y)/4-bg.height()/2,frame,1) tr['center'].setValue([bg.width()/2,bg.height()/2]) frame = frame + 1 roto['curves'].changed() if C2Tgroup["Matrix"].value() == False: nuke.delete(cpm) if C2Tgroup["Roto"].value() == False: nuke.delete(roto) if C2Tgroup["Transform"].value() == False: nuke.delete(tr) # check for turnover k = cp['to1'] vals = [] valSort =[] for i in range(first,last+1): vals.append(k.valueAt(i,0)) valSort.append(k.valueAt(i,0)) valSort.sort() minVal = valSort[0] maxVal = valSort[-1] #clean up rmL = [r1,r2,r3,r4,a1,a2,a3,a4,aM,bg] for i in rmL: nuke.delete(i) #nuke.delete(bg) if axisCase ==1: C2Tgroup.setInput(2,axisNode) card['label'].setValue(label) elif axisCase == 2:#card case C2Tgroup.setInput(2,None) card.setInput(0,None) card['label'].setValue(label) if C2Tgroup["CornerPin"].value() == False: nuke.delete(cp) if C2Tgroup["Card_1"].value() == False: nuke.delete(card) if dialog == False: roto.setXYpos(x+100,y) #remove all non roto nodes nuke.delete(cp) nuke.delete(cpm) print ('C2T done.!!!!!')
def Axis_My(): import nuke nuke.nodePaste('H:/.nuke/GeneralSetups/AxisMy.nk') n = nuke.selectedNode() nuke.show(n)
def animatedCP2MTX(): try: input = nuke.selectedNode() #---------------------------------------------------------------------------------------------------------- if input.Class() == 'CornerPin2D': node_in = input.input(0) cp = nuke.nodes.CornerPin2D( name = 'CornerPin_to_Matrix') xpos = input['xpos'].value() ypos = input['ypos'].value() cp_width = cp.screenWidth() cp_height = cp.screenHeight() cp.setXYpos(int(xpos) + int(cp_width) + 25 , int(ypos)) cp.knob('extra matrix').setValue(True) cp.setInput(0, node_in) nuke.show(cp) cp_em = cp.knob('transform_matrix') #--------------------------------------------------------------------------------------- # conversion cp_to_mtx def getAnimatedCPasMTX(cornerpin, iterator): i = iterator cp = cornerpin pmTo = nuke.math.Matrix4() pmFrom = nuke.math.Matrix4() imageWidth = float(cp.width()) imageHeight = float(cp.height()) to1x = cp['to1'].getValueAt(i)[0] to1y = cp['to1'].getValueAt(i)[1] to2x = cp['to2'].getValueAt(i)[0] to2y = cp['to2'].getValueAt(i)[1] to3x = cp['to3'].getValueAt(i)[0] to3y = cp['to3'].getValueAt(i)[1] to4x = cp['to4'].getValueAt(i)[0] to4y = cp['to4'].getValueAt(i)[1] from1x = cp['from1'].getValueAt(i)[0] from1y = cp['from1'].getValueAt(i)[1] from2x = cp['from2'].getValueAt(i)[0] from2y = cp['from2'].getValueAt(i)[1] from3x = cp['from3'].getValueAt(i)[0] from3y = cp['from3'].getValueAt(i)[1] from4x = cp['from4'].getValueAt(i)[0] from4y = cp['from4'].getValueAt(i)[1] pmTo.mapUnitSquareToQuad(to1x,to1y,to2x,to2y,to3x,to3y,to4x,to4y) pmFrom.mapUnitSquareToQuad(from1x,from1y,from2x,from2y,from3x,from3y,from4x,from4y) mtx = pmTo*pmFrom.inverse() mtx.transpose() return mtx #--------------------------------------------------------------------------------------- #--------------------------------''' Define Frame Range'''--------------------------------- frames = nuke.getFramesAndViews('get FrameRange', '%s-%s' % (nuke.root().firstFrame(), nuke.root().lastFrame())) frame_range = nuke.FrameRange( frames[0] ) #--------------------------------------------------------------------------------------- for i in frame_range: mtx = getAnimatedCPasMTX(input, i) #------------------------------------------------------------------------------ #apply values cp_em.setAnimated() for j in range(16): cp_em.setValueAt(mtx[j], i, j ) #----------------------------------------------------------------------------------------------- else: nuke.message('please select a CornerPin node') except: nuke.message('please select a CornerPin node') #end script