Ejemplo n.º 1
0
def listbookmarks():
    
    bm=[]
    zoomBy=1

    #find bookmark nodes
    for n in nuke.allNodes():
        n['selected'].setValue( False )
        if n['icon'].value() == 'bookmark.png':
            n['selected'].setValue( True )      #select nodes for clarity
            bmLabel=nuke.selectedNode()['label'].value() 

            if bmLabel:
                bm_name='"'+bmLabel+'"' # '"'<-lets it list correctly
            else:
                bm_name='"'+n.name()+'"' # '"'<-allows it to be sorted correctly with above
            bm.append(bm_name)
    if 0==len(bm):
        nuke.message('no bookmarks found')
    else:
        bookmarkList=str(sorted(bm))  

        #clean up list name
        pattern = re.compile('[\[\]\']')
        bookmarkList = pattern.sub('', bookmarkList)
        pattern = re.compile('[\,]')
        bookmarkList = pattern.sub(' ', bookmarkList)

           
        #let user choose bookmark
        panel = nuke.Panel ('BookMarks',200)     
        panel.addEnumerationPulldown('go to',bookmarkList)
        panel.addSingleLineInput('zoom',zoomBy)
        panel.addBooleanCheckBox('also open node', False)          
        panel.addButton("Cancel")
        panel.addButton("Zoom to")
        panel.addButton("Open")
        result=panel.show()

        if result:
            goto= panel.value('go to')
            zoomf= panel.value('zoom')
            alwaysOpen= panel.value('also open node')

            #select only relevent node
            for n in nuke.allNodes():
                if goto == n.name() or goto == n['label'].value():
                    n['selected'].setValue( True )
                else:
                    n['selected'].setValue( False )

            #set nuke to highlight chosen node, get xy pos and zoom into area and open if selected.
            if result ==1:                  
                nuke.zoom(float(zoomf),(nuke.selectedNode().xpos(),nuke.selectedNode().ypos()))
                if alwaysOpen:
                    nuke.show(nuke.selectedNode())
            elif result ==2:                  
                nuke.show(nuke.selectedNode())
            else:
                pass
Ejemplo n.º 2
0
def convert_to_dolly():
    """
    Will extract the "translate" channel of a Camera and put it into
    an Axis node. The rotating Camera will be parented underneath the Axis.
    After that you can parent nodal elements (skydomes etc.) under the Axis.
    """
    if not ensure_camera_selected(nuke.selectedNode()):
        return
    
    cam = nuke.selectedNode()

    dolly = nuke.nodes.Axis()
    dolly.setName("DollyMount")

    # Put the dolly next to the camera in the DAG
    ONE_NODE_WIDTH = 82
    dolly['xpos'].setValue(cam['xpos'].getValue() + ONE_NODE_WIDTH)
    dolly['ypos'].setValue(cam['ypos'].getValue())

    # Move the "translate" knob values into the dolly axis.
    # Shortcut way to copy multiparameter knob animations
    # http://forums.thefoundry.co.uk/phpBB2/viewtopic.php?t=4311
    dolly['translate'].fromScript(cam['translate'].toScript()) 
    
    make_camera_nodal(cam)
    cam.setInput(0, dolly)
Ejemplo n.º 3
0
def nukeSelectedNode():

    sn = nuke.selectedNode()
    snx = nuke.selectedNode().xpos()
    sny = nuke.selectedNode().ypos()
    allValues = [[snx, sny]]
    return allValues
Ejemplo n.º 4
0
def convert_to_dolly():
	if not ensure_camera_selected(nuke.selectedNode()):
		return
	
	cam = nuke.selectedNode()

	dolly = nuke.nodes.Axis()
	dolly.setName("DollyMount")

	# Put the dolly next to the camera in the DAG
	ONE_NODE_WIDTH = 82
	dolly['xpos'].setValue(cam['xpos'].getValue() + ONE_NODE_WIDTH)
	dolly['ypos'].setValue(cam['ypos'].getValue())

	# Move the "translate" knob values into the dolly axis.
	# Shortcut way to copy multiparameter knob animations
	# http://forums.thefoundry.co.uk/phpBB2/viewtopic.php?t=4311
	dolly['translate'].fromScript(cam['translate'].toScript()) 

	# Reset the translations of the camera to 0
	cam['translate'].fromScript("0 0 0")
	cam.setInput(0, dolly)

	# Note that the cam is nodal
	cam['label'].setValue(cam['label'].getValue() + " (nodal)")
Ejemplo n.º 5
0
def precomp_write():

	first_node = nuke.selectedNode()

	read_node = nuke.selectedNode().dependencies()
	nodes_list = []

	while read_node:
	    read_node = read_node[0].dependencies()
	    nodes_list.append(read_node)

	read_node = nodes_list[-2][0]
	read_path = read_node.knob("file").value()
	file_name = read_path.split("/")[-1].split(".")[0]

	file_path = read_path.split("/")[:-1]
	file_path = "/".join(file_path)
	write_path = "{0}/precomp/{1}_precomp.%04d.jpg".format(file_path, file_name)

	write_node = nuke.nodes.Write()
	write_node.setInput(0, first_node)
	write_node.setSelected(True)
	write_node.knob("file").setValue(write_path)
	write_node.knob("file_type").setValue("jpeg")
	#write_node.knob("channels").setValue("rgba")
	write_node.knob("_jpeg_quality").setValue(100)
	write_node.knob("beforeRender").setValue("import os\nif not os.path.isdir(os.path.dirname(nuke.thisNode()[\'file\'].evaluate())):\n\tos.makedirs(os.path.dirname(nuke.thisNode()[\'file\'].evaluate()))")

	nuke.connectViewer(0,write_node)
Ejemplo n.º 6
0
def create_projector_panel():
    if not ensure_camera_selected(nuke.selectedNode()):
        return
    
    p = nukescripts.panels.PythonPanel("Create a projector")
    
    k = nuke.Boolean_Knob("link", "Link the projector camera to the original")
    k.setFlag(nuke.STARTLINE)
    k.setTooltip("This will create a live setup that will update when the camera keyframes change")
    p.addKnob(k)
    
    k = nuke.Boolean_Knob("create_shader_tree", "Create shader tree (FrameHold + project3d)")
    k.setFlag(nuke.STARTLINE)
    k.setTooltip("will also create a FrameHold and a Project3D to spare even more clicks")
    p.addKnob(k)
    
    result = p.showModalDialog()    
    if result == 0:
        return # Canceled

    # The API called "get value of the field by providing it's UI label" earns the
    # mark of the most f****d up disgusting crap engineering ever (tm)
    do_link = p.knobs()["link"].value()
    do_tree = p.knobs()["create_shader_tree"].value()
    if do_tree:
        create_camera_at_and_shader(nuke.selectedNode(), nuke.frame(), do_link)
    else:
        create_camera_at(nuke.selectedNode(), nuke.frame(), do_link)
Ejemplo n.º 7
0
def create_projection_alley_panel():
    if not ensure_camera_selected(nuke.selectedNode()):
        return

    p = nukescripts.panels.PythonPanel("Create projection alley")

    p.addKnob(nuke.Int_Knob("start", "First frame to project"))
    p.knobs()["start"].setValue(int(nuke.root()["first_frame"].getValue()))

    p.addKnob(nuke.Int_Knob("finish", "Last frame to project"))
    p.knobs()["finish"].setValue(int(nuke.root()["last_frame"].getValue()))

    p.addKnob(nuke.Int_Knob("step", "Step (project every N frames)"))
    p.knobs()["step"].setValue(int(nuke.root().fps()))

    k = nuke.Boolean_Knob("backwards", "Layer last frame to first frame")
    k.setFlag(nuke.STARTLINE)
    k.setTooltip(
        "Projected frames are layered first to last (last frame comes on top). When checked the first frames will come out on top"
    )

    p.addKnob(k)

    k = nuke.Boolean_Knob("crop", "Crop the projections to bbox")
    k.setFlag(nuke.STARTLINE)
    k.setTooltip("Use this with caution if you use lens distortion that stretches outside of the format")
    p.addKnob(k)

    k = nuke.Boolean_Knob("link", "Create linked cameras")
    k.setTooltip("Creates a linked multicam rig that will update if you change the camera path")
    k.setFlag(nuke.STARTLINE)
    p.addKnob(k)

    result = p.showModalDialog()

    if result == 0:
        return  # Canceled

    start = p.knobs()["start"].value()
    finish = p.knobs()["finish"].value()
    istep = p.knobs()["step"].value()

    frame_numbers = list(range(start, finish, istep))

    link = False
    crop = False
    if finish not in frame_numbers:
        frame_numbers.append(finish)  # If the step is higher and we somehow to not get the last frame for sure

    if p.knobs()["backwards"].value():
        frame_numbers.reverse()
    if p.knobs()["crop"].value():
        crop = True
    if p.knobs()["link"].value():
        link = True

    group = create_projection_alley(nuke.selectedNode(), frame_numbers, crop, link)
    group["label"].setValue("Cam prj f: %d to: %d every: %d" % (start, finish, istep))
    group.setName("ProjectionAlley")
Ejemplo n.º 8
0
Archivo: Tools.py Proyecto: Ahuge/Nuke
def CreateBackdrop():
	import random
	for i in nuke.selectedNodes():
		if i.Class() == "BackdropNode":
			i['tile_color'].setValue(int(random.randint(100000,699999999)))
			break
		else:
				FaceBook = nuke.getInput('Name?')
				autoBackdropCustom()
				nuke.selectedNode()['label'].setValue(FaceBook)
				break
Ejemplo n.º 9
0
def  FreezeFrom():
  for n in nuke.selectedNodes():

    n.knob('from1').fromScript(n.knob('to1').toScript())
    n.knob('from2').fromScript(n.knob('to2').toScript())
    n.knob('from3').fromScript(n.knob('to3').toScript())
    n.knob('from4').fromScript(n.knob('to4').toScript())
    nuke.Knob.clearAnimated(nuke.selectedNode().knob('from1'))
    nuke.Knob.clearAnimated(nuke.selectedNode().knob('from2'))
    nuke.Knob.clearAnimated(nuke.selectedNode().knob('from3'))
    nuke.Knob.clearAnimated(nuke.selectedNode().knob('from4'))
Ejemplo n.º 10
0
Archivo: Tools.py Proyecto: Ahuge/Nuke
def CreateBackdrop():
	import random
	for i in nuke.selectedNodes():
		if i.Class() == "BackdropNode":
			fColour = [random.random(), random.random(), random.random(), random.random()]
			hColour = int('%02x%02x%02x%02x' % (fColour[0]*255,fColour[1]*255,fColour[2]*255,fColour[3]),16) 
			i['tile_color'].setValue(hColour)
			break
		else:
				FaceBook = nuke.getInput('Name?')
				autoBackdropCustom()
				nuke.selectedNode()['label'].setValue(FaceBook)
				break
