Exemple #1
0
def run_engine_cmd(log, install_root, pipeline_config_root, context_items, command, using_cwd, args):
    """
    Launches an engine and potentially executes a command.

    :param log: logger
    :param install_root: tank installation
    :param pipeline_config_root: PC config location
    :param context_items: list of strings to describe context. Either ["path"],
                               ["entity_type", "entity_id"] or ["entity_type", "entity_name"]

    :param engine_name: engine to run
    :param command: command to run - None will display a list of commands
    :param using_cwd: Was the context passed based on the current work folder?
    """
    log.debug("")
    log.debug("Context items: %s" % str(context_items))
    log.debug("Command: %s" % command)
    log.debug("Command Arguments: %s" % args)
    log.debug("Code Location Root: %s" % install_root)
    log.debug("Sgtk Pipeline Config Location: %s" % pipeline_config_root)
    log.debug("Location of this script (__file__): %s" % os.path.abspath(__file__))

    log.info("")

    log.info("Welcome to the Shotgun pipeline toolkit!")
    log.info("For documentation, see https://toolkit.shotgunsoftware.com/forums")

    # Now create a tk instance and a context if possible

    if len(context_items) == 1:

        ctx_path = context_items[0]

        if using_cwd:
            log.info("Starting the Sgtk for your current directory '%s'" % ctx_path)

        # context str is a path
        if pipeline_config_root is not None:
            # we are running a project specific tank command
            tk =  tank.tank_from_path(pipeline_config_root)

        else:
            # we are running a studio wide command
            try:
                tk = tank.tank_from_path(ctx_path)
            except TankError, e:
                # this path was not valid. That's ok - we just wont have a tank instance
                # when we run our commands later. This may be if we for example have
                # just run tank setup_project from any random folder
                log.debug("Instantiating Sgtk raised: %s" % e)
                tk = None

        # now try to extract a context
        ctx = None
        if tk is not None:
            ctx = tk.context_from_path(ctx_path)
Exemple #2
0
def refresh_engine(engine_name, prev_context, menu_name):
    """
    refresh the current engine
    """
    current_engine = tank.platform.current_engine()

    if not current_engine:
        # If we don't have an engine for some reason then we don't have
        # anything to do.
        return

    if pm.sceneName() == "":
        # This is a File->New call, so we just leave the engine in the current
        # context and move on.
        return

    # determine the tk instance and ctx to use:
    tk = current_engine.sgtk

    # loading a scene file
    new_path = pm.sceneName().abspath()

    # this file could be in another project altogether, so create a new
    # API instance.
    try:
        tk = tank.tank_from_path(new_path)
    except tank.TankError, e:
        OpenMaya.MGlobal.displayInfo("Shotgun: Engine cannot be started: %s" % e)
        # build disabled menu
        create_sgtk_disabled_menu(menu_name)
        return
Exemple #3
0
def __tank_on_save_callback():
    """
    Callback that fires every time a file is saved.
    
    Carefully manage exceptions here so that a bug in Tank never
    interrupts the normal workflows in Nuke.
    """
    # get the new file name
    file_name = nuke.root().name()
    
    try:
        # this file could be in another project altogether, so create a new Tank
        # API instance.
        try:
            tk = tank.tank_from_path(file_name)
        except tank.TankError, e:
            __create_tank_disabled_menu(e)
            return
        
        # try to get current ctx and inherit its values if possible
        curr_ctx = None
        if tank.platform.current_engine():
            curr_ctx = tank.platform.current_engine().context
        
        # and now extract a new context based on the file
        new_ctx = tk.context_from_path(file_name, curr_ctx)
        
        # now restart the engine with the new context
        __engine_refresh(tk, new_ctx)
Exemple #4
0
def refresh_engine(engine_name, prev_context, menu_name):
    """
    refresh the current engine
    """    
    #import rpdb2;rpdb2.start_embedded_debugger("12345")
    current_engine = tank.platform.current_engine()
    
    # first make sure that the disabled menu is reset, if it exists...
    #if pm.menu("ShotgunMenuDisabled", exists=True):
    #    pm.deleteUI("ShotgunMenuDisabled")
    
    # if the scene opened is actually a file->new, then maintain the current
    # context/engine.
    scene_name  = lxtd.current_scene().filename

    if not scene_name:
        return current_engine

    new_path = scene_name
    
    # this file could be in another project altogether, so create a new Tank
    # API instance.
    try:
        tk = tank.tank_from_path(new_path)
    except tank.TankError, e:
        # render menu
        modoshotgunsupport.add_disabled_menu()
        
        # (AD) - this leaves the engine running - is this correct?        
        return current_engine
Exemple #5
0
def refresh_engine(engine_name, prev_context, menu_name):
    """
    refresh the current engine
    """    
    current_engine = tank.platform.current_engine()
    
    # first make sure that the disabled menu is removed, if it exists...
    menu_was_disabled = remove_sgtk_disabled_menu()
    
    # determine the tk instance and ctx to use:
    tk = current_engine.sgtk
    ctx = prev_context
    if pm.sceneName() == "":
        # if the scene opened is actually a file->new, then maintain the current
        # context/engine.
        if not menu_was_disabled:
            # just return the current engine - no need to restart it!
            return current_engine
    else:
        # loading a scene file
        new_path = pm.sceneName().abspath()
    
        # this file could be in another project altogether, so create a new
        # API instance.
        try:
            tk = tank.tank_from_path(new_path)
        except tank.TankError, e:
            OpenMaya.MGlobal.displayInfo("Shotgun: Engine cannot be started: %s" % e)
            # build disabled menu
            create_sgtk_disabled_menu(menu_name)
            return current_engine

        # and construct the new context for this path:
        ctx = tk.context_from_path(new_path, prev_context)
