Пример #1
0
    def __init__(self):
        nukescripts.PythonPanel.__init__(self, 'DiskCache',
                                         'uk.co.thefoundry.DiskCache')

        # CREATE KNOBS
        self.diskCachePrefText = nuke.Text_Knob('disk_cache_pref_GB',
                                                'Disk cache limit:')
        self.addKnob(self.diskCachePrefText)
        self.diskCachePrefText.setValue('?GB')
        self.diskCachePercUsed = nuke.Double_Knob('disk_cache_pref_GB',
                                                  '% used:')
        self.addKnob(self.diskCachePercUsed)
        self.diskCachePercUsed.setValue(50)
        self.diskCachePercUsed.setRange(0, 100)
        self.diskCachePercUsed.setEnabled(False)

        totalCacheGB = nuke.toNode('preferences').knob('diskCacheGB').value()

        self.diskCachePrefText.setValue(str(totalCacheGB) + 'GB')

        # Check if Major Version is 6 or later...
        if nuke.env['NukeVersionMajor'] >= 6:
            self.paintCachePrefText = nuke.Text_Knob('paint_cache_pref_GB',
                                                     'Paint cache limit:')
            self.addKnob(self.paintCachePrefText)
            self.paintCachePrefText.setValue('?GB')
            self.paintCachePercUsed = nuke.Double_Knob('paint_cache_pref_GB',
                                                       '% used:')
            self.addKnob(self.paintCachePercUsed)
            self.paintCachePercUsed.setValue(50)
            self.paintCachePercUsed.setRange(0, 100)
            self.paintCachePercUsed.setEnabled(False)
            self.paintCachePercUsed.setFlag(0x00002000)

            paintCacheGB = nuke.toNode('preferences').knob(
                'PaintCacheGB').value()
            self.paintCachePrefText.setValue(str(paintCacheGB) + 'GB')

        # Update Cache usage button
        self.updateButton = nuke.Script_Knob('update', 'Update')
        self.addKnob(self.updateButton)

        # Clear DiskCacheButton
        self.clearCacheButton = nuke.Script_Knob('clearCache',
                                                 'Clear Disk Cache')
        self.addKnob(self.clearCacheButton)

        self.addKnob(nuke.Text_Knob('', ''))

        # Clear Buffer Button
        self.clearBuffers = nuke.Script_Knob('clearBuffers', 'Clear Buffers')
        self.addKnob(self.clearBuffers)

        self.bufferReport = nuke.nuke.Multiline_Eval_String_Knob(
            "bufferReport", "Buffer Report")
        self.addKnob(self.bufferReport)
        self.bufferReport.setValue(str(nukescripts.cache_report(str())))

        # Initially populate the Sliders...
        updateSliders(self)
Пример #2
0
 def __init__(self):
     super(WatermarkControlPanel, self).__init__('Watermark Control')
     self.setMinimumSize(600, 260)
     self.sourceKnob = nuke.File_Knob('file', 'Open:')
     self.formatKnob = nuke.Format_Knob('format', 'Format:')
     self.outputKnob = nuke.File_Knob('file', 'Save:')
     self.addKnob(self.sourceKnob)
     self.addKnob(self.formatKnob)
     self.addKnob(self.outputKnob)
     self.formatKnob.setValue('HD_720')
     self.addSourceKnob = nuke.PyScript_Knob('add', 'Add')
     self.addKnob(self.addSourceKnob)
     self.watermarkType = nuke.Enumeration_Knob('type', 'Type:',
                                                ['Text', 'Image'])
     self.watermarkText = nuke.String_Knob('text', 'Text:')
     self.watermarkImage = nuke.File_Knob('image', 'Image:')
     self.watermarkNum = nuke.Enumeration_Knob(
         'num', 'Number:', ['1   ', '2   ', '3   ', '4   ', '6   ', '9   '])
     self.watermarkCreate = nuke.PyScript_Knob('create', 'Create')
     self.watermarkRotate = nuke.Double_Knob('rotate', 'Rotate:')
     self.watermarkScale = nuke.Double_Knob('scale', 'Scale:')
     self.watermarkOpacity = nuke.Double_Knob('opacity', 'Opacity:')
     self.watermarkRotate.setRange(-180, 180)
     self.watermarkOpacity.setDefaultValue([1, 1])
     self.watermarkScale.setRange(0.3, 1.5)
     self.watermarkScale.setDefaultValue([1, 1])
     self.addKnob(self.watermarkType)
     self.addKnob(self.watermarkText)
     self.addKnob(self.watermarkImage)
     self.addKnob(self.watermarkNum)
     self.addKnob(self.watermarkCreate)
     self.addKnob(self.watermarkRotate)
     self.addKnob(self.watermarkScale)
     self.addKnob(self.watermarkOpacity)
     self.controller = WatermarkController(self)
Пример #3
0
def preferencesCreatedCallback():
    p = nuke.toNode('preferences')
    
    #Setup J_Ops prefs knobs if they don't exist.
    try:
        jopsKnobsPresent = p["J_Ops"]
    except (SyntaxError, NameError):
        k = nuke.Tab_Knob("J_Ops")
        k.setFlag(nuke.ALWAYS_SAVE)
        p.addKnob(k)

        v = nuke.Double_Knob("j_ops_ver", "j_ops_ver")
        v.setFlag(nuke.ALWAYS_SAVE)
        v.setFlag(nuke.INVISIBLE)
        v.setValue(2.0101)
        p.addKnob(v)
        
        k = nuke.Boolean_Knob("j_ops_enable_drop", "Improved drag and drop")
        k.setFlag(nuke.ALWAYS_SAVE)
        k.setFlag(nuke.STARTLINE)
        k.setValue(1.0)
        k.setTooltip("Enable/disable a somewhat improved drag and drop behaviour. Requires Nuke restart to take effect. Adds creation of geo, camera, light and vectorfield nodes based on incoming file extensions, as well as support for sequences when dropping folders onto DAG.")
        p.addKnob(k)

        k = nuke.Boolean_Knob("j_ops_enable_bookmark", "DAG bookmarks")
        k.setFlag(nuke.ALWAYS_SAVE)
        k.setFlag(nuke.STARTLINE)
        k.setValue(1.0)
        k.setTooltip("Enable/disable DAG bookmarks, allowing storing and recalling of particular DAG locations and zoom settings, for easy navigation around a script. Requires Nuke restart to take effect. Adds Python-DAG Bookmarks menu to J_Ops toolbar, offering access via mouse, tab menu, or hotkeys.")
        p.addKnob(k)

        k = nuke.Text_Knob("j_ops_dropdivider_label", "Drag And Drop")
        k.setFlag(nuke.ALWAYS_SAVE)
        p.addKnob(k)

        k = nuke.Boolean_Knob("j_ops_drop_recurse", "Recurse directories")
        k.setFlag(nuke.ALWAYS_SAVE)
        k.setValue(1.0)
        k.setTooltip("Enable/disable recursion into directories dropped on DAG. When enabled will result in entire directory structure being imported into DAG, when disabled only the directory dropped will be imported (ie none of its sub directories)")
        p.addKnob(k)
        
    #Check for preference setting, and if drop enabled add its callback/
    dropEnabled = False
    try:
        dropEnabled = nuke.toNode('preferences')["j_ops_enable_drop"].getValue()
    except (SyntaxError, NameError):
        pass

    if dropEnabled == True:
        nukescripts.drop.addDropDataCallback(jopsDropHandler)

    #Check for preference setting, and if drop enabled add its callback/
    bookmarkEnabled = False
    try:
        bookmarkEnabled = nuke.toNode('preferences')["j_ops_enable_bookmark"].getValue()
    except (SyntaxError, NameError):
        pass

    if bookmarkEnabled == True:
        jopsBookmarkAddMenus()
Пример #4
0
def getExprThis():

    p = nuke.Panel('rotate Center')
    p.addSingleLineInput("Node_Name:", nodeName)
    p.addSingleLineInput("Knob_Name:", knobName)
    result = p.show()
    nameType = p.value("Node_Name:")
    KnobName2 = p.value("Knob_Name:")
    nameType2 = nameType
    KnobName3 = KnobName2

    firstExpr = str('%s.%s' % (nameType2, KnobName3))
    getExprX = '(((%s) - width/4) * 2) + ((%s - (((%s) - width/4) * 2)) * intensity)' % (
        firstExpr, firstExpr, firstExpr)
    getExprY = '(((%s) - height/4) * 2) + ((%s - (((%s) - height/4) * 2)) * intensity)' % (
        firstExpr, firstExpr, firstExpr)

    newNoop = nuke.createNode('NoOp')
    newNoopTab = nuke.Tab_Knob('rotateCenter')
    newNoopXyKnob = nuke.XY_Knob('Expr')
    newNoopFloat = nuke.Double_Knob('intensity')
    newNoop.addKnob(newNoopTab)
    newNoop.addKnob(newNoopXyKnob)
    newNoop.addKnob(newNoopFloat)
    newNoopFloat.setValue(0)
    newNoopFloat.setRange(-1, 1)
    newNoopXyKnob.setExpression(getExprX, 0)
    newNoopXyKnob.setExpression(getExprY, 1)
Пример #5
0
    def __init__(self, node):

        #get reference of tKey knob
        knob_names = nuke.animations()
        knob_name_with_suffix = knob_names[0]
        #print"knob_name_with_suffix "
        #print knob_name_with_suffix
        knob_name = getKnobName(knob_name_with_suffix)
        k = nuke.thisNode()[knob_name]

        #so that our default frame range can be the length of it's keyframes
        tFirst = first_keyframe_location(k)
        tLast = last_keyframe_location(k)

        nukescripts.PythonPanel.__init__(
            self, 'Reduce keyframes in selected animation?')

        # CREATE KNOBS
        self.tFrameRange = nuke.String_Knob('tFrameRange', 'Frame Range',
                                            '%s-%s' % (tFirst, tLast))
        self.tErrorPercent = nuke.Double_Knob('tErrorPercent',
                                              'Error threshold (%)')
        self.tErrorPercent.setValue(10)
        self.tErrorPercent.setRange(1, 100)

        self.pcText = nuke.Text_Knob('%')
        self.pcText.clearFlag(nuke.STARTLINE)

        # ADD KNOBS
        for k in (self.tFrameRange, self.tErrorPercent):
            self.addKnob(k)
Пример #6
0
def preferencesCreatedCallback():
    p = nuke.toNode('preferences')

    #Setup J_Ops prefs knobs if they don't exist.
    try:
        jopsKnobsPresent = p["J_Ops"]
    except (SyntaxError, NameError):
        k = nuke.Tab_Knob("J_Ops")
        k.setFlag(nuke.ALWAYS_SAVE)
        p.addKnob(k)

        v = nuke.Double_Knob("j_ops_ver", "j_ops_ver")
        v.setFlag(nuke.ALWAYS_SAVE)
        v.setFlag(nuke.INVISIBLE)
        v.setValue(2.0101)
        p.addKnob(v)

        k = nuke.Boolean_Knob("j_ops_enable_drop", "Improved drag and drop")
        k.setFlag(nuke.ALWAYS_SAVE)
        k.setFlag(nuke.STARTLINE)
        k.setValue(1.0)
        k.setTooltip(
            "Enable/disable a somewhat improved drag and drop behaviour. Requires Nuke restart to take effect. Adds creation of geo, camera, light and vectorfield nodes based on incoming file extensions, as well as support for sequences when dropping folders onto DAG. Warning: does not observe hash vs regex file path expression, due to Nuke python functions ignoring it."
        )
        p.addKnob(k)

        k = nuke.Text_Knob("j_ops_dropdivider_label", "Drag And Drop")
        k.setFlag(nuke.ALWAYS_SAVE)
        p.addKnob(k)

        k = nuke.Boolean_Knob("j_ops_drop_recurse", "Recurse directories")
        k.setFlag(nuke.ALWAYS_SAVE)
        k.setValue(1.0)
        k.setTooltip(
            "Enable/disable recursion into directories dropped on DAG. When enabled will result in entire directory structure being imported into DAG, when disabled only the directory dropped will be imported (ie none of its sub directories)"
        )
        p.addKnob(k)

        #Knobs created. Hide obselete ones, update ver
        #2.1
        try:
            p["j_ops_ver"].setValue(2.0201)
            try:
                p["j_ops_enable_bookmark"].setFlag(nuke.INVISIBLE)
            except Exception:
                pass
        except Exception:
            pass

    #Check for preference setting, and if drop enabled add its callback/
    dropEnabled = False
    try:
        dropEnabled = nuke.toNode(
            'preferences')["j_ops_enable_drop"].getValue()
    except (SyntaxError, NameError):
        pass

    if dropEnabled == True:
        nukescripts.drop.addDropDataCallback(jopsDropHandler)
