Beispiel #1
0
def init_shot_env():
    global config
    homedir = os.path.expanduser('~')
    logfile = ""
    if sys.platform == 'win32':
        logfile = os.path.join(homedir, 'AppData', 'Local', 'IHPipeline',
                               'nuke_launch.log')
    elif sys.platform == 'darwin':
        logfile = os.path.join(homedir, 'Library', 'Logs', 'IHPipeline',
                               'nuke_launch.log')
    elif sys.platform == 'linux2':
        logfile = os.path.join(homedir, 'Logs', 'IHPipeline',
                               'nuke_launch.log')
    if not os.path.exists(os.path.dirname(logfile)):
        os.makedirs(os.path.dirname(logfile))
    logFormatter = logging.Formatter(
        "%(asctime)s:[%(threadName)s]:[%(levelname)s]:%(message)s")
    log = logging.getLogger()
    log.setLevel(logging.DEBUG)
    fileHandler = logging.FileHandler(logfile)
    fileHandler.setFormatter(logFormatter)
    log.addHandler(fileHandler)
    consoleHandler = logging.StreamHandler()
    consoleHandler.setFormatter(logFormatter)
    log.addHandler(consoleHandler)

    script_path = os.path.normpath(nuke.root().name())
    script_path_lst = script_path.split(os.path.sep)
    path_idx = 0
    str_show_code = None
    str_shot = None
    str_seq = None

    try:
        str_show_code = os.environ['IH_SHOW_CODE']
    except KeyError:
        log.warning(
            "IH_SHOW_CODE environment variable not defined. Proceeding without environment."
        )
        return

    str_show_root = None
    try:
        str_show_root = os.environ['IH_SHOW_ROOT']
    except KeyError:
        log.warning(
            "IH_SHOW_ROOT environment variable not defined. Proceeding without environment."
        )
        return

    if not os.path.exists(str_show_root):
        log.warning("Show root directory does not exist at %s." %
                    str_show_root)
        return

    cfg_shot_dir = config.get(str_show_code, 'shot_dir_format')
    cfg_seq_dir = config.get(str_show_code, 'seq_dir_format')
    cfg_shot_regexp = config.get(str_show_code, 'shot_regexp')
    cfg_seq_regexp = config.get(str_show_code, 'sequence_regexp')

    # were we called from within shotgun?
    b_shotgun = False
    b_shotgun_res = False
    engine = None
    ctx = None
    entity = None
    for envvar in os.environ.keys():
        log.debug('ENVIRONMENT - %s: %s' % (envvar, os.environ[envvar]))

    try:
        toolkit_engine = os.environ['TANK_ENGINE']
        b_shotgun = True
        log.info(
            'Setting b_shotgun to True, os.environ[\'TANK_ENGINE\'] exists.')
    except:
        pass

    if not script_path.startswith(str_show_root):
        log.warning(
            "Unable to match show root directory with Nuke script path.")
        b_shotgun_res = True

    matchobject = re.search(cfg_shot_regexp, script_path)
    # make sure this file matches the shot pattern
    if not matchobject:
        log.warning(
            "This script name does not match the shot regular expression pattern for the show."
        )
        b_shotgun_res = True
    else:
        str_shot = matchobject.group(0)
        str_seq = re.search(cfg_seq_regexp, str_shot).group(0)

    if b_shotgun:
        log.info("Nuke executed from within Shotgun Desktop Integration.")
        ctx = None
        try:
            import sgtk
            ctx = sgtk.Context.deserialize(os.environ['TANK_CONTEXT'])
        except KeyError:
            log.error("Envionrment variable TANK_CONTEXT not found.")
        except ImportError:
            log.error("Unable to import sgtk.")
        if ctx == None:
            log.warning(
                "Nuke executed within Shotgun, but the context associated with the current engine is None."
            )
        else:
            log.info("Shotgun Toolkit Context Object:")
            log.info(ctx)
            entity = ctx.entity
            if entity == None:
                log.warning(
                    "Nuke executed within Shotgun, but the entity associated with the current context is None."
                )
            else:
                if entity['type'] != 'Shot':
                    log.warning(
                        "Nuke executed within Shotgun, but not in the context of a specific shot."
                    )
                else:
                    if b_shotgun_res:
                        log.info(
                            "Nuke executed within Shotgun, but no active script available. Setting sequence and shot from current engine context."
                        )
                        try:
                            str_shot = entity['name']
                            str_seq = re.search(cfg_seq_regexp,
                                                str_shot).group(0)
                        except KeyError:
                            log.error(
                                "For some reason, context provided by Shotgun to Nuke is %s. Unable to proceed."
                                % ctx)
                            str_shot = None

    if str_shot == None:
        log.warning(
            "Could not determine current shot from script name, or from database. Exiting init_shot_env()."
        )
        return

    str_seq = re.search(cfg_seq_regexp, str_shot).group(0)
    log.info('Sequence is %s' % str_seq)
    log.info('Shot is %s' % str_shot)
    str_seq_path = ""
    str_shot_path = ""
    str_show_path = str_show_root

    str_shot_path = cfg_shot_dir.format(show_root=str_show_path,
                                        pathsep=os.path.sep,
                                        sequence=str_seq,
                                        shot=str_shot)
    str_seq_path = cfg_seq_dir.format(show_root=str_show_path,
                                      pathsep=os.path.sep,
                                      sequence=str_seq)

    str_show = str_show_code

    log.info("Located show %s, path %s" % (str_show, str_show_path))
    log.info("Located sequence %s, path %s" % (str_seq, str_seq_path))
    log.info("Located shot %s, path %s" % (str_shot, str_shot_path))

    os.environ['SHOW'] = str_show
    os.environ['SHOW_PATH'] = str_show_path
    os.environ['SEQ'] = str_seq
    os.environ['SEQ_PATH'] = str_seq_path
    os.environ['SHOT'] = str_shot
    os.environ['SHOT_PATH'] = str_shot_path

    # add knobs to root, if they don't exist already
    root_knobs_dict = nuke.root().knobs()
    k_ih_tab = None
    k_ih_show = None
    k_ih_show_path = None
    k_ih_seq = None
    k_ih_seq_path = None
    k_ih_shot = None
    k_ih_shot_path = None
    try:
        k_ih_tab = root_knobs_dict['tab_inhouse']
    except KeyError:
        k_ih_tab = nuke.Tab_Knob('tab_inhouse', 'In-House')
        nuke.root().addKnob(k_ih_tab)
    try:
        k_ih_show = root_knobs_dict['txt_ih_show']
    except KeyError:
        k_ih_show = nuke.String_Knob('txt_ih_show', 'show')
        nuke.root().addKnob(k_ih_show)
    try:
        k_ih_show_path = root_knobs_dict['txt_ih_show_path']
    except KeyError:
        k_ih_show_path = nuke.String_Knob('txt_ih_show_path', 'show path')
        nuke.root().addKnob(k_ih_show_path)
    try:
        k_ih_seq = root_knobs_dict['txt_ih_seq']
    except KeyError:
        k_ih_seq = nuke.String_Knob('txt_ih_seq', 'sequence')
        nuke.root().addKnob(k_ih_seq)
    try:
        k_ih_seq_path = root_knobs_dict['txt_ih_seq_path']
    except KeyError:
        k_ih_seq_path = nuke.String_Knob('txt_ih_seq_path', 'sequence path')
        nuke.root().addKnob(k_ih_seq_path)
    try:
        k_ih_shot = root_knobs_dict['txt_ih_shot']
    except KeyError:
        k_ih_shot = nuke.String_Knob('txt_ih_shot', 'shot')
        nuke.root().addKnob(k_ih_shot)
    try:
        k_ih_shot_path = root_knobs_dict['txt_ih_shot_path']
    except KeyError:
        k_ih_shot_path = nuke.String_Knob('txt_ih_shot_path', 'shot path')
        nuke.root().addKnob(k_ih_shot_path)
    k_ih_show.setValue(str_show)
    k_ih_show_path.setValue(str_show_path)
    k_ih_seq.setValue(str_seq)
    k_ih_seq_path.setValue(str_seq_path)
    k_ih_shot.setValue(str_shot)
    k_ih_shot_path.setValue(str_shot_path)

    # remove old favorite directories if they exist
    nuke_prefs_file = os.path.join(os.path.expanduser("~"), '.nuke',
                                   'FileChooser_Favorites.pref')
    if os.path.exists(nuke_prefs_file):
        with open(nuke_prefs_file) as npf:
            for line in npf:
                if line.startswith('add_favorite_dir'):
                    line_array = shlex.split(line)
                    fav_name = line_array[1]
                    if fav_name.startswith('SHOW') or fav_name.startswith(
                            'SEQ') or fav_name.startswith('SHOT'):
                        nuke.removeFavoriteDir(fav_name)

    # add favorite directories in file browser
    # TODO: pull these values out of the show config file
    nuke.addFavoriteDir("SHOW", '[getenv IH_SHOW_ROOT]')
    if os.path.exists(os.path.join(str_show_root, 'SHARED')):
        nuke.addFavoriteDir("SHOW/SHARED",
                            os.path.join('[getenv IH_SHOW_ROOT]', 'SHARED'))
    if os.path.exists(os.path.join(str_show_root, 'ref')):
        nuke.addFavoriteDir("SHOW/ref",
                            os.path.join('[getenv IH_SHOW_ROOT]', 'ref'))
    if 'SEQUENCE' in cfg_shot_dir:
        nuke.addFavoriteDir("SEQ", '[getenv SEQ_PATH]')
        if os.path.exists(os.path.join(str_seq_path, 'SHARED')):
            nuke.addFavoriteDir("SEQ/SHARED",
                                os.path.join('[getenv SEQ_PATH]', 'SHARED'))
        if os.path.exists(os.path.join(str_seq_path, 'ref')):
            nuke.addFavoriteDir("SEQ/ref",
                                os.path.join('[getenv SEQ_PATH]', 'ref'))
    nuke.addFavoriteDir("SHOT", '[getenv SHOT_PATH]')

    # shot directories
    try:
        l_nukescript_dir = config.get('shot_structure',
                                      'nukescript_dir').split('{pathsep}')
        l_plate_dir = config.get('shot_structure',
                                 'plate_dir').split('{pathsep}')
        l_precomp_dir = config.get('shot_structure',
                                   'precomp_dir').split('{pathsep}')
        l_rendercomp_dir = config.get('shot_structure',
                                      'rendercomp_dir').split('{pathsep}')
        l_element_dir = config.get('shot_structure',
                                   'element_dir').split('{pathsep}')
        l_renderelem_dir = config.get('shot_structure',
                                      'renderelem_dir').split('{pathsep}')
        l_mograph_dir = config.get('shot_structure',
                                   'mograph_dir').split('{pathsep}')
        l_ref_dir = config.get('shot_structure', 'ref_dir').split('{pathsep}')
        l_nukescript_dir.insert(0, r'[getenv SHOT_PATH]')
        l_plate_dir.insert(0, r'[getenv SHOT_PATH]')
        l_precomp_dir.insert(0, r'[getenv SHOT_PATH]')
        l_rendercomp_dir.insert(0, r'[getenv SHOT_PATH]')
        l_element_dir.insert(0, r'[getenv SHOT_PATH]')
        l_renderelem_dir.insert(0, r'[getenv SHOT_PATH]')
        l_mograph_dir.insert(0, r'[getenv SHOT_PATH]')
        l_ref_dir.insert(0, r'[getenv SHOT_PATH]')
        log.info(
            'Successfully retrieved Shot directory structure from config file.'
        )
        log.info(l_nukescript_dir)
        log.info(os.path.sep.join(l_nukescript_dir))
        nuke.addFavoriteDir("SHOT/nuke", os.path.sep.join(l_nukescript_dir))
        nuke.addFavoriteDir("SHOT/plates", os.path.sep.join(l_plate_dir))
        nuke.addFavoriteDir("SHOT/precomp", os.path.sep.join(l_precomp_dir))
        nuke.addFavoriteDir("SHOT/comp", os.path.sep.join(l_rendercomp_dir))
        nuke.addFavoriteDir("SHOT/elements", os.path.sep.join(l_element_dir))
        nuke.addFavoriteDir("SHOT/renders", os.path.sep.join(l_renderelem_dir))
        nuke.addFavoriteDir("SHOT/mograph", os.path.sep.join(l_mograph_dir))
        nuke.addFavoriteDir("SHOT/ref", os.path.sep.join(l_ref_dir))
    except Exception as e:
        log.warning(
            "Caught exception %s when attempting to extract shot structure from the config file. Reverting to hard-coded shortcut paths."
            % type(e).__name__)
        log.warning(traceback.format_exc())
        nuke.addFavoriteDir("SHOT/nuke",
                            os.path.join('[getenv SHOT_PATH]', 'nuke'))
        nuke.addFavoriteDir(
            "SHOT/plates", os.path.join('[getenv SHOT_PATH]', 'pix', 'plates'))
        nuke.addFavoriteDir(
            "SHOT/precomp", os.path.join('[getenv SHOT_PATH]', 'pix',
                                         'precomp'))
        nuke.addFavoriteDir("SHOT/comp",
                            os.path.join('[getenv SHOT_PATH]', 'pix', 'comp'))
        nuke.addFavoriteDir(
            "SHOT/elements",
            os.path.join('[getenv SHOT_PATH]', 'pix', 'elements'))
        nuke.addFavoriteDir(
            "SHOT/renders", os.path.join('[getenv SHOT_PATH]', 'pix',
                                         'renders'))
        nuke.addFavoriteDir(
            "SHOT/mograph", os.path.join('[getenv SHOT_PATH]', 'pix',
                                         'mograph'))
        nuke.addFavoriteDir("SHOT/ref",
                            os.path.join('[getenv SHOT_PATH]', 'ref'))
Beispiel #2
0
    def process(self):
        inputs = []
        outputs = []
        instance = nuke.toNode(self.data["subset"])
        selected_node = None

        # use selection
        if (self.options or {}).get("useSelection"):
            nodes = self.nodes

            if not (len(nodes) < 2):
                msg = ("Select only one node. The node "
                       "you want to connect to, "
                       "or tick off `Use selection`")
                self.log.error(msg)
                nuke.message(msg)

            if len(nodes) == 0:
                msg = (
                    "No nodes selected. Please select a single node to connect"
                    " to or tick off `Use selection`")
                self.log.error(msg)
                nuke.message(msg)

            selected_node = nodes[0]
            inputs = [selected_node]
            outputs = selected_node.dependent()

            if instance:
                if (instance.name() in selected_node.name()):
                    selected_node = instance.dependencies()[0]

        # if node already exist
        if instance:
            # collect input / outputs
            inputs = instance.dependencies()
            outputs = instance.dependent()
            selected_node = inputs[0]
            # remove old one
            nuke.delete(instance)

        # recreate new
        write_data = {
            "nodeclass": self.n_class,
            "families": [self.family],
            "avalon": self.data,
            "creator": self.__class__.__name__
        }

        if self.presets.get('fpath_template'):
            self.log.info("Adding template path from preset")
            write_data.update(
                {"fpath_template": self.presets["fpath_template"]})
        else:
            self.log.info("Adding template path from plugin")
            write_data.update({
                "fpath_template": ("{work}/prerenders/nuke/{subset}"
                                   "/{subset}.{frame}.{ext}")
            })

        self.log.info("write_data: {}".format(write_data))

        write_node = lib.create_write_node(self.data["subset"],
                                           write_data,
                                           input=selected_node,
                                           prenodes=[],
                                           review=False)

        # relinking to collected connections
        for i, input in enumerate(inputs):
            write_node.setInput(i, input)

        write_node.autoplace()

        for output in outputs:
            output.setInput(0, write_node)

        # open group node
        write_node.begin()
        for n in nuke.allNodes():
            # get write node
            if n.Class() in "Write":
                w_node = n
        write_node.end()

        # add inner write node Tab
        write_node.addKnob(nuke.Tab_Knob("WriteLinkedKnobs"))

        # linking knobs to group property panel
        linking_knobs = ["channels", "___", "first", "last", "use_limit"]
        for k in linking_knobs:
            if "___" in k:
                write_node.addKnob(nuke.Text_Knob(''))
            else:
                lnk = nuke.Link_Knob(k)
                lnk.makeLink(w_node.name(), k)
                lnk.setName(k.replace('_', ' ').capitalize())
                lnk.clearFlag(nuke.STARTLINE)
                write_node.addKnob(lnk)

        return write_node