Exemple #6
0
def refresh_engine(engine_name, prev_context, menu_name):
    """
    refresh the current engine
    """    
    current_engine = tank.platform.current_engine()
    
    # first make sure that the disabled menu is reset, if it exists...
    if pm.menu("ShotgunMenuDisabled", exists=True):
        pm.deleteUI("ShotgunMenuDisabled")
    
    # if the scene opened is actually a file->new, then maintain the current
    # context/engine.
    if pm.sceneName() == "":
        return current_engine

    new_path = pm.sceneName().abspath()
    
    # this file could be in another project altogether, so create a new Tank
    # API instance.
    try:
        tk = tank.tank_from_path(new_path)
    except tank.TankError, e:
        OpenMaya.MGlobal.displayInfo("Shotgun: Engine cannot be started: %s" % e)
        # render menu
        create_tank_disabled_menu(menu_name)
        
        # (AD) - this leaves the engine running - is this correct?        
        return current_engine
Exemple #7
0
    def _on_project_load_callback(self, event):
        """
        Callback executed after project load in Hiero and Nuke Studio. This
        triggers an attempt to change the SGTK context to that of the newly
        opened project file.

        :param event:   The event object from Hiero/NS.
        """
        import hiero.core

        project = hiero.core.projects()[-1]
        script_path = project.path()

        # We're going to just skip doing anything if this fails
        # for any reason. It would be nice to swap to the error
        # menu item, but unfortunately a project open event is
        # triggered on launch when Hiero/Nuke Studio loads the
        # "Untitled" project from the Nuke install location. There
        # isn't a way to distinguish between that and something the
        # user purposefully opened, and we don't want to hose the
        # toolkit context with that.
        try:
            tk = tank.tank_from_path(script_path)

            # Extract a new context based on the file and change to that
            # context.
            new_context = tk.context_from_path(
                script_path,
                previous_context=self.context,
            )

            if new_context != self.context:
                tank.platform.change_context(new_context)
        except Exception:
            self.log_debug("Unable to determine context for file: %s" % script_path)
Exemple #8
0
def refresh_engine(engine_name, prev_context, menu_name):
    """
    refresh the current engine
    """
    current_engine = tank.platform.current_engine()

    if not current_engine:
        # If we don't have an engine for some reason then we don't have
        # anything to do.
        return

    doc = c4d.documents.GetActiveDocument()

    scene_path = doc.GetDocumentPath()
    scene_name = doc.GetDocumentName()

    # This is a File->New call, so we just leave the engine in the current
    # context and move on.
    if scene_path == "":
        if prev_context != tank.platform.current_engine().context:
            current_engine.change_context(ctx)
        return

    # determine the tk instance and ctx to use:
    tk = current_engine.sgtk

    # loading a scene file
    new_path = os.path.abspath(os.path.join(scene_path, scene_name))

    # this file could be in another project altogether, so create a new
    # API instance.
    try:
        tk = tank.tank_from_path(new_path)
        # and construct the new context for this path:
        ctx = tk.context_from_path(new_path, prev_context)
    except tank.TankError:
        try:
            ctx = current_engine.sgtk.context_from_entity_dictionary(
                current_engine.context.project)
        except tank.TankError:
            (exc_type, exc_value, exc_traceback) = sys.exc_info()
            message = ""
            message += "Shotgun Cinema Engine cannot be started:.\n"
            message += "Please contact you technical support team for more "
            message += "information.\n\n"
            message += "Exception: %s - %s\n" % (exc_type, exc_value)
            message += "Traceback (most recent call last):\n"
            message += "\n".join(traceback.format_tb(exc_traceback))

            display_error(message)
            return

    # shotgun menu may have been removed, so add it back in if its not already
    # there.
    current_engine.create_shotgun_menu()

    if ctx != tank.platform.current_engine().context:
        current_engine.change_context(ctx)
 def test_alternate_branch(self):
     """
     Test path not from primary branch.
     """
     os.mkdir(os.path.join(self.alt_root_1, "child_dir"))
     child_path = os.path.join(self.alt_root_1, "child_dir")
     result = tank.tank_from_path(child_path)
     self.assertIsInstance(result, Tank)
     self.assertEqual(result.project_path, self.project_root)
Exemple #10
0
def get_tk_object(project):
    conf_data = ShotgunConfParser.sg_conf_data()
    api_script = conf_data.get("script_name")
    api_key = conf_data.get("api_key")
    root_pn = conf_data[project].get("root_pn")
    # connect to shotgun server
    tk_connect(api_script, api_key)
    # init a tk object
    return tank.tank_from_path(root_pn)
Exemple #11
0
 def test_primary_branch(self):
     """
     Test path from primary branch.
     """
     child_path = os.path.join(self.project_root, "child_dir")
     os.mkdir(os.path.join(self.project_root, "child_dir"))
     result = tank.tank_from_path(child_path)
     self.assertIsInstance(result, Tank)
     self.assertEquals(result.project_path, self.project_root)
