示例#1
0
    def renameCreateSharedToolset(self, name, rename):
        ret = False
        nameList = name.split('/')
        fileName = nameList[-1]
        del nameList[-1]
        dirs = '/'.join(nameList)
        fullPath = posixpath.join(SHARED_TOOLSET_PATH, dirs)

        try:
            if not os.path.isdir(fullPath):
                os.makedirs( fullPath )
            filePath = posixpath.join(fullPath, fileName + '.nk')
            if not os.path.exists(filePath):
                if self.rename == True:
                    os.rename(self.fullFilePath, filePath)
                else:
                    # create way
                    nuke.nodeCopy(filePath)
            elif nuke.ask('Overwrite existing \n %s?' % filePath):
                if self.rename == True:
                    os.remove(filePath)
                    os.rename(self.fullFilePath, filePath)
                else:
                    # create way
                    nuke.nodeCopy(filePath)
            ret = True
        except:
            ret = False
        return ret
def tetherCopy(nodes):
    cp = list()
    unselectAll()
    for n in nodes:
        n.setSelected(True)
        nuke.nodeCopy("%clipboard%")
        n.setSelected(False)
        nuke.nodePaste("%clipboard%")

        cp.append(nuke.selectedNodes()[0])
        copy = cp[len(cp) - 1]
        copy.setSelected(False)
        copy["xpos"].setValue(n["xpos"].value() + 50)
        copy["ypos"].setValue(n["ypos"].value() + 50)

    if len(cp) <= len(nodes):
        for i in range(len(cp)):
            src = nodes[i]
            dst = cp[i]
            deps = src.dependencies()
            for di in range(len(deps)):
                d = deps[di]
                if d in nodes:
                    ni = nodes.index(d)
                    if src.input(di) is not None:
                        dst.connectInput(di, cp[ni])
                else:
                    if src.input(di) is not None:
                        dst.connectInput(di, d)

    for n in cp:
        n.setSelected(True)
    def process(self, instance):
        import os

        import nuke

        if not instance.data["publish"]:
            return

        file_path = instance.data["output_path"]
        directory = os.path.dirname(file_path)

        # Create workspace if necessary
        if not os.path.exists(directory):
            os.makedirs(directory)

        # Export gizmo
        # Deselect all nodes
        for node in nuke.selectedNodes():
            node["selected"].setValue(False)

        instance[0]["selected"].setValue(True)

        nuke.nodeCopy(file_path)

        data = ""
        with open(file_path, "r") as f:
            data = f.read()

        data = data.replace("set cut_paste_input [stack 0]\n", "")
        data = data.replace("push $cut_paste_input\n", "")
        data = data.replace("Group {\n", "Gizmo {\n")

        with open(file_path, "w") as f:
            f.write(data)
示例#4
0
    def testDefaultExpression(self):

        # create opholder and check the default expression we asked for works

        fnOH = IECoreNuke.FnOpHolder.create("op", "add", 1)
        self.assertEqual(fnOH.node().knob("parm_a").toScript(),
                         '{"frame * 2"}')
        self.failUnless(fnOH.node().knob("parm_a").isAnimated())

        self.assertEqual(nuke.frame(), 1)
        self.assertEqual(fnOH.node().knob("parm_a").getValue(), 2)

        # remove the expression, cut and paste the node, and make sure
        # it doesn't reappear

        fnOH.node().knob("parm_a").clearAnimated()
        self.failIf(fnOH.node().knob("parm_a").isAnimated())

        nuke.nodeCopy("test/IECoreNuke/parameterisedHolder.nk")

        nuke.scriptClear()

        n = nuke.nodePaste("test/IECoreNuke/parameterisedHolder.nk")

        fnOH = IECoreNuke.FnOpHolder(n)
        self.assertEqual(fnOH.node().knob("parm_a").toScript(), "2")
示例#5
0
文件: publish.py 项目: parimalvfx/ada
def publish(save_dir, save_name, nodes=None):
    """
    Very simple "publisher" where the script is saved along side a graph file.

    Args:
        save_dir (str): A valid file path.
        save_name (str): What you want to call the script.
        nodes (list): List of nodes to publish.

    Returns:

    """
    nodes = nodes or nuke.selectedNodes()

    if not os.path.exists(save_dir):
        return

    id, path = tempfile.mkstemp(".nk", "F_")
    nuke.nodeCopy(path)

    nuke_script = "F_{0}.nk".format(save_name)
    script_path = os.path.join(save_dir, nuke_script)
    shutil.move(path, script_path)

    processor = Engine()
    nodes = processor.gather(nodes)
    queue = processor.queue(nodes)

    graph = serialise_node_knobs(queue)
    write_proto_file(graph, save_dir, "F_{0}".format(save_name), ".graph")

    return graph, script_path
    def process(self, instance):
        node = instance[0]

        ext = "nknc" if nuke.env["nc"] else "nk"

        staging_dir = utils.stage_dir()
        filename = "%s.%s" % (instance.data["subset"], ext)
        outpath = "%s/%s" % (staging_dir, filename)

        instance.data["repr.nkscript._stage"] = staging_dir
        instance.data["repr.nkscript._files"] = [filename]
        instance.data["repr.nkscript.scriptName"] = filename
        instance.data["repr.nkscript.outputNode"] = node.fullName()

        with lib.maintained_selection():
            lib.reset_selection()
            for n in walk_tree(node):
                n["selected"].setValue(True)

            if node.Class() == "Write":
                # Swap image file path to published path bedore copy
                output = node["file"].value()
                node["file"].setValue(instance.data["publishedSeqPatternPath"])
                nuke.nodeCopy(outpath)
                node["file"].setValue(output)

            else:
                nuke.nodeCopy(outpath)
示例#7
0
 def bntSavePressed(self, a):
     panel = nuke.Panel("Name me!!!")
     panel.addSingleLineInput("Name:", "")
     if panel.show():
         a = panel.value("Name:")
     nuke.nodeCopy(pathToTemplates + a)
     self.close()