Beispiel #3
0
def dg_PerspLines_AlignCamera():
    nodes = nuke.selectedNodes()
    if not len(nodes) == 2:
        nuke.message(
            'Illegal amount of selected nodes.\nPlease select exactly two dg_PerspLines nodes'
        )
        return
    for n in nodes:
        #if not n.Class()=='dg_PerspLines':
        # Gizmos were converted to groups
        ##### workaround start #####
        nType = None
        try:
            nType = n['nodeType'].value()
        except:
            pass
        if not nType == 'dg_PerspLines':
            ##### workaround end #####
            nuke.message('One of selected nodes is not dg_PerspLines')
            return

    V1 = nodes[0]['PT'].value()
    V2 = nodes[1]['PT'].value()

    K = (V2[1] - V1[1]) / (V2[0] - V1[0])
    print K

    Oi = [nodes[0].width() / 2, nodes[0].height() / 2]
    print Oi

    Vix = (1 / K * Oi[0] + Oi[1] + K * V1[0] - V1[1]) / (K + 1 / K)
    Viy = -1 / K * (Vix - Oi[0]) + Oi[1]
    Vi = [Vix, Viy]
    print Vi

    ViV1 = sqrt(pow(Vi[0] - V1[0], 2) + pow(Vi[1] - V1[1], 2))
    ViV2 = sqrt(pow(Vi[0] - V2[0], 2) + pow(Vi[1] - V1[1], 2))

    print ViV1
    print ViV2

    OcVi = sqrt(ViV1 * ViV2)
    OiVi = sqrt(pow(Oi[0] - Vi[0], 2) + pow(Oi[1] - Vi[1], 2))
    print OcVi
    print OiVi

    f = sqrt(pow(OcVi, 2) - pow(OiVi, 2))
    print f

    f_scale = sqrt(pow(Oi[0] * 2, 2) + pow(Oi[1] * 2, 2)) / f

    camNode = nuke.createNode('Camera', inpanel=False)
    camNode['tile_color'].setValue(884320767)

    camNode['focal'].setValue(
        sqrt(
            pow(camNode['haperture'].value(), 2) +
            pow(camNode['vaperture'].value(), 2)) / f_scale)

    Rx = atan((Oi[1] - Vi[1]) / f) * 180 / PI
    Ry = atan(min(ViV1, ViV2) / f) * 180 / PI
    Ry2 = atan(max(ViV1, ViV2) / f) * 180 / PI
    Rz = -atan(K) * 180 / PI

    camNode['rotate'].setValue([Rx, Ry, Rz])
    camNode['translate'].setValue([0, 1, 0])

    k = nuke.Double_Knob('Ry')
    k.setValue(Ry2)
    camNode.addKnob(nuke.Tab_Knob('alternate'))
    camNode.addKnob(k)

    k = nuke.PyScript_Knob('swap')
    k.setCommand('dg_PerspLines_swap(nuke.thisNode())')
    camNode.addKnob(k)
Beispiel #4
0
def link_transform(target_node):
    """
    Utility function for link_transform: creates linked transform node
    """
    grid_x = int(nuke.toNode('preferences').knob('GridWidth').value())
    grid_y = int(nuke.toNode('preferences').knob('GridHeight').value())

    target_name = target_node.name()
    nclass = target_node.Class()
    if "Tracker" not in nclass and "Transform" not in nclass:
        print("Must select Tracker or Transform node!")
        return

    target_node.setSelected(False)
    # Create linked Transform Node
    trans = nuke.createNode('Transform')
    trans.setName('TransformLink')
    trans.setSelected(True)
    trans.knob('help').setValue(
        "<b>TransformLink</b>\n\nA Transform node with options for linking to a Tracker or a Transform node. \n\nAllows you to set a seperate identity transform frame from the linked Tracker. Select the link target and click 'Set Target', or set the link target by name. You can also bake the expression link into keyframes if you want it independant from the target node. \n\nThe transform Matchmoves or Stabilizes depending on what the parent tracker node is set to, but you can invert this by enabling the 'invert' checkbox."
    )
    trans.knob('label').setValue(target_node.name())
    trans.setXYpos(target_node.xpos() - grid_x * 0,
                   target_node.ypos() + grid_y * 2)
    trans.addKnob(nuke.Tab_Knob('TrackLink'))
    trans.addKnob(nuke.Int_Knob('reference_frame', 'reference frame'))

    if 'Tracker' in nclass:
        trans.knob('reference_frame').setValue(
            int(target_node.knob('reference_frame').value()))
    else:
        trans.knob('reference_frame').setValue(nuke.frame())

    trans.addKnob(
        nuke.PyScript_Knob('identity_to_curframe', 'Set to Current Frame'))
    trans.knob('identity_to_curframe').setTooltip(
        "Set identity frame to current frame.")
    trans.knob('identity_to_curframe').setCommand(
        "nuke.thisNode().knob('reference_frame').setValue(nuke.frame())")
    trans.knob('identity_to_curframe').setFlag(nuke.STARTLINE)
    trans.addKnob(nuke.PyScript_Knob('bake_link', 'Bake Expression Links'))

    trans.knob('bake_link').setTooltip('Bake expression links to keyframes')
    trans.knob('bake_link').setCommand('''import tools.expressions
node = nuke.thisNode()
try:
    target_node = nuke.toNode(node['link_target'].value())
    first_frame = int(target_node['translate'].animation(0).keys()[0].x)
    last_frame = int(target_node['translate'].animation(0).keys()[-1].x)
except:
    first_frame = nuke.root()['first_frame']
    last_frame = nuke.root()['last_framed']
tools.expressions.bake([node], first_frame, last_frame)''')

    # add target node as a knob so we can use it later
    trans.addKnob(nuke.Text_Knob("link_target"))
    target_node_knob = trans['link_target']
    target_node_knob.setValue(target_node.name())
    target_node_knob.setVisible(False)

    # # Link knobs
    trans.knob('translate').setExpression(
        'parent.{0}.translate - parent.{0}.translate(reference_frame)'.format(
            target_name))
    trans.knob('rotate').setExpression(
        'parent.{0}.rotate - parent.{0}.rotate(reference_frame)'.format(
            target_name))
    trans.knob('scale').setExpression(
        'parent.{0}.scale / parent.{0}.scale(reference_frame)'.format(
            target_name))
    trans.knob('skewX').setExpression(
        'parent.{0}.skewX - parent.{0}.skewX(reference_frame)'.format(
            target_name))
    trans.knob('skewY').setExpression(
        'parent.{0}.skewY - parent.{0}.skewY(reference_frame)'.format(
            target_name))
    trans.knob('center').setExpression(
        'parent.{0}.center+parent.{0}.translate(reference_frame)'.format(
            target_name))
Beispiel #5
0
def DuplicateGeometry():
    for n in nuke.selectedNodes():
        if n.Class() == "Cube" or n.Class() == "Card2" or n.Class(
        ) == "Cylinder" or n.Class() == "Sphere" or n.Class() == "ReadGeo2":

            class dialog(object):
                window = nuke.Panel("Duplicate Geometry")
                window.addSingleLineInput("Clones:", 10)

            dialogResult = dialog.window.show()

            if dialogResult == 1:
                nuke.tprint("Duplicating Geometry...")
            else:
                nuke.tprint("Canceled")
                return None

            nodeYPos = n.ypos()
            nodeXPos = n.xpos()

            controlNode = nuke.createNode("NoOp")
            controlNode.knob("name").setValue("DuplicateGeometry")
            controlNode.knob('xpos').setValue(nodeXPos + 150)
            controlNode.knob('ypos').setValue(nodeYPos)

            controlNode.addKnob(nuke.Tab_Knob('Controls'))

            code = 'import random\nfor a in range(%s):\n a += 1\n TKnob = \"Translate_\" + str(a)\n RKnob = \"Rotate_\" + str(a)\n SKnob = \"Scale_\" + str(a)\n nuke.toNode(\"DuplicateGeometry\").knob(TKnob).setValue(random.uniform(-1, 1), 0)\n nuke.toNode(\"DuplicateGeometry\").knob(TKnob).setValue(random.uniform(-1, 1), 1)\n nuke.toNode(\"DuplicateGeometry\").knob(TKnob).setValue(random.uniform(-1, 1), 2)\n nuke.toNode(\"DuplicateGeometry\").knob(RKnob).setValue(random.uniform(-1, 1), 0)\n nuke.toNode(\"DuplicateGeometry\").knob(RKnob).setValue(random.uniform(-1, 1), 1)\n nuke.toNode(\"DuplicateGeometry\").knob(RKnob).setValue(random.uniform(-1, 1), 2)\n nuke.toNode(\"DuplicateGeometry\").knob(SKnob).setValue(random.uniform(-1, 1), 0)\n nuke.toNode(\"DuplicateGeometry\").knob(SKnob).setValue(random.uniform(-1, 1), 1)\n nuke.toNode(\"DuplicateGeometry\").knob(SKnob).setValue(random.uniform(-1, 1), 2)' % int(
                dialog.window.value("Clones:"))

            controlNode.addKnob(
                nuke.PyScript_Knob('Randomize', 'Randomize', code))

            controlNode.addKnob(nuke.XYZ_Knob('Translate'))
            controlNode.addKnob(nuke.XYZ_Knob('Rotate'))
            controlNode.addKnob(nuke.XYZ_Knob('Scale'))

            controlNode.addKnob(nuke.XYZ_Knob('TranslateRandom'))
            controlNode.addKnob(nuke.XYZ_Knob('RotateRandom'))
            controlNode.addKnob(nuke.XYZ_Knob('ScaleRandom'))

            for a in range(int(dialog.window.value("Clones:"))):
                a += 1
                TKnob = "Translate_" + str(a)
                RKnob = "Rotate_" + str(a)
                SKnob = "Scale_" + str(a)
                controlNode.addKnob(nuke.XYZ_Knob(TKnob))
                controlNode.addKnob(nuke.XYZ_Knob(RKnob))
                controlNode.addKnob(nuke.XYZ_Knob(SKnob))

                controlNode.knob(TKnob).setVisible(bool(0))
                controlNode.knob(RKnob).setVisible(bool(0))
                controlNode.knob(SKnob).setVisible(bool(0))

                controlNode.knob(TKnob).setValue(random.uniform(-1, 1), 0)
                controlNode.knob(TKnob).setValue(random.uniform(-1, 1), 1)
                controlNode.knob(TKnob).setValue(random.uniform(-1, 1), 2)
                controlNode.knob(RKnob).setValue(random.uniform(-1, 1), 0)
                controlNode.knob(RKnob).setValue(random.uniform(-1, 1), 1)
                controlNode.knob(RKnob).setValue(random.uniform(-1, 1), 2)
                controlNode.knob(SKnob).setValue(random.uniform(-1, 1), 0)
                controlNode.knob(SKnob).setValue(random.uniform(-1, 1), 1)
                controlNode.knob(SKnob).setValue(random.uniform(-1, 1), 2)

            scene = nuke.createNode("Scene")
            scene.knob('xpos').setValue(nodeXPos + 300)
            scene.knob('ypos').setValue(nodeYPos + 150)
            nuke.extractSelected()

            for i in range(int(dialog.window.value("Clones:"))):
                transform = nuke.createNode("TransformGeo")
                nuke.extractSelected()
                transform.knob('xpos').setValue(nodeXPos + 150)
                transform.knob('ypos').setValue(nodeYPos + (150 * (i + 1)))
                transform.setInput(0, n)

                scene.setInput(i, transform)

                vTranslate_0 = "DuplicateGeometry.Translate * " + str(
                    i + 1
                ) + " + DuplicateGeometry.TranslateRandom * DuplicateGeometry.Translate_" + str(
                    i + 1)
                vTranslate_1 = "DuplicateGeometry.Translate * " + str(
                    i + 1
                ) + " + DuplicateGeometry.TranslateRandom * DuplicateGeometry.Translate_" + str(
                    i + 1)
                vTranslate_2 = "DuplicateGeometry.Translate * " + str(
                    i + 1
                ) + " + DuplicateGeometry.TranslateRandom * DuplicateGeometry.Translate_" + str(
                    i + 1)
                vRotate_0 = "DuplicateGeometry.Rotate * " + str(
                    i + 1
                ) + " + DuplicateGeometry.RotateRandom * DuplicateGeometry.Rotate_" + str(
                    i + 1)
                vRotate_1 = "DuplicateGeometry.Rotate * " + str(
                    i + 1
                ) + " + DuplicateGeometry.RotateRandom * DuplicateGeometry.Rotate_" + str(
                    i + 1)
                vRotate_2 = "DuplicateGeometry.Rotate * " + str(
                    i + 1
                ) + " + DuplicateGeometry.RotateRandom * DuplicateGeometry.Rotate_" + str(
                    i + 1)
                vScale_0 = "1 + DuplicateGeometry.Scale * " + str(
                    i + 1
                ) + " + DuplicateGeometry.ScaleRandom * DuplicateGeometry.Scale_" + str(
                    i + 1)
                vScale_1 = "1 + DuplicateGeometry.Scale * " + str(
                    i + 1
                ) + " + DuplicateGeometry.ScaleRandom * DuplicateGeometry.Scale_" + str(
                    i + 1)
                vScale_2 = "1 + DuplicateGeometry.Scale * " + str(
                    i + 1
                ) + " + DuplicateGeometry.ScaleRandom * DuplicateGeometry.Scale_" + str(
                    i + 1)

                transform.knob("translate").setExpression(vTranslate_0, 0)
                transform.knob("translate").setExpression(vTranslate_1, 1)
                transform.knob("translate").setExpression(vTranslate_2, 2)
                transform.knob("rotate").setExpression(vRotate_0, 0)
                transform.knob("rotate").setExpression(vRotate_1, 1)
                transform.knob("rotate").setExpression(vRotate_2, 2)
                transform.knob("scaling").setExpression(vScale_0, 0)
                transform.knob("scaling").setExpression(vScale_1, 1)
                transform.knob("scaling").setExpression(vScale_2, 2)
Beispiel #6
0
    'box.t': 0.13,
    'alignment': 'right',
    'font': 0.4
}]

# -------------------------------- GROUP CREATION -------------------------------- #

# GROUP
g_count = 1
while nuke.toNode(GROUP_NAME + str(g_count)):
    g_count += 1

g = nuke.nodes.Group(name=GROUP_NAME + str(g_count))

# INPUTS TAB
stamp_info_tab = nuke.Tab_Knob(KNOB_BASE_NAME + 'stamp_input_tab',
                               'Stamp input')
g.addKnob(stamp_info_tab)

shot_info_label = nuke.Text_Knob(KNOB_BASE_NAME + 'shot_info_label', '',
                                 '<font color=white size=5>Shot information')
g.addKnob(shot_info_label)

seq_name_input = nuke.String_Knob(SEQ_INPUT_NAME, 'Seq:', DEFAULT_SEQ)
g.addKnob(seq_name_input)

shot_num_input = nuke.Int_Knob(SHOT_INPUT_NAME, '     Shot: ', DEFAULT_SHOT)
shot_num_input.clearFlag(nuke.STARTLINE)
g.addKnob(shot_num_input)

artist_name_input = nuke.String_Knob(ARTIST_INPUT_NAME, 'Artist:',
                                     current_user)