Пример #7
0
def forEach():
    forbidden = ['RotoPaint', 'Roto']

    for n in nuke.selectedNodes():
        feMsg = 'Nodes from type ' + n.Class(
        ) + ' are not supported yet. Please remove them from the selection before creating the ForEach node.'
        if n.Class() in forbidden:
            nuke.message(feMsg)
            return False

    feGroup = nuke.collapseToGroup()
    feGroup.setName("forEach")

    for n in feGroup.nodes():
        n.setSelected(False)
    nuke.allNodes("Input", feGroup)[0].setSelected(True)

    feTab = feGroup.addKnob(nuke.Tab_Knob("forEach"))
    feGroup.addKnob(nuke.Int_Knob("n_inputs", "number of inputs"))
    feGroup.addKnob(nuke.Boolean_Knob("manual", "manual loop"))
    feGroup.addKnob(nuke.Int_Knob("init", "from:"))
    feGroup.addKnob(nuke.Int_Knob("end", "to:"))
    feGroup['n_inputs'].setValue(1)
    feGroup['n_inputs'].setTooltip(
        "determines the number of inputs (arrows) the node has got.")
    feGroup["manual"].setTooltip(
        "If in manual mode forEach will run from init to end.")
    feGroup["init"].setTooltip(
        "The init value of the loop. In pseudocode, this would correspond to for(i=init; i<=end; i++)"
    )
    feGroup["end"].setTooltip(
        "The end value of the loop. In pseudocode, this would correspond to for(i=init; i<=end; i++)"
    )
    feGroup["end"].setValue(10)
    feGroup["manual"].setFlag(nuke.STARTLINE)
    feGroup["init"].clearFlag(nuke.STARTLINE)
    feGroup["init"].setEnabled(False)
    feGroup["end"].clearFlag(nuke.STARTLINE)
    feGroup["end"].setEnabled(False)
    feGroup.knob("knobChanged").setValue(
        "with nuke.thisNode():\n    knob = nuke.thisKnob();\n    if(knob.name() == 'n_inputs'):\n        n_inps = len(nuke.allNodes('Input'));\n        n_knob = int(float(knob.value()))-1;\n\n        if n_knob != n_inps:\n            for i in range(n_inps-1, n_knob, cmp(n_knob, n_inps)):\n                if(n_inps < n_knob):\n                    nuke.nodes.Input();\n                elif n_knob > -1:\n                    nuke.delete(nuke.allNodes('Input')[0]);\n    elif(knob.name() == 'manual'):\n        nuke.thisNode()['init'].setEnabled(knob.value());\n        nuke.thisNode()['end'].setEnabled(knob.value());"
    )

    feGroup.addKnob(nuke.PyScript_Knob("run_btn", "explode loop"))
    feGroup['run_btn'].setTooltip(
        "transforms the forEach group into clones created by the loop.")
    feGroup['run_btn'].setCommand(
        "from types import *\n\ndef is_numeric(n):\n    try: \n        float(n);\n        return True;\n    except TypeError:\n        return False;\n\nfeGroup = nuke.thisNode();\nfePadding = feGroup.knob('padd').getValue();\nfeCY = int(feGroup.ypos() + feGroup.screenHeight()/2);\nfeCX = int(feGroup.xpos() + feGroup.screenWidth()/2);\nfeW = 0; feH = 0;\nfe_horiz = (feGroup.knob('layout').value() == 'horizontal');\n\nfe_manual = feGroup['manual'].value();\n\nfeInputs_num = feGroup.inputs() if not fe_manual else (int(feGroup['end'].value()) - int(feGroup['init'].value()));\nfeInputs = feGroup.dependencies();\nfeInputs.sort(lambda a,b: cmp(a.xpos() if fe_horiz else a.ypos(), b.xpos() if fe_horiz else b.ypos()));\n\nif fe_manual: feInputs += [fakeInp for fakeInp in xrange(feInputs_num - len(feInputs))];\n\n#expand group:\nfeGroup = feGroup.expand();\n\n#create a clone for every input\nfor i, feInput in enumerate(feInputs):\n    if i>0: nuke.cloneSelected();\n\n    feGroup = nuke.selectedNodes();\n\n    feEach = nuke.nodes.NoOp();\n    feEach.setName('each');\n    \n    feI = nuke.String_Knob('i', 'instance #');\n    feEach.addKnob(feI);\n    feI.setValue(str(i));\n    feI.setTooltip('Use [python {forEach_i()}] inside an expression of a node created by the forEach node to access the iterator of the for loop (i). For this to work you need to keep the each-nodes.');\n    feI.setEnabled(False);\n    \n    # find first node:\n    for feC in feGroup:\n        if feC.isSelected():\n            feClone = feC;\n        else:\n            break;\n    \n    if feClone.maxInputs > 0: feClone.setInput(0, feEach);\n\n    if not fe_manual or not is_numeric(feInput): feEach.setInput(0, feInput);\n    if fe_horiz: \n        feEach.setYpos(feCY);\n    else:\n        feEach.setXpos(feCX);\n\n    feEach.setSelected(True);\n    feGroup = nuke.selectedNodes();\n    \n    for j,node in enumerate(feGroup):       #walk thru all nodes within & position\n        if fe_horiz:\n            feW = max(feW, node.screenWidth() + fePadding);\n        else:\n            feH = max(feH, node.screenHeight() + fePadding);\n\n        if fe_horiz: \n            node.setXpos(int(feCX - feW * (feInputs_num/2) + feW * i));\n        else: \n            node.setYpos(int(feCY - feH * (feInputs_num/2) + feH * i));\n    feEach.setYpos(feClone.ypos()-feClone.screenHeight()-feEach.screenHeight()-40);\n    feEach.setSelected(False);\n\n#clean up\nnuke.selectAll();\nnuke.invertSelection();\n\n#i-function\ndef forEach_i():\n    n = nuke.thisNode();\n    if n.name() != 'Root':\n        while (n.Class() != 'NoOp' or not n.name().startswith('each')) and len(n.dependencies()) > 0:\n            n = n.dependencies()[0];\n        return int(n['i'].value()) if n.knob('i') != None else -1;\n    else:\n        return -1;"
    )
    feGroup['run_btn'].setFlag(nuke.STARTLINE)
    feGroup.addKnob(nuke.Tab_Knob("display", "display options"))
    feGroup.addKnob(
        nuke.Enumeration_Knob("layout", "preferred layout",
                              ["horizontal", "vertical"]))
    feGroup.addKnob(nuke.Double_Knob("padd", "padding"))
    feGroup['padd'].setTooltip("determines the space between branches.")
    feGroup['padd'].setValue(300)
    return True
Пример #8
0
        def __init__(self, allcdl):
            super(_SelectCCCIDPanel, self).__init__()
            self.available = {}
            for cur in allcdl:
                self.available[cur.getID()] = cur

            self.addKnob(nuke.Enumeration_Knob("cccid", "cccid", self.available.keys()))
            self.addKnob(nuke.Text_Knob("divider"))
            self.addKnob(nuke.Color_Knob("slope"))
            self.addKnob(nuke.Color_Knob("offset"))
            self.addKnob(nuke.Color_Knob("power"))
            self.addKnob(nuke.Double_Knob("saturation"))
Пример #9
0
    def showModalDialog(self, parser):
        """Called to display the dialogue to the user."""

        self.parser = parser

        self.cdlcorrectionid = nuke.Enumeration_Knob(
            "cdlcorrectionid", "ID",
            sorted(self.parser.cdlcorrectionvalues.keys()))
        self.addKnob(self.cdlcorrectionid)

        self.dividerone = nuke.Text_Knob("dividerone", "")
        self.addKnob(self.dividerone)

        self.cdlcorrectiondesc = nuke.Multiline_Eval_String_Knob(
            "cdlcorrectiondesc", "Description", "")
        self.addKnob(self.cdlcorrectiondesc)
        self.cdlcorrectiondesc.setFlag(nuke.DISABLED)

        self.dividertwo = nuke.Text_Knob("dividertwo", "")
        self.addKnob(self.dividertwo)

        self.extrefsearchpath = nuke.Enumeration_Knob("extrefsearchpath", "Ref Search", \
                                    ["Same Name, Same Dir", "Any Name, Same Dir", "Specified"])
        self.addKnob(self.extrefsearchpath)

        self.extrefpath = nuke.File_Knob("extrefpath", "Ref Path")
        self.addKnob(self.extrefpath)

        self.dividerthree = nuke.Text_Knob("dividerthree", "")
        self.addKnob(self.dividerthree)

        self.cdloffset = nuke.Color_Knob("cdloffset", "Offset")
        self.addKnob(self.cdloffset)
        self.cdloffset.setFlag(nuke.DISABLED)

        self.cdlslope = nuke.Color_Knob("cdlslope", "Slope")
        self.addKnob(self.cdlslope)
        self.cdlslope.setFlag(nuke.DISABLED)

        self.cdlpower = nuke.Color_Knob("cdlpower", "Power")
        self.addKnob(self.cdlpower)
        self.cdlpower.setFlag(nuke.DISABLED)

        self.cdlsaturation = nuke.Double_Knob("cdlsaturation", "Saturation")
        self.addKnob(self.cdlsaturation)
        self.cdlsaturation.setFlag(nuke.DISABLED)

        self.dividerfour = nuke.Text_Knob("dividerfour", "")
        self.addKnob(self.dividerfour)

        self.updateDesc()
        return nukescripts.PythonPanel.showModalDialog(
            self), self.cdlcorrectionid.value()
Пример #10
0
def scatterObjects():
    '''
    Places an object on each selected vertex. The new Scene node gets user knobs to control the new objects.
    args:
        obj  -  class of object to scatter (default = Card2)
    '''
    # pop up a panel to ask for the desired object type
    # the dictionary maps the name in the panel to the actual class used
    typeDict = dict(Axis='Axis',
                    Card='Card2',
                    Sphere='Sphere',
                    Cylinder='Cylinder',
                    Cube='Cube')

    # create the initial panel and give it a title
    p = nuke.Panel('Pick object type to scatter')

    # add a drop down list with the dictionary's keys as choices
    p.addEnumerationPulldown('object', ' '.join(typeDict.keys()))

    # adjust the panel's width a bit
    p.setWidth(250)

    # if the user confirms the dialogsave the choice for later, otherwise do nothing
    if p.show():
        objType = typeDict[p.value('object')]
    else:
        return

    vsel = nukescripts.snap3d.getSelection()
    sc = nuke.nodes.Scene()
    # add user knobs to control new nodes:
    offsetKnob = nuke.XYZ_Knob('offset')
    sc.addKnob(offsetKnob)
    scaleKnob = nuke.Double_Knob('scale')
    scaleKnob.setValue(1)
    sc.addKnob(scaleKnob)

    for i, v in enumerate(vsel):
        obj = eval('nuke.nodes.%s()' % objType)
        # assign expressions to link to scene node's user knobs
        obj['translate'].setExpression(
            '%s + %s.offset' % (v.position.x, sc.name()), 0)
        obj['translate'].setExpression(
            '%s + %s.offset' % (v.position.y, sc.name()), 1)
        obj['translate'].setExpression(
            '%s + %s.offset' % (v.position.z, sc.name()), 2)
        obj['uniform_scale'].setExpression('%s.scale' % sc.name())
        sc.setInput(i, obj)

    sc.setInput(i + 1, nuke.thisNode())
    nuke.connectViewer(1, sc)
 def __init__(self, nodes):
     '''
     Adjust nodes' position and scale
     args:
         nodes -  list of nodes to control. nodes in thi list have to have a 3D transform knob
     '''
     nukescripts.PythonPanel.__init__(self, 'Adjust Scattered Objects')
     self.nodes = nodes
     self.origPos = dict([(n, n['translate'].value()) for n in nodes])
     self.offset = nuke.XYZ_Knob('offset', 'offset')
     self.scale = nuke.Double_Knob('uniform_scale', 'uniform scale')
     self.scale.setValue(1)
     self.addKnob(self.offset)
     self.addKnob(self.scale)
Пример #12
0
def cropOverscan():

    n = nuke.thisNode()
    if 'Overscan' not in n.knobs():
        overscan_tab = nuke.Tab_Knob('Overscan')
        overscanKnob = nuke.Double_Knob('overscan', 'overscan')
        onlyHorizontalKnob = nuke.Boolean_Knob('onlyH', 'Only Horizontal')
        overscanKnob.setRange(0, 100)
        overscanKnob.setValue(40)
        for k in (overscan_tab, overscanKnob, onlyHorizontalKnob):
            n.addKnob(k)
        onlyHorizontalKnob.clearFlag(nuke.STARTLINE)
        n['box'].setExpression('-overscan', 0)
        n['box'].setExpression('onlyH == 1 ? 0 : -overscan', 1)
        n['box'].setExpression('width+overscan', 2)
        n['box'].setExpression('onlyH == 1 ? height : height + overscan', 3)
Пример #13
0
def auto_contact_sheet(inputs=[], offset=move.align_offset):
    n = nuke.nodes.ContactSheet(roworder='TopBottom', gap=0)
    scale_knob = nuke.Double_Knob('scale', 'Scale:')
    scale_knob.setValue(0.5)
    n.addKnob(scale_knob)
    n['width'].setExpression('input.width * columns * scale')
    n['height'].setExpression('input.height * rows * scale')
    n['rows'].setExpression('ceil(inputs / columns)')
    n['columns'].setValue(min((7, len(inputs))))
    for i, inp in enumerate(inputs):
        n.setInput(i, inp)
    input_group = pos.PositionGroup(inputs)
    cen_x, cen_y = input_group.center
    move.center_to(n, cen_x, cen_y)
    print input_group.center
    move.nudge(n, x=0, y=((input_group.height / 2) + offset))
    return n
