Exemplo n.º 1
0
Arquivo: Tools.py Projeto: Ahuge/Nuke
def RotoOutputNode():
    #Creates a NoOp
    Placeholder = nuke.createNode("NoOp")
    #assigns a varriable to the currently selected node
    OpNo = nuke.selectedNode()
    #Creates a roto node
    Roto = nuke.createNode("Roto")
    #Creates the RotoOutput tool
    Output = nuke.loadToolset("Ahuge_Tools/Roto_Output.nk")
    #Sets the first input of the RotoOutput to our NoOp
    Output.setInput (0, Placeholder)
    #Sets the second input to the roto node
    Output.setInput(1, Roto)
	#Move the Output Node
    Output.setXpos (Output.xpos() -140)
    Output.setYpos (Output.ypos() +84)
    #Move the Roto Node
    Roto.setXpos (Output.xpos() -220)
    Roto.setYpos (Output.ypos() +6)
    #Creates a Input node for the roto to connect to
    Dummy = nuke.createNode("Input")
    Roto.setInput(0, Dummy)
    #Deletes the Input and the NoOp
    nuke.delete(Dummy)
    nuke.delete(Placeholder)
Exemplo n.º 2
0
	def levelDistinction(self):
		'''
		create scene and camera node
		'''
		swch = 0

		self.camera = nuke.createNode('Camera2', 'read_from_file true file %s' % self.fbxCamFile,inpanel=False)

		self.camera.forceValidate()
		self.camera.setXYpos( -77 , -1282 )
		self.bDropA  = nuke.createNode('BackdropNode', inpanel=False)
		self.bDropA['label'].setValue('Cam imported from Maya')

		self.bDropA.setXYpos( -149 , -1360 )
		self.bDropA['bdwidth'].setValue(180)
		self.bDropA['bdheight'].setValue(260)

		self.scene = nuke.createNode('Scene',inpanel=False)
		self.scene.setXYpos( -100 , -70)

		'''
		from within each of fg mg and bg read sub levels , call createNodeSet for each of them
		'''
		for single in self.nkNodeList:
			copiedNode = nuke.nodePaste(single)
			self.SceneIncr = self.SceneIncr + 1
			retv = self.createNodeSet(copiedNode,self.SceneIncr)

		return swch
Exemplo n.º 3
0
    def populate(self, number):
        """
        from the number of points given by the user,
        create a sphere on a random point of the source object
        """
        # randomize points
        numPList = range(self.numP)
        random.shuffle(numPList)
        numP = numPList[1:number+1]
        objects = []

        for p in numP:
            point =  self.numPList[p]   
            # create sphere
            sphere = nuke.createNode("Sphere", inpanel = False)
            sphere['uniform_scale'].setValue(.2)
            sphere['rows'].setValue(8)
            sphere['columns'].setValue(8)
            # move the sphere
            sphere['translate'].setValue(point)
          
            objects.append(sphere)
    
        # unselect all nodes
        [node.knob('selected').setValue(False) for node in nuke.allNodes()]

        # create scene
        if objects:
            for node in objects:
                node['selected'].setValue(True)
            scene = nuke.createNode("Scene")
            
            return objects, scene
Exemplo n.º 4
0
	def testUndo( self ) :

		# check our custom knob undoes in the same way as
		# standard knobs

		n = nuke.createNode( "ieObject" )
		n2 = nuke.createNode( "Blur" )

		self.assertEqual( n.knob( "object" ).getValue(), None )
		self.assertEqual( n2.knob( "size" ).getValue(), 0 )

		self.assertEqual( nuke.Undo.disabled(), True )

		with IECoreNuke.UndoEnabled() :

			self.assertEqual( nuke.Undo.disabled(), False )

			with IECoreNuke.UndoBlock() :

				n.knob( "object" ).setValue( IECore.IntData( 10 ) )
				self.assertEqual( n.knob( "object" ).getValue(), IECore.IntData( 10 ) )

				n2.knob( "size" ).setValue( 10 )
				self.assertEqual( n2.knob( "size" ).getValue(), 10 )

		self.assertEqual( nuke.Undo.disabled(), True )

		self.assertEqual( n.knob( "object" ).getValue(), IECore.IntData( 10 ) )
		self.assertEqual( n2.knob( "size" ).getValue(), 10 )

		nuke.undo()

		self.assertEqual( n2.knob( "size" ).getValue(), 0 )
		self.assertEqual( n.knob( "object" ).getValue(), None )
Exemplo n.º 5
0
 def createCards(self, autocropnodes):
     
     cards = []
     xformgeos = []
     ID = 0
     trZ = 0
     
     for node in autocropnodes:
         
         Psdutils().selectReplace(node)
         
         X, Y, w, h, r, t, trX, trY, scaleX, scaleY, cardcol, cardrow = self.getXform(node, ID)
         
         card = nuke.createNode('Card2', inpanel = False)
         card.knob('rows').setValue(cardrow)
         card.knob('columns').setValue(cardcol)
         card.knob('image_aspect').setValue(0)
         cards.append(card)
         
         tr3d = nuke.createNode('TransformGeo', inpanel = False)			
         tr3d.knob('translate').setValue([trX, trY, trZ])
         tr3d.knob('scaling').setValue([scaleX, scaleY, 1])
         
         xformgeos.append(tr3d)
         ID = ID+1
         trZ = trZ-1.5
         
     return cards, xformgeos
Exemplo n.º 6
0
def allMerge():
	sels = nuke.selectedNodes()
	sels = sorted(sels, key=lambda s: s.xpos())
	n = nuke.getInput('number of items in a group', '0')
	try:
		n = int(n)
	except:
		print('wrong input')
		raise
	if n == 0 or n > len(sels):
		n = len(sels)
	if n == 1:
		for s in sels:
			merge = nuke.createNode('Merge')
			merge.setInput(0, s)
			merge.setInput(1, None)
		return
	selGroup=zip(*[sels[i::n] for i in range(n)])
	for group in selGroup:
		A = None
		for B in group:
			if not A:
				A = B
			else:
				merge = nuke.createNode('Merge')
				merge.setInput(0, A)
				merge.setInput(1, B)
				A = merge
Exemplo n.º 7
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)
Exemplo n.º 8
0
def createWriteFromRead(nodes=[]):
  '''
  function to create a write node
  from a selected read node
  '''

  # if no nodes are defined look for selected nodes
  if not nodes:
    nodes = nuke.selectedNodes()
  
  # if nodes is still empty, nothing is selected
  if not nodes:
    nuke.message('ERROR: No node(s) selected.')
    return
  
  for node in nodes:
    _class = node.Class()
    if _class == "Read":
      file = node.knob('file').getValue()
      proxy = node.knob('proxy').getValue()
      first = nuke.toNode('root').knob('first_frame').getValue()
      last = nuke.toNode('root').knob('last_frame').getValue()
      xpos = node.knob('xpos').getValue()
      ypos = int(node.knob('ypos').getValue()) + 40
      knobs = []
      fields = ('file','proxy','first','last','xpos','ypos')
      for entry in fields:
        if eval(entry) != '':
          knobs.append(entry)
          #knobs.append(str(eval(entry)))
      nuke.createNode('Write', string.join(knobs))  
  return