Beispiel #7
0
def preferencesCreatedCallback():
    p = nuke.toNode('preferences')

    #Setup J_Ops prefs knobs if they don't exist.
    try:
        jopsKnobsPresent = p["J_Ops"]
    except (SyntaxError, NameError):
        k = nuke.Tab_Knob("J_Ops")
        k.setFlag(nuke.ALWAYS_SAVE)
        p.addKnob(k)

        v = nuke.Double_Knob("j_ops_ver", "j_ops_ver")
        v.setFlag(nuke.ALWAYS_SAVE)
        v.setFlag(nuke.INVISIBLE)
        v.setValue(2.0101)
        p.addKnob(v)

        k = nuke.Boolean_Knob("j_ops_enable_drop", "Improved drag and drop")
        k.setFlag(nuke.ALWAYS_SAVE)
        k.setFlag(nuke.STARTLINE)
        k.setValue(1.0)
        k.setTooltip(
            "Enable/disable a somewhat improved drag and drop behaviour. Requires Nuke restart to take effect. Adds creation of geo, camera, light and vectorfield nodes based on incoming file extensions, as well as support for sequences when dropping folders onto DAG."
        )
        p.addKnob(k)

        k = nuke.Boolean_Knob("j_ops_enable_bookmark", "DAG bookmarks")
        k.setFlag(nuke.ALWAYS_SAVE)
        k.setFlag(nuke.STARTLINE)
        k.setValue(1.0)
        k.setTooltip(
            "Enable/disable DAG bookmarks, allowing storing and recalling of particular DAG locations and zoom settings, for easy navigation around a script. Requires Nuke restart to take effect. Adds Python-DAG Bookmarks menu to J_Ops toolbar, offering access via mouse, tab menu, or hotkeys."
        )
        p.addKnob(k)

        k = nuke.Text_Knob("j_ops_dropdivider_label", "Drag And Drop")
        k.setFlag(nuke.ALWAYS_SAVE)
        p.addKnob(k)

        k = nuke.Boolean_Knob("j_ops_drop_recurse", "Recurse directories")
        k.setFlag(nuke.ALWAYS_SAVE)
        k.setValue(1.0)
        k.setTooltip(
            "Enable/disable recursion into directories dropped on DAG. When enabled will result in entire directory structure being imported into DAG, when disabled only the directory dropped will be imported (ie none of its sub directories)"
        )
        p.addKnob(k)

    #Check for preference setting, and if drop enabled add its callback/
    dropEnabled = False
    try:
        dropEnabled = nuke.toNode(
            'preferences')["j_ops_enable_drop"].getValue()
    except (SyntaxError, NameError):
        pass

    if dropEnabled == True:
        nukescripts.drop.addDropDataCallback(jopsDropHandler)

    #Check for preference setting, and if drop enabled add its callback/
    bookmarkEnabled = False
    try:
        bookmarkEnabled = nuke.toNode(
            'preferences')["j_ops_enable_bookmark"].getValue()
    except (SyntaxError, NameError):
        pass

    if bookmarkEnabled == True:
        jopsBookmarkAddMenus()
Beispiel #8
0
    def __init__(self):
        nukescripts.PythonPanel.__init__( self, "Start a Script")
        self.first_tab = nuke.Tab_Knob("START", "Start")
        self.second_tab = nuke.Tab_Knob("OPEN", "Open")
        #Create Knobs
        self.Text = nuke.Text_Knob('Start', 'Start a new Script')

        #self.Text()['label'].setValue("<center> <h1>Heading 1</h1><h2>Start a new Script</h2> </center>>")
        self.gap = nuke.Text_Knob("divName","","")

        #Change name input
        self.name = nuke.String_Knob('Skript-Name', 'Name')
        
        if nuke.root()['name'].value() == '':
             self.name.setValue('Shot0000_V01_TTMMJJ.nk')
        else:
             self.name.setValue(nuke.root()['name'].value())
             
        self.proj = nuke.File_Knob('directory', 'Speicherort')

        ########################Please insert your standard File Location Folder (Watch out for "/" at the end)#############
        if nuke.root()['project_directory'].value() == '':
             self.proj.setValue('J:/Working_Volume/WIP/002_LuN_Comp/20191118_VFX_Paket_Robin/02.2_Dorf/LuN_VFX_02.2_Dorf/')
        else:
             self.proj.setValue(nuke.root()['project_directory'].value())
        ########################
        
        
        self.set = nuke.PyScript_Knob('SET', 'Set')
        self.set.setFlag(nuke.STARTLINE)

        self.save = nuke.Script_Knob('SAVE', 'Save')
        self.save.setFlag(nuke.STARTLINE)

        self.cancel = nuke.PyScript_Knob('CANCEL', 'CANCEL')

        self.Ordner = nuke.Script_Knob('Ordner', 'Ordner anlegen')

        self.format = nuke.Format_Knob('Resolutions')

        self.realFPS = nuke.Int_Knob('Frames', 'fps')
        self.realFPS.setValue(25)

        self.label = nuke.Multiline_Eval_String_Knob('Notes', 'Notizen', '' )
        self.label.setValue('Changes/ToDo-Liste')
        
        self.bdropt = nuke.Text_Knob('BDROPT', 'Choose your Backdrops')

        self.bdrop1 = nuke.Boolean_Knob('BDROP1','Input+Output')
        self.bdrop1.setFlag(nuke.STARTLINE)
        self.bdrop2 = nuke.Boolean_Knob('BDROP2','CG_Passes')
        self.bdrop2.setFlag(nuke.STARTLINE)
        self.bdrop3 = nuke.Boolean_Knob('BDROP3','Blacklevels')
        self.bdrop3.setFlag(nuke.STARTLINE)
        self.bdrop4 = nuke.Boolean_Knob('BDROP4','POST')
        self.bdrop4.setFlag(nuke.STARTLINE)
        self.bdrop5 = nuke.Boolean_Knob('BDROP5','ColourCorrection')
        self.bdrop5.setFlag(nuke.STARTLINE)
        self.bdrop6 = nuke.Boolean_Knob('BDROP6','Keying')
        self.bdrop6.setFlag(nuke.STARTLINE)
        self.bdrop7 = nuke.Boolean_Knob('BDROP7','Despill')
        self.bdrop7.setFlag(nuke.STARTLINE)
        self.bdrop8 = nuke.Boolean_Knob('BDROP8','Camera Projection')
        self.bdrop8.setFlag(nuke.STARTLINE)
        self.gap2 = nuke.Text_Knob("divName","","")
        self.gap3 = nuke.Text_Knob("divName","","")

        self.Delete = nuke.PyScript_Knob("DELETE", "Delete all Backdrops")
   
        #######################################################################
        #######################################################################Second Tab: Open a old script

        self.opentxt = nuke.Text_Knob('OPENTXT', 'Open a Script')
        self.opentxtgap = nuke.Text_Knob("divName3","","")
        self.Proj_Folder = nuke.File_Knob("PROJECT", "Project folder with all Shots")
        ############################### Set overall Projects Folder here: 
        self.Proj_Folder.setValue('J:/Working_Volume/WIP/002_LuN_Comp/20191118_VFX_Paket_Robin/02.2_Dorf/LuN_VFX_02.2_Dorf/')
        ###############################
        

        path = self.Proj_Folder.value()
        self.CheckforFiles = nuke.PyScript_Knob("CheckFiles", "Find all Scripts")
        self.Load = nuke.PyScript_Knob("OPEN", "   Open Script  ")
        self.Load.setFlag(nuke.STARTLINE)
        
        files = []
        
        self.ChooseScript = nuke.Enumeration_Knob("AllScripts", "All Found Scripts",files)
        self.ChooseScript.setFlag(nuke.STARTLINE)

        self.listcount = nuke.Text_Knob ('List-Text', 'Total count of Nuke-Files')
        self.listcount.setFlag(nuke.STARTLINE)
        
        self.cancel2 = nuke.PyScript_Knob('CANCEL2', 'CANCEL')
    	   
        self.bgap = nuke.Text_Knob("DIV_2",'', '')
        self.filter = nuke.String_Knob('FILTER', 'Filter for this String')
        
        
        #Window_Settings
        self.setMinimumSize(700, 750)
        #add Knobs
        for k in (self.first_tab, self.Text, self.gap, self.name, self.proj, self.realFPS, self.format, self.label, self.set, self.Ordner,self.bdropt, self.bdrop1,self.bdrop2,self.bdrop3,self.bdrop4,self.bdrop5,self.bdrop6,self.bdrop7,self.bdrop8,self.gap2,self.Delete, self.gap3, self.save, self.cancel, self.second_tab, self.opentxt, self.opentxtgap, self.Proj_Folder,self.filter, self. CheckforFiles, self.ChooseScript,self.bgap, self.listcount, self.Load, self.cancel2):
            self.addKnob( k )
Beispiel #9
0
    def SequenceLoader(self):
        '''main function construct the image group'''

        dir_renderVersion = joinPath(self.lgtPath.text(),
                                     self.renderVersion_mu.currentText())
        if dir_renderVersion == None:
            nuke.message("Import Canceled")
        else:
            name_renderVersion = os.path.basename(
                dir_renderVersion.rstrip('/'))  # TIO_orbit_1k_v001
            ver_renderVersion = int(name_renderVersion.split('_v')[1])
            RGBA = 'beauty'

            # Building Image Group
            ls_aov = getAOVs(dir_renderVersion)
            for p in ls_aov[ls_aov.keys()[0]]:
                nuke.Layer(p, [
                    '%s.red' % p,
                    '%s.green' % p,
                    '%s.blue' % p,
                    '%s.alpha' % p
                ])
            # nodeLabel = '%s\nv%s' % (name_renderVersion.split('_v')[0], name_renderVersion.split('_v')[1])
            nodeLabel = "nuke.thisNode().name()+'\\n'+nuke.thisNode()['tx_version'].value()+'\\n\\n'+nuke.thisNode()['tx_layer'].value()+'\\n'+'v'+nuke.thisNode()['int_thisVersion'].value()"
            for l in ls_aov.keys():
                imgGroup = nuke.nodes.Group(autolabel=nodeLabel,
                                            postage_stamp=1)
                imgGroup.setName('kpRead1')
                t_tab = nuke.Tab_Knob('tb_user', 'kpRead')
                k_pipeline = nuke.Text_Knob('kupipeline', 'kpRead',
                                            'kpRead')  # Ku Pipeline Identifier
                k_renderVersion = nuke.Text_Knob(
                    'tx_version', '<b>render: </b>',
                    name_renderVersion.split('_v')[0])
                mod = os.path.basename(__file__).split('.py')[0]
                k_verUp = nuke.PyScript_Knob(
                    'btn_verUp', '<b>&#9650;</b>',
                    '%s.versionUp(nuke.thisNode())' % mod)
                k_verDown = nuke.PyScript_Knob(
                    'btn_verDown', '<b>&#9660;</b>',
                    '%s.versionDown(nuke.thisNode())' % mod)
                k_verLatest = nuke.PyScript_Knob(
                    'btn_verLatest', '<b>&#9733;</b>',
                    '%s.versionLatest(nuke.thisNode())' % mod)
                k_thisVersion = nuke.Text_Knob('int_thisVersion',
                                               '<b>version: </b>')
                k_thisVersion.setValue('%03d' % ver_renderVersion)
                k_renderLayer = nuke.Text_Knob('tx_layer', '<b>layer: </b>', l)
                k_div = nuke.Text_Knob('', "<b>Switch Version:</b>")
                k_path = nuke.Text_Knob('tx_dir', '<b>path: </b>',
                                        dir_renderVersion)
                # k_aov = nuke.Text_Knob('tx_aov', '<b>aovs: </b>', '\n'.join(ls_aov[l]))

                # k_thisVersion.setEnabled(False)
                k_thisVersion.setFlag(nuke.STARTLINE)
                k_path.setVisible(False)
                k_verUp.setFlag(nuke.STARTLINE)
                k_verUp.setTooltip("Version Up")
                k_verDown.clearFlag(nuke.STARTLINE)
                k_verDown.setTooltip("Version Down")
                k_verLatest.clearFlag(nuke.STARTLINE)
                k_verLatest.setTooltip("Latest Version")
                k_pipeline.setVisible(False)

                for k in [
                        t_tab, k_pipeline, k_path, k_renderVersion,
                        k_thisVersion, k_renderLayer, k_div, k_verUp,
                        k_verDown, k_verLatest
                ]:
                    imgGroup.addKnob(k)

                with imgGroup:
                    aov_beauty = None
                    aov_rest = []
                    for p in ls_aov[l]:
                        path = joinPath(dir_renderVersion, l, p)
                        createRead(path)
                    aov_beauty = nuke.toNode(RGBA)
                    aov_rest = [
                        n for n in nuke.allNodes('Read') if n != aov_beauty
                    ]
                    shuffling(aov_beauty, aov_rest)

            self.close()
Beispiel #10
0
def LinkedStamp(mode='set'):
    '''Main function
	mode='set': creating link (default)
	mode='reconnect': reconnect
	'''

    rNode = nuke.selectedNode()

    if mode == 'set':
        rNode_nam = rNode.name()
        base_name = "LinkStamp"
        stp = None

        if rNode.Class().startswith('Deep'):
            stp = nuke.nodes.NoOp()
        else:
            stp = nuke.nodes.PostageStamp()

        stp.setInput(0, rNode)
        stp['hide_input'].setValue(1)
        stp['postage_stamp'].setValue(True)
        #stp['label'].setValue(rNode_nam)
        stp['tile_color'].setValue(stpColor(rNode))
        stp.setName(stpRename(base_name))
        stp.setXYpos(rNode.xpos() + 75, rNode.ypos() + 25)

        #stp['postage_stamp'].setValue(False) if rNode.Class().startswith('Roto') else stp['postage_stamp'].setValue(True)

        # Add User knobs
        py_cmd_restore = "n=nuke.thisNode()\nn.setInput(0, nuke.toNode(n['connect'].value()))"
        py_cmd_orig = "origNode = nuke.thisNode().input(0);\
						origXpos = origNode.xpos();\
						origYpos = origNode.ypos();\
						nuke.zoom(2, [origXpos,origYpos]);\
						nuke.thisNode()['selected'].setValue(False);\
						origNode['selected'].setValue(True);\
						nuke.show(origNode)"

        py_cmd_copy = "origNode = nuke.thisNode().input(0);\
						filter(lambda n: n.setSelected(False), nuke.selectedNodes());\
						nuke.thisNode().setSelected(True);\
						nuke.nodeCopy('%clipboard%');\
						new_node = nuke.nodePaste('%clipboard%');\
						new_node.setInput(0, origNode);\
						new_node.setXpos(nuke.thisNode().xpos()+120)"

        k_tab = nuke.Tab_Knob("LinkedStamp")
        k_text = nuke.String_Knob('tx_nodename', "Set Input to: ")
        k_enable = nuke.Boolean_Knob('ck_enable', "Enable")
        k_setInput = nuke.PyScript_Knob('link', "Set Input", py_cmd_restore)
        k_showParent = nuke.PyScript_Knob('orig', "Show Parent Node",
                                          py_cmd_orig)
        k_copy = nuke.PyScript_Knob('copy', "Copy this Node", py_cmd_copy)
        k_connect = nuke.String_Knob('connect', 'toConnect', rNode_nam)

        k_setInput.setFlag(nuke.STARTLINE)
        k_text.setEnabled(False)
        k_enable.clearFlag(nuke.STARTLINE)
        k_showParent.clearFlag(nuke.STARTLINE)
        k_copy.clearFlag(nuke.STARTLINE)
        k_connect.setFlag(nuke.INVISIBLE)

        stp.addKnob(k_tab)
        stp.addKnob(k_text)
        stp.addKnob(k_enable)
        stp.addKnob(k_setInput)
        stp.addKnob(k_showParent)
        stp.addKnob(k_copy)
        stp.addKnob(k_connect)

        k_text.setValue(stp['connect'].value())
        k_setInput.setTooltip("Taking the node name from label and connect")
        k_showParent.setTooltip("Show parent node in DAG")
        k_copy.setTooltip("Copy this node with its inputs")

        stp['knobChanged'].setValue(
            'k=nuke.thisKnob()\nif k.name()=="ck_enable":\n\tnuke.thisNode()["tx_nodename"].setEnabled(k.value())'
        )
        stp['autolabel'].setValue(
            "('Disconnected from\\n' if len(nuke.thisNode().dependencies())<=0 else 'Linked to\\n')+nuke.thisNode()['tx_nodename'].value()"
        )
    elif mode == 'reconnect':
        rNodes = nuke.selectedNodes()
        for n in rNodes:
            if n['LinkedStamp'].value():
                n.setInput(0, nuke.toNode(n['connect'].value()))