Пример #14
0
            def link_to_bezier(selected_roto, selected_bezier):
                """
                Node bezier animation UI and expression setting.
                :param selected_roto: Roto node name
                :type selected_roto: str
                :param selected_bezier: Bezier name
                :type selected_bezier: str
                :return: None
                :rtype: None
                """
                this_knob = nuke.thisKnob()
                this_node = nuke.thisNode()

                tab = nuke.Tab_Knob("BezierAnimation")
                slider = nuke.Double_Knob("bezier_animation", "Bezier Animation")
                slider.setTooltip("Animate along bezier shape from start to end.")
                this_node.addKnob(tab)
                this_node.addKnob(slider)

                x_expression = """
[python -execlocal {
try:
    shape = nuke.toNode('%s')['curves'].toElement('%s').evaluate(0, nuke.frame())
except:
    pass
ret = shape.getPoint(nuke.thisNode()['bezier_animation'].value()).x
}]
""" % (selected_roto, selected_bezier)

                y_expression = """
[python -execlocal {
try:
    shape = nuke.toNode('%s')['curves'].toElement('%s').evaluate(0, nuke.frame())
except:
    pass
ret = shape.getPoint(nuke.thisNode()['bezier_animation'].value()).y
}]
""" % (selected_roto, selected_bezier)

                this_knob.setExpression(x_expression, channel=0)
                this_knob.setExpression(y_expression, channel=1)
                try:
                    this_node["center"].setValue(0)
                except:
                    pass
Пример #15
0
        def __set(name, value):
            # in case the knob does not exist, creating it.
            if name not in nuke.Root().knobs():
                if isinstance(value, int):
                    targetKnob = nuke.Int_Knob(name)
                elif isinstance(value, bool):
                    targetKnob = nuke.Boolean_Knob(name)
                elif isinstance(value, float):
                    targetKnob = nuke.Double_Knob(name)
                else:
                    targetKnob = nuke.String_Knob(name)
                nuke.Root().addKnob(targetKnob)

            # replacing all escape to forward slashes
            if isinstance(value, basestring):
                value = value.replace("\\", "/")

            # updating knob value
            nuke.Root()[name].setValue(value)

            # updating tcl variable
            nuke.tcl('set {} "{}"'.format(name, value))
Пример #16
0
def panAndTile():

  #### error out if selected node is not a read ####
  read = nuke.selectedNode()
  if read.Class() != 'Read':
    nuke.message( "The selected node is not a read node" )
    return  
  curPos = (read['xpos'].value(), read['ypos'].value())
  
  #### Create knobs ####
  tabKnob = nuke.Tab_Knob('Panorama')
  focal = nuke.Double_Knob ( 'focal')
  haperture = nuke.Double_Knob ( 'haperture' )
  size = nuke.Double_Knob( 'size' )
  rotate = nuke.Double_Knob ( 'rotate' )
  tilt = nuke.Double_Knob( 'tilt' )
  turn = nuke.Enumeration_Knob( 'turn' , 'orientation', ('landscape', 'portrait'))
  
  ### set up sensible default values
  focal.setValue( 20 )
  focal.setRange(0, 100 )
  haperture.setValue( 36 )
  haperture.setRange( 0, 100 )
  size.setValue( 1 )
  size.setRange( 0,10000 )
  rotate.setValue( int( 360 / ( read['last'].value() - read['first'].value() + 1 ) ) )
  rotate.setRange( 0 , 360 )
  tilt.setValue( 30 )
  tilt.setRange( 0, 360 )
  turn.setValue( 1 )
  
  ####  create and add to scene node
  scene = nuke.nodes.Scene()
  
  for k in [tabKnob, focal, haperture, size, rotate, tilt, turn]:
    scene.addKnob( k )
    
  sceneExpr = 'parent.' + scene.name() + '.'
  
  ### loop through input images
  for i in range( read['first'].value(), read['last'].value() + 1 ):
    
    ### create frame hold
    frameHold = nuke.createNode( "FrameHold", inpanel = False )
    frameHold['postage_stamp'].setValue( True )
    frameHold['first_frame'].setValue( i )
    frameHold.setXYpos( int(curPos[0]+i*100 ), int(curPos[1]+100) )

    ### create card and set expressions
    card = nuke.createNode( "Card", inpanel = False ) 
    card['z'].setExpression( sceneExpr + 'size', 0 )
    card['lens_in_focal'].setExpression( sceneExpr + 'focal', 0 )
    card['lens_in_haperture'].setExpression( sceneExpr + 'haperture', 0 )
    
    card['rotate'].setExpression( sceneExpr + 'tilt', 0 )
    card['rotate'].setExpression( sceneExpr + 'rotate  * -' + str(i-1), 1 )
    card['rotate'].setExpression( sceneExpr + 'turn * 90' , 2 )
    card.setXYpos( int(curPos[0]+i*100), int(curPos[1]+200) )
    
    ### hook up nodes
    frameHold.setInput(0, read )
    card.setInput(0, frameHold )
    scene.setInput( i-1, card )
  scene.setXYpos( int(curPos[0]+(i*100/2)), int(curPos[1]+300) )
Пример #17
0
def doReduceKeyframes():

    p = doReduceKeyframesPanel(nuke.selectedNode())

    if p.showModalDialog():  #user did not hit cancel button

        undo = nuke.Undo()
        undo.begin("Reduce keyframes")

        tErrorPercent = p.tErrorPercent.value()

        if (tErrorPercent > 100):
            tErrorPercent = 100

        if (tErrorPercent < 0.000001):
            tErrorPercent = 0.000001

        #print "tErrorPercent " + str(tErrorPercent)

        tFrameRange = nuke.FrameRange(p.tFrameRange.value())
        tFirstFrame = tFrameRange.first()
        tLastFrame = tFrameRange.last()

        knob_names = nuke.animations(
        )  # Returns the animations names under this knob

        i = getKnobIndex(
        )  #find out if user only clicked on a single knob index, or the entire knob

        #print "knob index: " + str(i)

        j = 0  #index for knob

        for knob_name_with_suffix in knob_names:

            if (i > -1):
                j = i

            #print "for knob_name_with_suffix in knob_names:"

            knob_name = getKnobName(knob_name_with_suffix)

            # so that we can get at the knob object and do...
            k = nuke.thisNode()[knob_name]

            if (k.isAnimated(j)):

                tOriginalCurve = k.animation(j)

                tKeys = tOriginalCurve.keys()

                tOrigFirstFrame = tKeys[0].x

                tOrigLastFrame = tKeys[len(tKeys) - 1].x

                tOrigKeys = len(tOriginalCurve.keys())

                fErrorHeight = getCurveHeight(tOriginalCurve, tFirstFrame,
                                              tLastFrame)

                tErrorThreshold = fErrorHeight * (tErrorPercent / 100)

                #print "tErrorThreshold " + str(tErrorThreshold)

                if (tOrigKeys > 2):  #no point in reducing a straight line!

                    x = nuke.selectedNode()

                    #create a temp knob to copy new keyframes into

                    tempname = "temp_" + knob_name + str(j)

                    tTempKnob = nuke.Double_Knob(tempname)

                    tTempKnob.setAnimated()

                    tTempKnob.setValueAt(tOriginalCurve.evaluate(tFirstFrame),
                                         tFirstFrame)

                    tTempKnob.setValueAt(tOriginalCurve.evaluate(tLastFrame),
                                         tLastFrame)

                    tTempCurve = tTempKnob.animation(0)

                    #if we are only reducing keyframes on a smaller frame range, then copy the original keyframes into the other frames

                    if (tFirstFrame > tOrigFirstFrame) | (tLastFrame <
                                                          tOrigLastFrame):

                        tKeys = x[knob_name].animation(j).keys()

                        tCopyKeys = []

                        for tKey in tKeys:
                            if ((tKey.x < tFirstFrame) |
                                (tKey.x > tLastFrame)):
                                tCopyKeys.append(tKey)
                        tTempKnob.animation(0).addKey(tCopyKeys)

                    #do a quick check to see if 2 keyframes are enough
                    deltaH = (tLastFrame - tFirstFrame)
                    deltaV = (tTempKnob.getValueAt(tLastFrame) -
                              tTempKnob.getValueAt(tFirstFrame))
                    tMasterSlope = 90 - getAngle(deltaH, deltaV)
                    if (tMasterSlope < 0): tMasterSlope = tMasterSlope + 360

                    if (findErrorHeight(tOriginalCurve, tTempCurve,
                                        tFirstFrame, tLastFrame, tMasterSlope)
                            < tErrorThreshold):
                        print "Looks like this selection of frames was a straight line. Reduce the error threshold % if it isn't"
                    else:

                        #otherwise we run the keyframe reducing function on the selected frame range
                        recursion = findGreatestErrorFrame(
                            tOriginalCurve, tFirstFrame, tLastFrame,
                            tErrorThreshold, tTempKnob, tTempCurve, 0)

                    #copy our reduced keyframes from the temp knob back into our original knob
                    x[knob_name].copyAnimation(j, tTempKnob.animation(0))

                    #calculate how much we have reduced number of keyframes
                    tFinalKeys = len(x[knob_name].animation(j).keys())
                    tReductionPC = int(
                        (float(tFinalKeys) / float(tOrigKeys)) * 100)

                    print knob_name + "[" + str(j) + "] had " + str(
                        tOrigKeys) + " keys reduced to " + str(
                            tFinalKeys) + " keys (" + str(tReductionPC) + "%)"

            else:

                print "No animation found in " + knob_name + " index " + str(j)

            #break the loop if we are only running script on single knob index
            if (i > -1):
                break
            else:
                j = j + 1

        undo.end()