Exemplo n.º 9
0
def CreatPointCloud(points):
    #Takes: points as list of OrderedDicts, each vertex should have 9 keys [x,y,z,u,v,w,r,g,b] values should be formatted as strings
    #Performs: creates BakedPointCloud node in nuke, populates it with data
    #Returns: BakedPointCloud node
    import nuke
    pcPoints = pcVelocities = pcColors = str(len(points))+' '
    for point in points:
        pcPoints += ' '.join(point.values()[0:3])+' '
        pcVelocities += ' '.join(point.values()[3:6])+' '
        pcColors += ' '.join(point.values()[6:9])+' '
    pcNode = nuke.createNode("BakedPointCloud")
    pcNode['serializePoints'].fromScript(pcPoints)
    pcNode['serializeNormals'].fromScript(pcVelocities)
    pcNode['serializeColors'].fromScript(pcColors)
    pcNode['pointSize'].setValue(0.25)
    
    axisNode = nuke.createNode('Axis')
    axisNode.setName('BakedPointCloudAxis'+pcNode.name().rsplit('Cloud',1)[-1])
    pcNode['translate'].setExpression('parent.BakedPointCloudAxis1.translate')
    pcNode['rotate'].setExpression('parent.BakedPointCloudAxis1.rotate')
    pcNode['scaling'].setExpression('parent.BakedPointCloudAxis1.scaling')
    pcNode['uniform_scale'].setExpression('parent.BakedPointCloudAxis1.uniform_scale')
    pcNode['skew'].setExpression('parent.BakedPointCloudAxis1.skew')
    pcNode['pivot'].setExpression('parent.BakedPointCloudAxis1.pivot')
    pcNode['useMatrix'].setExpression('parent.BakedPointCloudAxis1.useMatrix')
    
    return pcNode
Exemplo n.º 10
0
def quick_3d():

# create a checkerboard, card, scene, scanlinerender, camera node
    checkerboard_node = nuke.createNode('CheckerBoard2', inpanel=False)
    card_node = nuke.createNode('Card', inpanel=False)
    scene_node = nuke.createNode('Scene', inpanel=False)
    scanline_node = nuke.createNode('ScanlineRender', inpanel=False)
    cam_node = nuke.createNode('Camera', inpanel=False)

# Connect the camera to the scanline render
    scanline_node.setInput(2, cam_node) # input_number, node_to_connect

# Connect the camera to the scene
    scene_node.setInput(1, cam_node)

    x_pos = checkerboard_node['xpos'].value()
    y_pos = checkerboard_node['ypos'].value()

    card_node['xpos'].setValue(x_pos)
    card_node['ypos'].setValue(y_pos + 100)
    
    scene_node['xpos'].setValue(x_pos)
    scene_node['ypos'].setValue(y_pos + 200)

    scanline_node['xpos'].setValue(x_pos)
    scanline_node['ypos'].setValue(y_pos + 300)

    cam_node['xpos'].setValue(x_pos - 100)
    cam_node['ypos'].setValue(y_pos + 300)
Exemplo n.º 11
0
def createReadFromWrite(nodes=[]):
	'''
	function to create a read node
	from a selected write node
	'''

	# if no nodes are defined look for selected nodes
	if not nodes:
		nodes = nuke.selectedNodes()
	
	# if nodes is still empty, nothing is selected
	if nodes == ():
		nuke.message('ERROR: No node(s) selected.')
		return
	
	#work around to select single node as an object
	node = nodes[0]
	_class = node.Class()
	if _class == "Write":
		file = node.knob('file').getValue()
		proxy = node.knob('proxy').getValue()
		first = nuke.toNode('root').knob('first_frame').getValue()
		last = nuke.toNode('root').knob('last_frame').getValue()
		xpos = node.knob('xpos').getValue()
		ypos = int(node.knob('ypos').getValue()) + 40
		knobs = []
		fields = ('file','proxy','first','last','xpos','ypos')
		for entry in fields:
			if eval(entry) != '':
				knobs.append(entry)
				knobs.append(str(eval(entry)))
		nuke.createNode('Read', string.join(knobs))	
	return
Exemplo n.º 12
0
	def testReadOfShwAgainstExr( self ) :
		import IECoreRI
	
		# Create a DeepReader to read a deep EXR.	
		readerExr = nuke.createNode( "DeepRead" )
		readerExr["file"].setText( self.__inputPaths()["exr"] )

		# Create an ieDeepImageReader to read the deep SHW.
		readerShw = nuke.createNode("DeepRead")
		readerShw["file"].setText( self.__inputPaths()["shw"] )
		
		random.seed( 1 )

		# Randomly sample 200 points and check that they are the same in both images.
		for i in range( 0, 200 ) :
			x = random.randint( 0, 511 )
			y = random.randint( 0, 511 )
			
			# Check that both image have the same number of samples.
			nSamplesExr = readerExr.deepSampleCount( x, y )
			nSamplesShw = readerShw.deepSampleCount( x, y )
			self.assertEqual( nSamplesExr, nSamplesShw )
		
			for channel in [ "front", "back", "A" ] :
				for idx in range( 0, nSamplesExr ) :
					frontExr = readerExr.deepSample( channel, x, y, idx )
					frontShw = readerShw.deepSample( channel, x, y, idx )
					self.assertEqual( frontExr, frontShw )
Exemplo n.º 13
0
def pStamp(nodes,posX,posY):
    #create postage stamp
    inputNodes = []
    inputNodes.append(nodes)
    for a in inputNodes:
        if a.Class()=='Read':
            namer = a.knob('file').getValue()
            col=2570627072
        else:
            namer=a.knob('name').getValue()
            col=2993684480
        namer= namer.split('/')[-1].split('.')[0]
        namer=namer+'_001'
        nukescripts.clear_selection_recursive()
        nuke.createNode('PostageStamp').setXYpos(posX,posY)
        for i in nuke.selectedNodes():
            i.setInput(0,a)
            i['tile_color'].setValue(col)
            verList=[]
            for i in nuke.allNodes():
                    if i.Class()=='PostageStamp':
                        if i.knob('name').getValue()[:-2]==namer[:-2]:
                            nVer = i.knob('name').getValue()[-1]
                            verList.append(nVer)
                            while namer[-1] in verList:
                                ver=int(namer[-1])
                                ver=str(int(ver)+1)
                                namer=namer[:-1]+ver
            for a in nuke.selectedNodes():
                if a.Class()=='PostageStamp':
                    a.knob('hide_input').setValue(True)
                    a.knob('name').setValue(namer)
                    nukescripts.clear_selection_recursive()
    return namer    
Exemplo n.º 14
0
def sb_backdrop():