Exemple #12
0
 def test_alternate_branch(self):
     """
     Test path not from primary branch.
     """
     os.mkdir(os.path.join(self.alt_root_1, "child_dir"))
     child_path = os.path.join(self.alt_root_1, "child_dir")
     result = tank.tank_from_path(child_path)
     self.assertIsInstance(result, Tank)
     self.assertEquals(result.project_path, self.project_root)
    def test_from_path(self):
        """
        Ensures tank_from_path will resolve site wide configs.
        """
        os.environ["TANK_CURRENT_PC"] = self.pipeline_config_root
        try:
            result = tank.tank_from_path(self.project_root)
            self.assertEqual(result.project_path, self.project_root)
            self.assertEqual(result.pipeline_configuration.get_path(), self.pipeline_config_root)

            self._invalidate_pipeline_configuration_yml()
            with self.assertRaisesRegex(
                TankInitError,
                "however that is not associated with the pipeline configuration"
            ):
                tank.tank_from_path(self.project_root)
        finally:
            del os.environ["TANK_CURRENT_PC"]
    def test_from_path(self):
        """
        Ensures tank_from_path will resolve site wide configs.
        """
        os.environ["TANK_CURRENT_PC"] = self.pipeline_config_root
        try:
            result = tank.tank_from_path(self.project_root)
            self.assertEquals(result.project_path, self.project_root)
            self.assertEquals(result.pipeline_configuration.get_path(), self.pipeline_config_root)

            self._invalidate_pipeline_configuration_yml()
            with self.assertRaisesRegexp(
                TankInitError,
                "however that is not associated with the pipeline configuration"
            ):
                tank.tank_from_path(self.project_root)
        finally:
            del os.environ["TANK_CURRENT_PC"]
 def test_primary_branch(self):
     """
     Test path from primary branch.
     """
     child_path = os.path.join(self.project_root, "child_dir")
     os.mkdir(os.path.join(self.project_root, "child_dir"))
     result = tank.tank_from_path(child_path)
     self.assertIsInstance(result, Tank)
     self.assertEqual(result.project_path, self.project_root)
Exemple #16
0
def get_tk_object(
        api_script="tank",
        api_key="f28b2d9918667f240426d33d3ce3ad4c9d589c9ccba6cc3db6c59aaa28403fb8",
        root_pn=r"Z:\Resource\Pipeline\app_config\settings\projects\df\sgtk\main"
):
    # connect to shotgun server
    tk_connect(api_script, api_key)
    # init a tk object
    return tank.tank_from_path(root_pn)
Exemple #17
0
 def test_from_path(self):
     """
     Ensures tank_from_path will resolve site wide configs.
     """
     os.environ["TANK_CURRENT_PC"] = self.pipeline_config_root
     try:
         result = tank.tank_from_path(self.project_root)
         self.assertEquals(result.project_path, self.project_root)
         self.assertEquals(result.pipeline_configuration.get_path(),
                           self.pipeline_config_root)
     finally:
         del os.environ["TANK_CURRENT_PC"]
def getTankEntity(projPath):
    '''
    Build a tank instance from project path

    :Params:
        projPath: str
            The path of project that tank defined

    :Returns: 
        a tank instance
    '''
    return tank.tank_from_path(projPath)
    def __get_nuke_path(self):

        # Get the shotgun paths.yml file
        current_engine = sgtk.platform.current_engine()
        context = current_engine.context
        tk = tank.tank_from_path(context.tank.roots["primary"])
        config_path = tk.pipeline_configuration.get_path() + "\\config\\env\\includes\\paths.yml"

        # use yaml to extract the path location
        with open(config_path, 'r') as yml_config_file:
            config_file = yaml.load(yml_config_file)

        nuke_path = config_file["nuke_windows"]
        return nuke_path
Exemple #20
0
def __tank_startup_node_callback():
    """
    Callback that fires every time a node gets created.
    
    Carefully manage exceptions here so that a bug in Tank never
    interrupts the normal workflows in Nuke.    
    """
    try:
        # look for the root node - this is created only when a new or existing file is opened.
        tn = nuke.thisNode()
        if tn != nuke.root():
            return

        if nuke.root().name() == "Root":
            # file->new
            # base it on the context we 'inherited' from the prev session
            # get the context from the previous session - this is helpful if user does file->new
            project_root = os.environ.get("TANK_NUKE_ENGINE_INIT_PROJECT_ROOT")
            tk = tank.Tank(project_root)

            ctx_yaml = os.environ.get("TANK_NUKE_ENGINE_INIT_CONTEXT")
            if ctx_yaml:
                try:
                    new_ctx = yaml.load(ctx_yaml)
                except:
                    new_ctx = tk.context_empty()
            else:
                new_ctx = tk.context_empty()

        else:
            # file->open
            file_name = nuke.root().name()

            try:
                tk = tank.tank_from_path(file_name)
            except tank.TankError, e:
                __create_tank_disabled_menu(e)
                return

            # try to get current ctx and inherit its values if possible
            curr_ctx = None
            if tank.platform.current_engine():
                curr_ctx = tank.platform.current_engine().context

            new_ctx = tk.context_from_path(file_name, curr_ctx)

        # now restart the engine with the new context
        __engine_refresh(tk, new_ctx)