Пример #18
0
def makeCrowd(group):
    ''' Atists hits make crowd button and we make a crowd '''

    with group:
        # get a list of points we want to creat cards on
        points = []
        if group['useSelection'].value() and len(
                group['vertexStore'].value()) > 0:
            allPoints = retrieveSavedVertices(group)
            points = everyNthPointOfPoints(allPoints, group)
        else:
            allPoints = verticesFromInput(group)
            points = everyNthPointOfPoints(allPoints, group)

        cardWarningLevel = 500
        if len(points) > cardWarningLevel:
            if not nuke.ask(
                    'Are you sure you want to create %s cards? This may take a long time...'
                    % (len(points))):
                return

        #delete the old scene
        removePreviousScene(group)

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

        lookDot = nuke.toNode('lookDot')
        img1 = nuke.toNode('img1')
        lastXY = [img1['xpos'].value() - gridWidth, img1['ypos'].value()]
        lookDot.setYpos(int(lastXY[1] + gridHeight * 76))

        switchInputs = imageInputList(group)

        # make channels, channel strings are used later in node creation
        crowdRandomColorStr = 'crowdRandomColor'
        nuke.Layer(crowdRandomColorStr, ['red', 'green', 'blue'])

        crowdIDStr = 'crowdID'
        nuke.Layer(crowdIDStr, ['id', 'sprite'])
        '''
        crowdCharacterMaskStr = 'crowdCharacterMask'
        nuke.Layer( crowdCharacterMaskStr , ['alpha'] )
        '''

        crowdMirrorMaskStr = 'crowdMirrorMask'
        nuke.Layer(crowdMirrorMaskStr, ['alpha'])

        transformGeoList = []
        cardList = []
        whichInput = 0

        for i in range(len(points)):
            point = points[i]

            # make a switch to plug in the image inputs
            inputSwitch = nuke.createNode('Switch', inpanel=False)
            inputSwitch.setName('imgSwitch')
            inputSwitch['label'].setValue(
                'which: [value which]\nauto-generated')
            inputSwitch.setXpos(int(lastXY[0] + gridWidth))
            inputSwitch.setYpos(int(lastXY[1] + gridHeight * 20))

            for j in range(len(switchInputs)):
                inputSwitch.setInput(j, nuke.toNode(switchInputs[j]))

            # Input switch to chose what images appear on what cards
            # TODO: Make a a fucntion for Duplication radius
            inputFromDuplicationRadius = whichInput
            ifStepExpr = '[string match [value inputOrder] "Step"]?%s' % (
                whichInput)
            ifRandomExpr = '[string match [value inputOrder] "Random"]?'\
                'rint(random(%s+%s,1)*%s)' % ('parent.inputSeed', i, len(switchInputs)-1)
            inputSwitch['which'].setExpression(
                '%s:%s:%s' %
                (ifStepExpr, ifRandomExpr, str(inputFromDuplicationRadius)))
            whichInput = whichInput + 1
            if whichInput >= len(switchInputs):
                whichInput = 0
            '''
            # make the id channel
            idShuffle = nuke.createNode('Shuffle', inpanel = False)
            idShuffle.setName('aov_idShuffle')
            idShuffle['in'].setValue('none')
            idShuffle['out'].setValue(crowdIDStr)
            idShuffle['label'].setValue('([value out])\nauto-generated')
            idShuffle['disable'].setExpression('!parent.displayAOVs')
            idShuffle.setXpos(int(lastXY[0]+gridWidth))
            idShuffle.setYpos(int(lastXY[1]+gridHeight*30))

            # make the id mult
            idKnob = nuke.Int_Knob('ID','ID')
            idKnob.setValue(i)

            idMult = nuke.createNode('Multiply' ,inpanel = False)
            idMult.addKnob( idKnob )
            idMult.setName('aov_idMult')
            idMult['channels'].setValue(crowdIDStr)
            idMult['value'].setSingleValue(True)
            idMult['value'].setExpression('%s' % ('this.ID+1'))
            #idMult['maskChannelInput'].setValue('rgba.alpha')
            idMult['label'].setValue('auto-generated')
            idMult['disable'].setExpression('!parent.aov_id')
            idMult.setXpos(int(lastXY[0]+gridWidth))
            idMult.setYpos(int(lastXY[1]+gridHeight*32))
            '''

            # make the id expression
            idExpr = nuke.createNode('Expression', inpanel=False)
            idExpr.setName('aov_idExpr')
            idExpr['temp_name0'].setValue('id')
            idExpr['temp_expr0'].setValue(str(i))
            idExpr['temp_name1'].setValue('inp')
            idExpr['temp_expr1'].setValue('[value %s.which]' %
                                          inputSwitch.name())
            idExpr['channel0'].setValue(crowdIDStr)
            idExpr['channel0'].enableChannel(0, True)
            idExpr['channel0'].enableChannel(1, False)
            idExpr['channel0'].enableChannel(2, False)
            idExpr['expr0'].setValue('id*rgba.alpha')
            idExpr['channel1'].setValue(crowdIDStr)
            idExpr['channel1'].enableChannel(0, False)
            idExpr['channel1'].enableChannel(1, True)
            idExpr['channel1'].enableChannel(2, False)
            idExpr['expr1'].setValue('inp*rgba.alpha')
            idExpr['channel2'].setValue('none')
            idExpr['channel3'].setValue('none')
            idExpr['label'].setValue('auto-generated')
            idExpr['disable'].setExpression('!parent.displayAOVs')
            idExpr.setXpos(int(lastXY[0] + gridWidth))
            idExpr.setYpos(int(lastXY[1] + gridHeight * 30))

            # make the grade layer which shuffles in the alpha
            randomShuffle = nuke.createNode('Shuffle', inpanel=False)
            randomShuffle.setName('aov_randomShuffle')
            randomShuffle['in'].setValue('alpha')
            randomShuffle['out'].setValue(crowdRandomColorStr)
            randomShuffle['label'].setValue('([value out])\nauto-generated')
            randomShuffle['disable'].setExpression('!parent.displayAOVs')
            randomShuffle.setXpos(int(lastXY[0] + gridWidth))
            randomShuffle.setYpos(int(lastXY[1] + gridHeight * 40))

            # make the grade layer mult
            randomColorMult = nuke.createNode('Multiply', inpanel=False)
            randomColorMult.setName('aov_randomMult')
            randomColorMult['channels'].setValue(crowdRandomColorStr)
            randomColorMult['value'].setSingleValue(False)
            randomColorMult['value'].setExpression(
                'random(%s+%s,1)' % ('parent.aov_randomSeed', str(i + 0)), 0)
            randomColorMult['value'].setExpression(
                'random(%s+%s,1)' % ('parent.aov_randomSeed', str(i + 1)), 1)
            randomColorMult['value'].setExpression(
                'random(%s+%s,1)' % ('parent.aov_randomSeed', str(i + 2)), 2)
            randomColorMult['unpremult'].setValue('rgba.alpha')
            randomColorMult['label'].setValue('auto-generated')
            randomColorMult['disable'].setExpression('!parent.displayAOVs')
            randomColorMult.setXpos(int(lastXY[0] + gridWidth))
            randomColorMult.setYpos(int(lastXY[1] + gridHeight * 42))

            # make the character mask which can be used for lighting
            '''
            charMaskShuffle = nuke.createNode('Shuffle', inpanel = False)
            charMaskShuffle['in'].setValue('alpha')
            charMaskShuffle['out'].setValue(crowdCharacterMaskStr)
            charMaskShuffle['label'].setValue('([value out])\nauto-generated')
            charMaskShuffle.setXpos(int(lastXY[0]+gridWidth))
            charMaskShuffle.setYpos(int(lastXY[1]+gridHeight*40))
            '''

            # make the mirror mask which can be used for flipping AOVs
            mirrorMaskShuffle = nuke.createNode('Shuffle', inpanel=False)
            mirrorMaskShuffle.setName('aov_mirrorShuffle')
            mirrorMaskShuffle['in'].setValue('alpha')
            mirrorMaskShuffle['out'].setValue(crowdMirrorMaskStr)
            mirrorMaskShuffle['label'].setValue(
                '([value out])\nauto-generated')
            mirrorMaskShuffle['disable'].setExpression('!parent.displayAOVs')
            mirrorMaskShuffle.setXpos(int(lastXY[0] + gridWidth))
            mirrorMaskShuffle.setYpos(int(lastXY[1] + gridHeight * 50))

            # make the mirror for flopping random cards
            idKnob = nuke.Int_Knob('mirrorID', 'mirrorID')
            idKnob.setValue(i)

            flop = nuke.createNode('Mirror2', inpanel=False)
            flop.addKnob(idKnob)
            flop['flop'].setValue(True)
            flop['disable'].setExpression(
                'parent.mirror?random(this.mirrorID+parent.mirrorSeed,1)>0.5?1:0:1'
            )
            flop['label'].setValue('auto-generated')
            flop.setXpos(int(lastXY[0] + gridWidth))
            flop.setYpos(int(lastXY[1] + gridHeight * 52))

            # make the mirror mask mult which can be used for flipping AOVs
            mirrorMaskMult = nuke.createNode('Multiply', inpanel=False)
            mirrorMaskMult.setName('aov_mirrorMult')
            mirrorMaskMult['channels'].setValue(crowdMirrorMaskStr)
            mirrorMaskMult['value'].setValue(0)
            mirrorMaskMult['disable'].setExpression(
                'parent.displayAOVs?!input0.disable:1')
            mirrorMaskMult['label'].setValue('(auto-generated')
            mirrorMaskMult.setXpos(int(lastXY[0] + gridWidth))
            mirrorMaskMult.setYpos(int(lastXY[1] + gridHeight * 54))

            # make the time offset
            idKnob = nuke.Int_Knob('offsetID', 'offsetID')
            idKnob.setValue(i)

            timeOffset = nuke.createNode('TimeOffset', inpanel=False)
            timeOffset.addKnob(nuke.Tab_Knob('User'))
            timeOffset.addKnob(idKnob)
            timeOffsetRandomizeExpr = 'rint(random(parent.timeOffsetSeed+%s,1)*parent.timeOffset*2-parent.timeOffset)' % (
                'this.offsetID')
            timeOffsetStepExpr = 'parent.timeOffset?parent.timeOffsetStep*this.offsetID%abs(parent.timeOffset):0'
            timeOffset['time_offset'].setExpression(
                'parent.timeOffsetRandomize?%s:%s' %
                (timeOffsetRandomizeExpr, timeOffsetStepExpr))
            timeOffset['label'].setValue(
                '[value time_offset] frames\nauto-generated')
            timeOffset.setXpos(int(lastXY[0] + gridWidth))
            timeOffset.setYpos(int(lastXY[1] + gridHeight * 60))

            # make the card
            idKnob = nuke.Double_Knob('cardID', 'cardID')
            idKnob.setRange(0, 100)
            idOffsetKnob = nuke.Double_Knob('cardIDOffset', 'cardIDOffset')
            idOffsetKnob.setRange(0, 100)

            card = nuke.createNode('Card', inpanel=False)
            card.addKnob(nuke.Tab_Knob('User'))
            card.addKnob(idKnob)
            card.addKnob(idOffsetKnob)
            card['cardIDOffset'].setExpression('parent.displayPercentOffset+this.cardID<=100?'\
                'parent.displayPercentOffset+this.cardID:this.cardID-100+parent.displayPercentOffset')
            card['disable'].setExpression(
                '$gui?parent.displayPercentage<100?parent.displayPercentage>this.cardIDOffset?0:1:0:0'
            )
            card.setXpos(int(lastXY[0] + gridWidth))
            card.setYpos(int(lastXY[1] + gridHeight * 70))
            cardList.append(card)

            # make the transform geo
            transformGeo = nuke.createNode('TransformGeo', inpanel=False)
            transformGeo.setXpos(int(lastXY[0] + gridWidth))
            transformGeo.setYpos(int(lookDot['ypos'].value()))
            transformGeo.setInput(0, card)
            transformGeo.setInput(2, lookDot)
            transformGeo['translate'].setExpression('random(%s+%s,1)*parent.positionOffset(0)' \
                '-parent.positionOffset(0)/2+%s' % ('parent.positionOffsetXZseed',str(i+0),point[0]),0)
            transformGeo['translate'].setExpression('random(%s+%s,1)*parent.positionOffset(1)' \
                '-parent.positionOffset(1)/2+%s' % ('parent.positionOffsetYseed',str(i+1),point[1]),1)
            transformGeo['translate'].setExpression('random(%s+%s,1)*parent.positionOffset(2)' \
                '   -parent.positionOffset(2)/2+%s' % ('parent.positionOffsetXZseed',str(i+2),point[2]),2)
            transformGeo['pivot'].setExpression('parent.pivotOffset', 1)
            transformGeo['uniform_scale'].setExpression('parent.scale+random(%s+%s,1)*' \
                '(scaleVariation*parent.scale)-(scaleVariation*parent.scale)/2' % ('parent.scaleSeed', str(i)))
            transformGeo['look_axis'].setExpression('parent.look_axis')
            transformGeo['look_rotate_x'].setExpression('parent.look_rotate_x')
            transformGeo['look_rotate_y'].setExpression('parent.look_rotate_y')
            transformGeo['look_rotate_z'].setExpression('parent.look_rotate_z')
            transformGeo['look_strength'].setExpression('parent.look_strength')
            transformGeo['look_use_quaternions'].setExpression(
                'parent.look_use_quaternions')

            transformGeoList.append(transformGeo)

            lastXY = [lastXY[0] + gridWidth, lastXY[1]]

        # pipe up all the transform geos into the output scene
        scene = nuke.toNode('scene')
        for i in range(len(transformGeoList)):
            scene.setInput(i, transformGeoList[i])
        scene.setYpos(int(lookDot['ypos'].value() + gridHeight * 10))
        nuke.toNode('Output').setYpos(
            int(lookDot['ypos'].value() + gridHeight * 20))

        # set up the cards so that they can be culled by a percentage in the gui
        random.seed(int(group['vertexStep'].value()))
        random.shuffle(cardList)
        for i in range(0, len(cardList)):
            cardID = float(i) * 100 / len(cardList)
            cardList[i]['cardID'].setValue(cardID)

        # change the group label and let artist know how many cards were created
        group['label'].setValue('%s Cards' % (len(transformGeoList)))
