Esempio n. 1
0
def executeRender(node, start, end):
	try:
		nuke.execute(node, start, end)
		sys.exit(0)
	except Exception as e:
		nuke.tprint('Failed to render range')
		sys.exit(1)
Esempio n. 2
0
def render_png(nodes, frame=None, show=False):
    """create png for given @nodes."""

    assert isinstance(nodes, (nuke.Node, list, tuple))
    assert nuke.value('root.project_directory'), '未设置工程目录'
    if isinstance(nodes, nuke.Node):
        nodes = (nodes, )
    script_name = os.path.join(
        os.path.splitext(os.path.basename(nuke.value('root.name')))[0])
    if frame is None:
        frame = nuke.frame()
    for read_node in nodes:
        if read_node.hasError() or read_node['disable'].value():
            continue
        name = read_node.name()
        LOGGER.info('渲染: %s', name)
        n = nuke.nodes.Write(inputs=[read_node], channels='rgba')
        n['file'].fromUserText(
            os.path.join(script_name, '{}.{}.png'.format(name, frame)))
        nuke.execute(n, frame, frame)

        nuke.delete(n)
    if show:
        webbrowser.open(
            os.path.join(nuke.value('root.project_directory'), script_name))
Esempio n. 3
0
def newFlixPanelFromCurrentViewerImage(nukeStudioViewer=True):
    print "Adding a new FLIX panel from current Viewer"
    uniquePath = getFlixTempFolder() + "flix_" + getUniqueString() + "_"

    lastTempNumber = "1"
    filePath = uniquePath + lastTempNumber + ".xml"
    fileRef_out = open(filePath, 'w')
    dialogue = "I do not believe in fairies"  #getDialogue(psdDocument);
    fileRef_out.write("<flixImport waitForSource='1' multipleSetups='1'>\n")

    # Depending on the action, we can grab the active Nuke (comp) or NukeStudio Viewer image
    if nukeStudioViewer:
        currentImage = currentViewer().image()
        tempFilePath = uniquePath + lastTempNumber + "_.FLIXTEMP.png"
        currentImage.save(tempFilePath)
    else:
        # It's the Nuke Comp image
        vn = nuke.activeViewer().node()
        frame = vn['frame'].value()
        tempFilePath = uniquePath + lastTempNumber + "_.FLIXTEMP.png"
        vn['file'].setValue(tempFilePath)
        nuke.execute(vn, frame, frame)

    fileRef_out.write("<image originalFile='" + getActiveDocumentFilename() +
                      "' dialogue='I do not believe in Fairies' imageFile='" +
                      tempFilePath + "'/>\n")
    fileRef_out.write("</flixImport>\n")
    fileRef_out.close()
    sendFileToFlix(filePath)
Esempio n. 4
0
def burnLut(strRes=''):
    """creation of nuke node script to convert exr image in tif 16bit or jpg using the Asterix2_film lut
        @strRes sting in format of a dictionary
        strRes is converted back to a dict using the json module.
        Each elements of the dict is composed of:
            -file path source (fileIn)
            -file path output (fileOut)
            -fileType jpg or tif
    """
    writeNodeList =[]
    strFix = strRes.replace("'","\"")
    res = json.loads(strFix)
    for key in res.keys():
        fileType = res[key]['fileType']
        fileIn = res[key]['fileIn']
        fileOut = res[key]['fileOut']
        # create a read node
        readNode = nuke.nodes.Read(file = fileIn)
        # create the color node to convert from linear space to asterix2_film space
        colorConvertNode = nuke.nodes.OCIOColorSpace(in_colorspace="linear",out_colorspace="vd/asterix2_film")
        # if tif file set the output to be 16 bit
        if fileType == "tif":
            writeNode = nuke.nodes.Write(name = 'WriteBurnLutFile', colorspace = "linear", file_type = fileType, file =fileOut )
            writeNode.knob('datatype').setValue(1)
        else:
            writeNode = nuke.nodes.Write(name = 'WriteBurnLutFile', colorspace = "linear", file_type = fileType, file =fileOut )

        colorConvertNode.setInput(0,readNode)
        writeNode.setInput(0,colorConvertNode)
        # append the write node to the list
        writeNodeList.append(writeNode)
    # for each node in the list create the image
    for node in writeNodeList:
        print 'calculating : ' + node.knob('file').getValue()
        nuke.execute(node,1,1)
Esempio n. 5
0
def render():
    cn = nuke.thisNode()
    setCommentPath()

    frameStart = int(cn["frameStart"].getValue())
    frameEnd = int(cn["frameEnd"].getValue())

    if cn["submit"].getValue() == 0.0:
        threads = int(cn["threads"].getValue())
        from plugins.vuRenderThreads.plugin_nuke import plugin_nuke
        plugin_nuke.createThreads(frameStart, frameEnd, threads, [cn.name()])
        LOG.info("END    : RENDERTHREADS : " + cn["exrPathComment"].getValue())

    elif cn["submit"].getValue() == 1.0:
        import rrenderSubmit
        nuke.load('rrenderSubmit')
        rrenderSubmit.rrSubmit_Nuke_Node(cn, frameStart, frameEnd)
        LOG.info("END    : RRSUBMIT : " + cn["exrPathComment"].getValue())

    else:
        try:
            nuke.execute(nuke.thisNode(),
                         start=frameStart,
                         end=frameEnd,
                         incr=1)
            LOG.info("END    : LOCAL : " + cn["exrPathComment"].getValue())
        except:
            print "END    : LOCAL : Execution failed"
            LOG.error("END    : LOCAL : " + cn["exrPathComment"].getValue(),
                      exc_info=True)
Esempio n. 6
0
def WatermarkTools():
    w.showModalDialog()

    for i in range(flag):
        nuke.execute(writeNodes[i].knob('name').value(),
                     srcReadNodes[i].knob('first').value(),
                     srcReadNodes[i].knob('last').value(), 1)
Esempio n. 7
0
def main():
    """
    sys.argv[0]: current file
    sys.argv[1]: nuke file path
    sys.argv[2]: write node
    sys.argv[3]: frame range 1001-1002
    sys.argv[4]: output path
    :return:
    """
    file_name = sys.argv[1]
    nuke.scriptOpen(file_name.replace('\\', '/'))

    if not os.path.isdir(os.path.dirname(sys.argv[4])):
        os.makedirs(os.path.dirname(sys.argv[4]))

    nuke.toNode(sys.argv[2])['file'].setValue(sys.argv[4])
    nuke.toNode(sys.argv[2])['disable'].setValue(False)

    frames = sys.argv[3].split('-')
    first_frame, last_frame = int(frames[0]), int(frames[1])

    switch_path()
    #nuke.scriptSave()

    nuke.execute(sys.argv[2], first_frame, last_frame, continueOnError=True)

    nuke.scriptClose(file_name)
Esempio n. 8
0
    def testExecuteWithImageInput(self):

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

        self.assertEqual(fnOH.node().minimumInputs(), 1)
        self.assertEqual(fnOH.node().maximumInputs(), 1)

        check = nuke.nodes.CheckerBoard()

        fnOH.node().setInput(0, check)

        # get the image as output by the op
        image = fnOH.execute()

        # write the same image direct to disk without using the op
        write = nuke.nodes.Write()
        write.setInput(0, check)
        write.knob("file").setValue("test/IECoreNuke/check.exr")
        write.knob("channels").setValue("rgba")
        nuke.execute(write, 1, 1)

        # check that they are the same in terms of size and channel data.
        # allow a slight difference due to one having been saved as half float and reloaded.

        image2 = IECore.Reader.create("test/IECoreNuke/check.exr").read()
        self.assertEqual(
            IECoreImage.ImageDiffOp()(imageA=image,
                                      imageB=image2,
                                      maxError=0.001).value, False)
Esempio n. 9
0
    def thumb_snap(self):
        self.check_for_tmp()

        #lets make sure were snapping for the current shot
        shot = self.shotcombo.currentText()
        if os.getenv('SHOT') == shot:
            viewer = nuke.activeViewer()
            actInput = nuke.ViewerWindow.activeInput(viewer)
            viewNode = nuke.activeViewer().node()
            selInput = nuke.Node.input(viewNode, actInput)
            
            reformatNode = nuke.nodes.Reformat( type = "to format", format = "240 135 eight_scaled", resize = 'fill') 
            reformatNode.setInput(0, selInput) 
            
            self.shot_thumb = os.path.join(jeeves_core.jobsRoot, self.job, 'vfx', 'nuke', self.shot, 'plates', '.tmp', '%s.jpg' % self.shot).replace('\\', '/')

            writeNode = nuke.nodes.Write( file = self.shot_thumb, name = 'tmpWrite2' , file_type = 'jpg')
            writeNode.setInput(0,reformatNode)
            curFrame = int(nuke.knob("frame"))
        
            nuke.execute(writeNode.name(), curFrame, curFrame)
            nuke.delete(writeNode)
            nuke.delete(reformatNode)
            
            self.update_thumb()
        else:
            #print 'not snapping for current shot'
            nuke.message('not snapping for current shot')
Esempio n. 10
0
def shuffleChannelLayers():
    selectedNodes = nuke.selectedNodes()

    for readNode in selectedNodes:
        if readNode.Class() == "Read":
            uniqueChannelLayers = uniqueChannelLayerList(readNode)

            for channelLayer in uniqueChannelLayers:
                shuffleNode = nuke.nodes.Shuffle(name="Shuffle_" +
                                                 channelLayer)
                shuffleNode.knob("in").setValue(channelLayer)
                shuffleNode.setInput(0, readNode)
                curveNode = nuke.nodes.CurveTool(name="AC_" + channelLayer,
                                                 inputs=[shuffleNode],
                                                 operation="Auto Crop")
                curveNode.knob("ROI").setValue(
                    [0, 0, shuffleNode.width(),
                     shuffleNode.height()])
                nuke.execute(curveNode,
                             readNode.knob("first").value(),
                             readNode.knob("last").value())
                cropNode = nuke.nodes.Crop(name="Crop_" + channelLayer,
                                           inputs=[curveNode])
                cropNode.knob("box").copyAnimations(
                    curveNode.knob("autocropdata").animations())
    def check_bounding_box(self, instance):
        node = instance[0]

        first_frame = instance.data["frameStart"]
        last_frame = instance.data["frameEnd"]

        format_width = node.format().width()
        format_height = node.format().height()

        # The trick is that we need to execute() some node every time we go to
        # a next frame, to update the context.
        # So we create a CurveTool that we can execute() on every frame.
        temporary_node = nuke.nodes.CurveTool()
        bbox_check = True
        for frame in range(first_frame, last_frame + 1):
            # Workaround to update the tree
            nuke.execute(temporary_node, frame, frame)

            x = node.bbox().x()
            y = node.bbox().y()
            w = node.bbox().w()
            h = node.bbox().h()

            if x < 0 or (x + w) > format_width:
                bbox_check = False
                break

            if y < 0 or (y + h) > format_height:
                bbox_check = False
                break

        nuke.delete(temporary_node)
        return bbox_check