示例#8
0
    def _create_toolset(self):
        """
        If all condition are met, create a toolset in the selected
        folder...

        :return:
        """

        index = self.toolset_directory.currentIndex()
        name = self.toolset_name.text() + '.nk'

        path = os.path.abspath(
            os.path.join(self.toolset_directory.itemData(index), name))
        _message = self._condition(name, path)

        if not _message:
            return False

        gf.mkdir(os.path.dirname(path))
        nuke.nodeCopy(path)

        shared_toolset_api.refresh_toolset()
        self._message.setText('Toolset has been created...')
        self._message.exec_()

        return True
示例#9
0
    def get_view_process_node(self):

        # Select only the target node
        if nuke.selectedNodes():
            [n.setSelected(False) for n in nuke.selectedNodes()]

        ipn_orig = None
        for v in [n for n in nuke.allNodes()
                  if "Viewer" in n.Class()]:
            ip = v['input_process'].getValue()
            ipn = v['input_process_node'].getValue()
            if "VIEWER_INPUT" not in ipn and ip:
                ipn_orig = nuke.toNode(ipn)
                ipn_orig.setSelected(True)

        if ipn_orig:
            nuke.nodeCopy('%clipboard%')

            [n.setSelected(False) for n in nuke.selectedNodes()]  # Deselect all

            nuke.nodePaste('%clipboard%')

            ipn = nuke.selectedNode()

            return ipn
示例#10
0
def main():
    grp=nuke.thisNode()
    for n in nuke.allNodes():
        try:
            path=n.filename()
            if 'gizmo' in path:
                name=n.name()
                nodeInputs=[]
                for i in range(n.inputs()):
                    nodeInputs.append(n.input(i))
                nPos=[n.xpos(),n.ypos()]
                nName=n.name()
                c = n.makeGroup()
                c.setSelected(1)
                nuke.nodeCopy('%clipboard%')
                nuke.delete(c)
                with grp:
                    n.setSelected(1)
                    c=nuke.nodePaste('%clipboard%')
                    nuke.delete(n)
                    c.setXYpos(nPos[0],nPos[1])
                    c.setName(nName)
                    for i in range(len(nodeInputs)):
                        c.setInput(i,nodeInputs[i])

        except:
            pass
	def testDefaultExpression( self ) :

		# create opholder and check the default expression we asked for works

		fnOH = IECoreNuke.FnOpHolder.create( "op", "add", 1 )
		self.assertEqual( fnOH.node().knob( "parm_a" ).toScript(), '{"frame * 2"}' )
		self.failUnless( fnOH.node().knob( "parm_a" ).isAnimated() )

		self.assertEqual( nuke.frame(), 1 )
		self.assertEqual( fnOH.node().knob( "parm_a" ).getValue(), 2 )

		# remove the expression, cut and paste the node, and make sure
		# it doesn't reappear

		fnOH.node().knob( "parm_a" ).clearAnimated()
		self.failIf( fnOH.node().knob( "parm_a" ).isAnimated() )

		nuke.nodeCopy( "test/IECoreNuke/parameterisedHolder.nk" )

		nuke.scriptClear()

		n = nuke.nodePaste( "test/IECoreNuke/parameterisedHolder.nk" )

		fnOH = IECoreNuke.FnOpHolder( n )
		self.assertEqual( fnOH.node().knob( "parm_a" ).toScript(), "2" )
示例#12
0
    def process(self, instance):

        if not instance.data["publish"]:
            return

        file_path = instance.data["output_path"]
        directory = os.path.dirname(file_path)

        # Create workspace if necessary
        if not os.path.exists(directory):
            os.makedirs(directory)

        # Export gizmo
        # Deselect all nodes
        for node in nuke.selectedNodes():
            node["selected"].setValue(False)

        instance[0]["selected"].setValue(True)

        nuke.nodeCopy(file_path)

        data = ""
        with open(file_path, "r") as f:
            data = f.read()

        data = data.replace("set cut_paste_input [stack 0]\n", "")
        data = data.replace("push $cut_paste_input\n", "")
        data = data.replace("Group {\n", "Gizmo {\n")

        with open(file_path, "w") as f:
            f.write(data)
示例#13
0
 def export_as(self, version):
     """the export action for nuke environment
     """
     # set the extension to '.nk'
     version.extension = '.nk'
     nuke.nodeCopy(version.fullPath)
     return True
示例#14
0
 def export_as(self, version):
     """the export action for nuke environment
     """
     # set the extension to '.nk'
     version.extension = '.nk'
     nuke.nodeCopy(version.fullPath)
     return True
示例#15
0
文件: orgnize.py 项目: tws0002/Nuke-2
def split_by_backdrop():
    # TODO: need refactor and test.
    """Split workfile to multiple file by backdrop."""

    text_saveto = '保存至:'
    text_ask_if_create_new_folder = '目标文件夹不存在, 是否创建?'

    # Panel
    panel = nuke.Panel('splitByBackdrop')
    panel.addFilenameSearch(text_saveto, os.getenv('TEMP'))
    panel.show()

    # Save splited .nk file
    save_path = panel.value(text_saveto).rstrip('\\/')
    noname_count = 0
    for i in nuke.allNodes('BackdropNode'):
        label = repr(i['label'].value()).strip("'").replace('\\', '_').replace(
            '/', '_')
        if not label:
            noname_count += 1
            label = 'noname_{0:03d}'.format(noname_count)
        if not os.path.exists(save_path):
            if not nuke.ask(text_ask_if_create_new_folder):
                return False
        dir_ = save_path + '/splitnk/'
        dir_ = os.path.normcase(dir_)
        if not os.path.exists(dir_):
            os.makedirs(dir_)
        filename = dir_ + label + '.nk'
        i.selectOnly()
        i.selectNodes()
        nuke.nodeCopy(filename)
    os.system('explorer "' + dir_ + '"')
    return True
    def extract_nkscript(self, packager):
        node = self.member[0]

        package_path = packager.create_package()

        ext = "nknc" if nuke.env["nc"] else "nk"

        fname = packager.file_name(extension=ext)
        fpath = os.path.join(package_path, fname)

        with lib.maintained_selection():
            lib.reset_selection()
            for n in walk_tree(node):
                n["selected"].setValue(True)

            if node.Class() == "Write":
                # Swap image file path to published path bedore copy
                output = node["file"].value()
                node["file"].setValue(self.data["publishedSeqPatternPath"])
                nuke.nodeCopy(fpath)
                node["file"].setValue(output)

            else:
                nuke.nodeCopy(fpath)

        packager.add_data({
            "outputNode": node.fullName(),
            "scriptName": fname,
        })