def autoBackdrop():
    '''
    Automatically puts a backdrop behind the selected nodes.

    The backdrop will be just big enough to fit all the select nodes in,
    with room at the top for some text in a large font.
    '''
    sel = nuke.selectedNodes()
    forced = False

    # if nothing is selected
    if not sel:
        forced = True
        b = nuke.createNode('NoOp')
        sel.append(b)

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

    zOrder = 0
    selectedBackdropNodes = nuke.selectedNodes("BackdropNode")

    # if there are backdropNodes selected
    # put the new one immediately behind the farthest one
    if len(selectedBackdropNodes):
        zOrder = min([node.knob("z_order").value()
                      for node in selectedBackdropNodes]) - 1
    else:
        # otherwise (no backdrop in selection) find the nearest backdrop
        # if exists and set the new one in front of it
        nonSelectedBackdropNodes = nuke.allNodes("BackdropNode")
        for nonBackdrop in sel:
            for backdrop in nonSelectedBackdropNodes:
                if nodeIsInside(nonBackdrop, backdrop):
                    zOrder = max(zOrder, backdrop.knob("z_order").value() + 1)

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

    R, G, B = colorsys.hsv_to_rgb(random.random(),
                                  .1+random.random()*.15,
                                  .15 + random.random()*.15)

    n = nuke.nodes.BackdropNode(xpos=bdX, bdwidth=bdW, ypos=bdY,
                                bdheight=bdH,
                                tile_color=int('%02x%02x%02x%02x' % (R*255,
                                                                     G*255,
                                                                     B*255,
                                                                     255), 16),
                                note_font_size=50, z_order=zOrder)

    n.showControlPanel()

    # Buid all knobs for Backdrop
    tab = nuke.Tab_Knob('F_VFX', 'BackdropNode')
    text = nuke.Multiline_Eval_String_Knob('text', 'Text')
    position = nuke.Enumeration_Knob('position', '', ['Left', 'Center'])
    size = nuke.Double_Knob('font_size', 'Font Size') 
    size.setRange(10,100)
    space1 = nuke.Text_Knob('S01', ' ', ' ')
    space2 = nuke.Text_Knob('S02', ' ', ' ')

    grow = nuke.PyScript_Knob('grow', ' <img src="F_scalep.png">', "n=nuke.thisNode()\n\ndef grow(node=None,step=50):\n    try:\n        if not node:\n            n=nuke.selectedNode()\n        else:\n            n=node\n            n['xpos'].setValue(n['xpos'].getValue()-step)\n            n['ypos'].setValue(n['ypos'].getValue()-step)\n            n['bdwidth'].setValue(n['bdwidth'].getValue()+step*2)\n            n['bdheight'].setValue(n['bdheight'].getValue()+step*2)\n    except Exception,e:\n        print('Error:: %s' % e)\n\ngrow(n,50)")
    shrink = nuke.PyScript_Knob('shrink', ' <img src="F_scalem.png">', "n=nuke.thisNode()\n\ndef shrink(node=None,step=50):\n    try:\n        if not node:\n            n=nuke.selectedNode()\n        else:\n            n=node\n            n['xpos'].setValue(n['xpos'].getValue()+step)\n            n['ypos'].setValue(n['ypos'].getValue()+step)\n            n['bdwidth'].setValue(n['bdwidth'].getValue()-step*2)\n            n['bdheight'].setValue(n['bdheight'].getValue()-step*2)\n    except Exception,e:\n        print('Error:: %s' % e)\n\nshrink(n,50)")

    colorandom = nuke.PyScript_Knob('colorandom', ' <img src="ColorBars.png">', "import colorsys, random\nn=nuke.thisNode()\nR,G,B= colorsys.hsv_to_rgb(random.random(),.1+random.random()*.15,.15+random.random()*.15)\nn['tile_color'].setValue( int('%02x%02x%02x%02x' % (R*255,G*255,B*255,255), 16 ) )")

    red = nuke.PyScript_Knob('red', ' <img src="F_r.png">', "import colorsys\nn=nuke.thisNode()\nR,G,B= [0.0, 0.77, 0.8]\nR,G,B=colorsys.hsv_to_rgb(R,G,B)\nn['tile_color'].setValue( int('%02x%02x%02x%02x' % (R*255,G*255,B*255,255), 16 ))\n")
    orange = nuke.PyScript_Knob('orange', ' <img src="F_o.png">', "import colorsys\nn=nuke.thisNode()\nR,G,B= [0.1, 0.8, 0.8]\nR,G,B=colorsys.hsv_to_rgb(R,G,B)\nn['tile_color'].setValue( int('%02x%02x%02x%02x' % (R*255,G*255,B*255,255), 16 ))\n")
    yellow = nuke.PyScript_Knob('yellow', ' <img src="F_y.png">', "import colorsys\nn=nuke.thisNode()\nR,G,B= [0.16, 0.8, 0.8]\nR,G,B=colorsys.hsv_to_rgb(R,G,B)\nn['tile_color'].setValue( int('%02x%02x%02x%02x' % (R*255,G*255,B*255,255), 16 ))\n")
    green = nuke.PyScript_Knob('green', ' <img src="F_g.png">', "import colorsys\nn=nuke.thisNode()\nR,G,B= [0.33, 0.8, 0.7]\nR,G,B=colorsys.hsv_to_rgb(R,G,B)\nn['tile_color'].setValue( int('%02x%02x%02x%02x' % (R*255,G*255,B*255,255), 16 ))\n")
    cyan = nuke.PyScript_Knob('cyan', ' <img src="F_c.png">', "import colorsys\nn=nuke.thisNode()\nR,G,B= [0.46, 0.8, 0.7]\nR,G,B=colorsys.hsv_to_rgb(R,G,B)\nn['tile_color'].setValue( int('%02x%02x%02x%02x' % (R*255,G*255,B*255,255), 16 ))\n")
    blue = nuke.PyScript_Knob('blue', ' <img src="F_b.png">', "import colorsys\nn=nuke.thisNode()\nR,G,B= [0.6, 0.7, 0.76]\nR,G,B=colorsys.hsv_to_rgb(R,G,B)\nn['tile_color'].setValue( int('%02x%02x%02x%02x' % (R*255,G*255,B*255,255), 16 ))\n")
    darkblue = nuke.PyScript_Knob('darkblue', ' <img src="F_db.png">', "import colorsys\nn=nuke.thisNode()\nR,G,B= [0.67, 0.74, 0.6]\nR,G,B=colorsys.hsv_to_rgb(R,G,B)\nn['tile_color'].setValue( int('%02x%02x%02x%02x' % (R*255,G*255,B*255,255), 16 ))\n")
    magenta = nuke.PyScript_Knob('magenta', ' <img src="F_m.png">', "import colorsys\nn=nuke.thisNode()\nR,G,B= [0.8, 0.74, 0.65]\nR,G,B=colorsys.hsv_to_rgb(R,G,B)\nn['tile_color'].setValue( int('%02x%02x%02x%02x' % (R*255,G*255,B*255,255), 16 ))\n")
    pink = nuke.PyScript_Knob('pink', ' <img src="F_p.png">', "import colorsys\nn=nuke.thisNode()\nR,G,B= [0.92, 0.74, 0.8]\nR,G,B=colorsys.hsv_to_rgb(R,G,B)\nn['tile_color'].setValue( int('%02x%02x%02x%02x' % (R*255,G*255,B*255,255), 16 ))\n")

    copyright = nuke.Text_Knob("Ftools","","<font color=\"#1C1C1C\"> Franklin VFX - 2018")

    n.addKnob(tab)
    n['knobChanged'].setValue("try:\n    listenedKnobs = ['text', 'position', 'name']\n    node = nuke.thisNode()\n    name = node.knob('name').value()\n    text = node.knob('text').value()\n    position = node.knob('position').value()\n    position = \"<\" + position + \">\"\n    label = node.knob('label').value()\n    \n    if nuke.thisKnob().name() in listenedKnobs:\n        if text == \"\":\n            if node.knob('position').value() == \"left\":\n                node.knob('label').setValue()\n            else:\n                node.knob('label').setValue(position + name)\n        else:\n            if node.knob('position').value() == \"left\":\n                node.knob('label').setValue(text)\n            else:\n                node.knob('label').setValue(position + text)\n                \n    elif nuke.thisKnob().name() == 'font_size':\n        fontSize = node.knob('font_size').value()\n        node.knob('note_font_size').setValue(fontSize)\nexcept:\n    pass")
    n.addKnob(text)
    n['text'].setFlag(nuke.STARTLINE)
    n.addKnob(size)
    n['font_size'].setValue(50)
    n.addKnob(position)
    n['position'].clearFlag(nuke.STARTLINE)
    n.addKnob(space1)
    n.addKnob(grow)
    n.addKnob(shrink)
    n.addKnob(colorandom)
    n.addKnob(red)
    n.addKnob(orange)
    n.addKnob(yellow)
    n.addKnob(green)
    n.addKnob(cyan)
    n.addKnob(blue)
    n.addKnob(darkblue)
    n.addKnob(magenta)
    n.addKnob(pink)
    n.addKnob(space2)
    n.addKnob(copyright)

    # revert to previous selection
    n['selected'].setValue(True)

    if forced:
        nuke.delete(b)
    else:
        for node in sel:
            node['selected'].setValue(True)
    return n
Пример #20
0
def jopsBookmarkSave(index, mode='dag'):
    tabNameString   = "DAG_Bookmarks"
    try:
        nuke.root()[tabNameString]
    except (SyntaxError, NameError):
        nuke.root().addKnob(nuke.Tab_Knob(tabNameString))
        for ind in range(1,10):
            zoomNameString  = "jops_bookmark_"+str(ind)+"_zoom"
            posNameString   = "jops_bookmark_"+str(ind)+"_pos"
            xyKnob   = nuke.XY_Knob(posNameString, str(ind))
            zoomKnob = nuke.Double_Knob(zoomNameString, "")
            zoomKnob.setFlag(nuke.NO_ANIMATION)
            zoomKnob.setFlag(nuke.DISABLED)
            xyKnob.setFlag(nuke.NO_ANIMATION)
            xyKnob.setFlag(nuke.DISABLED)
            zoomKnob.clearFlag(nuke.STARTLINE)
            nuke.root().addKnob(xyKnob)
            nuke.root().addKnob(zoomKnob)
        nuke.root().addKnob(nuke.Text_Knob("j_ops_bookmarks_note", "", "<i>DAG bookmarks are part of the J_Ops toolset available on Nukepedia</i>"))
    
    xpos = 0.0
    ypos = 0.0
    zoom = 0.0
    selectedList = []

    if mode == 'node':
        if nuke.selectedNodes():
            xposList = []
            yposList = []
            for anode in nuke.selectedNodes():
                xposList.append(anode["xpos"].getValue())
                yposList.append(anode["ypos"].getValue())
            xpos = sum(xposList, 0.0) / len(xposList)
            ypos = sum(yposList, 0.0) / len(yposList)
        else:
            return
    else:
        if nuke.selectedNodes():
            for anode in nuke.selectedNodes():
                selectedList.append(anode)
                anode["selected"].setValue(0.0)

        tempNode = nuke.createNode("Dot", inpanel=False)
        xpos = tempNode["xpos"].getValue()
        ypos = tempNode["ypos"].getValue()
        nuke.delete(tempNode)
    
    zoom = nuke.zoom()
    
    zoomNameString  = "jops_bookmark_"+str(index)+"_zoom"
    posNameString   = "jops_bookmark_"+str(index)+"_pos"
        
    nuke.root()[zoomNameString].clearFlag(nuke.DISABLED)
    nuke.root()[zoomNameString].setValue(zoom)
    nuke.root()[posNameString].clearFlag(nuke.DISABLED)
    nuke.root()[posNameString].setValue(xpos,0)
    nuke.root()[posNameString].setValue(ypos,1)
    
    if selectedList:
        for anode in selectedList:
            anode["selected"].setValue(1.0)
Пример #21
0
def create_knobs(data, tab=None):
    """Create knobs by data

    Depending on the type of each dict value and creates the correct Knob.

    Mapped types:
        bool: nuke.Boolean_Knob
        int: nuke.Int_Knob
        float: nuke.Double_Knob
        list: nuke.Enumeration_Knob
        six.string_types: nuke.String_Knob

        dict: If it's a nested dict (all values are dict), will turn into
            A tabs group. Or just a knobs group.

    Args:
        data (dict): collection of attributes and their value
        tab (string, optional): Knobs' tab name

    Returns:
        list: A list of `nuke.Knob` objects

    """
    def nice_naming(key):
        """Convert camelCase name into UI Display Name"""
        words = re.findall('[A-Z][^A-Z]*', key[0].upper() + key[1:])
        return " ".join(words)

    # Turn key-value pairs into knobs
    knobs = list()

    if tab:
        knobs.append(nuke.Tab_Knob(tab))

    for key, value in data.items():
        # Knob name
        if isinstance(key, tuple):
            name, nice = key
        else:
            name, nice = key, nice_naming(key)

        # Create knob by value type
        if isinstance(value, Knobby):
            knobby = value
            knob = knobby.create(name, nice)

        elif isinstance(value, float):
            knob = nuke.Double_Knob(name, nice)
            knob.setValue(value)

        elif isinstance(value, bool):
            knob = nuke.Boolean_Knob(name, nice)
            knob.setValue(value)
            knob.setFlag(nuke.STARTLINE)

        elif isinstance(value, int):
            knob = nuke.Int_Knob(name, nice)
            knob.setValue(value)

        elif isinstance(value, six.string_types):
            knob = nuke.String_Knob(name, nice)
            knob.setValue(value)

        elif isinstance(value, list):
            knob = nuke.Enumeration_Knob(name, nice, value)

        elif isinstance(value, dict):
            if all(isinstance(v, dict) for v in value.values()):
                # Create a group of tabs
                begain = nuke.BeginTabGroup_Knob()
                end = nuke.EndTabGroup_Knob()
                begain.setName(name)
                end.setName(name + "_End")
                knobs.append(begain)
                for k, v in value.items():
                    knobs += create_knobs(v, tab=k)
                knobs.append(end)
            else:
                # Create a group of knobs
                knobs.append(nuke.Tab_Knob(name, nice, nuke.TABBEGINGROUP))
                knobs += create_knobs(value)
                knobs.append(nuke.Tab_Knob(name, nice, nuke.TABENDGROUP))
            continue

        else:
            raise TypeError("Unsupported type: %r" % type(value))

        knobs.append(knob)

    return knobs
