Пример #1
0
 def _add_knob(k):
     _knob_tcl_name = 'preferences.{}'.format(k.name())
     if nuke.exists(_knob_tcl_name):
         k.setValue(pref[k.name()].value())
         pref.removeKnob(pref[k.name()])
     k.setFlag(nuke.ALWAYS_SAVE)
     pref.addKnob(k)
Пример #2
0
def create_write_product_node():

    node = nuke.createNode('Write', inpanel=True)

    node_name = 'WriteProduct'
    node_inst = 1

    while nuke.exists(node_name + str(node_inst)):
        node_inst += 1

    node_name += str(node_inst)

    node.knob('name').setValue(node_name)
    node.knob('beforeRender').setValue(
        'dpa.nuke.utils.create_product_before_render()')
    node.knob('afterFrameRender').setValue(
        'dpa.nuke.utils.set_permissions_after_frame()')

    products_tab = nuke.Tab_Knob("Product")
    node.addKnob(products_tab)
    node.addKnob(nuke.EvalString_Knob('product_desc', 'description', ""))
    node.addKnob(
        nuke.EvalString_Knob('product_name', 'name',
                             get_default_product_name()))
    node.addKnob(nuke.EvalString_Knob('product_ver_note', 'description', ""))

    # hide the file knob
    node.knob('file_type').setValue('exr')
    node.knob('product_ver_note').setVisible(False)
Пример #3
0
def import_all_gizmos():

    session = ftrack_connect.session.get_shared_session()
    task = session.query('select parent.id from Task '
                         'where id is "{0}"'.format(
                             os.environ["FTRACK_TASKID"])).one()
    versions = session.query('AssetVersion where asset.parent.id is "{0}" and'
                             ' asset.type.short is "nuke_gizmo"'.format(
                                 task["parent"]["id"]))

    # Collect all components.
    components = []
    for version in get_latest_versions(versions):
        components.extend(version["components"])

    # Collect all new components
    new_components = []
    for component in components:
        node_exists = nuke.exists(
            HelpFunctions.safeString(component["version"]["asset"]["name"]) +
            "_" + HelpFunctions.safeString(component["name"]))
        if not node_exists:
            new_components.append(component)

    progress_bar = ProgressBar()
    progress_bar.show()
    for progress in import_components(components):
        progress_bar.bar.setValue(progress * 100)

    progress_bar.deleteLater()
Пример #4
0
def create_write_product_node():

    node = nuke.createNode('Write', inpanel=True)

    node_name = 'WriteProduct'
    node_inst = 1

    while nuke.exists(node_name + str(node_inst)):
        node_inst += 1

    node_name += str(node_inst)

    node.knob('name').setValue(node_name)
    node.knob('beforeRender').setValue(
        'dpa.nuke.utils.create_product_before_render()')
    node.knob('afterFrameRender').setValue(
        'dpa.nuke.utils.set_permissions_after_frame()')

    products_tab = nuke.Tab_Knob("Product")
    node.addKnob(products_tab)
    node.addKnob(nuke.EvalString_Knob('product_desc', 'description', ""))
    node.addKnob(nuke.EvalString_Knob('product_name', 'name', 
        get_default_product_name()))
    node.addKnob(nuke.EvalString_Knob('product_ver_note', 'description', ""))

    # hide the file knob
    node.knob('file_type').setValue('exr')
    node.knob('product_ver_note').setVisible(False)
Пример #5
0
def toggle(knob):
  """ "Inverts" some flags on the selected nodes.

  What this really does is set all of them to the same value, by finding the
  majority value and using the inverse of that."""

  value = 0
  n = nuke.selectedNodes()
  for i in n:
    try:
      val = i.knob(knob).value()
      if val:
        value += 1
      else:
        value -= 1
    except:
      pass

  status = value < 0
  for i in n:
    if not nuke.exists(i.name()+"."+knob):
      continue
    knobbie = i.knob(knob)
    knobbie_str = i.name()+"."+knob
    size = nuke.animation(knobbie_str, "size")
    if size is not None and int(size) > 0:
      knobbie.setKeyAt(nuke.frame())
      knobbie.setValue(status)
    else:
      knobbie.setValue(status)
    nuke.modified(True)
Пример #6
0
def collect_dependencies(write_nodes, views, dependency_knobs=None):
    '''
    For the given Write nodes, traverse up their hierarchy to query any nodes
    for dependency filepaths and return them.

    write_nodes: a list of Write nodes (their node names) for which to collect
                 dependencies for.

    dependency_knobs: A dictionary of nuke node types (and their knob names) for
                      which to query for dependency paths, e.g.
                            {'Read':['file'],
                             'DeepRead':['file']}

    '''
    dependency_knobs = dependency_knobs or {}
    deps = set()

    for node_name in write_nodes:
        if nuke.exists(node_name):
            write_node = nuke.toNode(node_name)
            for dep_node in get_node_dependencies(write_node):
                for knob_name in dependency_knobs.get(dep_node.Class(), []):
                    knob = dep_node.knob(knob_name)
                    if knob:
                        raw_file_path = knob.value()

                        if re.search("%[Vv]", raw_file_path):
                            for view in views:
                                view_path = re.sub("%V", view, raw_file_path)
                                view_path = re.sub("%v", view[0], view_path)
                                deps.add(view_path)
                        else:
                            deps.add(raw_file_path)

    return sorted(deps)
 def _get_all_reads(self):
     if nuke.exists("root"):
         return nuke.allNodes(group=nuke.root(),
                              filter='Read',
                              recurseGroups=True)
     else:
         return []
Пример #8
0
def getUniqueName(name):
    regex_name = re.compile('(?P<name>.*?)(?P<number>[0-9]+)$')
    while nuke.exists(name):
        info = [match.groupdict() for match in regex_name.finditer(name)]
        if info:
            info = info[0]
            name = info['name'] + str(int(info['number']) + 1)
    return name
Пример #9
0
def getAvailableName(name="Untitled"):
    ''' Returns a node name starting with @name followed by a number, that doesn't exist already '''
    i = 1
    while True:
        available_name = name + str(i)
        if not nuke.exists(available_name):
            return available_name
        i += 1