Esempio n. 12
0
    def execute_render(self):
        if self.execute_pushButton.clicked:
            self.quit()

        # sort by render order
        self.nodes.sort(key=lambda x: x['render_order'].value())

        # disable proxy
        proxy = nuke.root()['proxy'].value()
        nuke.root()['proxy'].setValue(False)

        # empty tuple for storing frame start/end/incr
        t = ()  # only used in executeMultiple()

        # render!
        self.write_list = []
        for i, node in enumerate(self.nodes):
            self.first_frame = int(node['first'].value())
            self.last_frame = int(node['last'].value())

            # execute node
            nuke.execute(node, self.first_frame, self.last_frame, 1)
            t = t + ((self.first_frame, self.last_frame, 1),)  # only used in executeMultiple()
            write_is_done = "%s is done" % (node.name())
            self.write_list.append(write_is_done)

        # set proxy back to original value
        nuke.root()['proxy'].setValue(proxy)
Esempio n. 13
0
def merge_image(images,tile_output):
 
    read_nodes = []
    for i in images:
        read_nodes.append(create_read(i))
    
    merge = nuke.createNode('Merge2')
    x = 0
    for i in read_nodes:
        if x == 2:
            x += 1
            # print i.name()
            merge.setInput(x, i)
            x += 1
        else:
            merge.setInput(x, i)
            x += 1
    merge["operation"].setValue("max")
    merge["also_merge"].setValue("all")
    
    tile_output_folder = os.path.dirname(tile_output)
    if not os.path.exists(tile_output_folder):
        os.makedirs(tile_output_folder)
    
    write = nuke.nodes.Write(inputs=[merge], file=tile_output)
    write["channels"].setValue("all")
    nuke.execute(write.name(), 1, 1, 1)
    nuke.scriptClear()
Esempio n. 14
0
def newFlixPanelFromCurrentViewerImage(nukeStudioViewer = True):
    print "Adding a new FLIX panel from current Viewer"
    uniquePath = getFlixTempFolder()+"flix_"+getUniqueString()+"_"

    lastTempNumber = "1"
    filePath = uniquePath+lastTempNumber+".xml";
    fileRef_out = open(filePath, 'w');
    dialogue = "I do not believe in fairies" #getDialogue(psdDocument);
    fileRef_out.write("<flixImport waitForSource='1' multipleSetups='1'>\n");

    # Depending on the action, we can grab the active Nuke (comp) or NukeStudio Viewer image
    if nukeStudioViewer:
        currentImage = currentViewer().image()
        tempFilePath = uniquePath+lastTempNumber+"_.FLIXTEMP.png"
        currentImage.save(tempFilePath)
    else:
        # It's the Nuke Comp image
        vn = nuke.activeViewer().node()
        frame = vn['frame'].value()
        tempFilePath = uniquePath+lastTempNumber+"_.FLIXTEMP.png"
        vn['file'].setValue(tempFilePath)
        nuke.execute(vn, frame, frame)

    fileRef_out.write("<image originalFile='"+getActiveDocumentFilename()+"' dialogue='I do not believe in Fairies' imageFile='"+tempFilePath+"'/>\n");
    fileRef_out.write("</flixImport>\n");
    fileRef_out.close()
    sendFileToFlix(filePath)
Esempio n. 15
0
def trackRangeForward():
    node = nuke.thisNode()
    size = nuke.thisNode()['size'].value()
    rootLayer = node.knob("curves").rootLayer
    curve = node.knob("curves").getSelected()[0]
    start = int(nuke.root()['frame'].value())
    end = int(nuke.root()['last_frame'].value())
    task = nuke.ProgressTask('Baking camera from meta data in %s' %
                             node.name())
    for i in range(start, end):
        if task.isCancelled():
            nuke.executeInMainThread("")
            break
        task.setMessage('processing frame %s' % i)
        task.setProgress(int((float(i - start) / float(end)) * 100))
        temp = nuke.nodes.CurveTool()
        nuke.execute(temp, i, i)

        nuke.root()['frame'].setValue(i)
        for c, point in enumerate(curve):
            point.center.evaluate(i)
            pos = point.center.getPosition(i)
            print pos
            dx = nuke.sample(node, "red", pos.x, pos.y, size, size)
            dy = nuke.sample(node, "green", pos.x, pos.y, size, size)
            print c, dx, dy
            pos.x = pos.x + dx
            pos.y = pos.y + dy
            point.center.addPositionKey(i, pos)
            node['curves'].changed()
        nuke.delete(temp)
Esempio n. 16
0
def nuke_viewerSnapshot(img_path=DEFAULT_PATH):
    LOG.info("nuke_viewerSnapshot")
    import nuke
    viewer = nuke.activeViewer()
    viewNode = nuke.activeViewer().node()

    actInput = nuke.ViewerWindow.activeInput(viewer)
    if actInput < 0: return False

    selInput = nuke.Node.input(viewNode, actInput)

    # look up filename based on top read node
    topName = "[file tail [knob [topnode].file]]"

    # create writes and define render format
    write1 = nuke.nodes.Write(
        file=img_path.replace("\\", "/"),
        name='writeNode1',
        file_type=Tank().data_project['EXTENSION']['thumnail'])
    write1.setInput(0, selInput)

    # look up current frame
    curFrame = int(nuke.knob("frame"))
    # start the render
    nuke.execute(write1.name(), curFrame, curFrame)
    # clean up
    for n in [write1]:
        nuke.delete(n)
Esempio n. 17
0
    def createThumbNail(nodeObject):
        try:
            #test creating thumbnail
            reformatNode = nuke.nodes.Reformat()
            reformatNode['type'].setValue("to box")
            reformatNode['box_width'].setValue(200.0)

            reformatNode.setInput(0, nodeObject)

            w2 = nuke.nodes.Write()
            w2.setInput(0, reformatNode)
            thumbNailFilename = 'thumbnail_' + HelpFunctions.getUniqueNumber() + '.png'
            thumbnailDestination = os.path.join(tempfile.gettempdir(), thumbNailFilename)
            w2['file'].setValue(Connector.windowsFixPath(thumbnailDestination))
            w2['file_type'].setValue('png')

            curFrame = int(nuke.knob("frame"))
            nuke.execute(w2, curFrame, curFrame)

            nuke.delete(reformatNode)
            nuke.delete(w2)

            return thumbnailDestination
        except:
            import traceback
            traceback.print_exc(file=sys.stdout)
            return None
Esempio n. 18
0
def get_max(node, channel='rgb'):
    # TODO: Need test.
    '''
    Return themax values of a given node's image at middle frame

    @parm n: node
    @parm channel: channel for sample
    '''
    first = node.firstFrame()
    last = node.lastFrame()
    middle = (first + last) // 2
    ret = 0

    n = nuke.nodes.Invert(channels=channel, inputs=[node])
    n = nuke.nodes.MinColor(channels=channel, target=0, inputs=[n])

    for frame in (middle, first, last):
        try:
            nuke.execute(n, frame, frame)
        except RuntimeError:
            continue
        ret = max(ret, n['pixeldelta'].value() + 1)
        if ret > 0.7:
            break

    print(u'getMax({1}, {0}) -> {2}'.format(channel, node.name(), ret))

    nuke.delete(n.input(0))
    nuke.delete(n)

    return ret
Esempio n. 19
0
def get_min_max(src_node, channel='depth.Z'):
    '''
    Return the min and max values of a given node's image as a tuple

    args:
       src_node  - node to analyse
       channels  - channels to analyse.
            This can either be a channel or layer name
    '''
    min_color = nuke.nodes.MinColor(channels=channel,
                                    target=0,
                                    inputs=[src_node])
    inv = nuke.nodes.Invert(channels=channel, inputs=[src_node])
    max_color = nuke.nodes.MinColor(channels=channel, target=0, inputs=[inv])

    cur_frame = nuke.frame()
    nuke.execute(min_color, cur_frame, cur_frame)
    min_v = -min_color['pixeldelta'].value()

    nuke.execute(max_color, cur_frame, cur_frame)
    max_v = max_color['pixeldelta'].value() + 1

    for n in (min_color, max_color, inv):
        nuke.delete(n)
    return min_v, max_v
Esempio n. 20
0
def createNukeFile(seq = 's0060',shName=True,outFile = '/tmp/tmp.tif',task = 'compo_comp'):
    nbShots = len(findShotsInSequence(seq,False))
    intNb = nbShots/5
    floatNb = nbShots/5.0
    if floatNb-intNb > 0:
        intNb += 1
    sequenceGroupNode = sequenceGroup.create()
    sequenceGroupNode['sequence'].setValue(seq)
    sequenceGroupNode['task'].setValue(task)
    sequenceGroupNode['outputMode'].setValue('contactSheet')
    sequenceGroupNode['Rebuild'].execute()
    # a.knob('Rebuild').execute()
    sequenceGroupNode['RowCol'].setValue([intNb, 5])
    sequenceGroupNode['Resolution'].setValue([5*2048,intNb*858])
    if shName:
        sequenceGroupNode['showName'].setValue(True)
    else:
        sequenceGroupNode['showName'].setValue(False)

    colorConvertNode = nuke.nodes.OCIOColorSpace(in_colorspace="Linear", out_colorspace="Lut")
    #colorConvertNode = nuke.nodes.OCIOColorSpace( out_colorspace="Lut")
    colorConvertNode.setInput(0,sequenceGroupNode)

    writeNode = nuke.nodes.Write(name = seq + "WriteLutBurn", colorspace = "linear", file_type = "tiff",file =outFile+'/'+seq+'.tif')
    writeNode['datatype'].setValue('16 bit')
    #writeNode['views'].setValue('left left')
    writeNode.setInput(0,colorConvertNode)
    nuke.scriptSave('/tmp/tmp.nk')
    print 'done'
    nuke.execute(writeNode, 1, 1)