Exemple #21
0
def __tank_startup_node_callback():    
    """
    Callback that fires every time a node gets created.
    
    Carefully manage exceptions here so that a bug in Tank never
    interrupts the normal workflows in Nuke.    
    """    
    try:
        # look for the root node - this is created only when a new or existing file is opened.
        tn = nuke.thisNode()
        if tn != nuke.root():
            return
            
        if nuke.root().name() == "Root":
            # file->new
            # base it on the context we 'inherited' from the prev session
            # get the context from the previous session - this is helpful if user does file->new
            project_root = os.environ.get("TANK_NUKE_ENGINE_INIT_PROJECT_ROOT")
            tk = tank.Tank(project_root)
            
            ctx_str = os.environ.get("TANK_NUKE_ENGINE_INIT_CONTEXT")
            if ctx_str:
                try:
                    new_ctx = tank.context.deserialize(ctx_str)
                except:
                    new_ctx = tk.context_empty()
            else:
                new_ctx = tk.context_empty()
    
        else:
            # file->open
            file_name = nuke.root().name()
            
            try:
                tk = tank.tank_from_path(file_name)
            except tank.TankError, e:
                __create_tank_disabled_menu(e)
                return
                
            # try to get current ctx and inherit its values if possible
            curr_ctx = None
            if tank.platform.current_engine():
                curr_ctx = tank.platform.current_engine().context                
                
            new_ctx = tk.context_from_path(file_name, curr_ctx)
    
        # now restart the engine with the new context
        __engine_refresh(tk, new_ctx)
    def __group_yeti_nodes(self, yetinodes):
        # define the group from the current shotgun ass
        scene_name = cmds.file(query=True, sn=True)
        tk = tank.tank_from_path(scene_name)
        templ = tk.template_from_path(scene_name)
        fields = templ.get_fields(scene_name)

        group_name = fields['Asset'] + "_yetiFurNodes_v" + str(fields['version']).zfill(3)

        # select the top group yeti nodes to maintain hierarchy
        nodes = []
        for i in yetinodes:
            p = cmds.listRelatives(i, parent=True, fullPath=True)
            nodes.append(p[0].split('|')[1])

        cmds.select(nodes)
        return cmds.group(cmds.ls(sl=True), name=group_name, relative=True)
Exemple #23
0
    def _get_context_from_script(self, script):
        """
        Returns an sgtk.context.Context object from the given script path.

        :param script:  The path to a script file on disk.
        """
        tk = tank.tank_from_path(script)

        context = tk.context_from_path(
            script,
            previous_context=self.engine.context,
        )

        if context.project is None:
            raise tank.TankError(
                "The Nuke engine needs at least a project "
                "context in order to start! Your context: %s" % context)
        else:
            return context
Exemple #24
0
def shotgun_run_action(log, install_root, pipeline_config_root, is_localized, args):
    """
    Executes the special shotgun run action command from inside of shotgun
    """

    # we are talking to shotgun! First of all, make sure we switch on our html style logging
    log.handlers[0].formatter.enable_html_mode()

    log.debug("Running shotgun_run_action command")
    log.debug("Arguments passed: %s" % args)

    try:
        tk = tank.tank_from_path(pipeline_config_root)
        # attach our logger to the tank instance
        # this will be detected by the shotgun and shell engines
        # and used.
        tk.log = log
    except TankError, e:
        raise TankError("Could not instantiate an Sgtk API Object! Details: %s" % e )
Exemple #25
0
def shotgun_run_action(log, install_root, pipeline_config_root, is_localized, args):
    """
    Executes the special shotgun run action command from inside of shotgun
    """

    # we are talking to shotgun! First of all, make sure we switch on our html style logging
    log.handlers[0].formatter.enable_html_mode()

    log.debug("Running shotgun_run_action command")
    log.debug("Arguments passed: %s" % args)

    try:
        tk = tank.tank_from_path(pipeline_config_root)
        # attach our logger to the tank instance
        # this will be detected by the shotgun and shell engines
        # and used.
        tk.log = log
    except TankError, e:
        raise TankError("Could not instantiate an Sgtk API Object! Details: %s" % e )
def get_idA(objA=[]):
    """
    Store asset ids
    :return:
    """

    assetID_A = []

    for x in objA:
        ass_path = cmds.getAttr(x + '.definition')

        tk_ref = tank.tank_from_path(ass_path)
        context_ref = tk_ref.context_from_path(ass_path)

        if context_ref:
            if context_ref.entity:
                if context_ref.entity.get('id'):
                    assetID_A.append(int(context_ref.entity.get('id')))

    return assetID_A
def get_idA(objA=[]):
    """
    Store asset ids
    :return:
    """

    assetID_A = []

    for x in objA:
        ass_path = cmds.getAttr(x + '.definition')

        tk_ref = tank.tank_from_path(ass_path)
        context_ref = tk_ref.context_from_path(ass_path)

        if context_ref:
            if context_ref.entity:
                if context_ref.entity.get('id'):
                    assetID_A.append(int(context_ref.entity.get('id')))

    return assetID_A
Exemple #28
0
    def _get_context_from_script(self, script):
        """
        Returns an sgtk.context.Context object from the given script path.

        :param script:  The path to a script file on disk.
        """
        tk = tank.tank_from_path(script)

        context = tk.context_from_path(
            script,
            previous_context=self.engine.context,
        )

        if context.project is None:
            raise tank.TankError(
                "The Nuke engine needs at least a project "
                "context in order to start! Your context: %s" % context
            )
        else:
            return context
Exemple #29
0
def refresh_engine(engine_name, prev_context, menu_name):
    """
    refresh the current engine
    """
    logger.debug("Refreshing the engine, previous context: '%r'", prev_context)
    current_engine = tank.platform.current_engine()

    if not current_engine:
        # If we don't have an engine for some reason then we don't have
        # anything to do.
        logger.debug(
            "No currently initialized engine found; aborting the refresh of the engine"
        )
        return

    if pm.sceneName() == "":
        # This is a File->New call, so we just leave the engine in the current
        # context and move on.
        logger.debug("New file call, aborting the refresh of the engine.")
        return

    # determine the tk instance and ctx to use:
    tk = current_engine.sgtk

    # loading a scene file
    new_path = pm.sceneName().abspath()

    # this file could be in another project altogether, so create a new
    # API instance.
    try:
        tk = tank.tank_from_path(new_path)
        logger.debug("Extracted sgtk instance: '%r' from path: '%r'", tk,
                     new_path)

    except tank.TankError, e:
        logger.exception("Could not execute tank_from_path('%s')" % new_path)
        OpenMaya.MGlobal.displayInfo("Shotgun: Engine cannot be started: %s" %
                                     e)
        # build disabled menu
        create_sgtk_disabled_menu(menu_name)
        return