示例#17
0
def sendNodes():
    # ----------------------------------------------------------------------------
    # (NOTE: Change this to an email address you have created.)
    fromaddr = '*****@*****.**'
    username = '******'
    password = '******'
    # ----------------------------------------------------------------------------

    # Grab the selected nodes and copy to the clipboard.
    try:
        nuke.selectedNodes()
        nuke.nodeCopy(nukescripts.cut_paste_file())
        clipboard = QtGui.QApplication.clipboard()
        clipboard = clipboard.text()
    except:
        nuke.message(
            "You have to select something first. Try clicking and dragging")
        return

    # Grab some input from the user, exit if they pressed cancel
    p = nuke.Panel('Send nodes via email')
    p.addSingleLineInput('To:', '*****@*****.**')
    p.addSingleLineInput('Subject:', 'My copied node setup')
    p.addNotepad('Body:', clipboard)
    p.addButton('Cancel')
    p.addButton('Send')
    if p.show() == 0:
        return

    # Exit if we only have the default/example email address
    toaddrs = p.value('To:')
    if toaddrs == '*****@*****.**':
        nuke.message(
            "Please provide an email address other than the default example.")
        return

    # Exit if we don't have a message body
    body = p.value('Body:')
    if body == '':
        nuke.message("Please provide a message body.")
        return

    # Format the body to include the subject lines
    body = 'Subject: %s\n\n%s' % (p.value('Subject:'), body)

    # Everything checks out, let's try to send it!
    try:
        server = SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.login(username, password)
        server.sendmail(fromaddr, toaddrs, body)
        server.quit()
        nuke.message('Your nodes have been sent to "%s"!' % toaddrs)
    except:
        nuke.message("Error occured. Couldn't send nodes.")
        nuke.tprint("Error occured. Couldn't send nodes.")
        nuke.tprint(sys.exc_type)
        nuke.tprint(sys.exc_value)
示例#18
0
文件: nukeEnv.py 项目: eoyilmaz/anima
 def export_as(self, version):
     """the export action for nuke environment
     """
     # set the extension to '.nk'
     version.update_paths()
     version.extension = self.extensions[0]
     nuke.nodeCopy(version.absolute_full_path)
     return True
示例#19
0
 def export_as(self, version):
     """the export action for nuke environment
     """
     # set the extension to '.nk'
     version.update_paths()
     version.extension = self.extensions[0]
     nuke.nodeCopy(version.absolute_full_path)
     return True
 def copyNode(self):
     nuke.nodeCopy('%clipboard%')
     copied = nuke.nodePaste('%clipboard%')
     copied.setInput(0, None)
     # remove dependencies
     if len(copied.dependent()) > 0:
         copied.dependent()[0].setInput(0, None)
     return copied
示例#21
0
def addLocal():

    # path variables

    repo = '/mnt/karramba'
    home = '/home/tfx/job.local'

    # copies footage to local machine

    readList = [
        node.knob('file').value() for node in nuke.selectedNodes('Read')
    ]

    for path in readList:

        fileDirList = [
            path.rsplit(os.sep, 1)[0] + os.sep + img
            for img in os.listdir(path.rsplit(os.sep, 1)[0])
            if img[:len(path.rsplit(os.sep, 1)[1].split('%')[0])] ==
            path.rsplit(os.sep, 1)[1].split('%')[0]
        ]

        for img in fileDirList:

            newPath = home + img.rsplit(os.sep, 1)[0].split(repo)[-1] + os.sep
            if not os.path.exists(newPath):
                os.makedirs(newPath)
            shutil.copy(img, newPath)

#creates new read nodes and controller to switch controller between local and network

    for node in nuke.selectedNodes('Read'):

        node.setSelected(True)

        sw = nuke.createNode('Switch', inpanel=False)
        sw.setSelected(False)
        sw.knob('which').setExpression('locController.location')
        node.setSelected(True)
        nuke.nodeCopy('%context%')
        c = nuke.nodePaste('%context%')

        sw.setInput(0, c)
        sw.setInput(1, node)

        node.setYpos(node.ypos() - 90)
        c.setYpos(node.ypos())
        c.setXpos(node.xpos() - 150)

        c.setName(c.name() + 'Local')
        node.setName(node.name() + 'Network')

        c.knob('file').setValue(home +
                                node.knob('file').value().split(repo)[-1])

        node.setSelected(False)
        c.setSelected(False)
示例#22
0
    def load(self, context, name, namespace, data):
        # get main variables
        version = context['version']
        version_data = version.get("data", {})
        vname = version.get("name", None)
        first = version_data.get("frameStart", None)
        last = version_data.get("frameEnd", None)
        fps = version_data.get("fps") or nuke.root()["fps"].getValue()
        namespace = namespace or context['asset']['name']
        object_name = "{}_{}".format(name, namespace)

        # prepare data for imprinting
        # add additional metadata from the version to imprint to Avalon knob
        add_keys = ["source", "author", "fps"]

        data_imprint = {
            "frameStart": first,
            "frameEnd": last,
            "version": vname,
            "objectName": object_name
        }

        for k in add_keys:
            data_imprint.update({k: version_data[k]})

        # getting file path
        file = self.fname.replace("\\", "/")

        with anlib.maintained_selection():
            camera_node = nuke.createNode(
                "Camera2",
                "name {} file {} read_from_file True".format(
                    object_name, file),
                inpanel=False)
            camera_node.forceValidate()
            camera_node["frame_rate"].setValue(float(fps))

            # workaround because nuke's bug is not adding
            # animation keys properly
            xpos = camera_node.xpos()
            ypos = camera_node.ypos()
            nuke.nodeCopy("%clipboard%")
            nuke.delete(camera_node)
            nuke.nodePaste("%clipboard%")
            camera_node = nuke.toNode(object_name)
            camera_node.setXYpos(xpos, ypos)

        # color node by correct color by actual version
        self.node_version_color(version, camera_node)

        return containerise(node=camera_node,
                            name=name,
                            namespace=namespace,
                            context=context,
                            loader=self.__class__.__name__,
                            data=data_imprint)