Esempio n. 21
0
	def testExecuteWithImageInput( self ) :
	
		fnOH = IECoreNuke.FnOpHolder.create( "test", "imagePrimitiveInOut", 1 )
		
		self.assertEqual( fnOH.node().minimumInputs(), 1 )
		self.assertEqual( fnOH.node().maximumInputs(), 1 )
		
		check = nuke.nodes.CheckerBoard()
		
		fnOH.node().setInput( 0, check )
		
		# get the image as output by the op
		image = fnOH.execute()

		# write the same image direct to disk without using the op
		write = nuke.nodes.Write()
		write.setInput( 0, check )
		write.knob( "file" ).setValue( "test/IECoreNuke/check.exr" )
		write.knob( "channels" ).setValue( "rgba" )
		nuke.execute( write, 1, 1 )
		
		# check that they are the same in terms of size and channel data.
		# allow a slight difference due to one having been saved as half float and reloaded.
		
		image2 = IECore.EXRImageReader( "test/IECoreNuke/check.exr" ).read()
		self.assertEqual( IECore.ImageDiffOp()( imageA = image, imageB = image2, maxError = 0.001 ).value, False )
Esempio n. 22
0
def main(args):
	import nuke
	import helix.api.nuke.utils as nkutils
	import helix.environment.environment as env

	read = nkutils.read(file=args.input)
	first = read.knob('first').value()
	last = read.knob('last').value()
	seqWrite = None
	movWrite = None

	if args.seqOut is not None:
		seqWrite = nkutils.write(file=args.seqOut)
		seqWrite.knob('first').setValue(first)
		seqWrite.knob('last').setValue(last)

		nkutils.connect(read, seqWrite)

	if args.movOut is not None:
		movWrite = nkutils.write(file=args.movOut)
		movWrite.knob('first').setValue(first)
		movWrite.knob('last').setValue(last)

		nkutils.connect(read, movWrite)

	if seqWrite is not None:
		nuke.execute(seqWrite)

	if movWrite is not None:
		nuke.execute(movWrite)
Esempio n. 23
0
 def exportObj(self, filePy, objects, filePath, objPath):
     objPathList = []        
     filePy.write("# importing obj files...\n\n")        
     for node in objects:
         
         for i in nuke.allNodes():
             i['selected'].setValue(0)
     
         print "processing "+node.name()+" ..."
         node['selected'].setValue(1)
         writeObj = nuke.createNode('WriteGeo', inpanel=False)
         writeObj['name'].setValue(node.name()+"_export")
         writeObj['file'].setValue(objPath+node.name()+".obj")
         writeObj['file_type'].setValue('obj')
         # writeObj['views'].setValue('main')
         
         objPathList.append(objPath+node.name()+".obj")
         nuke.execute(writeObj, int(nuke.root()['first_frame'].getValue()), int(nuke.root()['first_frame'].getValue()))
         for i in nuke.allNodes():
             i['selected'].setValue(0)
         writeObj['selected'].setValue(1)
         nukescripts.node_delete()
             
     for object in objPathList:
         filePy.write("cmds.file('"+object+"', i = True, type = 'OBJ', ra = True)\n")
         
     filePy.write("\n")
     filePy.write("# make group of all the *_Mesh nodes ...\n\n")
     filePy.write("cmds.select('*_Mesh')\n")
     filePy.write("cmds.group(name = 'geo_GRP')\n\n")
     filePy.write("# renaming the files without '_Mesh' ...\n\n")
     filePy.write("meshes = cmds.ls('*_Mesh')\n")
     filePy.write("for node in meshes:\n")
     filePy.write("	cmds.rename(node, node[-0:-5])\n\n")
Esempio n. 24
0
 def renderPip(self, read1, read2, yRes, xRes):
     """ Create the Nuke script and execute it to render the new thumbnail
     """
     # Clear the nk script
     FlixNuke().clearScript()
     # Tweak this parameter for the pic in pic to be smaller(down to 0) or bigger (up to 1)
     scale = 0.25
     # Create the read nodes for both the layout and board panels
     readNode1 = nuke.createNode("Read",
                                 "file {%s}" % self.rePath.localize(read1))
     readNode2 = nuke.createNode("Read",
                                 "file {%s}" % self.rePath.localize(read2))
     # Create the transform node to resize and move the board to the bottom right hand corner
     transformNode = nuke.createNode("Transform")
     transformNode.setInput(0, readNode2)
     transformNode["scale"].setValue(scale)
     ytranslate = yRes * (scale - 1) / 2
     xtranslate = xRes * (1 - scale) / 2
     transformNode["translate"].setValue([xtranslate, ytranslate])
     # Create the merge node that puts the board over the layout panel
     mergeNode = nuke.createNode("Merge2")
     mergeNode.setInput(1, transformNode)
     mergeNode.setInput(0, readNode1)
     # Create the Write node to render the thumbnail
     writeNode = nuke.createNode("Write")
     writeNode["file"].setValue(self.rePath.localize(read1))
     # Execute the script to render the thumbnail
     nuke.execute(writeNode["name"].getValue(), 1, 1, 1)
     # Comment out to actually save the nk script to troubleshoot or modify
     # nuke.scriptSave(self.rePath.localize(read1.replace(".jpg", ".nk")))
     # Clear the nk script
     FlixNuke().clearScript()
Esempio n. 25
0
def main():

    nSel = nuke.selectedNodes()
    cam = ''
    first = int(nuke.root()['first_frame'].value())
    last = int(nuke.root()['last_frame'].value())
    for n in nSel:
        if n.Class() == 'Camera2':
            cam = n

    if not cam:
        nuke.message('must have a camera in selection')

    if cam:
        for n in nSel:
            if not n.Class() == 'Camera2':
                #create reconcile and constant
                c = nuke.nodes.Constant()
                rec = nuke.nodes.Reconcile3D()
                rec.setInput(0, c)
                rec.setInput(1, cam)
                rec.setInput(2, n)
                nuke.execute(rec, first, last)
                tr = nuke.nodes.Transform()
                tr['name'].setValue('2Doutput_From_' + n.name())
                tr['translate'].copyAnimation(0, rec['output'].animation(0))
                tr['translate'].copyAnimation(1, rec['output'].animation(1))
                tr.setXYpos(n.xpos(), n.ypos() + 200)
                nuke.delete(c)
                nuke.delete(rec)
Esempio n. 26
0
def merge_image(images, tile_output):
    read_nodes = []
    for i in images:
        read_nodes.append(create_read(i))
    merge = nuke.createNode('Merge2')
    x = 0
    for i in read_nodes:
        if x == 2:
            x += 1
            # print i.name()
            merge.setInput(x, i)
            x += 1
        else:
            merge.setInput(x, i)
            x += 1
    merge["operation"].setValue("max")
    merge["also_merge"].setValue("all")

    tile_output_folder = os.path.dirname(tile_output)
    if not os.path.exists(tile_output_folder):
        os.makedirs(tile_output_folder)

    write = nuke.nodes.Write(inputs=[merge], file=tile_output)
    write["channels"].setValue("all")
    if tile_output.endswith(".exr"):
        write["file_type"].setValue("exr")
        write["datatype"].setValue("32 bit float")
        write["metadata"].setValue("all metadata")
        # write["compression"].setValue("none")
    nuke.execute(write.name(), 1, 1, 1)
    nuke.scriptClear()
Esempio n. 27
0
    def testLensDistortAgainstLensDistortOp(self):
        """Test that the output of the Cortex LensDistortOp and the LensDistort node are the same.\n"""

        paths = self.__paths()
        for p in paths.keys():
            self.assertTrue(os.path.exists(paths[p]))

        outputPath = self.__outputPath()
        if os.path.exists(outputPath):
            os.remove(outputPath)

            # Set the default format to be something fun.
        nuke.root()["format"].fromScript("1144 862 0 0 1144 862 2 CortexTestAlexaProxyAnamorphic(2.66)")

        r = nuke.createNode("Read")

        # Create a LensDistort node.
        l = nuke.createNode("ieLensDistort")
        l["mode"].setValue(IECore.LensModel.Undistort)
        l.setInput(0, r)

        # Set the parameters of the lens distort node.
        l["lensFileSequence"].fromScript(os.path.abspath("test/IECore/data/StandardRadialLens.cob"))

        # Create a write node.
        w = nuke.createNode("Write")
        w.setInput(0, l)
        w["file"].setText(outputPath)

        # Create the op that we will compare the result of the nuke LensDistort node with.
        lensDistortOp = IECore.LensDistortOp()
        lensDistortOp["mode"].setValue(IECore.LensModel.Undistort)
        lensDistortOp["lensModel"].setValue(self.__testLens())

        for path in paths.keys():
            # Update the read node.
            r["file"].setText(paths[path])

            if path == "path":
                # When the format is the same as the data window, nuke doesn't create a black border around the image.
                # As a result, we shouldn't create one using our LensDistortOp either.
                lensDistortOp["boundMode"].setValue(IECore.WarpOp.BoundMode.Clamp)
            else:
                lensDistortOp["boundMode"].setValue(IECore.WarpOp.BoundMode.SetToBlack)

                # Write out the result of the LensDistort so that we can compare it to the output of the cortex op.
            nuke.execute(w, 1, 1)

            img = IECore.Reader.create(paths[path]).read()
            lensDistortOp["input"].setValue(img)

            cortexImg = lensDistortOp()
            nukeImg = IECore.Reader.create(outputPath).read()

            # Assert that the two images are almost identical.
            # We expect a little bit of error as the cortex op uses a different sampling filter to the nuke node.
            imageDiffOp = IECore.ImageDiffOp()
            imageDiffOp["alignDisplayWindows"].setValue(True)
            res = imageDiffOp(imageA=cortexImg, imageB=nukeImg)
            self.assertFalse(res.value)
Esempio n. 28
0
def _createObjWriter(tmpWriterName, tmpfilePath, selectedNode, curFrame, alembic, frames):
    
    w = nuke.createNode('WriteGeo', inpanel=False)
    w.setName(tmpWriterName)
    w["file"].setValue(tmpfilePath.replace("\\", "/"))
    w.setInput(0, selectedNode)
    
    try:
        
        if alembic:
            w["use_limit"].setValue(True)
            w["first"].setValue(int(frames[0]))
            w["last"].setValue(int(frames[1]))
            w["file_type"].setValue(1)
            nuke.execute(tmpWriterName, int(frames[0]), int(frames[1]), 1)
        else:
            w["file_type"].setValue(3)
            nuke.execute(tmpWriterName, curFrame, curFrame, 1)
            
    except RuntimeError as e:
        
        print str(e)
        return False
    
    return True