Пример #10
0
def append_knob(node, knob):
    """Add @knob as @node's last knob.  """

    knob_name = u(knob.name())
    node_name = u(node.name())
    if nuke.exists('{}.{}'.format(node_name, knob_name).encode('utf-8')):
        knob.setValue(node[knob_name.encode('utf-8')].value())
        node.removeKnob(node[knob_name.encode('utf-8')])
    node.addKnob(knob)
Пример #11
0
def node_exists(node):
    """
    Check whether or not node exists.
    """

    try:
        result = nuke.exists(node.name())
        return result
    except:
        return False
Пример #12
0
def node_exists(node):
    """
    Check whether or not node exists.
    """

    try:
        result = nuke.exists(node.name())
        return result
    except:
        return False
Пример #13
0
def _gizmo_to_group_update_ui():
    n = nuke.thisNode()
    _temp_knob_name = 'wlf_gizmo_to_group'
    _has_temp_knob = nuke.exists(
        utf8('{}.{}'.format(u(n.name()), _temp_knob_name)))

    if _has_temp_knob:
        n = edit.gizmo_to_group(n)
        n.removeKnob(n[_temp_knob_name])
        n.removeKnob(n['User'])
Пример #14
0
def _add_root_info():
    """add info to root.  """

    artist = nuke.value('preferences.wlf_artist', '')
    if not artist:
        return
    if not nuke.exists('root.wlf'):
        n = nuke.Root()
        k = nuke.Tab_Knob('wlf', b'吾立方')
        k.setFlag(nuke.STARTLINE)
        n.addKnob(k)

        k = nuke.String_Knob('wlf_artist', b'制作人')
        k.setFlag(nuke.STARTLINE)
        k.setValue(artist)
        n.addKnob(k)
    else:
        if nuke.exists('root.wlf_artist') and not nuke.value('root.wlf_artist', ''):
            nuke.knob('root.wlf_artist', artist)
Пример #15
0
def get_write_node_filepath(node_name):
    '''
    For the given Write/Deepwrite node (name), return it's output filepath ("file" attr)
    If the node does not exist or it's not a write/deepwrite node, raise an exception
    '''
    write_node_types = ["Write", "DeepWrite"]
    if not nuke.exists(node_name):
        raise Exception("Write node does not exist: %s", node_name)
    node = nuke.toNode(node_name)
    if node.Class() not in write_node_types:
        raise Exception("Node not of expected types: %s. Got: %s" % (write_node_types, node.Class()))
    return node.knob("file").value()
Пример #16
0
    def nuke_node_exists(self):
        """
        Return True or False whether or not
        nuke node exists.
        """

        try:
            full_name = self.get_nuke_node_full_name()
            return nuke.exists(full_name)

        except:
            return False
Пример #17
0
    def nuke_node_exists(self):
        """
        Return True or False whether or not
        nuke node exists.
        """

        try:
            full_name = self.get_nuke_node_full_name()
            return nuke.exists(full_name)

        except:
            return False
Пример #18
0
def createAutowrite():
	w = nuke.createNode('Write', inpanel=False)
	count = 1
	while nuke.exists('AutoWrite' + str(count)):
	    count += 1
	w.knob('name').setValue('AutoWrite' + str(count))
	w.knob('tile_color').setValue(8388607)
	t = nuke.Tab_Knob("Additional Parameters")
	w.addKnob(t)
	w.addKnob(nuke.Enumeration_Knob('outputType', 'Output Type', ['Comp', 'Precomp','LTComp','Matte']))
	w.addKnob(nuke.EvalString_Knob('aov','Prefix',''))
	w.addKnob(nuke.EvalString_Knob('descriptor','Suffix',''))
	w['file_type'].setValue('exr')
Пример #19
0
def get_write_node_filepath(node_name):
    '''
    For the given Write/Deepwrite node (name), return it's output filepath ("file" attr)
    If the node does not exist or it's not a write/deepwrite node, raise an exception
    '''
    write_node_types = ["Write", "DeepWrite"]
    if not nuke.exists(node_name):
        raise Exception("Write node does not exist: %s", node_name)
    node = nuke.toNode(node_name)
    if node.Class() not in write_node_types:
        raise Exception("Node not of expected types: %s. Got: %s" % (write_node_types, node.Class()))

    # Resolve the path of any TCL expressions, or relative path
    return resolve_knob_path(node.knob("file"))
Пример #20
0
def rename_all_nodes():
    """Rename all nodes by them belonged backdrop node ."""

    for i in nuke.allNodes('BackdropNode'):
        _nodes = i.getNodes()
        j = i['label'].value().split('\n')[0].split(' ')[0]
        for k in _nodes:
            if k.Class() == 'Group' and not '_' in k.name() and not (
                    k['disable'].value()):
                name = k.name().rstrip('0123456789')
                k.setName(name + '_' + j + '_1', updateExpressions=True)
            elif not ('_' in k.name() or nuke.exists(k.name() + '.disable') or
                      (k['disable'].value())):
                k.setName(k.Class() + '_' + j + '_1', updateExpressions=True)