Beispiel #11
0
def LinkedStamp(mode='set'):
    """Main function
	mode='set': creating link (default)
	mode='reconnect': reconnect
	mode='marking': marking a node for LinkedStamp to connect to
	"""

    if mode == 'set':

        # Nothing is selected
        if not len(nuke.selectedNodes()): node_parent = FindMarker().run()
        else: node_parent = nuke.selctedNode()

        # User Cancels or Select A Marker
        if node_parent == None: print("User Cancelled")
        else:
            node_parent_nam = node_parent.name()
            node_slave = None

            if isOutputDeep(node_parent):
                node_slave = nuke.nodes.NoOp()
            else:
                node_slave = nuke.nodes.PostageStamp()
                node_slave['postage_stamp'].setValue(
                    False) if node_parent.Class().startswith(
                        'Roto') else node_slave['postage_stamp'].setValue(True)

            stpMarking(node_parent)
            node_slave.setInput(0, node_parent)

            node_slave['hide_input'].setValue(1)
            node_slave['label'].setValue('linked to: [value tx_nodename]')
            node_slave['tile_color'].setValue(stpColor(node_parent))
            node_slave.setName(BASE_NAME)
            node_slave.setXYpos(node_parent.xpos() + 75,
                                node_parent.ypos() + 25)

            # Add User knobs
            py_cmd_restore = "n=nuke.thisNode()\nn.setInput(0, nuke.toNode(n['connect'].value()))"
            py_cmd_orig = "origNode = nuke.thisNode().input(0);\
							origXpos = origNode.xpos();\
							origYpos = origNode.ypos();\
							nuke.zoom(2, [origXpos,origYpos]);\
							nuke.thisNode()['selected'].setValue(False);\
							origNode['selected'].setValue(True);\
							nuke.show(origNode)"

            py_cmd_copy = "origNode = nuke.thisNode().input(0);\
							filter(lambda n: n.setSelected(False), nuke.selectedNodes());\
							nuke.thisNode().setSelected(True);\
							nuke.nodeCopy('%clipboard%');\
							new_node = nuke.nodePaste('%clipboard%');\
							new_node.setInput(0, origNode);\
							new_node.setXpos(nuke.thisNode().xpos()+120)"

            k_tab = nuke.Tab_Knob("LinkedStamp")
            k_text = nuke.String_Knob('tx_nodename', "Set Input to: ")
            k_enable = nuke.Boolean_Knob('ck_enable', "Enable")
            k_setInput = nuke.PyScript_Knob('link', "Set Input",
                                            py_cmd_restore)
            k_showParent = nuke.PyScript_Knob('orig', "Show Parent Node",
                                              py_cmd_orig)
            k_copy = nuke.PyScript_Knob('copy', "Copy this Node", py_cmd_copy)
            k_connect = nuke.String_Knob('connect', 'toConnect',
                                         node_parent_nam)

            k_setInput.setFlag(nuke.STARTLINE)
            k_text.setEnabled(False)
            k_enable.clearFlag(nuke.STARTLINE)
            k_showParent.clearFlag(nuke.STARTLINE)
            k_copy.clearFlag(nuke.STARTLINE)
            k_connect.setFlag(nuke.INVISIBLE)

            node_slave.addKnob(k_tab)
            node_slave.addKnob(k_text)
            node_slave.addKnob(k_enable)
            node_slave.addKnob(k_setInput)
            node_slave.addKnob(k_showParent)
            node_slave.addKnob(k_copy)
            node_slave.addKnob(k_connect)

            k_text.setValue(node_slave['connect'].value())
            k_setInput.setTooltip(
                "Taking the node name from label and connect")
            k_showParent.setTooltip("Show parent node in DAG")
            k_copy.setTooltip("Copy this node with its inputs")

            node_slave['knobChanged'].setValue(
                'k=nuke.thisKnob()\nif k.name()=="ck_enable":\n\tnuke.thisNode()["tx_nodename"].setEnabled(k.value())'
            )
            node_slave['autolabel'].setValue(
                "('Disconnected from\\n' if len(nuke.thisNode().dependencies())<=0 else 'Linked to\\n')+nuke.thisNode()['tx_nodename'].value()"
            )

    elif mode == 'reconnect':
        node_parents = nuke.selectedNodes()
        for n in node_parents:
            if n['LinkedStamp'].value():
                n.setInput(0, nuke.toNode(n['connect'].value()))

    elif mode == 'marking':
        for n in nuke.selectedNodes():
            stpMarking(n)
Beispiel #12
0
def import_components(components):

    for new_component in components:

        component = ftrack.Component(new_component["id"])
        assetversion = component.getVersion()
        asset = assetversion.getAsset()
        assettype = asset.getType()

        # Create node
        resultingNode = nuke.createNode('Read', inpanel=False)
        resultingNode['name'].setValue(
            HelpFunctions.safeString(asset.getName()) + '_' +
            HelpFunctions.safeString(component.getName()))

        # Add Ftrack tab
        knobs = resultingNode.knobs().keys()
        if 'ftracktab' not in knobs:
            # Note: the tab is supposed to be existing as it gets created
            # through callback during the read and write nodes creation.
            # This check is to ensure corner cases are handled properly.
            tab = nuke.Tab_Knob('ftracktab', 'ftrack')
            resultingNode.addKnob(tab)

        btn = nuke.String_Knob('componentId')
        resultingNode.addKnob(btn)
        btn = nuke.String_Knob('componentName')
        resultingNode.addKnob(btn)
        btn = nuke.String_Knob('assetVersionId')
        resultingNode.addKnob(btn)
        btn = nuke.String_Knob('assetVersion')
        resultingNode.addKnob(btn)
        btn = nuke.String_Knob('assetName')
        resultingNode.addKnob(btn)
        btn = nuke.String_Knob('assetType')
        resultingNode.addKnob(btn)
        btn = nuke.String_Knob('assetId')
        resultingNode.addKnob(btn)

        # Setup node
        file_path = component.getResourceIdentifier()
        resultingNode['file'].fromUserText(HelpFunctions.safeString(file_path))

        members = component.getMembers()
        frames = [int(member.getName()) for member in members]
        start = min(frames)
        end = max(frames)

        resultingNode['first'].setValue(start)
        resultingNode['origfirst'].setValue(start)
        resultingNode['last'].setValue(end)
        resultingNode['origlast'].setValue(end)

        resultingNode.knob('assetId').setValue(
            HelpFunctions.safeString(asset.getId()))
        resultingNode.knob('componentId').setValue(
            HelpFunctions.safeString(component.getEntityRef()))
        resultingNode.knob('componentName').setValue(
            HelpFunctions.safeString(component.getName()))
        resultingNode.knob('assetVersionId').setValue(
            HelpFunctions.safeString(assetversion.getEntityRef()))
        resultingNode.knob('assetVersion').setValue(
            HelpFunctions.safeString(str(assetversion.getVersion())))
        resultingNode.knob('assetName').setValue(
            HelpFunctions.safeString(asset.getName()))
        resultingNode.knob('assetType').setValue(
            HelpFunctions.safeString(assettype.getShort()))
Beispiel #13
0
def copyConnected():
    ### group the selected nodes
    selNodes = nuke.selectedNodes()

    ### we start the per node loop
    for node in selNodes:

        ### original list with dependencies to check if the node is connected
        dep = node.dependencies(nuke.INPUTS | nuke.HIDDEN_INPUTS)

        ### condition if the list is not empty (unconnected node)
        if dep:

            ### creates empty dict where we will add our inputs and connected nodes
            depDict = {}

            ## we get the number of inputs connected and we create a list with the range
            inputMax = node.inputs()
            inputRange = range(0, inputMax)

            ### we loop per input and store the name of the node connected to it (the if statement is in case there connection is empty it will do nothing)
            for inputCon in inputRange:
                inputNode = node.input(inputCon)
                if inputNode:
                    nodename = inputNode['name'].value()
                    depDict[inputCon] = nodename

            ### we check if our node selected is a wired or anchor node (trixter only)
            if node.knob('connection'):
                connection = node.knob('connection').getValue()

            ### we create the temp knobs with the dictionary of inputs and nodes (if the node is connected of course)
            else:
                tempTab = nuke.Tab_Knob('temp_tab', 'temp tab')
                node.addKnob(tempTab)
                depDictStr = str(depDict)
                tempText = nuke.Text_Knob('connectionTemp', 'connected to: ',
                                          depDictStr)
                node.addKnob(tempText)

    ### copy paste the nodes
    nukescripts.node_copypaste()

    ### group the new nodes created that are selected by default
    newNodes = nuke.selectedNodes()

    ### start of the loop for the new nodes
    for node in newNodes:

        ### we check if our node selected is a wired or anchor node (trixter only) and connects it to its input if the input is not duplicated
        if node.knob('connection'):
            anchor = node['connection'].value()
            inputNode = nuke.toNode(anchor)
            if inputNode not in selNodes:
                node.setInput(0, inputNode)

        ### we retrieve the dict knob and set it as dictionary
        elif node.knob('connectionTemp'):
            anchorStr = node['connectionTemp'].value()
            anchorDict = eval(anchorStr)

            ### for every key we retrieve the value of the dict
            for key in anchorDict:
                element = anchorDict[key]
                ### important f**k up, i don't know why nuke does not like the string resultant so i force the evaluation
                #evalInput = eval(element)

                ### we connect to the original input if it is not copied (selNodes) using the key (input number) and the value (node)
                inputNode = nuke.toNode(element)
                if inputNode not in selNodes:
                    node.setInput(key, inputNode)

            ### deletes the temp knobs from new nodes
            knobs = node.knobs()
            node.removeKnob(knobs['connectionTemp'])
            node.removeKnob(knobs['temp_tab'])

        ### we delete the variable count so it does'nt pile up
        # if 'count' in locals():
        #     del count

    ### deletes the temp knobs from old selected nodes
    for node in selNodes:
        if node.knob('connectionTemp'):
            node.hideControlPanel()
            allknobs = node.knobs()
            node.removeKnob(allknobs['connectionTemp'])
            node.removeKnob(allknobs['temp_tab'])
Beispiel #14
0
    def __new__(cls, *args, **kwargs):
        """Constructs a Groupmo and returns the node.

        Args:
            All args and keyword args will be passed to the creation of the
            Nuke Group with the exception of:

            padding : (int)
                The amount of spacing between any currently selected node
                and the newly created Groupmo, if the Groupmo has inputs.

        Returns:
            (<nuke.nodes.Group>)
                Note that this does NOT return an instance of `Groupmo`. We
                instead return the nuke node.

        Raises:
            N/A

        """
        padding = kwargs.pop('padding', None)

        if 'help' not in kwargs:
            kwargs['help'] = cls.help

        # Grab our selected node if there is one.
        try:
            selected = nuke.selectedNode()
        except ValueError:
            selected = None

        # Create Group, passing along all given arguments.
        groupmo = nuke.nodes.Group(*args, **kwargs)

        # Add tab that matches class name
        groupmo.addKnob(nuke.Tab_Knob(cls.Class, cls.Class))

        # Set our groupmo class id knob
        class_knob = nuke.Text_Knob('groupmo_class', 'Groupmo Class: ',
                                    cls.Class)
        class_knob.setFlag(nuke.INVISIBLE)
        groupmo.addKnob(class_knob)

        if 'name' not in kwargs:
            # Set our groupmo's name.
            groupmo.setName(cls.Class)

        # Call the setup function, which will be overriden by each Groupmo.
        groupmo.begin()
        cls.setup(groupmo)
        groupmo.end()

        if selected and groupmo.maxInputs():
            # If we've been given a padding, obey it. Otherwise, do not
            # pass padding and let the default padding for the func rule.
            center_args = [groupmo, selected]
            if padding:
                center_args.append(padding)

            if 'xpos' not in kwargs and 'ypos' not in kwargs:
                center_below(*center_args)

            connect_inline(groupmo, selected)

        elif selected:
            space_args = [selected, padding] if padding else [selected]
            if 'xpos' not in kwargs and 'ypos' not in kwargs:
                groupmo.setXYpos(space_x(*space_args),
                                 center_y(groupmo, selected))

        if selected:
            for node in nuke.selectedNodes():
                node['selected'].setValue(False)

        groupmo['selected'].setValue(True)

        return groupmo