Esempio n. 29
0
def getAvrageColor(
    frameNumber=[101, 125, 150],
    frame='/s/prods/captain/sequences/s0300/s0300_p00480/compo/compo_precomp/publish/images/generic/v012/s0300_p00480-s0300_p00480-base-compo_precomp-v012.'
):
    nodeList = []
    numberOfFrame = len(frameNumber)
    frameNumber = sorted(frameNumber)
    appendClipNode = nuke.nodes.AppendClip(firstFrame=frameNumber[0])
    nodeList.append(appendClipNode)
    for i in range(numberOfFrame):
        readFile = frame + str(frameNumber[i]).zfill(4) + '.exr'
        readNode = nuke.nodes.Read(file=readFile)
        appendClipNode.setInput(i, readNode)
        nodeList.append(readNode)
    curveToolNode = nuke.nodes.CurveTool(name="CurveTool", avgframes=1)
    curveToolNode['ROI'].setValue([0, 0, 1968, 1080])
    curveToolNode.setInput(0, appendClipNode)
    nuke.execute("CurveTool", frameNumber[0],
                 (frameNumber[0] - 1) + numberOfFrame)
    nodeList.append(curveToolNode)
    col = curveToolNode['intensitydata'].value()
    #clamp the color to a maximum 1
    for i in range(len(col)):
        if col[i] > 1:
            col[i] = 1
    for node in nodeList:
        nuke.delete(node)
    return col
Esempio n. 30
0
def create_video():
    t_source_path = sys.argv[1]
    t_des_path = sys.argv[2]
    t_fomant = sys.argv[3]
    t_start_frame = sys.argv[4][6:]
    t_end_frame = sys.argv[5][4:]
    t_frame = sys.argv[6][4:]
    # create node
    t_read_node = nuke.createNode("Read")
    T_write_node = nuke.createNode("Write")
    # set read node
    t_read_node["file"].setValue(t_source_path)
    t_read_node["first"].setValue(int(t_start_frame))
    t_read_node["last"].setValue(int(t_end_frame))
    source_code = t_read_node.metadata()["quicktime/codec_id"]
    #-------
    if not t_fomant in [".jpg", ".png", ".dpx", ".exr", ".tiff"]:
        if not os.path.exists(os.path.dirname(t_des_path)):
            os.makedirs(os.path.dirname(t_des_path))
        T_write_node["file"].setValue(t_des_path)
        T_write_node["file_type"].setValue("mov")
        T_write_node["meta_encoder"].setValue("mov32")
        T_write_node["mov32_fps"].setValue(int(t_frame))
        T_write_node["meta_codec"].setValue(source_code)
        nuke.execute(T_write_node, int(t_start_frame), int(t_end_frame))
    else:
        if not os.path.exists(t_des_path):
            os.makedirs(t_des_path)
        t_file = t_des_path + "/" + os.path.splitext(
            os.path.basename(t_source_path))[0] + ".%04d" + t_fomant
        T_write_node["file"].setValue(t_file)
        nuke.execute(T_write_node, int(t_start_frame), int(t_end_frame))
Esempio n. 31
0
 def createTimelineFromDroppedClip(self, clipPath):
     nuke.scriptClear()
     nuke.scriptReadFile('/Users/ant/.nuke/Python/Startup/cut_detection/cutDetector.nk')
     self.inputNode = nuke.toNode('InputClip')
     self.cutDetector = nuke.toNode('CutDetector')
     self.inputNode['file'].fromUserText(clipPath)
     self.first = self.inputNode['first'].value()
     self.last = self.inputNode['last'].value()
     nuke.execute("CutDetector.CurveTool1", self.first, self.last)
Esempio n. 32
0
def executeMultipleCompares(node, start, end):
	try:
		nuke.execute(node ,start ,end , inpanel = False)
		nuke.tprint('Compared and Succeeded')
		return 1
	except RuntimeError as e:
		nuke.tprint('Compare failed badly')
		nuke.tprint(str(e))
		return 0
Esempio n. 33
0
 def finalRendering(self): #rendering the results
     global flag
     for i in range(flag):
         nuke.execute(writeNodes[i].knob('name').value(),renderFirst[i],renderLast[i],1)
     del srcReadNodes[:]
     del mergeNodes[:]
     del writeNodes[:]
     del transformNodes[:]
     flag = 0
Esempio n. 34
0
    def process(self, instance):
        node = None
        for x in instance:
            if x.Class() == "Write":
                node = x

        self.log.debug("instance collected: {}".format(instance.data))

        first_frame = instance.data.get("frameStart", None)
        last_frame = instance.data.get("frameEnd", None)
        node_subset_name = instance.data.get("name", None)

        self.log.info("Starting render")
        self.log.info("Start frame: {}".format(first_frame))
        self.log.info("End frame: {}".format(last_frame))

        # Ensure output directory exists.
        directory = os.path.dirname(node["file"].value())
        if not os.path.exists(directory):
            os.makedirs(directory)

        # Render frames
        nuke.execute(node_subset_name, int(first_frame), int(last_frame))

        path = node['file'].value()
        out_dir = os.path.dirname(path)
        ext = node["file_type"].value()

        if "representations" not in instance.data:
            instance.data["representations"] = []

        collected_frames = os.listdir(out_dir)
        repre = {
            'name': ext,
            'ext': ext,
            'frameStart': "%0{}d".format(len(str(last_frame))) % first_frame,
            'files': collected_frames,
            "stagingDir": out_dir,
            "anatomy_template": "render"
        }
        instance.data["representations"].append(repre)

        self.log.info("Extracted instance '{0}' to: {1}".format(
            instance.name, out_dir))

        instance.data['family'] = 'render'
        instance.data['families'].append('render')

        collections, remainder = clique.assemble(collected_frames)
        self.log.info('collections: {}'.format(str(collections)))

        if collections:
            collection = collections[0]
            instance.data['collection'] = collection

        self.log.info('Finished render')
        return
Esempio n. 35
0
    def setUp(self):

        paths = self.__paths()
        for p in paths.keys():
            if os.path.exists(p):
                os.remove(p)

        # Set the default format to be something fun.
        nuke.root()["format"].fromScript(
            "1144 862 0 0 1144 862 2 CortexTestAlexaProxyAnamorphic(2.66)")

        # Create a colourful test image that we will distort.
        n1 = nuke.createNode("ColorWheel")
        n2 = nuke.createNode("ColorBars")
        n3 = nuke.createNode("CheckerBoard2")
        m1 = nuke.createNode("Merge2")
        m2 = nuke.createNode("Merge2")
        m1.setInput(0, n1)
        m1.setInput(1, n2)
        m2.setInput(0, m1)
        m2.setInput(1, n3)
        m2["operation"].setValue(1)

        # Create a write node so that we can save the image to disk.
        w = nuke.createNode("Write")
        w.setInput(0, m2)
        w["file"].setText(paths['path'])

        # Crop the image and generate another test image.
        c = nuke.createNode("Crop")
        c["box"].setValue((29, -74, 374, 448))
        c.setInput(0, m2)

        w2 = nuke.createNode("Write")
        w2.setInput(0, c)
        w2["file"].setText(paths['croppedPath'])

        # Create the test files.
        nuke.execute(w, 1, 1)
        nuke.execute(w2, 1, 1)

        # Finally, read back the images and offset their display windows to make the
        # tests even more interesting...
        offsetImg = IECore.Reader.create(paths['path']).read()
        offsetDisplayWindow = imath.Box2i(
            offsetImg.displayWindow.min() + imath.V2i(-261, 172),
            offsetImg.displayWindow.max() + imath.V2i(-261, 172))
        offsetImg.displayWindow = offsetDisplayWindow
        IECore.Writer.create(offsetImg, paths['offsetPath']).write()

        croppedOffsetImg = IECore.Reader.create(paths['croppedPath']).read()
        offsetDisplayWindow = imath.Box2i(
            croppedOffsetImg.displayWindow.min() + imath.V2i(120, -100),
            croppedOffsetImg.displayWindow.max() + imath.V2i(120, -100))
        croppedOffsetImg.displayWindow = offsetDisplayWindow
        IECore.Writer.create(croppedOffsetImg,
                             paths['croppedOffsetPath']).write()
Esempio n. 36
0
	def writeOut(self, node):
		deselectAllViews()
		reformatNode = self.createReformat(node)
		reformatNode.connectInput(1, node)
		write, pathToCompare = createWriteNode(self.fileName)
		write.connectInput(1, reformatNode)
		nuke.execute(write, 1, 1)
		nuke.tprint("Asserted that WRITE EXECUTED SUCCESSFULLY.")
		return pathToCompare
Esempio n. 37
0
    def setUp(self):

        paths = self.__paths()
        for p in paths.keys():
            if os.path.exists(p):
                os.remove(p)

                # Set the default format to be something fun.
        nuke.root()["format"].fromScript("1144 862 0 0 1144 862 2 CortexTestAlexaProxyAnamorphic(2.66)")

        # Create a colourful test image that we will distort.
        n1 = nuke.createNode("ColorWheel")
        n2 = nuke.createNode("ColorBars")
        n3 = nuke.createNode("CheckerBoard2")
        m1 = nuke.createNode("Merge2")
        m2 = nuke.createNode("Merge2")
        m1.setInput(0, n1)
        m1.setInput(1, n2)
        m2.setInput(0, m1)
        m2.setInput(1, n3)
        m2["operation"].setValue(1)

        # Create a write node so that we can save the image to disk.
        w = nuke.createNode("Write")
        w.setInput(0, m2)
        w["file"].setText(paths["path"])

        # Crop the image and generate another test image.
        c = nuke.createNode("Crop")
        c["box"].setValue((29, -74, 374, 448))
        c.setInput(0, m2)

        w2 = nuke.createNode("Write")
        w2.setInput(0, c)
        w2["file"].setText(paths["croppedPath"])

        # Create the test files.
        nuke.execute(w, 1, 1)
        nuke.execute(w2, 1, 1)

        # Finally, read back the images and offset their display windows to make the
        # tests even more interesting...
        offsetImg = IECore.Reader.create(paths["path"]).read()
        offsetDisplayWindow = IECore.Box2i(
            offsetImg.displayWindow.min + IECore.V2i(-261, 172), offsetImg.displayWindow.max + IECore.V2i(-261, 172)
        )
        offsetImg.displayWindow = offsetDisplayWindow
        IECore.Writer.create(offsetImg, paths["offsetPath"]).write()

        croppedOffsetImg = IECore.Reader.create(paths["croppedPath"]).read()
        offsetDisplayWindow = IECore.Box2i(
            croppedOffsetImg.displayWindow.min + IECore.V2i(120, -100),
            croppedOffsetImg.displayWindow.max + IECore.V2i(120, -100),
        )
        croppedOffsetImg.displayWindow = offsetDisplayWindow
        IECore.Writer.create(croppedOffsetImg, paths["croppedOffsetPath"]).write()
 def takeScreenshot(self, fileName):
     fileName = fileName.replace('\\', '/')
     viewer = nuke.activeViewer()
     actInput = nuke.ViewerWindow.activeInput(viewer)
     viewNode = nuke.activeViewer().node()
     selInput = nuke.Node.input(viewNode, actInput)
     write = nuke.nodes.Write(file=fileName, name='tmpWrite', file_type='jpg')
     write.setInput(0, selInput)
     curFrame = int(nuke.knob("frame"))
     nuke.execute(write.name(), curFrame, curFrame)
     nuke.delete(write)