Пример #21
0
def dropAutoWrite():
    """
    Creates an automatic Write node (an "AutoWrite") which uses the name and 
    path of the Nuke script that it's in to create it's own output path.
    
    Changes made to the script's name (such as versioning up) wil be reflected 
    in the output path auto-magically with no user intervention.
    """
    
    # Create the Write node that will become an AutoWrite
    w= nuke.createNode('Write', inpanel=False)
    # Rename it to AutoWrite
    # (Also, deal with the number problem)
    count = 1
    while nuke.exists('AutoWrite' + str(count)):
        count += 1
    w.knob('name').setValue('AutoWrite' + str(count))
    
    # Add the tab to hold the variables containing path fragments so we can have
    # a less messy file path.
    t = nuke.Tab_Knob("Path Fragments")
    USERNAME = os.environ["USERNAME"]
    w.addKnob(t)
    w.addKnob(nuke.EvalString_Knob('proj_root', 'Project Root', '[join [lrange [split [value root.name] / ] 0 5 ] / ]'))
    w.addKnob(nuke.EvalString_Knob('seq', 'Sequence', '[lrange [split [value root.name] / ] 6 6 ]'))
    w.addKnob(nuke.EvalString_Knob('episode', 'Episode Name', '[lrange [split [value root.name] / ] 7 7 ]'))
    w.addKnob(nuke.EvalString_Knob('shot', ' Shot Name', '[lrange [split [value root.name] / ] 8 8 ]'))
    w.addKnob(nuke.EvalString_Knob('script', 'Script Name', '[file rootname [file tail [value root.name] ] ]'))
    w.addKnob(nuke.EvalString_Knob('stripe', 'Stripe Name', '[join [lreplace [lreplace [split [file rootname [file tail [value root.name]]] _] end end] 4 4] _]'))
    w.addKnob(nuke.EvalString_Knob('user', 'userName Name', '[getenv USERNAME]'))
    
    # Display the values of our path fragment knobs on the node in the DAG for
    # error-checking.
    # This can be turned off if it makes too much of a mess for your taste.
    feedback = """
    Output Path: [value file]
    
    Project Root: [value proj_root]
    Sequence: [value seq]
    Episode Name: [value episode]
    Shot Name: [value shot]
    Script Name: [value script]
    Stripe Name: [value stripe]
    userName Name: [value user]
    """
    w.knob('label').setValue(feedback)
    
    # Re-assemble the path fragments into a proper output path
    output_path = "[value proj_root]/[value seq]/[value episode]/[value shot]/nuke/[value user]/render/[value stripe]/[value stripe].%04d.jpeg"
    w.knob('file').fromScript(output_path)
Пример #22
0
def collect_dependencies(write_nodes, views, dependency_knobs=None):
    '''
    For the given Write nodes, traverse up their hierarchy to query any nodes
    for dependency filepaths and return them.

    Note that a path value found in a node/knob may contain tcl expressions that this function
    will resolve, e.g. a path value of:
        "[python {nuke.script_directory()}]/[value seq]/[value shot]/cat.####.jpg"
    may resolve to:
        "/tmp/conductor/nuke/010/010_250/cat.%04d.jpg

    write_nodes: a list of Write nodes (their node names) for which to collect
                 dependencies for.

    dependency_knobs: A dictionary of nuke node types (and their knob names) for
                      which to query for dependency paths, e.g.
                            {'Read':['file'],
                             'DeepRead':['file']}

    '''
    dependency_knobs = dependency_knobs or {}
    deps = set()

    for node_name in write_nodes:
        if nuke.exists(node_name):
            write_node = nuke.toNode(node_name)
            for dep_node in get_node_dependencies(write_node):
                for knob_type in dependency_knobs.get(dep_node.Class(), []):
                    knob = dep_node.knob(knob_type)
                    if knob:

                        # Handle OCIOCDLTransform:  Skip node/knob if "read from file" is not enabled
                        if dep_node.Class() == "OCIOCDLTransform":
                            if not dep_node.knob("read_from_file").value():
                                logger.debug("Skipping %s",
                                             knob.fullyQualifiedName())
                                continue

                        # Resolve TCL expressions and relative paths
                        path = resolve_knob_path(knob)

                        if re.search("%[Vv]", path):
                            for view in views:
                                view_path = re.sub("%V", view, path)
                                view_path = re.sub("%v", view[0], view_path)
                                deps.add(view_path)
                        else:
                            deps.add(path)

    return sorted(deps)
Пример #23
0
def collect_dependencies(write_nodes, views, dependency_knobs=None):
    '''
    For the given Write nodes, traverse up their hierarchy to query any nodes
    for dependency filepaths and return them.

    Note that a path value found in a node/knob may contain tcl expressions that this function
    will resolve, e.g. a path value of:
        "[python {nuke.script_directory()}]/[value seq]/[value shot]/cat.####.jpg"
    may resolve to:
        "/tmp/conductor/nuke/010/010_250/cat.%04d.jpg

    write_nodes: a list of Write nodes (their node names) for which to collect
                 dependencies for.

    dependency_knobs: A dictionary of nuke node types (and their knob names) for
                      which to query for dependency paths, e.g.
                            {'Read':['file'],
                             'DeepRead':['file']}

    '''
    dependency_knobs = dependency_knobs or {}
    deps = set()

    for node_name in write_nodes:
        if nuke.exists(node_name):
            write_node = nuke.toNode(node_name)
            for dep_node in get_node_dependencies(write_node):
                for knob_type in dependency_knobs.get(dep_node.Class(), []):
                    knob = dep_node.knob(knob_type)
                    if knob:

                        # Handle OCIOCDLTransform:  Skip node/knob if "read from file" is not enabled
                        if dep_node.Class() == "OCIOCDLTransform":
                            if not dep_node.knob("read_from_file").value():
                                logger.debug("Skipping %s", knob.fullyQualifiedName())
                                continue

                        # Resolve TCL expressions and relative paths
                        path = resolve_knob_path(knob)

                        if re.search("%[Vv]", path):
                            for view in views:
                                view_path = re.sub("%V", view, path)
                                view_path = re.sub("%v", view[0], view_path)
                                deps.add(view_path)
                        else:
                            deps.add(path)

    return sorted(deps)
Пример #24
0
def get_write_node_filepath(node_name):
    '''
    For the given Write/Deepwrite node (name), return it's output filepath ("file" attr)
    If the node does not exist or it's not a write/deepwrite node, raise an exception
    '''
    write_node_types = ["Write", "DeepWrite"]
    if not nuke.exists(node_name):
        raise Exception("Write node does not exist: %s", node_name)
    node = nuke.toNode(node_name)
    if node.Class() not in write_node_types:
        raise Exception("Node not of expected types: %s. Got: %s" %
                        (write_node_types, node.Class()))

    # Resolve the path of any TCL expressions, or relative path
    return resolve_knob_path(node.knob("file"))