Exemple #30
0
def add_alembic_tag():
    selection = libUtilities.get_selected()
    if selection:
        for node in selection:
            # Add the alembic Tag
            scene_name = cmds.file(query=True, sn=True)
            tk = tank.tank_from_path(scene_name)
            templ = tk.template_from_path(scene_name)
            fields = templ.get_fields(scene_name)

            asset_name = "assetNameOrShotStep"

            if "Asset" in fields:
                asset_name = fields["Asset"]

            elif "Shot" in fields:
                asset_name = fields["Step"]
         
            libUtilities.addStrAttr(node, 'Alembic')
            node.Alembic.set(asset_name)
            # Add the frame rate tag
            libUtilities.addAttr(node, "Step", 100, 0.0001, df=1)
            node.Step.setKeyable(False)
            node.Step.showInChannelBox(False)
            # Frame Relative Sample
            libUtilities.addBoolAttr(node, "RelativeFrameSample")
            node.RelativeFrameSample.setKeyable(False)
            node.RelativeFrameSample.showInChannelBox(False)
            libUtilities.addAttr(node, "RelativeLow", 100, -100, df=-.2)
            node.RelativeLow.setKeyable(False)
            node.RelativeLow.showInChannelBox(False)
            libUtilities.addAttr(node, "RelativeHigh", 100, -100, df=.2)
            node.RelativeHigh.setKeyable(False)
            node.RelativeHigh.showInChannelBox(False)
            libUtilities.addStrAttr(node, "WARNING")
            node.WARNING.set("DO NOT EDIT ANYTHING BELOW THIS ATTRIBUTE")
            node.WARNING.lock()
            libUtilities.addStrAttr(node, "ModelUsed")
            libUtilities.addStrAttr(node, "Namespace")
    else:
        libGUI.nothing_selected_box()
Exemple #31
0
    def _startup_node_callback(self):
        """
        Callback that fires every time a node gets created.
        """
        try:
            # Look for the root node. This is created only when a new or existing
            # file is opened.
            if nuke.thisNode() != nuke.root():
                return

            if nuke.root().name() == "Root":
                # This is a file->new call, so base it on the context we
                # stored from the previous session.
                tk = tank.Tank(self.init_project_root)

                if self.init_context:
                    new_ctx = self.init_context
                else:
                    new_ctx = tk.context_empty()
            else:
                # This is a file->open call, so we can get the new context
                # from the file path that was opened.
                file_name = nuke.root().name()
                try:
                    tk = tank.tank_from_path(file_name)
                except tank.TankError as e:
                    self.engine.menu_generator.create_sgtk_disabled_menu(e)
                    return

                new_ctx = tk.context_from_path(
                    file_name,
                    previous_context=self.context,
                )

            # Now change the context for the engine and apps.
            self.change_context(new_ctx)
        except Exception:
            self.engine.menu_generator.create_sgtk_error_menu()
Exemple #32
0
    def _on_save_callback(self):
        """
        Callback that fires every time a file is saved.
        """
        try:
            # Get the new file name.
            file_name = nuke.root().name()
            try:
                # This file could be in another project altogether, so
                # create a new Tank instance.
                tk = tank.tank_from_path(file_name)
            except tank.TankError, e:
                self.engine.menu_generator.create_sgtk_disabled_menu(e)
                return

            # Extract a new context based on the file and change to that
            # context.
            new_context = tk.context_from_path(
                file_name,
                previous_context=self.context,
            )

            self.change_context(new_context)
Exemple #33
0
    def _on_save_callback(self):
        """
        Callback that fires every time a file is saved.
        """
        try:
            # Get the new file name.
            file_name = nuke.root().name()
            try:
                # This file could be in another project altogether, so
                # create a new Tank instance.
                tk = tank.tank_from_path(file_name)
            except tank.TankError, e:
                self.engine.menu_generator.create_sgtk_disabled_menu(e)
                return

            # Extract a new context based on the file and change to that
            # context.
            new_context = tk.context_from_path(
                file_name,
                previous_context=self.context,
            )

            self.change_context(new_context)
Exemple #34
0
def refresh_engine(engine_name, prev_context, menu_name):
    """
    refresh the current engine
    """
    logger.debug("Refreshing the engine, previous context: '%r'", prev_context)
    current_engine = tank.platform.current_engine()

    if not current_engine:
        # If we don't have an engine for some reason then we don't have
        # anything to do.
        logger.debug("No currently initialized engine found; aborting the refresh of the engine")
        return

    if pm.sceneName() == "":
        # This is a File->New call, so we just leave the engine in the current
        # context and move on.
        logger.debug("New file call, aborting the refresh of the engine.")
        return

    # determine the tk instance and ctx to use:
    tk = current_engine.sgtk

    # loading a scene file
    new_path = pm.sceneName().abspath()

    # this file could be in another project altogether, so create a new
    # API instance.
    try:
        tk = tank.tank_from_path(new_path)
        logger.debug("Extracted sgtk instance: '%r' from path: '%r'", tk, new_path)

    except tank.TankError, e:
        logger.exception("Could not execute tank_from_path('%s')" % new_path)
        OpenMaya.MGlobal.displayInfo("Shotgun: Engine cannot be started: %s" % e)
        # build disabled menu
        create_sgtk_disabled_menu(menu_name)
        return