Esempio n. 39
0
def _createWriter(name, filePath, selectedNode, curFrame):
    
    n = nuke.createNode('Write', inpanel=False)
    n.setName(name)
    n["file"].setValue(filePath.replace("\\", "/"))
    n.setInput(0, selectedNode)
    
    try:
        nuke.execute(name, curFrame, curFrame, 1)
    except RuntimeError as e:
        print str(e)
        return False
    
    return True
Esempio n. 40
0
    def execute(self, instance):
        import nuke

        # Get frame range
        node = instance[0]
        first_frame = nuke.root()["first_frame"].value()
        last_frame = nuke.root()["last_frame"].value()

        if node["use_limit"].value():
            first_frame = node["first"].value()
            last_frame = node["last"].value()

        # Render frames
        nuke.execute(node.name(), int(first_frame), int(last_frame))
Esempio n. 41
0
def executeSelection(firstFrame=nuke.frame(), lastFrame=nuke.frame()):
    nodes = nuke.selectedNodes()
    if nodes:
        try:
            for node in nodes:
                nuke.frame(firstFrame)
                print "executing", node.name(), nuke.frame()
                print 'writing', node['file'].getValue()
                nuke.execute(node, firstFrame, lastFrame)
        except:
            print 'cannot execute', node.name(), '...'
        print 'all done.'
    else:
        nuke.message("Please select some write nodes!")
Esempio n. 42
0
def animatedSnapFunc(nodeToSnap, vertexSelection, knobsToAnimate, knobsToVerify, minVertices = 1, snapFunc = s3d.translateToPointsVerified):
  '''A wrapper to call the relevant snap functions within a framerange loop'''
  temp = None
  try:
    s3d.verifyNodeToSnap(nodeToSnap, knobsToVerify)
    
    # verify vertex selection once before the loop
    s3d.verifyVertexSelection(vertexSelection, minVertices)
    
    # now ask for a framerange
    frames = getFrameRange()
   
    if not frames:  return  # Exit eary if cancelled or empty framerange
    
    # Add a CurveTool for the forced-evaluation hack
    temp = nuke.nodes.CurveTool()
    
    # Set the anim flag on knobs
    for knob in [nodeToSnap[x] for x in knobsToAnimate]:
      # reset animated status
      if knob.isAnimated():
        knob.clearAnimated()
      knob.setAnimated()  

    # Set up Progress Task  
    task = nuke.ProgressTask("animatedSnap3D")
    task.setMessage("Matching position of %s to selected vertices" % nodeToSnap.name())
    
    # Loop through the framerange
    for frame in frames:    
      if task.isCancelled():
        break
      
      # Execute the CurveTool node to force evaluation of the tree
      nuke.execute(temp, frame, frame)
      
      # this is repetitive, but the vertex selection needs to be computed again
      # in order to get the vertices at the right context (time)
      vertexSelection = s3d.getSelection()
      
      # this is also repetitive. Selection should be already verified
      # but checking again in case topology has changed between frames
      s3d.verifyVertexSelection(vertexSelection, minVertices)
      
      # Call the passed snap function from the nukescripts.snap3d module
      snapFunc(nodeToSnap, vertexSelection)
    
  except ValueError, e:
    nuke.message(str(e))
Esempio n. 43
0
def main():
    readNodes = nuke.allNodes('Read')

    readNodePair = readPair(readNodes)

    lrPairs = gernerateLRPair(readNodePair)
        
    for lrPair in lrPairs:
        output = stereoVerticalCombineOutput(lrPair)
        startframe = lrPair[0]['first'].getValue()
        endframe = lrPair[0]['last'].getValue()

        nuke.execute( output, int(startframe), int(endframe) )
    
    os.startfile("e:/nuke")
Esempio n. 44
0
def saveImage(sel, renderTo, filetype):

	w = nuke.nodes.Write()
	w.setInput(0,sel[0])
	w.setXpos(sel[0].xpos())
	w.setYpos(sel[0].ypos()+150)
	w.knob("name").setValue("capture")
	w.knob("use_limit").setValue(True)
	w.knob("first").setValue(nuke.frame())
	w.knob("last").setValue(nuke.frame())
	w.knob("file_type").setValue(filetype)
	w.knob("file").setValue(renderTo+"capture_{time}.{ext}".format(time=getTime(), ext=filetype))
	nuke.execute(w,nuke.frame(),nuke.frame())
	nuke.delete(w)

	openFolder(renderTo)
Esempio n. 45
0
def BreakDowner(listNodes = nuke.selectedNodes()):

    if listNodes is None or listNodes == []:
        raise TypeError, 'You have not selected any nodes !'

    listWriteNode = []
    for node in listNodes:
        nodeName = node['name'].value()
        wName = 'Write_'+nodeName
        w = nuke.nodes.Write()
        w['name'].setValue(wName)
        w.setInput(0, node)
        listWriteNode.append(w)

    project = h.currentProject(filePath)
    print project
    print h.PROJECTS
    shotNumber = h.currentShot(filePath)#.split('/')[-2]
    print shotNumber
    pathBKD = os.path.join(h.PROJECTS, project, h.SHOTS, h.RENDER, shotNumber)#, 'Breakdown')
    if not os.path.exists(pathBKD):
        try:
            os.mkdir(pathBKD)
        except IOError:
            print 'Error IO'
    pathBKD = os.path.join(pathBKD, 'Breakdown')
    try:
        if not os.path.exists(pathBKD):
            os.mkdir(pathBKD)
        else:
            print 'Already Created'
    except IOError:
        print 'An error occured whil creating the dir'
        return -1

    #We set the correct path for the write nodes
    renderOrder = 1
    for w in listWriteNode:
        fileKnob = os.path.join(pathBKD, w['name'].value())
        fileKnob += '.'+str(nuke.frame())+'.exr'

        w['file_type'].setValue('exr')

        w['file'].setValue(fileKnob)

        #write
        nuke.execute(w['name'].value(), int(nuke.frame()), int(nuke.frame()))
Esempio n. 46
0
def exr_split():




    #Path for source and where to
    path_for_jpg = "H://Image Test//Nuke Test"
    path_sequence_to_read = "H://Image Test//testEtienne.exr"

    layers = []
    write_number = 1


    #Creation du read node et attribution du path
    read_node = nuke.createNode('Read')
    read_node.knob("file").setValue(path_sequence_to_read)

    #Query pour le first et last frame
    first_frame = read_node.knob("first").value()
    last_frame = read_node.knob("last").value()


    channels = read_node.channels()

    for c in channels:      #Pour tout les channel dans le node
        layers.append(c.split('.')[0])  #Separer les channels  I.E.: RGBA.Red devient [RGBA,Red] et on prend RGBA
    layers = list(set(layers))      #Eliminer les doubles dans la liste


    for lay in layers:
        if lay == "rgba" or lay == "depth":     #Pour layers qui ne sont pas les layers de base RGBA et Depth
            pass
        else:
            #Creer le shuffle et le write
            shuffle_node = nuke.nodes.Shuffle( label= str(lay), inputs= [read_node])
            write_node = nuke.nodes.Write(inputs= [shuffle_node])

            #Linker le shuffle au channel
            shuffle_node['in'].setValue( lay )

            #Changer le filepath du write et executer le rendu
            write_node.knob("file").setValue(path_for_jpg + "/" + lay + ".jpg")
            nuke.execute("Write" + str(write_number), first_frame, last_frame)

            #Iterer le numero du node write
            write_number = write_number + 1
Esempio n. 47
0
	def testCreationOfZBack( self ) :

		if not IECore.withDeepEXR :
			return
		
		## This test is disabled because Nuke is seg faulting when executing
		## a DeepWrite from command line mode. The same test in an interactive
		## Nuke session works as expected. Last tested in Nuke8.0v3.
		## \todo: Re-enable this test when the Nuke bug is fixed.
		return
		
		# Create a DeepReader to read the deep EXR.
		reader = nuke.createNode( "DeepRead" )
		reader["file"].setText( DeepImageReaderTest.__smokeWithoutZBack )

		# Write it back out. We do this because nuke's DeepSample node is un
		writer = nuke.createNode( "DeepWrite" )
		writer["file"].setText( DeepImageReaderTest.__output )
		nuke.execute( writer, 1, 1 )
		
		# Read the image back in and check the values of it's ZBack channel.
		reader = IECore.EXRDeepImageReader( DeepImageReaderTest.__output )
		header = reader.readHeader()
		resolution = reader['dataWindow'].size() + IECore.V2i( 1 )
			
		self.assertEqual( set( header['channelNames'] ), set( [ 'R', 'G', 'B', 'A', 'ZBack' ] ) )

		for y in range( 0, resolution[0] ) :
			for x in range( 0, resolution[1] ) :
				
				p = reader.readPixel( x, y )
				n = p.numSamples()
				zBackIndex = p.channelIndex( 'ZBack' )

				if n >= 1 :
					n = n - 1

				for s in range( 0, n ) : 
					front = p.getDepth( s )
					back = p.getDepth( s+1 )
					actualBack = p.channelData( s )[ zBackIndex ]
					self.assertEqual( back, actualBack )