Пример #25
0
def createAutowrite():
    w = nuke.createNode('Write', inpanel=False)
    count = 1
    while nuke.exists('AutoWrite' + str(count)):
        count += 1
    w.knob('name').setValue('AutoWrite' + str(count))
    w.knob('tile_color').setValue(8388607)
    t = nuke.Tab_Knob("Additional Parameters")
    w.addKnob(t)
    w.addKnob(
        nuke.Enumeration_Knob('outputType', 'Output Type',
                              ['Comp', 'Precomp', 'LTComp', 'Matte']))
    w.addKnob(nuke.EvalString_Knob('aov', 'Prefix', ''))
    w.addKnob(nuke.EvalString_Knob('descriptor', 'Suffix', ''))
    w['file_type'].setValue('exr')
Пример #26
0
def create_read_sub_node():

    node = nuke.createNode('Read', inpanel=True)

    node_name = 'ReadSub'
    node_inst = 1

    while nuke.exists(node_name + str(node_inst)):
        node_inst += 1

    node_name += str(node_inst)

    node.knob('name').setValue(node_name)

    sub_tab = nuke.Tab_Knob("Sub")

    # make sure the product reprs are cached
    populate_sub_cache(refresh=False)

    repr_str_list = [DEFAULT_REPR_STR]
    repr_str_list.extend(sorted(PRODUCT_REPR_STR_TO_PATH.keys()))

    product_repr_select = nuke.Enumeration_Knob(
        'product_repr_select',
        'subscription',
        repr_str_list,
    )

    product_seq_select = nuke.Enumeration_Knob(
        'product_seq_select',
        'files',
        [],
    )

    nuke.callbacks.addKnobChanged(read_sub_knob_changed,
                                  nodeClass='Read',
                                  node=node)

    node.addKnob(sub_tab)
    node.addKnob(product_repr_select)
    node.addKnob(product_seq_select)

    # make the tab pop to front
    node['Sub'].setFlag(0)

    read_sub_knob_changed(node=node, knob=node.knob('product_repr_select'))
Пример #27
0
def create_read_sub_node():

    node = nuke.createNode('Read', inpanel=True)

    node_name = 'ReadSub'
    node_inst = 1

    while nuke.exists(node_name + str(node_inst)):
        node_inst += 1

    node_name += str(node_inst)

    node.knob('name').setValue(node_name)
    
    sub_tab = nuke.Tab_Knob("Sub")

    # make sure the product reprs are cached
    populate_sub_cache(refresh=False)

    repr_str_list = [DEFAULT_REPR_STR]
    repr_str_list.extend(sorted(PRODUCT_REPR_STR_TO_PATH.keys()))

    product_repr_select = nuke.Enumeration_Knob(
        'product_repr_select',
        'subscription',
        repr_str_list,
    )

    product_seq_select = nuke.Enumeration_Knob(
        'product_seq_select',
        'files',
        [],
    )

    nuke.callbacks.addKnobChanged(read_sub_knob_changed,
        nodeClass='Read', node=node)

    node.addKnob(sub_tab)
    node.addKnob(product_repr_select)
    node.addKnob(product_seq_select)

    # make the tab pop to front
    node['Sub'].setFlag(0) 

    read_sub_knob_changed(node=node, knob=node.knob('product_repr_select'))
Пример #28
0
def stuffShuffleSimple():
    read_node = nuke.selectedNodes('Read')
    sel0 = read_node[0]
    chnls = sel0.channels()
    lys = list(set([ech.split('.')[0] for ech in chnls]))
    lys.sort()
    p=nuke.Panel('Merge Selected Cameras and Create Channels')
    for layer in lys:
        p.addBooleanCheckBox(layer, False)
    if not p.show():
        print("Nothing selected")
        return None
    foundLy = [ea for ea in lys if p.value(ea) ]
    foundLy.sort()
    for ea_rd in read_node:
        px,py = ea_rd.xpos() -130,ea_rd.ypos() + 135
        ea_rd.setSelected(False)
        h_bias = 140
        v_bias = 40
        pos_index = len(foundLy)
        bd_nm_str = "{}_channles".format(ea_rd.name())
        bd = None
        if nuke.exists(bd_nm_str):
            bd = nuke.toNode(bd_nm_str)
        else:
            bd = nukescripts.autoBackdrop()
            bd.knob('name').setValue("{}_channles".format(ea_rd.name()))
            bd.setXpos(px-25)
            bd.setYpos(py - 25)
            bd.knob('bdwidth').setValue(420)
        bd.selectNodes()
        exist_shfs = len(nuke.selectedNodes("Shuffle"))
        for i in range(pos_index):
            shuf_1=nuke.nodes.Shuffle()
            shuf_1['in'].setValue(foundLy[i])
            shuf_1.setInput(0,ea_rd)
            shuf_1['hide_input'].setValue(True)
            shuf_1.setName("{}_".format(foundLy[i]))
            #shuf_1.knob('label').setValue("ExShf_{}_{}".format(ea_rd.name().upper(),foundLy[i]))
            shuf_1.setXYpos(px + h_bias*((i+exist_shfs)%3),py + v_bias*((i+exist_shfs)/3))
            shuf_1.setSelected(True)
    sel_shf_nm = len(nuke.selectedNodes("Shuffle"))
    newH =  38 + ((sel_shf_nm-1)/3 + 1)*40
    bd.knob('bdheight').setValue(newH)
    for ea in nuke.selectedNodes(): ea.setSelected(False)
Пример #29
0
def getReadFromWrite():
    #WriteNodes = [node for node in nuke.selectedNodes() if node.Class()=='Write']
    count = 1
    while nuke.exists('AutoWrite' + str(count)):
        count += 1
    for node in nuke.selectedNodes():
        #rfirst = int(node['first'].value())
        #rlast = int(node['last'].value())
        readNode = nuke.createNode('Read')
        readNode['file'].setValue(node['file'].getValue())
        readNode['xpos'].setValue(node['xpos'].getValue())
        readNode['ypos'].setValue(node['ypos'].getValue() + 100)
        rfirst = nuke.root().knob('first_frame').value()
        rlast = nuke.root().knob('last_frame').value()
        readNode['first'].setValue(rfirst)
        readNode['last'].setValue(rlast)
        #readNode.knob('name').setValue('AutoRead' + str(count))
        #readNode.knob('reload').execute()