Beispiel #15
0
def makeCrowd(group):
    ''' Atists hits make crowd button and we make a crowd '''

    with group:
        # get a list of points we want to creat cards on
        points = []
        if group['useSelection'].value() and len(
                group['vertexStore'].value()) > 0:
            allPoints = retrieveSavedVertices(group)
            points = everyNthPointOfPoints(allPoints, group)
        else:
            allPoints = verticesFromInput(group)
            points = everyNthPointOfPoints(allPoints, group)

        cardWarningLevel = 500
        if len(points) > cardWarningLevel:
            if not nuke.ask(
                    'Are you sure you want to create %s cards? This may take a long time...'
                    % (len(points))):
                return

        #delete the old scene
        removePreviousScene(group)

    with group:
        # pity the fool who doesn't use default node graph preferences
        prefs = nuke.toNode('preferences')
        gridWidth = prefs['GridWidth'].value()
        gridHeight = prefs['GridHeight'].value()

        lookDot = nuke.toNode('lookDot')
        img1 = nuke.toNode('img1')
        lastXY = [img1['xpos'].value() - gridWidth, img1['ypos'].value()]
        lookDot.setYpos(int(lastXY[1] + gridHeight * 76))

        switchInputs = imageInputList(group)

        # make channels, channel strings are used later in node creation
        crowdRandomColorStr = 'crowdRandomColor'
        nuke.Layer(crowdRandomColorStr, ['red', 'green', 'blue'])

        crowdIDStr = 'crowdID'
        nuke.Layer(crowdIDStr, ['id', 'sprite'])
        '''
        crowdCharacterMaskStr = 'crowdCharacterMask'
        nuke.Layer( crowdCharacterMaskStr , ['alpha'] )
        '''

        crowdMirrorMaskStr = 'crowdMirrorMask'
        nuke.Layer(crowdMirrorMaskStr, ['alpha'])

        transformGeoList = []
        cardList = []
        whichInput = 0

        for i in range(len(points)):
            point = points[i]

            # make a switch to plug in the image inputs
            inputSwitch = nuke.createNode('Switch', inpanel=False)
            inputSwitch.setName('imgSwitch')
            inputSwitch['label'].setValue(
                'which: [value which]\nauto-generated')
            inputSwitch.setXpos(int(lastXY[0] + gridWidth))
            inputSwitch.setYpos(int(lastXY[1] + gridHeight * 20))

            for j in range(len(switchInputs)):
                inputSwitch.setInput(j, nuke.toNode(switchInputs[j]))

            # Input switch to chose what images appear on what cards
            # TODO: Make a a fucntion for Duplication radius
            inputFromDuplicationRadius = whichInput
            ifStepExpr = '[string match [value inputOrder] "Step"]?%s' % (
                whichInput)
            ifRandomExpr = '[string match [value inputOrder] "Random"]?'\
                'rint(random(%s+%s,1)*%s)' % ('parent.inputSeed', i, len(switchInputs)-1)
            inputSwitch['which'].setExpression(
                '%s:%s:%s' %
                (ifStepExpr, ifRandomExpr, str(inputFromDuplicationRadius)))
            whichInput = whichInput + 1
            if whichInput >= len(switchInputs):
                whichInput = 0
            '''
            # make the id channel
            idShuffle = nuke.createNode('Shuffle', inpanel = False)
            idShuffle.setName('aov_idShuffle')
            idShuffle['in'].setValue('none')
            idShuffle['out'].setValue(crowdIDStr)
            idShuffle['label'].setValue('([value out])\nauto-generated')
            idShuffle['disable'].setExpression('!parent.displayAOVs')
            idShuffle.setXpos(int(lastXY[0]+gridWidth))
            idShuffle.setYpos(int(lastXY[1]+gridHeight*30))

            # make the id mult
            idKnob = nuke.Int_Knob('ID','ID')
            idKnob.setValue(i)

            idMult = nuke.createNode('Multiply' ,inpanel = False)
            idMult.addKnob( idKnob )
            idMult.setName('aov_idMult')
            idMult['channels'].setValue(crowdIDStr)
            idMult['value'].setSingleValue(True)
            idMult['value'].setExpression('%s' % ('this.ID+1'))
            #idMult['maskChannelInput'].setValue('rgba.alpha')
            idMult['label'].setValue('auto-generated')
            idMult['disable'].setExpression('!parent.aov_id')
            idMult.setXpos(int(lastXY[0]+gridWidth))
            idMult.setYpos(int(lastXY[1]+gridHeight*32))
            '''

            # make the id expression
            idExpr = nuke.createNode('Expression', inpanel=False)
            idExpr.setName('aov_idExpr')
            idExpr['temp_name0'].setValue('id')
            idExpr['temp_expr0'].setValue(str(i))
            idExpr['temp_name1'].setValue('inp')
            idExpr['temp_expr1'].setValue('[value %s.which]' %
                                          inputSwitch.name())
            idExpr['channel0'].setValue(crowdIDStr)
            idExpr['channel0'].enableChannel(0, True)
            idExpr['channel0'].enableChannel(1, False)
            idExpr['channel0'].enableChannel(2, False)
            idExpr['expr0'].setValue('id*rgba.alpha')
            idExpr['channel1'].setValue(crowdIDStr)
            idExpr['channel1'].enableChannel(0, False)
            idExpr['channel1'].enableChannel(1, True)
            idExpr['channel1'].enableChannel(2, False)
            idExpr['expr1'].setValue('inp*rgba.alpha')
            idExpr['channel2'].setValue('none')
            idExpr['channel3'].setValue('none')
            idExpr['label'].setValue('auto-generated')
            idExpr['disable'].setExpression('!parent.displayAOVs')
            idExpr.setXpos(int(lastXY[0] + gridWidth))
            idExpr.setYpos(int(lastXY[1] + gridHeight * 30))

            # make the grade layer which shuffles in the alpha
            randomShuffle = nuke.createNode('Shuffle', inpanel=False)
            randomShuffle.setName('aov_randomShuffle')
            randomShuffle['in'].setValue('alpha')
            randomShuffle['out'].setValue(crowdRandomColorStr)
            randomShuffle['label'].setValue('([value out])\nauto-generated')
            randomShuffle['disable'].setExpression('!parent.displayAOVs')
            randomShuffle.setXpos(int(lastXY[0] + gridWidth))
            randomShuffle.setYpos(int(lastXY[1] + gridHeight * 40))

            # make the grade layer mult
            randomColorMult = nuke.createNode('Multiply', inpanel=False)
            randomColorMult.setName('aov_randomMult')
            randomColorMult['channels'].setValue(crowdRandomColorStr)
            randomColorMult['value'].setSingleValue(False)
            randomColorMult['value'].setExpression(
                'random(%s+%s,1)' % ('parent.aov_randomSeed', str(i + 0)), 0)
            randomColorMult['value'].setExpression(
                'random(%s+%s,1)' % ('parent.aov_randomSeed', str(i + 1)), 1)
            randomColorMult['value'].setExpression(
                'random(%s+%s,1)' % ('parent.aov_randomSeed', str(i + 2)), 2)
            randomColorMult['unpremult'].setValue('rgba.alpha')
            randomColorMult['label'].setValue('auto-generated')
            randomColorMult['disable'].setExpression('!parent.displayAOVs')
            randomColorMult.setXpos(int(lastXY[0] + gridWidth))
            randomColorMult.setYpos(int(lastXY[1] + gridHeight * 42))

            # make the character mask which can be used for lighting
            '''
            charMaskShuffle = nuke.createNode('Shuffle', inpanel = False)
            charMaskShuffle['in'].setValue('alpha')
            charMaskShuffle['out'].setValue(crowdCharacterMaskStr)
            charMaskShuffle['label'].setValue('([value out])\nauto-generated')
            charMaskShuffle.setXpos(int(lastXY[0]+gridWidth))
            charMaskShuffle.setYpos(int(lastXY[1]+gridHeight*40))
            '''

            # make the mirror mask which can be used for flipping AOVs
            mirrorMaskShuffle = nuke.createNode('Shuffle', inpanel=False)
            mirrorMaskShuffle.setName('aov_mirrorShuffle')
            mirrorMaskShuffle['in'].setValue('alpha')
            mirrorMaskShuffle['out'].setValue(crowdMirrorMaskStr)
            mirrorMaskShuffle['label'].setValue(
                '([value out])\nauto-generated')
            mirrorMaskShuffle['disable'].setExpression('!parent.displayAOVs')
            mirrorMaskShuffle.setXpos(int(lastXY[0] + gridWidth))
            mirrorMaskShuffle.setYpos(int(lastXY[1] + gridHeight * 50))

            # make the mirror for flopping random cards
            idKnob = nuke.Int_Knob('mirrorID', 'mirrorID')
            idKnob.setValue(i)

            flop = nuke.createNode('Mirror2', inpanel=False)
            flop.addKnob(idKnob)
            flop['flop'].setValue(True)
            flop['disable'].setExpression(
                'parent.mirror?random(this.mirrorID+parent.mirrorSeed,1)>0.5?1:0:1'
            )
            flop['label'].setValue('auto-generated')
            flop.setXpos(int(lastXY[0] + gridWidth))
            flop.setYpos(int(lastXY[1] + gridHeight * 52))

            # make the mirror mask mult which can be used for flipping AOVs
            mirrorMaskMult = nuke.createNode('Multiply', inpanel=False)
            mirrorMaskMult.setName('aov_mirrorMult')
            mirrorMaskMult['channels'].setValue(crowdMirrorMaskStr)
            mirrorMaskMult['value'].setValue(0)
            mirrorMaskMult['disable'].setExpression(
                'parent.displayAOVs?!input0.disable:1')
            mirrorMaskMult['label'].setValue('(auto-generated')
            mirrorMaskMult.setXpos(int(lastXY[0] + gridWidth))
            mirrorMaskMult.setYpos(int(lastXY[1] + gridHeight * 54))

            # make the time offset
            idKnob = nuke.Int_Knob('offsetID', 'offsetID')
            idKnob.setValue(i)

            timeOffset = nuke.createNode('TimeOffset', inpanel=False)
            timeOffset.addKnob(nuke.Tab_Knob('User'))
            timeOffset.addKnob(idKnob)
            timeOffsetRandomizeExpr = 'rint(random(parent.timeOffsetSeed+%s,1)*parent.timeOffset*2-parent.timeOffset)' % (
                'this.offsetID')
            timeOffsetStepExpr = 'parent.timeOffset?parent.timeOffsetStep*this.offsetID%abs(parent.timeOffset):0'
            timeOffset['time_offset'].setExpression(
                'parent.timeOffsetRandomize?%s:%s' %
                (timeOffsetRandomizeExpr, timeOffsetStepExpr))
            timeOffset['label'].setValue(
                '[value time_offset] frames\nauto-generated')
            timeOffset.setXpos(int(lastXY[0] + gridWidth))
            timeOffset.setYpos(int(lastXY[1] + gridHeight * 60))

            # make the card
            idKnob = nuke.Double_Knob('cardID', 'cardID')
            idKnob.setRange(0, 100)
            idOffsetKnob = nuke.Double_Knob('cardIDOffset', 'cardIDOffset')
            idOffsetKnob.setRange(0, 100)

            card = nuke.createNode('Card', inpanel=False)
            card.addKnob(nuke.Tab_Knob('User'))
            card.addKnob(idKnob)
            card.addKnob(idOffsetKnob)
            card['cardIDOffset'].setExpression('parent.displayPercentOffset+this.cardID<=100?'\
                'parent.displayPercentOffset+this.cardID:this.cardID-100+parent.displayPercentOffset')
            card['disable'].setExpression(
                '$gui?parent.displayPercentage<100?parent.displayPercentage>this.cardIDOffset?0:1:0:1'
            )
            card.setXpos(int(lastXY[0] + gridWidth))
            card.setYpos(int(lastXY[1] + gridHeight * 70))
            cardList.append(card)

            # make the transform geo
            transformGeo = nuke.createNode('TransformGeo', inpanel=False)
            transformGeo.setXpos(int(lastXY[0] + gridWidth))
            transformGeo.setYpos(int(lookDot['ypos'].value()))
            transformGeo.setInput(0, card)
            transformGeo.setInput(2, lookDot)
            transformGeo['translate'].setExpression('random(%s+%s,1)*parent.positionOffset(0)' \
                '-parent.positionOffset(0)/2+%s' % ('parent.positionOffsetXZseed',str(i+0),point[0]),0)
            transformGeo['translate'].setExpression('random(%s+%s,1)*parent.positionOffset(1)' \
                '-parent.positionOffset(1)/2+%s' % ('parent.positionOffsetYseed',str(i+1),point[1]),1)
            transformGeo['translate'].setExpression('random(%s+%s,1)*parent.positionOffset(2)' \
                '   -parent.positionOffset(2)/2+%s' % ('parent.positionOffsetXZseed',str(i+2),point[2]),2)
            transformGeo['pivot'].setExpression('parent.pivotOffset', 1)
            transformGeo['uniform_scale'].setExpression('parent.scale+random(%s+%s,1)*' \
                '(scaleVariation*parent.scale)-(scaleVariation*parent.scale)/2' % ('parent.scaleSeed', str(i)))
            transformGeo['look_axis'].setExpression('parent.look_axis')
            transformGeo['look_rotate_x'].setExpression('parent.look_rotate_x')
            transformGeo['look_rotate_y'].setExpression('parent.look_rotate_y')
            transformGeo['look_rotate_z'].setExpression('parent.look_rotate_z')
            transformGeo['look_strength'].setExpression('parent.look_strength')
            transformGeo['look_use_quaternions'].setExpression(
                'parent.look_use_quaternions')

            transformGeoList.append(transformGeo)

            lastXY = [lastXY[0] + gridWidth, lastXY[1]]

        # pipe up all the transform geos into the output scene
        scene = nuke.toNode('scene')
        for i in range(len(transformGeoList)):
            scene.setInput(i, transformGeoList[i])
        scene.setYpos(int(lookDot['ypos'].value() + gridHeight * 10))
        nuke.toNode('Output').setYpos(
            int(lookDot['ypos'].value() + gridHeight * 20))

        # set up the cards so that they can be culled by a percentage in the gui
        random.seed(int(group['vertexStep'].value()))
        random.shuffle(cardList)
        for i in range(0, len(cardList)):
            cardID = float(i) * 100 / len(cardList)
            cardList[i]['cardID'].setValue(cardID)

        # change the group label and let artist know how many cards were created
        group['label'].setValue('%s Cards' % (len(transformGeoList)))
Beispiel #16
0
def freezeWarp_v2():
    try:
        node = nuke.selectedNode()
        if node.Class() not in ('SplineWarp3'):
            if nuke.GUI:
                nuke.message('Unsupported node type. Node must be SplineWarp')
            return
    except:
        if nuke.GUI:
            nuke.message('Select a SplineWarp Node')
            return

    shapeList = []
    curves = node['curves']
    nodeRoot = curves.rootLayer
    shapeList = fws_walker(nodeRoot, shapeList)

    #===========================================================================
    # panel setup
    #===========================================================================
    p = nukescripts.panels.PythonPanel("Freeze Splinewarp")
    k = nuke.Int_Knob("freezeframe", "Freezeframe")
    k.setFlag(nuke.STARTLINE)
    k.setTooltip("Set the frame to freeze the shapes positions")
    p.addKnob(k)
    k.setValue(nuke.root().firstFrame())
    k = nuke.Enumeration_Knob('outputcurve', 'Curves to Freeze', ['A', 'B'])
    k.setFlag(nuke.STARTLINE)
    k.setTooltip("Freeze all the curves on the A or B output")
    p.addKnob(k)

    k = nuke.Boolean_Knob("mt", "MultiThread")
    k.setFlag(nuke.STARTLINE)
    k.setTooltip(
        "This will speed up the script but without an accurate progress bar")
    p.addKnob(k)
    k.setValue(True)
    k = nuke.Boolean_Knob("exp", "Use Expression to Freeze")
    k.setFlag(nuke.STARTLINE)
    k.setTooltip(
        "Instead of deleting keyframes, it will use expressions on the shapes and also add a frame control on the node"
    )
    p.addKnob(k)
    k.setValue(True)
    k = nuke.Boolean_Knob("fh", "Create FrameHold")
    k.setFlag(nuke.STARTLINE)
    k.setTooltip(
        "This will create a Framehold Node and set it to the Freezeframe value, if you use expressions mode it will be linked"
    )
    p.addKnob(k)
    k.setValue(True)

    if not checkAB(shapeList):
        p.addKnob(
            nuke.Text_Knob(
                "", "",
                "\nWARNING: your node has only\ncurves on A or B outputs\n"))

    #===========================================================================
    # end of panel setup
    #===========================================================================
    result = p.showModalDialog()
    if result == 0:
        return  # Canceled

    freezeFrame = p.knobs()["freezeframe"].value()
    ab = 1.0 if p.knobs()["outputcurve"].value() == "A" else 2.0
    exp = p.knobs()["exp"].value()
    mt = p.knobs()["mt"].value()
    if nuke.NUKE_VERSION_MAJOR > 6:
        #=======================================================================
        # task setup
        #=======================================================================
        global cancel
        cancel = False
        task = nuke.ProgressTask('Freeze SplineWarp')
        n = 0
        #=======================================================================
        # task end
        #=======================================================================
        if exp:
            names = []
            for i in node.allKnobs():
                names.append(i.name())
            if "FreezeFrame" not in names:  #avoid creating the pane if it already exists
                tab = nuke.Tab_Knob('FreezeFrame')
                node.addKnob(tab)
                ff = nuke.Int_Knob('fframe', "Freeze Frame")
                node.addKnob(ff)
                try:
                    ff.setValue(freezeFrame)
                except:
                    pass

            for shape in shapeList:
                if cancel:
                    return
                task.setMessage('Processing ' + shape.name)
                task.setProgress((int(n / len(shapeList) * 100)))
                if mt:
                    threading.Thread(None,
                                     expressionLock,
                                     args=(shape, ab, freezeFrame, node,
                                           task)).start()
                else:
                    expressionLock(shape, ab, freezeFrame, node, task)
                n += 1
        else:
            for shape in shapeList:
                if cancel:
                    return
                task.setMessage('Processing ' + shape.name)
                task.setProgress((int(n / len(shapeList) * 100)))
                if mt:
                    threading.Thread(None,
                                     keyFreeze,
                                     args=(shape, ab, freezeFrame,
                                           task)).start()
                else:
                    keyFreeze(shape, ab, freezeFrame, task)
                n += 1

        #===========================================================================
        #  join existing threads (to wait completion before continue)
        #===========================================================================
        main_thread = threading.currentThread()
        for t in threading.enumerate():
            if t is main_thread:
                continue
            t.join()

        curves.changed()
    else:
        nuke.message(
            'This version is for Nuke v7, use v1.1 with Nuke v6.3 from Nukepedia'
        )

    fh = p.knobs()["fh"].value()
    if fh:
        framehold = nuke.nodes.FrameHold()
        if exp:
            framehold["first_frame"].setExpression(node.name() + ".fframe")

        else:
            framehold.knob("first_frame").setValue(freezeFrame)
        #=======================================================================
        # some layout beautyfication
        #=======================================================================
        framehold["xpos"].setValue(node["xpos"].getValue() - 100)
        framehold["ypos"].setValue(node["ypos"].getValue() - 80)
        dot = nuke.nodes.Dot()
        dot["xpos"].setValue(node["xpos"].getValue() + 35)
        dot["ypos"].setValue(framehold["ypos"].getValue() + 11)
        set_inputs(node, dot)
        set_inputs(dot, framehold)

    label = "FreezeF: [value fframe]" if exp else "FreezeF:" + str(freezeFrame)
    node.knob('label').setValue(label)
    node.knob('filter').setValue('Mitchell')  #less smoother than cubic
    print "FreezeSplineWarp Finished,", len(
        shapeList), "shape(s) at frame", freezeFrame
        def __init__(self, n):
            nukescripts.PythonPanel.__init__(self, 'shuffle channels')
            self.n = n
            self.channels = self.n.channels()

            # Layers list builder
            self.layers = []
            for i in range(len(self.channels)):
                chanName = self.channels[i].split('.')[0]
                if chanName not in self.layers and 'rgba' not in chanName:
                    self.layers.append(chanName)

            # UI
            self.tabGroup = nuke.BeginTabGroup_Knob('tabGroup', '')
            self.addKnob(self.tabGroup)
            # Layers Tab
            self.layersTab = nuke.Tab_Knob('layersTab', 'channels')
            self.addKnob(self.layersTab)

            availableNodes = '%s (%s node)' % (self.n.name(), self.n.Class())
            self.selectedNodeName = nuke.Text_Knob('selectedNodeName',
                                                   'selected node: ',
                                                   availableNodes)
            self.addKnob(self.selectedNodeName)

            self.separator = nuke.Text_Knob('separator', '')
            self.addKnob(self.separator)

            self.presets = nuke.Enumeration_Knob('presets',
                                                 '', ['                   '])
            self.addKnob(self.presets)

            self.listLayers = []
            for i in range(len(self.layers)):
                layer = nuke.Boolean_Knob('layer'+str(i), str(self.layers[i]))
                layer.setValue(True)
                layer.setEnabled(False)
                self.addKnob(layer)
                layer.setFlag(4096)
                self.listLayers.append(layer)

            # Prefs Tab
            self.prefsTab = nuke.Tab_Knob('prefsTab', 'preferences')
            self.addKnob(self.prefsTab)

            self.text1 = nuke.Text_Knob('texte_separation',
                                        'generate')
            self.addKnob(self.text1)

            self.autocrop = nuke.Boolean_Knob('autocrop', 'Autocrop')
            self.addKnob(self.autocrop)
            self.autocrop.setFlag(4096)

            self.postage = nuke.Boolean_Knob('postage', 'Postage stamp')
            self.addKnob(self.postage)
            self.postage.setFlag(4096)

            self.remove = nuke.Boolean_Knob('remove', 'Remove node')
            self.addKnob(self.remove)
            self.remove.setFlag(4096)

            self.grade = nuke.Boolean_Knob('grade', 'Grade node')
            self.addKnob(self.grade)
            self.grade.setFlag(4096)

            self.noShuffLabel = nuke.Boolean_Knob('noShuffLabel',
                                                  'remove label from Shuffles')
            self.noShuffLabel.setValue(True)
            self.noShuffLabel.setFlag(4096)
            self.noShuffLabel.setVisible(False)
            self.addKnob(self.noShuffLabel)

            self.bdrop = nuke.Boolean_Knob('bdrop', 'Backdrop')
            self.addKnob(self.bdrop)
            self.bdrop.setFlag(4096)

            self.bdropColor = nuke.ColorChip_Knob('bdropColor',
                                                  'backDrop color')
            self.addKnob(self.bdropColor)
            self.bdropColor.setDefaultValue([926365441])

            self.text = nuke.Text_Knob('texte_separation',
                                       'separation between nodes')
            self.addKnob(self.text)

            self.separation = nuke.Double_Knob('separation',
                                               '')
            self.addKnob(self.separation)
            self.separation.setFlag(4096)
            self.separation.setRange(100, 400)
            self.separation.setDefaultValue([200])

            self.shuffLayersColor = nuke.ColorChip_Knob('shuffLayersColor',
                                                        'Shuffle color')
            self.addKnob(self.shuffLayersColor)
            prefNode = nuke.toNode('preferences')['NodeColour05Color'].value()
            self.shuffLayersColor.setDefaultValue([prefNode])

            self.EndTab = nuke.EndTabGroup_Knob('endTabGroup', '')
            self.addKnob(self.EndTab)