Пример #22
0
def stereoRig():

    nukescripts.stereo.setViewsForStereo()
    #ACCESSING TARGET NODE
    target = nuke.thisNode()
    if target.Class() != 'Camera2':
        nuke.message('select a camera node')
        pass
    else:
        targetx = target['xpos'].value()
        targety = target['ypos'].value()
        #ADJUSTING TARGET KNOBS
        try:
            knob = target['BKUP']
            knob2 = target['stereoRig']
            knob3 = target['plus']
            target.removeKnob(knob)
            target.removeKnob(knob2)
            target.removeKnob(knob3)
        except:
            pass
        #CREATE STEREO TAB
        stereotab = nuke.Tab_Knob('StereoRig', 'Stereo Rig')
        IPDSlider = nuke.Double_Knob('IPD', 'Interpupillary Distance')
        IPDSlider.setFlag(nuke.STARTLINE)
        IPDSlider.setRange(52, 78)
        convergence = nuke.Double_Knob('convergence', 'Convergence Point')
        convergence.setFlag(nuke.STARTLINE)
        convergence.setRange(1, 1000)
        hshift = nuke.Double_Knob('Hshift', 'Hshift')
        hshift.setRange(-100, 100)
        hshift.setFlag(nuke.STARTLINE)
        vshift = nuke.Double_Knob('Vshift', 'Vshift')
        vshift.setFlag(nuke.STARTLINE)
        vshift.setRange(-100, 100)
        targeted = nuke.Enumeration_Knob('targeted', 'Targeted Camera',
                                         ['free', 'targeted'])
        MAINCAMLIST = [
            stereotab, targeted, IPDSlider, convergence, hshift, vshift
        ]
        for k in MAINCAMLIST:
            target.addKnob(k)
        target['IPD'].setValue(65)
        target['convergence'].setValue(250)

        #CREATE RIGHT CAMERA
        CAM__RIGHT = nuke.nodes.Camera2(name=target.name() + "__RIGHT",
                                        xpos=targetx + 220,
                                        ypos=targety + 75)
        #RIGHT CAM NODE PARAMETERS
        CAM__RIGHT.setInput(0, target)
        CAM__RIGHT['translate'].setExpression(
            target.name() + '.IPD/20+' + target.name() + '.Hshift', 0)
        CAM__RIGHT['translate'].setExpression(target.name() + '.Vshift', 1)
        hexCameraRight = int(
            '%02x%02x%02x%02x' % (0 * 255, 1 * 255, 0 * 255, 1), 16)
        CAM__RIGHT['tile_color'].setValue(hexCameraRight)
        CAM__RIGHT['focal'].setExpression(target.name() + '.focal')
        CAM__RIGHT['haperture'].setExpression(target.name() + '.haperture')
        CAM__RIGHT['vaperture'].setExpression(target.name() + '.vaperture')
        CAM__RIGHT['near'].setExpression(target.name() + '.near')
        CAM__RIGHT['far'].setExpression(target.name() + '.far')
        CAM__RIGHT['win_translate'].setExpression(target.name() +
                                                  '.win_translate')
        CAM__RIGHT['win_scale'].setExpression(target.name() + '.win_scale')
        CAM__RIGHT['winroll'].setExpression(target.name() + '.winroll')
        CAM__RIGHT['focal_point'].setExpression(target.name() + '.focal_point')
        CAM__RIGHT['fstop'].setExpression(target.name() + '.fstop')
        CAM__RIGHT['look_rotate_x'].setValue(0)
        CAM__RIGHT['look_rotate_z'].setValue(0)

        #CREATE LEFT CAMERA
        CAM__LEFT = nuke.nodes.Camera2(name=target.name() + "__LEFT",
                                       xpos=targetx - 220,
                                       ypos=targety + 75)
        #LEFT CAM NODE PARAMETERS
        CAM__LEFT.setInput(0, target)
        CAM__LEFT['translate'].setExpression(
            '-1*' + target.name() + '.IPD/20+' + target.name() + '.Hshift', 0)
        CAM__LEFT['translate'].setExpression(target.name() + '.Vshift', 1)
        hexCameraLeft = int(
            '%02x%02x%02x%02x' % (1 * 255, 0 * 255, 0 * 255, 1), 16)
        CAM__LEFT['tile_color'].setValue(hexCameraLeft)
        CAM__LEFT['focal'].setExpression(target.name() + '.focal')
        CAM__LEFT['haperture'].setExpression(target.name() + '.haperture')
        CAM__LEFT['vaperture'].setExpression(target.name() + '.vaperture')
        CAM__LEFT['near'].setExpression(target.name() + '.near')
        CAM__LEFT['far'].setExpression(target.name() + '.far')
        CAM__LEFT['win_translate'].setExpression(target.name() +
                                                 '.win_translate')
        CAM__LEFT['win_scale'].setExpression(target.name() + '.win_scale')
        CAM__LEFT['winroll'].setExpression(target.name() + '.winroll')
        CAM__LEFT['focal_point'].setExpression(target.name() + '.focal_point')
        CAM__LEFT['fstop'].setExpression(target.name() + '.fstop')
        CAM__LEFT['look_rotate_x'].setValue(0)
        CAM__LEFT['look_rotate_z'].setValue(0)

        #NODES POSITIONS
        CAM__RIGHTX = CAM__RIGHT['xpos'].value()
        CAM__RIGHTY = CAM__RIGHT['ypos'].value()
        CAM__LEFTX = CAM__LEFT['xpos'].value()
        CAM__LEFTY = CAM__LEFT['ypos'].value()
        nodeWidth = target.screenWidth() / 2
        DOT1xpos = CAM__RIGHTX + nodeWidth
        DOT2xpos = CAM__LEFTX + nodeWidth
        #CREATING DOTS
        DOT_RIGHT = nuke.nodes.Dot(xpos=DOT1xpos - 6, ypos=CAM__RIGHTY - 200)
        DOT_LEFT = nuke.nodes.Dot(xpos=DOT2xpos - 6, ypos=CAM__LEFTY - 200)
        #CONNECTING CAMERAS TO DOTS
        CAM__LEFT.setInput(1, DOT_LEFT)
        CAM__RIGHT.setInput(1, DOT_RIGHT)

        #CREATE CONVERGENCE POINT
        convergence = nuke.nodes.Axis2(name=target.name() +
                                       '_ConvergencePoint',
                                       xpos=targetx,
                                       ypos=targety - 250)
        DOT_RIGHT.setInput(0, convergence)
        DOT_LEFT.setInput(0, convergence)
        convergence.setInput(0, target)
        convergence['translate'].setExpression('0', 0)
        convergence['translate'].setExpression('0', 1)
        convergence['translate'].setExpression(
            '-1*' + target.name() + '.convergence', 2)

        #CREATE CLOSEST OBJECT WARNING POINT
        ClosestObject = nuke.nodes.Axis2(
            name=target.name() + '_ClosestObject',
            label="1/30 Limit rule For reference only",
            xpos=targetx + 90,
            ypos=targety - 125)
        ClosestObject.setInput(0, target)
        ClosestObject['translate'].setExpression(
            target.name() + '.IPD/10 * -30', 2)
        for n in ClosestObject.allKnobs():
            n.setEnabled(False)

        #CREATE MAIN CAM DOT
        DOT_MAIN = nuke.nodes.Dot(xpos=targetx + 120,
                                  ypos=targety + nodeWidth - 40,
                                  label='Connect Camera \n animation here')
        target.setInput(0, DOT_MAIN)
        DOT_MAIN['hide_input'].setValue(1)
        hexDOT_MAIN = int('%02x%02x%02x%02x' % (1 * 255, 0 * 255, 1 * 255, 1),
                          16)
        DOT_MAIN.knob('tile_color').setValue(hexDOT_MAIN)
        hexfnDOT_MAIN = int(
            '%02x%02x%02x%02x' % (1 * 255, 1 * 255, 1 * 255, 1), 16)
        DOT_MAIN.knob('note_font_color').setValue(hexfnDOT_MAIN)

        #CREATE TARGET SWITCH
        targetswitch = nuke.nodes.Switch(name=target.name() + '_TargetSwitch',
                                         xpos=targetx - 110,
                                         ypos=targety + nodeWidth - 30)
        target.setInput(1, targetswitch)
        targetswitch['which'].setExpression(target.name() + '.targeted')

        #CREATE TARGET NODE
        targetnode = nuke.nodes.Axis2(name=target.name() + '_Target',
                                      xpos=targetx - 100,
                                      ypos=targety + nodeWidth - 150)
        targetswitch.setInput(1, targetnode)
        hex_MAIN = int(
            '%02x%02x%02x%02x' % (0.5 * 255, 0.5 * 255, 0.5 * 255, 1), 16)
        target.knob('tile_color').setValue(hex_MAIN)
        targetnode.knob('tile_color').setValue(hex_MAIN)
        targetPOSx = target['translate'].getValue(0)
        targetPOSy = target['translate'].getValue(1)
        targetPOSz = target['translate'].getValue(2)
        targetnode['translate'].setValue(targetPOSx, 0)
        targetnode['translate'].setValue(targetPOSy, 1)
        targetnode['translate'].setValue(targetPOSz, 2)
Пример #23
0
def setNode():
	'''builds controls
	return: n (obj)
	'''

	n = nuke.nodes.NoOp()
	n.setName('ku_FlickerWaves')
	n['label'].setValue('[format "%.2f" [value wave]]')
	n['note_font'].setValue('Bold')
	n['note_font_size'].setValue(24)
	n['tile_color'].setValue(4290707711)
	n['hide_input'].setValue(True)
	nuke.zoom(2, [n.xpos(),n.ypos()])
	print "Created %s" % n.name()

	# First Tab
	k_tab = nuke.Tab_Knob('tb_main', 'ku_FlickerWaves')

	k_output = nuke.Array_Knob('wave', 'output wave',1)
	k_output.setEnabled(False)
	k_edit = nuke.Boolean_Knob('edit','enable')
	k_edit.clearFlag(nuke.STARTLINE)
	k_global_amp = nuke.Double_Knob('g_amp', 'global amp')
	k_global_freq = nuke.Double_Knob('g_freq', 'global freq')
	k_fade = nuke.Double_Knob('fade','fade')

	k_div1 = nuke.Text_Knob('','')

	k_tx1 = nuke.Text_Knob('','Array Order',"[Base Wave, Mid Wave, High Wave]")
	k_seed = nuke.Array_Knob('seed','seed',3)
	k_amp_ratio = nuke.Array_Knob('amp_ratio','amp ratio',3)
	k_freq_ratio = nuke.Array_Knob('freq_ratio','freq ratio',3)
	k_shift = nuke.Double_Knob('shift','base shift')
	k_timeoffset = nuke.Array_Knob('timeoffset','timeoffset',3)

	k_div2 = nuke.Text_Knob('','')
	k_link = nuke.PyScript_Knob('bt_link','link to selected<br><b>Multiply</b> node','')
	k_curve = nuke.PyScript_Knob('bt_curve','Show in<br><b>Curve Editor</b>',"nuke.tcl('curve_editor')")
	k_curve.clearFlag(nuke.STARTLINE)

	# Second Tab
	k_secondary = nuke.Tab_Knob('tb_secondary','Output Waves')

	k_b_out = nuke.Double_Knob('base_freq', 'base freq')
	k_m_out = nuke.Double_Knob('mid_freq', 'mid freq')
	k_h_out = nuke.Double_Knob('high_freq', 'high freq')

	# Set default values
	k_fade.setValue(1)
	k_global_amp.setValue(1)
	k_global_amp.setRange(1,2)
	k_global_freq.setValue(1)
	k_global_freq.setRange(1,2)
	k_seed.setValue([666,888,686])
	k_amp_ratio.setValue([1,0.25,0.125])
	k_freq_ratio.setValue([0.25,0.5,1])
	k_shift.setRange(-1,1)

	ls_knob = [k_tab, k_output, k_edit ,k_global_amp, k_global_freq, k_fade, k_div1,k_tx1,k_seed,k_amp_ratio,k_freq_ratio,k_shift,k_timeoffset,k_div2,k_link,k_curve,k_secondary,k_b_out,k_m_out,k_h_out]
	for k in ls_knob:
		n.addKnob(k)

	return n