Пример #30
0
def pv2_emitterListRefresh(knob, workingNode, workingNodeName):
	import nuke
	
	#get existing values
	existingValues = workingNode['pv2_emitterList'].values()
	currentValue = workingNode['pv2_emitterList'].value()
	
	#get all connected
	emittersScene = workingNode.input(1)
	notAttached = []
	notAttachedExists = []
	
	#make sure something is connected 
	if emittersScene : 
	
		#check it's a scene
		if emittersScene.Class() == 'Scene':
			#get all attached nodes
			allAttachedObjs = emittersScene.dependencies()
			allAttached = []
			for each in allAttachedObjs:
				allAttached.append(each.name())
	        	
		#get entries that arent connected and. . 
		for i in existingValues :
			if i not in allAttached:
				notAttached.append(i)
		
		#..confirm they still exist (skip 'None')
		for j in notAttached :
			if nuke.exists(j) == True:
				notAttachedExists.append(i)
		
		#add all existing entries together and sort
		for each in allAttached:
			notAttachedExists.append(each)
			
		notAttachedExists.sort()
		
	notAttachedExists.insert(0, "None")
	
	#repopulate list
	workingNode['pv2_emitterList'].setValues(notAttachedExists)
Пример #31
0
def pv2_emitterListRefresh(knob, workingNode, workingNodeName):
	import nuke
	
	#get existing values
	existingValues = workingNode['pv2_emitterList'].values()
	currentValue = workingNode['pv2_emitterList'].value()
	
	#get all connected
	emittersScene = workingNode.input(1)
	notAttached = []
	notAttachedExists = []
	
	#make sure something is connected 
	if emittersScene : 
	
		#check it's a scene
		if emittersScene.Class() == 'Scene':
			#get all attached nodes
			allAttachedObjs = emittersScene.dependencies()
			allAttached = []
			for each in allAttachedObjs:
				allAttached.append(each.name())
	        	
		#get entries that arent connected and. . 
		for i in existingValues :
			if i not in allAttached:
				notAttached.append(i)
		
		#..confirm they still exist (skip 'None')
		for j in notAttached :
			if nuke.exists(j) == True:
				notAttachedExists.append(i)
		
		#add all existing entries together and sort
		for each in allAttached:
			notAttachedExists.append(each)
			
		notAttachedExists.sort()
		
	notAttachedExists.insert(0, "None")
	
	#repopulate list
	workingNode['pv2_emitterList'].setValues(notAttachedExists)
Пример #32
0
def dropAutoWrite():
    """
    Creates an automatic Write node (an "AutoWrite") which uses the name and 
    path of the Nuke script that it's in to create it's own output path.
    
    Changes made to the script's name (such as versioning up) wil be reflected 
    in the output path auto-magically with no user intervention.
    """
    
    # Create the Write node that will become an AutoWrite
    w= nuke.createNode('Write', inpanel=False)
    # Rename it to AutoWrite
    # (Also, deal with the number problem)
    count = 1
    while nuke.exists('AutoWrite' + str(count)):
        count += 1
    w.knob('name').setValue('AutoWrite' + str(count))
    
    # Add the tab to hold the variables containing path fragments so we can have
    # a less messy file path.
    t = nuke.Tab_Knob("Path Fragments")
    w.addKnob(t)
    w.addKnob(nuke.EvalString_Knob('proj_root', 'Project Root', '[join [lrange [split [value root.name] / ] 0 4 ] / ]'))
    w.addKnob(nuke.EvalString_Knob('seq', 'Sequence', '[lrange [split [value root.name] / ] 5 5 ]'))
    w.addKnob(nuke.EvalString_Knob('shot', 'Shot Name', '[lrange [split [value root.name] / ] 6 6 ]'))
    w.addKnob(nuke.EvalString_Knob('script', 'Script Name', '[file rootname [file tail [value root.name] ] ]'))
    
    # Display the values of our path fragment knobs on the node in the DAG for
    # error-checking.
    # This can be turned off if it makes too much of a mess for your taste.
    feedback = """
    Output Path: [value file]
    
    Project Root: [value proj_root]
    Sequence: [value seq]
    Shot Name: [value shot]
    Script Name: [value script]
    """
    w.knob('label').setValue(feedback)
    
    # Re-assemble the path fragments into a proper output path
    output_path = "[value proj_root]/[value seq]/[value shot]/comps/[value script]/[value input.width]x[value input.height]/[value script].%04d.dpx"
    w.knob('file').fromScript(output_path)
Пример #33
0
def dropAutoWrite():
    """
    Creates an automatic Write node (an "AutoWrite") which uses the name and 
    path of the Nuke script that it's in to create it's own output path.
    
    Changes made to the script's name (such as versioning up) wil be reflected 
    in the output path auto-magically with no user intervention.
    """

    # Create the Write node that will become an AutoWrite
    w = nuke.createNode("Write", inpanel=False)
    # Rename it to AutoWrite
    # (Also, deal with the number problem)
    count = 1
    while nuke.exists("AutoWrite" + str(count)):
        count += 1
    w.knob("name").setValue("AutoWrite" + str(count))

    # Add the tab to hold the variables containing path fragments so we can have
    # a less messy file path.
    t = nuke.Tab_Knob("Path Fragments")
    w.addKnob(t)
    w.addKnob(nuke.EvalString_Knob("proj_root", "Project Root", "[join [lrange [split [value root.name] / ] 0 4 ] / ]"))
    w.addKnob(nuke.EvalString_Knob("seq", "Sequence", "[lrange [split [value root.name] / ] 5 5 ]"))
    w.addKnob(nuke.EvalString_Knob("shot", "Shot Name", "[lrange [split [value root.name] / ] 6 6 ]"))
    w.addKnob(nuke.EvalString_Knob("script", "Script Name", "[file rootname [file tail [value root.name] ] ]"))

    # Display the values of our path fragment knobs on the node in the DAG for
    # error-checking.
    # This can be turned off if it makes too much of a mess for your taste.
    feedback = """
    Output Path: [value file]
    
    Project Root: [value proj_root]
    Sequence: [value seq]
    Shot Name: [value shot]
    Script Name: [value script]
    """
    w.knob("label").setValue(feedback)

    # Re-assemble the path fragments into a proper output path
    output_path = "[value proj_root]/[value seq]/[value shot]/comps/[value script]/[value input.width]x[value input.height]/[value script].%04d.dpx"
    w.knob("file").fromScript(output_path)