Ejemplo n.º 11
0
def mergeThis():
    import nuke
    try:
        if 'shadow_override' in nuke.selectedNode().knobs(
        ) or 'Camera' in nuke.selectedNode().Class(
        ) or 'render_mode' in nuke.selectedNode().knobs(
        ) or 'Light' in nuke.selectedNode().Class(
        ) or 'DisplaceGeo' in nuke.selectedNode().Class(
        ) or 'Axis' in nuke.selectedNode().Class():
            if len(nuke.selectedNodes()) == 1:
                return nuke.createNode("MergeGeo")
            else:
                smMerge("MergeGeo")

        elif 'MergeMat' in nuke.selectedNode().Class(
        ) or 'project_on' in nuke.selectedNode().knobs(
        ) or 'Mat' in nuke.selectedNode()['name'].value():
            if len(nuke.selectedNodes()) == 1:
                return nuke.createNode("MergeMat")
            else:
                smMerge("MergeMat")
        elif 'Deep' in nuke.selectedNode().Class(
        ) and "DeepHoldout" not in nuke.selectedNode()['name'].value(
        ) and "DeepToImage" not in nuke.selectedNode()['name'].value():
            if len(nuke.selectedNodes()) == 1:
                return nuke.createNode("DeepMerge")
            else:
                smMerge("DeepMerge")
        else:
            raise ValueError
    except:
        if len(nuke.selectedNodes()) <= 1:
            return nuke.createNode("Merge2")

        else:
            smMerge("Merge2")
Ejemplo n.º 12
0
def printKnobs():
    print '\n'.join(sorted(nuke.selectedNode().knobs()))
Ejemplo n.º 13
0
def SB_autopostage():
	s = nuke.selectedNode()
	# print s
	input_label = '[value this.input0.label]'
	print(input_label)
	sname = s.name()
	# print sname
	p = nuke.nodes.PostageStamp
	# print p
	# s['note_font_color'].setValue(00fffa

	p(name='PosStmp_' + s.name(), label=input_label, selected=True, note_font_color=(0, 1, 1), hide_input=True,
	  postage_stamp=True, tile_color=(0, 1, 1)).setInput(0, s)

	# n['label'].setValue(txt)

	#### IF READ NODE

	def postNamer():
		for i in nuke.selectedNodes('PostageStamp'):
			firstInput = i.input(0)
			if firstInput.Class() == 'Read':
				Fname = nuke.filename(firstInput)
				Fname = os.path.basename(Fname)
				Fname = Fname.split('.')[0]
				i['label'].setValue(Fname)
			elif firstInput.Class() != 'Read':
				pass

	postNamer()

	###copy label
	def copy_label():
		p = nuke.selectedNode()
		firstInput = p.input(0)
		if firstInput.Class() != 'Read':
			d = nuke.selectedNode().name()
			l = p['label'].getValue()
			txt = nuke.getInput('Change label', 'SB_POS_STMP_')
			print
			if l == "":
				for n in nuke.selectedNodes():
					n['label'].setValue(txt)
				else:
					n['label'].setValue(l + txt)
			if firstInput.Class() == 'Blur':
				p['label'].setValue('Blur size= [value this.input0.size]' + "__" + txt)
			if firstInput.Class() == 'Merge2':
				p['label'].setValue('Merge Mix= [value this.input0.mix]' + "__" + txt)
			if firstInput.Class() == 'Switch':
				p['label'].setValue('Switch input= [value this.input0.which]' + "__" + txt)
			if firstInput.Class() == 'TimeOffset':
				p['label'].setValue('TimeOffset= [value this.input0.time_offset]' + "__" + txt)
			if firstInput.Class() == 'Defocus':
				p['label'].setValue('defocus amount= [value this.input0.defocus]' + "__" + txt)
			if firstInput.Class() == 'AdjBBox':
				p['label'].setValue('amount= [value this.input0.numpixels]' + "__" + txt)
			if firstInput.Class() == 'Tracker4':
				p['label'].setValue('amount= [value this.input0.transform]' + "__" + txt)
			if firstInput.Class() == 'Reformat':
				p['label'].setValue('reformat= [value this.input0.format]' + "__" + txt)

	copy_label()

	###### SET COLOR######
	col = nuke.getColor()
	# h = inverse col
	if col:
		for n in nuke.selectedNodes():
			n['tile_color'].setValue(col)
			n['gl_color'].setValue(col)

	# def code():
	#  for i in nuke.selectedNodes:
	#      firstInput = i.input(0)
	#      xC = firstInput.xpos() + firstInput.screenWidth()/2
	#     yC = firstInput.ypos() + firstInput.screenHeight()/2
	#      nuke.zoom( 3, [ xC, yC ])'''

	def findPapa():
		for n in nuke.selectedNodes('PostageStamp'):
			m = nuke.PyScript_Knob("Papa", "Papa", "SB_button.code()")
			n.addKnob(m)
	findPapa()
Ejemplo n.º 14
0
def saveImage ():
    ### creating panel and assign buttons
    ef = nuke.Panel("saveImage As......  by satheesh-r", 420)
    ef.addFilenameSearch("Save Image As:\nchoose path & file type", "")
    ef.addButton("cancel")
    ef.addEnumerationPulldown('channels', "rgb rgba all")

    ef.addEnumerationPulldown('Exr data type', "16bit-half 32bit-float")
    ef.addButton("ok")
    window=ef.show()
    exrtype = ef.value('Exr data type')
    channel = ef.value('channels')
    path = ef.value("Save Image As:\nchoose path & file type")
    fileType = path.split('.')[-1]
    if window == 0 :
        return

    ### getting path from user input
    if path == "":
        nuke.message('no file path selected ')
    if path == "":
        return

    ### getting active node
    curViewer = nuke.activeViewer()
    curNode = curViewer.node()
    acticeVinput = curViewer.activeInput()
    curN = curNode.input(acticeVinput)

    ### creating temp write
    w = nuke.createNode("Write")
    w.setName("tempWrite")
    w.setInput(0, curN)
    w['file'].setValue(path)

    ### if file type is jpg
    if fileType == 'jpg' :
        w['_jpeg_sub_sampling'].setValue(2)
        w['_jpeg_quality'].setValue(1)

    ### if file type is exr
    if fileType == 'exr' :
        w['datatype'].setValue(exrtype)
        w['compression'].setValue(2)
        w['metadata'].setValue(0)

    if channel == 'rgba' :
        w['channels'].setValue('rgba')

    if channel == 'all' :
        w['channels'].setValue('all')

    ### setting current frame for render
    result = nuke.frame()
    if result =="":
      result = result

    ### execute write node
    nuke.execute(nuke.selectedNode(), (int(result)), result)
    name = w.knob('file').value()
    nukescripts.node_delete(popupOnError=True)

    ### create Read node
    r = nuke.createNode("Read")
    r['file'].setValue(name)
    result = nuke.frame()
    r['first'].setValue(int(result))
    r['last'].setValue(int(result))
    r['xpos'].setValue( 200 )

    if fileType == "":
        return
Ejemplo n.º 15
0
def inn():
	import nuke
	n=nuke.selectedNode()
	n['operation'].setValue('mask')
	n['bbox'].setValue('A')
Ejemplo n.º 16
0
def bakeGroup(group):
    '''
    Make a copy of the not massive group
    Remove sutff inside the group we don't need
    Remove knobs we don't keed
    Bake the expressions in the group
    '''

    if not nuke.ask(
            'Are you sure you want to bake? This may take a long time...\n\n1 minute per 100 cards is normal.'
    ):
        return

    with group:
        with nuke.thisParent():
            for n in nuke.selectedNodes():
                n.setSelected(False)

            # change temp dir if needed
            # defaulting to nuke's temp dir, not sure how kosher this is
            tmpDirRoot = os.environ.get('NUKE_TEMP_DIR')

            # give cloned node unique filename so that nuke won't use a cached version
            groupFileBase = str(uuid.uuid4())
            tmpDir = '%s/CrowdControl' % (tmpDirRoot)

            try:
                os.mkdir(tmpDir)
            except:
                pass
            tmpPath = '%s/%s.nk' % (tmpDir, groupFileBase)

            group.setSelected(True)
            nuke.nodeCopy(tmpPath)

            for n in nuke.selectedNodes():
                n.setSelected(False)

            nuke.nodePaste(tmpPath)
            newGroup = nuke.selectedNode()

            #remove callbacks
            newGroup.knob('knobChanged').setValue('')
            newGroup.knob('onCreate').setValue('')

            #link up the inputs
            for i in range(group.inputs()):
                inputNode = group.input(i)
                if inputNode is not None:
                    newGroup.setInput(i, inputNode)

            #Bake the group internals
            cards = []
            for n in newGroup.nodes():
                if n.Class() == 'Card':
                    cards.append(n)
            bakeSelectedNodes(newGroup, set(cards))
            keepSceneAndRemoveCrowdGeneratingNodes(newGroup)

            #Rename
            newGroupName = '%s_baked' % (group.name())
            newGroup.setName(newGroupName)

            #disable the dynamic knobs
            knobsToKeep = []
            knobsToKeep.append(newGroup['versionInfo'])

            newGroup['displayAOVs'].setValue(True)
            newGroup['displayPercentage'].setValue(100)

            values = []
            for key in newGroup.knobs().keys():
                if newGroup.knob(key) not in knobsToKeep:
                    try:
                        newGroup.knob(key).setEnabled(False)
                    except:
                        #not a user knob
                        pass
            versionInfo = newGroup['versionInfo'].value()
            versionInfo = versionInfo.replace('\'s', '\'s baked with')
            newGroup['versionInfo'].setValue(versionInfo)

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

            # position the baked groupp set off from original group
            newGroup.setXpos(int(group.xpos() + gridWidth))
            newGroup.setYpos(int(group.ypos() + gridHeight * 2))

            bakeTileColor(newGroup)
Ejemplo n.º 17
0
    def getData():
        # Gets selected node or not
        try:
            global n
            n = nuke.selectedNode()
        except:
            nuke.message('Select a node.')
            return

        rgbaSolo = True
        for channel in n.channels():
            if 'rgba' not in channel:
                rgbaSolo = False
                break

        if rgbaSolo:
            msg = 'There is only the rgba channel on this node.'
            nuke.message(msg)
            return
        else:
            global p
            # if all good, build and launches the panel
            p = shuffleChannels(n)

        # Returns the layers list
        layers = p.returnLayers()

        # Changes panel dimensions
        windowHeight = len(layers)*20+165
        if windowHeight > 1000:
            windowHeight = 1000
        p.setMinimumSize(600, windowHeight)
        readPrefsFile(p)
        refreshPresetsMenu()

        # Launches the panel
        thePanel = p.showModalDialog()

        if thePanel is None or thePanel is False:
            return

        # Beyond this point all happens after the panel has been closed
        # Creation of the prefs variable
        prefs = {'remove': p.remove.value(),
                 'grade': p.grade.value(),
                 'noShuffLabel': p.noShuffLabel.value(),
                 'separation': p.separation.value(),
                 'shuffLayersColor': p.shuffLayersColor.value(),
                 'bdrop': p.bdrop.value(),
                 'bdropColor': p.bdropColor.value(),
                 'autocrop': p.autocrop.value(),
                 'postage': p.postage.value()}

        # Writes the preferences file
        writePrefsFile(p, str(prefs))
        # Here I collect what layers have been selected
        layerList = []
        for i in range(len(layers)):
            gate = p.listLayers[i].value()
            if gate is True:
                layerList.append(layers[i])

        # Here it will create a node tree if some layers have been selected
        if len(layerList) > 0:
            buildTree(layerList, prefs)
        else:
            return