Exemple #35
0
    def _on_project_load_callback(self, event):
        """
        Callback executed after project load in Hiero and Nuke Studio. This
        triggers an attempt to change the SGTK context to that of the newly
        opened project file.

        :param event:   The event object from Hiero/NS.
        """
        import hiero.core

        project = hiero.core.projects()[-1]
        script_path = project.path()

        # We're going to just skip doing anything if this fails
        # for any reason. It would be nice to swap to the error
        # menu item, but unfortunately a project open event is
        # triggered on launch when Hiero/Nuke Studio loads the
        # "Untitled" project from the Nuke install location. There
        # isn't a way to distinguish between that and something the
        # user purposefully opened, and we don't want to hose the
        # toolkit context with that.
        try:
            tk = tank.tank_from_path(script_path)

            # Extract a new context based on the file and change to that
            # context.
            new_context = tk.context_from_path(
                script_path,
                previous_context=self.context,
            )

            if new_context != self.context:
                tank.platform.change_context(new_context)
        except Exception:
            self.log_debug("Unable to determine context for file: %s" %
                           script_path)
Exemple #36
0
    def _startup_node_callback(self):
        """
        Callback that fires every time a node gets created.
        """
        try:
            # Look for the root node. This is created only when a new or existing
            # file is opened.
            if nuke.thisNode() != nuke.root():
                return

            if nuke.root().name() == "Root":
                # This is a file->new call, so base it on the context we
                # stored from the previous session.
                tk = tank.Tank(self.init_project_root)

                if self.init_context:
                    new_ctx = self.init_context
                else:
                    new_ctx = tk.context_empty()
            else:
                # This is a file->open call, so we can get the new context
                # from the file path that was opened.
                file_name = nuke.root().name()
                try:
                    tk = tank.tank_from_path(file_name)
                except tank.TankError, e:
                    self.engine.menu_generator.create_sgtk_disabled_menu(e)
                    return

                new_ctx = tk.context_from_path(
                    file_name,
                    previous_context=self.context,
                )

            # Now change the context for the engine and apps.
            self.change_context(new_ctx)
Exemple #37
0
import os
import sys
sys.path.append('Z:/_CORE/Tank/tank/install/core/python')

import tank
import maya.cmds as cmds

filePath = cmds.file(q=True, sn=True)
dirPath = os.path.dirname(filePath)
tk = tank.tank_from_path(dirPath)
#ctx = tk.context_from_path(path)

template_path = tk.templates['maya_shot_work']
data = template_path.get_fields(filePath)

fields = {
    "Episode": "000_dummy",
    "Shot": "0000",
    "Step": "Track",
    "name": "awesomeTrack",
    "version": 1
}
#print template_path.apply_fields(fields)
#print tank.util.find_publish(tk,filePath)
print tk.context_from_entity('TankPublishedFile', 32)

#engine = tank.platform.start_engine('tk-maya', tk, ctx)
#engine.init_app()

#print tank.platform.current_engine()
Exemple #38
0
def get_tk_object(api_script, api_key, root_pn):
    # connect to shotgun server
    tk_connect(api_script, api_key)
    # init a tk object
    return tank.tank_from_path(root_pn)
def run_engine_cmd(log, pipeline_config_root, context_items, command, using_cwd, args):
    """
    Launches an engine and potentially executes a command.

    :param log: logger
    :param pipeline_config_root: PC config location
    :param context_items: list of strings to describe context. Either ["path"],
                               ["entity_type", "entity_id"] or ["entity_type", "entity_name"]

    :param engine_name: engine to run
    :param command: command to run - None will display a list of commands
    :param using_cwd: Was the context passed based on the current work folder?
    """
    log.debug("")
    log.debug("Context items: %s" % str(context_items))
    log.debug("Command: %s" % command)
    log.debug("Command Arguments: %s" % args)
    log.debug("Sgtk Pipeline Config Location: %s" % pipeline_config_root)
    log.debug("Location of this script (__file__): %s" % os.path.abspath(__file__))

    log.info("")

    log.info("Welcome to the Shotgun Pipeline Toolkit!")
    log.info("For documentation, see https://toolkit.shotgunsoftware.com")

    # Now create a tk instance and a context if possible
    ctx = None
    tk = None

    if len(context_items) == 1:
        # path mode: e.g. tank /foo/bar/baz
        # create a context given a path as the input

        ctx_path = context_items[0]

        if using_cwd:
            log.info("Starting Toolkit for your current path '%s'" % ctx_path)
        else:
            log.info("Starting toolkit for path '%s'" % ctx_path)

        # context str is a path
        if pipeline_config_root is not None:
            # we are running a project specific tank command
            tk =  tank.tank_from_path(pipeline_config_root)

        else:
            # we are running a studio wide command
            try:
                tk = tank.tank_from_path(ctx_path)
            except TankError, e:
                # this path was not valid. That's ok - we just wont have a tank instance
                # when we run our commands later. This may be if we for example have
                # just run tank setup_project from any random folder
                log.debug("Instantiating Sgtk raised: %s" % e)

        if tk is not None:
            #
            # Right, there is a valid tk api handle, this means one of the following:
            #
            # - a project specific tank command guarantees a tk instance 
            #
            # - a studio level tank command which is targetting a path 
            #   which belongs to a toolkit project 
            # 
            # It is possible that someone has launched a project specific
            # tank command with a path which is outside the project.
            # In this case, initialize this to have the project context.   
            # We do this by attempting to construct a context and probing it
            
            ctx = tk.context_from_path(ctx_path)
            if ctx.project is None:
                # context could not be determined based on the path
                # revert back to the project context
                log.info("- The path is not associated with any Shotgun object.")
                log.info("- Falling back on default project settings.")
                project_id = tk.pipeline_configuration.get_project_id()
                ctx = tk.context_from_entity("Project", project_id)                