Пример #34
0
def setSwitchRoute():
	"""
	Hook into addBeforeRender of Write nodes. Sets the "state" of 
	Swicthes across the DAG before rendering.
	"""
	try:
		route = nuke.thisNode()['switchroute'].value()
		nodename = nuke.thisNode().name()
		if route:
			ss = route.split(" ")
			for s in zip(ss[0::2],ss[1::2]):
				switchname = s[0]
				which = int(s[1])
				print "%s | %s -> %i" % (nodename, switchname, which)
				if nuke.exists(switchname):
					nuke.toNode(switchname)['which'].setValue(which)
				else:
					print "%s switch does not exists!" % name
	except NameError:
		pass
Пример #35
0
def photoshopWrite():
    w = nuke.createNode('Write', inpanel=True)
    count = 1
    while nuke.exists('photoshopWrite' + str(count)):
        count += 1
    w.knob('name').setValue('photoshopWrite' + str(count))
    
    t = nuke.Tab_Knob("Photoshop Write")
    w.addKnob(t)
    feedback = """
    [value dirName]
    """
    w.addKnob(nuke.EvalString_Knob('fileName', 'fileName', '[string trimright [string trimright [file tail [value root.name]] .nk] _thread0]'))
    w.addKnob(nuke.EvalString_Knob('dirName', 'dirName', os.path.join(jeevesStatic.jobsRoot, os.getenv('JOB'), 'vfx', 'adobe', 'photoshop', 'from_nuke', ).replace('\\', '/')))

    output_path = "[value dirName]/[value fileName]/[value fileName].%04d.tiff"
    w.knob('file').fromScript(output_path)
    
    w.knob('colorspace').setValue('srgb')
    w.knob('file_type').setValue('tiff')
    w.knob('datatype').setValue('16')
Пример #36
0
def outputWrite():
    w = nuke.createNode('Write', inpanel=True)
    count = 1
    while nuke.exists('Jeeves_Write' + str(count)):
        count += 1
    w.knob('name').setValue('Jeeves_Write' + str(count))
    
    t = nuke.Tab_Knob("Output Write")
    w.addKnob(t)
    feedback = """
    [value dirName]
    """
    w.addKnob(nuke.EvalString_Knob('fileName', 'fileName', '[string trimright [string trimright [file tail [value root.name]] .nk] _thread0]'))
    w.addKnob(nuke.EvalString_Knob('dirName', 'dirName', os.path.join(jeeves_core.jobsRoot, os.getenv('JOB'), 'vfx', 'nuke', os.getenv('SHOT'), 'plates', 'output' ).replace('\\', '/')))
    w.addKnob(nuke.Enumeration_Knob('renderType', 'render_dir', ['slapcomp', 'cleanup', 'prerender', 'matte', 'final']))

    output_path = "[value dirName]/[value renderType]/[value fileName]/[value fileName].%04d.dpx"
    w.knob('file').fromScript(output_path)
    w.knob('colorspace').setValue('linear')
    w.knob('file_type').setValue('dpx')
    w.knob('datatype').setValue('10')
Пример #37
0
def run():
    file_open = nuke.Root().name()
    x = core.locate.find()

    job = x.job
    shot = x.shot
    user = x.user
    script = x.version

    w = nuke.createNode('Write', inpanel=True)
    count = 1
    while nuke.exists('RAW_Write_' + str(count)):
        count += 1
    w.knob('name').setValue('RAW_Write_' + str(count))

    t = nuke.Tab_Knob("RAW Write")
    w.addKnob(t)
    feedback = """
    [value dirName]
    """
    w.addKnob(
        nuke.EvalString_Knob(
            'fileName', 'fileName',
            '[string trimright [string trimright [file tail [value root.name]] .nk] _thread0]'
        ))
    w.addKnob(
        nuke.EvalString_Knob(
            'dirName', 'dirName',
            os.path.join(core.jobsRoot, job, 'vfx', 'nuke', shot, 'plates',
                         'output').replace('\\', '/')))
    w.addKnob(
        nuke.Enumeration_Knob(
            'renderType', 'render_dir',
            ['slapcomp', 'cleanup', 'prerender', 'matte', 'final']))
    output_path = "[value dirName]/[value renderType]/[value fileName]/[value fileName].%04d.dpx"
    w.knob('file').fromScript(output_path)
    # w.knob('colorspace').setValue('linear')
    w.knob('raw').setValue(1)
    w.knob('file_type').setValue('dpx')
    w.knob('datatype').setValue('10')
Пример #38
0
 def alembic_rename():
     """
     Renames read geo nodes based off transform node name
     """
     # counter to use when we encounter nodes that have the name we want to use, avoids name clashes
     count = 1
     # ReadGeo2 is the class type, to check class select a node, and run nuke.selectedNode().Class()
     # Loop through all ReadGeo nodes in scene
     for node in nuke.allNodes('ReadGeo2'):
         # get the scene view values
         scene_view = node['scene_view']
         # this will return a list with the hierarchy as the first element and the
         # path as 'root/geo/shape', for example:
         # ['/root/mp_Mtn/mp_Mtn_Shape']
         full_hierarchy = scene_view.getAllItems()
         # parse string for the transform name, do this by splitting string at forward slash
         node_name = full_hierarchy[0].split("/")[-2]
         # check if node name exists, if it does append a number to avoid name clash
         if nuke.exists(node_name):
             node_name = node_name + "_" + str(count)
             count += 1
         # set name
         node['name'].setValue(node_name)
