def startup(self, origin): origin.timer.stop() for obj in QApplication.topLevelWidgets(): if (obj.inherits('QMainWindow') and obj.metaObject().className() == 'Foundry::UI::DockMainWindow'): nukeQtParent = obj break else: nukeQtParent = QWidget() origin.messageParent = QWidget() origin.messageParent.setParent(nukeQtParent, Qt.Window) if platform.system() != "Windows" and self.core.useOnTop: origin.messageParent.setWindowFlags(origin.messageParent.windowFlags() ^ Qt.WindowStaysOnTopHint) nuke.menu('Nuke').addCommand( 'Prism/Save Version', origin.saveScene) nuke.menu('Nuke').addCommand( 'Prism/Save Comment', origin.saveWithComment) nuke.menu('Nuke').addCommand( 'Prism/Project Browser', origin.projectBrowser) nuke.menu('Nuke').addCommand( 'Prism/Update selected read nodes', self.updateNukeNodes) nuke.menu('Nuke').addCommand( 'Prism/Settings', origin.prismSettings) toolbar = nuke.toolbar("Nodes") iconPath = os.path.join(origin.prismRoot, "Scripts", "UserInterfacesPrism", "p_tray.png") toolbar.addMenu( 'Prism', icon=iconPath ) toolbar.addCommand( "Prism/WritePrism", lambda: nuke.createNode('WritePrism')) nuke.addOnScriptLoad(origin.sceneOpen) self.isRendering = [False,""] self.useLastVersion = False
def registerNukePanel(): '''Register widget as a Nuke panel and add callback for saveing scripts''' import nuke import nukescripts nukescripts.registerWidgetAsPanel('ToDoList.MainWindow', 'To Do List', MainWindow.appName) nuke.addOnScriptSave(findAndReload) nuke.addOnScriptLoad(findAndReload)
def __init__ (self) : self.rvc = rvNetwork.RvCommunicator("Nuke"); self.port = 45128 self.initialized = False self.running = False self.selectedNode = None self.commands = self.LockedFifo() self.crashFlag = self.LockedFlag() self.sessionDir = "" self.syncSelection = False self.syncFrameChange = False self.syncReadChanges = False self.rvExecPath = "" self.updateFromPrefs() self.portFile = self.sessionDir + "/rv" + str(os.getpid()) self.zoomTargetNode = None log ("adding callbacks") # nuke.addUpdateUI (self.updateUI) nuke.addKnobChanged (self.knobChanged) nuke.addOnCreate (self.onCreate) nuke.addOnDestroy (self.onDestroy) nuke.addOnScriptClose (self.onScriptClose) nuke.addOnScriptLoad (self.onScriptLoad)
def standard_setup(): """Non-standalone user setup.""" import traceback import os import nuke import metatools.imports import sgfs.nuke.menu def callback(): try: metatools.imports.autoreload(sgfs.nuke.menu) sgfs.nuke.menu.build_for_path(nuke.root().name()) except Exception: traceback.print_exc() nuke.addOnScriptSave(callback) nuke.addOnScriptLoad(callback) try: sgfs.nuke.menu.build_for_path(os.getcwd()) except Exception: traceback.print_exc()
def startup(self, origin): origin.timer.stop() for obj in qApp.topLevelWidgets(): if (obj.inherits('QMainWindow') and obj.metaObject().className() == 'Foundry::UI::DockMainWindow'): nukeQtParent = obj break else: nukeQtParent = QWidget() origin.messageParent = QWidget() origin.messageParent.setParent(nukeQtParent, Qt.Window) origin.messageParent.setWindowFlags(origin.messageParent.windowFlags() ^ Qt.WindowStaysOnTopHint) #>>>Custom menu START nuke.menu('Nuke').addCommand( 'Prism/Project Browser', origin.projectBrowser, 'Ctrl+o', icon="F_explorer.png") nuke.menu('Nuke').addCommand( 'Prism/Save New Version', origin.saveScene, 'Alt+Shift+s') #nuke.menu('Nuke').addCommand( 'Prism/Save Comment', origin.saveWithComment) nuke.menu('Nuke').addCommand( 'Prism/Version to Latest (Reads)', self.updateNukeNodes, 'Alt+Shift+up') prismSlashMenu = nuke.menu('Nuke').addCommand( 'Prism/--------------------------------------------------') nuke.menu('Nuke').addCommand( 'Prism/Prism Settings', origin.prismSettings, icon="F_deeptopos.png") #<<<Custom menu END nuke.addOnScriptLoad(origin.sceneOpen) self.isRendering = [False,""] self.useLastVersion = False
def __init__(self): self.rvc = rvNetwork.RvCommunicator("Nuke") self.port = 45128 self.initialized = False self.running = False self.selectedNode = None self.commands = self.LockedFifo() self.crashFlag = self.LockedFlag() self.sessionDir = "" self.syncSelection = False self.syncFrameChange = False self.syncReadChanges = False self.rvExecPath = "" self.updateFromPrefs() self.portFile = self.sessionDir + "/rv" + str(os.getpid()) self.zoomTargetNode = None log("adding callbacks") # nuke.addUpdateUI (self.updateUI) nuke.addKnobChanged(self.knobChanged) nuke.addOnCreate(self.onCreate) nuke.addOnDestroy(self.onDestroy) nuke.addOnScriptClose(self.onScriptClose) nuke.addOnScriptLoad(self.onScriptLoad)
def init_app(self): """ Called as the application is being initialized """ # first, we use the special import_module command to access the app module # that resides inside the python folder in the app. This is where the actual UI # and business logic of the app is kept. By using the import_module command, # toolkit's code reload mechanism will work properly. #app_payload = self.import_module("app") # now register a *command*, which is normally a menu entry of some kind on a Shotgun # menu (but it depends on the engine). The engine will manage this command and # whenever the user requests the command, it will call out to the callback. # Get Current Shotgun Toolkit path #tk = sgtk.sgtk_from_entity(context.project["type"], context.project["id"]) #sgtk_path = str(tk).split(" ")[-1] sgtk_python_path = sgtk.get_sgtk_module_path() sgtk_config_path = os.path.join( sgtk_python_path.split("install")[0], "config") # Check if hook folder exists, this app will not work without making a bespoke lut gizmo and script. app_hook_path = os.path.join(sgtk_config_path, "hooks", "tk-nuke", "tk-nuke-lut-app") if not os.path.exists(app_hook_path): os.makedirs(app_hook_path) self.logger.info("Created Hooks folder: tk-nuke/tk-nuke-lut-app") # # Copy over the update_lut.py # callback_script = "update_lut.py" # src = os.path.join(os.path.dirname(__file__), "resources", callback_script) # dst = os.path.join(app_hook_path, callback_script) # if not os.path.exists(dst): # shutil.copy2(src, dst) # self.logger.info("Copied "+callback_script+" script to hooks folder because it did not exist yet.") # # Copy over the example init.py # resource = "init.py" # src = os.path.join(os.path.dirname(__file__), "resources", resource) # dst = os.path.join(app_hook_path, resource) # if not os.path.exists(dst): # shutil.copy2(src, dst) # self.logger.info("Copied "+resource+" script to hooks folder because it did not exist yet.") # Adding hook folder to Nuke Path so the custom gizmo and script can be picked up nuke.pluginAddPath(app_hook_path) self.logger.error("Adding " + app_hook_path + " to nuke plugin path") # first, set up our callback, calling out to a method inside the app module contained # in the python folder of the app menu_callback = lambda: loadLut() # now register the command with the engine self.engine.register_command("Load Viewer LUT...", menu_callback) # Callbacks nuke.addOnScriptSave(loadLut()) nuke.addOnScriptLoad(loadLut())
def registerNukePanel(): """Register widget as a Nuke panel and add callback for saveing scripts""" import nuke import nukescripts nukescripts.registerWidgetAsPanel("ToDoList.MainWindow", "To Do List", MainWindow.appName) nuke.addOnScriptSave(findAndReload) nuke.addOnScriptLoad(findAndReload)
def set_open_file_callback(self, func=None): """ set_open_file_callback will set a callback function for when a file is opened """ if func: nuke.addOnScriptSave(func) nuke.addOnScriptLoad(func)
def tank_ensure_callbacks_registered(): """ Make sure that we have callbacks tracking context state changes. """ global g_tank_callbacks_registered if not g_tank_callbacks_registered: nuke.addOnScriptLoad(tank_startup_node_callback) nuke.addOnScriptSave(__tank_on_save_callback) g_tank_callbacks_registered = True
def addCallbackOnScriptLoad(self, func, nodeClass=None, group=None): """Executed when a script is loaded. This will be called by onCreate (for root), and straight after onCreate. """ self._addNukeCallbackGroup(group) self.windowInstance()['callback'][group]['onScriptLoad'][func].add(nodeClass) if not self.__windowHidden: if nodeClass is None: nuke.addOnScriptLoad(func) else: nuke.addOnScriptLoad(func, nodeClass=nodeClass)
def setup(): nuke.addBeforeRender(CALLBACKS_BEFORE_RENDER.execute) nuke.addOnScriptLoad(CALLBACKS_ON_SCRIPT_LOAD.execute) nuke.addOnScriptSave(CALLBACKS_ON_SCRIPT_SAVE.execute) nuke.addOnScriptClose(CALLBACKS_ON_SCRIPT_CLOSE.execute) nuke.addOnCreate(CALLBACKS_ON_CREATE.execute) nuke.addUpdateUI(CALLBACKS_UPDATE_UI.execute) if nuke.GUI: import nukescripts nukescripts.addDropDataCallback(CALLBACKS_ON_DROP_DATA.execute)
def startup(self, origin): origin.timer.stop() for obj in qApp.topLevelWidgets(): if (obj.inherits('QMainWindow') and obj.metaObject().className() == 'Foundry::UI::DockMainWindow'): nukeQtParent = obj break else: nukeQtParent = QWidget() origin.messageParent = QWidget() origin.messageParent.setParent(nukeQtParent, Qt.Window) if platform.system() != "Windows" and self.core.useOnTop: origin.messageParent.setWindowFlags( origin.messageParent.windowFlags() ^ Qt.WindowStaysOnTopHint) ''' # New organise menu prism in nuke nuke.menu('Nuke').addCommand( 'Prism/Save Version', origin.saveScene) nuke.menu('Nuke').addCommand( 'Prism/Save Comment', origin.saveWithComment) nuke.menu('Nuke').addCommand( 'Prism/Project Browser', origin.projectBrowser) nuke.menu('Nuke').addCommand( 'Prism/Update selected read nodes', self.updateNukeNodes) nuke.menu('Nuke').addCommand( 'Prism/Settings', origin.prismSettings) toolbar = nuke.toolbar("Nodes") iconPath = os.path.join(origin.prismRoot, "Scripts", "UserInterfacesPrism", "p_tray.png") toolbar.addMenu( 'Prism', icon=iconPath ) toolbar.addCommand( "Prism/WritePrism", lambda: nuke.createNode('WritePrism')) ''' #>>>Custom menu START nuke.menu('Nuke').addCommand('Prism/Project Browser', origin.projectBrowser, 'Ctrl+o', icon="F_explorer.png") nuke.menu('Nuke').addCommand('Prism/Save New Version', origin.saveScene, 'Alt+Shift+s') #nuke.menu('Nuke').addCommand( 'Prism/Save Comment', origin.saveWithComment) nuke.menu('Nuke').addCommand('Prism/Version to Latest (Reads)', self.updateNukeNodes, 'Alt+Shift+up') prismSlashMenu = nuke.menu('Nuke').addCommand( 'Prism/--------------------------------------------------') nuke.menu('Nuke').addCommand('Prism/Prism Settings', origin.prismSettings, icon="F_deeptopos.png") #<<<Custom menu END nuke.addOnScriptLoad(origin.sceneOpen) self.isRendering = [False, ""] self.useLastVersion = False
def tank_ensure_callbacks_registered(): """ Make sure that we have callbacks tracking context state changes. """ import sgtk engine = sgtk.platform.current_engine() # Register only if we're missing an engine (to allow going from disabled to something else) # or if the engine specifically requests for it. if not engine or engine.get_setting("automatic_context_switch"): global g_tank_callbacks_registered if not g_tank_callbacks_registered: nuke.addOnScriptLoad(tank_startup_node_callback) nuke.addOnScriptSave(__tank_on_save_callback) g_tank_callbacks_registered = True
def __init__(self, parent=None): super(ConnectionManagerWidget, self).__init__() self.items = QtWidgets.QListWidget() self.toolbar = ConnectionManagerToolbar() mainlayout = QtWidgets.QHBoxLayout(self) mainlayout.addWidget(self.toolbar) mainlayout.addWidget(self.items) self.setLayout(mainlayout) self.installEventFilter(self) self.toolbar.refresh_action.triggered.connect(self.update_items) self.toolbar.add_action.triggered.connect(self.add_nodes) self.toolbar.remove_action.triggered.connect(self.remove_selection) self.toolbar.connect_input1_action.triggered.connect( partial(self.connect_node, node_input=0)) self.toolbar.connect_input2_action.triggered.connect( partial(self.connect_node, node_input=1)) self.toolbar.connect_mask_action.triggered.connect( partial(self.connect_node, mask_input=True)) self.toolbar.view_action.triggered.connect(self.view_node) self.items.itemDoubleClicked.connect(self.select_item) nuke.addOnScriptLoad(self.update_items)
def init(): # Adding scan_for_unused_components menubar = nuke.menu("Nuke") menu = menubar.menu("pyblish-bumpybox") cmd = "from pyblish_bumpybox.nuke import utils;" cmd += "utils.scan_for_unused_components()" menu.addCommand("Scan for unused components", cmd) # Adding published LUT lut_init() # pyblish-bumpybox callbacks nuke.addOnScriptLoad(fps_init) nuke.addOnScriptLoad(resolution_init) nuke.addOnScriptLoad(frame_range_init) nuke.addOnScriptLoad(utils.scan_for_unused_components) # Scan explicitly for new assets on startup, # since Ftrack native implementation only scans # when loading a script within Nuke. nuke.addOnScriptLoad(scan_for_new_assets) # pyblish-qml settings try: __import__("pyblish_qml") except ImportError as e: print("pyblish-bumpybox: Could not load pyblish-qml: %s " % e) else: from pyblish_qml import settings session = ftrack_api.Session() task = session.get("Task", os.environ["FTRACK_TASKID"]) ftrack_path = "" for item in task["link"]: ftrack_path += session.get(item["type"], item["id"])["name"] ftrack_path += " / " settings.WindowTitle = ftrack_path[:-3]
def tank_ensure_callbacks_registered(engine=None): """ Make sure that we have callbacks tracking context state changes. The OnScriptLoad callback really only comes into play when you're opening a file or creating a new script, when there is no current script open in your Nuke session. If there is a script currently open then this will spawn a new Nuke instance and the callback won't be called. """ global g_tank_callbacks_registered # Register only if we're missing an engine (to allow going from disabled to something else) # or if the engine specifically requests for it. if not engine or engine.get_setting("automatic_context_switch"): if not g_tank_callbacks_registered: nuke.addOnScriptLoad(sgtk_on_load_callback) nuke.addOnScriptSave(__sgtk_on_save_callback) g_tank_callbacks_registered = True elif engine and not engine.get_setting("automatic_context_switch"): # we have an engine but the automatic context switching has been disabled, we should ensure the callbacks # are removed. if g_tank_callbacks_registered: nuke.removeOnScriptLoad(sgtk_on_load_callback) nuke.removeOnScriptSave(__sgtk_on_save_callback) g_tank_callbacks_registered = False
def init(): # Check to see if launched from a task. if "FTRACK_TASKID" not in os.environ: return # Adding menu items menubar = nuke.menu("Nuke") menu = menubar.menu("grill-tools") cmd = "from grill_tools.nuke import ftrack_utils;" cmd += "ftrack_utils.scan_for_unused_components()" menu.addCommand("Scan for unused components", cmd) cmd = "from grill_tools.nuke import ftrack_utils;" cmd += "ftrack_utils.import_all_image_sequences()" menu.addCommand("Import All Image Sequences", cmd) cmd = "from grill_tools.nuke import ftrack_utils;" cmd += "ftrack_utils.import_all_gizmos()" menu.addCommand("Import All Gizmos", cmd) cmd = "from grill_tools.nuke import ftrack_utils;" cmd += "ftrack_utils.setup()" menu.addCommand("Setup", cmd) # Adding published LUT lut_init() # grill-tools callbacks nuke.addOnScriptLoad(project_settings_init) nuke.addOnScriptLoad(ftrack_utils.scan_for_unused_components) # Scan explicitly for new assets on startup, # since Ftrack native implementation only scans # when loading a script within Nuke. nuke.addOnScriptLoad(scan_for_new_assets) # pyblish-qml settings try: __import__("pyblish_qml") except ImportError as e: print("grill-tools: Could not load pyblish-qml: %s " % e) else: from pyblish_qml import settings # Check to see if launched from a task. if "FTRACK_TASKID" not in os.environ: return session = ftrack_api.Session() task = session.get("Task", os.environ["FTRACK_TASKID"]) ftrack_path = "" for item in task["link"]: ftrack_path += session.get(item["type"], item["id"])["name"] ftrack_path += " / " settings.WindowTitle = ftrack_path[:-3]
def tank_ensure_callbacks_registered(engine=None): """ Make sure that we have callbacks tracking context state changes. The OnScriptLoad callback really only comes into play when you're opening a file or creating a new script, when there is no current script open in your Nuke session. If there is a script currently open then this will spawn a new Nuke instance and the callback won't be called. """ # Register only if we're missing an engine (to allow going from disabled to something else) # or if the engine specifically requests for it. if not engine or engine.get_setting("automatic_context_switch"): global g_tank_callbacks_registered if not g_tank_callbacks_registered: nuke.addOnScriptLoad(sgtk_on_load_callback) nuke.addOnScriptSave(__sgtk_on_save_callback) g_tank_callbacks_registered = True elif engine and not engine.get_setting("automatic_context_switch"): # we have an engine but the automatic context switching has been disabled, we should ensure the callbacks # are removed. global g_tank_callbacks_registered if g_tank_callbacks_registered: nuke.removeOnScriptLoad(sgtk_on_load_callback) nuke.removeOnScriptSave(__sgtk_on_save_callback) g_tank_callbacks_registered = False
if n['reading'].value(): n['postage_stamp'].setValue(True) n['tile_color'].setValue(13500671) elif n['reading'].value() != True and n['tile_color'].value != 0: n['postage_stamp'].setValue(False) n['tile_color'].setValue(0) else: pass nuke.addUpdateUI(writeReadingStatus,(),{},"Write") def dpxNoAlpha(): """ Do not allow DPX files to be written with alpha """ n = nuke.thisNode() if nuke.filename(n).endswith("dpx"): n['channels'].setValue("rgb") nuke.addUpdateUI(dpxNoAlpha,(),{},"Write") # Attach Reveal in Finder to Write/Read nodes""" def deprecated_attach_reveal_in_finder(): n = nuke.thisNode() if not n.knobs().has_key("revealPath"): K = pyScriptKnob(" Reveal file ", "nuke.revealFile(nuke.filename(nuke.thisNode()))", "revealPath") n.addKnob(K) #nuke.addUpdateUI(attach_reveal_in_finder,(),{},"Write") #nuke.addUpdateUI(attach_reveal_in_finder,(),{},"Read") nuke.addOnScriptLoad(createRootKnob,pyScriptKnob(" Reveal file ", "nuke.revealFile(nuke.root().name())", "revealPath"))
def populate_ftrack(self): import nuke import legacy from nukescripts import panels from ftrack_connect_nuke.connector import Connector # Check if QtWebKit or QWebEngine is avaliable. from FnAssetAPI.ui.toolkit import is_webwidget_supported has_webwidgets = is_webwidget_supported() Connector.registerAssets() # wrappers for initializing the widgets with # the correct connector object def wrapImportAssetDialog(*args, **kwargs): from ftrack_connect.ui.widget.import_asset import FtrackImportAssetDialog return FtrackImportAssetDialog(connector=Connector()) def wrapAssetManagerDialog(*args, **kwargs): from ftrack_connect.ui.widget.asset_manager import FtrackAssetManagerDialog return FtrackAssetManagerDialog(connector=Connector()) # Populate the ui nukeMenu = nuke.menu("Nuke") ftrackMenu = nukeMenu.addMenu("&ftrack") ftrackMenu.addSeparator() # add ftrack publish node to the menu ftrackMenu.addCommand('Create Publish Node', lambda: legacy.createFtrackPublish()) ftrackMenu.addSeparator() globals()['ftrackImportAssetClass'] = wrapImportAssetDialog panels.registerWidgetAsPanel( '{0}.{1}'.format(__name__, 'ftrackImportAssetClass'), 'ftrackImportAsset', 'ftrackDialogs.ftrackImportAssetDialog') ftrackMenu.addSeparator() ftrackMenu.addCommand( 'Import Asset', 'pane = nuke.getPaneFor("Properties.1");' 'panel = nukescripts.restorePanel("ftrackDialogs.ftrackImportAssetDialog");' 'panel.addToPane(pane)') globals()['ftrackAssetManagerDialogClass'] = wrapAssetManagerDialog # Create the asset manager dialog entry in the menu panels.registerWidgetAsPanel( '{0}.{1}'.format(__name__, 'ftrackAssetManagerDialogClass'), 'ftrackAssetManager', 'ftrackDialogs.ftrackAssetManagerDialog') ftrackMenu.addCommand( 'Asset Manager', 'pane = nuke.getPaneFor("Properties.1");' 'panel = nukescripts.restorePanel("ftrackDialogs.ftrackAssetManagerDialog");' 'panel.addToPane(pane)') if has_webwidgets: def wrapAssetInfoDialog(*args, **kwargs): from ftrack_connect_nuke.ui.widget.info_view import AssetInfoView return AssetInfoView(bridge=self._bridge) globals()['ftrackAssetInfoDialogClass'] = wrapAssetInfoDialog # Create the crew dialog entry in the menu panels.registerWidgetAsPanel( '{0}.{1}'.format(__name__, 'ftrackAssetInfoDialogClass'), 'ftrackAssetInfo', 'ftrackDialogs.ftrackAssetInfoDialog') ftrackMenu.addCommand( 'Asset Info', 'pane = nuke.getPaneFor("Properties.1");' 'panel = nukescripts.restorePanel("ftrackDialogs.ftrackAssetInfoDialog");' 'panel.addToPane(pane)') ftrackMenu.addSeparator() if has_webwidgets: from ftrack_connect_foundry.ui.info_view import WorkingTaskInfoView as _WorkingTaskInfoView from ftrack_connect_foundry.ui.tasks_view import TasksView as _TasksView # Add Web Views located in the ftrack_connect_foundry package to the # menu for easier access. for widget in [_TasksView, _WorkingTaskInfoView]: ftrackMenu.addCommand( widget.getDisplayName(), 'pane = nuke.getPaneFor("Properties.1");' 'panel = nukescripts.restorePanel("{identifier}");' 'panel.addToPane(pane)'.format( identifier=widget.getIdentifier())) ftrackMenu.addSeparator() # Add new entries in the ftrack menu. ftrackMenu.addSeparator() if has_webwidgets: from ftrack_connect_nuke.ui.widget.publish_gizmo import GizmoPublisherDialog ftrackMenu.addCommand('Publish gizmo', GizmoPublisherDialog) # Add ftrack publish node toolbar = nuke.toolbar("Nodes") ftrackNodesMenu = toolbar.addMenu("ftrack", icon="ftrack_logo.png") ftrackNodesMenu.addCommand('ftrackPublish', lambda: legacy.createFtrackPublish()) # Set calbacks def asset_info_menu_switch(): '''Enable and disable asset info depending on selection.''' this_node = nuke.thisNode() # Do not continue if selection is not node. if not isinstance(this_node, nuke.Node): return try: is_ftrack = this_node.knob('assetVersionId') except ValueError: is_ftrack = False nuke_menu = nuke.menu('Nuke') menu_item = nuke_menu.findItem('&ftrack') asset_info_menu = menu_item.findItem('Asset Info') if has_webwidgets and asset_info_menu: if is_ftrack: asset_info_menu.setEnabled(True) else: asset_info_menu.setEnabled(False) nuke.addKnobChanged(asset_info_menu_switch) # other callbacks nuke.addOnScriptLoad(legacy.refAssetManager) nuke.addOnScriptLoad(legacy.scan_for_new_assets) nuke.addOnUserCreate(legacy.addFtrackComponentField, nodeClass='Write') nuke.addOnUserCreate(legacy.addFtrackComponentField, nodeClass='WriteGeo') nuke.addOnUserCreate(legacy.addFtrackComponentField, nodeClass='Read') nuke.addKnobChanged(legacy.ftrackPublishKnobChanged, nodeClass="Group") nuke.addOnCreate(legacy.ftrackPublishHieroInit) # Set default values from environments. start_frame = os.environ.get('FS', 0) end_frame = os.environ.get('FE', 100) FnAssetAPI.logging.debug( 'Setting start frame : {}'.format(start_frame)) nuke.knob('root.first_frame', str(start_frame)) FnAssetAPI.logging.debug('Setting end frame : {}'.format(end_frame)) nuke.knob('root.last_frame', str(end_frame))
import os import sys import KnobScripter from pype.nuke.lib import (writes_version_sync, on_script_load, check_inventory_versions) import nuke from pypeapp import Logger log = Logger().get_logger(__name__, "nuke") # nuke.addOnScriptSave(writes_version_sync) nuke.addOnScriptSave(on_script_load) nuke.addOnScriptLoad(check_inventory_versions) nuke.addOnScriptSave(check_inventory_versions) # nuke.addOnScriptSave(writes_version_sync) log.info('Automatic syncing of write file knob to script version')
import os import nuke def check_script_version(): script_write_nd_name = nuke.root()['timeline_write_node'].getValue() script_write_nd = nuke.toNode(script_write_nd_name) render_file = script_write_nd['file'].getValue() xml_file = render_file.split('.')[0] + ".xml" if os.path.exists(xml_file): nuke.message( "WARNING! It appears as if this script version has already been submitted for review. Please version up the script before you continue working." ) nuke.addOnScriptLoad(check_script_version)
m.addCommand( 's_PointsToCornerPin', lambda: nuke.createNode( 's_PointsToCornerPin' ), icon = 's_PointsToCornerPin.png' ) m.addCommand( 's_TrackReformat', lambda: nuke.createNode( 's_TrackReformat' ), icon = 's_TrackReformat.png' ) m.addCommand( 's_MaskedBlur', lambda: nuke.createNode( 's_MaskedBlur' ), icon = 's_MaskedBlur.png' ) ### Lockviewer l = LockViewer() def onScriptLoadCallback(): for n in nuke.allNodes(): if n.Class() == "Viewer": if n.knob('locked0'): for i in range(10): if n.input(i) != None: l.lockInput(True, i, n, n.input(i)) nuke.addOnScriptLoad(onScriptLoadCallback) m = nuke.menu( 'Nuke' ).addMenu('Sap Tools') subm = m.addMenu('Lock Selected Node to Viewer') subm.addCommand( 'lockViewer1', lambda: l.lockInput(True,0,nuke.activeViewer().node(),nuke.selectedNode()), '#1') subm.addCommand( 'unlockViewer1', lambda: l.lockInput(False,0,nuke.activeViewer().node(),None), '^#1') subm.addCommand( 'lockViewer2', lambda: l.lockInput(True,1,nuke.activeViewer().node(),nuke.selectedNode()), '#2') subm.addCommand( 'unlockViewer2', lambda: l.lockInput(False,1,nuke.activeViewer().node(),None), '^#2') subm.addCommand( 'lockViewer3', lambda: l.lockInput(True,2,nuke.activeViewer().node(),nuke.selectedNode()), '#3') subm.addCommand( 'unlockViewer3', lambda: l.lockInput(False,2,nuke.activeViewer().node(),None), '^#3') subm.addCommand( 'lockViewer4', lambda: l.lockInput(True,3,nuke.activeViewer().node(),nuke.selectedNode()), '#4') subm.addCommand( 'unlockViewer4', lambda: l.lockInput(False,3,nuke.activeViewer().node(),None), '^#4') subm.addCommand( 'lockViewer5', lambda: l.lockInput(True,4,nuke.activeViewer().node(),nuke.selectedNode()), '#5') subm.addCommand( 'unlockViewer5', lambda: l.lockInput(False,4,nuke.activeViewer().node(),None), '^#5') subm.addCommand( 'lockViewer6', lambda: l.lockInput(True,5,nuke.activeViewer().node(),nuke.selectedNode()), '#6') subm.addCommand( 'unlockViewer6', lambda: l.lockInput(False,5,nuke.activeViewer().node(),None), '^#6')
nuke.addBeforeFrameRender(writeNoOverwrite) def writeNoOverwriteKnob(): n = nuke.thisNode() if 'no_overwrite' not in n.knobs().keys(): n.addKnob(nuke.Boolean_Knob("no_overwrite","no_overwrite")) else: pass nuke.addOnCreate(writeNoOverwriteKnob,(),{},"Write") def setEnvironment(): """ Any knob added to a script's Root panel whose name is all capitalized is declared as an environment variable callable from any node with [getenv VARIABLE]. Note that you must reload the script before the variable becomes active. """ isAllCaps = lambda s: True if s.upper() == s else False N = [nuke.root()[i].name() for i in nuke.root().knobs() if isAllCaps(nuke.root()[i].name())] V = [nuke.root()[i].value() for i in nuke.root().knobs() if isAllCaps(nuke.root()[i].name())] h = dict(zip(N,V)) for k in h.keys(): os.environ[k] = h[k] nuke.addOnScriptLoad(setEnvironment) def removeTimecode(): try: nuke.thisNode()['timecode'].setValue(None) except NameError: pass nuke.addBeforeRender(removeTimecode, args=(), kwargs={}, nodeClass='Write')
#THIS LINE WILL ADD THE NEW ENTRY TO THE PANE MENU nuke.menu('Pane').addCommand('SearchReplace', addSRPanel) # CREATE A READ NODE AND OPEN THE "DB" TAB def customRead(): n = nuke.createNode( 'Read' ) n['PipeL'].setFlag( 0 ) return n nuke.menu( 'Nodes' ).addCommand( 'Image/ReadPipel', customRead, 'Shift+r' ) nuke.addOnUserCreate( nuk.general.read.createVersionKnobs, nodeClass='Read' ) nuke.addKnobChanged( nuk.general.read.updateVersionKnob, nodeClass='Read' ) nuke.addOnScriptLoad( nuk.general.read.checkVersions ) nuke.addOnScriptSave( nuk.general.read.checkVersions ) """ import nuk.general.read import nuke nuke.removeOnScriptLoad(nuk.general.read.checkVersions) nuke.removeOnScriptSave(nuk.general.read.checkVersions) """ def mergeColor(): n = nuke.thisNode() k = nuke.thisKnob() if k.name() == "mix": v = k.value() green = v red = 1 - int(v)
def markNodesWithDangerousExpressions(): """For any expression-driven knob that has a potentially confusing expression in it, mark it's node orange and put a warning in the label. """ # List of expressions that can cause us trouble. Add more as you wish. dangerous_expressions = ['$gui', 'proxy'] knobs=allKnobsWithExpressions() for knob in knobs: for expr in dangerous_expressions: if expr in knob.toScript(): # Mark this one markThisNode(knob.node(), str(expr)) def markNodesWithHiddenInputs(): """For any node with a hidden input, mark it and put a warning in the label. """ for node in allNodesWithHiddenInputs(): markThisNode(node, 'hiddden input') nuke.addOnScriptLoad(markNodesWithDangerousExpressions) # TODO: Test this, then turn it on. #nuke.addOnScriptLoad(markNodesWithHiddenInputs)
menubar.addCommand('Node/Align/Under Y', 'Ym_alignNodes.alignUY()') menubar.addCommand('Node/Align/Interval Y', 'Ym_alignNodes.align_intY()') menubar.addCommand('Node/Align/Interval XX', 'Ym_alignNodes.align_intXX()') menubar.addCommand('Node/Align/Interval YY', 'Ym_alignNodes.align_intYY()') import mirrorNodes menubar.addCommand('Node/Align/Mirror Horiz', 'mirrorNodes.mirrorNodes( nuke.selectedNodes(), direction="x" )', 'alt+ctrl+x') menubar.addCommand('Node/Align/Mirror Vert', 'mirrorNodes.mirrorNodes( nuke.selectedNodes(), direction="y" )', 'alt+ctrl+y') #frank's node scale up trick import scaleNodes menubar.addCommand('Node/Align/Scale Up', 'scaleNodes.scaleNodes( 1.1 )', '=') menubar.addCommand('Node/Align/Scale Down', 'scaleNodes.scaleNodes( 0.9 )', '-') menubar.findItem('Node').addCommand('Toggle Viewer Pipes', 'nodeOps.toggleViewerPipes()', 'alt+t') nuke.addOnScriptLoad(nodeOps.toggleViewerPipes) #thumbnailer menubar.addCommand('Node/Thumbnailer', 'thumbnailer.thumbnailer()', 'shift+t') #version read nodes to latest import versionToLatest menubar.addCommand( 'Edit/Node/Filename/Version to Latest (Reads only)' , versionToLatest.versionToLatest) # select a tracker and a bezier node and hit ctrl+t to auto link the two together #only works with Bezier, so disabling for the moment till I get it to work with Rotopaint #nuke.menu('Nuke').findItem('Edit/Node').addCommand("Transform/Connect2Tracker", "nuke.tcl(\"Connect2Tracker\")", 'ctrl+t') #menu "Transform/Connect2Tracker" "^t" Connect2Tracker ##########################################################################################
import nuke import os nuke.pluginAddPath(os.path.join(os.environ['SHOW_PATH'], '_show', 'presets')) def fixTimelineWrite(): if nuke.root().knob('timeline_write_node') is None: k = nuke.String_Knob('timeline_write_node') nuke.root().addKnob(k) nuke.root()['timeline_write_node'].setValue('SHOT_WRITE') nuke.addOnScriptLoad(fixTimelineWrite)
os.path.join(currentFile, "..", "..", "..", "..")) moduleName = os.path.basename( os.path.normpath(os.path.join(currentFile, "..", "..", ".."))) if not main_folder in sys.path: sys.path.append(main_folder) ### Registering Callback ### exec("from {0} import config as wsconfig".format(moduleName)) def store_recent(): wsconfig.add_recent(nuke.Root().knob("name").value()) nuke.addOnScriptLoad(store_recent) nuke.addOnScriptSave(store_recent) if nuke.env['NukeVersionMajor'] < 11: execfile(os.path.join(main_folder, moduleName, "main.py")) ### Import Required Modules ### def WelcomeScreen_start(): ws = WelcomeScreen() ws.start() ### Registering Menu ### menu = nuke.menu('Nuke') menu.addCommand('General/Welcome Screen', lambda f=WelcomeScreen_start: nuke.executeInMainThread(f), 'ctrl+shift+w')
import os import sys import KnobScripter from pype.nuke.lib import (writes_version_sync, onScriptLoad, checkInventoryVersions) import nuke from pypeapp import Logger log = Logger().get_logger(__name__, "nuke") # nuke.addOnScriptSave(writes_version_sync) nuke.addOnScriptSave(onScriptLoad) nuke.addOnScriptLoad(checkInventoryVersions) nuke.addOnScriptSave(checkInventoryVersions) # nuke.addOnScriptSave(writes_version_sync) log.info('Automatic syncing of write file knob to script version')
# ----------------------------------------------------------------------------- def load_toolbars(): """Load all custom toolbars via config files.""" ptask_area = PTaskArea.current() nuke_toolbar_config = ptask_area.config(config_file=NUKE_TOOLBAR_CONFIG, composite_ancestors=True) for (toolbar_name, toolbar_config) in nuke_toolbar_config.iteritems(): toolbar = nuke.toolbar(toolbar_name) for (item_key, item_config) in toolbar_config.iteritems(): name = item_config.get("label", item_key) command = item_config.get("command", "print 'No op'") icon = item_config.get("image", None) tooltip = item_config.get("annotation", "") if icon: icon = IconFactory().disk_path(icon) toolbar.addCommand(name=name, command=command, icon=icon, tooltip=tooltip) # ----------------------------------------------------------------------------- load_toolbars() print "Loading DPA Nuke nodes..." add_commands() nuke.addOnScriptLoad(dpa.nuke.nodes.on_load)
#Import and execute Carls Startup scripts #------------------------------------------------------------------ #import and execute rbNukeStartupCarl module try: #import from rugbyBugs.nuke.rbNukeStartupCarl import rbNukeStartupCarl if(doReload): reload(rbNukeStartupCarl) #execute nuke.addOnScriptLoad(rbNukeStartupCarl.RbNukeStartupCarl().createInitialSetup) nuke.tprint('Successfully loaded and executed Carls startup scripts') except: nuke.tprint('Error loading Carls Nuke startup module')
keep['channels2'].setValue('none') def startupCallbacks(): if 'composite' in nuke.root().name().split('/')[-1]: #add gizmos to aovs #from mlScripts import gizmoTools #gizmoTools.findMissingAssetGizmos.main() addAssetGizmos() #setLightingStatusComplete() #overideSumbitter() #addUserText() updateCamera() #removeStartRGBAChannel() #delete viewers for v in nuke.allNodes('Viewer'): nuke.delete(v) for grp in nuke.allNodes('Group'): with grp: for v in nuke.allNodes('Viewer'): nuke.delete(v) #if grp.name()=='Submitter': # nuke.delete(grp) #preferences nuke.toNode('preferences')['postage_stamp_mode'].setValue(1) nuke.toNode('preferences')['expression_arrows'].setValue(0) nuke.addOnScriptLoad(startupCallbacks)
menu = nuke.menu("Nuke") menu.addCommand( "Tools/Ada/Remove Ada Tab", "__import__('ada.nuke.utils', " "fromlist=['remove_ada_tab']).remove_ada_tab(nuke.selectedNodes())", shortcut="Shift+Alt+t", ) menu.addCommand( "Tools/Ada/Bake Selected", "__import__('ada.nuke.context', " "fromlist=['Engine']).Engine.run(nodes=nuke.selectedNodes())", shortcut="Shift+b", ) menu.addCommand( "Tools/Ada/Add Knobs To Bake", "__import__('ada.nuke.node', " "fromlist=['add_knob_to_bake']).add_knob_to_bake(nuke.selectedNode())", shortcut="Shift+t", ) # add ada file loader nuke.addOnScriptLoad(load_ada_context_from_file) # add ada file loader nuke.addOnScriptSave(save_ada_context_to_file) # add on destroy callback to remove any context information that nodes are associated with.
p.addSingleLineInput('shotcode', shotCode) p.addSingleLineInput('version name', scriptName) p.addMultilineTextInput('description', '') res = p.show() if res==1: shotCode = p.value('shotcode') vrName = p.value('version name') vrDescrip = p.value('description') try: res = shotgun.createVersion(projName, shotCode, vrName, vrDescrip, scriptPath) if res.has_key('id'): nuke.message('Published to Shotgun!') except Exception: nuke.message('Publish failed!') nuke.createShotgunVersion = createShotgunVersion nuke.addOnScriptLoad(createRootKnob,pyScriptKnob("Publish version","nuke.createShotgunVersion()",'publishVr')) nuke.addOnScriptLoad(createRootKnob,pyScriptKnob("Update status","nuke.updateShotgunStatus()",'updateSGStatus'))
1] + "_" + fileNameSplit[2] projectName = path fileVersion = fileNameSplit[3].replace(".nk", "") print dirname print projectPath nuke.addFavoriteDir("Project", projectPath) nuke.addFavoriteDir("Inputs", projectPath + "\\input\\" + dirname + "\\") nuke.addFavoriteDir("Write", writeRootDir + "\\" + projectName + "\\" + dirname) def scriptSaved(): loadScriptVars() checkWriteNodes() #checkInputNodes() def scriptLoaded(): loadScriptVars() checkWriteNodes() #checkInputNodes() nuke.addOnScriptLoad(scriptLoaded) nuke.addOnScriptSave(scriptSaved)
lambda: rbRenderReconstruct.RbRenderReconstruct().reconstructMultiMatteREs( )) rugbyBugsRenderReconstructMenu.addCommand( 'Reconstruct Shadow Elements', lambda: rbRenderReconstruct.RbRenderReconstruct().reconstructShadowREs()) #Create RugbyBugs Ui (Pane) #------------------------------------------------------------------ #registerWidgetAsPanel panels.registerWidgetAsPanel('rugbyBugsNukeInterface.RugbyBugsNukeInterface', 'RugbyBugsUi', 'uk.co.thefoundry.NukeTestWindow') #Import and execute Carls Startup scripts #------------------------------------------------------------------ #import and execute rbNukeStartupCarl module try: #import from rugbyBugs.nuke.rbNukeStartupCarl import rbNukeStartupCarl if (doReload): reload(rbNukeStartupCarl) #execute nuke.addOnScriptLoad( rbNukeStartupCarl.RbNukeStartupCarl().createInitialSetup) nuke.tprint('Successfully loaded and executed Carls startup scripts') except: nuke.tprint('Error loading Carls Nuke startup module')
#help elif knob.name()=="www.leafpictures.de": url = 'http://www.leafpictures.de/zooom' webbrowser.open_new(url) # press an zooomItem else: loc = knob.name() #solve knobdata zooomActive="" for z in nuke.ZOOOMDATA: if loc in z: zooomActive = z break zooomTo(zooomActive) def addZooomPanel(): global zooomPanel nuke.ZOOOMDATA="" zooomPanel = zooomPanel() return zooomPanel.addToPane() #init zooom data for current script nuke.addOnScriptLoad(initZooomData)
#this sets default node values on the grade node and write node nuke.knobDefault('Grade.black_clamp','false')#turns off black clamp knob on Grade nodes when created nuke.knobDefault("Write.channels", "rgba")#changes the default on write nodes from rgb to rgba #example for spawining an external application or process from a nuke button import subprocess nuke.menu("Nuke").addMenu("Footage").addCommand('BrokenGlass rv', "subprocess.Popen('/usr/local/tweaks/rv/bin/rv /path/to/my/files/', shell = True)")#this spawns flipbook for specific render nuke.menu("Nuke").addMenu("Utilities").addCommand('Vim', "subprocess.Popen('/usr/bin/gvim', shell = True)")#this creates a menu on the top bar called Utilities and adds a button to start up gvim #example for adding slog lut in root nuke.root().knob('luts').addCurve("sLog", "{pow(10.0, ((t - 0.616596 - 0.03) /0.432699)) - 0.037584}") #example for killing all viewers apon opening new script to speed up working with large scripts def killViewers(): for v in nuke.allNodes("Viewer"): nuke.delete(v) nuke.addOnScriptLoad(killViewers) #adds frank's search and replace python panel which is included def addSRPanel(): '''Run the panel script and add it as a tab into the pane it is called from''' myPanel = SearchReplacePanel.SearchReplacePanel() return myPanel.addToPane() nuke.menu('Pane').addCommand('SearchReplace', addSRPanel)#THIS LINE WILL ADD THE NEW ENTRY TO THE PANE MENU nukescripts.registerPanel('com.ohufx.SearchReplace', addSRPanel)#THIS LINE WILL REGISTER THE PANEL SO IT CAN BE RESTORED WITH LAYOUTS
(pName, pExt) = os.path.splitext(os.path.basename(root['name'].value())) pData = etree.fromstring(root['tri_project_xml_formats'].value()) for group in nuke.allNodes("Group", nuke.root()): if 'triwrite_gizmo' not in group.knobs(): continue resultNode = group.node('result') dailiesNode = group.node('dailies') #--- update results params filename = pName + pData.find('result').find('file').get('numbers') + pData.find('result').find('file').get('file_type') filename = nukenormpath(filename) oldfilename = os.path.basename(resultNode['file'].value()) resultNode['file'].setValue(resultNode['file'].value().replace(oldfilename, filename)) #--- update dailies params filename = pName + pData.find('dailies').find('file').get('numbers') + pData.find('dailies').find('file').get('file_type') filename = nukenormpath(filename) oldfilename = os.path.basename(dailiesNode['file'].value()) dailiesNode['file'].setValue(dailiesNode['file'].value().replace(oldfilename, filename)) pData = None nuke.addOnUserCreate(tri_project_init, nodeClass="Root") nuke.addOnUserCreate(tri_writeGizmo_init, nodeClass="Group") nuke.addOnScriptSave(tri_writeGizmo_update, nodeClass="Root") nuke.addOnScriptLoad(tri_project_init, nodeClass="Root")
# Animation Menu animation = nuke.menu("Animation") # Viewer Menu viewer = nuke.menu("Viewer") # Preferences Condition if os.path.exists(platform_pref_path()): # Preferences Available import Bc_ToolSet_preferences as pref gizmoColor = pref.gizmo_color if pref.save_log is True: from PrPy.SaveLog import save_log, lock_save_log nuke.addOnScriptSave(save_log) nuke.addOnScriptLoad(lock_save_log) # Gizmos - Nodes Menu if pref.Bc_ShuffleMatte is True: Bc_ShuffleMatte = "nuke.createNode('Bc_ShuffleMatte', 'tile_color %d')" % gizmoColor nodes.addCommand("Bc_ShuffleMatte", Bc_ShuffleMatte, "", icon="Bc_ShuffleMatte_v01.png") if pref.Bc_LBGrain is True: Bc_LBGrain = "nuke.createNode('Bc_LBGrain', 'tile_color %d')" % gizmoColor nodes.addCommand("Bc_LBGrain", Bc_LBGrain, "", icon="Bc_LBGrain_v01.png") if pref.Bc_RGBLuma is True:
def run(): for (i,node) in enumerate(readingNodes): if 'checksums' not in node.knobs().keys(): tKnob = nuke.Text_Knob('checksums','checksums') tKnob.setVisible(False) node.addKnob(tKnob) (dirPath, basename, filename) = nuke.actualFilename(node) filepath = os.path.join(dirPath, filename) if os.path.exists(filepath): crc = hashlib.sha1(open(filepath).read(10485760)).hexdigest() node['checksums'].setValue(crc) task.setProgress(int(i*1./len(readingNodes)*100)) if threaded: threading.Thread( None, run ).start() else: run() nuke.addOnScriptLoad(checksumOfReadNode) nuke.addOnScriptClose(checksumOfReadNode, args=(), kwargs={'threaded':False}, nodeClass='Root') # ------------- Reconnect functions ---------------- # # Callback functions used to reconnect all missing reads on # scripLoad with the help of OS-dependent indexing services. # def reconnectMissing(indexCmd): # On Windows, use Everything (http://www.voidtools.com/). # Assumes "es.exe" command line program is in PATH. Note that # "es.exe" doesn't work with networked drives. # On OS X, use Spotlight. errors = [n for n in nuke._allNodes() if n.hasError() and nuke.filename(n) is not None] if errors: task = nuke.ProgressTask("Missing files!")
def force24fps(): nuke.root()['fps'].setValue(24) def setupshot(): for n in nuke.allNodes('NoOp'): if n.name() == 'SETUP': print "PERFORMING INITIAL SHOT SETUP..." nuke.delete(n) nuke.delete(nuke.toNode('ModifyMetaData1')) nuke.delete(nuke.toNode('ModifyMetaData2')) nuke.root()['first_frame'].setValue( nuke.toNode('Read1')['first'].getValue() + 16) nuke.root()['last_frame'].setValue( nuke.toNode('Read1')['last'].getValue() - 16) pf = nuke.toNode('MAE_PLATE_FORMATTER_v2') nuke.delete(nuke.toNode('MAE_PLATE_FORMATTER_v2')) nuke.scriptReadFile( os.path.join(os.environ['IH_PATH_SERVER'], '13th_Floor', '_pipeline', 'nuke', 'ToolSets', 'mae_shared', 'mae_plate_formatter.nk')) nuke.addOnScriptLoad(setupshot) #nuke.knobDefault("Grade.black_clamp", "False")