Ejemplo n.º 18
0
def whatClass():
    try:
        node = nuke.selectedNode()
        nuke.message('Node Class is:\n'+ node.Class() )
    except:
        nuke.message('Please select a node')
Ejemplo n.º 19
0
import nuke

root=nuke.root()
size=root.format().r()

frame=nuke.frame()
nframe=frame+1
pframe=frame-1
sel=nuke.selectedNode()
cKnob=sel['curves']
selShapes=cKnob.getSelected()

def break(direction):
	for s in selShapes:
	    A=s.getAttributes()
	    A.set(frame,'opc',0)
	    if direction==forward:
			A.set(pframe,'opc',1)
		if direction==backward:
	    	A.set(nframe,'opc',1)

	    T=s.getTransform()
	    T.addTranslationKey(frame,0,0,0)
	    T.addTranslationKey(pframe,size,0,0)
	return


'''
def breakB():
	for s in selShapes:
	    A=s.getAttributes()
Ejemplo n.º 20
0
def bakeCamera():
    ver=str(nuke.NUKE_VERSION_MAJOR)+str(nuke.NUKE_VERSION_MINOR)
    if int(ver) < 61:
        nuke.message("This script works only withe Nuke 6.1 and higher")
        return
 
    if len(nuke.selectedNodes()) != 1:
        nuke.message("Select Camera Node")
        return
 
    n=nuke.selectedNode()
    if n.Class() != "Camera2":
        nuke.message("No Camera selected")
        return
 
    firstFrame = int(nuke.numvalue('root.first_frame'))
    lastFrame = int(nuke.numvalue('root.last_frame'))
    step = 1
    _range = str(nuke.FrameRange(firstFrame,lastFrame,step))
    r = nuke.getInput('Enter Frame Range:', _range)
 
    bakeFocal = False
    bakeHaperture = False
    bakeVaperture = False
 
 
    k = n['world_matrix']
 
    newCam = nuke.createNode("Camera2")
    newCam.setInput(0, None)
    newCam['rotate'].setAnimated()
    newCam['translate'].setAnimated()
 
    oldFocal = n['focal']
    if oldFocal.isAnimated() and not (oldFocal.animation(0).constant()):
        newCam['focal'].setAnimated()
        bakeFocal = True
    else:
        newCam['focal'].setValue(oldFocal.value())
 
    oldHaperture = n['haperture']
    if oldHaperture.isAnimated() and not (oldHaperture.animation(0).constant()):
        newCam['haperture'].setAnimated()
        bakeHaperture = True
    else:
        newCam['haperture'].setValue(oldHaperture.value())
 
    oldVaperture = n['vaperture']
    if oldVaperture.isAnimated() and not (oldVaperture.animation(0).constant()):
        newCam['vaperture'].setAnimated()
        bakeVaperture = True
    else:
        newCam['vaperture'].setValue(oldVaperture.value())
 
    newCam['win_translate'].setValue(n['win_translate'].value())
    newCam['win_scale'].setValue(n['win_scale'].value())
 
    for x in nuke.FrameRange(r):
        m = nuke.math.Matrix4()
        for y in range(k.height()):
            for z in range(k.width()):
                m[z+(y*k.width())] = k.getValueAt(x, (y+(z*k.width())))
 
        rotM = nuke.math.Matrix4(m)
        rotM.rotationOnly() 
        rot = rotM.rotationsZXY()
 
        newCam['rotate'].setValueAt(math.degrees(rot[0]), x, 0)
        newCam['rotate'].setValueAt(math.degrees(rot[1]), x, 1)
        newCam['rotate'].setValueAt(math.degrees(rot[2]), x, 2)
        newCam['translate'].setValueAt(k.getValueAt(x, 3), x, 0)
        newCam['translate'].setValueAt(k.getValueAt(x, 7), x, 1)
        newCam['translate'].setValueAt(k.getValueAt(x, 11), x, 2)
 
        if bakeFocal:
            newCam['focal'].setValueAt(oldFocal.getValueAt(x), x)
        if bakeHaperture:
            newCam['haperture'].setValueAt(oldHaperture.getValueAt(x), x)
        if bakeVaperture:
            newCam['vaperture'].setValueAt(oldVaperture.getValueAt(x), x)
Ejemplo n.º 21
0
def DotCamConnect():

    color_red = int('%02x%02x%02x%02x' % (1 * 255, 0 * 255, 0 * 255, 0 * 255),
                    16)
    color_white = int(
        '%02x%02x%02x%02x' % (1 * 255, 1 * 255, 1 * 255, 1 * 255), 16)

    # Find All the Camera nodes
    node_ls_cam = [n.name() for n in nuke.allNodes('Camera2')]
    node_ls_cam.sort()

    # Set Connect Function OR setting Dot Node Function
    def setDotNode(d, node_sel_cam):

        d['label'].setValue("\n%s" % (node_sel_cam))
        d['note_font'].setValue('bold')
        d['note_font_size'].setValue(24)
        d['note_font_color'].setValue(color_white)
        d['tile_color'].setValue(color_red)
        d['hide_input'].setValue(True)
        d.setInput(0, nuke.toNode(node_sel_cam))

        # Add Show Panel Knob
        cmd_ppanel = "n=nuke.thisNode()\ntry:\n\tn.input(0).showControlPanel(forceFloat=n.knob('isFloat').value())\nexcept:\n\tpass"
        cmd_orig = "origNode = nuke.thisNode().input(0);\
						origXpos = origNode.xpos();\
						origYpos = origNode.ypos();\
						nuke.zoom(2, [origXpos,origYpos]);\
						nuke.thisNode()['selected'].setValue(False);\
						origNode['selected'].setValue(True);\
						nuke.show(origNode)"

        t_tab = nuke.Tab_Knob('t_user', "DotCamConnect")
        k_showPanel = nuke.PyScript_Knob('ppanel', "Show Input Property Panel",
                                         cmd_ppanel)
        k_float = nuke.Boolean_Knob('isFloat', "Floating Panel", True)
        k_showCam = nuke.PyScript_Knob('orig', "Show Camera Node", cmd_orig)

        k_float.clearFlag(nuke.STARTLINE)
        k_float.setFlag(nuke.STARTLINE)

        d.addKnob(t_tab)
        d.addKnob(k_showPanel)
        d.addKnob(k_float)
        d.addKnob(k_showCam)

        print "%s -> %s" % (d.name(), node_sel_cam)

    # If there is a camera selected
    if len(nuke.selectedNodes('Camera2')) > 0:

        for c in nuke.selectedNodes('Camera2'):

            nuke.selectedNode()['selected'].setValue(False)
            node_create_dot = nuke.createNode('Dot', inpanel=False)

            node_create_dot['xpos'].setValue(c['xpos'].value() + 100)
            node_create_dot['ypos'].setValue(c['ypos'].value() + 100)

            setDotNode(node_create_dot, c.name())

    # If there isn't a camera selected
    else:

        if len(node_ls_cam) > 1:
            '''prompt to select which camera to connect'''

            p = nuke.Panel('Select A Camera Node to Connect')
            p.addEnumerationPulldown('Cam to Connect', ' '.join(node_ls_cam))
            p.addButton('Cancel')
            p.addButton('Connect!')

            if p.show():

                node_sel_cam = p.value('Cam to Connect')

                # Detect if it's a selection or just create a Dot
                if len(nuke.selectedNodes('Dot')) > 0:
                    node_ls_dot = nuke.selectedNodes('Dot')

                    for d in node_ls_dot:
                        setDotNode(d, node_sel_cam)

                else:
                    node_create_dot = nuke.createNode('Dot', inpanel=False)

                    setDotNode(node_create_dot, node_sel_cam)

        elif len(node_ls_cam) == 1:
            '''connect the only camera in the script'''

            node_create_dot = nuke.createNode('Dot', inpanel=False)
            setDotNode(node_create_dot, node_ls_cam[0])
Ejemplo n.º 22
0
    """
    if node.knob('file'):
        file_value = node['file'].value()
        directory_name = os.path.dirname(file_value)
        directory_list = os.listdir(directory_name)
        file_name = os.path.basename(file_value)
        file_name = os.path.splitext(file_name)[0]
        file_name = file_name.split('%')
        print file_name[0]
        print ( r'\.' + file_value.split('.')[1])
        pattern = '({0})(\d+)(\w+)?({1})'.format(
                                file_name[0],
                                ( r'\.' + file_value.split('.')[1])
                                )

        regx = re.compile(pattern)
        sq = []
        for f in directory_list:
            if re.search(regx,f):
                search = re.search(regx,f).groups()
                print search
                first, num, mid, last = search
                sq.append((first, num, last))
        sq.sort(key=operator.itemgetter(1))
    
    else:
        return None

if __name__ == "__main__":
    file_sequence(nuke.selectedNode())
def AutoProjectSettings():

    print
    print('.............................')
    print('... Starting Auto Project ...')
    print('.............................')

    #######################
    # Create a Dialog Box #

    # Input variables
    readFile = '/groups/cenote/BYU_anm_pipeline/production/shots/'

    startAt = 'Force Start at Frame 1001'
    exportAt = 'Export at Original Frame Range'
    localizer = 'Localization Policy'
    TCL = 'Use TCL command on Write node'

    saveFolder = '/groups/cenote/'
    scriptName = 'Script Name'
    addFolder = 'scripts, render'

    z = nuke.Panel('New comp from shot layers')

    z.addFilenameSearch('Read File', readFile)
    z.addBooleanCheckBox(startAt, 'True')
    z.addBooleanCheckBox(exportAt, 'False')
    z.addBooleanCheckBox(localizer, 'False')
    z.addBooleanCheckBox(TCL, 'True')
    z.addFilenameSearch('Save Folder', saveFolder)
    z.addSingleLineInput('Script Name', scriptName)
    z.addSingleLineInput('Additional Folders', addFolder)

    z.addButton('Cancel')
    z.addButton('OK')

    z.setWidth(600)
    result = z.show()

    # End of Dialog Box #
    #####################

    if result == 0:
        pass  # If hit 'Cancel', pass

    else:

        #files = glob.glob(readFile, recursive=True)
        #print(files)

        # Get values
        readFile = z.value(readFile)

        startAt = z.value(startAt)
        exportAt = z.value(exportAt)
        localizer = z.value(localizer)
        TCL = z.value(TCL)

        saveFolder = z.value(saveFolder)
        scriptName = z.value(scriptName)
        addFolder = z.value('Additional Folders')

        # Internal variables
        createFolder = False
        versionUp = False
        createScriptFolder = False
        createExportFolder = False

        if (readFile == ('Read File')) or (
                readFile == ('')
        ):  # If Read file keep with the original value or is empty, the process will not run
            print('Nothing to do here!')
            pass

        else:

            task = nuke.ProgressTask('Creating script...')

            if (saveFolder == '') or (saveFolder == 'Master Folder'):
                createFolder = False
                print
                print('No folder structure created ')

            else:

                ###########################
                # Create Folder Structure #

                createFolder = True

                shotFolder = (os.path.join(saveFolder, scriptName))

                print
                print('Create folder structure at')
                print(saveFolder)

                try:
                    os.mkdir(shotFolder)
                    print
                    print('-> Shot folder created: ' + shotFolder)
                    task.setMessage('Creating: %s' % (shotFolder))

                except:
                    print
                    print('-> Main folder already exist!\n%s' % (shotFolder))

                if (addFolder == ''):
                    #createFolder = False
                    print
                    print("--> Don't create any sub-folders")
                    pass

                else:

                    folderList = []

                    for i in addFolder.split(', '):
                        folderList.append(i)

                    # Create sub-directories
                    for i in folderList:
                        folderName = (os.path.join(shotFolder, i))
                        folderName = folderName.replace('\\', '/')

                        task.setMessage('Creating: %s' % (folderName))

                        try:
                            os.mkdir(folderName)
                            print
                            print('--> Created sub-directory: ' + folderName)

                        except:
                            print
                            print('--> Folder already exist!\n%s' %
                                  (folderName))
                            versionUp = True

                        if folderList.index(i) == 0:
                            scriptFolder = folderName  # Get the first folder name to save the Script
                            createScriptFolder = True

                        if folderList.index(i) == 1:
                            exportFolder = folderName  # Get the second folder name to set the Write node
                            createExportFolder = True

                print
                print('++++++++++++++++++++++++++++++++++')

                # End of Folder Creator #
                #####################

            ###############
            # Create Read #

            filelist = [readFile]

            if filelist != None:
                for f in filelist:
                    newRead = nuke.createNode("Read",
                                              "file {" + f + "}",
                                              inpanel=True)

            inPoint = newRead['first'].getValue()
            outPoint = newRead['last'].getValue()
            newRead['before'].setValue('black')
            newRead['after'].setValue('black')
            newRead.hideControlPanel()

            inPoint = int(inPoint)
            outPoint = int(outPoint)

            print
            print('Read Node created: ' + newRead.name())
            print('--> ' + f)

            task.setMessage('Creating: %s' % (newRead.name()))

            if localizer == True:
                newRead['localizationPolicy'].setValue('on')

            # Get Read infos
            width = (newRead.width())
            height = (newRead.height())

            frameRate = (newRead.metadata('input/frame_rate'))

            xPos = newRead['xpos'].getValue()
            yPos = newRead['ypos'].getValue()

            readFormat = newRead.knob('format').value().name()

            redAspect = False

            aspectRatio = (newRead.metadata('exr/pixelAspectRatio'))
            if aspectRatio == None:
                try:
                    aspectRatio = (newRead.metadata('r3d/pixel_aspect_ratio'))
                    redAspect = True

                except:
                    aspectRatio = (newRead.metadata('input/pixel_aspect'))
                    print('Input aspect Ratio')

            # End Create Read #
            ###################

            ###################
            # Create Timeclip #

            tclip = nuke.createNode('TimeClip')

            tclip['first'].setValue(int(inPoint))
            tclip['last'].setValue(int(outPoint))

            tclip['before'].setValue('black')
            tclip['after'].setValue('black')

            tclip['frame_mode'].setValue('start at')

            print
            print('Timeclip Node created: ' + tclip.name())

            task.setMessage('Creating: %s' % (tclip.name()))

            if exportAt == True:
                origInPoint = inPoint
                origOutPoint = outPoint

            if startAt == True:
                outPoint = (outPoint - inPoint) + 1001
                inPoint = 1001

            tclip['frame'].setValue(str(inPoint))

            tclip.setInput(0, newRead)

            tclip.hideControlPanel()

            tclip['xpos'].setValue(xPos)
            tclip['ypos'].setValue(yPos + 100)

            tclip['selected'].setValue(False)

            # End Timeclip #
            ################

            ##############
            # Create Dot #

            nDot = nuke.createNode('Dot')
            nDot['name'].setValue('FinalOutput')
            nDot['label'].setValue('Final Output')

            nDot.setInput(0, tclip)

            nDot.hideControlPanel()

            nDot['xpos'].setValue(xPos + 34)
            nDot['ypos'].setValue(yPos + 650)

            nDot['selected'].setValue(False)

            # End Dot #
            ###########

            #################
            # Create Viewer #

            v = 0

            for i in nuke.allNodes():
                if i.Class() in ('Viewer'):
                    v = v + 1

            if v == 0:
                nViewer = nuke.createNode('Viewer')
                nViewer.setInput(0, nDot)
                nViewer['xpos'].setValue(xPos + 200)
                nViewer['ypos'].setValue(yPos + 650)
                nViewer['selected'].setValue(False)

            if startAt == True:
                nuke.frame(1001)

            else:
                nuke.frame(int(inPoint))

            # End Viewer #
            ##############

            ####################################
            # Create Backdrop for Read Session #

            newRead['selected'].setValue(True)

            sel = nuke.selectedNode()

            Xw = sel['xpos'].getValue()
            Yw = sel['ypos'].getValue()

            if exportAt == True:
                rLabel = (
                    '<center><img src = "'
                    "Read.png"
                    '" >Read File\n<font size = 1>Frame Range: %d - %d\nOriginal Frame Range: %d - %d'
                    % ((inPoint),
                       (outPoint), int(origInPoint), int(origOutPoint)))

            else:
                rLabel = ('<center><img src = "'
                          "Read.png"
                          '" >Read File\n<font size = 1>Frame Range: %s - %s' %
                          (inPoint, outPoint))

            bk = nukescripts.autoBackdrop()
            bk['label'].setValue(rLabel)
            bk['bdwidth'].setValue(500)
            bk['bdheight'].setValue(500)
            bk['xpos'].setValue(Xw - 225)
            bk['ypos'].setValue(Yw - 200)

            print
            print('Backdrop created: ' + bk.name())
            print
            print('++++++++++++++++++++++++++++++++++')

            task.setMessage('Creating: %s' % (bk.name()))

            # End of create Backdrop #
            ##########################

            ##########################
            # Setup Project Settings #

            print
            print('Project Settings')

            task.setMessage('Project Settings...')

            sel = nuke.selectedNode()

            nkRoot = nuke.root()

            if frameRate == None:
                nkRoot['fps'].setValue(24)

            else:
                nkRoot['fps'].setValue(frameRate)

            if aspectRatio == None:
                aspectRatio = 1

            nkRoot['first_frame'].setValue(inPoint)
            nkRoot['last_frame'].setValue(outPoint)
            nkRoot['lock_range'].setValue(True)

            print
            print('Set Frame Range to %s:%s' % (str(inPoint), str(outPoint)))

            if readFormat == None:
                newFormatName = ('%s_Resolution' % (newRead.name()))
                nuke.addFormat('%d %d %d %s' %
                               (width, height, aspectRatio, newFormatName))
                nkRoot['format'].setValue(newFormatName)
                newRead['format'].setValue(newFormatName)
                print
                print(
                    'Set Format to %s %sx%s, and aspect ratio to %s' %
                    (newFormatName, str(width), str(height), str(aspectRatio)))

            else:
                for each in (nuke.formats()):
                    if (each.name()) == readFormat:
                        nkRoot['format'].setValue(each.name())
                        print
                        print(
                            'Set Format to %s %sx%s, and aspect ratio to %s' %
                            (str(each.name()), str(width), str(height),
                             str(aspectRatio)))
                        pass

            print
            print('++++++++++++++++++++++++++++++++++')

            # End of Project Settings #
            ###########################

            ##################################################
            # Create Timeclip to set to original plate range #

            if exportAt == True:
                newRead['selected'].setValue(False)

                exclip = nuke.createNode('TimeClip')

                exclip['first'].setValue(int(inPoint))
                exclip['last'].setValue(int(outPoint))

                exclip['before'].setValue('black')
                exclip['after'].setValue('black')

                exclip.hideControlPanel()

                exclip['xpos'].setValue(xPos)
                exclip['ypos'].setValue(yPos + 910)

                exclip.setInput(0, nDot)

                exclip['selected'].setValue(False)
                exclip['frame_mode'].setValue('start at')

                exclip['frame'].setValue(str(origInPoint))

                task.setMessage('Creating: %s' % (exclip.name()))

                print
                print('Timeclip Node created: ' + exclip.name())

            # End Timeclip Reverse #
            ########################

            ####################
            #Create Write node #

            newRead['selected'].setValue(False)

            nWrite = nuke.createNode('Write')

            nWrite['name'].setValue('Write_Output')
            nWrite['channels'].setValue('rgb')
            nWrite['file_type'].setValue('exr')
            nWrite['create_directories'].setValue(True)

            task.setMessage('Creating: %s' % (nWrite.name()))

            frHash = '####'

            if (createExportFolder == True):
                if TCL == True:
                    folderTCL = '[lindex [split [lindex [split [value root.name] /] end] .] 0]'
                    scriptTCL = '[lindex [split [lindex [split [value root.name] /] end] .] 0].%05d.exr'
                    writeFile = ('%s/%s/%s' %
                                 (exportFolder, folderTCL, scriptTCL))

                else:
                    writeFile = (
                        '%s/%s_v001/%s_v001.%s.exr' %
                        (exportFolder, scriptName, scriptName, frHash))

                nWrite['file'].setValue(writeFile)

            nWrite['xpos'].setValue(xPos)
            nWrite['ypos'].setValue(yPos + 1000)

            print
            print('Write Node created: ' + nWrite.name())

            if exportAt == True:
                nWrite.setInput(0, exclip)

            else:
                nWrite.setInput(0, nDot)

            nWrite.hideControlPanel()

            nWrite['selected'].setValue(True)
            sel = nuke.selectedNode()

            Xw = sel['xpos'].getValue()
            Yw = sel['ypos'].getValue()

            # End Write #
            #############

            ################################
            #Create Backdrod to Write Area #

            if exportAt == True:
                wLabel = (
                    '<center><img src = "'
                    "Write.png"
                    '" >Output\n<font size = 1>Frame Range: %d - %d\nOriginal Frame Range: %d - %d'
                    % ((inPoint),
                       (outPoint), int(origInPoint), int(origOutPoint)))

            else:
                wLabel = ('<center><img src = "'
                          "Write.png"
                          '" >Output\n<font size = 1>Frame Range: %d - %d' %
                          (inPoint, outPoint))

            bk = nukescripts.autoBackdrop()
            bk['label'].setValue(wLabel)
            bk['bdwidth'].setValue(500)
            bk['bdheight'].setValue(400)
            bk['xpos'].setValue(Xw - 225)
            bk['ypos'].setValue(Yw - 300)

            task.setMessage('Creating: %s' % (bk.name()))

            print
            print('Backdrop created: ' + bk.name())
            print
            print('++++++++++++++++++++++++++++++++++')

            # End Backdrop #
            ################

            ######################################################
            # Save project at first folder name from user's list #

            message = False
            version = 'v001'

            try:
                path, dirs, files = next(os.walk(scriptFolder))

                if (len(files) >= 1):
                    a = len(files) + 1
                    version = 'v00' + str(a) + '_avoidOverwrite'
                    message = True

            except:
                print
                print('No script Folder')
                pass

            # Get name from clip
            clipname = os.path.basename(readFile)

            nameList = []

            for a in clipname.split('.'):
                nameList.append(a)

            newName = nameList[0]

            newName = newName.replace('#', '')

            if (createScriptFolder == True):
                task.setMessage('Saving...')

                if scriptName == '':
                    nukeFile = os.path.join(scriptFolder,
                                            ('%s_%s.nk' % (newName, version)))

                else:
                    nukeFile = os.path.join(
                        scriptFolder, ('%s_%s.nk' % (scriptName, version)))

                nukeFile = nukeFile.replace('\\', '/')

                if (message == True):
                    nuke.message(
                        'Saved as\n%s\nto avoid overwrite other script!\nPlease, save comp with new name.'
                        % (nukeFile))

                nuke.scriptSaveAs(nukeFile)

                print
                print('Script saved at: ' + nukeFile)
                print
                print('++++++++++++++++++++++++++++++++++')
                print

            elif (createFolder == True):
                task.setMessage('Saving...')

                if scriptName == '':
                    nukeFile = os.path.join(shotFolder,
                                            ('%s_%s.nk' % (newName, version)))

                else:
                    nukeFile = os.path.join(
                        shotFolder, ('%s_%s.nk' % (scriptName, version)))

                nukeFile = nukeFile.replace('\\', '/')

                if (message == True):
                    nuke.message(
                        'Saved as\n%s\nto avoid overwrite other script!\nPlease, save comp with new name.'
                        % (nukeFile))

                nuke.scriptSaveAs(nukeFile)

                print
                print('Script saved at: ' + nukeFile)
                print
                print('++++++++++++++++++++++++++++++++++')
                print

            else:
                nuke.message(
                    '<font size = "4" color = "red"><center><b>ATENTION!</b></font>\nScript unsaved! Please, do it!'
                )

                print
                print('######### ATENTION! ##########')
                print('Script unsaved! Please, do it!')
                print
                print('++++++++++++++++++++++++++++++++++')
                print

            print('++++++++++++++++++++++++++++++++++')
            print('..................................')
            print
Ejemplo n.º 24
0
def update():

    import nuke
    from datetime import datetime
    import os
    import sys

    ########################################################################################################
    print "Connecting to Shotgun"

    try:
        import sgtk
        # get the engine we are currently running in
        current_engine = sgtk.platform.current_engine()
        # get hold of the shotgun api instance used by the engine, (or we could have created a new one)
        sg = current_engine.shotgun
        print "Connected to Shotgun via current SGTK engine...\n"
    except:
        sys.path.append(os.environ["SHOTGUN_API3"])
        try:
            import sg_connection
            import shotgun_api3
            # Connect to SG
            sg = shotgun_api3.Shotgun(os.environ["SERVER_PATH"],
                                      os.environ["SCRIPT_NAME"],
                                      os.environ["SCRIPT_KEY"])
            print "Connected to Shotgun via api...\n"
        except:
            import shotgun_api3
            sg = shotgun_api3.Shotgun(os.environ["SHOTGUN_API_SERVER_PATH"],
                                      os.environ["SHOTGUN_API_SCRIPT_NAME"],
                                      os.environ["SHOTGUN_API_SCRIPT_KEY"])
            print "Connected to Shotgun via api...\n"

    ########################################################################################################
    print "Loading Functions"

    def getSGStatusFriendlyName(status_short_code):
        fields = ["name"]
        filters = [['code', 'is', status_short_code]]
        friendly_status = sg.find_one("Status", filters, fields)
        #print friendly_status
        return friendly_status.get("name")

    "Run code on this node unless developing in the nuke script editor"
    try:
        n = nuke.thisNode()
    except Exception as e:
        #print e
        n = nuke.selectedNode()

    "Making sure we are connected to a node with a file knob"
    try:
        try:
            "Get Upstream Node"
            read = nuke.toNode(n.input(0)["name"].getValue())
        except:
            "Get Node from Knob"
            read = nuke.toNode(n["source_node"].getValue())
        print "Using Read:" + str(read["name"].getValue())
        print "File knob: " + read["file"].getValue()
    except:
        nuke.message(
            "Please connect to a node with a file knob or add the name in the input knob!"
        )
        return

    "Filename to search Shotgun with"
    searchString = read["file"].getValue()
    if ".mov" in searchString:
        shotgun_field = "sg_path_to_movie"
    else:
        shotgun_field = "sg_path_to_frames"
    searchString_backwards = searchString.replace("/", "\\")
    searchString_forwards = searchString.replace("\\", "/")

    ##########################################
    print "Primary Search"
    ##########################################
    print "Searching Shotgun for data with search string:\n" + searchString_forwards + "\n"
    fields = [
        "code", "sg_status_list", "client_code", "entity", "sg_slate_notes",
        "project", "user", "created_at", "description", "sg_version_type",
        "sg_tech_check_notes", "sg_tech_check_approved", "sg_editorial_status"
    ]
    filters = [[shotgun_field, "contains", searchString_forwards]]
    version_data = sg.find_one('Version', filters, fields)
    #print version_data

    if version_data == None:
        ##########################################
        print "Secondary Search"
        ##########################################
        filters = [[shotgun_field, "contains", searchString_backwards]]
        version_data = sg.find_one('Version', filters, fields)
        print "Searching Shotgun for data with search string:\n" + searchString_backwards + "\n"
        #print version_data

    ##########################################
    print "Searching for Entity Data"
    ##########################################
    print "\nSearching Shotgun for entity data "
    fields = [
        "sg_asset_type", "sg_status_list", "sg_head_in", "sg_tail_out",
        "sg_head_handle", "sg_tail_handle", "sg_cut_in", "sg_cut_out",
        "tank_name", "sg_sequence", "sg_episode"
    ]
    filters = [["id", "is", version_data.get("entity").get("id")]]
    entity_data = sg.find_one(
        version_data.get("entity").get("type"), filters, fields)
    #print entity_data

    ##########################################
    print "Searching for Project Data"
    ##########################################
    print "\nSearching Shotgun for project data "
    fields = ["tank_name", "sg_fps"]
    filters = [['name', 'contains', version_data.get("project").get("name")]]
    project_data = sg.find_one("Project", filters, fields)
    #print project_data

    #############################################################################
    print "\nProcessing Project data"
    try:
        field = "tank_name"
        n[field].setValue("")
        n[field].setValue(project_data.get(field))
    except Exception as e:
        print field
        print e
    try:
        n["project_fps"].setValue("")
        n["project_fps"].setValue(str(project_data.get("sg_fps")))
    except Exception as e:
        print "project_fps"
        print e

    #############################################################################
    print "\nProcessing Version data"
    try:
        field = "project"
        n[field].setValue("")
        n[field].setValue(version_data.get(field).get("name"))
    except Exception as e:
        print field
        print e
    try:
        n["version_name"].setValue("")
        n["version_name"].setValue(version_data.get("code"))
    except Exception as e:
        print "version_name"
        print e
    try:
        field = "client_code"
        n[field].setValue("")
        n[field].setValue(version_data.get(field))
    except Exception as e:
        print field
        print e
    try:
        field = "user"
        n[field].setValue("")
        n[field].setValue(version_data.get(field).get("name"))
    except Exception as e:
        print field
        print e
    try:
        field = "created_at"
        n[field].setValue("")
        n[field].setValue(str(version_data.get(field)))
    except Exception as e:
        print field
        print e
    try:
        n["entity_type"].setValue(version_data.get("entity").get("type"))
    except Exception as e:
        print "entity_type"
        print e
    try:
        entity_name = version_data.get("entity").get("name")
        n["entity_name"].setValue("")
        n["entity_name"].setValue(entity_name)
    except Exception as e:
        print "entity_name"
        print e
    try:
        field = "description"
        n[field].setValue("")
        n[field].setValue(version_data.get(field))
    except Exception as e:
        print field
        print e
    try:
        field = "sg_slate_notes"
        n[field].setValue("")
        n[field].setValue(version_data.get(field))
    except Exception as e:
        print field
        print e
    try:
        field = "sg_version_type"
        n[field].setValue("")
        n[field].setValue(version_data.get(field))
    except Exception as e:
        print field
        print e
    try:
        field = "sg_tech_check_notes"
        n[field].setValue("")
        n[field].setValue(version_data.get(field))
    except Exception as e:
        print field
        print e
    try:
        field = "sg_tech_check_approved"
        n[field].setValue("")
        n[field].setValue(version_data.get(field))
    except Exception as e:
        print field
        print e
    try:
        field = "sg_editorial_status"
        n[field].setValue("")
        n[field].setValue(version_data.get(field))
    except Exception as e:
        print field
        print e
    try:
        field = "sg_status_list"
        status = getSGStatusFriendlyName(version_data.get(field))
        n["sg_version_status_list"].setValue("")
        n["sg_version_status_list"].setValue(status)
    except Exception as e:
        print field
        print e

    #############################################################################
    print "\nProcessing Entity data"
    try:
        field = "sg_asset_type"
        n[field].setValue("")
        n[field].setValue(entity_data.get(field))
    except Exception as e:
        print field
        print e
    try:
        field = "sg_episode"
        n[field].setValue("")
        n[field].setValue(entity_data.get(field).get("name"))
    except Exception as e:
        print field
        print e
    try:
        field = "sg_sequence"
        n[field].setValue("")
        n[field].setValue(entity_data.get(field).get("name"))
    except Exception as e:
        print field
        print e
    try:
        field = "sg_head_in"
        n[field].setValue("")
        value = str(entity_data.get(field))
        if value == "None":
            value = "0"
        n[field].setValue(str(value))
    except Exception as e:
        print field
        print e
    try:
        field = "sg_tail_out"
        n[field].setValue("")
        value = str(entity_data.get(field))
        if value == "None":
            value = "0"
        n[field].setValue(str(value))
    except Exception as e:
        print field
        print e
    try:
        field = "sg_head_handle"
        n[field].setValue("")
        value = str(entity_data.get(field))
        if value == "None":
            value = "0"
        n[field].setValue(str(value))
    except Exception as e:
        print field
        print e
    try:
        field = "sg_tail_handle"
        n[field].setValue("")
        value = str(entity_data.get(field))
        if value == "None":
            value = "0"
        n[field].setValue(str(value))
    except Exception as e:
        print field
        print e
    try:
        field = "sg_cut_in"
        n[field].setValue("")
        value = str(entity_data.get(field))
        if value == "None":
            value = "0"
        n[field].setValue(str(value))
    except Exception as e:
        print field
        print e
    try:
        field = "sg_cut_out"
        n[field].setValue("")
        value = str(entity_data.get(field))
        if value == "None":
            value = "0"
        n[field].setValue(str(value))
    except Exception as e:
        print field
        print e
    try:
        field = "sg_status_list"
        n["sg_entity_status_list"].setValue("")
        friendly_status = getSGStatusFriendlyName(entity_data.get(field))
        n["sg_entity_status_list"].setValue(friendly_status)
    except Exception as e:
        print field
        print e

    #############################################################################
    print "\nFinding Step"
    try:
        n["step"].setValue("")
        try:
            step = searchString.replace("\\", "/").lower()
            step = step.split(entity_name.lower())[1]
            step = step.split("/")[1]
            n["step"].setValue(step)
        except:
            step = searchString.replace("\\", "/").lower()
            step = step.split("/publish")[0]
            step = step.split("/")[-1]
            n["step"].setValue(step)
    except Exception as e:
        print "step"
        print e


#update()
Ejemplo n.º 25
0
def selectDependencies():
    selectedNode = nuke.selectedNode()
    depNodes = selectedNode.dependencies()
    for depNode in depNodes:
        depNode.setSelected(True)
Ejemplo n.º 26
0
def xor():
    import nuke
    n = nuke.selectedNode()
    n['operation'].setValue('min')
            def multiChannelSplit():
                '''
                main function
                split the selected read node in separate channel layers
                if set create separate folders and write nodes
                '''
                sel = nuke.selectedNode()

                shuffles = []
                renderTo = ""
                autocropNodeRGB_exists = False
                cropNode = None
                dot = None

                if sel is not None:
                    # Main procedure
                    # Create shuffle, shuffle channel in, curvetool crop
                    # Create cropnode and paste that information in
                    # Delete crop node
                    o = 0
                    if self.autoCrop.getValue() == 1.0:
                        curveName = 'Autocrop_Master'
                        curveNode = nuke.nodes.CurveTool(name=curveName,
                                                         inputs=[sel],
                                                         operation="Auto Crop")
                        curveNode["channels"].setValue("rgba")
                        curveNode.knob("ROI").setValue(
                            [0, 0, sel.width(),
                             sel.height()])
                        nuke.execute(curveNode,
                                     sel.knob("first").value(),
                                     sel.knob("last").value())

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

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

                        for channelLayer in layersToProcess:
                            shuffleName = "Shuffle_" + channelLayer
                            shuffleNode = nuke.nodes.Shuffle(name=shuffleName)
                            shuffles.append(shuffleNode.name())
                            shuffleNode.knob("in").setValue(channelLayer)
                            shuffleNode["hide_input"].setValue(True)
                            shuffleNode.setInput(0, sel)

                            xpos = sel["xpos"].getValue() + (o * 100)
                            ypos = sel["ypos"].getValue() + 150
                            shuffleNode["xpos"].setValue(xpos)
                            shuffleNode["ypos"].setValue(ypos)
                            shuffleNode.setInput(0, dot)
                            shuffleNode["postage_stamp"].setValue(True)

                            # Auto crop if selected
                            if self.autoCrop.getValue() == 1.0:
                                if autocropNodeRGB_exists is False:
                                    cropNode = nuke.nodes.Crop(
                                        name=channelLayer,
                                        inputs=[shuffleNode])
                                    cropNode.knob("hide_input").setValue(True)
                                    cropNode.knob("box").copyAnimations(
                                        curveNode.knob(
                                            "autocropdata").animations())
                                    nuke.delete(curveNode)
                                    cropNode.knob("postage_stamp").setValue(
                                        True)

                                    xpos = int(shuffleNode["xpos"].getValue())
                                    ypos = shuffleNode["ypos"].getValue() + 80
                                    ypos = int(ypos)
                                    cropNode.setXpos(xpos)
                                    cropNode.setYpos(ypos)
                                    shuffleNode["hide_input"].setValue(False)
                                    cropNode["hide_input"].setValue(True)
                                    nukescripts.clear_selection_recursive()
                                    cropNode["selected"].setValue(True)
                                    nuke.nodeCopy("%clipboard%")
                                    autocropNodeRGB_exists = True
                                    shuffleNode["postage_stamp"].setValue(
                                        False)
                                    cropNode["postage_stamp"].setValue(True)
                                else:
                                    cropCopy = nuke.nodePaste("%clipboard%")
                                    cropCopy["name"].setValue(channelLayer)
                                    cropCopy.setInput(0, shuffleNode)

                                    xpos = int(shuffleNode["xpos"].getValue())
                                    ypos = shuffleNode["ypos"].getValue() + 80
                                    ypos = int(ypos)
                                    cropCopy.setXpos(xpos)
                                    cropCopy.setYpos(ypos)

                            # Create folders for all layer and
                            # Create write node for every shuffle
                            if self.outputPath.getValue() != "":
                                renderTo = self.outputPath.getValue()
                                # CreateFolder
                                createFolders(renderTo + "/" + channelLayer)
                                # Create write node
                                write = nuke.nodes.Write()
                                write.knob("file_type").setValue("exr")

                                fileValue = renderTo + channelLayer
                                fileValue += '/' + channelLayer + "_%04d.exr"
                                write.knob("file").setValue(fileValue)

                                cValue = "Zip (16 scanlines)"
                                write.knob("compression").setValue(cValue)
                                write.knob("channels").setValue("rgba")

                                if self.autoCrop.getValue() is True:
                                    write.setInput(0, cropNode)
                                else:
                                    write.setInput(0, shuffleNode)
                            o += 1

                    if len(layersToProcess) > 0:
                        nuke.delete(dot)

                    # Hide all created shuffle inputs
                    for shuffleNode in shuffles:
                        if self.autoCrop.getValue() == 1.0:
                            temp = nuke.toNode(shuffleNode)
                            temp.knob("hide_input").setValue(True)
                            temp.knob("postage_stamp").setValue(True)
                else:
                    pass
Ejemplo n.º 28
0
    def showDialog( self ):

        result = nukescripts.PythonPanel.showModalDialog( self )



        if result:

            # User Input Value

            inputPath = "/All/"+self.project.value()+'/'+self.scene.value()+'/'+ \

                        self.camera.value()+'/STUFF/'+self.department.value()+'/'+ \

                        self.folder.value()+'/*'+self.key.value()+'*/'

            

            # Via InputPath search All Correct Path

            searchPath = glob.glob(inputPath)

            searchPath.sort()

            

            # Remove Void Folder

            for i in searchPath:

                if glob.glob(i+'*') == []:

                    searchPath.remove(i)

            

            # Folder Last Version

            if self.lastversion.value():

                

                folderPath = []

                lastFolderPath = []

                

                for i in searchPath:

                    t = i.split('_'+self.department.value()).pop(0)

                    folderPath.append(t)

                folderPath = list(set(folderPath))

                folderPath.sort()

                

                for i in folderPath:

                    lastFolderPath.append(max(glob.glob(i+'*'+self.key.value()+'*')))

                searchPath = lastFolderPath



            # Define xPos is ReadNode x position in the NodeGraph

            # Define clip is each ReadNode number of AppendclipNode

            xPos = 0

            clip = 0

            

            # Need AppendClipNode

            if self.appendclip.value():

                # Create AppendclipNode

                appendClip = nuke.createNode('AppendClip',inpanel=False)

                appendClip.setXYpos(len(searchPath)*50,500)

                

                # Create ReadNodes in the loop

                for i in searchPath:

                    # fileList is each Folder's Files

                    fileList = glob.glob(i+'/*')

                    fileList.sort()

                    
                    # Remove the Error file

                    for i in fileList:

                        if len(i.split('.'))!=3 or len(i.split('.').pop(1)) != 4  or i.split('.').pop(1).isdigit() is False :

                            fileList.remove(i)

                    

                    # Calculate First Frame and Last Frame

                    frontNum = str(int(min(fileList).split('.').pop(1)) + self.frmplus.value())

                    backNum = str(int(max(fileList).split('.').pop(1)) - self.frmminus.value())

                    # fileName is fullname of the ReadNode

                    fileName = fileList[0].split('.').pop(0)+'.%04d.'+fileList[0].split('.').pop()

                    

                    # Create ReadNode

                    creatRead=nuke.createNode("Read","file {"+fileName+" "+frontNum+"-"+backNum+"}", inpanel = False)

                    creatRead.setXYpos(xPos,1)

                    xPos=xPos+100

                    

                    # link to AppendclipNode

                    sc=nuke.selectedNode()

                    appendClip.setInput(clip,sc)

                    clip=clip+1



            # Needn't AppendClipNode

            else:

                # Create ReadNodes in the loop

                for i in searchPath:

                    # fileList is each Folder's Files

                    fileList = glob.glob(i+'/*')

                    fileList.sort()

                    

                    # Remove the Error file

                    for i in fileList:

                        if len(i.split('.'))!=3 or len(i.split('.').pop(1)) != 4  or i.split('.').pop(1).isdigit() is False :

                            fileList.remove(i)

                    

                    # Calculate First Frame and Last Frame

                    frontNum = str(int(min(fileList).split('.').pop(1)) + self.frmplus.value())

                    backNum = str(int(max(fileList).split('.').pop(1)) - self.frmminus.value())
                    # fileName is fullname of the ReadNode

                    fileName = fileList[0].split('.').pop(0)+'.%04d.'+fileList[0].split('.').pop()

                    

                    # Create ReadNode

                    creatRead=nuke.createNode("Read","file {"+fileName+" "+frontNum+"-"+backNum+"}", inpanel = False)

                    creatRead.setXYpos(xPos,1)

                    xPos=xPos+100



            # Show the message

            length=len(searchPath)

            nuke.message(str(length)+'Reads')
Ejemplo n.º 29
0
def main():
    ShapeAndCVPanel(nuke.selectedNode()).showModalDialog()
Ejemplo n.º 30
0
def bake_gizmo(gizmo):
    '''
    copy gizmo to group and replace it in the tree, so all inputs and outputs use the new group.
    returns the new group node
    '''
    parent = get_parent(gizmo)
    gizmo_outputs = get_outputs(gizmo)
    gizmo_inputs = gizmo.inputs()

    print "INPUTS:", gizmo_inputs  #[inputnodes.name() for inputnodes in gizmo_inputs]
    print "OUTPUTS:", gizmo_outputs  #[output_nodes.name() for output_nodes in gizmo_outputs]

    # This old method can't detect failures
    #groupName = nuke.tcl( 'global no_gizmo; set no_gizmo 1; in %s {%s -New} ; return [value [stack 0].name]' % ( parent.fullName(), gizmo.Class() ) )
    for n in get_all_nodes(nuke.root()):
        n.setSelected(False)
    try:
        nuke.tcl('copy_gizmo_to_group {0}'.format(gizmo.fullName()))
        #group = nuke.toNode( '.'.join( (parent.fullName(), groupName) ) )
        ## We will use the selected node to get the created group
        group = nuke.selectedNode()

        if gizmo_outputs:
            #RECONNECT OUTPUTS IF THERE ARE ANY
            for node, pipes in gizmo_outputs.iteritems():
                for i in pipes:
                    node.setInput(i, group)

        #RECONNECT INPUTS
        for i in range(gizmo.inputs()):
            group.setInput(i, gizmo.input(i))
        group.setSelected(False)

    except RuntimeError:
        # Occurs if the gizmo was sourced: "RuntimeError: This gizmo was created with a "load" or "source" command. Copy to group does not work for it."
        print "This gizmo was created with a 'load' or 'source' command. Manually re-creating it..."
        with parent:
            # gizmo.Class() fails because the gizmo class is defined as "Gizmo" - super hacky but we'll try to use the node's name
            gizmo_guess_class = re.split('[0-9]*$', gizmo.name())[0]
            tmp_gizmo = nuke.createNode(gizmo_guess_class, inpanel=False)
            nuke.tcl('copy_gizmo_to_group {0}'.format(tmp_gizmo.fullName()))

        # fix bug where the copy_gizmo_to_group puts node outside of the parent: cut node outside group, paste node inside group
        nuke.nodeCopy(nukescripts.cut_paste_file())
        nukescripts.node_delete(popupOnError=True)
        with parent:
            nuke.nodePaste(nukescripts.cut_paste_file())

            group = nuke.selectedNode()
            nuke.delete(tmp_gizmo)
            group.setSelected(False)

    group.hideControlPanel()

    if gizmo_outputs:
        #RECONNECT OUTPUTS IF THERE ARE ANY
        for node, pipes in gizmo_outputs.iteritems():
            for i in pipes:
                node.setInput(i, group)

    #RECONNECT INPUTS
    for i in range(gizmo_inputs):
        group.setInput(i, gizmo.input(i))

    group.setXYpos(gizmo.xpos(), gizmo.ypos())
    # COPY VALUES
    group.readKnobs(gizmo.writeKnobs(nuke.TO_SCRIPT))
    gizmoName = gizmo.name()
    nuke.delete(gizmo)
    group.setName(gizmoName)
    return group
Ejemplo n.º 31
0
    def buildTree(layers, prefs):
        n = nuke.selectedNode()
        nukePrefs = nuke.toNode('preferences')
        defGoofyFootValue = nukePrefs['goofy_foot'].value()
        nukePrefs['goofy_foot'].setValue(0)

        selNodeXPos = n.xpos()
        selNodeYPos = n.ypos()

        n.setSelected(False)

        shuffDot0 = nuke.createNode('Dot', 'selected False', False)
        shuffDot0YPos = int(selNodeYPos + 100)
        shuffDot0.setXYpos(int(selNodeXPos + 200), shuffDot0YPos)
        shuffDot0.setInput(0, n)

        # Creation of nodes
        listShuffDots = []
        for i in range(len(layers)):
            # Dots
            if i == 0:
                shuffDot = shuffDot0
            else:
                newXPos = (prefs['separation']*i)+shuffDot0.xpos()
                shuffDot = nuke.createNode('Dot', inpanel=False)
                shuffDot.setSelected(False)
                shuffDot.setXYpos(int(newXPos), shuffDot0YPos)
                shuffDot.setInput(0, listShuffDots[i-1])
            listShuffDots.append(shuffDot)

        # Shuffles
        save = nuke.toNode('preferences')['NodeColour05Color'].value()
        for i in range(len(layers)):
            newXPos = (prefs['separation']*i) + shuffDot0.xpos()
            setShuf = 'in %s ' % (layers[i])
            shuf = nuke.createNode('Shuffle', setShuf, False)
            shuf.setName(layers[i])
            shuf.setInput(0, listShuffDots[i])
            shuf.setXYpos(int(newXPos-34), shuffDot0YPos+50)

            # Color
            if prefs['shuffLayersColor'] != save:
                shuf['tile_color'].setValue(prefs['shuffLayersColor'])

            # Label
            if prefs['noShuffLabel'] == True:
                shuf['label'].setValue('')

            # Removes
            if prefs['remove'] == True:
                setRem = 'operation keep channels rgba selected False'
                rem = nuke.createNode('Remove', setRem, False)
                rem.setInput(0, shuf)

            # Grades
            if prefs['grade'] == True:
                nuke.createNode('Grade', inpanel=False)

            # Autocrop
            if prefs['autocrop']:
                nukescripts.autocrop()

            # Postage stamp
            if prefs['postage']:
                shuf.knob('postage_stamp').setValue(True)

            for node in nuke.selectedNodes():
                node.setSelected(False)

        # BackDrop
        width = 0
        height = 0
        if prefs['bdrop'] == True:
            width = (prefs['separation'] * (len(layers)))
            height = 350

            bd = nuke.createNode('BackdropNode',
                                 'tile_color %s' % (prefs['bdropColor']),
                                 inpanel=False)

            bd.setXYpos(int(shuffDot0.xpos() - 100), shuffDot0.ypos() - 100)
            bd['bdwidth'].setValue(width)
            bd['bdheight'].setValue(height)
            bd.setSelected(False)

        # Resets prefs to user defined state
        nukePrefs = nuke.toNode('preferences')
        nukePrefs['goofy_foot'].setValue(defGoofyFootValue)
Ejemplo n.º 32
0
######
'''WIP'''
#####



import nuke.rotopaint as rp,nukescripts, nuke

rp_node = nuke.selectedNode()
elements = {}

def parse_layer(layer, elements, parents):
    """Return a list of all Shapes or Strokes in a Roto or Rotopaint node's heirarchy, with a list of all parent Layers for each item."""
    for e in layer:
        if isinstance(e, rp.Shape):
            elements['Shapes'].append([e, parents])
        elif isinstance(e, rp.Stroke):
            elements['Strokes'].append([e, parents])
        elif isinstance(e, rp.Layer):
            parents_copy = parents[:]
            parents_copy.insert(0, e)
            elements = parse_layer(e, elements, parents_copy)
    return elements

def get_elements():
    """    Get all Shape Stroke and Layer elements in our Roto/Paint node."""
    elements = { 'Shapes':[], 'Strokes':[] }
    curves_knob = rp_node['curves']
    root_layer = curves_knob.rootLayer
    elements = parse_layer(root_layer, elements, [root_layer])
    print elements
def silhouetteFxsExporter():
    '''
    Main exporter code, UI 
    '''
    try:
        rotoNode = nuke.selectedNode()
        if rotoNode.Class() not in ('Roto', 'RotoPaint'):
            if nuke.GUI:
                nuke.message(
                    'Unsupported node type. Selected Node must be Roto or RotoPaint'
                )
            return
    except:
        if nuke.GUI:
            nuke.message('Select a Roto or RotoPaint Node')
            return
    #===========================================================================
    # Nuke UI panel setup
    #===========================================================================
    p = nukescripts.panels.PythonPanel("FXS Shape Exporter")
    k = nuke.String_Knob("framerange", "FrameRange")
    k.setFlag(nuke.STARTLINE)
    k.setTooltip(
        "Set the framerange to bake the shapes, by default its the project start-end. Example: 10-20"
    )
    p.addKnob(k)
    k.setValue("%s-%s" % (nuke.root().firstFrame(), nuke.root().lastFrame()))
    k = nuke.Boolean_Knob("bake", "Bake Shapes")
    k.setFlag(nuke.STARTLINE)
    k.setTooltip("Export the shapes baking keyframes and transforms")
    p.addKnob(k)
    result = p.showModalDialog()

    if result == 0:
        return  # Canceled
    try:
        fRange = nuke.FrameRange(p.knobs()["framerange"].getText())
    except:
        if nuke.GUI:
            nuke.message(
                'Framerange format is not correct, use startframe-endframe i.e.: 0-200'
            )
        return
    #===========================================================================
    # end of panel
    #===========================================================================
    start_time = time.time()
    rptsw_shapeList = []
    global cancel
    cancel = False

    if nuke.NUKE_VERSION_MAJOR > 6:
        #=======================================================================
        # creates a copy of the node to modify and keep original safe
        #=======================================================================
        nukescripts.node_copypaste()
        #=======================================================================
        bakeshapes = p.knobs()["bake"].value()
        rptsw_shapeList = []
        rotoNode = nuke.selectedNode()
        rotoCurve = rotoNode['curves']
        rotoRoot = rotoCurve.rootLayer
        #=*=*=*=*=*=*==task=related=code========================================
        task = nuke.ProgressTask('FXS Shape Exporter')
        task.setMessage('Starting FXS export')
        task.setProgress(10)
        #=*=*=*=*=*=*==task=related=code========================================
        rptsw_shapeList = rptsw_walker(rotoRoot, rptsw_shapeList)
        #=======================================================================
        # creates additional layers to handle shape transforms
        #=======================================================================
        #=*=*=*=*=*=*==task=related=code========================================
        task.setMessage('Sorting out Transforms')
        task.setProgress(20)
        #=*=*=*=*=*=*==task=related=code========================================
        uniqueNames(rptsw_shapeList)
        if not bakeshapes:
            manageTransforms(fRange, rotoNode, rptsw_shapeList)  #,task)
        #=*=*=*=*=*=*==task=related=code========================================
        if cancel:
            return
        #=*=*=*=*=*=*==task=related=code========================================
        rotoCurve.changed()  #just for debugging purposes
        #=======================================================================
        rptsw_shapeList = []
        rptsw_shapeList = rptsw_walker(rotoRoot, rptsw_shapeList)
        nodeFormat = rotoNode['format'].value()
        fxsExport = ET.Element(
            'Silhouette', {
                'width': str(nodeFormat.width()),
                'height': str(nodeFormat.height()),
                'workRangeStart': str(fRange.first()),
                'workRangeEnd': str(fRange.last()),
                'sessionStartFrame': str(fRange.first())
            })
        #=======================================================================
        # create the root layer first
        #=======================================================================
        item = [rotoRoot, rotoRoot]
        createLayers(item, fRange, rotoNode, rptsw_shapeList, task, fxsExport,
                     bakeshapes)
        #=*=*=*=*=*=*==task=related=code========================================
        task.setMessage('Creating Layers')
        task.setProgress(30)
        taskLength = len(rptsw_shapeList)
        taskCount = 0.0
        #=*=*=*=*=*=*==task=related=code========================================
        #=======================================================================
        # create all layers and shapes inside them
        #=======================================================================
        for item in rptsw_shapeList:
            taskCount += 1.0
            x = (taskCount / taskLength) * 10 + 30
            task.setProgress(30 + int((taskCount / taskLength) * 20))
            #=*=*=*=*=*=*==task=related=code========================================
            if cancel:
                break
            #=*=*=*=*=*=*==task=related=code========================================
            if isinstance(item[0], nuke.rotopaint.Layer):
                createLayers(item, fRange, rotoNode, rptsw_shapeList, task,
                             fxsExport, bakeshapes)
        #===================================================================
        # reorder layers/shapes
        #===================================================================
        layerlist = []
        for item in rptsw_shapeList[::-1]:
            if item[1].name not in layerlist:  #find all parent names
                layerlist.append(item[1].name)
        #=*=*=*=*=*=*==task=related=code========================================
        task.setMessage('Reordering Layer/Shapes')
        task.setProgress(50)
        taskLength = len(rptsw_shapeList)
        taskCount = 0.0
        #=*=*=*=*=*=*==task=related=code========================================
        for name in layerlist:
            #=*=*=*=*=*=*==task=related=code========================================
            task.setProgress(50 + int((taskCount / taskLength) * 50))
            taskCount += 1.0
            if cancel:
                break
            #=*=*=*=*=*=*==task=related=code========================================
            data = []
            parentElement = []
            for item in rptsw_shapeList[::-1]:
                if item[1].name == name:  #all items from same parent
                    for itemx in fxsExport.findall('.//*'):
                        if itemx.get('label') != None:
                            if item[0].name == itemx.get('label'):
                                if itemx not in data:
                                    data.append(
                                        itemx
                                    )  #locate the elements of that parent
            for itemx in fxsExport.findall('.//*'):
                if itemx.get('label') == name:
                    obj = itemx.findall("Properties/Property")
                    for item in obj:
                        if item.get('id') == "objects":
                            parentElement.append(item)
                            break
            for n in range(len(data)):
                parentElement[0][n] = data[n]
        #===================================================================
        # end of reorder layers/shapes
        #===================================================================
    else:
        nuke.message('Shape Exporter is for Nuke v7 only')

    #=*=*=*=*=*=*==task=related=code========================================
    if cancel:
        nuke.delete(rotoNode)
        return
    #=*=*=*=*=*=*==task=related=code========================================

    #===========================================================================
    # EXPORT the fxs file
    #===========================================================================
    path = os.getenv('FXSEXPORTPATH')
    if path == None:
        path = nuke.getFilename('Save the .fxs file', '*.fxs', "fxsExport.fxs")
        if path == None:
            if nuke.GUI:
                nuke.message(
                    'Aborting Script, you need to save the export to a file')
                return
        else:
            base = os.path.split(path)[0]
            ext = os.path.split(path)[1][-4:]
            #==================================================================
            # adds extension if not present on the filename
            #==================================================================
            if ext != ".fxs":
                ext = ext + ".fxs"
                path = os.path.join(base, ext)
    else:
        print "Saving file to: %s" % path

    indent(fxsExport)
    ET.ElementTree(fxsExport).write(path)
    nuke.delete(rotoNode)
    task.setProgress(100)
    print "Time elapsed: %s seconds" % (time.time() - start_time)
Ejemplo n.º 34
0
def multiply():
    import nuke
    n = nuke.selectedNode()
    n['operation'].setValue('multiply')
    n['bbox'].setValue('union')
Ejemplo n.º 35
0
def freezeWarp_v2():
    try:
        node = nuke.selectedNode()
        if node.Class() not in ('SplineWarp3'):
            if nuke.GUI:
                nuke.message('Unsupported node type. Node must be SplineWarp')
            return
    except:
        if nuke.GUI:
            nuke.message('Select a SplineWarp Node')
            return

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

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

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

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

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

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

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

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

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

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

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

    label = "FreezeF: [value fframe]" if exp else "FreezeF:" + str(freezeFrame)
    node.knob('label').setValue(label)
    node.knob('filter').setValue('Mitchell')  #less smoother than cubic
    print "FreezeSplineWarp Finished,", len(
        shapeList), "shape(s) at frame", freezeFrame
Ejemplo n.º 36
0
def fetchMetaCamToTransform():
    exr = nuke.selectedNode()
    global transform_keyword
    if exr.metadata(
            'exr/arnold'
    ) == None:  # "It's not an Arnold EXR so let's go with a V-ray one !"
        focal_keyword = "exr/cameraFocalLength"
        haperture_keyword = "exr/cameraAperture"
        transform_keyword = "exr/cameraTransform"
    else:  # else it might be a V-ray Cam, who seriously use Mental Ray yet !?
        focal_keyword = "exr/CameraFocalLength"
        haperture_keyword = "exr/CameraFilmApertureHorizontal"
        transform_keyword = "exr/worldToCamera"

    first_frame = exr["first"].value()
    last_frame = exr["last"].value()
    cam = nuke.createNode("Camera2", "name EXRcam")
    cam['label'].setValue("from " +
                          exr['file'].value().split("/")[-1].split("%")[0] +
                          "\n" + exr.metadata('input/ctime'))
    if len(nuke.views()) > 1:
        cam['translate'].splitView()
        cam['rotate'].splitView()
    cam['rot_order'].setValue('XYZ')
    for view in nuke.views():
        for cur_frame in range(first_frame, last_frame + 1):
            task = nuke.ProgressTask('Baking camera from metadata')
            if task.isCancelled():
                break
            task.setMessage('processing frame %s' % cur_frame)
            k = cam['focal']
            k.setAnimated(0, view)
            a = k.animations(view)
            focal = exr.metadata(focal_keyword, cur_frame, view)
            # if exr.metadata('exr/arnold')!=None:
            # focal = focal*10
            print "focal : ", focal
            a[0].setKey(cur_frame, focal)
            #cam['near'].setValue(exr.metadata('exr/clipNear', cur_frame, view))
            #cam['far'].setValue(exr.metadata('exr/clipFar', cur_frame, view))
            cam['haperture'].setValue(exr.metadata(haperture_keyword))
            cam['vaperture'].setValue(
                exr.metadata(haperture_keyword) *
                exr.metadata('input/height') / exr.metadata('input/width'))
            kt = cam['translate']
            kt.setAnimated(0, view)
            cam_aniX = cam['translate'].animations(view)[0]
            cam_aniX.setKey(cur_frame, translate("x", exr, cur_frame, view))
            kt.setAnimated(1, view)
            cam_aniY = cam['translate'].animations(view)[1]
            cam_aniY.setKey(cur_frame, translate("y", exr, cur_frame, view))
            kt.setAnimated(2, view)
            cam_aniY = cam['translate'].animations(view)[2]
            cam_aniY.setKey(cur_frame, translate("z", exr, cur_frame, view))
            kr = cam['rotate']
            kr.setAnimated(0, view)
            cam_aniX = cam['rotate'].animations(view)[0]
            cam_aniX.setKey(cur_frame, rotation("x", exr, cur_frame, view))
            kr.setAnimated(1, view)
            cam_aniY = cam['rotate'].animations(view)[1]
            cam_aniY.setKey(cur_frame, rotation("y", exr, cur_frame, view))
            kr.setAnimated(2, view)
            cam_aniY = cam['rotate'].animations(view)[2]
            cam_aniY.setKey(cur_frame, rotation("z", exr, cur_frame, view))
            task.setProgress(int(cur_frame / last_frame * 100))
Ejemplo n.º 37
0
def MNE_ProjectorCam():

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

        #get selected camera
        cam = nuke.selectedNode()

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

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

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

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

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

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

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

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

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

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

                #link all values (and add the expression)

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

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

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

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

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

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

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

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

                else:

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

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

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

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

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

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

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

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

        else:
            nuke.message("The node you selected isn't a camera.")
    else:
        nuke.message("Please select a camera node.")
Ejemplo n.º 38
0
    def __init__(self, node = True, name = ''):
        super ( hotboxCenter ,self ).__init__()

        self.node = node

        nodeColor = '#525252'
        textColor = '#eeeeee'

        selectedNodes = nuke.selectedNodes()

        if node:

            #if no node selected
            if len(selectedNodes) == 0:
                name = 'W_hotbox'
                nodeColorRGB = interface2rgb(640034559)

            #if node(s) selected
            else:
                name = nuke.selectedNode().name()
                nodeColorRGB = interface2rgb(getTileColor())

            if preferencesNode.knob('hotboxColorCenter').value():
                nodeColor = rgb2hex(nodeColorRGB)

                nodeColorHSV = colorsys.rgb_to_hsv(nodeColorRGB[0],nodeColorRGB[1],nodeColorRGB[2])

                if nodeColorHSV[2] > 0.7 and nodeColorHSV[1] < 0.4:
                    textColor = '#262626'

            width = 115
            height = 60


            if (len(set([i.Class() for i in selectedNodes]))) > 1:
                name = 'Selection'

        else:

            name = open(name + '/_name.json').read()
            nodeColor = getSelectionColor()

            width = 105
            height = 35

        self.setText(name)

        self.setAlignment(QtCore.Qt.AlignCenter)

        self.setFixedWidth(width)
        self.setFixedHeight(height)

        #resize font based on length of name
        fontSize = max(5,(13-(max(0,(len(name) - 11))/2)))
        font = QtGui.QFont(preferencesNode.knob('UIFont').value(), fontSize)
        self.setFont(font)

        self.setStyleSheet("""
                border: 1px solid black;
                color:%s;
                background:%s""" %(textColor, nodeColor))

        self.setSelectionStatus(True)
Ejemplo n.º 39
0
def Axis_My():
    import nuke
    nuke.nodePaste('H:/.nuke/GeneralSetups/AxisMy.nk')
    n = nuke.selectedNode()
    nuke.show(n)
Ejemplo n.º 40
0
def autoCrop_MB():
    #Check if a node is selected.
    try:
        n = nuke.selectedNode()
        nodeClass = n.Class()
    except:
        n = 0

    #Run if statement based on above try statement.
    if n == 0:
        print nuke.message('Please selected a node to run autoCrop_MB on...')
    else:
        #Check how many nodes are selected.
        numberOfNodes = len(nuke.selectedNodes())

        #Convert the int to a str.
        numberOfNodesInt = str(numberOfNodes)

    #Get channels from stream and sort so alpha is at the top.
    channelL = n.channels()
    channelS = channelL.sort()

    #Convert list to a string and add space.
    channelS = ' '.join(channelL)

    if nodeClass == 'Read':
        range = 'input' + ' ' + 'global' + ' ' + 'custom'
    else:
        range = 'global' + ' ' + 'custom'

    #Create and execute panel.
    p = nuke.Panel('autoCrop_MB v3.5')
    p.addEnumerationPulldown('frame range', range)
    p.addSingleLineInput('custom start', '')
    p.addSingleLineInput('custom end', '')
    p.addEnumerationPulldown('layer', channelS)
    p.addBooleanCheckBox('crop to format', False)
    p.show()

    increment = int('1')
    layersForCrop = p.value('layer')
    #Add quotation marks to layers variables.
    layersToAnalysis = '\"' + layersForCrop + '\"'

    #Work out the frame range wanted.
    if p.value('frame range') == 'custom':
        startFrame = int(p.value('custom start'))
        endFrame = int(p.value('custom end'))
    else:
        if p.value('frame range') == 'input':
            startFrame = n.knob('first').getValue()
            endFrame = n.knob('last').getValue()
        else:
            root = nuke.root()
            startFrame = int(root.knob("first_frame").value())
            endFrame = int(root.knob("last_frame").value())

#Reset variables.

    first = startFrame
    last = endFrame
    inc = increment
    layer = layersToAnalysis

    #Run autocrop in curve tool.  Taken from The Foundry's nukescripts/crop.py

    # Remember original set of selected nodes...we'll need this
    original_nodes = nuke.selectedNodes()

    # Deselect everything so we can add CurveTool nodes
    all_nodes = nuke.allNodes()
    for i in all_nodes:
        i.knob("selected").setValue(False)

    for i in original_nodes:
        # Reselect originally selected nodes and create a CurveTool node,
        # which will automatically connect to the last selected.
        i.knob("selected").setValue(True)
        #Check if user wants to analysis outside the format.
        if p.value('crop to format') == True:
            autocropper = nuke.createNode(
                "CurveTool",
                '''operation 0 ROI {0 0 input.width input.height} Layer %s label "Processing Crop..." selected true'''
                % (str(layer), ), False)
        else:
            autocropper = nuke.createNode(
                "CurveTool",
                '''operation 0 ROI {input.bbox.x input.bbox.y input.bbox.r input.bbox.t} Layer %s label "Processing Crop..." selected true'''
                % (str(layer), ), False)

    # Execute the CurveTool node thru all the frames
    nuke.executeMultiple([
        autocropper,
    ], ([first, last, inc], ))

    # select the curvewriter
    autocropper.knob("selected").setValue(True)

    # add crop node
    cropnode = nuke.createNode("Crop", "label AutoCrop", False)

    # put the new data from the autocrop into the new crop
    cropbox = cropnode.knob("box")
    autocropbox = autocropper.knob("autocropdata")
    cropbox.copyAnimations(autocropbox.animations())

    # turn on the animated flag
    cropnode.knob("indicators").setValue(1)

    # deselect everything
    all_nodes = nuke.allNodes()
    for j in all_nodes:
        j.knob("selected").setValue(False)

    # select the curvewriter and delete it
    autocropper.knob("selected").setValue(True)

    # delete the autocropper to make it all clean
    #nodes.node_delete()
    nuke.delete(autocropper)

    # deselect everything
    all_nodes = nuke.allNodes()
    for j in all_nodes:
        j.knob("selected").setValue(False)

    # select the new crop
    cropnode.knob("selected").setValue(True)

    # place it in a nice spot
    nuke.autoplace(cropnode)

    # De-Select it
    cropnode.knob("selected").setValue(False)