示例#23
0
def createArtifact():

    if nuke.GUI == True:

        filepath = nuke.value("root.name")
        nukescript = filepath[:-3]
        nuke.selectAll()
        nuke.nodeCopy(nukescript + '_artifact.nk')
        nukescripts.clear_selection_recursive()

    return
示例#24
0
def reduce_selected_brush_stroke(withDefaults=False):
    #------------------------
    #       SETTINGS
    #------------------------
    epsilon     = 10                    #Your threshold
    frame       = nuke.frame()          #The frame to reference...
    rpNode      = nuke.selectedNode()   #The node to process
    makeCopy    = False                 #Since nuke.Undo is broken, we want to make a backup

    if not withDefaults:
        #Make a little fancy menu
        p = nuke.Panel('Reduce Brush Strokes :: Settings')
        p.addSingleLineInput('Epsilon', '10')
        p.addBooleanCheckBox('Make Copy of Node?', False)
        ret = p.show()
        epsilon = float(p.value('Epsilon'))
        makeCopy =  p.value('Make Copy')

    if makeCopy: #Make a copy of the selected node.
        originalNode = rpNode
        nuke.nodeCopy('%clipboard%')
        nuke.nodePaste('%clipboard%')
        rpNode =  nuke.selectedNode()
        rpNode.setInput(0,originalNode.input(0))

    solver = DPAlgorithm() #The algorithm object
    cKnob= rpNode['curves']
    selectedShapes = cKnob.getSelected()
    task = nuke.ProgressTask('Reducing Roto...')
    task.setProgress(0)  
    for i,shape in enumerate(selectedShapes) :
        thisShape = [] 
        alen = float(len(selectedShapes))                       #Used to calculate progress

        try:         
            for x,p in enumerate(shape) :                       #Get a list of all the points in the roto shape
                tempPosition = p.getPosition(frame)
                thisShape.append([tempPosition[0],tempPosition[1],x])

            reducedShape = solver.rdp(thisShape,epsilon)        #Magic happens here.. reduce the shape  

            for x,p in reversed( list( enumerate( shape) ) ) :  #Go through all of the points in reversed order and remove the ones that are not in the reduced list
                slen=float(len(shape))                          #Used to calculate progress
                tempPosition = p.getPosition(frame)             #LAZY!!!
                
                if not [tempPosition[0],tempPosition[1],x] in reducedShape :
                    shape.remove(x)                             #Damn, this thing is slow! (could be threaded!?)

                task.setProgress(int(((float(i)/alen)+((float(slen-x)/slen)/alen))*100.0)) #Update the progress bar
                task.setMessage("Processing point %s in brush %s (yes, this is slow)" %(x,i))  
        except:
            pass #Not a supported item                             

    task.setProgress(100)    
示例#25
0
	def testCopyPasteNoValue( self ) :

		n = nuke.createNode( "ieObject" )
		self.assertEqual( nuke.selectedNodes(), [ n ] )

		nuke.nodeCopy( "test/IECoreNuke/objectKnob.nk" )

		nuke.scriptClear()

		n2 = nuke.nodePaste( "test/IECoreNuke/objectKnob.nk" )
		self.assertEqual( n2.knob( "object" ).getValue(), None )
示例#26
0
	def testCopyPasteNoValue( self ) :

		n = nuke.createNode( "ieObject" )
		self.assertEqual( nuke.selectedNodes(), [ n ] )

		nuke.nodeCopy( "test/IECoreNuke/objectKnob.nk" )

		nuke.scriptClear()

		n2 = nuke.nodePaste( "test/IECoreNuke/objectKnob.nk" )
		self.assertEqual( n2.knob( "object" ).getValue(), None )
示例#27
0
def publishTemplate(outputPath, locationType, templateType, templateName,
                    counter):
    # change directory to output path
    os.chdir(outputPath)
    # print os.getcwd()

    ## Check if the location folder already exists or not.
    if not os.path.exists(locationType):
        os.mkdir(locationType)

    # change directory path to the locationType
    os.chdir(outputPath + "/" + locationType)

    ## Check if the template folder already exists or not.
    if not os.path.exists(templateType):
        os.mkdir(templateType)

    newTemplatePath = outputPath + "/" + locationType + "/" + templateType + "/" + templateName + ".nk"
    # print newTemplatePath

    selectedNodes = nuke.selectedNodes()
    if counter == 1:
        selectedNodes = selectedNodes[::-1]

    # print [node.name() for node in oldSelectedNodes]
    if selectedNodes:
        print[node.name() for node in selectedNodes]
        viewerNodes = filter(lambda viewer: viewer.Class() == "Viewer",
                             selectedNodes)
        if viewerNodes:
            selectedNodes = filter(
                lambda viewer: not viewer.Class() == "Viewer", selectedNodes)
            nukescripts.clear_selection_recursive()
            map(lambda node: node['selected'].setValue('True'), selectedNodes)
        if not selectedNodes[-1].Class() == "BackdropNode":
            newBd = nukescripts.autoBackdrop()
            newBd['selected'].setValue('True')
            selectedNodes.append(newBd)
            print[node.name() for node in selectedNodes]

        # check if file already exists
        if os.path.isfile(newTemplatePath):
            userInput = nuke.ask(
                "The template already exists. Are you sure you want to override?"
            )
            if userInput:
                nuke.nodeCopy(newTemplatePath)
            else:
                showPublishPanel(1)
        else:
            print newTemplatePath
            nuke.nodeCopy(newTemplatePath)
    else:
        nuke.message("Please select nodes!")