# Create the panel.
    p = nuke.Panel( "sb Backdrop" )
    p.addSingleLineInput('Backdrop name', '')
    p.addSingleLineInput('Font size', '92')
    result = p.show()
    
    if not result:
        return
    
    bd_name = p.value("Backdrop name")
    font_size = p.value("Font size")

    if not font_size.isdigit():
        font_size = 92
    else:
        font_size = int(font_size)

    ok_colors =  [726945023, 758728703, 1194668799, 1161185279, 658977535, 1145521407, 1095189759, 942753791, 994522623]
    ran_num = random.randrange(0,len(ok_colors))
    color = ok_colors[ran_num]

    selNodes = nuke.selectedNodes()
    if not selNodes:
        n = nuke.createNode("BackdropNode", inpanel=False)
        n["tile_color"].setValue(color)
        n["note_font_size"].setValue(font_size)
        n["label"].setValue(bd_name)
        return

    # Calculate bounds for the backdrop node.
    bdX = min([node.xpos() for node in selNodes])
    bdY = min([node.ypos() for node in selNodes])
    bdW = max([node.xpos() + node.screenWidth() for node in selNodes]) - bdX
    bdH = max([node.ypos() + node.screenHeight() for node in selNodes]) - bdY

    # Expand the bounds to leave a little border. Elements are offsets for left, top, right and bottom edges respectively
    left, top, right, bottom = (-200, -250, 200, 200)
    bdX += left
    bdY += top
    bdW += (right - left)
    bdH += (bottom - top)

    n = nuke.createNode("BackdropNode", inpanel=False)
    n["xpos"].setValue(bdX)
    n["bdwidth"].setValue(bdW)
    n["ypos"].setValue(bdY)
    n["bdheight"].setValue(bdH)
    n["tile_color"].setValue(color)
    n["note_font_size"].setValue(font_size)
    n["label"].setValue(bd_name)

    # revert to previous selection
    n['selected'].setValue(False)
    for node in selNodes:
        node['selected'].setValue(True)

    return n
Exemplo n.º 15
0
def custom_create_read(defaulttype="Read"):

    """Create a Read node for a file selected from the file browser. 
    If a node is currently selected in the nodegraph and it has a 'file' 
    (or failing that a 'proxy') knob, the value (if any) will be used as the default 
    path for the file browser."""
    # Get the selected node, and the path on it's 'file' knob if it
    # has one, or failing that, it's 'proxy' node, if it has that.
    sel_node = None
    default_dir = None
    try:
        sel_node = nuke.selectedNode()
    except:
        pass
    if (sel_node is not None) and (sel_node != ""):
        if "file" in sel_node.knobs():
            default_dir = sel_node["file"].value()
        if (default_dir == None or default_dir == "") and "proxy" in sel_node.knobs():
            default_dir = sel_node["proxy"].value()

    # Revert default_dir to None if it's empty so that the file browser
    # will do it's default unset behaviour rather than open on an empty path.
    if default_dir == "":
        default_dir = None

    # Raise the file browser and get path(s) for Read node(s).
    files = nuke.getClipname("Read File(s)", default=default_dir, multiple=True)
    if files != None:
        maxFiles = nuke.numvalue("preferences.maxPanels")
        n = len(files)
        for f in files:
            log_(f)
            isAbc = False
            stripped = nuke.stripFrameRange(f)
            nodeType = defaulttype
            if isAudioFilename(f):
                nodeType = "AudioRead"
            if isGeoFilename(f):
                nodeType = "ReadGeo2"
            if isAbcFilename(f):
                isAbc = True
            if isDeepFilename(f):
                nodeType = "DeepRead"

                # only specify inpanel for the last n nodes. Old panels are kicked out using
                # a deferred delete, so reading large numbers of files can internally build
                # large numbers of active widgets before the deferred deletes occur.
            useInPanel = True
            if maxFiles != 0 and n > maxFiles:
                useInPanel = False
            n = n - 1

            if isAbc:
                nuke.createScenefileBrowser(f, "")
            else:
                try:
                    nuke.createNode(nodeType, "file {" + f + "}", inpanel=useInPanel)
                except RuntimeError, err:
                    nuke.message(err.args[0])
Exemplo n.º 16
0
def createProject3D(CameraNode, ReadNode, LastMergeNode):
    ProjectNode = nuke.createNode('Project3D')
    ProjectNode.setInput(0, ReadNode)
    ProjectNode.setInput(1, CameraNode)
    deselectAll()
    MergeNode = nuke.createNode('MergeMat')
    MergeNode.setInput(0, LastMergeNode)
    MergeNode.setInput(1, ProjectNode)
    deselectAll()
    return ProjectNode, MergeNode
Exemplo n.º 17
0
def mosaicer():
    values = getTextureNodes()
    
    if values:
        nodes = values['reads']
        tiles = values['tilesNumber']
        prefix = values['texturePrefix']
        #resolution = getResolutionFromNodes(nodes)
        resolution = values['resolution']
        tileSize = float(resolution)/float(tiles)

        # add format
        formatN = ("mosaicFormat")
        form = ("%s %s 1 %s" % (resolution, resolution, formatN))
        nuke.addFormat(form)
        formatDict = {}
        for item in nuke.formats():
            formatDict[item.name()]=item
        nuke.Root()['format'].setValue(formatDict[formatN])
        
        # create background node
        bg = nuke.createNode('Constant', inpanel=False)
        bg['format'].setValue(formatN)

        merges = []
        deselectAll()

        for node in nodes:
            node.setSelected(True)
            filename = os.path.basename(node['file'].value())
            s, t = filename.split('_')[-3].split('s')[-1].split('t')
            # create reformat
            reformat = nuke.createNode('Reformat', inpanel=False)
            reformat['type'].setValue(1)
            reformat['box_fixed'].setValue(True)
            reformat['box_width'].setValue(tileSize)
            reformat['box_height'].setValue(tileSize)
            # create transform
            transform = nuke.createNode('Transform', inpanel=False)
            transform['center'].setValue([0, 0])
            transform['translate'].setValue([float(s)*tileSize, float(t)*tileSize])
            deselectAll()
            # create merge
            merge = nuke.createNode('Merge', inpanel=False)
            merge.setInput(1, transform)
            merge.setInput(0, bg)
            merges.append(merge)

        #deselectAll()
        #for m in merges:
        #    m.setSelected(True)
        #nuke.createNode('Merge', inpanel=False)
    else:
        print "abort."
Exemplo n.º 18
0
def createBeautyNodeTree():
    """
    This method creates all the necessary nodes needed for a beauty pass.
    This is basically like a preset which is followed in every similar scenario
    :return:
    """
    node = nuke.toNode("beautyRead")
    node['selected'].setValue(True)
    nuke.createNode('EdgeBlur')
    bGrade = nuke.createNode('Grade')
    bGrade.knob('name').setValue('beautyGrade')
Exemplo n.º 19
0
def merge():
    sel = nuke.selectedNodes()
    sel3d = []
    for node in sel:
        if node.knob('display'):
            sel3d.append(node)

    if sel3d and len(sel) == len(sel3d):
        nuke.createNode('Scene')
    else:
        nuke.createNode('Merge2')