Esempio n. 48
0
def getMinMax( srcNode, channel='depth.Z' ):
    '''
    Return the min and max values of a given node's image as a tuple
    args:
       srcNode  - node to analyse
       channels  - channels to analyse. This can either be a channel or layer name
    '''
    MinColor = nuke.nodes.MinColor( channels=channel, target=0, inputs=[srcNode] )
    Inv = nuke.nodes.Invert( channels=channel, inputs=[srcNode])
    MaxColor = nuke.nodes.MinColor( channels=channel, target=0, inputs=[Inv] )
    
    curFrame = nuke.frame()
    nuke.execute( MinColor, curFrame, curFrame )
    minV = -MinColor['pixeldelta'].value()
    
    nuke.execute( MaxColor, curFrame, curFrame )
    maxV = MaxColor['pixeldelta'].value() + 1
    
    for n in ( MinColor, MaxColor, Inv ):
        nuke.delete( n )
    return minV, maxV
Esempio n. 49
0
def outputmov(src,out):
    #global log
    try:
        
        readNode = nuke.createNode('Read')
        writeNode = nuke.createNode('Write')
        readNode.knob('file').setValue(src)
        filePath = nukescripts.replaceHashes(readNode.knob('file').getValue()).replace('%d', '%01d')
        padRe = re.compile('%0(\d+)d')
        padMatch = padRe.search(filePath)
        padSize = int(padMatch.group(1)) 
   
        if padMatch:
            frameList = sorted(glob.iglob(padRe.sub('[0-9]' * padSize, filePath)))
            if frameList:
                missing = 0
                firstVal = os.path.splitext(frameList[0])[0][-padSize:] 
                lastVal = os.path.splitext(frameList[-1])[0][-padSize:] 
                readNode.knob('first').setValue(int(firstVal))
                readNode.knob('last').setValue(int(lastVal))
                readNode.knob('origfirst').setValue(int(firstVal))
                readNode.knob('origlast').setValue(int(lastVal))
            else:
                missing = 1
                errFlg = 1
    
        readNode.knob('colorspace').setValue("rec709")
        #readNode.knob("reload").execute()
        writeNode.knob('file_type').setValue("mov")
        writeNode.knob('file').setValue(out)
        writeNode.knob('colorspace').setValue("rec709")
        writeNode.knob('meta_codec').setValue("png")
        writeNode.knob('mov64_fps').setValue(25)
        nuke.execute('Write1', int(firstVal),int(lastVal))
        nuke.delete(writeNode)
        nuke.delete(readNode)
    except:
        print 'Error'
        nuke.delete(writeNode)
        nuke.delete(readNode)
Esempio n. 50
0
def custom_execute_panel(_list, exceptOnError = True):
	"""
	Override the default way Nuke executes multiple Write nodes to allow
	each Write node's addBeforeRender and addBeforeFrameRender to execute
	code *specific to that node* before they are rendered.
	"""
	_list = nuke.allNodes("Write") if _list[0]	== nuke.root() else _list
	_list = [n for n in _list if not (n['disable'].value() or n['reading'].value())]
	if len(_list) == 0:
		nuke.message("No renderable Write nodes!")
		return
	else:
		_list = sorted(_list,key=lambda x: x['render_order'].value())
		nuke.scriptSave("")
		for n in _list:
			if n['use_limit'].value():
				first,last = n['first'].value(),n['last'].value()
			else:
				first,last = nuke.root().firstFrame(),nuke.root().lastFrame()
			print "Render started: %s" % n.name()
			nuke.execute(n.name(),int(first),int(last))
			print "Render completed: %s" % n.name()
Esempio n. 51
0
def renderQTS(node=nuke.thisNode()):
    verCheck(node)
    if verCheck(node) == "pass" and dpxPath(node) != 'break':
        # Assign Variables
        renderNode = node
        qtPath = outputPath()
        node.begin()
        switch = nuke.toNode("Controller")['which']
        origSwitchValue = switch.animation(0).expression()
        editRender = nuke.toNode("Editorial_RenderNode")
        vfxRender = nuke.toNode("VFX_RenderNode")
        # If QTs already exist, remove them
        for the_file in os.listdir(qtPath):
            file_path = os.path.join(qtPath, the_file)
            if os.path.isfile(file_path) and shotName(node) in the_file:
                os.remove(file_path)
        # Begin rendering
        switch.setExpression(str(0))
        # Sets off specific write nodes depending on the user input
        """ This part needs a callback to stop the function if the render is canceled """
        warning = "In order to render a Quicktime file you must have the DPX input connected to an input."
        if node.input(1):
            try:
                if numQTS == 1:
                    nuke.execute(editRender, (nuke.root().firstFrame()-startFrame), (nuke.root().lastFrame()))
                else:
                    nuke.execute(vfxRender, (nuke.root().firstFrame()-startFrame), (nuke.root().lastFrame()))
                    nuke.execute(editRender, (nuke.root().firstFrame()-startFrame), (nuke.root().lastFrame()))
            except RuntimeError:
                switch.setExpression(origSwitchValue)
                node.end()
                nuke.message(warning)
        else:
            nuke.message(warning)
        switch.setExpression(origSwitchValue)
        node.end()
    else:
        pass
Esempio n. 52
0
	def execute( self ) :

		nuke.execute( self.node(), nuke.frame(), nuke.frame() )
		return _IECoreNuke._opHolderExecuteResult()
Esempio n. 53
0
    else:
        parser.error("can't find matching resolution for " + options.resolution)
else:
    parser.error("can't parse resolution: " + options.resolution)
    
output_movie = nuke.toNode("output_movie")
output_movie["file"].fromUserText(os.path.abspath(options.outputPath))

ext = os.path.splitext(options.outputPath)[1][1:]
if ext == "mov":
    output_movie["format"].setValue("QuickTime / MOV (mov)")
else:
    parser.error("Unsupported output file type: " + ext)

if output_format.width() == 1920 and output_format.height() == 1080 and options.fps in (23.976, 24) and options.codec == "DNxHD 115":
    output_movie["file_type"].setValue("ffmpeg")
    output_movie["fps"].setValue(options.fps)
    output_movie["codec"].setValue("VC3/DNxHD")
    output_movie["bitrate"].setValue(120586240)
else:
    parser.error("Unsupported resolution/codec/fps combination: {width}x{height}/{codec}/{fps}".format(
                           width=output_format.width(),
                           height=output_format.height(),
                           codec=options.codec,
                           fps=options.fps))

if options.onlyDump:
    nuke.scriptSaveAs("/usr/tmp/dump.nk");
else:
    nuke.execute(output_movie, options.frameStart-1, options.frameEnd)
     except Exception, e:
         errors.append("Submit to Screening Room failed - %s" % e)
 
 #render local---
 elif output_name == 'render_local':
     
     #rendering---
     #getting write node
     write_node = item.get("other_params", dict()).get("node")
     
     #getting frame range
     firstframe=nuke.toNode( "root" )['first_frame'].value()
     lastframe=nuke.toNode( "root" )['last_frame'].value()
     
     #render write node
     nuke.execute(write_node,int(firstframe),int(lastframe),1)
     
     #not validating renders atm, might be a problem?---
     
     #publishing files---
     # publish write-node rendered sequence                
     try:
         (sg_publish, thumbnail_path) = self._publish_write_node_render(task, 
                                                                        write_node, 
                                                                        write_node_app, 
                                                                        primary_publish_path, 
                                                                        sg_task, 
                                                                        comment, 
                                                                        progress_cb)
         
         # keep track of our publish data so that we can pick it up later in review