示例#28
0
def showPublishTemplatePanel():

    # Add GUI elements
    panel = nuke.Panel("Publish Template", 450)

    currentScriptName = nuke.Root().name().split('/')[-1][0:-3]

    panel.addSingleLineInput("Script Name:", currentScriptName)
    panel.addFilenameSearch("Output Path:", "Select Output Path")
    panel.addEnumerationPulldown("Select Nodes:", "All Selected")
    panel.addButton("Cancel")
    panel.addButton("Publish Template")

    # Show GUI
    result = panel.show()

    #if user publishes the template
    if result == 1:

        outputPath = panel.value("Output Path:")
        scriptName = panel.value("Script Name:")
        outputNodes = panel.value("Select Nodes:")

        ##Check for output path errors
        if outputPath == "Select Output Path":
            nuke.message("Please select output path")
            showPublishTemplatePanel()

        #Check if user input is all or selected nodes
        if outputNodes == "All":  # ALL NODES IN THE CURRENT SCRIPT
            #pick all read nodes
            nodes = nuke.allNodes("Read")

            #select all the nodes
            nuke.selectAll()

            #copy selected nodes to a new nuke script
            nuke.nodeCopy(outputPath + scriptName + '.nk')
            return outputPath, scriptName, nodes
        else:
            ## Check if user has selected nodes
            if nuke.selectedNodes() == []:
                nuke.message("Please select the nodes.")
                #Don't bring up the tool
                return

            nodes = nuke.selectedNodes(
                "Read")  # SELECTED NODES IN THE CURRENT SCRIPT
            # copy selected nodes to a new nuke script
            nuke.nodeCopy(outputPath + scriptName + '.nk')

            return outputPath, scriptName, nodes
示例#29
0
    def add_btn_clicked(self):
        current_node = nuke.selectedNodes()

        existItem = False

        if len(current_node) > 0:
            if len(current_node) == 1:
                tool_name = nuke.getInput(u'请输入预设名字:',
                                          current_node[0].name()[:-1])
            else:
                tool_name = nuke.getInput(u'请输入预设名字:')

            if tool_name:
                if self.tool_list.count() == 0:
                    existItem = True

                else:
                    for list_num in xrange(self.tool_list.count()):
                        if self.tool_list.item(list_num).text() == tool_name:
                            QtGui.QMessageBox.information(
                                self, u"提示", u"您选的节点已添加过了,请不要重复添加")
                            existItem = False
                            break
                        else:
                            existItem = True

                if existItem:
                    tool_item = QtGui.QListWidgetItem(tool_name)
                    tool_item.setTextAlignment(
                        QtCore.Qt.AlignCenter)  # 设置item居中
                    tool_item.setSizeHint(
                        QtCore.QSize(tool_item.sizeHint().width(),
                                     25))  # 设置item高度
                    self.tool_list.addItem(tool_item)

                    # 保存成预设文件
                    toolset_path = os.path.join(config_dir,
                                                "%s.nk" % tool_name)
                    nuke.nodeCopy(toolset_path.encode("gbk"))

                    # 写入json
                    tools_list = read_json()
                    current_tool = {
                        "name": tool_name,
                        "type": "tool_set",
                        "command": toolset_path.replace("\\", "/")
                    }
                    tools_list.append(current_tool)
                    write_json(tools_list)

        else:
            QtGui.QMessageBox.information(self, u"提示", u"请选择节点")
示例#30
0
 def addToTool(self):
     input = self.nameKnob.value()
     if input == "":
         pass
     elif input.split("/")[-1] == "":
         pass
     else:
         file = "%s/%s.nk" % (RootPath, input)
         print file
         filePath = os.path.dirname(file)
         if not os.path.exists(filePath):
             os.makedirs(filePath)
         nuke.nodeCopy(file)
示例#31
0
def selectBackdropContents(backdropNode):
    '''Select all nodes inside a backdrop.
    There is a built in method for this on Nuke6.3v5,
    but this is kept here to expand compatibility
    to earlier versions
    '''
    bx, by = backdropNode.xpos(), backdropNode.ypos()
    nukescripts.clear_selection_recursive()
    backdropNode.setSelected(True)
    nuke.nodeCopy(nukescripts.cut_paste_file())
    nuke.nodeDelete(popupOnError=False)
    nuke.nodePaste(nukescripts.cut_paste_file())
    nuke.selectedNode().setXYpos(bx, by)
示例#32
0
def export_selected_nodes():
    path = nuke.getFilename("Export Selected To:")
    if not path:
        return
    nuke.nodeCopy(path)
    root = nuke.root()
    rootstring = root.writeKnobs(nuke.TO_SCRIPT | nuke.WRITE_USER_KNOB_DEFS)
    rootstring = "%s\nfirst_frame %d\nlast_frame %d" % (rootstring, root['first_frame'].value(), root['last_frame'].value())
    rootstring = "%s\nproxy_format \"%s\"" % (rootstring, root['proxy_format'].toScript())
    rootstring = "Root {\n%s\n}" % rootstring
    noroot = open(path).read()
    with open(path, "w+") as f:
        f.write((rootstring + "\n" + noroot))
示例#33
0
def sb_globalToolSet(defaultPath):

    # Create the panel.
    p = nuke.Panel( "sb_globalToolSet" )
    p.addFilenameSearch('Folder path', defaultPath)
    p.addSingleLineInput('Subfolder', '(Optional)')
    p.addSingleLineInput('ToolSet name', '')
    result = p.show()
    
    if result:
    
        n = nuke.selectedNodes()
    
        if len(n) == 0:
            nuke.message("No nodes selected.")
            return

        folderPath = p.value("Folder path")
        name = p.value("ToolSet name")
        sub = p.value("Subfolder")

        if folderPath == "":
            nuke.message("Specify a folder path.")
            return

        if not folderPath.endswith("/"):
            folderPath = "{0}/".format(folderPath)

        if name == "":
            nuke.message("Specify a name.")
            return

        if sub == "" or sub == "(Optional)":
            folderPath = folderPath
        else:
            folderPath = "{0}{1}/".format(folderPath, sub.replace(" ", "_"))

        if not os.path.exists(folderPath):
            try:
                os.makedirs(folderPath)
            except:
                print "Can't create folder at:\n\n{0}".format(folderPath)
                return

        nameFix = name.replace(" ", "_")

        # Create the file.
        toolset = "{0}{1}.nk".format(folderPath, nameFix)
        nuke.nodeCopy(toolset)

        print "{0}.nk was successfully exported as a ToolSet.".format(nameFix)