Exemplo n.º 20
0
def createViewerInput():
    """create the color check node"""
    if 'VIEWER_INPUT' not in [node.name() for node in nuke.allNodes()]:
        for node in nuke.allNodes():
            node['selected'].setValue(False)
        nuke.createNode("dmpViewerInput")
        node = nuke.toNode('VIEWER_INPUT')
        node.showControlPanel()
        node['selected'].setValue(False)
    else:
        nuke.toNode('VIEWER_INPUT').showControlPanel()
Exemplo n.º 21
0
 def _readwrites(blankread, check, threshold,  report):
     
     sn = [n for n in nuke.selectedNodes() if n.Class() == "Write"]
     
     if sn == [] and blankread == True:
         nuke.createNode("Read", "", True)
         
     elif sn == [] and blankread == False:
         return None
         
     elif sn != []:
         for n in sn:
             
             file = n.knob('file').value()
             proxy = n.knob('proxy').value()
             colorspace = n.knob('colorspace').value()
             premult = n.knob('premultiplied').value()
             rawdata = n.knob('raw').value()
             xpos = n.knob('xpos').value()
             ypos = n.knob('ypos').value()
             
             firstFrame = nuke.value(n.name()+".first_frame")
             lastFrame = nuke.value(n.name()+".last_frame")
             
             if file == '' and proxy == '':
                 if blankread == True:
                     read = nuke.createNode("Read", "", False)
                     read.knob('xpos').setValue(xpos)
                     read.knob('ypos').setValue(ypos + 80)
                     nuke.inputs(read, 0)
                     continue
                 elif blankread == False:
                     continue
             
             args = 'file {%s} proxy {%s} first %s last %s colorspace %s premultiplied %s raw %s' % (file, proxy, firstFrame, lastFrame, colorspace, premult, rawdata)
             
             read = nuke.createNode('Read', args)
             read.knob('xpos').setValue(xpos)
             read.knob('ypos').setValue(ypos + 80)
             nuke.inputs(read, 0)
             if check == True:
                 _checkbadframes(read, report)
                 continue
                 
             else:
                 continue
                 
             return None
             
     else:
         return None 
    def _create_read_node(self, path, sg_publish_data):
        """
        Create a read node representing the publish.
        
        :param path: Path to file.
        :param sg_publish_data: Shotgun data dictionary with all the standard publish fields.        
        """        
        import nuke
        
        (_, ext) = os.path.splitext(path)


        # If this is an Alembic cache, use a ReadGeo2 and we're done.
        if ext.lower() == ".abc":
            nuke.createNode("ReadGeo2", "file {%s}" % path)
            return

        valid_extensions = [".png", 
                            ".jpg", 
                            ".jpeg", 
                            ".exr", 
                            ".cin", 
                            ".dpx", 
                            ".tiff", 
                            ".tif", 
                            ".mov",
                            ".mp4",
                            ".psd",
                            ".tga",
                            ".ari",
                            ".gif",
                            ".iff"]

        if ext.lower() not in valid_extensions:
            raise Exception("Unsupported file extension for '%s'!" % path)

        # `nuke.createNode()` will extract the format and frame range from the
        # file itself (if possible), whereas `nuke.nodes.Read()` won't. We'll
        # also check to see if there's a matching template and override the
        # frame range, but this should handle the zero config case. This will
        # also automatically extract the format and frame range for movie files.
        read_node = nuke.createNode("Read")
        read_node["file"].fromUserText(path)

        # find the sequence range if it has one:
        seq_range = self._find_sequence_range(path)

        if seq_range:
            # override the detected frame range.
            read_node["first"].setValue(seq_range[0])
            read_node["last"].setValue(seq_range[1])
Exemplo n.º 23
0
def abcDropping( mimeType, text):
	if text[-4:] == '.abc' and os.path.exists(text):
		readGeo = nuke.createNode('ReadGeo2', 'file {%s}' % (text))
		sceneView = readGeo['scene_view']
		allItems = sceneView.getAllItems()

		if allItems:
			sceneView.setImportedItems(allItems)
			sceneView.setSelectedItems(allItems)
		else:
			nuke.delete(readGeo)
			nuke.createNode('Camera2', 'file {%s} read_from_file True' % (text))
		return True
	return False
Exemplo n.º 24
0
def shuffleLayers():
	""" expand channels
	"""

	selectedNode = nuke.selectedNode()

	re_rgba = re.compile(r"^rgba$")
	re_rgb = re.compile(r"^rgb$")
	re_alpha = re.compile(r"^alpha$")

	layerList = [i for i in nuke.layers(selectedNode) if (not re_rgba.match(i)) and (not re_rgb.match(i)) and (not re_alpha.match(i))]
	if not layerList:
		return
	print layerList

	dot1 = nuke.createNode('Dot', inpanel = False)
	dot1.setInput(0, selectedNode)
	dot1['ypos'].setValue(dot1.ypos() + 100)

	# first shuffle
	firstLayer = layerList[0]
	shuffle = nuke.createNode('Shuffle', inpanel = False)
	shuffle['label'].setValue('<b>[value in]')
	shuffle['in'].setValue(firstLayer)
	shuffle['in2'].setValue('alpha')
	shuffle['alpha'].setValue('rea2')

	shuffle.setInput(0, dot1)
	shuffle['selected'].setValue(False)
	shuffle['ypos'].setValue(shuffle.ypos() + 100)

	if len(layerList) == 1:
		return

	# dot1['selected'].setValue(Ture)
	dotList = []
	shuffleList = []

	m = 0
	n = 0

	for i in layerList[1:]:
		m += 1
		n += 200
	    dotn = nuke.createNode('Dot', inpanel = False)
	    dotList.append(dotn)
	    dotn['xpos'].setValue(dot1.xpos() + n)
	    dotn['ypos'].setValue(dot1.ypos())
	    if m == 1:
	    	dotn.setInput(0, dot1)
Exemplo n.º 25
0
def splitRoto():
    
    if nuke.selectedNode().Class() == 'RotoPaint':
        roto = nuke.selectedNode().knob('curves').rootLayer
        for i in roto:
            tempRoto = nuke.createNode('RotoPaint')
            tempRoto.knob('curves').rootLayer.append(i.clone())
    elif nuke.selectedNode().Class() == 'Roto':
        roto = nuke.selectedNode().knob('curves').rootLayer
        for i in roto:
            tempRoto = nuke.createNode('Roto')
            tempRoto.knob('curves').rootLayer.append(i.clone())
    else:
        nuke.message('No roto/paint node selected')
Exemplo n.º 26
0
def readShot():
	import shotgun
	shotcode = nuke.getInput('Shot Code')
	s = shotgun.getShotData(shotcode, ['Source clip', 'Cut In', 'Cut Out'])
	(clipName, crc) = s['Source clip'].strip().split(':')
	results = nuke.spotlight(clipName)
	if results:
		for readPath in results:
			if sha1(open(readPath).read()).hexdigest() == crc:
				readPath = nuke.pacify(readPath)
				nuke.createNode('Read','file %s' % readPath)
				rangeStr = 'first_frame %s last_frame %i' % (s['Cut In'],int(s['Cut Out']-1))
				nuke.createNode('FrameRange',rangeStr)
	else:
		nuke.message('Cannot locate clip %s' % clipName)