Пример #24
0
    def __init__( self):
        '''Convert focal length, aperture and field of view'''
        nukescripts.PythonPanel.__init__( self, "Fov Calculator","com.ohufx.FovCalculator" )
        #super( FovCalculator, self ).__init__( 'Fov Calculator', 'com.ohufx.FovCalc' )
        modes = ['aperture', 'focal', 'fov']
        self.apDict = {}
        self.getAps()
            
        self.mode = nuke.Enumeration_Knob( 'mode', 'get <img src=":qrc/images/Eyedropper.png">', modes)
        self.mode.setValue( 'fov' )
        self.mode.setTooltip( 'select which value you want to calculate' )
        self.focal = nuke.Double_Knob( 'focal', 'focal length @TargetCamera.png' )
        self.focal.setTooltip( 'focal length in mm' )
        self.focal.setRange( 5, 200 )
        self.focal.setDefaultValue( [50] )
        div1 = nuke.Text_Knob('')
        self.apNames = self.apDict.keys()
        self.apNames.sort()
        self.apNames.insert( 0, 'custom')
        self.apList = nuke.Enumeration_Knob( 'ap', 'aperture @Grid.png', self.apNames )
        self.apList.setTooltip( 'select a preset to fill in the filmback dimensions to the right. These values are read from any "apertures.txt" found in the plugin path.\
                                The syntax of the apertures.txt should ismply be "name width height".' )
        self.haperture = nuke.Double_Knob( 'haperture', '' )
        self.haperture.setTooltip( 'width in mm of the film back or chip' )
        if not self.apDict:
            self.apList.setVisible( False )
        self.haperture.clearFlag( nuke.STARTLINE )
        self.haperture.clearFlag( 2 )
        self.haperture.setRange( 0.1, 50 )
        self.haperture.setValue( 24.576 )
        self.vaperture = nuke.Double_Knob( 'vaperture', '' )
        self.vaperture.setTooltip( 'height in mm of the film back or chip' )
        self.vaperture.clearFlag( nuke.STARTLINE )
        self.vaperture.clearFlag( 2 )
        self.vaperture.setRange( 0.1, 50 )
        self.vaperture.setValue( 18.672 )
        
        self.hfov = nuke.Double_Knob( 'hfov', 'horizontal fov @hfov.png' )
        self.hfov.setTooltip( 'horizontal field of view aka "angle of view"' )
        self.hfov.setRange( 10, 180 )
        self.hfov.setValue( focalToFov( self.focal.value(), self.haperture.value() ) )
        self.hfov.setEnabled( False )
        self.vfov = nuke.Double_Knob( 'vfov', 'vertical fov @vfov.png' )
        self.vfov.setTooltip( 'vertical field of view aka "angle of view"' )
        self.vfov.setRange( 10, 180 )
        self.vfov.setValue( focalToFov( self.focal.value(), self.vaperture.value() ) )
        self.vfov.setEnabled( False )
        self.useVert = nuke.Boolean_Knob( 'useVert', 'use vertical' )
        self.useVert.setTooltip( 'if checked, the vertical aperture and fov are used to calucltae the focla length. If off the gorizontal values are used.' )
        
        div2 = nuke.Text_Knob('')
        self.driveCam = nuke.Boolean_Knob( 'driveCam', '<img src=":qrc/images/Roto/CloneToolbar.png"> Drive Existing Camera')
        self.driveCam.setTooltip( 'When checked the camera with the given name will be temprarily linked to the value sin this panel.\
                                  This is handy to do visual checks while tweaking tha panel\'s parameters.\
                                  If a camera node is selected when the checkbox is activated, it\'s name is automatically filled in to the text filed to the right.'
                                  )
        self.driveCam.setFlag( nuke.STARTLINE )
        self.driveCamName = nuke.String_Knob( 'driveCamName', '')
        self.driveCamName.setTooltip( 'name of the camera in the DAG to drive with the above values. This can be manually filled in but is also automatically filled based on the current selection when the checkbox on the left is activated.' )
        self.driveCamName.clearFlag( nuke.STARTLINE )
        self.createCam = nuke.PyScript_Knob( 'createCam', '@Camera.png Create New Camera')
        self.createCam.setTooltip( 'create a new cmeara node with the current values.' )
        
        for k in ( self.mode, self.useVert, div1, self.focal, self.apList, self.haperture, self.vaperture, self.hfov, self.vfov, div2, self.createCam, self.driveCam, self.driveCamName ):
            self.addKnob( k )

        self.useVert.setVisible( False )
Пример #25
0
    def __init__( self, node ):
        nukescripts.PythonPanel.__init__( self, 'Multiple Nodes' )


        #Creating Knobs
        self.name = nuke.String_Knob( 'name', 'Knob name' ) 
        self.enum = nuke.Enumeration_Knob('enum', 'Knob Type', ['integer', 'slider', 'double',
                                          'XY', 'XYZ', 'rgb', 'rgba', 'bbox', 'string', 'boolean'])
        self.enum.setFlag(nuke.STARTLINE)

        self.boolean = nuke.Boolean_Knob('boolean', 'boolean')
        self.boolean.setFlag(nuke.STARTLINE)
        self.boolean.setFlag(nuke.INVISIBLE)

        self.integer = nuke.Int_Knob( 'integer', 'integer' '')    
        self.integer.setFlag(nuke.STARTLINE) 
        self.integer.setFlag(nuke.INVISIBLE)

        self.slider = nuke.Double_Knob( 'slider', 'slider'  )  
        self.slider.setFlag(nuke.STARTLINE)

        self.double = nuke.WH_Knob( 'double', 'double'  )  
        self.double.setFlag(nuke.STARTLINE)
        self.double.setFlag(nuke.INVISIBLE)

        self.XY = nuke.UV_Knob( 'XY', 'XY'  )  
        self.XY.setFlag(nuke.STARTLINE)
        self.XY.setFlag(nuke.INVISIBLE)

        self.XYZ = nuke.Scale_Knob( 'XYZ', 'XYZ'  )  
        self.XYZ.setFlag(nuke.STARTLINE)
        self.XYZ.setFlag(nuke.INVISIBLE)

        self.rgb = nuke.Color_Knob( 'rgb', 'rgb' )  
        self.rgb.setFlag(nuke.STARTLINE)
        self.rgb.setFlag(nuke.INVISIBLE)

        self.rgba = nuke.AColor_Knob( 'rgba', 'rgba' )  
        self.rgba.setFlag(nuke.STARTLINE)
        self.rgba.setFlag(nuke.INVISIBLE)

        self.bbox = nuke.BBox_Knob( 'bbox', 'bbox' )  
        self.bbox.setFlag(nuke.STARTLINE)
        self.bbox.setFlag(nuke.INVISIBLE)

        self.string = nuke.String_Knob( 'string', 'string' )  
        self.string.setFlag(nuke.STARTLINE)
        self.string.setFlag(nuke.INVISIBLE)




        

        #set initial values
        self.enum.setValue('slider')


        #Adding knobs
        for k in (  self.name, self.enum, self.integer, self.slider, self.double, self.XY,
                    self.XYZ, self.rgb, self.rgba, self.bbox, self.string, self.boolean ):
            self.addKnob( k )
Пример #26
0
def bm_QuickKeys(type):

    # Set some initial variables for later use.
    node = nuke.selectedNode()
    frame = nuke.frame()

    # Find the correct knob based on the node's class. If it's not specified, presume the user
    # wants to use the shortcut on the mix knob.
    dict = {
        'Switch': 'which',
        'Dissolve': 'which',
        'Roto': 'opacity',
        'RotoPaint': 'opacity'
    }

    if node.Class() in dict.keys():
        knob = node.knob(dict[node.Class()])
    else:
        knob = node.knob('mix')

    # If the mix knob has a non-zero value we should use it, but if it's zero things can break so we'll use 1 instead.
    if knob.value() != 0:
        knob_value = knob.value()
    else:
        knob_value = 1

    # Now, let's make things work!

    # "on" is the function's argument. We're using it as an easy way to set shortcuts,
    # But there is no error-checking because users won't be seeing / setting them.

    # "on" sets a keyframe with the current value on the current frame, and a keyframe with a value of 0 on the previous frame.
    if type == "on":

        # Prime node for animation
        knob.setAnimated(0)
        knob_anim = knob.animations()[0]

        knob_anim.setKey(frame, knob_value)
        knob_anim.setKey(frame - 1, 0)
        return

    # "off" sets a keyframe with the current value on the current frame, and a keyframe with a value of 0 on the next frame.
    elif type == "off":

        # Prime node for animation
        knob.setAnimated(0)
        knob_anim = knob.animations()[0]

        knob_anim.setKey(frame, knob_value)
        knob_anim.setKey(frame + 1, 0)
        return

    # "offonoff" sets a keyframe with the current value on the current frame, and a keyframe with a value of 0 on both the next and the previous frames.
    elif type == "offonoff":

        # Prime node for animation
        knob.setAnimated(0)
        knob_anim = knob.animations()[0]

        knob_anim.setKey(frame - 1, 0)
        knob_anim.setKey(frame, knob_value)
        knob_anim.setKey(frame + 1, 0)
        return

    # "onoffon" sets a keyframe with a value of 0 on the current frame, and a keyframe with the current value on both the next and the previous frames.
    elif type == "onoffon":

        # Prime node for animation
        knob.setAnimated(0)
        knob_anim = knob.animations()[0]

        knob_anim.setKey(frame - 1, knob_value)
        knob_anim.setKey(frame, 0)
        knob_anim.setKey(frame + 1, knob_value)
        return

    # "custom" is a little more involved, as it opens a panel. You can set whatever values you want, including a "fade" option to make transitions
    # not-so-instant.
    elif type == "custom":

        # Create the panel
        panel = nukescripts.PythonPanel("Quick Keys")

        # Add the knobs, position them on the pop-up window and set default values
        on_frame_input = nuke.Int_Knob('on_frame_input', 'First Frame')
        on_frame_input.setValue(frame)
        panel.addKnob(on_frame_input)

        on_frame_value = nuke.Double_Knob('on_frame_value', '   Set value')
        on_frame_value.setValue(knob_value)
        on_frame_value.clearFlag(nuke.STARTLINE)
        panel.addKnob(on_frame_value)

        on_chk = nuke.Boolean_Knob('on_chk', 'enable', True)
        panel.addKnob(on_chk)

        off_frame_input = nuke.Int_Knob('off_frame_input', 'Last Frame')
        off_frame_input.setValue(frame + 10)
        panel.addKnob(off_frame_input)

        off_frame_value = nuke.Double_Knob('off_frame_value', '   Set value')
        off_frame_value.setValue(knob_value)
        off_frame_value.clearFlag(nuke.STARTLINE)
        panel.addKnob(off_frame_value)

        off_chk = nuke.Boolean_Knob('off_chk', 'enable', True)
        panel.addKnob(off_chk)

        fade_input = nuke.Int_Knob('fade_frame_input', 'Fade Duration', frame)
        panel.addKnob(fade_input)

        fade_chk = nuke.Boolean_Knob('fade_chk', 'enable', True)
        panel.addKnob(fade_chk)

        # If the window successfully opens and the ok button is pressed, do the things.
        if panel.showModalDialog() == True:

            # Prime node for animation
            knob.setAnimated(0)
            knob_anim = knob.animations()[0]

            # If there's no fading happening, we need to force an offset of 1 frame so keyframes don't overwrite each other.
            if fade_chk.value() == False or fade_input.value() == 0:
                fade_input.setValue(1)

            if on_chk.value() == True:
                knob_anim.setKey(on_frame_input.value(),
                                 on_frame_value.value())
                knob_anim.setKey(on_frame_input.value() - (fade_input.value()),
                                 0)

            if off_chk.value() == True:
                knob_anim.setKey(off_frame_input.value(),
                                 off_frame_value.value())
                knob_anim.setKey(
                    off_frame_input.value() + (fade_input.value()), 0)

        # Otherwise, if the cancel button is pressed, don't do anything...
        else:
            return
Пример #27
0
    def transformImage(self,read,merge,image,position,num):
        x1 = read.metadata('input/width')*(17.0/64.0)
        s1 = read.metadata('input/width')*(13.0/32.0)/image.metadata('input/width')
        x2 = read.metadata('input/width')*(1.0/3.0)
        s2 = read.metadata('input/width')*((1.0/3.0)-(1.0/32.0))/image.metadata('input/width')
        y1 = read.metadata('input/height')*(1.0/4.0)
        y2 = read.metadata('input/height')*(1.0/3.0)
        position.knob('translate').setValue([read.metadata('input/width')/2-image.metadata('input/width')/2,read.metadata('input/height')/2-image.metadata('input/height')/2])
        del transformNodes[:]

        if num == 1:
            transform = nuke.nodes.Transform()
            transform.setInput(0,position)
            transform.knob('center').setValue([(read.metadata('input/width')/2),(read.metadata('input/height')/2)])
            transform.knob('scale').setValue(0.5)
            transform.addKnob(nuke.Double_Knob('ori_scale','original scale'))
            transform.knob('ori_scale').setValue(0.5)
            merge.setInput(1,transform)

        if num == 2:
            for i in range(2):
                transform = nuke.nodes.Transform()
                transform.setInput(0,position)
                transform.knob('center').setValue([(read.metadata('input/width')/2),(read.metadata('input/height')/2)])
                transform.knob('scale').setValue(s1)
                transform.addKnob(nuke.Double_Knob('ori_scale','original scale'))
                transform.knob('ori_scale').setValue(s1)
                transformNodes.append(transform)
                merge.setInput(i+3,transform)
            transformNodes[0].knob('translate').setValue([x1,0])
            transformNodes[1].knob('translate').setValue([-x1,0])

        if num == 3:
            for i in range(3):
                transform = nuke.nodes.Transform()
                transform.setInput(0,position)
                transform.knob('center').setValue([(read.metadata('input/width')/2),(read.metadata('input/height')/2)])
                transform.knob('scale').setValue(s2)
                transform.addKnob(nuke.Double_Knob('ori_scale','original scale'))
                transform.knob('ori_scale').setValue(s2)
                transformNodes.append(transform)
                merge.setInput(i+3,transform)
            transformNodes[0].knob('translate').setValue([x2,0])
            transformNodes[1].knob('translate').setValue([-x2,0])

        if num == 4:
            for i in range(4):
                transform = nuke.nodes.Transform()
                transform.setInput(0,position)
                transform.knob('center').setValue([(read.metadata('input/width')/2),(read.metadata('input/height')/2)])
                transform.knob('scale').setValue(s1)
                transform.addKnob(nuke.Double_Knob('ori_scale','original scale'))
                transform.knob('ori_scale').setValue(s1)
                transformNodes.append(transform)
                merge.setInput(i+3,transform)
            transformNodes[0].knob('translate').setValue([x1,y1])
            transformNodes[1].knob('translate').setValue([-x1,y1])
            transformNodes[2].knob('translate').setValue([x1,-y1])
            transformNodes[3].knob('translate').setValue([-x1,-y1])

        if num == 6:
            for i in range(6):
                transform = nuke.nodes.Transform()
                transform.setInput(0,position)
                transform.knob('center').setValue([(read.metadata('input/width')/2),(read.metadata('input/height')/2)])
                transform.knob('scale').setValue(s2)
                transform.addKnob(nuke.Double_Knob('ori_scale','original scale'))
                transform.knob('ori_scale').setValue(s2)
                transformNodes.append(transform)
                merge.setInput(i+3,transform)
            transformNodes[0].knob('translate').setValue([x2,y1])
            transformNodes[1].knob('translate').setValue([-x2,y1])
            transformNodes[2].knob('translate').setValue([x2,-y1])
            transformNodes[3].knob('translate').setValue([-x2,-y1])
            transformNodes[4].knob('translate').setValue([0,-y1])
            transformNodes[5].knob('translate').setValue([0,y1])

        if num == 9:
            for i in range(9):
                transform = nuke.nodes.Transform()
                transform.setInput(0,position)
                transform.knob('center').setValue([(read.metadata('input/width')/2),(read.metadata('input/height')/2)])
                transform.knob('scale').setValue(s2)
                transform.addKnob(nuke.Double_Knob('ori_scale','original scale'))
                transform.knob('ori_scale').setValue(s2)
                transformNodes.append(transform)
                merge.setInput(i+3,transform)
            transformNodes[0].knob('translate').setValue([x2,y1])
            transformNodes[1].knob('translate').setValue([-x2,y1])
            transformNodes[2].knob('translate').setValue([x2,-y1])
            transformNodes[3].knob('translate').setValue([-x2,-y1])
            transformNodes[4].knob('translate').setValue([0,-y1])
            transformNodes[5].knob('translate').setValue([0,y1])
            transformNodes[6].knob('translate').setValue([x2,0])
            transformNodes[7].knob('translate').setValue([-x2,0])