示例#34
0
def addLocal():
	
	# path variables

	repo = '/mnt/karramba'
	home = '/home/tfx/job.local'
	

# copies footage to local machine

	readList = [node.knob('file').value() for node in nuke.selectedNodes('Read')]
	

	for path in readList:
		
		fileDirList =[path.rsplit(os.sep,1)[0] + os.sep + img for img in os.listdir(path.rsplit(os.sep,1)[0]) if img[:len(path.rsplit(os.sep,1)[1].split('%')[0])] == path.rsplit(os.sep,1)[1].split('%')[0]]
		
		for img in fileDirList:
			
			newPath = home + img.rsplit(os.sep, 1)[0].split(repo)[-1] + os.sep
			if not os.path.exists(newPath):
				os.makedirs(newPath)
			shutil.copy(img, newPath)

#creates new read nodes and controller to switch controller between local and network
			
	for node in nuke.selectedNodes('Read'):
		
		node.setSelected(True)
		
		sw = nuke.createNode('Switch', inpanel=False)
		sw.setSelected(False)
		sw.knob('which').setExpression('locController.location')
		node.setSelected(True)
		nuke.nodeCopy('%context%')
		c = nuke.nodePaste('%context%')
		
		sw.setInput(0, c)
		sw.setInput(1, node)
		
		node.setYpos(node.ypos()-90)
		c.setYpos(node.ypos())
		c.setXpos(node.xpos()-150)
		
		c.setName(c.name() + 'Local')
		node.setName(node.name() + 'Network')
		
		c.knob('file').setValue(home + node.knob('file').value().split(repo)[-1])
		
		node.setSelected(False)
		c.setSelected(False)
示例#35
0
def gizmoToGroup():
    grp= nuke.thisGroup()
    if not grp.Class()=='root':
        with grp:
            n=nuke.selectedNode()
            nPos=[n.xpos(),n.ypos()]
            nName=n.name()
            c = n.makeGroup()
    nuke.nodeCopy('%clipboard%')
    with grp:
        c=nuke.nodePaste('%clipboard%')
        nuke.delete(n)
        c.setXYpos(nPos[0],nPos[1])
        c.setName(nName)
示例#36
0
def add_template(template_name):
    root_menu = nuke.menu('Nuke')
    template_menu = 'Toolkit/{}/{}'.format(user_name, template_name)
    if not root_menu.findItem(template_menu):
        if not os.path.isdir('{}/{}'.format(TOOLKIT_ROOT, user_name)):
            os.makedirs('{}/{}'.format(TOOLKIT_ROOT, user_name))
        nuke.nodeCopy('{}/{}/{}.nk'.format(TOOLKIT_ROOT, user_name,
                                           template_name))
        root_menu.addCommand(
            'Toolkit/{}/{}/{}'.format(user_name, template_name, template_name),
            lambda: nuke.scriptReadFile('{}/{}/{}.nk'.format(
                TOOLKIT_ROOT, user_name, template_name)))
        root_menu.addCommand(
            'Toolkit/{}/{}/remove'.format(user_name, template_name),
            lambda: remove_template(template_name))
示例#37
0
    def copy(self, num):
        ### Creates the MultiClipBoard folder inside of user's .nuke folder if it doesnt exist.
        self.loadPath = self.getFolder()
        osdir = nuke.callbacks.filenameFilter(self.loadPath)
        try:
            os.makedirs(osdir)
            print "Initial directories created"
        except OSError:
            pass

        ### Copies the script
        self.savePath = self.loadPath + '/' + 'mCB_data_' + str(num) + '.nk'
        nuke.nodeCopy(self.savePath)

        print "Selected nodes saved to " + self.savePath
示例#38
0
def copy_viewer_input(node=None):
    """
    :param node: viewerInput
    :return: copy of current Viewer input
    """
    orig = nuke.selectedNodes()
    [x.setSelected(False) for x in nuke.selectedNodes()]
    node.setSelected(True)
    nuke.nodeCopy("%clipboard%")
    node.setSelected(False)
    nuke.nodePaste("%clipboard%")
    new_node = nuke.selectedNode()
    [x.setSelected(False) for x in nuke.selectedNodes()]
    [x.setSelected(True) for x in orig]
    return new_node
示例#39
0
def copySpecial():
    """copy selection, paste and reconnect (just one node)"""
    depNode = nuke.dependencies(nuke.selectedNode())
    dependNode = nuke.dependentNodes(nuke.INPUTS or nuke.HIDDEN_INPUTS or nuke.EXPRESSIONS, [nuke.selectedNode()])
    i = 0
    if dependNode[0].Class() in ['Scene', 'MergeGeo']:
        i = nuke.inputs(dependNode[0])+1

    nuke.nodeCopy(nukescripts.cut_paste_file())

    for node in nuke.allNodes():
        node['selected'].setValue(0)

    nuke.nodePaste(nukescripts.cut_paste_file())

    newNode = nuke.selectedNode()
    newNode.setInput(0, depNode[0])
    dependNode[0].setInput(i+1, newNode)
示例#40
0
    def testCopyPaste(self):

        fnPH = IECoreNuke.FnProceduralHolder.create("procedural", "read", 1)

        nuke.nodeCopy("test/IECoreNuke/parameterisedHolder.nk")

        nuke.scriptClear()

        n = nuke.nodePaste("test/IECoreNuke/parameterisedHolder.nk")

        fnPH = IECoreNuke.FnProceduralHolder(n)

        p = fnPH.getParameterised()

        self.assertEqual(p[1], "read")
        self.failUnless(isinstance(p[2], int))
        self.assertEqual(p[2], 1)
        self.assertEqual(p[3], "IECORE_PROCEDURAL_PATHS")