Exemplo n.º 27
0
def autoWritedpx():
	import os
	import nuke
	import re
	import nukescripts

	scriptPath = nuke.root().knob('name').value()
	scriptPathList = re.split('/',scriptPath)

	tempA = scriptPathList[-1]
	tempB = re.split('\.', tempA)

	scriptName = tempB[0]
	showName = scriptPathList[-5]
	shotName = scriptPathList[-3]
	diskStationPath = '/Volumes/VOLT_CENTRAL'
	print showName
	print shotName
	print scriptName


	p = nuke.Panel('Any Sub Folder?')

	p.addSingleLineInput('Sub Folder', 'None')
	p.addButton('Nope')
	p.addButton('Yes, mkdir please')

	ret = p.show()
	subFolder = None
	subFolder = p.value('Sub Folder')

	if subFolder == 'None':
		try:
			os.makedirs(diskStationPath +'/'+ showName +'/'+ 'Dailies' +'/'+ shotName +'/'+ scriptName)
		except:
			pass
		w = nuke.createNode('Write', inpanel = True)
		output_path = diskStationPath +'/'+ showName +'/'+ 'Dailies' +'/'+ shotName +'/'+ scriptName +'/'+ scriptName +'.%04d.dpx'
		w.knob('file').fromScript(output_path)

	else:
		try:
			os.makedirs(diskStationPath +'/'+ showName +'/'+ 'Dailies' +'/'+ shotName +'/'+ scriptName + '/' + subFolder)
		except:
			pass
		w = nuke.createNode('Write', inpanel = True)
		output_path = diskStationPath +'/'+ showName +'/'+ 'Dailies' +'/'+ shotName +'/'+ scriptName +'/'+ subFolder + '/' + scriptName +'.%04d.dpx'
		w.knob('file').fromScript(output_path)
Exemplo n.º 28
0
def mocha_import():
    """
    Asks the user for the filename to be imported, then decides the pathway and builds the appropriate Tracker node.
    """
    initial = _getfilename()
    imported = []

    if initial.endswith('.txt'):
        imported = _ascii_import(initial)
    elif initial.endswith('.shk'):
        imported = _shk_import(initial)
    else:
        print "That file is not a .txt or a .shk"
    
    track1 = str(imported[0][0])
    track2 = str(imported[0][1])
    track3 = str(imported[0][2])
    track4 = str(imported[0][3])
    shapeName = str(imported[1])

    tk = nuke.createNode("Tracker3")
    tk.knob("track1").fromScript(track1)
    tk.knob("track2").fromScript(track2)
    tk.knob("track3").fromScript(track3)
    tk.knob("track4").fromScript(track4)
    tk.knob("label").setValue(shapeName)
    tk.knob("enable1").setValue(True)
    tk.knob("enable2").setValue(True)
    tk.knob("enable3").setValue(True)
    tk.knob("enable4").setValue(True)
    tk.knob("use_for1").fromScript('all')
    tk.knob("use_for2").fromScript('all')
    tk.knob("use_for3").fromScript('all')
    tk.knob("use_for4").fromScript('all')
Exemplo n.º 29
0
def shakeClone():
	EXCLUSION_LIST = ["xpos","ypos","help","hide_input","note_font_color","onCreate","updateUI","knobChanged","note_font","tile_color","selected","autolabel","process_mask","label","onDestroy","inject","indicators","maskFrom","maskChannelMask","maskChannelInput","Mask","postage_stamp", "postage_stamp_frame","disable","maskChannelMask", "panel", "maskFromFlag","name","cached","fringe", "maskChannelInput" , "note_font_size" , "filter", "gl_color","transform", "dope_sheet"]

	originals = nuke.selectedNodes()
	[ n['selected'].setValue(False) for n in nuke.allNodes() ]

	for original in originals:
		new = nuke.createNode(original.Class())

		for i in original.knobs():
			if i not in EXCLUSION_LIST:
								# Try to set the expression on the knob
				new.knob(i).setExpression("%s.%s" % (original.name(), original.knob(i).name()))

								# This will fail if the knob is an Array Knob...use setSingleValue to compensate
								# Thanks Hugh!
				if isinstance(new.knob(i), nuke.Array_Knob):
					new.knob(i).setSingleValue(original.knob(i).singleValue()) 

								# This will fail if the knob is a String Knob...use a TCL expression link to compensate
								# Thanks Michael!
				elif isinstance(new.knob(i), nuke.String_Knob): 
					new.knob(i).setValue("[value %s.%s]" % (original.name(), original.knob(i).name())) 

		new['selected'].setValue(False)	

	[ n['selected'].setValue(True) for n in originals ]
Exemplo n.º 30
0
 def _with_timoffset(sel):
     
     for n in sel:
         for i in sel:
             n.knob('selected').setValue(False)
         n.knob('selected').setValue(True)
         rt = nuke.createNode('TimeOffset', '', False)
         rt.knob('selected').setValue(False)
         sequencer.append(rt)
         
     for rt in sequencer:
         idx = sequencer.index(rt)
         
         if idx == 0:
             idx = idx
             rt.knob('label').setValue("Cut " + str(idx+1))
             continue
         else:
             idx = idx-1
             offset = float(nuke.value(sequencer[idx].name()+".last_frame"))+1.0
             rt.knob('selected').setValue(True)
             rt.knob('time_offset').setValue(offset)
             rt.knob('label').setValue("Cut " + str(idx+2))
             rt.knob('selected').setValue(False)
             continue
Exemplo n.º 31
0
def createCameraFromMatrix(matrixstr):
    #Takes: matrixstr as str of ' ' separated floats
    #Performs: generates camera node with matrix values:
    #Returns: node reference
    matrix = matrixstr.split(' ')[0:16]
    node = nuke.createNode('Camera')
    node['useMatrix'].setValue(True)
    node['matrix'].setValue(matrix)
    #node['far'].setValue(150.0)
    deselectAll()
    return node
Exemplo n.º 32
0
def autowriteMOV():
    loadRoot = easyRenderRoot()
    writeMagic = nuke.createNode("Write")
    writeMagic['channels'].setValue("rgba")
    writeMagic.knob('file').setValue(
        easyRenderRoot() +
        '[string range [file tail [knob root.name]] 0 6]/02 OUT/LOW/MOV/[string range [file tail [knob root.name]] 0 11 ].mov'
    )
    writeMagic.knob('colorspace').setValue(111)
    writeMagic.knob('meta_codec').setValue(4)
    writeMagic.knob('create_directories').setValue(True)