Esempio n. 55
0
def corn3D():
    import nuke
    u = nuke.selectedNodes()
    x = 0
    for u in u:
        x=x+1
    
    if x == 3:  
        # here are basic stuff i will use later frame range and a table    
        frame = nuke.frame()
        panel = nuke.Panel("Card to track")
        first = nuke.Root().knob('first_frame').getValue()
        first = int(first)
        first = str(first)
        last = nuke.Root().knob('last_frame').getValue()
        last = int(last)
        last = str(last)
        basicRange = first+"-"+last
        panel.addSingleLineInput("Range:", basicRange)
        panel.addEnumerationPulldown("Output:", "Tracker CornerPin CornerPin(matrix) All ")
        panel.addSingleLineInput("Ref frame:", frame)
        panel.addBooleanCheckBox('Translate Only', False)
        panel.show()
    
        basicRange = panel.value("Range:")
        refFrame = panel.value("Ref frame:")
        Output = panel.value("Output:")
        Axis = panel.value("Translate Only")
    
    
        refFrame = float(refFrame)
        rangeA = basicRange.split("-")[0]
        rangeA=int(rangeA)
        rangeB = basicRange.split("-")[1]
        rangeB=int(rangeB)
        rangeA=int(rangeA)
        rangeB=int(rangeB)
        
        #here coming the main part where tracker and corner pin are created 
        if Axis == False:
            n = nuke.selectedNodes("Card2")
            for n in n:

                dep = n.dependencies(nuke.INPUTS)[0]
                name = dep['name'].value()
                w = '[value ' + name + '.bbox.w]'
                h = '[value ' + name + '.bbox.h]'
                width = nuke.expression(w)
                heght = nuke.expression(h)
                aspect =  heght/width

                x = n['xpos'].value()
                y = n['ypos'].value()
                unifscale = n['uniform_scale'].value()
                scalingx = n['scaling'].value(0)
                scalingy = n['scaling'].value(1)
                trans = n['translate'].value()
                rot = n['rotate'].value()

                traA = n['translate'].isAnimated()
                rotA = n['rotate'].isAnimated()

                labelC = n['label'].value()
                mainA = nuke.nodes.Axis()

                #mainA['translate'].setValue(trans)
                #mainA['rotate'].setValue(rot)
                mainA['xform_order'].setValue(1)
                if traA is True:
                    mainA['translate'].copyAnimations(n['translate'].animations())
                else:
                    mainA['translate'].setValue(trans)
                
                if rotA is True:
                    mainA['rotate'].copyAnimations(n['rotate'].animations())
                else:
                    mainA['rotate'].setValue(rot)



                mainA['name'].setValue("mainA")
                mainA['xpos'].setValue(x)
                mainA['ypos'].setValue(y)
                
                LU = nuke.nodes.Axis()
                LU['xform_order'].setValue(1)
                LU['translate'].setValue([-0.5*unifscale*scalingx,aspect*0.5*unifscale*scalingy,0])
                LU.setInput(0,mainA)
                LU['name'].setValue('LU')
                LU['xpos'].setValue(x)
                LU['ypos'].setValue(y)        
                
                RU = nuke.nodes.Axis()
                RU['xform_order'].setValue(1)

                RU['translate'].setValue([0.5*unifscale*scalingx,aspect*0.5*unifscale*scalingy,0])
                RU.setInput(0,mainA)
                RU['name'].setValue('RU')
                RU['xpos'].setValue(x)
                RU['ypos'].setValue(y)
                
                LL = nuke.nodes.Axis()
                LL['translate'].setValue([-0.5*unifscale*scalingx,aspect*-0.5*unifscale*scalingy,0])
                LL.setInput(0,mainA)
                LL['name'].setValue('LL')
                LL['xpos'].setValue(x)
                LL['ypos'].setValue(y)
                
                
                RL= nuke.nodes.Axis()
                RL['translate'].setValue([0.5*unifscale*scalingx,aspect*-0.5*unifscale*scalingy,0])
                RL.setInput(0,mainA)
                RL['name'].setValue('RL')
                RL['xpos'].setValue(x)
                RL['ypos'].setValue(y)
            
            n = nuke.selectedNodes()
            for n in n:
                if 'fstop' in n.knobs():
                    Cam = n
                elif 'orientation' in n.knobs():
                    print "."
                else:
                    BG = n 
            
            LUP = nuke.nodes.Reconcile3D()
            LUP.setInput(2,LU)
            LUP.setInput(1,Cam)
            LUP.setInput(0,BG)
            LUP['name'].setValue("P4")
            LUP['xpos'].setValue(x)
            LUP['ypos'].setValue(y)
            
            RUP = nuke.nodes.Reconcile3D()
            RUP.setInput(2,RU)
            RUP.setInput(1,Cam)
            RUP.setInput(0,BG)
            RUP['name'].setValue("P3")
            RUP['xpos'].setValue(x)
            RUP['ypos'].setValue(y)
            
            LLP = nuke.nodes.Reconcile3D()
            LLP.setInput(2,LL)
            LLP.setInput(1,Cam)
            LLP.setInput(0,BG)
            LLP['name'].setValue("P1")
            LLP['xpos'].setValue(x)
            LLP['ypos'].setValue(y)    
            
            RLP = nuke.nodes.Reconcile3D()
            RLP.setInput(2,RL)
            RLP.setInput(1,Cam)
            RLP.setInput(0,BG)
            RLP['name'].setValue("P2")
            RLP['xpos'].setValue(x)
            RLP['ypos'].setValue(y)
        
        
            n = nuke.nodes.Tracker3()
            n['enable1'].setValue(1)
            n['enable2'].setValue(1)
            n['enable3'].setValue(1)
            n['enable4'].setValue(1)
            
            P1 = nuke.toNode("P1")
            nuke.execute(P1,rangeA,rangeB)
            P1p = P1['output'].value()
            
            P2 = nuke.toNode("P2")
            nuke.execute(P2,rangeA,rangeB)
            P2p = P2['output'].value()
            
            P3 = nuke.toNode("P3")
            nuke.execute(P3,rangeA,rangeB)
            P3p = P3['output'].value()
            
            P4 = nuke.toNode("P4")
            nuke.execute(P4,rangeA,rangeB)
            P4p = P4['output'].value()
            
            n['track1'].copyAnimations(P1['output'].animations())
            n['track2'].copyAnimations(P2['output'].animations())
            n['track3'].copyAnimations(P3['output'].animations())
            n['track4'].copyAnimations(P4['output'].animations())
            n['use_for1'].setValue(7)
            n['use_for2'].setValue(7)
            n['use_for3'].setValue(7)
            n['use_for4'].setValue(7)
        
            n['xpos'].setValue(x+100)
            n['ypos'].setValue(y)
            n['label'].setValue(labelC)
        
            # corner pin 
            corner = nuke.nodes.CornerPin2D()  
            corner['to1'].copyAnimations(P1['output'].animations())
            corner['to2'].copyAnimations(P2['output'].animations())
            corner['to3'].copyAnimations(P3['output'].animations())
            corner['to4'].copyAnimations(P4['output'].animations())
            P1val = P1['output'].getValueAt(refFrame)
            P2val = P2['output'].getValueAt(refFrame)
            P3val = P3['output'].getValueAt(refFrame)
            P4val = P4['output'].getValueAt(refFrame)
            corner['from1'].setValue(P1val)
            corner['from2'].setValue(P2val)
            corner['from3'].setValue(P3val)
            corner['from4'].setValue(P4val)
            corner['xpos'].setValue(x+200)
            corner['ypos'].setValue(y)
            refFrame = int(refFrame)
            refFrame = str(refFrame)
            corner["label"].setValue("ref frame: " + refFrame)
        
           
            # cleanup    
            mainA = nuke.toNode("mainA")
            LU = nuke.toNode("LU")
            RU = nuke.toNode("RU")
            LL = nuke.toNode("LL")
            RL = nuke.toNode("RL")
        
            nuke.delete(mainA)
            nuke.delete(LU)
            nuke.delete(RU)
            nuke.delete(LL)
            nuke.delete(RL)
            nuke.delete(P1)
            nuke.delete(P2)
            nuke.delete(P3)
            nuke.delete(P4)
            if Output == "Tracker":
                nuke.delete(corner)
            if Output == "CornerPin":
                nuke.delete(n)
            if Output == "CornerPin(matrix)" or Output == "All":
                print "fdsfdsfsdf"
                projectionMatrixTo = nuke.math.Matrix4()
                projectionMatrixFrom = nuke.math.Matrix4()

                #dir(projectionMatrix)
                theCornerpinNode = corner
                theNewCornerpinNode = nuke.nodes.CornerPin2D()
                theNewCornerpinNode['transform_matrix'].setAnimated()

                imageWidth = float(theCornerpinNode.width())
                imageHeight = float(theCornerpinNode.height())

                first = rangeA                                
                last = rangeB
                frame = first
                while frame<last+1:
                    to1x = theCornerpinNode['to1'].valueAt(frame)[0]
                    to1y = theCornerpinNode['to1'].valueAt(frame)[1]
                    to2x = theCornerpinNode['to2'].valueAt(frame)[0]
                    to2y = theCornerpinNode['to2'].valueAt(frame)[1]
                    to3x = theCornerpinNode['to3'].valueAt(frame)[0]
                    to3y = theCornerpinNode['to3'].valueAt(frame)[1]
                    to4x = theCornerpinNode['to4'].valueAt(frame)[0]
                    to4y = theCornerpinNode['to4'].valueAt(frame)[1] 
                    
                   
                    from1x = theCornerpinNode['from1'].valueAt(frame)[0]
                    from1y = theCornerpinNode['from1'].valueAt(frame)[1]
                    from2x = theCornerpinNode['from2'].valueAt(frame)[0]
                    from2y = theCornerpinNode['from2'].valueAt(frame)[1]
                    from3x = theCornerpinNode['from3'].valueAt(frame)[0]
                    from3y = theCornerpinNode['from3'].valueAt(frame)[1]
                    from4x = theCornerpinNode['from4'].valueAt(frame)[0]
                    from4y = theCornerpinNode['from4'].valueAt(frame)[1]

                    projectionMatrixTo.mapUnitSquareToQuad(to1x,to1y,to2x,to2y,to3x,to3y,to4x,to4y)
                    projectionMatrixFrom.mapUnitSquareToQuad(from1x,from1y,from2x,from2y,from3x,from3y,from4x,from4y)
                    theCornerpinAsMatrix = projectionMatrixTo*projectionMatrixFrom.inverse()
                    theCornerpinAsMatrix.transpose()
                    
                    a0 = theCornerpinAsMatrix[0]
                    a1 = theCornerpinAsMatrix[1]
                    a2 = theCornerpinAsMatrix[2]
                    a3 = theCornerpinAsMatrix[3]    
                    a4 = theCornerpinAsMatrix[4]
                    a5 = theCornerpinAsMatrix[5]
                    a6 = theCornerpinAsMatrix[6]
                    a7 = theCornerpinAsMatrix[7]   
                    a8 = theCornerpinAsMatrix[8]
                    a9 = theCornerpinAsMatrix[9]
                    a10 = theCornerpinAsMatrix[10]
                    a11 = theCornerpinAsMatrix[11]    
                    a12 = theCornerpinAsMatrix[12]
                    a13 = theCornerpinAsMatrix[13]
                    a14 = theCornerpinAsMatrix[14]
                    a15 = theCornerpinAsMatrix[15]

                    theNewCornerpinNode['transform_matrix'].setValueAt(a0,frame,0)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a1,frame,1)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a2,frame,2)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a3,frame,3)    
                    theNewCornerpinNode['transform_matrix'].setValueAt(a4,frame,4)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a5,frame,5)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a6,frame,6)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a7,frame,7)    
                    theNewCornerpinNode['transform_matrix'].setValueAt(a8,frame,8)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a9,frame,9)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a10,frame,10)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a11,frame,11)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a12,frame,12)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a13,frame,13)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a14,frame,14)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a15,frame,15)
                    

                    theNewCornerpinNode['xpos'].setValue(x+300)
                    theNewCornerpinNode['ypos'].setValue(y)
                    theNewCornerpinNode['label'].setValue("matrix")
                    
                    frame = frame + 1
            if Output == "CornerPin(matrix)":
                nuke.delete(corner)
                nuke.delete(n)
       # here is a code for Reconcile only
        else:
            n = nuke.selectedNodes("Card2")
            for n in n:
                x = n['xpos'].value()
                y = n['ypos'].value()        
                trans = n['translate'].value()
                rot = n['rotate'].value()
                scalex = n['scaling'].value(0)
                scaley = n['scaling'].value(1)
                labelC = n['label'].value()
                mainA = nuke.nodes.Axis()
                mainA['translate'].setValue(trans)
                mainA['rotate'].setValue(rot)
                mainA['name'].setValue("mainA")
                mainA['xpos'].setValue(x)
                mainA['ypos'].setValue(y)
            
            n = nuke.selectedNodes()
            for n in n:
                if 'fstop' in n.knobs():
                    Cam = n
                elif 'orientation' in n.knobs():
                    print "."
                else:
                    BG = n 
            
            LUP = nuke.nodes.Reconcile3D()
            LUP.setInput(2,mainA)
            LUP.setInput(1,Cam)
            LUP.setInput(0,BG)
            LUP['name'].setValue("rec")
            LUP['xpos'].setValue(x)
            LUP['ypos'].setValue(y)
                
            n = nuke.nodes.Tracker3()
            n['enable1'].setValue(1)
            
            P1 = nuke.toNode("rec")
            nuke.execute(LUP,rangeA,rangeB)
            P1p = P1['output'].value()
    
            n['track1'].copyAnimations(LUP['output'].animations())
            n['xpos'].setValue(x+100)
            n['ypos'].setValue(y)
            n['label'].setValue(labelC)
                   
            # cleanup    
            mainA = nuke.toNode("mainA")
            rec = nuke.toNode("rec")     
            nuke.delete(mainA)
            nuke.delete(rec)

    else:
        nuke.message("upps... I think you forgot to select Camera+BG+Card") 