示例#41
0
def duplicateNode(node):
    # Store selection
    orig_selection = nuke.selectedNodes()

    # Select only the target node
    [n.setSelected(False) for n in nuke.selectedNodes()]
    node.setSelected(True)

    # Copy the selected node and clear selection again
    nuke.nodeCopy("%clipboard%")
    node.setSelected(False)

    nuke.nodePaste("%clipboard%")
    duplicated_node = nuke.selectedNode()

    # Restore original selection
    [n.setSelected(False) for n in nuke.selectedNodes()]  # Deselect all
    [n.setSelected(True) for n in orig_selection]  # Select originally selected

    return duplicated_node
示例#42
0
    def duplicate_node(self, node, to_file=None):
        """Slightly convoluted but reliable(?) way duplicate a node, using
        the same functionality as the regular copy and paste.
        Could almost be done tidily by doing:
        for knobname in src_node.knobs():
            value = src_node[knobname].toScript()
            new_node[knobname].fromScript(value)
        ..but this lacks some subtly like handling custom knobs
        to_file can be set to a string, and the node will be written to a
        file instead of duplicated in the tree
        """
        import nuke

        # Store selection
        orig_selection = nuke.selectedNodes()

        # Select only the target node
        [n["selected"].setValue(False) for n in nuke.selectedNodes()]
        node["selected"].setValue(True)

        # If writing to a file, do that, restore the selection and return
        if to_file is not None:
            nuke.nodeCopy(to_file)
            [n["selected"].setValue(False) for n in orig_selection]
            return

        # Copy the selected node and clear selection again
        nuke.nodeCopy("%clipboard%")
        node["selected"].setValue(False)

        if to_file is None:
            # If not writing to a file, call paste function, and the new node
            # becomes the selected
            nuke.nodePaste("%clipboard%")
            new_node = nuke.selectedNode()

        # Restore original selection
        [n["selected"].setValue(False) for n in nuke.selectedNodes()]
        [n["selected"].setValue(True) for n in orig_selection]

        return new_node
	def testClassParameterSetClassAndValues( self ) :

		fnOH = IECoreNuke.FnOpHolder.create( "test", "classParameterTest", 1 )

		with fnOH.parameterModificationContext() as parameterised :

			parameterised["cp"].setClass( "maths/multiply", 2 )
			parameterised["cp"]["a"].setNumericValue( 10 )
			parameterised["cp"]["a"].setNumericValue( 20 )

		self.__checkParameterKnobs( parameterised.parameters(), fnOH.node() )

		nuke.nodeCopy( "test/IECoreNuke/parameterisedHolder.nk" )

		nuke.scriptClear()

		n = nuke.nodePaste( "test/IECoreNuke/parameterisedHolder.nk" )

		fnOH = IECoreNuke.FnOpHolder( n )

		parameterised2 = fnOH.getParameterised()[0]

		self.assertEqual( parameterised.parameters().getValue(), parameterised2.parameters().getValue() )
示例#44
0
  def renameCreateSharedToolset(self, name, rename):
    ret = False
    
    nameList = name.split('/')
    fileName = nameList[-1]
    
    del nameList[-1]
    dirs = '/'.join(nameList)
    
    fullPath = posixpath.join(SHARED_TOOLSET_PATH, dirs)
    
    try:
      if not os.path.isdir(fullPath):
        os.makedirs( fullPath )
      
      filePath = posixpath.join(fullPath, fileName + '.nk')
      
      if not os.path.exists(filePath):
        if self.rename == True:
          os.rename(self.fullFilePath, filePath)
        else:
          # create way
          nuke.nodeCopy(filePath)

      elif nuke.ask('Overwrite existing \n %s?' % filePath):
        if self.rename == True:
          os.remove(filePath)
          os.rename(self.fullFilePath, filePath)
        else:
          # create way
          nuke.nodeCopy(filePath)

      ret = True
    except:
      ret = False
    return ret
示例#45
0
import nuke

def alembicMerge():
    mainNode = nuke.selectedNode()
    mainScene = mainNode['scene_view']
    mainItems = mainScene.getSelectedItems()
    items = []
    selNodes = nuke.selectedNodes()
    for node in selNodes:
        item = node['scene_view'].getSelectedItems()
        print(item)
        items.extend(item)
    mainScene.setSelectedItems(items)
    delNodes = [n for n in selNodes if n is not mainNode]
    print(selNodes, delNodes)
    for d in delNodes:
        nuke.delete(d)


s = nuke.selectedNode()
items = s['scene_view'].getSelectedItems()
nuke.nodeCopy('%clipboard%')
for i in items:
    p=nuke.nodePaste('%clipboard%')
    p['scene_view'].setSelectedItems([i])
示例#46
0
def copyPaste():
  nuke.nodeCopy(clipboard())
  deselectAllNodes()
  nuke.nodePaste(clipboard())
示例#47
0
	def parentNodeCopy(self,papaNode):
		papaNode.knob("selected").setValue(True)
		nuke.nodeCopy('%clipboard%')
		self.parentNode = nuke.nodePaste('%clipboard%')
示例#48
0
def setLocal():
	
# path variables

	repo = '/mnt/karramba'
	home = '/home/tfx/job.local'
	
# clears the selection if smth was selected	
	for node in nuke.allNodes():
		node.setSelected(False)

# copies footage to local machine

	readList = [node.knob('file').value() for node in nuke.allNodes('Read')]
	

	for path in readList:
		
		fileDirList =[path.rsplit(os.sep,1)[0] + os.sep + img for img in os.listdir(path.rsplit(os.sep,1)[0]) if img[:len(path.rsplit(os.sep,1)[1].split('%')[0])] == path.rsplit(os.sep,1)[1].split('%')[0]]
		newPath = home + path.rsplit(os.sep, 1)[0].split(repo)[-1] + os.sep
		
		if not os.path.exists(newPath):
			os.makedirs(newPath)
		
		for img in fileDirList:
			if not os.path.isdir(img):
				shutil.copy(img, newPath)