Exemplo n.º 33
0
def autowritePreRender():
    loadRoot = easyRenderRoot()
    prName = nuke.getInput('PreRender Name:', 'PreRender01')
    writeMagic = nuke.createNode("Write")
    writeMagic['channels'].setValue("rgba")
    writeMagic.knob('colorspace').setValue(12)
    writeMagic.knob('file').setValue(
        easyRenderRoot() +
        '[string range [file tail [knob root.name]] 0 6]/04 PRERENDERS/{}/{}_####.exr'
        .format(prName, prName))
    writeMagic.knob('create_directories').setValue(True)
Exemplo n.º 34
0
def createLutNode(lut):
    '''
    Create a ColorLookup node to hold lut. The values are normalised.
    args:
        lut  -  list of floating point numbers
    '''
    lutNode = nuke.createNode('ColorLookup')
    lutKnob = lutNode['lut']
    for i, y in enumerate(lut):
        x = float(i) / len(lut)
        lutKnob.setValueAt(y, x)
Exemplo n.º 35
0
    def _create_deep_read_node(self, path, sg_publish_data):
        """
        Create a read node representing the publish.

        :param path: Path to file.
        :param sg_publish_data: Shotgun data dictionary with all the standard publish fields.
        """
        import nuke

        (_, ext) = os.path.splitext(path)

        # deep files should only be EXRs
        valid_extensions = [".exr"]

        if ext.lower() not in valid_extensions:
            raise Exception("Unsupported file extension for '%s'!" % path)

        # `nuke.createNode()` will extract the format from the
        # file itself (if possible), whereas `nuke.nodes.Read()` won't. We'll
        # also check to see if there's a matching template and override the
        # frame range, but this should handle the zero config case. This will
        # also automatically extract the format and frame range for movie files.
        read_node = nuke.createNode("DeepRead")
        # this detects frame range automatically only if it is explicitly passed
        # (i.e. if the argument to fromUserText() is of the format
        # "<img_seq_path> <start>-<end>")
        read_node["file"].fromUserText(path)

        # find the sequence range if it has one:
        seq_range = self._find_sequence_range(path)

        # to fetch the nuke prefs from pipeline
        step = self._find_pipe_step(path, sg_publish_data)
        nuke_prefs = NukePreferences(step)

        for knob_name, knob_value in nuke_prefs.getKnobOverridesGenerator(step):
            if read_node.Class() in knob_name:
                knob_name = knob_name.replace(read_node.Class(), read_node.name())
                nuke.knob(knob_name, knob_value)

        if seq_range:
            # override the detected frame range.
            read_node["first"].setValue(seq_range[0])
            read_node["last"].setValue(seq_range[1])
        else:
            self.parent.logger.warning("{}: Not setting frame range.".format(read_node.name()))

        # try to fetch a proxy path using templates
        proxy_path = self._get_proxy_path(path)

        if proxy_path:
            read_node["proxy"].fromUserText(proxy_path)
        else:
            self.parent.logger.warning("{}: Not setting proxy path.".format(read_node.name()))
Exemplo n.º 36
0
def RotoBlur_Shortcut():
    y_offset = 60
    r = nuke.createNode('Roto', 'output rgba')
    y = int(r.ypos() + y_offset)
    b = nuke.nodes.Blur()
    b['size'].setValue(2)
    b['label'].setValue('Size: [value size]')
    b['xpos'].setValue(r.xpos())
    b['ypos'].setValue(y)
    b.setInput(0,r)
    b.hideControlPanel()
Exemplo n.º 37
0
def create_transform():
    # Create a Transform or TransformGeo node depending on node type
    nodes = nuke.selectedNodes()
    if not nodes:
        nuke.createNode('Transform')
        return
    unselect()
    transform_nodes = list()
    for node in nodes:
        node.setSelected(True)
        if 'render_mode' in node.knobs():
            new_node = nuke.createNode('TransformGeo')
            if new_node:
                transform_nodes.append(new_node)
        else:
            new_node = nuke.createNode('Transform')
            if new_node:
                transform_nodes.append(new_node)
        unselect()
    select(transform_nodes)
Exemplo n.º 38
0
def create_dots(side=False):
    # Create dot nodes
    nodes = nuke.selectedNodes()
    dots = list()
    for node in nodes:
        unselect()
        pos = get_pos(node)
        if not side:
            select([node])
        dot = nuke.createNode('Dot', inpanel=False)
        if side:
            set_pos(dot, pos[0] - grid[0], pos[1])
            dot.setInput(0, node)
        else:
            set_pos(dot, pos[0], pos[1] + grid[1] * 2)
        dots.append(dot)
        unselect(dot)
    select(dots)
    if not nodes:
        dot = nuke.createNode('Dot', inpanel=False)
Exemplo n.º 39
0
def create_node(node_name, read_data):
    label = "%s points" % (read_data["verts_count"])
    node = nuke.createNode("BakedPointCloud")
    node.knob("serializePoints").setValue(
        "%s %s" % (read_data["total"], read_data["points"]))
    node.knob("serializeNormals").setValue(
        "%s %s" % (read_data["total"], read_data["normals"]))
    node.knob("serializeColors").setValue(
        "%s %s" % (read_data["total"], read_data["colors"]))
    node.knob("name").setValue(node_name)
    node.knob("label").setValue(label)
Exemplo n.º 40
0
def copyCamera(srcCam):
    while srcCam is not None and srcCam.Class() == 'Dot':
        srcCam = srcCam.input(0)
    if srcCam.Class() == 'Camera':
        newCam = nuke.createNode('Camera')
        newCam.readKnobs(srcCam.writeKnobs(nuke.TO_SCRIPT))
    else:
        clearNodeSelection()
        newCam = nuke.clone(srcCam, '', False)
        newCam.setSelected(True)
    return newCam
Exemplo n.º 41
0
	def createUtilityPass(self, origin, filePath,firstFrame,lastFrame, nukeXPos, nukeSetupWidth, idx):
		
		curReadNode = nuke.createNode("Read",'file "%s" first %s last %s origfirst %s origlast %s' % (filePath,firstFrame,lastFrame,firstFrame,lastFrame),False)
		curReadNode.setYpos(0)
		curReadNode.setXpos(nukeXPos+nukeSetupWidth+500+idx*100)
		try:
			curReadNode.setXpos(curReadNode.xpos()+self.maskNodes[-1].xpos()-nukeXPos-nukeSetupWidth)
		except:
			pass

		self.utilityNodes.append(curReadNode)