Beispiel #18
0
def addPreferences():
    '''
    Add knobs to the preferences needed for this module to work properly.
    '''
    
    homeFolder = os.getenv('HOME').replace('\\','/') + '/.nuke'
    
    addToPreferences(nuke.Tab_Knob('hotboxLabel','W_hotbox'))

    addToPreferences(nuke.Text_Knob('hotboxGeneralLabel','<b>General</b>'))

    locationKnob = nuke.File_Knob('hotboxLocation','Hotbox location')
    locationKnobAdded = addToPreferences(locationKnob)
    if locationKnobAdded != None:
        location = homeFolder + '/W_hotbox'
        for i in ['','All','Single','Multiple','Single/No Selection']:
            try:
                os.mkdir(location + '/' + i)
            except:
                pass
        locationKnob.setValue(location)

    iconLocationKnob = nuke.File_Knob('iconLocation','Icons location')
    iconLocationKnob.setValue(homeFolder +'/icons/W_hotbox')
    addToPreferences(iconLocationKnob)

    shortcutKnob = nuke.String_Knob('hotboxShortcut','shortcut')
    shortcutKnob.setValue('`')
    addToPreferences(shortcutKnob)
    global shortcut
    shortcut = preferencesNode.knob('hotboxShortcut').value()

    opaqueKnob = nuke.Boolean_Knob('hotboxOpaqueBackground', 'Disable transparancy')
    opaqueKnob.setValue(False)
    opaqueKnob.setFlag(nuke.STARTLINE)
    addToPreferences(opaqueKnob)

    openManagerKnob = nuke.PyScript_Knob('hotboxOpenManager','open hotbox manager','W_hotboxManager.showHotboxManager()')
    openManagerKnob.setFlag(nuke.STARTLINE)
    addToPreferences(openManagerKnob)

    openFolderKnob = nuke.PyScript_Knob('hotboxOpenFolder','open hotbox folder','W_hotbox.revealInBrowser(True)')
    addToPreferences(openFolderKnob)

    deletePreferencesKnob = nuke.PyScript_Knob('hotboxDeletePreferences','delete preferences','W_hotbox.deletePreferences()')
    addToPreferences(deletePreferencesKnob)

    addToPreferences(nuke.Text_Knob('hotboxAppearanceLabel','<b>Appearance</b>'))

    colorDropdownKnob = nuke.Enumeration_Knob('hotboxColorDropdown', 'Color scheme',['Maya','Nuke','Custom'])
    addToPreferences(colorDropdownKnob)

    colorCustomKnob = nuke.ColorChip_Knob('hotboxColorCustom','')
    colorCustomKnob.clearFlag(nuke.STARTLINE)
    addToPreferences(colorCustomKnob)

    colorHotboxCenterKnob = nuke.Boolean_Knob('hotboxColorCenter','Colorize hotbox center')
    colorHotboxCenterKnob.setValue(True)
    colorHotboxCenterKnob.clearFlag(nuke.STARTLINE)
    addToPreferences(colorHotboxCenterKnob)

    addToPreferences(nuke.Text_Knob('hotboxItemsLabel','<b>Items per Row</b>'))

    rowAmountSelectionKnob = nuke.Int_Knob('hotboxRowAmountSelection', 'Selection specific')
    rowAmountSelectionAll = nuke.Int_Knob('hotboxRowAmountAll','All')

    for knob in [rowAmountSelectionKnob,rowAmountSelectionAll]:
        knob.setValue(3)
        addToPreferences(knob)
    
    stepSizeKnob = nuke.Int_Knob('hotboxRowStepSize','Step size')
    stepSizeKnob.setValue(1)
    addToPreferences(stepSizeKnob)

    spawnModeKnob = nuke.Boolean_Knob('hotboxButtonSpawnMode','Add new buttons to the sides')
    spawnModeKnob.setValue(True)
    spawnModeKnob.setFlag(nuke.STARTLINE)
    addToPreferences(spawnModeKnob)

    #Check if the compositing manager is running. If thats not the case, disable the transparancy.
    if not preferencesNode.knob('hotboxOpaqueBackground').value():
        try:
            if not QtGui.QX11Info.isCompositingManagerRunning():
                preferencesNode.knob('hotBoxOpaqueBackground').setValue(True)
        except:
            pass
Beispiel #19
0
def jopsBookmarkSave(index, mode='dag'):
    tabNameString = "DAG_Bookmarks"
    try:
        nuke.root()[tabNameString]
    except (SyntaxError, NameError):
        nuke.root().addKnob(nuke.Tab_Knob(tabNameString))
        for ind in range(1, 10):
            zoomNameString = "jops_bookmark_" + str(ind) + "_zoom"
            posNameString = "jops_bookmark_" + str(ind) + "_pos"
            xyKnob = nuke.XY_Knob(posNameString, str(ind))
            zoomKnob = nuke.Double_Knob(zoomNameString, "")
            zoomKnob.setFlag(nuke.NO_ANIMATION)
            zoomKnob.setFlag(nuke.DISABLED)
            xyKnob.setFlag(nuke.NO_ANIMATION)
            xyKnob.setFlag(nuke.DISABLED)
            zoomKnob.clearFlag(nuke.STARTLINE)
            nuke.root().addKnob(xyKnob)
            nuke.root().addKnob(zoomKnob)
        nuke.root().addKnob(
            nuke.Text_Knob(
                "j_ops_bookmarks_note", "",
                "<i>DAG bookmarks are part of the J_Ops toolset available on Nukepedia</i>"
            ))

    xpos = 0.0
    ypos = 0.0
    zoom = 0.0
    selectedList = []

    if mode == 'node':
        if nuke.selectedNodes():
            xposList = []
            yposList = []
            for anode in nuke.selectedNodes():
                xposList.append(anode["xpos"].getValue())
                yposList.append(anode["ypos"].getValue())
            xpos = sum(xposList, 0.0) / len(xposList)
            ypos = sum(yposList, 0.0) / len(yposList)
        else:
            return
    else:
        if nuke.selectedNodes():
            for anode in nuke.selectedNodes():
                selectedList.append(anode)
                anode["selected"].setValue(0.0)

        tempNode = nuke.createNode("Dot", inpanel=False)
        xpos = tempNode["xpos"].getValue()
        ypos = tempNode["ypos"].getValue()
        nuke.delete(tempNode)

    zoom = nuke.zoom()

    zoomNameString = "jops_bookmark_" + str(index) + "_zoom"
    posNameString = "jops_bookmark_" + str(index) + "_pos"

    nuke.root()[zoomNameString].clearFlag(nuke.DISABLED)
    nuke.root()[zoomNameString].setValue(zoom)
    nuke.root()[posNameString].clearFlag(nuke.DISABLED)
    nuke.root()[posNameString].setValue(xpos, 0)
    nuke.root()[posNameString].setValue(ypos, 1)

    if selectedList:
        for anode in selectedList:
            anode["selected"].setValue(1.0)
Beispiel #20
0
def MNE_ProjectorCam():

    #check if any nodes are selected
    if len(nuke.selectedNodes()) == 1:

        #get selected camera
        cam = nuke.selectedNode()

        #check it's a camera
        if cam.Class() == "Camera" or cam.Class() == "Camera2":

            #check it's not a ProjectorCam
            if cam['label'].value() != "[value freezeFrame]":

                #store its position
                xx = cam['xpos'].value()
                yy = cam['ypos'].value()

                #copy the camera
                nuke.nodeCopy(cam['name'].value())
                #deselect first camera
                cam['selected'].setValue(False)
                #paste it into new reference
                newCam = nuke.nodePaste(cam['name'].value())
                #show the panel in properties
                newCam.showControlPanel()
                #change the name
                newName = checkNodeName('Proj_Cam')
                newCam['name'].setValue(newName)

                #Create a custom tab in the new camera node (which will show by default)
                tabKnob = nuke.Tab_Knob('Freeze Frame')
                newCam.addKnob(tabKnob)

                #make the knob for the tab
                intKnob = nuke.Int_Knob('freezeFrame', 'Freeze on frame')
                intKnob.setValue(nuke.frame())
                updateKnob = nuke.PyScript_Knob('Set to this frame')
                updateKnob.setValue(
                    "nuke.thisNode()['freezeFrame'].setValue(nuke.frame())")

                #add the new knobs
                newCam.addKnob(intKnob)
                newCam.addKnob(updateKnob)

                #set the freeze frame to show on the node's label
                newCam['label'].setValue('[value freezeFrame]')

                #turn the new camera node an icy blue
                newCam['tile_color'].setValue(int(0x84e0d0ff))

                #position it next to the original camera
                newCam['xpos'].setValue(xx + 200)
                newCam['ypos'].setValue(yy)

                #link all values (and add the expression)

                if (cam.Class() == "Camera2"):
                    #this is an imported camera, so do things differently
                    #there are no expressions only curves. If there's no animation, the value is already there
                    #so don't do anything

                    #translate
                    if (newCam['translate'].isAnimated()):
                        newCam['translate'].setExpression("curve(freezeFrame)")

                    #rotate
                    if (newCam['rotate'].isAnimated()):
                        newCam['rotate'].setExpression("curve(freezeFrame)")

                    #win_translate
                    if (newCam['win_translate'].isAnimated()):
                        newCam['win_translate'].setExpression(
                            "curve(freezeFrame)")

                    #win_scale
                    if (newCam['win_scale'].isAnimated()):
                        newCam['win_scale'].setExpression("curve(freezeFrame)")

                    #focal
                    if (newCam['focal'].isAnimated()):
                        newCam['focal'].setExpression("curve(freezeFrame)")

                    #haperture
                    if (newCam['haperture'].isAnimated()):
                        newCam['haperture'].setExpression("curve(freezeFrame)")

                    #vaperture
                    if (newCam['vaperture'].isAnimated()):
                        newCam['vaperture'].setExpression("curve(freezeFrame)")

                else:

                    #translate
                    tempString = newCam['translate'].toScript(
                    )  #get the expression string
                    tempArray = string.split(tempString,
                                             " ")  #split into three for x,y,z
                    theExpr = tempArray[0][
                        1:
                        -1] + "(freezeFrame)"  #take the x expressions, chop off the {} and add the frame number variable
                    newCam['translate'].setExpression(theExpr)

                    #rotate
                    tempString = newCam['rotate'].toScript(
                    )  #get the expression string
                    tempArray = string.split(tempString,
                                             " ")  #split into three for x,y,z
                    theExpr = tempArray[0][
                        1:
                        -1] + "(freezeFrame)"  #take the x expressions, chop off the {} and add the frame number variable
                    newCam['rotate'].setExpression(theExpr)

                    #win_translate
                    tempString = newCam['win_translate'].toScript(
                    )  #get the expression string
                    tempArray = string.split(tempString,
                                             " ")  #split into two for x,y
                    theExpr = tempArray[0][
                        1:
                        -1] + "(freezeFrame)"  #take the x expressions, chop off the {} and add the frame number variable
                    newCam['win_translate'].setExpression(theExpr)

                    #win_scale
                    tempString = newCam['win_scale'].toScript(
                    )  #get the expression string
                    tempArray = string.split(tempString,
                                             " ")  #split into two for x,y
                    theExpr = tempArray[0][
                        1:
                        -1] + "(freezeFrame)"  #take the x expressions, chop off the {} and add the frame number variable
                    newCam['win_scale'].setExpression(theExpr)

                    #focal
                    tempString = newCam['focal'].toScript(
                    )  #get the expression string
                    theExpr = tempString[
                        1:
                        -1] + "(freezeFrame)"  #take the expression, chop off the {} and add the frame number variable
                    newCam['focal'].setExpression(theExpr)

                    #haperture
                    tempString = newCam['haperture'].toScript(
                    )  #get the expression string
                    theExpr = tempString[
                        1:
                        -1] + "(freezeFrame)"  #take the expression, chop off the {} and add the frame number variable
                    newCam['haperture'].setExpression(theExpr)

                    #vaperture
                    tempString = newCam['vaperture'].toScript(
                    )  #get the expression string
                    theExpr = tempString[
                        1:
                        -1] + "(freezeFrame)"  #take the expression, chop off the {} and add the frame number variable
                    newCam['vaperture'].setExpression(theExpr)

            else:
                nuke.message(
                    "You can't create a ProjectorCam out of another ProjectorCam. Select a tracked camera."
                )

        else:
            nuke.message("The node you selected isn't a camera.")
    else:
        nuke.message("Please select a camera node.")
Beispiel #21
0
                                  .15 + random.random() * .15)

    n = nuke.nodes.BackdropNode(
        xpos=bdX,
        bdwidth=bdW,
        ypos=bdY,
        bdheight=bdH,
        tile_color=int('%02x%02x%02x%02x' % (R * 255, G * 255, B * 255, 255),
                       16),
        note_font_size=fntSize)

    n.showControlPanel()

    #Creating additional tabs

    chTab = nuke.Tab_Knob('mainTabTK', 'backdropTK')
    chLogo = nuke.Text_Knob(
        'logo1', '',
        '<font color="lightgreen" size="5">backdrop</font><font color="#FFCC66" size="5">TK</font>'
    )
    chLogo1 = nuke.Text_Knob(
        'logo1', '',
        '<font color="lightgreen" size="2">by Timur Khodzhaev</font>')
    chlabel = nuke.Link_Knob('label_1', 'label')
    chlabel.makeLink(n.name(), 'label')

    n.addKnob(chTab)
    #    n.addKnob(chLogo)
    #    n.addKnob(chLogo1)
    n.addKnob(chlabel)
Beispiel #22
0
 def create_tab(self):
     tab_name = "{}_tab".format(self.knob_name_prefix)
     if tab_name not in self.get_our_knob_names():
         tab_label = self.tab_label
         t = nuke.Tab_Knob(tab_name, tab_label)
         self.p.addKnob(t)