#creates new read nodes and controller to switch controller between local and network
			
	for node in nuke.allNodes('Read'):
		
		node.setSelected(True)
		
		sw = nuke.createNode('Switch', inpanel=False)
		sw.setSelected(False)
		sw.knob('which').setExpression('locController.location')
		node.setSelected(True)
		nuke.nodeCopy('%context%')
		c = nuke.nodePaste('%context%')
		
		sw.setInput(0, c)
		sw.setInput(1, node)
		
		node.setYpos(node.ypos()-90)
		c.setYpos(node.ypos())
		c.setXpos(node.xpos()-150)
		
		c.setName(c.name() + 'Local')
		node.setName(node.name() + 'Network')
		
		c.knob('file').setValue(home + node.knob('file').value().split(repo)[-1])
		
		node.setSelected(False)
		c.setSelected(False)

	n =	nuke.createNode('NoOp')
	n.setName('locController')
	k = nuke.Double_Knob('location', 'location')
	k.setRange(0, 1)
	n.addKnob(k)
	n.knob('hide_input').setValue(True)
	n.setXpos(nuke.toNode(findHighestRead()).xpos() + 500)
	n.setYpos(nuke.toNode(findHighestRead()).ypos())
	n.setSelected(False)
	
	st = nuke.createNode('StickyNote', inpanel=False)
	st.setName('status')
	st.setXpos(n.xpos())
	st.setYpos(n.ypos()-50)
	st.knob('label').setValue('LOCAL')
	st.knob('note_font_size').setValue(35)

	nuke.addKnobChanged(switchStatus, nodeClass='NoOp')
def copy_paste():
  nuke.nodeCopy(clipboard())
  for node in nuke.allNodes():
    node.knob("selected").setValue(False)
  nuke.nodePaste(clipboard())
示例#50
0
            def multiChannelSplit():
                '''
                main function
                split the selected read node in separate channel layers
                if set create separate folders and write nodes 
                '''
                sel = nuke.selectedNode()
                
                shuffles=[]
                renderTo=""
                autocropNodeRGB_exists=False
                cropNode=None
                dot=None

                if sel != None:

                    #main procedure
                    #create shuffle, shuffle channel in, curvetool crop, create cropnode and paste that information in, delete crop node
                            
                    o=0;
                    
                    if self.autoCrop.getValue()==1.0:
                        curveNode = nuke.nodes.CurveTool(name="Autocrop_Master", inputs = [sel], operation="Auto Crop")
                        curveNode["channels"].setValue("rgba")
                        curveNode.knob("ROI").setValue([0,0,sel.width(),sel.height()])
                        nuke.execute(curveNode, sel.knob("first").value(), sel.knob("last").value())
                    
                    layersToProcess=[]

                    if self.which.getValue()== 0.0:
                        layersToProcess = uniqueLayers
                    else:
                        for layer in layerCheckboxes:
                            if layer.getValue()==True:
                                layersToProcess.append(layer.name())

                    if len(layersToProcess)>0:
                        dot = nuke.createNode("Dot", inpanel=False)

                        for channelLayer in layersToProcess:
                            shuffleNode = nuke.nodes.Shuffle(name="Shuffle_"+channelLayer)        
                            shuffles.append(shuffleNode.name())
                            shuffleNode.knob("in").setValue(channelLayer)
                            shuffleNode["hide_input"].setValue(True)
                            shuffleNode.setInput(0,sel)
                            shuffleNode["xpos"].setValue(sel["xpos"].getValue()+(o*100))
                            shuffleNode["ypos"].setValue(sel["ypos"].getValue()+150)
                            shuffleNode.setInput(0,dot)
                            shuffleNode["postage_stamp"].setValue(True)
                            
                            #auto crop if selected
                            if self.autoCrop.getValue()==1.0:
                                if autocropNodeRGB_exists==False:
                                    cropNode = nuke.nodes.Crop(name=channelLayer, inputs = [shuffleNode])
                                    cropNode.knob("hide_input").setValue(True)
                                    cropNode.knob("box").copyAnimations(curveNode.knob("autocropdata").animations())
                                    nuke.delete(curveNode)
                                    cropNode.knob("postage_stamp").setValue(True)
                                    cropNode.setXpos(int(shuffleNode["xpos"].getValue()))
                                    cropNode.setYpos(int(shuffleNode["ypos"].getValue()+80))                                    
                                    shuffleNode["hide_input"].setValue(False)
                                    cropNode["hide_input"].setValue(True)
                                    nukescripts.clear_selection_recursive()
                                    cropNode["selected"].setValue(True)
                                    nuke.nodeCopy("%clipboard%")
                                    autocropNodeRGB_exists=True
                                    shuffleNode["postage_stamp"].setValue(False)
                                    cropNode["postage_stamp"].setValue(True)
                                else:    
                                    cropCopy = nuke.nodePaste("%clipboard%")
                                    cropCopy["name"].setValue(channelLayer)
                                    cropCopy.setInput(0,shuffleNode)
                                    cropCopy.setXpos(int(shuffleNode["xpos"].getValue()))
                                    cropCopy.setYpos(int(shuffleNode["ypos"].getValue()+80))        
                        
                            #create folders for all layer and create write node for every shuffle                       
                            if self.outputPath.getValue()!="":
                                renderTo = self.outputPath.getValue()
                                #createFolder
                                createFolders(renderTo+"/"+channelLayer)            
                                #create write node
                                write = nuke.nodes.Write()
                                write.knob("file_type").setValue("exr")
                                write.knob("file").setValue(renderTo+channelLayer+"/"+channelLayer+"_%04d.exr")
                                write.knob("compression").setValue("Zip (16 scanlines)")
                                write.knob("channels").setValue("rgba")
     
                                if self.autoCrop.getValue()==True:       
                                    write.setInput(0,cropNode) 
                                else:
                                    write.setInput(0,shuffleNode) 
                            o+=1  
                         
                    if len(layersToProcess)>0:
                        nuke.delete(dot)

                    #hide all created shuffle inputs
                    for shuffleNode in shuffles:
                        if self.autoCrop.getValue()==1.0:
                            temp = nuke.toNode(shuffleNode)
                            temp.knob("hide_input").setValue(True)
                            temp.knob("postage_stamp").setValue(True)
                else:
                    pass