def checkout(self): asset_name = self.checkout_dialog.get_current_item() toCheckout = os.path.join(os.environ['SHOTS_DIR'], asset_name,'compositing') #nuke.message(toCheckout) try: destpath = amu.checkout(toCheckout, True) #nuke.message(destpath) except Exception as e: if not amu.checkedOutByMe(toCheckout): nuke.message(str(e)) return else: destpath = amu.getCheckoutDest(toCheckout) #nuke.message("destpath = " + destpath) toOpen = os.path.join(destpath,self.get_filename(toCheckout)+'.nk') #nuke.message(toOpen) #nuke.message("toOpen = " + toOpen) #nuke.scriptClose() if not os.path.exists(toOpen): nuke.scriptClear() nuke.scriptSaveAs(filename=toOpen, overwrite=1) else: nuke.scriptClear() nuke.scriptOpen(toOpen) nuke.message('Checkout Successful')
def testDefaultExpression( self ) : # create opholder and check the default expression we asked for works fnOH = IECoreNuke.FnOpHolder.create( "op", "add", 1 ) self.assertEqual( fnOH.node().knob( "parm_a" ).toScript(), '{"frame * 2"}' ) self.failUnless( fnOH.node().knob( "parm_a" ).isAnimated() ) self.assertEqual( nuke.frame(), 1 ) self.assertEqual( fnOH.node().knob( "parm_a" ).getValue(), 2 ) # remove the expression, cut and paste the node, and make sure # it doesn't reappear fnOH.node().knob( "parm_a" ).clearAnimated() self.failIf( fnOH.node().knob( "parm_a" ).isAnimated() ) nuke.nodeCopy( "test/IECoreNuke/parameterisedHolder.nk" ) nuke.scriptClear() n = nuke.nodePaste( "test/IECoreNuke/parameterisedHolder.nk" ) fnOH = IECoreNuke.FnOpHolder( n ) self.assertEqual( fnOH.node().knob( "parm_a" ).toScript(), "2" )
def execute(self, operation, file_path, **kwargs): """ Main hook entry point :operation: String Scene operation to perform :file_path: String File path to use if the operation requires it (e.g. open) :returns: Depends on operation: 'current_path' - Return the current scene file path as a String all others - None """ if file_path: file_path = file_path.replace("/", os.path.sep) if operation == "current_path": # return the current script path return nuke.root().name().replace("/", os.path.sep) elif operation == "open": # open the specified script into the current window if nuke.root().modified(): raise TankError("Script is modified!") nuke.scriptClear() nuke.scriptOpen(file_path) elif operation == "save": # save the current script: nuke.scriptSave()
def merge_image(images, tile_output): read_nodes = [] for i in images: read_nodes.append(create_read(i)) merge = nuke.createNode('Merge2') x = 0 for i in read_nodes: if x == 2: x += 1 # print i.name() merge.setInput(x, i) x += 1 else: merge.setInput(x, i) x += 1 merge["operation"].setValue("max") merge["also_merge"].setValue("all") tile_output_folder = os.path.dirname(tile_output) if not os.path.exists(tile_output_folder): os.makedirs(tile_output_folder) write = nuke.nodes.Write(inputs=[merge], file=tile_output) write["channels"].setValue("all") if tile_output.endswith(".exr"): write["file_type"].setValue("exr") write["datatype"].setValue("32 bit float") write["metadata"].setValue("all metadata") # write["compression"].setValue("none") nuke.execute(write.name(), 1, 1, 1) nuke.scriptClear()
def merge_image(images,tile_output): read_nodes = [] for i in images: read_nodes.append(create_read(i)) merge = nuke.createNode('Merge2') x = 0 for i in read_nodes: if x == 2: x += 1 # print i.name() merge.setInput(x, i) x += 1 else: merge.setInput(x, i) x += 1 merge["operation"].setValue("max") merge["also_merge"].setValue("all") tile_output_folder = os.path.dirname(tile_output) if not os.path.exists(tile_output_folder): os.makedirs(tile_output_folder) write = nuke.nodes.Write(inputs=[merge], file=tile_output) write["channels"].setValue("all") nuke.execute(write.name(), 1, 1, 1) nuke.scriptClear()
def tearDown( self ) : nuke.scriptClear() for f in glob( "test/IECoreNuke/scripts/data/sceneCacheTestResults*.exr" ) : try: os.remove(f) except: pass
def testDefaultExpression(self): # create opholder and check the default expression we asked for works fnOH = IECoreNuke.FnOpHolder.create("op", "add", 1) self.assertEqual(fnOH.node().knob("parm_a").toScript(), '{"frame * 2"}') self.failUnless(fnOH.node().knob("parm_a").isAnimated()) self.assertEqual(nuke.frame(), 1) self.assertEqual(fnOH.node().knob("parm_a").getValue(), 2) # remove the expression, cut and paste the node, and make sure # it doesn't reappear fnOH.node().knob("parm_a").clearAnimated() self.failIf(fnOH.node().knob("parm_a").isAnimated()) nuke.nodeCopy("test/IECoreNuke/parameterisedHolder.nk") nuke.scriptClear() n = nuke.nodePaste("test/IECoreNuke/parameterisedHolder.nk") fnOH = IECoreNuke.FnOpHolder(n) self.assertEqual(fnOH.node().knob("parm_a").toScript(), "2")
def test_delete_unused_node(): nuke.scriptClear(True) _ = [nuke.nodes.NoOp() for _ in xrange(10)] n = nuke.nodes.NoOp(name='_test') assert len(nuke.allNodes()) == 11 edit.delete_unused_nodes() assert nuke.allNodes() == [n]
def nysBuild(team_list): report = '' # Deliverable name, frame range, matchup?, primetime? scenes = [('CFB_E_NYS_TEAM_TRANS_01', '1-75', True, True), ('CFB_E_MATCHUP_ENDSTAMP_01_ST', '1-300', True, True), ('CFB_S_MATCHUP_FE_01_ST', '1-83', True, False), ('CFB_E_TEAM_FE_01_ST', '1-75', False, True), ('CFB_E_TEAM_ENDSTAMP_01_ST', '1-300', False, True), ('CFB_S_TEAM_FE_01', '1-90', False, False)] for scene in scenes: # Pull values from the scene list deliverable, frange, matchup, primetime = scene print deliverable # check that the _TOOLKIT.nk file exists for that deliverable file_name = '{}_TOOLKIT.nk'.format(deliverable) scene_path = join(cfb.ANIMATION_PROJECT_DIR, deliverable, 'nuke', file_name) # if it exists, do the business if exists(scene_path): nuke.scriptClear() nuke.scriptOpen(scene_path) createTeamScenes(team_list, frange, submit_to_farm=True, matchup=matchup, jumbo=matchup) report += '\nCOOL: Successfully submitted nuke scene for {}'.format( deliverable) else: report += '\nERROR: Could not find toolkit nuke scene for {}'.format( deliverable) # Repeat the process with a PRIMETIME tag if this is a nighttime scene as well if (primetime): file_name = '{}_PRIMETIME_TOOLKIT.nk'.format(deliverable) scene_path = join(cfb.ANIMATION_PROJECT_DIR, deliverable, 'nuke', file_name) if exists(scene_path): nuke.scriptClear() nuke.scriptOpen(scene_path) createTeamScenes(team_list, frange, submit_to_farm=True, matchup=matchup, jumbo=matchup) report += '\nCOOL: Successfully submitted nuke scene for {}_PRIMETIME'.format( deliverable) else: report += '\nERROR: Could not find toolkit nuke scene for {}_PRIMETIME'.format( deliverable) print report
def modify_nodes_path(self): nuke.scriptSaveAs('{}/{}'.format(self.dest_root, os.path.basename(nuke.Root().name())), 1) for node in self.nodes: modify_path(node) nuke.scriptSave() nuke.scriptClear() nuke.scriptOpen(self.original_nk)
def createTimelineFromDroppedClip(self, clipPath): nuke.scriptClear() nuke.scriptReadFile('/Users/ant/.nuke/Python/Startup/cut_detection/cutDetector.nk') self.inputNode = nuke.toNode('InputClip') self.cutDetector = nuke.toNode('CutDetector') self.inputNode['file'].fromUserText(clipPath) self.first = self.inputNode['first'].value() self.last = self.inputNode['last'].value() nuke.execute("CutDetector.CurveTool1", self.first, self.last)
def reload_script(): """Reloads the current script """ # get the current script current_script = nuke.root().knob('name').value() # clear the current nuke session nuke.scriptClear() # reload the script nuke.scriptOpen(current_script)
def createTimelineFromDroppedClip(self, clipPath): nuke.scriptClear() nuke.scriptReadFile( '/Users/ant/.nuke/Python/Startup/cut_detection/cutDetector.nk') self.inputNode = nuke.toNode('InputClip') self.cutDetector = nuke.toNode('CutDetector') self.inputNode['file'].fromUserText(clipPath) self.first = self.inputNode['first'].value() self.last = self.inputNode['last'].value() nuke.execute("CutDetector.CurveTool1", self.first, self.last)
def buildCompScript(layerOrderFile, compScriptFile, isRunningFromScript): # kept here if script is run from the comp itself if not os.path.isfile(layerOrderFile): print "Could not find layer_order.yml in " + shotDir sys.exit() if not isRunningFromScript: nuke.scriptClear() # get nuke script to build nuke.scriptOpen(compScriptFile) nuke.selectAll() [nuke.delete(node) for node in nuke.selectedNodes()] # arrange templates in the given nuke script in vertical order templates = getTemplateList(layerOrderFile) for i, template in enumerate(templates): nuke.nodePaste(template) bdNodes = nuke.selectedNodes() node = nuke.selectedNodes("BackdropNode")[0] dotNode = nuke.selectedNodes('Dot')[0] if i > 0: bdNodes.remove(node) nodePrevX = node.xpos() nodePrevY = node.ypos() node.setYpos(previousNode.ypos() + 500) node.setXpos(previousNode.xpos()) for n in bdNodes: if n.ypos() > nodePrevY: n.setYpos(node.ypos() + (n.ypos() - nodePrevY)) else: n.setYpos(node.ypos() + (n.ypos() + nodePrevY)) if n.xpos() > nodePrevX: n.setXpos(node.xpos() + (n.xpos() - nodePrevX)) else: n.setXpos(node.xpos() + (n.xpos() + nodePrevX)) if i > 1: dotNode.setInput(0, previousDotNode.dependent()[0]) else: dotNode.setInput(0, previousDotNode) previousNode = node previousDotNode = dotNode if not isRunningFromScript: # save nuke script nuke.scriptSave(compScriptFile) # avoid opening GUI and getting extra nodes from previous script nuke.scriptClose() # remove temp files [os.remove(template) for template in templates if "temp" in template]
def testCopyPasteNoValue( self ) : n = nuke.createNode( "ieObject" ) self.assertEqual( nuke.selectedNodes(), [ n ] ) nuke.nodeCopy( "test/IECoreNuke/objectKnob.nk" ) nuke.scriptClear() n2 = nuke.nodePaste( "test/IECoreNuke/objectKnob.nk" ) self.assertEqual( n2.knob( "object" ).getValue(), None )
def checkin(): save = nuke.scriptSave() if save == True: toCheckin = get_checkin_path() if can_checkin(): amu.setComment(toCheckin, 'comment') dest = amu.checkin(toCheckin) nuke.message('Checkin Successful!') nuke.scriptClear() else: nuke.message('Can not check in')
def open_file(filepath): filepath = filepath.replace("\\", "/") # To remain in the same window, we have to clear the script and read # in the contents of the workfile. nuke.scriptClear() nuke.scriptReadFile(filepath) nuke.Root()["name"].setValue(filepath) nuke.Root()["project_directory"].setValue(os.path.dirname(filepath)) nuke.Root().setModified(False) return True
def test_remove_duplicated_read(): nuke.scriptClear(True) nodes = [nuke.nodes.Read(file=b'dummy file', ) for _ in xrange(10)] downstream_nodes = [nuke.nodes.NoOp(inputs=[n]) for n in nodes] assert len(nuke.allNodes('Read')) == 10 assert not nuke.allNodes('Dot') edit.remove_duplicated_read() assert len(nuke.allNodes('Read')) == 1 assert len(nuke.allNodes('Dot')) == 9 for n in downstream_nodes: assert n.input(0).Class() in ('Read', 'Dot')
def checkin(): save = nuke.scriptSave() if save==True: toCheckin = get_checkin_path() if can_checkin(): amu.setComment(toCheckin, 'comment') dest = amu.checkin(toCheckin) nuke.message('Checkin Successful!') nuke.scriptClear() else: nuke.message('Can not check in')
def discard(): file_path = get_file_path() if file_path: toDiscard = get_checkin_path() if amu.isCheckedOutCopyFolder(toDiscard): if show_confirm_dialog(): nuke.scriptClear() amu.discard(toDiscard) else: show_dialog('ERROR: Not checked out.') else: show_dialog('ERROR: Not a file.')
def changeWriteNode(self): currents = self.listWidget.selectedItems() currents.sort() path = "W:\\Production\\3D_Shots\\" + self.searchLine.text( ) + "\\Composite" for current in currents: print current.text() fullpath = os.path.join(path, str(current.text())).replace("/", "\\") nuke.scriptClear() nuke.scriptOpen(fullpath) self.executeSetup() nuke.scriptSave()
def open_scene(file_, force=False): """Open a scene in the current nuke. Args: file_ (str): path to file to open force (bool): lose unsaved changes with no confirmation """ from psyhive import host if not force: host.handle_unsaved_changes() nuke.scriptClear() nuke.scriptOpen(file_)
def run(found_file): #check if scene is modified if nuke.Root().modified() == True: #prompt user to save if nuke.ask('Unsaved script\n\nWould you like to save?'): if nuke.Root().name() == 'Root': #run up the save_as module as this script hasnt been saved yet, then clear and open import jnuke.pipeline.save_as jnuke.pipeline.save_as.run() nuke.scriptClear() nuke.scriptOpen(found_file) else: #save the script, clear and open selected script nuke.scriptSave("") nuke.scriptClear() nuke.scriptOpen(found_file) else: #they dont want to save, so just clear the script and open the selected script nuke.scriptClear() nuke.scriptOpen(found_file) else: #not modified, simply clear and open nuke.scriptClear() nuke.scriptOpen(found_file)
def modify_nodes_path(self): """Modify file knobs in specific nodes to use relative paths.""" # We save the script to destination folder before modify it, # by this way we do not change anything in the original nk file. nuke.scriptSaveAs( '{}/{}'.format(self.dest_root, os.path.basename(nuke.Root().name())), 1) for node in self.nodes: utils.modify_path(node) nuke.scriptSaveAs( '{}/{}'.format(self.dest_root, os.path.basename(nuke.Root().name())), 1) # Restore original nk file to let users continue to do their jobs. nuke.scriptClear() nuke.scriptOpen(self.original_nk)
def testCopyPaste(self): fnPH = IECoreNuke.FnProceduralHolder.create("procedural", "read", 1) nuke.nodeCopy("test/IECoreNuke/parameterisedHolder.nk") nuke.scriptClear() n = nuke.nodePaste("test/IECoreNuke/parameterisedHolder.nk") fnPH = IECoreNuke.FnProceduralHolder(n) p = fnPH.getParameterised() self.assertEqual(p[1], "read") self.failUnless(isinstance(p[2], int)) self.assertEqual(p[2], 1) self.assertEqual(p[3], "IECORE_PROCEDURAL_PATHS")
def open_file(filepath): filepath = filepath.replace("\\", "/") # To remain in the same window, we have to clear the script and read # in the contents of the workfile. nuke.scriptClear() nuke.scriptReadFile(filepath) nuke.Root()["name"].setValue(filepath) nuke.Root()["project_directory"].setValue(os.path.dirname(filepath)) nuke.Root().setModified(False) # Since we clear the current script and read in contents of the file path # instead of loading the script (to stay within the same window), there are # no callbacks emitted by Nuke. To accommodate callbacks on loading we # introduce this signal. api.emit("workio.open_file") return True
def open_published_script(entity_reference): '''Open script based on *entity_reference*. This method is based on `nuke.assetmgr.commands.openPublishedScript`. ''' session = FnAssetAPI.SessionManager.currentSession() context = session.createContext() with context.scopedOverride(): context.access = context.kRead context.locale = FnAssetAPI.specifications.DocumentLocale() try: path = session.resolveIfReference(entity_reference, context) except FnAssetAPI.exceptions.InvalidEntityReference: FnAssetAPI.logging.warning( 'Could not resolve file path for ' 'entity reference "{0}".'.format(entity_reference)) raise if not os.path.isfile(path): FnAssetAPI.logging.warning( '"{0}" is not a valid file path.'.format(path)) return # Make a temporary file copy to work around the save as issue. _, extension = os.path.splitext(path) temporary_script_name = os.path.join( tempfile.gettempdir(), '{random}{ext}'.format(random=uuid.uuid4().hex, ext=extension)) shutil.copy2(path, temporary_script_name) nuke.scriptClear() nuke.scriptOpen(temporary_script_name) nuke.assetmgr.utils.storeTemporaryRootNodeData('entityReference', entity_reference) return entity_reference
def _nuke_execute(self, operation, file_path, **kwargs): """ The Nuke specific scene operations. """ if file_path: file_path = file_path.replace("/", os.path.sep) if operation == "current_path": # return the current script path return nuke.root().name().replace("/", os.path.sep) elif operation == "open": # open the specified script into the current window if nuke.root().modified(): raise TankError("Script is modified!") nuke.scriptClear() nuke.scriptOpen(file_path) elif operation == "save": # save the current script: nuke.scriptSave()
def SaveandClose(): ignoreUnsavedChanges = False filename = None root = nuke.Root() if not ignoreUnsavedChanges and root is not None and root.modified( ) and len(root.nodes()) > 0: runScriptSave = False if filename is None: scriptName = '' try: scriptName = nuke.scriptName() except RuntimeError: scriptName = 'untitled' try: runScriptSave = nuke.askWithCancel("Save changes to " + scriptName + " before closing?") except nuke.CancelledError: pass else: runScriptSave = True if runScriptSave: try: nuke.scriptSave(filename) except RuntimeError: pass nuke.scriptClear() AutoProjectSettings()
def testLifetime( self ) : n = nuke.createNode( "ieObject" ) k = n.knob( "object" ) nuke.scriptClear() self.assertRaises( RuntimeError, k.name ) self.assertRaises( RuntimeError, k.label ) self.assertRaises( RuntimeError, k.setValue, None ) self.assertRaises( RuntimeError, k.getValue ) w = weakref.ref( k ) self.failIf( w() is None ) del k self.failIf( w() is not None )
def testLifetime( self ) : n = nuke.createNode( "ieObject" ) k = n.knob( "object" ) nuke.scriptClear() self.assertRaises( RuntimeError, k.name ) self.assertRaises( RuntimeError, k.label ) self.assertRaises( RuntimeError, k.setValue, None ) self.assertRaises( RuntimeError, k.getValue ) w = weakref.ref( k ) self.assertFalse( w() is None ) del k self.assertFalse( w() is not None )
def close_file(): if HOST == STANDALONE: from tentaculo.api import standalone standalone.message_function("close_file") elif HOST == MAYA or HOST == MAYA2: mc.file(new=True, force=True) elif HOST == NUKE: nuke.scriptClear() elif HOST == HOUDINI: hou.hipFile.clear(suppress_save_prompt=True) elif HOST == MAX: MaxPlus.FileManager.Reset(noPrompt=True) elif HOST == C4D: c4d.documents.CloseAllDocuments() elif HOST == BLENDER: bpy.ops.wm.read_homefile() elif HOST == KATANA: KatanaFile.New() return True
def main(): parser = argparse.ArgumentParser(_file) parser.add_argument('dir', metavar='working_dir') args = parser.parse_args(_args[1:]) logging.basicConfig(level=logging.DEBUG) files = get_files(args.dir) logging.debug(files) tags = get_tags(files) logging.debug(tags) nuke.scriptClear() for tag, files in tags.items(): script_setup() create_combine(files, tag) autoplace_all() filename = u'{}/{num}#{tag}.nk'.format(args.dir, tag=tag, num=len(files)) nuke.scriptSave(slug(filename, separator='').encode('UTF-8'))
def test_glow_no_mask(): nuke.scriptClear(True) mask_channel = 'red' width_channel = 'blue' temp_channel = 'mask.a' n = nuke.nodes.Glow2(inputs=(None, nuke.nodes.Constant()), W=width_channel, maskChannelMask=mask_channel) edit.best_practice.glow_no_mask(temp_channel) assert n['W'].value() == temp_channel assert n['mask'].value() == 'none' assert n.input(1) is None n = n.input(0) assert n.Class() == 'ChannelMerge' assert n['A'].value() == temp_channel assert n['operation'].value() == 'in' assert n['B'].value() == width_channel n = n.input(0) assert n.Class() == 'Copy' assert n['from0'].value() == mask_channel assert n['to0'].value() == temp_channel
def file_open(self, filepath): """ Open the specified file. """ if self.confirm(): try: nuke.scriptClear() nuke.scriptOpen(filepath) recent_files.recents.put(filepath) self.update_recents_menu() return filepath except RuntimeError as e: # exc_type, exc_value, exc_traceback = sys.exc_info() # # traceback.print_exception(exc_type, exc_value, exc_traceback) # dialog_msg = traceback.format_exception_only(exc_type, exc_value)[0] dialog = prompt.dialog() dialog.display(str(e), "Error Opening File", conf=True) return False else: return False
def testClassParameterSetClassAndValues( self ) : fnOH = IECoreNuke.FnOpHolder.create( "test", "classParameterTest", 1 ) with fnOH.parameterModificationContext() as parameterised : parameterised["cp"].setClass( "maths/multiply", 2 ) parameterised["cp"]["a"].setNumericValue( 10 ) parameterised["cp"]["a"].setNumericValue( 20 ) self.__checkParameterKnobs( parameterised.parameters(), fnOH.node() ) nuke.nodeCopy( "test/IECoreNuke/parameterisedHolder.nk" ) nuke.scriptClear() n = nuke.nodePaste( "test/IECoreNuke/parameterisedHolder.nk" ) fnOH = IECoreNuke.FnOpHolder( n ) parameterised2 = fnOH.getParameterised()[0] self.assertEqual( parameterised.parameters().getValue(), parameterised2.parameters().getValue() )
def openscript(self): print 'OPEN SCRIPT' print self.job print self.shot print self.user print self.script if os.path.sep in self.script: self.fullpath = jeeves_core.searchJob.searchNukeFullpath(self.job, self.shot, '', self.script) else: self.fullpath = jeeves_core.searchJob.searchNukeFullpath(self.job, self.shot, self.user, self.script) if self.script == 'NEW.NK': print 'Dont need to open anything just set vars and enable stuff' jeeves_core.setVars.setJob(self.job) jeeves_core.setVars.setShot(self.shot) nukePipe.jeevesConnectUtils.enablemenus() nuke.scriptClear() #prompt to save now if there is contents in the current script else: if not os.path.isfile(self.fullpath): print 'no file' return jeeves_core.setVars.setJob(self.job) jeeves_core.setVars.setShot(self.shot) jeeves_core.setVars.setScript(self.script) jeeves_core.setVars.setFullpath(self.fullpath) #self.enablemenus() nukePipe.jeevesConnectUtils.enablemenus() #save current scrpt if not root or untitled and open target script nuke.scriptClear() nuke.scriptOpen(self.fullpath) self.update_font()
def setUp( self ) : nuke.scriptClear() nuke.Undo.undoTruncate( 0 ) nuke.Undo.redoTruncate( 0 )
def setUp( self ) : nuke.scriptClear()