Exemple #40
0
    elif context_items[1].isdigit():

        # shotgun entity type and entity id!
        entity_type = context_items[0]
        entity_id = int(context_items[1])

        # note - tank from path method will validate that we are launching
        # from the right tank command etc.
        tk = tank.tank_from_entity(entity_type, entity_id)

        ctx = tk.context_from_entity(entity_type, entity_id)

    elif pipeline_config_root is not None:

        # shotgun entity type and entity name and we are running a local tank command
        tk =  tank.tank_from_path(pipeline_config_root)

        # now parse and resolve the entity name string
        entity_type = context_items[0]
        entity_search_token = context_items[1]
        project_id = tk.pipeline_configuration.get_project_id()
        entity_id = _resolve_shotgun_entity(log, entity_type, entity_search_token, project_id)
        ctx = tk.context_from_entity(entity_type, entity_id)

    else:

        # shotgun entity type and entity name and we are running a global tank command

        # now parse and resolve the entity name string
        entity_type = context_items[0]
        entity_search_token = context_items[1]
Exemple #41
0
    def test_project_setup(self, rw_dir, sg):
        # prepare the mock db - reuse the tank implementation as it's already what tank needs
        project = {      'type': 'Project',
                         'id': 1,
                         'sg_project_folder' : u'project_folder',
                         'sg_project_short_name' : 'testy',
                         'tank_name': None,
                         # 'name': u'project_name_™äü' } // tank can't do unicode, but we can
                         'name': u'project_name' }

        local_storage = {'code' : constants.PRIMARY_STORAGE_NAME,
                         'mac_path' : str(rw_dir),
                         'linux_path' : str(rw_dir), 
                         'windows_path' : str(rw_dir),
                         'id' : 1,
                         'type' : 'LocalStorage'}
        sg.set_entities([project, local_storage])
        sg.set_server_info(version_tuple=(4, 3, 9))

        for dummy in ('PublishedFile','PublishedFileType', 'PublishedFileDependency'):
            sg.set_entity_schema(dummy, dict())
        # end for each dummmy
        sg.set_entity_schema('Project', dict((k, None) for k in project.keys()))


        stp = SetupTankProject()

        pb, wb = self._setup_bootstrapper_at(rw_dir, 'btank')
        config_uri = self._default_configuration_tree()
        patch_installer = SetupProjectPatcher()
        settings = DictObject({'bootstrapper' : {'host_path' : pb, # will work on all platforms in our case
                                                 'posix_symlink_path' : pb, 
                                                 'windows_symlink_path' : wb,
                                                 'enforce_winlink_entry' : True,
                                                 'assume_smb_share' : False},
                               'tank' : {'windows_python2_interpreter_path' : 'c:\\foo',
                                         'configuration_uri': config_uri}})
        location = stp.handle_project_setup(sg, log, DictObject(project), settings)
        assert location.isdir(), "expected a valid tank instance as return value"


        # If it's correct, folder structure should be doable.
        tk = tank.tank_from_path(location)
        tk.create_filesystem_structure(project['type'], project['id'])


        ##############################
        # Test Event Engine Plugin ##
        ############################
        plugin = sgevents.TankProjectEventEnginePlugin(sg, log)

        ctx = bapp.main().context().push('project-setup-settings')
        ctx.settings().set_value_by_schema(setup_project_schema, settings)

        event = {'entity' : {'type' : 'Project', 'id' : project['id']}}
        event = DictObject(event)

        try:
            plugin.handle_event(sg, log, event)
        except OSError as err:
            assert err.errno == 17, "project directory can't be created as it exists"
# python

import re
import modo
import tank


scene = modo.scene.current()


tk = tank.tank_from_path(r"w:\rts")
temp = tk.template_from_path(scene.filename)
assetName = temp.get_fields(scene.filename)['Asset']
matgrp = assetName + "(matgrp)"



def createMatGrp():
	allmats = []
	groups = []

	for shader in scene.items(itype="defaultShader"):
		if shader.parent.name == "Render":
			allmats.append(shader)

	for mat in scene.items(itype="mask"):
		if re.match(assetName, mat.name):
			allmats.append(mat)

	scene.deselect()
Exemple #43
0
def refresh_engine(scene_name, prev_context):
    """
    refresh the current engine
    """

    engine = tank.platform.current_engine()

    if not engine:
        # If we don't have an engine for some reason then we don't have
        # anything to do.
        sys.stdout.write("refresh_engine | no engine!\n")
        return

    # This is a File->New call, so we just leave the engine in the current
    # context and move on.
    if scene_name in ("", "Untitled.spp"):
        if prev_context and prev_context != engine.context:
            engine.change_context(prev_context)

        # shotgun menu may have been removed, so add it back in if its not
        # already there.
        engine.create_shotgun_menu()
        return

    # determine the tk instance and ctx to use:
    tk = engine.sgtk

    # loading a scene file
    new_path = os.path.abspath(scene_name)

    # this file could be in another project altogether, so create a new
    # API instance.
    try:
        # and construct the new context for this path:
        tk = tank.tank_from_path(new_path)
        ctx = tk.context_from_path(new_path, prev_context)
    except tank.TankError, e:
        try:
            # could not detect context from path, will use the project context
            # for menus if it exists
            ctx = engine.sgtk.context_from_entity_dictionary(
                engine.context.project)
            message = ("Shotgun Substance Painter Engine could not detect "
                       "the context\n from the project loaded. "
                       "Shotgun menus will be reset \n"
                       "to the project '%s' "
                       "context."
                       "\n" % engine.context.project.get('name'))
            engine.show_warning(message)

        except tank.TankError, e:
            (exc_type, exc_value, exc_traceback) = sys.exc_info()
            message = ""
            message += "Shotgun Substance Painter Engine cannot be started:.\n"
            message += "Please contact [email protected]\n\n"
            message += "Exception: %s - %s\n" % (exc_type, exc_value)
            message += "Traceback (most recent call last):\n"
            message += "\n".join(traceback.format_tb(exc_traceback))

            # disabled menu, could not get project context
            engine.create_shotgun_menu(disabled=True)
            engine.show_error(message)
            return