Beispiel #23
0
def link_camera(src_cam, proj_frame, expr_link, clone, index):
    """
        Create a linked camera to src_cam -- this camera can be frozen on a projection frame
    """
    # Default grid size is 110x24. This enables moving by grid increments.
    # http://forums.thefoundry.co.uk/phpBB2/viewtopic.php?t=3739&sid=c40e65b1f575ba9166583faf807184ee
    # Offset by 1 grid in x for each additional iteration
    grid_x = int(nuke.toNode('preferences').knob('GridWidth').value())
    grid_y = int(nuke.toNode('preferences').knob('GridHeight').value()) * index

    src_cam.setSelected(False)

    # Create Projection Camera
    proj_cam = nuke.createNode('Camera2')

    # Create Projection Frame knob
    frame_tab = nuke.Tab_Knob('Frame')
    proj_cam.addKnob(frame_tab)
    proj_frame_knob = nuke.Double_Knob('proj_frame')
    if clone:
        proj_frame_knob.setExpression('t')
    else:
        proj_frame_knob.setValue(proj_frame)

    proj_cam.addKnob(proj_frame_knob)

    ## Copy the knob values of the Source Camera
    for knob_name, knob in src_cam.knobs().items():
        # For Animated knobs, copy or link the values depending on if Expression Links are enabled.
        if knob.isAnimated():
            #print "setting animated knob", knob_name
            if expr_link == True:
                #print "setting expression for animated knobs"
                for index in range(src_cam.knob(knob_name).arraySize()):
                    if src_cam.knob(knob_name).isAnimated(index):
                        proj_cam[knob_name].copyAnimation(
                            index, src_cam[knob_name].animation(index))
                proj_cam[knob_name].setExpression('parent.' + src_cam.name() +
                                                  "." + knob_name +
                                                  "(proj_frame)")
            # http://www.nukepedia.com/python/knob-animation-and-python-a-primer/
            else:
                for index in range(src_cam.knob(knob_name).arraySize()):
                    if src_cam.knob(knob_name).isAnimated(index):
                        proj_cam[knob_name].copyAnimation(
                            index, src_cam[knob_name].animation(index))
                proj_cam[knob_name].setExpression('curve(proj_frame)')

        # For all non-animated knobs that are not set to default values, match value from src_cam
        elif hasattr(knob, "notDefault") and knob.notDefault():
            try:
                #print "changing ", knob_name
                proj_cam[knob_name].setValue(knob.value())
            except TypeError:
                pass

    # Set label, color, name, and position
    proj_cam.setXYpos(src_cam.xpos() - grid_x, src_cam.ypos() - grid_y * 4)
    if clone:
        proj_cam.setName("{0}_CLONE_".format(src_cam.name()))
        proj_cam["gl_color"].setValue(0xff5f00ff)
        proj_cam["tile_color"].setValue(0xff5f00ff)
    else:
        proj_cam.setName("{0}_PROJ_".format(src_cam.name()))
        proj_cam["gl_color"].setValue(0xffff)
        proj_cam["tile_color"].setValue(0xffff)
        proj_cam["label"].setValue("FRAME [value proj_frame]")
Beispiel #24
0
def addfunction():
	if 'function' not in nuke.thisNode().knobs().keys():
		nuke.thisNode().addKnob(nuke.Tab_Knob('function', 'Function'))
		nuke.thisNode().addKnob(nuke.PyScript_Knob('setref','Set Reference','cornerpin.cornerpinsetreference()'))
	else:
		print('cornerpin have function tab!')
Beispiel #25
0
    def __init__(self, maximumPriority, pools, secondaryPools, groups):
        super(ReserveFrameServerSlavesDialog,
              self).__init__("Setup Frame Server Slaves With Deadline",
                             "com.thinkboxsoftware.software.deadlinefrdialog")

        # The environment variables themselves are integers. But since we can't test Nuke 6 to ensure they exist,
        # we have to use their `GlobalsEnvironment`, not a dict, get method which only accepts strings as defaults.
        self.nukeVersion = (
            int(nuke.env.get('NukeVersionMajor', '6')),
            int(nuke.env.get('NukeVersionMinor', '0')),
            int(nuke.env.get('NukeVersionRelease', '0')),
        )

        width = 605
        height = 710
        self.setMinimumSize(width, height)

        self.JobID = None
        # In Nuke 11.2.X, Adding a Tab_Knob and showing the dialog hard crashes Nuke. With only 1 tab, we can just remove it.
        if self.nukeVersion < (11, 2):
            self.jobTab = nuke.Tab_Knob("DeadlineFR_JobOptionsTab",
                                        "Job Options")
            self.addKnob(self.jobTab)

        ##########################################################################################
        ## Job Description
        ##########################################################################################

        # Job Name
        self.jobName = nuke.String_Knob("DeadlineFR_JobName", "Job Name")
        self.addKnob(self.jobName)
        self.jobName.setTooltip(
            "The name of your job. This is optional, and if left blank, it will default to 'Untitled'."
        )
        self.jobName.setValue("Untitled")

        # Comment
        self.comment = nuke.String_Knob("DeadlineFR_Comment", "Comment")
        self.addKnob(self.comment)
        self.comment.setTooltip(
            "A simple description of your job. This is optional and can be left blank."
        )
        self.comment.setValue("")

        # Department
        self.department = nuke.String_Knob("DeadlineFR_Department",
                                           "Department")
        self.addKnob(self.department)
        self.department.setTooltip(
            "The department you belong to. This is optional and can be left blank."
        )
        self.department.setValue("")

        # Separator
        self.separator1 = nuke.Text_Knob("DeadlineFR_Separator1", "")
        self.addKnob(self.separator1)

        ##########################################################################################
        ## Job Scheduling
        ##########################################################################################

        # Pool
        self.pool = nuke.Enumeration_Knob("DeadlineFR_Pool", "Pool", pools)
        self.addKnob(self.pool)
        self.pool.setTooltip("The pool that your job will be submitted to.")
        self.pool.setValue("none")

        # Secondary Pool
        self.secondaryPool = nuke.Enumeration_Knob("DeadlineFR_SecondaryPool",
                                                   "Secondary Pool",
                                                   secondaryPools)
        self.addKnob(self.secondaryPool)
        self.secondaryPool.setTooltip(
            "The secondary pool lets you specify a Pool to use if the primary Pool does not have any available Slaves."
        )
        self.secondaryPool.setValue(" ")

        # Group
        self.group = nuke.Enumeration_Knob("DeadlineFR_Group", "Group", groups)
        self.addKnob(self.group)
        self.group.setTooltip("The group that your job will be submitted to.")
        self.group.setValue("none")

        # Priority
        self.priority = nuke.Int_Knob("DeadlineFR_Priority", "Priority")
        self.addKnob(self.priority)
        self.priority.setTooltip(
            "A job can have a numeric priority ranging from 0 to " +
            str(maximumPriority) + ", where 0 is the lowest priority.")
        self.priority.setValue(50)

        # If the job is interruptible
        self.isInterruptible = nuke.Boolean_Knob("DeadlineFR_IsInterruptible",
                                                 "Job Is Interruptible")
        self.addKnob(self.isInterruptible)
        self.isInterruptible.setTooltip(
            "If true, the Job can be interrupted during rendering by a Job with higher priority."
        )
        self.isInterruptible.setValue(False)

        # Task Timeout
        self.taskTimeout = nuke.Int_Knob("DeadlineFR_TaskTimeout",
                                         "Task Timeout")
        self.addKnob(self.taskTimeout)
        self.taskTimeout.setTooltip(
            "The number of minutes a slave has to render a task for this job before it requeues it. Specify 0 for no limit."
        )
        self.taskTimeout.setValue(0)

        # Machine List Is Blacklist
        self.isBlacklist = nuke.Boolean_Knob("DeadlineFR_IsBlacklist",
                                             "Machine List Is A Blacklist")
        self.addKnob(self.isBlacklist)
        self.isBlacklist.setTooltip(
            "You can force the job to render on specific machines by using a whitelist, or you can avoid specific machines by using a blacklist."
        )
        self.isBlacklist.setValue(False)

        # Machine List
        self.machineList = nuke.String_Knob("DeadlineFR_MachineList",
                                            "Machine List")
        self.addKnob(self.machineList)
        self.machineList.setTooltip(
            "The whitelisted or blacklisted list of machines.")
        self.machineList.setValue("")

        self.machineListButton = nuke.PyScript_Knob(
            "DeadlineFR_MachineListButton", "Browse")
        self.addKnob(self.machineListButton)

        # Limit Groups
        self.limitGroups = nuke.String_Knob("DeadlineFR_LimitGroups", "Limits")
        self.addKnob(self.limitGroups)
        self.limitGroups.setTooltip("The Limits that your job requires.")
        self.limitGroups.setValue("")

        self.limitGroupsButton = nuke.PyScript_Knob(
            "DeadlineFR_LimitGroupsButton", "Browse")
        self.addKnob(self.limitGroupsButton)

        # Separator
        self.separator2 = nuke.Text_Knob("DeadlineFR_Separator2", "")
        self.addKnob(self.separator2)

        # Host name or IP Address
        self.hostName = nuke.String_Knob("DeadlineFR_HostNameIPAddress",
                                         "IP Address or Host Name")
        self.addKnob(self.hostName)
        self.hostName.setTooltip(
            "The Host Name or IP Address of the host Nuke Studio machine.")
        self.hostName.setValue("")

        # Host Port number to use
        self.port = nuke.Int_Knob("DeadlineFR_Port", "Port")
        self.addKnob(self.port)
        self.port.setTooltip("The Port number to that the host uses.")
        self.port.setValue(5560)

        #Number of machines to reserve
        self.machines = nuke.Int_Knob("DeadlineFR_ReserveMachines",
                                      "Machines to reserve")
        self.addKnob(self.machines)
        self.machines.setTooltip(
            "The number of machines to reserve as workers for the render.")
        self.machines.setValue(10)

        #Number of workers to launch on each machine
        self.workers = nuke.Int_Knob("DeadlineFR_Workers", "Workers")
        self.addKnob(self.workers)
        self.workers.setTooltip(
            "The number of workers to launch on each machine.")
        self.workers.setValue(1)

        #Number of threads each worker is allocated
        self.workerThreads = nuke.Int_Knob("DeadlineFR_WorkerThreads",
                                           "Worker Threads")
        self.addKnob(self.workerThreads)
        self.workerThreads.setTooltip(
            "The number of worker threads to start for each worker.")
        self.workerThreads.setValue(1)

        #Worker memory override
        self.workerMem = nuke.Int_Knob("DeadlineFR_WorkerMem", "Worker Memory")
        self.addKnob(self.workerMem)
        self.workerMem.setTooltip(
            "The amount of memory, in MB, allocated to each frame server worker"
        )
        self.workerMem.setValue(4096)

        # Separator
        self.separator3 = nuke.Text_Knob("DeadlineFR_Separator3", "")
        self.addKnob(self.separator3)

        self.jobID = nuke.String_Knob("DeadlineFR_JobID", "Job ID")
        self.addKnob(self.jobID)
        self.jobID.setTooltip("The ID of the Job.")
        self.jobID.setFlag(nuke.READ_ONLY)
        self.jobID.setEnabled(False)

        self.jobStatus = nuke.String_Knob("DeadlineFR_JobStatus", "Job Status")
        self.addKnob(self.jobStatus)
        self.jobStatus.setTooltip("The status of the Job.")
        self.jobStatus.setFlag(nuke.READ_ONLY)
        self.jobStatus.setEnabled(False)

        self.reservedMachines = nuke.Multiline_Eval_String_Knob(
            "DeadlineFR_ReservedMachines", "Reserved Machines")
        self.addKnob(self.reservedMachines)
        self.reservedMachines.setTooltip("The machines reserved for this job.")
        self.reservedMachines.setFlag(nuke.READ_ONLY)
        self.reservedMachines.setEnabled(False)

        self.outputBox = nuke.Multiline_Eval_String_Knob(
            "DeadlineFR_Output", "Last command output")
        self.addKnob(self.outputBox)
        self.outputBox.setTooltip("The output from the last action, if any.")
        self.outputBox.setFlag(nuke.READ_ONLY)
        self.outputBox.setEnabled(False)

        #Submits a job that reserves machines
        self.reserveButton = nuke.PyScript_Knob("DeadlineFR_ReserveButton",
                                                "Reserve Machines")
        self.addKnob(self.reserveButton)
        self.reserveButton.setTooltip(
            "Submits the Job to Deadline, which reserves some slaves for the frame server."
        )
        self.reserveButton.setFlag(nuke.STARTLINE)

        #If there is a job submitted, mark it as complete
        self.freeButton = nuke.PyScript_Knob("DeadlineFR_FreeButton",
                                             "Release Machines")
        self.addKnob(self.freeButton)
        self.freeButton.setTooltip(
            "Sets the Deadline Job to complete and frees up the slaves reserved for the frame server."
        )
        self.freeButton.setEnabled(False)

        self.launchButton = nuke.PyScript_Knob("DeadlineFR_LaunchButton",
                                               "Start Deadline Monitor")
        self.addKnob(self.launchButton)
        self.launchButton.setTooltip("Launches the Deadline Monitor.")
Beispiel #26
0
def anchor(title="", tags="", input_node="", node_type="2D"):
    ''' Anchor Stamp '''
    try:
        n = nuke.createNode(StampClasses[node_type])
    except:
        n = nuke.createNode("NoOp")
    n["name"].setValue(getAvailableName("Anchor"))
    # Set default knob values
    defaults = STAMP_DEFAULTS.copy()
    defaults.update(ANCHOR_DEFAULTS)
    for i, j in defaults.items():
        try:
            n.knob(i).setValue(j)
        except:
            pass

    # Main knobs
    anchorTab_knob = nuke.Tab_Knob('anchor_tab', 'Anchor Stamp')
    identifier_knob = nuke.Text_Knob('identifier', 'identifier', 'anchor')
    identifier_knob.setVisible(False)
    title_knob = nuke.String_Knob('title', 'Title', title)
    prev_title_knob = nuke.Text_Knob('prev_title', '', title)
    prev_title_knob.setVisible(False)
    showing_knob = nuke.Int_Knob('showing', '', 0)
    showing_knob.setVisible(False)
    tags_knob = nuke.String_Knob('tags', 'Tags', tags)
    for k in [
            anchorTab_knob, identifier_knob, title_knob, prev_title_knob,
            showing_knob, tags_knob
    ]:
        n.addKnob(k)

    # Buttons
    wiredLabel_knob = nuke.Text_Knob('wiredLabel', 'Wired Stamps', "")
    wiredLabel_knob.setFlag(nuke.STARTLINE)
    buttonSelectStamps = nuke.PyScript_Knob(
        "selectStamps", "select",
        "import stamps; stamps.wiredSelectSimilar(nuke.thisNode().name())")
    buttonSelectStamps.setFlag(nuke.STARTLINE)
    buttonReconnectStamps = nuke.PyScript_Knob(
        "reconnectStamps", "reconnect",
        "import stamps; stamps.anchorReconnectWired()")
    buttonZoomNext = nuke.PyScript_Knob(
        "zoomNext", "zoom next",
        "import stamps; stamps.wiredZoomNext(nuke.thisNode().name())")

    for k in [
            wiredLabel_knob, buttonSelectStamps, buttonReconnectStamps,
            buttonZoomNext
    ]:
        n.addKnob(k)

    # Version (for future update checks)
    line_knob = nuke.Text_Knob("line", "", "")
    buttonHelp = nuke.PyScript_Knob("buttonHelp", "Help",
                                    "import stamps; stamps.showHelp()")
    version_knob = nuke.Text_Knob('version', '', version)
    version_knob.setTooltip(VERSION_TOOLTIP)
    version_knob.clearFlag(nuke.STARTLINE)
    for k in [line_knob, buttonHelp, version_knob]:
        n.addKnob(k)
    n["help"].setValue(STAMPS_HELP)

    return n