Пример #39
0
def checkNodeConnections(originalNode, lastNodeInSequence):
	global nodeConnectionSet
	global tmp 
	global tupleTmp

	#Make sure that the node you are searching to exists otherwise the test will pass incorrectly
	if nuke.exists(lastNodeInSequence):
		node = nuke.toNode(originalNode)
		#Check downstream node of the current selected node
		for downStreamNode in node.dependent():
		    if lastNodeInSequence in downStreamNode.name():
		        tmp.append(downStreamNode.name())
		        tupleTmp = tuple(tmp)
		        nodeConnectionSet.add(tupleTmp)
		        tmp = []
		    else:
		        tmp.append(downStreamNode.name())
		    #Recurse through nodes 
		    checkNodeConnections(downStreamNode.name(), lastNodeInSequence)
		return nodeConnectionSet
	else:
		nuke.tprint('The %s node does not exist, there is either a problem with the code or something is wrong with the build' % (lastNodeInSequence))
		sys.exit(1)
		print 'node error'
Пример #40
0
    def makeprogress(removeOnly):

        # make writable
        global nodestolink
        global loopbegin

        for i in nodesinbd:

            # get Loop_Begin
            if i.knob('loopbegin'):
                loopbegin = i
                i['selected'].setValue(False)

            # remove original iterationKnob
            if i.knob(iterationKnob):
                i.removeKnob(i[iterationKnob])

        # if 'parent.' should be removed from expressions in backdrop in the main graph
        if n['removeexprparent'].value():

            # for each node in the backdrop
            for selNode in nodesinbd:

                # list each knob
                for k in selNode.knobs().keys():

                    # get expression count in knob
                    exprList = selNode[k].getValue()
                    if not (type(exprList) == type([])):
                        exprList = [exprList]

                    count = len(exprList)

                    for c in xrange(count):

                        # for each knob with an expression at index c
                        if selNode[k].hasExpression(c):

                            oExpression = selNode[k].animation(c).expression()

                            # new expression placeholder
                            nExpression = oExpression

                            nExpression = nExpression.replace('parent.', '')

                            # set new expression at index c
                            selNode[k].setExpression(nExpression, c)

                            # on first iteration, print expression relinks
                            if not (oExpression == nExpression):
                                print ''
                                print SetLoopPrint + 'Removed \'.parent\' in expression for ' + selNode.name(
                                ) + '.' + k + '[' + str(c) + '], from/to:'
                                print SetLoopPrint + '-'
                                print SetLoopPrint + oExpression
                                print SetLoopPrint + nExpression
                                print ''

        # make new knobs
        if n['relinkextinputs'].value():

            for node in nodesinbd:

                if node.name() != loopbegin.name():
                    for i in xrange(0, node.inputs()):

                        try:

                            if (node.input(i)
                                    not in nodesinbd) and (nuke.exists(
                                        node.input(i).name())):

                                # make tab
                                if not node.knob(customtabname):
                                    node.addKnob(
                                        nuke.Tab_Knob(customtabname,
                                                      customtabname))

                                # make knob
                                node.addKnob(nuke.String_Knob(nodename_input))
                                # set knob value
                                node[nodename_input].setValue(
                                    node.input(i).name() + ' ' + str(i))
                                nodestolink.append(node.input(i).name())

                        except:
                            pass

        task = nuke.ProgressTask("SetLoop")
        if n['relinkextexpressions'].value():

            for eachN in nuke.allNodes(recurseGroups=False):
                allnodesinmaingraph.append(eachN.name())

        for i in xrange(0, 2):

            if i == 0:
                task.setProgress(1)
                task.setMessage("removing old loop")

                if not removeOnly:

                    if n['relinkextexpressions'].value():

                        # add each node in the main graph that's not in bd, nor is it called thisNode.name() or bd.name()
                        for h in allnodesinmaingraph:
                            if (nuke.toNode(h) not in nodesinbd) and (
                                    h != thisnode) and (h != bd.name()):
                                nodesoutsidebd.append(h)

                    if n['addIterationKnob'].value():

                        for i in nuke.selectedNodes():
                            if not i.knob(iterationKnob):

                                if not i.knob(customtabname):
                                    # make sure we're working in the custom tab
                                    i.addKnob(
                                        nuke.Tab_Knob(customtabname,
                                                      customtabname))

                                if not i.knob(iterationKnob):
                                    i.addKnob(nuke.Double_Knob(iterationKnob))

                            i.knob(iterationKnob).setExpression(n.name() +
                                                                '.offset')

                    for selectednode in nuke.selectedNodes():

                        for i in xrange(0, selectednode.inputs()):
                            try:

                                if selectednode.input(
                                        i).name() == loopbegin.name():

                                    if not selectednode.knob(
                                            customtabname
                                    ) and not selectednode == n:
                                        # make sure we're working in the custom tab
                                        selectednode.addKnob(
                                            nuke.Tab_Knob(
                                                customtabname, customtabname))

                                    selectednode.addKnob(
                                        nuke.Int_Knob(connectedtofirst))

                                    # set value of knob on node that's connected to Loop_Begin to the input it is connected with
                                    selectednode[connectedtofirst].setValue(i)

                            except:
                                pass

                    # set new clipboard
                    nuke.nodeCopy('%clipboard%')

                else:

                    # remove all inputs from EndLoop
                    for j in xrange(0, n.inputs()):
                        n.setInput(j, None)

                    # reconnect to StartLoop
                    n.setInput(0, loopbegin)

                # get all variable inputs
                for k in xrange(1, n.inputs()):

                    # and remove them
                    n.setInput(k, None)

                # dive into group
                n.begin()

                # delete previous contents
                for j in nuke.allNodes():
                    nuke.delete(j)

                if removeOnly:
                    inp = nuke.nodes.Input()
                    outp = nuke.nodes.Output()
                    outp.setInput(0, inp)

            elif i == 1:

                if not removeOnly:
                    task.setProgress(50)
                    task.setMessage("creating new loop")
                    setloop()
                break

            if task.isCancelled():

                nuke.message('Looping cancelled!')
                task.setProgress(100)
                break

            time.sleep(.5)

            # store the newest baked method
            n['method_storage'].setValue(loopmethod)

            # update the knobs in the UI
            updateKnobs()

            # set label
            n['label'].setValue('iteration: [value scroll]')