Exemplo n.º 42
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 )
Exemplo n.º 43
0
	def testSetValueReturn( self ) :

		n = nuke.createNode( "ieObject" )

		k = n.knob( "object" )

		self.assertEqual( k.setValue( None ), False )
		self.assertEqual( k.setValue( IECore.IntData( 1 ) ), True )
		self.assertEqual( k.setValue( IECore.IntData( 1 ) ), False )
		self.assertEqual( k.setValue( IECore.IntData( 10 ) ), True )
		self.assertEqual( k.setValue( None ), True )
    def getColorSpace(self):
        preset = None
        for (exportPath, _preset) in self._exportTemplate.flatten():
            if "trnla_project_id" in _preset.properties():
                preset = _preset
                break

        if preset:
            """This code is mainly from FnExternalRender.createWriteNode()"""
            try:
                properties = preset.properties()
                project = hiero.core.projects()[-1]
                colourTransform = properties.get("colourspace", None)
                if colourTransform:
                    # If a non-default colour transform is set, validate that it actually exists
                    # in the current project configuration.  This check should probably be done
                    # earlier, but there's no appropriate place to do it.
                    isTransformDefault = colourTransform == "default"
                    isValidTransform = isTransformDefault or getRoleFromProperty(
                        colourTransform) in hiero.core.LUTs(project)
                    if not isValidTransform:
                        raise RuntimeError(
                            "Unable to create Write node with invalid color space: %s"
                            % colourTransform)

                    colourSpace = getColorspaceFromProperty(
                        properties["colourspace"])
                    projectsettings = project.extractSettings()
                    colourTransform = FnNukeHelpers.nukeColourTransformNameFromHiero(
                        colourSpace, projectsettings)

                projectsettings = project.extractSettings()
                if projectsettings["lutUseOCIOForExport"] is True:
                    # If the colour transform hasnt been set or if set to default,
                    # we need to mimic the default colourspace of nukes write node
                    # Using the colour
                    if colourTransform in (None, "default"):
                        colourTransform = _mapDefaultColourTransform(
                            preset, projectsettings)
                if colourTransform is not None:
                    # Little hack to get the name of the colourspace in case default was selected.
                    w = nuke.createNode('Write')
                    colorSpaces = w.knob('colorspace').values()
                    nuke.delete(w)
                    tabColourTransform = '\t' + colourTransform
                    for cs in colorSpaces:
                        if tabColourTransform in cs:
                            _cs = cs.split('\t', 1)[1]
                            colourTransform = getColorspaceFromProperty(_cs)
                            break
                    return colourTransform
            except Exception as e:
                return "None"
        return "None"
Exemplo n.º 45
0
def TransformFromTracker():
    for a in nuke.selectedNodes():
        if a.Class().find("Tracker") > -1:
            n = nuke.createNode("Transform", inpanel=False)
            link = "parent." + a.knob('name').getValue() + "."
            n.knob('translate').setExpression(link + "translate")
            n.knob('rotate').setExpression(link + "rotate")
            n.knob('scale').setExpression(link + "scale")
            n.knob('center').setExpression(link + "center")
            for j in range(n.inputs()):
                n.setInput(j, None)
Exemplo n.º 46
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()
Exemplo n.º 47
0
def bm_MultiIBK():

    # If a node is selected, and nodes are created, for some reason the manual setting
    # of xpos and ypos screws up. So we have to check if a node is selected, create a dot,
    # then manually set it's xpos and ypos to be something sensible...
    try:
        n = nuke.selectedNode()
        n.setSelected(False)

        dot = nuke.createNode('Dot')
        dot.knob('xpos').setValue(n.knob('xpos').value() + 34)
        dot.knob('ypos').setValue(n.knob('ypos').value() + 100)
        dot.setInput(0, n)

    # But if no node is selected, then we just create the dot.
    except:
        dot = nuke.createNode('Dot')

    # Create the first IBKColour and position it down and to the right in the Node Graph.
    colour = nuke.createNode('IBKColourV3', 'screen_type green')
    colour.knob('xpos').setValue(dot.knob('xpos').value() + 100)
    colour.knob('ypos').setValue(dot.knob('ypos').value() + 100)

    # Create 6 more IBKColour nodes with expression links which set all the knobs' values to
    # the same thing as their input node's knobs.
    # Positioning in the node graph is automatic as each copy of the node will be selected upon creation.
    for i in range(0, 6):

        colour_linked = nuke.createNode('IBKColourV3', 'screen_type green')
        colour_linked.knob('Size').setExpression('input.Size')
        colour_linked.knob('off').setExpression('input.off')
        colour_linked.knob('mult').setExpression('input.mult')
        colour_linked.knob('erode').setExpression('input.erode')

    # Create the IBKGizmo node, set it's position in the Node Graph, then set the 'fg' and 'c' inputs to
    # the Dot and the last IBKColour node respectively.
    gizmo = nuke.createNode('IBKGizmoV3', 'st C-green')
    gizmo.knob('xpos').setValue(dot.knob('xpos').value() - 34)
    gizmo.knob('ypos').setValue(dot.knob('ypos').value() + 325)
    gizmo.setInput(0, dot)
    gizmo.setInput(1, colour_linked)
Exemplo n.º 48
0
    def addBurnIns(self, oldMovPath, newMovPath):
        FlixNuke().clearScript()

        readNode = nuke.createNode(
            "Read", "file {%s}" % self.rePath.localize(oldMovPath))
        firstframe = int(readNode["origfirst"].getValue())
        lastframe = int(readNode["origlast"].getValue())

        textNode = nuke.createNode("Text2")
        textNode.setInput(0, readNode)
        textNode["color"].setValue(0)
        textNode["message"].setValue("Hello World!")
        textNode["xjustify"].setValue("left")
        textNode["yjustify"].setValue("bottom")
        writeNode = nuke.createNode("Write")
        writeNode["file"].setValue(self.rePath.localize(newMovPath))
        writeNode.setInput(0, textNode)

        nuke.execute(writeNode["name"].getValue(), firstframe, lastframe, 1)
        nuke.scriptSave(self.rePath.localize(newMovPath.replace(".mov",
                                                                ".nk")))
Exemplo n.º 49
0
def create_child(parent_node):

    parentName = parent_node.knob('name').value()
    parentLabel = parent_node.knob('parentLabel').value()
    parentXpos = parent_node.knob('xpos').value()
    parentYpos = parent_node.knob('ypos').value()

    childName = parentLabel + '_' + str(random.randint(0, 1000000))
    prevChildList = parent_node.knob('childList').value()
    newChildList = prevChildList + childName + '\n'
    parent_node.knob('childList').setValue(newChildList)

    nukescripts.clear_selection_recursive()
    child = nuke.createNode('NoOp', inpanel=False)
    child.setInput(0, nuke.toNode(parentName))
    nuke.toNode(child['name'].value()).setSelected(True)

    child['hide_input'].setValue(
        nuke.toNode(parentName).knob('hideInputTracker').value())
    child['note_font_size'].setValue(20.0)
    child['tile_color'].setValue(3511807)
    child['note_font'].setValue('Verdana Bold Bold Bold')
    child['xpos'].setValue(parentXpos)
    child['ypos'].setValue(parentYpos + 50)
    child['name'].setValue(childName)

    childTabKnob = nuke.Tab_Knob('postalChild', 'postal child')
    child.addKnob(childTabKnob)

    parentIDKnob = nuke.String_Knob('parentID', 'parent ID', parentName)
    child.addKnob(parentIDKnob)

    parentLabelKnob = nuke.String_Knob('parentLabel', 'parent label',
                                       parentLabel)
    child.addKnob(parentLabelKnob)

    CONNECT_TO_PARENT = """
import connect_to_parent
connect_to_parent.connect_to_parent(nuke.thisNode())
"""
    CONNECT_TO_PARENT_TOOLTIP = """
Reconnects this node to its parentID. This button must be pressed to add this child to parent's list of children
	"""
    connectToParentButton = nuke.PyScript_Knob('connectToParent',
                                               'connect to parent',
                                               CONNECT_TO_PARENT)
    connectToParentButton.setFlag(0x0000000000001000)
    connectToParentButton.setTooltip(CONNECT_TO_PARENT_TOOLTIP)
    child.addKnob(connectToParentButton)

    nukescripts.clear_selection_recursive()
    nuke.toNode(child['name'].value()).setSelected(True)
    child['autolabel'].setValue("nuke.thisNode().knob('parentLabel').value()")