Beispiel #27
0
def create_pointer():
    # Create an anchor / pointer set
    nodes = nuke.selectedNodes()
    if not nodes:
        return

    for target in nodes:
        upstream = [
            n for n in connected(nodes, upstream=True, downstream=False)
        ]

        if len(upstream) > 5:
            if not nuke.ask(
                    'More than 5 upstream nodes. Are you sure you want to continue?'
            ):
                return

        randstr = ''.join(
            random.choice(string.ascii_lowercase) for i in range(4))

        topnode = get_topnode(target)

        target_label = target['label'].getValue()

        # If topnode has a file knob, use that to set title
        # If it's a roto node, use the roto label
        if 'file' in topnode.knobs():
            pointer_title = os.path.basename(topnode['file'].getValue())
            if '.' in pointer_title:
                pointer_title = pointer_title.split('.')[0]
        elif topnode.Class() in ['Roto', 'RotoPaint'
                                 ] and topnode['label'].getValue():
            pointer_title = topnode['label'].getValue()
        elif target_label:
            pointer_title = target_label
        else:
            pointer_title = ''

        topnode_color = topnode['tile_color'].value()

        if topnode_color == 0:
            # Get default color from prefs if node is not colored https://community.foundry.com/discuss/topic/103301/get-the-default-tile-color-from-preferences
            prefs = nuke.toNode('preferences')
            default_colors = {
                prefs['NodeColour{0:02d}Color'.format(i)].value():
                prefs['NodeColourClass{0:02d}'.format(i)].value()
                for i in range(1, 14)
            }
            node_class = topnode.Class().lower()
            node_class = ''.join([i for i in node_class if not i.isdigit()])
            for color, classes in default_colors.items():
                if node_class in classes:
                    topnode_color = color
                    break
            if 'deep' in node_class:
                topnode_color = prefs['NodeColourDeepColor'].value()

        if len(nodes) == 1:
            # Only prompt the user for info if there is one selected node
            panel = nuke.Panel('Create Pointer')
            panel.addSingleLineInput('title', pointer_title)
            if panel.show():
                pointer_title = panel.value('title')
            else:
                return

        has_downstream = len(select_downstream(target)) > 0
        unselect()

        if not has_downstream:
            target.setSelected(True)

        # create anchor node
        anchor = nuke.createNode(
            'NoOp',
            'name ___anchor_{0} icon Output.png label "<font size=7>\[value title]"'
            .format(randstr))
        anchor.addKnob(nuke.Tab_Knob('anchor_tab', 'anchor'))
        anchor.addKnob(nuke.String_Knob('title', 'title'))
        anchor['title'].setValue(pointer_title)
        anchor['tile_color'].setValue(topnode_color)
        anchor.setInput(0, target)
        anchor.setSelected(True)

        # create pointer node
        pointer = nuke.createNode(
            'NoOp',
            'name ___pointer_{0} hide_input true icon Input.png'.format(
                randstr))
        pointer.addKnob(nuke.Tab_Knob('pointer_tab', 'pointer'))
        pointer.addKnob(nuke.String_Knob('target', 'target'))
        pointer['target'].setValue(anchor.fullName())
        pointer['label'].setValue(
            '<font size=7> [if {[exists input.title]} {return [value input.title]}]'
        )
        pointer.addKnob(nuke.PyScript_Knob('connect_to_target', 'connect'))
        pointer['connect_to_target'].setFlag(nuke.STARTLINE)
        pointer.addKnob(nuke.PyScript_Knob('zoom_to_target', 'zoom'))
        pointer.addKnob(nuke.PyScript_Knob('set_target', 'set target'))
        pointer['connect_to_target'].setValue('''n = nuke.thisNode()
t = n['target'].getValue()
if nuke.exists(t):
    tn = nuke.toNode(t)
    n.setInput(0, tn)''')
        pointer['zoom_to_target'].setValue(
            '''t = nuke.thisNode()['target'].getValue()
if nuke.exists(t):
    tn = nuke.toNode(t)
    nuke.zoom(2.0, [tn.xpos(), tn.ypos()])''')
        pointer['set_target'].setValue('''n = nuke.thisNode()
sn = nuke.selectedNodes()
if sn:
    t = sn[-1]
n['target'].setValue(t.fullName())''')
        # set autolabel node to execute connect python script button.
        # it's a hack but it works to automatically reconnect the input without using knobChanged callbacks!
        # FYI, onCreate callback can not connect input 0 due to a nuke bug
        pointer['autolabel'].setValue(
            'nuke.thisNode()["connect_to_target"].execute()')
        pointer.setXYpos(anchor.xpos(), anchor.ypos() + 120)
        pointer['tile_color'].setValue(topnode_color)
Beispiel #28
0
def wired(anchor):
    ''' Wired Stamp '''
    global Stamps_LastCreated
    Stamps_LastCreated = anchor.name()
    node_type = nodeType(anchor)
    try:
        n = nuke.createNode(StampClasses[node_type])
    except:
        n = nuke.createNode("NoOp")
    n["name"].setValue(getAvailableName("Stamp"))
    # Set default knob values
    defaults = STAMP_DEFAULTS.copy()
    defaults.update(WIRED_DEFAULTS)
    for i, j in defaults.items():
        try:
            n.knob(i).setValue(j)
        except:
            pass
    n["onCreate"].setValue(wiredOnCreate_code)

    # Main knobs
    wiredTab_knob = nuke.Tab_Knob('wired_tab', 'Wired Stamp')
    identifier_knob = nuke.Text_Knob('identifier', 'identifier', 'wired')
    identifier_knob.setVisible(False)
    toReconnect_knob = nuke.Boolean_Knob("toReconnect")
    toReconnect_knob.setVisible(False)
    title_knob = nuke.String_Knob('title', 'Title', anchor["title"].value())
    prev_title_knob = nuke.Text_Knob('prev_title', '', anchor["title"].value())
    prev_title_knob.setVisible(False)
    anchor_knob = nuke.String_Knob('anchor', 'Anchor', anchor.name())

    for k in [
            wiredTab_knob, identifier_knob, toReconnect_knob, title_knob,
            prev_title_knob, anchor_knob
    ]:
        n.addKnob(k)

    wiredTab_knob.setFlag(0)  #Open the tab

    # Buttons
    anchorLabel_knob = nuke.Text_Knob('anchorLabel', 'Anchor Stamp', "")
    anchorLabel_knob.setFlag(nuke.STARTLINE)
    buttonShow = nuke.PyScript_Knob("show", "show",
                                    "import stamps; stamps.wiredShowAnchor()")
    buttonShow.clearFlag(nuke.STARTLINE)
    buttonZoomAnchor = nuke.PyScript_Knob(
        "zoomAnchor", "zoom", "import stamps; stamps.wiredZoomAnchor()")
    buttonReconnect = nuke.PyScript_Knob("reconnect", "reconnect",
                                         wiredReconnect_code)

    wiredLabel_knob = nuke.Text_Knob('wiredLabel', 'Wired Stamps', "")
    wiredLabel_knob.setFlag(nuke.STARTLINE)
    buttonSelectSimilar = nuke.PyScript_Knob(
        "selectSimilar", "select similar",
        "import stamps; stamps.wiredSelectSimilar()")
    buttonSelectSimilar.setFlag(nuke.STARTLINE)
    buttonZoomNext = nuke.PyScript_Knob(
        "zoomNext", "zoom next", "import stamps; stamps.wiredZoomNext()")
    buttonReconnectSimilar = nuke.PyScript_Knob(
        "reconnectSimilar", "reconnect similar",
        "import stamps; stamps.wiredReconnectSimilar()")

    for k in [
            anchorLabel_knob, buttonShow, buttonZoomAnchor, buttonReconnect,
            wiredLabel_knob, buttonSelectSimilar, buttonZoomNext,
            buttonReconnectSimilar
    ]:
        n.addKnob(k)

    # Version (for future update checks)
    line_knob = nuke.Text_Knob("line", "", "")
    buttonHelp = nuke.PyScript_Knob("buttonHelp", "Help",
                                    "import stamps; stamps.showHelp()")
    version_knob = nuke.Text_Knob('version', '', version)
    version_knob.clearFlag(nuke.STARTLINE)
    version_knob.setTooltip(VERSION_TOOLTIP)
    for k in [line_knob, buttonHelp, version_knob]:
        n.addKnob(k)

    # Hide input while not messing possition
    x, y = n.xpos(), n.ypos()
    n.setInput(0, anchor)
    n["hide_input"].setValue(True)
    n["xpos"].setValue(x)
    n["ypos"].setValue(y)

    n["help"].setValue(STAMPS_HELP)

    return n
    Stamps_LastCreated = anchor.name()
Beispiel #29
0
def CP_to_Matrix():

    node = nuke.thisNode()
    parentNode = node.input(0)
    imageWidth = float(node.width())
    imageHeight = float(node.height())
    xps = node['xpos'].value()
    yps = node['ypos'].value()

    #CREATING EMPTY MATRICES
    cornerPinMatrixTo = nuke.math.Matrix4()
    cornerPinMatrixFrom = nuke.math.Matrix4()

    #CREATING KNOBS
    baked = nuke.nodes.CornerPin2D(name=node.name() + '_Matrix',
                                   xpos=xps + 100,
                                   ypos=yps)
    baked['from2'].setValue(imageWidth, 0)
    baked['from3'].setValue(imageWidth, 0)
    baked['from3'].setValue(imageHeight, 1)
    baked['from4'].setValue(imageHeight, 1)
    baked['to2'].setValue(imageWidth, 0)
    baked['to3'].setValue(imageWidth, 0)
    baked['to3'].setValue(imageHeight, 1)
    baked['to4'].setValue(imageHeight, 1)
    baked.setInput(0, parentNode)
    tab = nuke.Tab_Knob('plus', 'plus')
    switcher = nuke.Enumeration_Knob('switcher', 'Matrix Type', [
        'All', 'Scale Only', 'Rotation Only', 'Translate Only',
        'ScaleAndRotate Only'
    ])
    finalMatrixArr = nuke.Array_Knob('finalMatrixKnob', 'All', 16)
    mtxScaleArr = nuke.Array_Knob('mtxScaleKnob', 'Scale Only', 16)
    mtxRotationArr = nuke.Array_Knob('mtxRotationKnob', 'Rotation Only', 16)
    mtxTranslationArr = nuke.Array_Knob('mtxTranslationKnob', 'Translate Only',
                                        16)
    mtxScaleRotationArr = nuke.Array_Knob('mtxScaleRotationKnob',
                                          'ScaleAndRotate Only', 16)
    #ADDING KNOBS
    check = node.knob('plus')
    if check is not None:
        baked.addKnob(switcher)
        for each in (finalMatrixArr, mtxScaleArr, mtxRotationArr,
                     mtxTranslationArr, mtxScaleRotationArr):
            baked.addKnob(each)
            each.setVisible(False)
    else:
        baked.addKnob(tab)
        baked.addKnob(switcher)
        for each in (finalMatrixArr, mtxScaleArr, mtxRotationArr,
                     mtxTranslationArr, mtxScaleRotationArr):
            baked.addKnob(each)
            each.setVisible(False)

    #FRAME RANGE
    range = nuke.getFramesAndViews(
        'Get Frame Range',
        '%s-%s' % (nuke.root().firstFrame(), nuke.root().lastFrame()))
    frange = nuke.FrameRange(range[0])

    for n in frange:
        #GETTING KNOBS VALUES
        vectorsTo = [
            nuke.math.Vector2(node[f].getValueAt(n)[0],
                              node[f].getValueAt(n)[1])
            for f in sorted(node.knobs().keys()) if f.startswith('to')
        ]
        vectorsFrom = [
            nuke.math.Vector2(node[f].getValueAt(n)[0],
                              node[f].getValueAt(n)[1])
            for f in sorted(node.knobs().keys()) if f.startswith('from')
        ]

        #CONVERTING CORNER PIN TO MATRICES
        cornerPinMatrixTo.mapUnitSquareToQuad(vectorsTo[0].x, vectorsTo[0].y,
                                              vectorsTo[1].x, vectorsTo[1].y,
                                              vectorsTo[2].x, vectorsTo[2].y,
                                              vectorsTo[3].x, vectorsTo[3].y)
        cornerPinMatrixFrom.mapUnitSquareToQuad(
            vectorsFrom[0].x, vectorsFrom[0].y, vectorsFrom[1].x,
            vectorsFrom[1].y, vectorsFrom[2].x, vectorsFrom[2].y,
            vectorsFrom[3].x, vectorsFrom[3].y)

        #FINAL MATRIX VALUE
        finalMatrix = cornerPinMatrixTo * cornerPinMatrixFrom.inverse()
        finalMatrix.transpose()

        #DERIVATIVES
        mtxRotation = nuke.math.Matrix4(finalMatrix)
        mtxRotation.rotationOnly()
        mtxScale = nuke.math.Matrix4(finalMatrix)
        mtxScale.scaleOnly()
        mtxTranslation = nuke.math.Matrix4(finalMatrix)
        mtxTranslation.translationOnly()
        mtxScaleRotation = nuke.math.Matrix4(finalMatrix)
        mtxScaleRotation.scaleAndRotationOnly()
        #SET ANIMATED
        baked['finalMatrixKnob'].setAnimated()
        baked['mtxScaleKnob'].setAnimated()
        baked['mtxRotationKnob'].setAnimated()
        baked['mtxTranslationKnob'].setAnimated()
        baked['mtxScaleRotationKnob'].setAnimated()

        #ASSIGNING MATRICES TO KNOBS
        knobsCount = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

        [(baked['finalMatrixKnob'].setValueAt(finalMatrix[i], n, i))
         for i in knobsCount]
        [(baked['mtxScaleKnob'].setValueAt(mtxScale[i], n, i))
         for i in knobsCount]
        [(baked['mtxRotationKnob'].setValueAt(mtxRotation[i], n, i))
         for i in knobsCount]
        [(baked['mtxTranslationKnob'].setValueAt(mtxTranslation[i], n, i))
         for i in knobsCount]
        [(baked['mtxScaleRotationKnob'].setValueAt(mtxScaleRotation[i], n, i))
         for i in knobsCount]

    baked['transform_matrix'].setExpression('finalMatrixKnob')
    print finalMatrix
Beispiel #30
0
def loadSelectedcomments():
    """Loads the comments for a selected node from the server. Comments are generated as text nodes inside a group"""
    nodes = nuke.selectedNodes()
    nukeroot = nuke.root()
    previouscommand = "animCurve = nuke.thisNode()['comment'].animation( 0 ) \nframe = False\nfor i in xrange(len(animCurve.keys())):\n    if nuke.frame() > animCurve.keys()[i].x:\n        frame = animCurve.keys()[i].x     \nif frame:\n    nuke.frame(frame)"
    nextcommand = "animCurve = nuke.thisNode()['comment'].animation( 0 ) \nframe = False\nfor i in xrange(len(animCurve.keys())):\n    if nuke.frame() < animCurve.keys()[i].x:\n        frame = animCurve.keys()[i].x\n        break\nif frame:\n    nuke.frame(frame)"
    if not 'frameioproject' in nukeroot.knobs():
        return False
    if nukeroot['frameioproject'].value() == '0':
        project = ''
    else:
        project = nukeroot['frameioproject'].value()
    for node in nodes:
        if not 'file' in node.knobs():
            continue
        filepath = os.path.abspath(node['file'].value())
        if not os.path.isfile(filepath):
            continue
        frameiosession = login(nukeroot['frameiousername'].value(), project)
        if frameiosession == None:
            return False
        projectid = node['projectid'].value()
        filereferenceid = node['filereferenceid'].value()
        frameiosession.setProjectid(projectid)
        filereference = frameiosession.getFilereference(filereferenceid)
        commentdict = filereference.getComments()
        if not commentdict:
            return False

        group = nuke.createNode('Group')

        group.addKnob(nuke.Tab_Knob('frameio', 'frame.io'))
        group.addKnob(nuke.Int_Knob('comment', 'Comment'))
        group.addKnob(nuke.Int_Knob('of', 'of'))
        group.addKnob(
            nuke.PyScript_Knob('previous', 'previous', previouscommand))
        group.addKnob(nuke.PyScript_Knob('next', 'next', nextcommand))
        group.addKnob(nuke.Boolean_Knob('showtext', 'Show text', True))
        group.addKnob(
            nuke.Boolean_Knob('showannotation', 'Show annotation', True))
        group.addKnob(nuke.Double_Knob('global_font_scale', 'Font scale'))
        group['global_font_scale'].setValue(.25)
        group['of'].clearFlag(nuke.STARTLINE)
        group['showtext'].setFlag(nuke.STARTLINE)
        group['comment'].setAnimated()
        i = 1
        while nuke.toNode('Comments' + str(i)) != None:
            i += 1
        group['name'].setValue('Comments' + str(i))
        group['label'].setValue(os.path.basename(filepath))
        with group:
            input = nuke.createNode('Input')
            input.hideControlPanel()
            i = 0
            for timestamps in sorted(commentdict.keys()):
                for comment in commentdict[timestamps]:
                    if node.Class() == 'Read':
                        if node['frame'].value() == '':
                            offset = 0
                        else:
                            offset = int(node['frame'].value())
                    else:
                        offset = int(nuke.root()['first_frame'].value())
                    frame = round(timestamps) + offset
                    user = comment[0]
                    text = comment[1]
                    draw_data = comment[2]
                    group['comment'].setValueAt(i + 1, frame)
                    textnode = nuke.createNode('Text2')
                    textnode['box'].setValue(
                        [10, 10, node.width() / 2,
                         node.height()])
                    textnode['yjustify'].setValue('bottom')
                    textnode['global_font_scale'].setExpression(
                        'parent.global_font_scale')
                    textnode['enable_background'].setValue(True)
                    textnode['background_opacity'].setValue(0.9)
                    textnode['useLifetime'].setValue(True)
                    textnode['lifetimeStart'].setValue(frame)
                    textnode['lifetimeEnd'].setValue(frame)
                    textnode['disable'].setExpression('1-parent.showtext')
                    annotationNode(draw_data, node.width(), node.height(),
                                   frame)
                    message = user
                    message += '\n\n'
                    message += text
                    textnode['message'].setValue(message.encode('utf-8'))
                    textnode.hideControlPanel()
                    i += 1
            group['of'].setValue(i)
            output = nuke.createNode('Output')
            output.hideControlPanel()
        group.setInput(0, node)
        nuke.autoplace(group)