def create_AutoWrite():
    try:
        # this just test the file
        test = os.path.basename(
            nuke.root().name()).split('_v')[1].split('.nk')[0]

        #creates a unique write node name
        AutoWrite = nuke.createNode('Write', inpanel=True)
        count = 1
        while nuke.exists('AutoWrite_' + str(count)):
            count += 1
        AutoWrite.knob('name').setValue('AutoWrite_' + str(count))

        AutoWrite.addKnob(nuke.Text_Knob('AutoWrite_test', '', "AutoWrite"))

        # Create AutoWrite Tab for settings
        AW_Settings = nuke.Tab_Knob('Auto Write Settings')
        AutoWrite.addKnob(AW_Settings)

        # Create AutoWrite UI
        AutoWrite.addKnob(nuke.File_Knob(
            'AW_userCompPath',
            'Render Dir : ',
        ))
        AutoWrite['AW_userCompPath'].setValue("SET YOUR RENDER FOLDER HERE")

        # Show Output
        AutoWrite.addKnob(
            nuke.EvalString_Knob('AW_show_output', 'OUTPUT: ', ''))
        AutoWrite['AW_show_output'].setEnabled(False)

        # Script name
        AutoWrite.addKnob(
            nuke.EvalString_Knob('AW_autoScriptName', 'Script name : ', ''))
        AutoWrite['AW_autoScriptName'].setEnabled(False)

        # Version number
        AutoWrite.addKnob(
            nuke.EvalString_Knob('AW_autoVersion', 'Version : ', ''))
        AutoWrite['AW_autoVersion'].setEnabled(False)

        # Additional Information
        AutoWrite.addKnob(nuke.EvalString_Knob('AW_userInfo', 'Info : ', ''))
        AutoWrite['AW_userInfo'].setValue("Info")

        # Auto Padding
        AutoWrite.addKnob(nuke.Int_Knob('AW_userPadding', 'Padding # :'))
        AutoWrite['AW_userPadding'].setValue(4)

        # Auto Naming
        AutoWrite.addKnob(nuke.Boolean_Knob('AW_autoName', 'Auto Name?'))
        AutoWrite['AW_autoName'].setEnabled(False)

        AutoWrite.addKnob(nuke.Text_Knob('auto_divider01', '', ''))

        # Formating Options
        AutoWrite.addKnob(
            nuke.EvalString_Knob('AW_userFormat', 'Format : ', ''))
        AutoWrite['AW_userFormat'].setValue(
            'Path/Script/Version/Script_Info_Version')
        AutoWrite['AW_userFormat'].setFlag(nuke.ENDLINE)

        AutoWrite.addKnob(nuke.Text_Knob('auto_divider02', '', ''))

        AutoWrite_FormatOptions = [
            "/", "_", "Path", "Script", "Version", "Info", "Date"
        ]
        for Options in AutoWrite_FormatOptions:
            AutoWrite.addKnob(
                nuke.PyScript_Knob(
                    "Options_" + Options, Options,
                    'MOTools.updateformat_AutoWrite("' + Options + '")'))

        AutoWrite.addKnob(nuke.Text_Knob('auto_divider03', '', ''))

        # Add user info
        AutoWrite.addKnob(
            nuke.Text_Knob(
                'data', '',
                infoScript + " | " + infoContact + " | " + __version__))
        AutoWrite.addKnob(
            nuke.PyScript_Knob(
                "help", "?",
                'nukescripts.start ("https://www.mikeoakley.com/wiki/motools-for-nuke/")'
            ))

        # Auto set file_type
        AutoWrite['file_type'].setValue('exr')

        return
    except IndexError:
        nuke.message(
            "ERROR: Version naming\nex: myfile_v001.nk\n Node will be deleted")
        nuke.delete(AutoWrite)
        return
    except:
        return
Пример #42
0
def ComExists(read_node):
    return nuke.exists(read_node['name'].getValue + '_BG')
Пример #43
0
    def __init__(self, nodeType='read'):
        'Creates a custom NIM Read/Write node'

        if nodeType.lower() in ['write']:
            nodeType = 'Write'
            nodeName = 'NIM_WriteNode'
        elif nodeType.lower() in ['read']:
            nodeType = 'Read'
            nodeName = 'NIM_ReadNode'

        P.info('\nCreating %s node\n' % nodeType)

        #  Create node :
        node = nuke.createNode(nodeType)

        count = 1
        #  Get unique node name :
        while nuke.exists('%s_%03d' % (nodeName, count)):
            count += 1
        node.knob('name').setValue('%s_%03d' % (nodeName, count))

        #  Create a Tab :
        tab = nuke.Tab_Knob('NIM')
        node.addKnob(tab)

        self.nim = {}
        #  Initialize the main dictionary :
        self.elements = ['job', 'show', 'shot', 'task', 'base', 'ver']
        for elem in self.elements:
            elemDict = {}
            elemDict['name'] = ''
            elemDict['ID'] = None
            elemDict['IDs'] = []
            elemDict['list'] = []
            elemDict['input'] = None
            self.nim[elem] = elemDict

        #  Add custom knobs :
        self.nim['job']['input']=nuke.Enumeration_Knob( 'job_input', 'Job:', \
            ['xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'] )
        self.nim['show']['input']=nuke.Enumeration_Knob( 'show_input', 'Show:', \
            ['xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'] )
        self.nim['shot']['input']=nuke.Enumeration_Knob( 'shot_input', 'Shot:', \
            ['xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'] )
        self.nim['task']['input']=nuke.Enumeration_Knob( 'task_input', 'Task:', \
            ['xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'] )
        self.nim['base']['input']=nuke.Enumeration_Knob( 'base_input', 'Basename:', \
            ['xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'] )
        self.nim['ver']['input']=nuke.Enumeration_Knob( 'ver_input', 'Version', \
            ['xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'] )

        #  Add knobs to tab :
        for knob in [self.nim['job']['input'], self.nim['show']['input'], self.nim['shot']['input'], self.nim['task']['input'], \
            self.nim['base']['input'], self.nim['ver']['input']] :
            node.addKnob(knob)

        self.elem_populate('job')
        self.elem_populate('show')
        self.elem_populate('shot')
        self.elem_populate('task')
        self.elem_populate('base')
        self.elem_populate('ver')

        #  Hook up knobs :
        nuke.addKnobChanged(self.knob_changed)

        return