Exemplo n.º 50
0
def renderOut():
    if len(lista) >= 2:
        a = nuke.createNode("Write")
        a.connectInput(0, node)
        nuke.connectViewer(0, node)
        a["channels"].setValue("all")
        a["file_type"].setValue("exr")
        a.autoplace()
        renderPath()
        a["file"].setValue(newdir)
    else:
        pass
Exemplo n.º 51
0
def run():
    sel = nuke.selectedNode()
    if sel.Class() == "Write":
        read = nuke.createNode("Read")
        read.setXpos(int(sel['xpos'].getValue()))
        read.setXpos(int(sel['xpos'].getValue() + 50))
        read['file'].setValue(sel['file'].getValue())
        read['first'].setValue(int(nuke.Root()['first_frame'].getValue()))
        read['last'].setValue(int(nuke.Root()['last_frame'].getValue()))
        read['origfirst'].setValue(int(nuke.Root()['first_frame'].getValue()))
        read['origlast'].setValue(int(nuke.Root()['last_frame'].getValue()))
        read['colorspace'].setValue(int(sel['colorspace'].getValue()))
Exemplo n.º 52
0
def shuffle():
    for selected_node in nuke.selectedNodes():
        if selected_node.Class() == 'Read':
            all_channels = selected_node.channels()
            all_channels = list(set([i.split('.')[0] for i in all_channels]))
            for channel in all_channels:
                shuffle_node = nuke.createNode('Shuffle', inpanel=False)
                shuffle_node['name'].setValue(channel + '_' +
                                              selected_node['name'].getValue())
                shuffle_node['in'].setValue(channel)
                shuffle_node.setInput(0, selected_node)
                shuffle_node['postage_stamp'].setValue(1)
Exemplo n.º 53
0
def smart_shuffle():
    # Find active viewer and assign current layer
    active_viewer = nuke.activeViewer()
    if active_viewer:
        layer = active_viewer.node()['channels'].value()
    else:
        layer = 'rgba'

    # Create Shuffle Node with active layer
    shuffle_node = nuke.createNode('Shuffle', 'in {}'.format(layer))
    if layer != 'rgba':
        shuffle_node['alpha'].setValue(0)
    def importAsset(self, iAObj=None):
        resultingNode = nuke.createNode("ReadGeo2", inpanel=False)
        resultingNode['file'].setValue(
            HelpFunctions.safeString(
                nukecon.Connector.windowsFixPath(iAObj.filePath)))
        resultingNode['name'].setValue(
            HelpFunctions.safeString(iAObj.assetName))

        self.addFTab(resultingNode)
        self.setFTab(resultingNode, iAObj)

        return 'Imported geo asset'
Exemplo n.º 55
0
def declone(node):
    if node.clones() == 0:
        return
    args = node.writeKnobs(nuke.WRITE_ALL | nuke.WRITE_USER_KNOB_DEFS
                           | nuke.WRITE_NON_DEFAULT_ONLY | nuke.TO_SCRIPT)
    newnode = nuke.createNode(node.Class(), knobs=args)
    nuke.inputs(newnode, nuke.inputs(node))
    num_inputs = nuke.inputs(node)
    for i in range(num_inputs):
        newnode.setInput(i, node.input(i))
    node.setInput(0, newnode)
    nuke.delete(node)
    def importAsset(self, iAObj=None):
        '''Import asset as new node.'''
        resultingNode = nuke.createNode('Read', inpanel=False)
        resultingNode['name'].setValue(
            HelpFunctions.safeString(iAObj.assetName) + '_' +
            HelpFunctions.safeString(iAObj.componentName))

        resultingNode['file'].fromUserText(
            HelpFunctions.safeString(iAObj.filePath))

        self.addFTab(resultingNode)
        self.setFTab(resultingNode, iAObj)
Exemplo n.º 57
0
def _useAsInputProcess():
  n = nuke.selectedNode()
  [i['selected'].setValue(False) for i in nuke.allNodes()]
  # FIXME: these two calls should have the arguments in the same order, or even better change the node bindings so they can go.
  if nuke.dependencies([n], nuke.INPUTS | nuke.HIDDEN_INPUTS) or nuke.dependentNodes(nuke.INPUTS | nuke.HIDDEN_INPUTS, [n]):
    m = nuke.createNode(n.Class())
  else:
    m = n
  if m is not n: _copyKnobsFromScriptToScript(n, m)
  viewer = nuke.activeViewer().node()
  viewer['input_process'].setValue(True)
  viewer['input_process_node'].setValue(m.name())
Exemplo n.º 58
0
def metadata_from_path(path):

    script = ""
    for column in get_columns(path):
        script += "{set "
        script += "\"source/{0}\" \"{1}\"".format(column[0], column[1])
        script += "}\n"

    node = nuke.createNode("ModifyMetaData")
    node.knob("metadata").fromScript(script)

    return node
Exemplo n.º 59
0
def unPremultWrapper():

    n = nuke.selectedNodes()

    if len(n) > 0:
        __setSelectState(n, False)
        ln = n[len(n) - 1]
        ln.setSelected(True)
        p = nuke.createNode('Premult')
        ln.setSelected(False)
        p.setSelected(False)

        fn = n[0]
        try:
            d = fn.dependencies()[0]
            d.setSelected(True)
            nuke.createNode('Unpremult')
        except:
            pass
    else:
        p = nuke.createNode('Premult')
Exemplo n.º 60
0
def create_read_from_write():
    sel = nuke.selectedNode()
    if sel.Class() == "Write":
        read = nuke.createNode("Read")
        read.setXpos(int(sel["xpos"].getValue()))
        read.setYpos(int(sel["ypos"].getValue() + 150))
        read["file"].setValue(sel["file"].getValue())
        read["first"].setValue(int(nuke.Root()["first_frame"].getValue()))
        read["last"].setValue(int(nuke.Root()["last_frame"].getValue()))
        read["origfirst"].setValue(int(nuke.Root()["first_frame"].getValue()))
        read["origlast"].setValue(int(nuke.Root()["last_frame"].getValue()))
        read["colorspace"].setValue(int(sel["colorspace"].getValue()))