Пример #28
0
    def transformText(self,read,merge,text,num):
        #calculate 6 properties
        x1 = read.metadata('input/width')*(17.0/64.0)
        s1 = read.metadata('input/width')*(13.0/32.0)/600
        x2 = read.metadata('input/width')*(1.0/3.0)
        s2 = read.metadata('input/width')*((1.0/3.0)-(1.0/32.0))/600
        y1 = read.metadata('input/height')*(1.0/4.0)
        y2 = read.metadata('input/height')*(1.0/3.0)

        #set text node
        text.knob('box').setValue([0,0,read.metadata('input/width'),read.metadata('input/height')])
        text.knob('xjustify').setValue('center')
        text.knob('yjustify').setValue('center')

        #initialize transform node list
        del transformNodes[:]

        if num == 1:
            transform = nuke.nodes.Transform()
            transform.setInput(0,text)
            transform.knob('center').setValue([(read.metadata('input/width')/2),(read.metadata('input/height')/2)])
            transform.knob('scale').setValue(0.5)
            transform.addKnob(nuke.Double_Knob('ori_scale','original scale'))
            transform.knob('ori_scale').setValue(0.5)
            merge.setInput(1,transform)

        if num == 2:
            for i in range(2):
                transform = nuke.nodes.Transform()
                transform.setInput(0,text)
                transform.knob('center').setValue([(read.metadata('input/width')/2),(read.metadata('input/height')/2)])
                transform.knob('scale').setValue(s1)
                transform.addKnob(nuke.Double_Knob('ori_scale','original scale')) #for storing s1/s2
                transform.knob('ori_scale').setValue(s1)
                transformNodes.append(transform)
                merge.setInput(i+3,transform)
            transformNodes[0].knob('translate').setValue([x1,0])  #watermark layout
            transformNodes[1].knob('translate').setValue([-x1,0])

        if num == 3:
            for i in range(3):
                transform = nuke.nodes.Transform()
                transform.setInput(0,text)
                transform.knob('center').setValue([(read.metadata('input/width')/2),(read.metadata('input/height')/2)])
                transform.knob('scale').setValue(s2)
                transform.addKnob(nuke.Double_Knob('ori_scale','original scale'))
                transform.knob('ori_scale').setValue(s2)
                transformNodes.append(transform)
                merge.setInput(i+3,transform)
            transformNodes[0].knob('translate').setValue([x2,0])
            transformNodes[1].knob('translate').setValue([-x2,0])

        if num == 4:
            for i in range(4):
                transform = nuke.nodes.Transform()
                transform.setInput(0,text)
                transform.knob('center').setValue([(read.metadata('input/width')/2),(read.metadata('input/height')/2)])
                transform.knob('scale').setValue(s1)
                transform.addKnob(nuke.Double_Knob('ori_scale','original scale'))
                transform.knob('ori_scale').setValue(s1)
                transformNodes.append(transform)
                merge.setInput(i+3,transform)
            transformNodes[0].knob('translate').setValue([x1,y1])
            transformNodes[1].knob('translate').setValue([-x1,y1])
            transformNodes[2].knob('translate').setValue([x1,-y1])
            transformNodes[3].knob('translate').setValue([-x1,-y1])

        if num == 6:
            for i in range(6):
                transform = nuke.nodes.Transform()
                transform.setInput(0,text)
                transform.knob('center').setValue([(read.metadata('input/width')/2),(read.metadata('input/height')/2)])
                transform.knob('scale').setValue(s2)
                transform.addKnob(nuke.Double_Knob('ori_scale','original scale'))
                transform.knob('ori_scale').setValue(s2)
                transformNodes.append(transform)
                merge.setInput(i+3,transform)
            transformNodes[0].knob('translate').setValue([x2,y1])
            transformNodes[1].knob('translate').setValue([-x2,y1])
            transformNodes[2].knob('translate').setValue([x2,-y1])
            transformNodes[3].knob('translate').setValue([-x2,-y1])
            transformNodes[4].knob('translate').setValue([0,-y1])
            transformNodes[5].knob('translate').setValue([0,y1])

        if num == 9:
            for i in range(9):
                transform = nuke.nodes.Transform()
                transform.setInput(0,text)
                transform.knob('center').setValue([(read.metadata('input/width')/2),(read.metadata('input/height')/2)])
                transform.knob('scale').setValue(s2)
                transform.addKnob(nuke.Double_Knob('ori_scale','original scale'))
                transform.knob('ori_scale').setValue(s2)
                transformNodes.append(transform)
                merge.setInput(i+3,transform)
            transformNodes[0].knob('translate').setValue([x2,y1])
            transformNodes[1].knob('translate').setValue([-x2,y1])
            transformNodes[2].knob('translate').setValue([x2,-y1])
            transformNodes[3].knob('translate').setValue([-x2,-y1])
            transformNodes[4].knob('translate').setValue([0,-y1])
            transformNodes[5].knob('translate').setValue([0,y1])
            transformNodes[6].knob('translate').setValue([x2,0])
            transformNodes[7].knob('translate').setValue([-x2,0])
Пример #29
0
def dg_PerspLines_AlignCamera():
    nodes = nuke.selectedNodes()
    if not len(nodes) == 2:
        nuke.message(
            'Illegal amount of selected nodes.\nPlease select exactly two dg_PerspLines nodes'
        )
        return
    for n in nodes:
        if not n.Class() == 'dg_PerspLines':
            nuke.message('One of selected nodes is not dg_PerspLines')
            return

    V1 = nodes[0]['PT'].value()
    V2 = nodes[1]['PT'].value()

    K = (V2[1] - V1[1]) / (V2[0] - V1[0])
    print K

    Oi = [nodes[0].width() / 2, nodes[0].height() / 2]
    print Oi

    Vix = (1 / K * Oi[0] + Oi[1] + K * V1[0] - V1[1]) / (K + 1 / K)
    Viy = -1 / K * (Vix - Oi[0]) + Oi[1]
    Vi = [Vix, Viy]
    print Vi

    ViV1 = sqrt(pow(Vi[0] - V1[0], 2) + pow(Vi[1] - V1[1], 2))
    ViV2 = sqrt(pow(Vi[0] - V2[0], 2) + pow(Vi[1] - V1[1], 2))

    print ViV1
    print ViV2

    OcVi = sqrt(ViV1 * ViV2)
    OiVi = sqrt(pow(Oi[0] - Vi[0], 2) + pow(Oi[1] - Vi[1], 2))
    print OcVi
    print OiVi

    f = sqrt(pow(OcVi, 2) - pow(OiVi, 2))
    print f

    f_scale = sqrt(pow(Oi[0] * 2, 2) + pow(Oi[1] * 2, 2)) / f

    camNode = nuke.createNode('Camera', inpanel=False)
    camNode['tile_color'].setValue(884320767)

    camNode['focal'].setValue(
        sqrt(
            pow(camNode['haperture'].value(), 2) +
            pow(camNode['vaperture'].value(), 2)) / f_scale)

    Rx = atan((Oi[1] - Vi[1]) / f) * 180 / PI
    Ry = atan(min(ViV1, ViV2) / f) * 180 / PI
    Ry2 = atan(max(ViV1, ViV2) / f) * 180 / PI
    Rz = -atan(K) * 180 / PI

    camNode['rotate'].setValue([Rx, Ry, Rz])
    camNode['translate'].setValue([0, 1, 0])

    k = nuke.Double_Knob('Ry')
    k.setValue(Ry2)
    camNode.addKnob(nuke.Tab_Knob('alternate'))
    camNode.addKnob(k)

    k = nuke.PyScript_Knob('swap')
    k.setCommand('dg_PerspLines_swap(nuke.thisNode())')
    camNode.addKnob(k)
Пример #30
0
def build_IP():
    '''build IP node'''
    if 'VIEWER_INPUT' in [n.name() for n in nuke.allNodes()]:
        nuke.message('IP already exist')
    else:

        str_autolabel = "\n('exp: %s\\n' % nuke.thisNode()['exp'].value())+('gamma: %s\\n' % nuke.thisNode()['y'].value())+('sat: %s\\n' % nuke.thisNode()['sat'].value())"
        colour_bg = 2135237631
        colour_text = 4289560575

        # Declare Node
        node_IP = nuke.nodes.Group(note_font_color=colour_text,
                                   note_font_size=48,
                                   note_font='bold',
                                   tile_color=colour_bg,
                                   hide_input=True)
        node_IP.setName('VIEWER_INPUT')

        # Declare knobs
        k_tab = nuke.Tab_Knob('tb_user', 'ku_IP')
        k_exp = nuke.Double_Knob('exp', 'exposure')
        k_exp_d = nuke.Boolean_Knob('d_exp', 'disable', True)
        k_y = nuke.Double_Knob('y', 'gamma')
        k_y_d = nuke.Boolean_Knob('d_y', 'disable', True)
        k_sat = nuke.Double_Knob('sat', 'saturation')
        k_sat_d = nuke.Boolean_Knob('d_sat', 'disable', True)
        k_div_preset = nuke.Text_Knob('tx_preset', 'preset')
        k_preset_add = nuke.PyScript_Knob('preset_add', '<b>&#43;</b>',
                                          'mod_IP.add_preset()')
        k_preset_remove = nuke.PyScript_Knob('preset_remove', '<b>&#8722;</b>',
                                             'mod_IP.remove_preset()')
        k_reset = nuke.PyScript_Knob('reset', '<b>reset</b>', 'mod_IP.reset()')

        k_exp.setValue(0)
        k_y.setValue(1)
        k_sat.setValue(1)

        for k in [k_exp_d, k_y_d, k_sat_d, k_preset_remove]:
            k.clearFlag(nuke.STARTLINE)
        k_reset.setFlag(nuke.STARTLINE)

        ## Add Knobs
        for k in [
                k_tab, k_exp, k_exp_d, k_y, k_y_d, k_sat, k_sat_d,
                k_div_preset, k_preset_add, k_preset_remove, k_reset
        ]:
            node_IP.addKnob(k)

        # Add nodes inside IP Group
        with node_IP:
            nuke.createNode('Input', "name Input", inpanel=False)
            nuke.createNode('Multiply',
                            "name _EXPOSURE_ channels all",
                            inpanel=False)
            nuke.createNode('Gamma',
                            "name _GAMMA_ channels all",
                            inpanel=False)
            nuke.createNode('Saturation',
                            "name _SATURATION_ channels all",
                            inpanel=False)
            copy_node = nuke.createNode('Copy',
                                        "name _ALPHA_COPY_",
                                        inpanel=False)
            copy_node.setInput(0, nuke.toNode('_SATURATION_'))
            copy_node.setInput(1, nuke.toNode('Input'))
            nuke.createNode('Output', "name Output", inpanel=False)

            nuke.toNode('_EXPOSURE_')['value'].setExpression(
                'pow(2,parent.exp)')
            nuke.toNode('_GAMMA_')['value'].setExpression('parent.y')
            nuke.toNode('_SATURATION_')['saturation'].setExpression(
                'parent.sat')

            nuke.toNode('_EXPOSURE_')['disable'].setExpression('parent.d_exp')
            nuke.toNode('_GAMMA_')['disable'].setExpression('parent.d_y')
            nuke.toNode('_SATURATION_')['disable'].setExpression(
                'parent.d_sat')

        node_IP['autolabel'].setValue(str_autolabel)