Exemple #44
0
    elif context_items[1].isdigit():

        # shotgun entity type and entity id!
        entity_type = context_items[0]
        entity_id = int(context_items[1])

        # note - tank from path method will validate that we are launching
        # from the right tank command etc.
        tk = tank.tank_from_entity(entity_type, entity_id)

        ctx = tk.context_from_entity(entity_type, entity_id)

    elif pipeline_config_root is not None:

        # shotgun entity type and entity name and we are running a local tank command
        tk = tank.tank_from_path(pipeline_config_root)

        # now parse and resolve the entity name string
        entity_type = context_items[0]
        entity_search_token = context_items[1]
        project_id = tk.pipeline_configuration.get_project_id()
        entity_id = _resolve_shotgun_entity(log, entity_type,
                                            entity_search_token, project_id)
        ctx = tk.context_from_entity(entity_type, entity_id)

    else:

        # shotgun entity type and entity name and we are running a global tank command

        # now parse and resolve the entity name string
        entity_type = context_items[0]
def modoTk_AssetNameFromPath():
	scene = modo.scene.current()
	tk = tank.tank_from_path(r"w:\rts")
	temp = tk.template_from_path(scene.filename)
	return temp.get_fields(scene.filename)['Asset']
import os
import sys

sys.path.append("Z:/_CORE/Tank/tank/install/core/python")

import tank
import maya.cmds as cmds

filePath = cmds.file(q=True, sn=True)
dirPath = os.path.dirname(filePath)
tk = tank.tank_from_path(dirPath)
# ctx = tk.context_from_path(path)


template_path = tk.templates["maya_shot_work"]
data = template_path.get_fields(filePath)

fields = {"Episode": "000_dummy", "Shot": "0000", "Step": "Track", "name": "awesomeTrack", "version": 1}
# print template_path.apply_fields(fields)
# print tank.util.find_publish(tk,filePath)
print tk.context_from_entity("TankPublishedFile", 32)

# engine = tank.platform.start_engine('tk-maya', tk, ctx)
# engine.init_app()

# print tank.platform.current_engine()
Exemple #47
0
import tank
from maya import cmds
path = cmds.file(q=True, sn=True)
tk = tank.tank_from_path(path)
ctx = tk.context_from_path(path)
tank.platform.start_engine('tk-maya', tk, ctx)
Exemple #48
0
def run_engine_cmd(log, pipeline_config_root, context_items, command,
                   using_cwd, args):
    """
    Launches an engine and potentially executes a command.

    :param log: logger
    :param pipeline_config_root: PC config location
    :param context_items: list of strings to describe context. Either ["path"],
                               ["entity_type", "entity_id"] or ["entity_type", "entity_name"]

    :param engine_name: engine to run
    :param command: command to run - None will display a list of commands
    :param using_cwd: Was the context passed based on the current work folder?
    """
    log.debug("")
    log.debug("Context items: %s" % str(context_items))
    log.debug("Command: %s" % command)
    log.debug("Command Arguments: %s" % args)
    log.debug("Sgtk Pipeline Config Location: %s" % pipeline_config_root)
    log.debug("Location of this script (__file__): %s" %
              os.path.abspath(__file__))

    log.info("")

    log.info("Welcome to the Shotgun Pipeline Toolkit!")
    log.info("For documentation, see https://toolkit.shotgunsoftware.com")

    # Now create a tk instance and a context if possible
    ctx = None
    tk = None

    if len(context_items) == 1:
        # path mode: e.g. tank /foo/bar/baz
        # create a context given a path as the input

        ctx_path = context_items[0]

        if using_cwd:
            log.info("Starting Toolkit for your current path '%s'" % ctx_path)
        else:
            log.info("Starting toolkit for path '%s'" % ctx_path)

        # context str is a path
        if pipeline_config_root is not None:
            # we are running a project specific tank command
            tk = tank.tank_from_path(pipeline_config_root)

        else:
            # we are running a studio wide command
            try:
                tk = tank.tank_from_path(ctx_path)
            except TankError, e:
                # this path was not valid. That's ok - we just wont have a tank instance
                # when we run our commands later. This may be if we for example have
                # just run tank setup_project from any random folder
                log.debug("Instantiating Sgtk raised: %s" % e)

        if tk is not None:
            #
            # Right, there is a valid tk api handle, this means one of the following:
            #
            # - a project specific tank command guarantees a tk instance
            #
            # - a studio level tank command which is targetting a path
            #   which belongs to a toolkit project
            #
            # It is possible that someone has launched a project specific
            # tank command with a path which is outside the project.
            # In this case, initialize this to have the project context.
            # We do this by attempting to construct a context and probing it

            ctx = tk.context_from_path(ctx_path)
            if ctx.project is None:
                # context could not be determined based on the path
                # revert back to the project context
                log.info(
                    "- The path is not associated with any Shotgun object.")
                log.info("- Falling back on default project settings.")
                project_id = tk.pipeline_configuration.get_project_id()
                ctx = tk.context_from_entity("Project", project_id)