Esempio n. 56
0
def createNodesAndWrite():
    print "Preparing nuke to start converting... please wait"
    count = 1
    total = (len(pairs))

    #create read and write for each pair of file paths
    #this can result in a massive script with hundreds of nodes,
    #but as there's no GUI, nuke doesn't care

    for pair in pairs:
        r = nuke.nodes.Read(file = pair[0])
        w = nuke.nodes.Write()

        w['file'].fromUserText(pair[1])#ensures other knobs are activated
        w.setInput(0, r)   

        #set up ideal settings for certain formats
        if format == "jpg" or format == "jpeg":
            w['_jpeg_quality'].setValue(1)
        elif format == "exr":
            w['compression'].setValue('Zip (1 scanline)')
            w['datatype'].setValue('16 bit half')

        #set amount of channels to match input
        if len(r.channels()) > 3:
            w['channels'].setValue('rgba')
        else:
            w['channels'].setValue('rgb')

    #execute all write nodes
    start_time = time.time()

    for w in nuke.allNodes('Write'):

        #clear the terminal of previous output
        os.system('cls' if os.name=='nt' else 'clear')

        #print info about this file and time estimation
        print "---------------------------------"
        print "Image %s of %s" %(count,total)
        print w.input(0)['file'].value().split(inputPath).pop()
        print w['file'].value().split(outputPath).pop()
   
        elapsedTime = time.time() - start_time        
        timeRemaining = ((elapsedTime / count) * (total - count))

        if timeRemaining >=0:
            m, s = divmod(timeRemaining, 60)
            h, m = divmod(m, 60)
            
            print "Est. time remaining: %d:%02d:%02d" % (h, m, s)
            print "---------------------------------"

        #create the output folder/subfolder if not there
        thisPath = os.path.dirname(w['file'].value())
        if not (os.path.exists(thisPath)):
            try:
                os.makedirs(thisPath)
            except:
                print "Problem creating output folder: %s" %(thisPath)
                break

        #execute node
        nuke.execute(w.name(),1,1)

        #delete the read and write to clear some memory
        try:
            r = w.input(0)
            nuke.delete(r)
            nuke.delete(w)
        except:
            print "Couldn't delete nodes"

        count+=1

    #all files converted, clear terminal and present results
    os.system('cls' if os.name=='nt' else 'clear')
    m, s = divmod(elapsedTime, 60)
    h, m = divmod(m, 60)
    print "-----------FINISHED!----------"
    print "%s image(s) converted" %(total)
    print "Total time taken: %d:%02d:%02d" % (h, m, s)
    print "------------------------------"
def MultiChannelSplitSgtk():
    '''
    main function
    split the selected read node in separate channel layers
    if set create separate folders and write nodes 
    '''
    selectedNodes = nuke.selectedNodes()
    lenSelectedNodes= len(selectedNodes)
    shuffles=[]
    renderTo=""
    p_renderLoc=None

    if len(selectedNodes)>0:
        
        p=createPanel()
        if p.show():
            if p.value("prepare for output?") == True:
                p_renderLoc = createPanel_renderloc()
                p_renderLoc.show()
            
            
            
            #main procedure
            #create shuffle, shuffle channel in, curvetool crop, create cropnode and paste that information in, delete crop node
            for readNode in selectedNodes:
                if readNode.Class()=="SgtkRead":
                    uniqueLayers = getUniqueChannelLayerList(readNode)
            
                    for channelLayer in uniqueLayers:
                        shuffleNode = nuke.nodes.Shuffle(name="Shuffle_"+channelLayer)        
                        shuffles.append(shuffleNode.name())
                        shuffleNode.knob("in").setValue(channelLayer)
                        shuffleNode.setInput(0,readNode)
                        
                        #auto crop if selected
                        if p.value("auto crop?")==True:
                            curveNode = nuke.nodes.CurveTool(name="Autocrop_"+channelLayer, inputs = [shuffleNode], operation="Auto Crop")
                            curveNode.knob("ROI").setValue([0,0,readNode.width(),readNode.height()])
                            nuke.execute(curveNode, readNode.knob("first").value(), readNode.knob("last").value())
                            cropNode = nuke.nodes.Crop(name="Crop_"+channelLayer, inputs = [curveNode])
                            cropNode.knob("hide_input").setValue(True)
                            cropNode.knob("box").copyAnimations(curveNode.knob("autocropdata").animations())
                            nuke.delete(curveNode)
                            cropNode.knob("postage_stamp").setValue(True)
                    
                        #create folders for all layer and create write node for every shuffle                       
                        if p_renderLoc!=None:
							renderTo = p_renderLoc.value("render to: ")
							#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 p.value("auto crop?")==True:       
								write.setInput(0,cropNode) 
							else:
								write.setInput(0,shuffleNode) 
                    
                else:
                    nuke.message("No read node selected")
            
            #hide all created shuffle inputs
            for shuffleNode in shuffles:
                if p.value("auto crop?")==False:
                	temp = nuke.toNode(shuffleNode)
                	temp.knob("hide_input").setValue(True)
                	temp.knob("postage_stamp").setValue(True)

            
            nuke.message("Finished shuffling channels and autocropping them")
    else:
            nuke.message("Please select a read node first")
Esempio n. 58
0
    errorExit("Scene open error:\n" + str(sys.exc_info()[1]))

# Try to process read nodes:
readnodes = options.rnode.split(",")
for nodename in readnodes:
    readnode = nuke.toNode(nodename)
    if readnode is None:
        errorExit('Read "%s" not found.' % nodename)

    if readnode.Class() != "Read":
        errorExit('Node "%s" class is not "Read".' % nodename)

    readnode["file"].setValue(sequence)
    readnode["first"].setValue(frame_first)
    readnode["last"].setValue(frame_last)

    if options.colorspace != "":
        readnode["colorspace"].setValue(options.colorspace)

# Try to process write nodes:
writenode = nuke.toNode(options.xnode)
if writenode is None:
    errorExit('Node "%s" not found.' % options.xnode)
if writenode.Class() != "Write":
    errorExit('Node "%s" class is not "Write".' % options.xnode)
writenode["file"].setValue(output)
writenode["fps"].setValue(options.fps)

# Execute process:
nuke.execute(writenode, frame_first, frame_last)
Esempio n. 59
0
def smartRender():

    sel = nuke.selectedNodes()

    if len(sel) > 0:

        # create and show panel
        p = createPanel()

        # getting and setting the path
        r = nuke.root()["name"].value()  # root
        if r != "":

            # save script
            nuke.scriptSave()

            p.show()

            renderChannels = p.value("channels")
            renderFiletype = p.value("filetype")
            renderFromFrame = float(p.value("render from:"))
            renderToFrame = float(p.value("render to:"))
            importRender = p.value("import render when finished")

            rArray = r.split("/")
            rootLast = rArray[len(rArray) - 1]
            rArray.pop()
            renderpath = "/".join(rArray)
            nameArray = rootLast.split(".")
            nameAndFolder = nameArray[0]
            renderTo = renderpath + "/" + nameAndFolder

            print renderpath

            # split up to new location
            renderToArr = renderTo.split("%s" % scriptPath)
            # keep only project path
            renderTo = renderToArr[0]

            # append renderpath and artist
            renderToFromArtist = renderTo + renderPath + "/" + artist
            # renderTo apend folder with name of the script
            renderTo = renderToFromArtist + "/" + nameAndFolder
            renderProjectDirTemp = renderToFromArtist + "/" + nameAndFolder
            renderProjectDirArr = renderProjectDirTemp.split("@")
            renderProjectDir = renderProjectDirArr[0]

            projectNameArr = renderProjectDir.split("/")
            projectName = projectNameArr.pop()

            time = "@" + renderProjectDirArr[1]

            # set render up if not canceled
            if renderChannels is not None:

                # create folder if not exist
                if not os.path.isdir(renderProjectDir + "/" + projectName + time):
                    os.makedirs(str(renderProjectDir + "/" + projectName + time))

                # create write node
                wr = nuke.nodes.Write(name="smart Render", inputs=sel, postage_stamp=True)
                wr.knob("file").setValue(
                    renderProjectDir + "/" + projectName + time + "/" + nameAndFolder + "_%04d." + renderFiletype
                )
                wr.knob("channels").setValue(renderChannels)
                wr.knob("file_type").setValue(renderFiletype)
                wr.knob("use_limit").setValue(True)
                wr.knob("first").setValue(renderFromFrame)
                wr.knob("last").setValue(renderToFrame)

                # write note
                if p.value("note") != "":
                    fobj_out = open(renderProjectDir + "/" + projectName + time + "/_rendernote.txt", "w")
                    fobj_out.write(p.value("note"))
                    fobj_out.close()

                # autoexecute
                autoexecute = p.value("autoexecute")
                if autoexecute == True:
                    nuke.execute(wr, renderFromFrame, renderToFrame)
                    nuke.delete(wr)
                    nuke.message("smart Render finished")

                    # auto import
                    if importRender == True:
                        r = nuke.nodes.Read()
                        r.knob("name").setValue("smart rendered %s" % nameAndFolder)
                        r.knob("file").setValue(
                            renderProjectDir
                            + "/"
                            + projectName
                            + time
                            + "/"
                            + nameAndFolder
                            + "_%04d."
                            + renderFiletype
                        )
                        r.knob("first").setValue(renderFromFrame)
                        r.knob("last").setValue(renderToFrame)
                    else:
                        pass

                else:
                    pass
            else:
                pass

            # save, create new script so the script of the rendered version won't get changed from here
            smartSaver()
        else:
            nuke.message(
                "You haven't safed your nuke project. Please make sure to save your project first in order to proceed."
            )

    else:
        nuke.message("Please select a node from where you want to render from")