Ejemplo n.º 1
0
    def xformFromMatrix(self, node, frame):
        """ used to transform matrix to translate, rotate, scale coord"""
        nuke.frame(frame)
        worldMatrix = node.knob('world_matrix')
        worldMatrixAt = node.knob('world_matrix').getValueAt(frame)
        
        matrix = nuke.math.Matrix4()

        worldMatrix = node.knob('world_matrix')
        matrix = nuke.math.Matrix4()
        for y in range(worldMatrix.height()):
            for x in range(worldMatrix.width()):
                matrix[x+(y*worldMatrix.width())] = worldMatrixAt[y+worldMatrix.width()*x]

        transM = nuke.math.Matrix4(matrix)
        transM.translationOnly()
        rotM = nuke.math.Matrix4(matrix)
        rotM.rotationOnly()
        scaleM = nuke.math.Matrix4(matrix)
        scaleM.scaleOnly()
        
        scale = (scaleM.xAxis().x, scaleM.yAxis().y, scaleM.zAxis().z)
        rot = rotM.rotationsZXY()
        rotate = (math.degrees(rot[0]), math.degrees(rot[1]), math.degrees(rot[2]))
        translate = (transM[12], transM[13], transM[14])
        
        return translate, rotate, scale
Ejemplo n.º 2
0
def create_projector_panel():
    if not ensure_camera_selected(nuke.selectedNode()):
        return
    
    p = nukescripts.panels.PythonPanel("Create a projector")
    
    k = nuke.Boolean_Knob("link", "Link the projector camera to the original")
    k.setFlag(nuke.STARTLINE)
    k.setTooltip("This will create a live setup that will update when the camera keyframes change")
    p.addKnob(k)
    
    k = nuke.Boolean_Knob("create_shader_tree", "Create shader tree (FrameHold + project3d)")
    k.setFlag(nuke.STARTLINE)
    k.setTooltip("will also create a FrameHold and a Project3D to spare even more clicks")
    p.addKnob(k)
    
    result = p.showModalDialog()    
    if result == 0:
        return # Canceled

    # The API called "get value of the field by providing it's UI label" earns the
    # mark of the most f****d up disgusting crap engineering ever (tm)
    do_link = p.knobs()["link"].value()
    do_tree = p.knobs()["create_shader_tree"].value()
    if do_tree:
        create_camera_at_and_shader(nuke.selectedNode(), nuke.frame(), do_link)
    else:
        create_camera_at(nuke.selectedNode(), nuke.frame(), do_link)
Ejemplo n.º 3
0
def fixPaths():
    oldDir = ""
    newDir = ""
    scriptDir = os.path.dirname(nuke.root().knob("name").getValue())

    for n in nuke.allNodes():
        #### check node types, supports Read, ReadGeo, or Axis nodes. You may want to add more here..
        if n.Class() == "Read" or n.Class() == "ReadGeo" or n.Class(
        ) == "ReadGeo2" or n.Class() == "Axis2":
            f = n.knob("file")
            filename = f.getValue()
            print 'Filename is ' + filename
            if filename and filename != '':
                basename = os.path.basename(filename)
                frame = getFrame(filename, nuke.frame())
                print "Looking for : " + frame
                if not os.path.exists(frame):
                    filename = filename.replace(oldDir, newDir)
                    frame = getFrame(filename, nuke.frame())
                    print "Looking for new filename " + frame
                    if not os.path.exists(frame):

                        n = nuke.getClipname("Looking for " + filename,
                                             basename, scriptDir)
                        if n != None:
                            (oldDir,
                             newDir) = getCommonBase(os.path.dirname(filename),
                                                     os.path.dirname(n))
                            f.setValue(getFile(n))
                        else:
                            pass
                    else:
                        f.setValue(getFile(filename))
Ejemplo n.º 4
0
def stereoCam(node=None, interoc=.6):
    '''
    Create a simple stereo camera or convert an existing one.
    args:
       node - camera node to convert to stereo. if None a camera will be created
       interoc  -  distance between right and left view
    '''
    try:
        node = node or nuke.selectedNode()
    except ValueError:
        # IF NO NODE IS GIVEN AND NOTHING IS SELECTED, CREATE A NEW NODE
        node = nuke.createNode('Camera2')

    # GET SCRIPT SETTIONGS' VIEWS
    views = nuke.views()
    leftView = views[0]
    rightView = views[1]

    # THE OFFSET AS REQUESTED
    rightOffset = float(interoc) / 2
    leftOffset = -rightOffset

    # THE KNOB TO SPLIT
    if node['useMatrix'].value():
        knob = node['matrix']
        leftEyeMatrix = node['transform'].value(
        )  # GETS MATRIX BUT IN REVERSE ORDER
        rightEyeMatrix = nuke.math.Matrix4(leftEyeMatrix)  # COPY MATRIX

        # GET THE NEW VALUES FOR LEFT AND RIGHT EYE
        leftEyeMatrix.translate(leftOffset, 0, 0)
        rightEyeMatrix.translate(rightOffset, 0, 0)

        # REVERSE FOR ASSIGNMENT
        leftEyeMatrix.transpose()
        rightEyeMatrix.transpose()

        # IF THERE ARE MORE THAN 2 VIEWS MAKE SURE TO SPLIT OFF LEFT VIEW AS WELL
        if len(views) > 2:
            knob.splitView(leftView)
        knob.splitView(rightView)

        # ASSIGN VALUES
        for i in range(16):
            knob.setValueAt(leftEyeMatrix[i], nuke.frame(), i, leftView)
            knob.setValueAt(rightEyeMatrix[i], nuke.frame(), i, rightView)
    else:
        knob = node['translate']
        # GET THE NEW VALUES FOR LEFT AND RIGHT EYE
        leftEye = knob.value(0) + leftOffset
        rightEye = knob.value(0) + rightOffset

        # IF THERE ARE MORE THAN 2 VIEWS MAKE SURE TO SPLIT OFF LEFT VIEW AS WELL
        if len(views) > 2:
            knob.splitView(leftView)
        knob.splitView(rightView)

        # ASSIGN NEW VALUE
        knob.setValue(leftEye, 0, view=leftView)
        knob.setValue(rightEye, 0, view=rightView)
Ejemplo n.º 5
0
def goToPlus():
    
    '''
    Allows you to directly enter simple math signs to
    go to a frame without explicity requiring you to
    enter the current frame number before it.
    '''
    
    cFrame = nuke.frame()
    
    p = nuke.Panel( 'Go to Frame Plus' )
    p.addSingleLineInput( '', '' )
    p.show()

    goTo = p.value( '' )
    pat1 = re.compile( '\+|-|\*|\/' )
    
    if goTo == '':
        return
    elif goTo[0].isdigit() == True and pat1.search( goTo ) == None:
        nuke.frame( int( goTo ) )
    elif goTo[0].isdigit() == True and pat1.search( goTo ) != None:
        try:
            nuke.frame( eval( goTo ) )
        except Exception, e:
            raise RuntimeError( e )
Ejemplo n.º 6
0
def Patcher_():
    a = nuke.createNode("Patcher")
    x = int(a['xpos'].value())
    y = int(a['ypos'].value())
    #a = nuke.nodes."Roto"()
    #a.setXYpos(x+50,y)
    a['from_frame'].setValue(nuke.frame())
    a['to_frame'].setValue(nuke.frame())
    a['cloneframe'].setValue(nuke.frame())
    
    
    g = nuke.toNode("root")['format'].value()
    w = g.width()
    h = g.height()
    a['center'].setValue([w/2,h/2])
    
    
    a['point1'].setAnimated()
    a['point2'].setAnimated()
    a['point3'].setAnimated()
    a['point4'].setAnimated()
    a['point1'].setValue([w/2-100,h/2-100])
    a['point2'].setValue([w/2+100,h/2-100])
    a['point3'].setValue([w/2+100,h/2+100])
    a['point4'].setValue([w/2-100,h/2+100])
Ejemplo n.º 7
0
    def initvalues(self):
        self.appendAnimation = nuke.thisNode().knob("appendAnimation").value()

        if nuke.thisNode().knob(
                "assistStep").value():  #We only run "x" number of frames
            _thisFrame = nuke.frame()
            _startFrame = _thisFrame - int(
                nuke.thisNode().knob("AssistStepSize").value())
            _endFrame = _thisFrame + int(
                nuke.thisNode().knob("AssistStepSize").value())
        else:  #We run the full range
            _thisFrame = nuke.frame()
            _startFrame = int(nuke.thisNode().knob("InputFrom").value())
            _endFrame = int(nuke.thisNode().knob("InputTo").value())
        if self.type == 0:  #Both Ways
            self.frameForRef = _thisFrame
            self.StartFrame = _startFrame
            self.EndFrame = _endFrame
        elif self.type == 1:  #Only forward
            self.frameForRef = _thisFrame
            self.StartFrame = _thisFrame
            self.EndFrame = _endFrame
        elif self.type == 2:  #Only Backwards
            self.frameForRef = _thisFrame
            self.StartFrame = _startFrame
            self.EndFrame = _thisFrame
Ejemplo n.º 8
0
def create_projector_panel():
    if not ensure_camera_selected(nuke.selectedNode()):
        return

    p = nukescripts.panels.PythonPanel("Create a projector")

    k = nuke.Boolean_Knob("link", "Link the projector camera to the original")
    k.setFlag(nuke.STARTLINE)
    k.setTooltip(
        "This will create a live setup that will update when the camera keyframes change"
    )
    p.addKnob(k)

    k = nuke.Boolean_Knob("create_shader_tree",
                          "Create shader tree (FrameHold + project3d)")
    k.setFlag(nuke.STARTLINE)
    k.setTooltip(
        "will also create a FrameHold and a Project3D to spare even more clicks"
    )
    p.addKnob(k)

    result = p.showModalDialog()
    if result == 0:
        return  # Canceled

    # The API called "get value of the field by providing it's UI label" earns the
    # mark of the most f****d up disgusting crap engineering ever (tm)
    do_link = p.knobs()["link"].value()
    do_tree = p.knobs()["create_shader_tree"].value()
    if do_tree:
        create_camera_at_and_shader(nuke.selectedNode(), nuke.frame(), do_link)
    else:
        create_camera_at(nuke.selectedNode(), nuke.frame(), do_link)
Ejemplo n.º 9
0
def goto_frame():
    f = nuke.frame()
    p = nuke.Panel("Goto Frame")
    p.addSingleLineInput("Frame:", f)
    result = p.show()
    if result == 1:
        nuke.frame(int(nuke.expression(p.value("Frame:"))))
Ejemplo n.º 10
0
def fixPaths( ):
  oldDir = ""
  newDir = ""
  scriptDir =  os.path.dirname ( nuke.root().knob("name").getValue() )

  for n in nuke.allNodes():
     #### check node types, supports Read, ReadGeo, or Axis nodes. You may want to add more here..
     if n.Class() == "Read" or n.Class() == "ReadGeo" or n.Class() == "ReadGeo2" or n.Class() == "Axis2":
       f = n.knob( "file" )
       filename =  f.getValue()
       print 'Filename is ' + filename
       if filename and filename != '':
         basename = os.path.basename( filename )
         frame = getFrame( filename, nuke.frame() )
         print "Looking for : " + frame
         if not os.path.exists( frame ):
           filename = filename.replace( oldDir, newDir )
           frame = getFrame( filename, nuke.frame() ) 
           print "Looking for new filename " + frame
           if not os.path.exists( frame ):
  
             n = nuke.getClipname( "Looking for " + filename, basename, scriptDir )
             if n != None:
               (oldDir, newDir) = getCommonBase( os.path.dirname( filename ), os.path.dirname( n ) )
               f.setValue ( getFile(n) )
             else:
               pass
           else:
             f.setValue( getFile(filename) )
Ejemplo n.º 11
0
def thumbnailer():
    selNodes = []
    selNodes = nuke.selectedNodes('Read')
    if not selNodes:
        selNodes = nuke.allNodes('Read')

    for readNode in selNodes:
        readNode.knob('postage_stamp').setValue(False)

        depNodes = readNode.dependent()

        isThumbnailed = False

        for node in depNodes:
            if node.Class() == 'FrameHold' and node.knob(
                    'name').value() == '%s_stamp' % (readNode.name()):
                node.knob('first_frame').setValue(nuke.frame())
                isThumbnailed = True

        if not isThumbnailed:
            nameMask = '%s_stamp' % (readNode.name())
            thumbnailer = nuke.nodes.FrameHold(name=nameMask,
                                               postage_stamp=True,
                                               first_frame=nuke.frame(),
                                               tile_color=4294967295)
            thumbnailer.setInput(0, readNode)
            thumbnailer.setXYpos(readNode.xpos(), readNode.ypos() - 80)
Ejemplo n.º 12
0
    def setShot(self, shot):
        
        try:
            scene = str(shot.split("_")[0])+"_"+str(shot.split("_")[1])
        except:
            scene = 'n/a'
        
        if not shot == 'n/a':
            
            try:
                #cameraGrp = self.node.knob("grpS_"+shot)
                camera = nuke.toNode(self.job+'_'+shot+'_renderCamera')
                #self.node.knob('cameraName').setValue(shot)
            except:
                pass
            try:
                version = camera.knob('versionHub').value()
            except:
                version = 'n/a'
            try:
                self.cameraSwitch.setInput(0, camera)
            except:
                pass
        
        if shot == 'n/a':
            version = 'n/a'
            #self.cameraSwitch.setInput(0)
            
        self.node.knob('shotList').setValue(shot)
        
        #set the timerange
        timeRange = hubUtils.getShotTimeRangeInfo(shot, scene, hubUtils.HubShotTimeRange.WORKING)['workFrameRange']
        
        if timeRange in ['n/a', 'n/a ', 'n/a - n/a', 'n/a-n/a']:
            try:
                camera = nuke.toNode(self.job+'_'+shot+'_renderCamera')
                label = camera.knob('label').value()
                if label:
                    timeRange = str(label)
            except:
                pass
        try:
            self.node.knob('actualCamera').setValue("<FONT COLOR=\"#7777EE\"> v"+version+" :   "+timeRange+"<\FONT>")
            self.node.knob('txt_'+shot).setValue("handles: <FONT COLOR=\"#7777EE\">"+timeRange+"<\FONT>")
        except:
            pass
            
        if not timeRange in ['n/a', 'n/a ', 'n/a - n/a', 'n/a-n/a']:

            firstFrame, lastFrame = timeRange.split('-')[0], timeRange.split('-')[1]
            
            if not firstFrame == 'n/a' and not lastFrame == 'n/a':
                
                # set root frame range
                nuke.root().knob('first_frame').setValue(int(firstFrame))
                nuke.root().knob('last_frame').setValue(int(lastFrame))
                # if the current frame is not in the frame range set frame at the begining of the shot
                if nuke.frame() not in range(int(firstFrame), int(lastFrame)):
                    nuke.frame(int(firstFrame))
	def setFrame(self):
		'''set the frame in nuke when marker is clicked'''
		thisSender = self.sender()
		try:
			nuke.frame(thisSender.frame)
		except:
			pass
		print "%s | %s | %s" % (thisSender.id, thisSender.frame, thisSender.label)
Ejemplo n.º 14
0
def Fader():
    curFrameA = nuke.frame()
    inFrame = nuke.frame() - 1
    outFrame = nuke.frame() + 1
    n = nuke.thisNode()
    k = nuke.thisKnob()
    curValue = k.getValue()
    k.setAnimated()

    class ShapePanel(nukescripts.PythonPanel):
        def __init__(self):
            nukescripts.PythonPanel.__init__(self, 'Fader menu')

            self.Value = nuke.Array_Knob("value", 'value', 4)
            self.Value.setValue(0, 0)
            self.Value.setValue(curValue, 1)
            self.Value.setValue(curValue, 2)
            self.Value.setValue(0, 3)

            self.Frame = nuke.Array_Knob("frame", 'frame', 4)
            self.Frame.setValue(inFrame, 0)
            self.Frame.setValue(curFrameA, 1)
            self.Frame.setValue(curFrameA, 2)
            self.Frame.setValue(outFrame, 3)

            self.Check = nuke.Boolean_Knob('Delete Current Animation')
            self.addKnob(self.Check)

            for k in (self.Frame, self.Value):
                self.addKnob(k)

    ### displays panel
    p = ShapePanel()
    p.showModalDialog()

    ### checks the checkerboard and deletes the animation if selected
    getCheck = p.Check.value()

    if getCheck == True:
        for curve in k.animations():
            curve.clear()

    ### creates the animation
    inV = p.Value.value(0)
    inF = p.Frame.value(0)
    k.setValueAt(inV, inF)

    curV = p.Value.value(1)
    curF = p.Frame.value(1)
    k.setValueAt(curV, curF)

    curVopt = p.Value.value(2)
    curFopt = p.Frame.value(2)
    k.setValueAt(curVopt, curFopt)

    outV = p.Value.value(3)
    outF = p.Frame.value(3)
    k.setValueAt(outV, outF)
Ejemplo n.º 15
0
    def setup(self):
        """Add tag knob to read nodes, then set project framerange."""

        if not nuke.value('root.project_directory'):
            nuke.knob(
                "root.project_directory", r"[python {os.path.join("
                r"nuke.value('root.name', ''), '../'"
                r").replace('\\', '/')}]")

        nodes = nuke.allNodes('Read')
        if not nodes:
            raise FootageError('没有读取节点')

        n = None
        root_format = None
        root = nuke.Root()
        first = None
        last = None
        formats = []

        for n in nodes:
            ReadNode(n)
            format_ = n.format()
            assert isinstance(format_, nuke.Format)
            if not n.hasError():
                formats.append((format_.width(), format_.height()))
            n_first, n_last = n.firstFrame(), n.lastFrame()

            # Ignore single frame.
            if n_first == n_last:
                continue

            # Expand frame range.
            if first is None:
                first = n_first
                last = n_last
            else:
                first = min(last, n.firstFrame())
                last = max(last, n.lastFrame())

        if first is None:
            first = last = 1

        root_format = root_format or n.format()

        root['first_frame'].setValue(first)
        root['last_frame'].setValue(last)
        nuke.frame((first + last) / 2)
        root['lock_range'].setValue(True)
        try:
            format_ = sorted([(formats.count(i), i)
                              for i in set(formats)])[-1][1]
            root['format'].setValue(nuke.addFormat('{} {}'.format(*format_)))
        except IndexError:
            root['format'].setValue('HD_1080')
            LOGGER.warning('不能获取工程格式, 使用默认值HD_1080')

        root['fps'].setValue(self.fps)
Ejemplo n.º 16
0
def change_framerange_from_read():

	cur_node = nuke.selectedNode()
	first_frame = cur_node["first"].value()
	last_frame = cur_node["last"].value()
	nuke.Root()['first_frame'].setValue(first_frame)
	nuke.Root()['last_frame'].setValue(last_frame)

	nuke.frame(cur_node["first"].value())
Ejemplo n.º 17
0
    def after_frame(self):
        """write a per framecatcher file and compacts into one large file."""
        if self._enable:
            if self._firstframe:
                self._firstframe = False
                for fc in self._catchers:
                    hackframestring = '{frm:0' + str(self._padding) + 'd}.txt'
                    hackframestring = hackframestring.format(frm=nuke.frame())
                    oldname = re.sub(fc['frame_fragment'].evaluate(),
                                     FIRSTFRAMESTRING,
                                     fc['out_file'].evaluate())

                    newname = re.sub(fc['frame_fragment'].evaluate(),
                                     hackframestring,
                                     fc['out_file'].evaluate())
                    try:
                        os.remove(newname)
                    except:
                        pass

                    # oh FFS. this assumes an output was generated, which
                    # isn't the case when you have unconnected read nodes
                    # as they will never be evaluated in the tree
                    try:
                        os.rename(oldname, newname)
                    except:
                        pass

            # we should deal with this. It's such an annoying fix required
            # this is a weird +1/-1 offset strangeness
            # just using the first one in the list. FuryFX pipe doesn't support
            # the more complex general case yet..

            newfile_prefix = self._prefix
            rootdir = self._catchers[0]['root_fragment'].evaluate()
            framestring = '{frm:0' + str(self._padding) + 'd}.txt'
            framestring = framestring.format(frm=nuke.frame())
            candidates = os.listdir(rootdir)
            candidates = [x for x in candidates
                          if os.path.isfile(os.path.join(rootdir, x)) and
                          x.endswith(framestring)]
            compacted_output = os.path.join(rootdir,
                                            newfile_prefix + '.' + framestring)
            try:
                os.remove(compacted_output)
            except:
                pass

            with open(compacted_output, 'w') as fp_out:
                for x in candidates:
                    with open(os.path.join(rootdir, x)) as fp_in:
                        lines = fp_in.readlines()
                        fp_out.write(''.join(lines))
            for x in candidates:
                os.remove(os.path.join(rootdir, x))   # delayed cleanup.
Ejemplo n.º 18
0
def _jump_frame():
    if nuke.numvalue('preferences.wlf_jump_frame', 0.0):
        LOGGER.debug('Jump frame')
        try:
            n = wlf_write_node()
        except ValueError:
            LOGGER.warning('No `wlf_Write` node.')
            return
        if n:
            nuke.frame(n['frame'].value())
            nuke.Root().setModified(False)
Ejemplo n.º 19
0
def onMousePos(pos):

    # set new frame if mouse is pressed
    if (scr_mouseDown):

        # get frame relative to screen width
        newFrameNorm = (pos[0] -
                        scr_lastPos) / float(scr_scrWidth) * scr_scrubSpeed
        newFrame = newFrameNorm * scr_rangeLength + scr_lastFrame

        # set frame
        nuke.frame(newFrame)
Ejemplo n.º 20
0
def replace_sequence():
    # TODO: Need refactor and test.
    '''Replace all read node to specified frame range sequence.  '''

    # Prepare Panel
    panel = nuke.Panel(b'单帧替换为序列')
    label_path_prefix = b'限定只替换此文件夹中的读取节点'
    label_first = b'设置工程起始帧'
    label_last = b'设置工程结束帧'

    panel.addFilenameSearch(label_path_prefix, 'z:/')
    panel.addExpressionInput(label_first,
                             int(nuke.Root()['first_frame'].value()))
    panel.addExpressionInput(label_last,
                             int(nuke.Root()['last_frame'].value()))

    confirm = panel.show()
    if confirm:
        render_path = os.path.normcase(u(panel.value(label_path_prefix)))

        first = int(panel.value(label_first))
        last = int(panel.value(label_last))
        flag_frame = None

        nuke.Root()[b'proxy'].setValue(False)
        nuke.Root()[b'first_frame'].setValue(first)
        nuke.Root()[b'last_frame'].setValue(last)

        for n in nuke.allNodes('Read'):
            file_path = u(nuke.filename(n))
            if os.path.normcase(file_path).startswith(render_path):
                search_result = re.search(r'\.([\d]+)\.', file_path)
                if search_result:
                    flag_frame = search_result.group(1)
                file_path = re.sub(
                    r'\.([\d#]+)\.',
                    lambda matchobj: r'.%0{}d.'.format(len(matchobj.group(1))),
                    file_path)
                n[b'file'].setValue(file_path.encode('utf-8'))
                n[b'format'].setValue(b'HD_1080')
                n[b'first'].setValue(first)
                n[b'origfirst'].setValue(first)
                n[b'last'].setValue(last)
                n[b'origlast'].setValue(last)

        n = wlf_write_node()
        if n:
            if flag_frame:
                flag_frame = int(flag_frame)
                n[b'custom_frame'].setValue(flag_frame)
                nuke.frame(flag_frame)
            n[b'use_custom_frame'].setValue(True)
Ejemplo n.º 21
0
def executeSelection(firstFrame=nuke.frame(), lastFrame=nuke.frame()):
    nodes = nuke.selectedNodes()
    if nodes:
        try:
            for node in nodes:
                nuke.frame(firstFrame)
                print "executing", node.name(), nuke.frame()
                print 'writing', node['file'].getValue()
                nuke.execute(node, firstFrame, lastFrame)
        except:
            print 'cannot execute', node.name(), '...'
        print 'all done.'
    else:
        nuke.message("Please select some write nodes!")
Ejemplo n.º 22
0
def doIT():
    n = nuke.selectedNode()
    print '_'*20
    print 'Selected Node on which the calculation will be processed %s' %n['name'].value()
    
    first   = nuke.Root()['first_frame'].value()
    last    = nuke.Root()['last_frame'].value()
    total   = last - first
    
    maxBBoxX = nuke.toNode('FrameBlend1').bbox().x()
    maxBBoxY = nuke.toNode('FrameBlend1').bbox().y()
    maxBBoxR = nuke.toNode('FrameBlend1').bbox().w() + maxBBoxX
    maxBBoxT = nuke.toNode('FrameBlend1').bbox().h() + maxBBoxY
    
    maxBBox = [maxBBoxX, maxBBoxY, maxBBoxR, maxBBoxT]
    print 'Value of the BBox '+str(maxBBox)
    
    task        = nuke.ProgressTask('Getting Frame for max BBox\n value at x,y,r,t')
    progIncr    = 100.0 / total
    result      = []
    for frame in xrange(int(first), int(last)):
        
        frame = float(frame)

        if task.isCancelled():
            nuke.executeInMainThread(nuke.message, args=('Calculation aborted'))
            return
        
        
        nuke.frame(frame)
        time.sleep(.1)
        
        # if n.bbox().x() == maxBBox[0]:
        #     print 'x found at frame %f' %frame
        #     result.append(('x', frame))
        # if n.bbox().y() == maxBBox[1]:
        #     print 'y found at frame %f' %frame
        #     result.append(('y', frame))
        print frame, n.bbox().w()-maxBBox[0], maxBBox[2]
        if n.bbox().w() == maxBBox[2]:
            print 'r found at frame %f' %frame
        if n.bbox().h() == maxBBox[3]:
            print 't found at frame %f' %frame
        
        task.setProgress(int(frame * progIncr))
        task.setMessage('Processing frame : '+str(frame))

    return 
Ejemplo n.º 23
0
def createThumbnail():
    try:
        sel = nuke.selectedNode()
    except:
        nuke.message("Need to select a node!")

    scriptsPath = nuke.selectedNode().knob('file').value().split(".")[0]
    clipname = scriptsPath.split("/")[-1]
    scriptsPath = scriptsPath.split('\\' + clipname)[0]
    scriptName = nuke.selectedNode().knob('file').value().split(".dpx")[0]
    scriptName = scriptName.split("/")[-1]

    #create thumbnail dir if not exist
    thumbnailDir = scriptsPath.split('PROD')[0]
    thumbnailDir = thumbnailDir + "PROD/Thumbnail/"
    if not os.path.isdir(thumbnailDir):
        os.makedirs(thumbnailDir)

    #full thumbnail path
    fullThumbnailPath = "{thumbnailDir}/{nodeName}_{frame}.{ext}".format(
        thumbnailDir=thumbnailDir,
        nodeName=clipname,
        frame=nuke.frame(),
        ext=fileType)

    #reformat node
    r = nuke.createNode("Reformat", inpanel=False)
    r.setInput(0, sel)
    r.setXYpos(sel.xpos(), sel.ypos() + 50)
    r["type"].setValue("scale")
    r["scale"].setValue(imageSize)

    #write node
    w = nuke.createNode("Write", inpanel=False)
    w.setInput(0, r)
    w.setXYpos(r.xpos(), r.ypos() + 50)
    w.knob("name").setValue("capture")
    w.knob("use_limit").setValue(True)
    w.knob("first").setValue(nuke.frame())
    w.knob("last").setValue(nuke.frame())
    w.knob("file_type").setValue(fileType)
    w.knob("file").setValue(fullThumbnailPath)
    nuke.execute(w, nuke.frame(), nuke.frame())

    nuke.delete(r)
    nuke.delete(w)

    nuke.message(clipname + " \n\nThumbnail OK")
Ejemplo n.º 24
0
def verticesFromInput(group):
    ''' return the points in the emitter geo that we want to stick cards to '''

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

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

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

    pythonGeoIn = nuke.toNode('EmitterPythonGeoIn')
    selectedPoints = pythonGeoIn['geo'].getSelection()

    # write out a file to read vertices from
    writeGeo = nuke.toNode('WriteEmitterGeo')
    writeGeo['file'].setValue(tmpPath)
    nuke.execute(writeGeo['name'].value(), nuke.frame(), nuke.frame())

    # read it back in and we get true vertiex positions in the PythonGeo node
    readGeo = nuke.toNode('ReadEmitterGeo')
    readGeo['file'].setValue(tmpPath)

    # get a list of vertices
    pythonGeoOut = nuke.toNode('EmitterPythonGeoOut')
    allTheGeo = pythonGeoOut['geo'].getGeometry()
    theGeoObj = allTheGeo[0]
    vList = theGeoObj.points()

    # remove the temp file, we no longer need it
    os.remove(tmpPath)

    # convert the list of vertices into a list of points
    allPoints = []
    p = []
    for v in vList:
        p.append(v)
        if len(p) == 3:
            allPoints.append(p)
            p = []

    return allPoints
Ejemplo n.º 25
0
    def createCamera(self, basecamera, framerange, cameraData, usematrix):
        """ create a new bake camera """

        camera = nuke.createNode('Camera2', inpanel =  False)
        camera.setName(basecamera.name()+'_bakedCamera')
            
        for frame in range(framerange[0], framerange[1]+1):
            nuke.frame(frame)
            attributes = cameraData[frame]

            if usematrix:
                camera.knob('useMatrix').setValue(True)
                camera.knob('matrix').setValue(attributes['matrix'])
                camera.knob('matrix').setKeyAt(frame)
            else:
                camera.knob('translate').setValue(attributes['translate'])
                camera.knob('translate').setKeyAt(frame)
                camera.knob('rotate').setValue(attributes['rotate'])
                camera.knob('rotate').setKeyAt(frame)
                camera.knob('scaling').setValue(attributes['scaling'])
                camera.knob('scaling').setKeyAt(frame)

            camera.knob('focal').setValue(attributes['focal'])
            camera.knob('focal').setKeyAt(frame)

            camera.knob('haperture').setValue(attributes['hap'])
            camera.knob('vaperture').setValue(attributes['vap'])
            camera.knob('haperture').setKeyAt(frame)
            camera.knob('vaperture').setKeyAt(frame)

            camera.knob('near').setValue(attributes['near'])
            camera.knob('far').setValue(attributes['far'])
            camera.knob('near').setKeyAt(frame)
            camera.knob('far').setKeyAt(frame)
            
            camera.knob('xform_order').setValue(attributes['trOrder'])
            camera.knob('rot_order').setValue(attributes['rotOrder'])
            camera.knob('xform_order').setKeyAt(frame)
            camera.knob('rot_order').setKeyAt(frame)
            
            camera.knob('win_translate').setValue(attributes['win_translate'])
            camera.knob('win_translate').getValueAt(frame)

            camera.knob('xpos').setValue(basecamera.knob('xpos').value()+100)
            camera.knob('ypos').setValue(basecamera.knob('ypos').value())
            
        return camera
        
Ejemplo n.º 26
0
    def addHotkey(self, _mime=None):
        viewer_node = nuke.activeViewer().node()
        viewerrange = viewer_node['frame_range'].value().split("-")
        timeLock = viewer_node['frame_range_lock'].value()
        timeIn = viewerrange[0]
        timeOut = viewerrange[1]
        globalIn = nuke.root()['first_frame'].value()
        globalOut = nuke.root()['last_frame'].value()
        frame = None
        iText = "%s - %s" % (timeIn, timeOut)
        node = None
        reference = None

        p = nuke.Panel('Save Hotkey')
        p.addSingleLineInput('Set shortcut name', "%s" % (nuke.frame()))
        p.addBooleanCheckBox('Save Frame Range', 1)
        p.addBooleanCheckBox('Save Current Frame', 1)
        p.addBooleanCheckBox('Save Viewed Node', 0)
        if _mime:
            p.addEnumerationPulldown('Save Data From', 'Knob Node')

        p.addButton('Cancel')
        p.addButton('Ok')
        ret = p.show()
        if ret:
            iText = p.value('Set shortcut name')
            if p.value('Save Viewed Node'):
                try:
                    node = viewer_node.input(nuke.activeViewer().activeInput())
                except:
                    node = None
            if p.value('Save Current Frame'):
                frame = nuke.frame()
            if _mime:  #If the user did a knob drop
                strSplit = _mime.split(":")[-1].split(".")
                if p.value('Save Data From') == "Knob":
                    reference = nuke.toNode(".".join(
                        strSplit[0:-1]))[strSplit[-1]]
                else:
                    reference = nuke.toNode(".".join(strSplit[0:-1]))

            hotkeyButton = TimeHotkeysButton(timeIn, timeOut, globalIn,
                                             globalOut, timeLock, frame, node,
                                             iText, reference)
            hotkeyButton.clicked.connect(self.pressedHotkey)
            hotkeyButton.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
            hotkeyButton.customContextMenuRequested.connect(self.rightclicked)
            self.generalLayout.addWidget(hotkeyButton)
Ejemplo n.º 27
0
def setRefToCurFrame(node):
    n = node
    frame = nuke.frame()

    fromOne = n['from1']
    fromTwo = n['from2']
    fromThree = n['from3']
    fromFour = n['from4']

    toOne = n['to1'].getValue()
    toTwo = n['to2'].getValue()
    toThree = n['to3'].getValue()
    toFour = n['to4'].getValue()

    fromOne.clearAnimated()
    fromTwo.clearAnimated()
    fromThree.clearAnimated()
    fromFour.clearAnimated()

    fromOne.setValue(toOne)
    fromTwo.setValue(toTwo)
    fromThree.setValue(toThree)
    fromFour.setValue(toFour)

    result = "cornerPin reference frame set to frame %s" % frame

    return result
def relative_cornerpins():
    cornerpin = nuke.selectedNode()

    try:
        for i in range(1, 5):
            cornerpin['from' + str(i)].clearAnimated()
            print "Animation Deleted"
    except AttributeError:
        pass


    for i in range(1, 5):
        to = cornerpin['to' + str(i)].value()
        cornerpin['from' + str(i)].setValue(to)


    current_frame = nuke.frame()

    current_label_lst = cornerpin['label'].value().lower().replace(' ', '\n').split('\n')

    programs = ['nuke', 'mocha']
    program = None
    for prog in programs:
        if prog in current_label_lst:
            program = prog

    label = '{}\nx{}'.format(program.upper(), current_frame)
    cornerpin['label'].setValue(label)
Ejemplo n.º 29
0
def bakeProjection(mb):
    """Create a projection setup for the current frame."""
    if mb.Class() != "ModelBuilder":
        return

    clearNodeSelection()
    srcCam = mb.input(1)
    if not srcCam:
        return
    w = mb.screenWidth()
    h = mb.screenHeight()
    src = mb.input(0)
    frame = nuke.frame()
    if (mb['textureType'].getValue() > 0):
        frame = mb['textureFrame'].getValue()
    label = '(frame ' + str(frame) + ')'

    srcdot = nuke.createNode('Dot', '', False)
    srcdot.setInput(0, src)
    srchold = nuke.createNode('FrameHold', '', False)
    stamp = nuke.createNode('PostageStamp', '', False)
    project = nuke.createNode('Project3D', '', False)
    apply = nuke.createNode('ApplyMaterial', '', False)

    cam = copyCamera(srcCam)

    camhold = nuke.clone(srchold, '', False)
    camdot = nuke.createNode('Dot', '', False)
    project.setInput(1, camdot)

    srcdot.setXYpos(int(mb.xpos() + w * 3.5), int(mb.ypos()))
    srchold.setXYpos(int(srchold.xpos()), int(srcdot.ypos() + w))
    stamp.setXYpos(int(stamp.xpos()),
                   int(stamp.ypos() + srchold.screenHeight() + h * 2))
    cam.setXYpos(
        int(srchold.xpos() - w * 1.5),
        int(srchold.ypos() + srchold.screenHeight() / 2 -
            cam.screenHeight() / 2))
    camhold.setXYpos(
        int(cam.xpos() + cam.screenWidth() / 2 - srchold.screenWidth() / 2),
        int(stamp.ypos() + h))
    project.setXYpos(int(stamp.xpos()),
                     int(stamp.ypos() + stamp.screenHeight() + h * 2))
    camdot.setXYpos(
        int(camdot.xpos()),
        int(project.ypos() + project.screenHeight() / 2 -
            camdot.screenHeight() / 2))
    apply.setXYpos(int(stamp.xpos()), int(apply.ypos() + w))

    srchold.knob('first_frame').setValue(frame)
    srcdot.setSelected(True)
    srchold.setSelected(True)
    stamp.setSelected(True)
    project.setSelected(True)
    apply.setSelected(True)
    cam.setSelected(True)
    camhold.setSelected(True)
    camdot.setSelected(True)
    bd = nukescripts.autoBackdrop()
    bd['label'].setValue('Frame %d' % frame)
Ejemplo n.º 30
0
def get_min_max(src_node, channel='depth.Z'):
    '''
    Return the min and max values of a given node's image as a tuple

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

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

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

    for n in (min_color, max_color, inv):
        nuke.delete(n)
    return min_v, max_v
Ejemplo n.º 31
0
def saveImage(sel, renderTo, filetype):

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

	openFolder(renderTo)
Ejemplo n.º 32
0
def cornerPinToTracker():

    cp = nuke.selectedNode()

    cp1 = cp["to1"].animations()
    cp2 = cp["to2"].animations()
    cp3 = cp["to3"].animations()
    cp4 = cp["to4"].animations()

    tr = nuke.createNode("Tracker3")
    tr.knob("enable2").setValue("True")
    tr.knob("enable3").setValue("True")
    tr.knob("enable4").setValue("True")
    tr.knob("warp").setValue("srt")
    tr.knob("transform").setValue("match-move")
    tr.knob("use_for1").setValue("all")
    tr.knob("use_for2").setValue("all")
    tr.knob("use_for3").setValue("all")
    tr.knob("use_for4").setValue("all")
    tr.knob("reference_frame").setValue(nuke.frame())

    nuke.toNode(tr.knob("name").value())["track1"].copyAnimations(cp1)
    nuke.toNode(tr.knob("name").value())["track2"].copyAnimations(cp2)
    nuke.toNode(tr.knob("name").value())["track3"].copyAnimations(cp3)
    nuke.toNode(tr.knob("name").value())["track4"].copyAnimations(cp4)
Ejemplo n.º 33
0
def init_common_vars(snapsDir=None):
    """
    Initialize common variables used in other functions
    :rtype : dictionary
    :param snapsDir: Script root directory + /snaps
    :return: Dict with all common variables
    """
    all_vars = {}
    scriptPath = nuke.toNode('root').knob('name').value()
    scriptName = scriptPath.split("/")[-1]
    timestamp = time.strftime("%d-%m-%Y") + '_' + time.strftime("%H-%M")
    snapPath = snapsDir + '/' + scriptName + '_' + timestamp
    snapScriptName = snapPath + "/" + scriptName + '_' + timestamp + '.nk'
    snapImageFile = snapPath + "/" + scriptName + '_' + timestamp + '.jpg'
    snapCommentFile = snapPath + "/" + scriptName + '_' + timestamp + '.txt'
    currentFrame = int(nuke.frame())
    fakeFrameRange = str(currentFrame) + "-" + str(currentFrame)
    writeUniqueName = "tmp_Snapshotr" + timestamp
    nodeLabel = "<b>SNAP</b><br />" + str(time.strftime("%d-%m-%Y")).replace(
        "-", ".") + ' ' + str(time.strftime("%H-%M")).replace("-", ":")
    all_vars.update({
        "scriptPath": scriptPath,
        "scriptName": scriptName,
        "timestamp": timestamp,
        "snapPath": snapPath,
        "snapScriptName": snapScriptName,
        "snapImageFile": snapImageFile,
        "snapCommentFile": snapCommentFile,
        "currentFrame": currentFrame,
        "fakeFrameRange": fakeFrameRange,
        "writeUniqueName": writeUniqueName,
        "nodeLabel": nodeLabel
    })
    return all_vars
Ejemplo n.º 34
0
def dieBefore():
    n = nuke.thisNode()
    F = nuke.frame()
    e = n['lifetime_end'].getValue()
    n['lifetime_type'].setValue(4)
    n['lifetime_start'].setValue(F)
    n['lifetime_end'].setValue(e)
Ejemplo n.º 35
0
def dieAfter():
    n = nuke.thisNode()
    F = nuke.frame()
    s = n['lifetime_start'].getValue()
    n['lifetime_type'].setValue(4)
    n['lifetime_end'].setValue(F)
    n['lifetime_start'].setValue(s)
Ejemplo n.º 36
0
def Solve2DTracker(_node):
    #Define Variables
    solve_method = int(nuke.thisNode().knob(
        "AssistType").getValue())  #0 = Local, 1 = Median, 2 = Average
    frameForRef = nuke.frame()
    StartFrame = int(nuke.thisNode().knob("InputFrom").value())
    EndFrame = int(nuke.thisNode().knob("InputTo").value())

    #Grap the number of trackers.
    n_tracks = int(_node["tracks"].toScript().split(" ")[3])

    #Constants etc.
    numColumns = 31
    colTrackX = 2
    colTrackY = 3
    RefPointList = []

    for x in range(0, n_tracks):
        track_a = [
            float(_node.knob("tracks").getValue(numColumns * x + colTrackX)),
            float(_node.knob("tracks").getValue(numColumns * x + colTrackY))
        ]
        RefPointList.append(track_a)
    print "the ref point list:", RefPointList

    #Grap data from the camera tracker and convert it into a format we can use.
    PointData = GrabListData()

    print "--Initializing Main Loop--"
    trackIdx = 0
    for item in RefPointList:
        temp_pos = item
        #--------------------------
        #Resolve backwards [<-----]
        for frame in reversed(range(StartFrame, frameForRef)):
            RefPointList = GetAnimtionList(PointData[0], PointData[1], frame,
                                           True)
            _xy = CalculatePositionDelta(solve_method, RefPointList, temp_pos)
            temp_pos = [
                temp_pos[0] + _xy[0], temp_pos[1] + _xy[1]
            ]  #Add our calculated motion delta to the current position
            _node.knob("tracks").setValueAt(temp_pos[0], frame,
                                            numColumns * trackIdx + colTrackX)
            _node.knob("tracks").setValueAt(temp_pos[1], frame,
                                            numColumns * trackIdx + colTrackY)

        #-------------------------
        #Resolve forwards [----->]
        temp_pos = item
        for frame in range(frameForRef, EndFrame):
            RefPointList = GetAnimtionList(PointData[0], PointData[1], frame)
            _xy = CalculatePositionDelta(solve_method, RefPointList, temp_pos)
            temp_pos = [
                temp_pos[0] + _xy[0], temp_pos[1] + _xy[1]
            ]  #Add our calculated motion delta to the current position
            _node.knob("tracks").setValueAt(temp_pos[0], frame + 1,
                                            numColumns * trackIdx + colTrackX)
            _node.knob("tracks").setValueAt(temp_pos[1], frame + 1,
                                            numColumns * trackIdx + colTrackY)
        trackIdx += 1
Ejemplo n.º 37
0
	def testDefaultExpression( self ) :

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

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

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

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

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

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

		nuke.scriptClear()

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

		fnOH = IECoreNuke.FnOpHolder( n )
		self.assertEqual( fnOH.node().knob( "parm_a" ).toScript(), "2" )
Ejemplo n.º 38
0
    def _update_gaps_listWidget(self):
        """
        Clear the Gaps List widget and re-fill with stored gaps information.
        """
        list_widget = self.ui.gapsList_list_listWidget
        list_widget.clear()

        if len(self._gaps_container) <= 0:
            return

        for gap in self._gaps_container:
            item_str = gap.get("repr")
            list_widget.addItem(item_str)

        cur_frame = nuke.frame()
        ind = 0  # Fallback default.
        for ind, gap in enumerate(self._gaps_container):
            gap_start = gap.get("start")
            gap_end = gap.get("end")
            if gap_start <= cur_frame <= gap_end:
                # Found the gap where current Viewer frame is.
                break

        # Check if current frame is outside of known Keyframe gaps.
        lowest_known = min(self._gaps_container, key=itemgetter("start"))
        highest_known = max(self._gaps_container, key=itemgetter("end"))
        if cur_frame <= lowest_known.get("start"):
            ind = self._gaps_container.index(lowest_known)
        elif cur_frame >= highest_known.get("end"):
            ind = self._gaps_container.index(highest_known)

        list_widget.setCurrentRow(ind)
Ejemplo n.º 39
0
    def testDefaultExpression(self):

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

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

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

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

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

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

        nuke.scriptClear()

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

        fnOH = IECoreNuke.FnOpHolder(n)
        self.assertEqual(fnOH.node().knob("parm_a").toScript(), "2")
Ejemplo n.º 40
0
def toggle(knob):
  """ "Inverts" some flags on the selected nodes.

  What this really does is set all of them to the same value, by finding the
  majority value and using the inverse of that."""

  value = 0
  n = nuke.selectedNodes()
  for i in n:
    try:
      val = i.knob(knob).value()
      if val:
        value += 1
      else:
        value -= 1
    except:
      pass

  status = value < 0
  for i in n:
    if not nuke.exists(i.name()+"."+knob):
      continue
    knobbie = i.knob(knob)
    knobbie_str = i.name()+"."+knob
    size = nuke.animation(knobbie_str, "size")
    if size is not None and int(size) > 0:
      knobbie.setKeyAt(nuke.frame())
      knobbie.setValue(status)
    else:
      knobbie.setValue(status)
    nuke.modified(True)
Ejemplo n.º 41
0
 def get_matrix_from_knob(knob):
     m_value = knob.valueAt(nuke.frame())
     m = nuke.math.Matrix4()
     for i in range(16):
         m[i] = m_value[i]
     m.transpose()
     return m
Ejemplo n.º 42
0
def sb_onOff():

    sn = nuke.selectedNodes()

    if len(sn) == 0:
        nuke.message("Select a node.")
        return

    frame = int(nuke.frame())

    p = nuke.Panel( "sb_onoff" )
    p.addSingleLineInput( "first frame:", "")
    p.addSingleLineInput( "last frame:", "")
    result = p.show()

    if result:

        ff = int(p.value("first frame:"))
        lf = int(p.value("last frame:"))

        for i in nuke.selectedNodes():
            m = nuke.createNode("Multiply", inpanel = False)
            m["channels"].setValue("all")
            val = m["value"]
            val.setAnimated()
            val.setValueAt(1, ff)
            val.setValueAt(1, lf)
            val.setValueAt(0, ff-1)
            val.setValueAt(0, lf+1)
            m.setInput(0, i)
            m["xpos"].setValue(i["xpos"].value())
            m["ypos"].setValue(i["ypos"].value() + 75)
            m["selected"].setValue(False)
            i["selected"].setValue(False)
Ejemplo n.º 43
0
def texConvert():
    """ converts an exr to tex """
    node = nuke.thisNode()
    convert = node.knob('texConvertCheckbox').value()

    if convert == True:
        currentFrame = nuke.frame() 

        fileIn = node.knob('file').getValue().replace('.####.','.%s.' %currentFrame).replace('.%4d.','.%s.' %currentFrame)
        ext = fileIn.split('.')[-1]
        fileOut = fileIn.replace('/%s/' %ext,'/tex/').replace('.%s' %ext,'.tex').replace('.####.','.%s.' %currentFrame).replace('.%4d.','.%s.' %currentFrame)
        
        mode = node.knob('mode').value()
        pattern = node.knob('pattern').value()
        format = node.knob('format').value()
        resize = node.knob('resize').value()
        filterValue = node.knob('filter').value()
        mipfilter = node.knob('mipfilter').value()
        otherFlags = node.knob('otherFlags').value()
        
        #if resize == 'none':
        #    command = 'txmake -verbose -float -pattern %s -mode %s -resize %s %s %s %s\n' %(pattern, format, mode, resize, otherFlags, fileIn, fileOut)
        #else:
        command = 'txmake -verbose -float -pattern %s -mode %s -format %s -resize %s -filter %s -mipfilter %s %s %s %s\n' %(pattern, mode, format, resize, filterValue, mipfilter, otherFlags, fileIn, fileOut)
        print '> converting tex...'
        print command
        popObj = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        out = popObj.communicate()

        print out[0]
Ejemplo n.º 44
0
def render_png(nodes, frame=None, show=False):
    """create png for given @nodes."""

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

        nuke.delete(n)
    if show:
        webbrowser.open(
            os.path.join(nuke.value('root.project_directory'), script_name))
Ejemplo n.º 45
0
def BreakDowner(listNodes = nuke.selectedNodes()):

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

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

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

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

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

        w['file'].setValue(fileKnob)

        #write
        nuke.execute(w['name'].value(), int(nuke.frame()), int(nuke.frame()))
Ejemplo n.º 46
0
def setRefFrame():
	"""
	set ref Frame to current positioners frame
	"""
	
	sel = nuke.selectedNode()
	if "Tracker" in sel.Class():
		sel.knob("reference_frame").setValue(nuke.frame())
Ejemplo n.º 47
0
def getOffset(verbose=False):
    numViews=len(nuke.views())
    #sn=nuke.selectedNodes()
    #s=len(sn)
        
    firstKeyFound=0
    offset=0
    keysList=[]

    nuke.root().begin()   
    for node in nuke.allNodes():
        if node.Class() not in exclusionList:
            nodeAnimated=isNodeAnimated(node)
            print node['name'].value(), nodeAnimated
            if nodeAnimated :
                #loop through and find largest offset
                for knob in node.knobs().values():
                    if knob.isAnimated():
                        try:
                            aSize = knob.arraySize()
                            for index in range(aSize):
                                  for vues in range(numViews+1):
                                    anim = knob.animation(index,vues)
                                    numKeys=anim.size()
                                    if numKeys:
                                        for i in range(numKeys):
                                            keySelected= (anim.keys()[i].selected)
                                            if keySelected:
                                                firstKeyFound+=1
                                                keyVals= (anim.keys()[i].x, anim.keys()[i].y)
                                                if firstKeyFound==1:
                                                    offset=nuke.frame()-keyVals[0]
                                                else:
                                                    foundKey=nuke.frame()-keyVals[0]
                                                    if foundKey>offset:
                                                        offset=foundKey
                                                    if verbose:
                                                        print (foundKey,offset)     
                        except:
                            continue
        else:
            print ('Skipped Node ' + str(node['name'].value()))
        if verbose:
            print (' : FirstKeyFound is '+ str(firstKeyFound) + ' : offset is' + str(offset))

    return (offset)
Ejemplo n.º 48
0
def fetchReadNode():
    # ...
    node = nuke.thisNode()
    print str(node.name())
    read = fetchReadNodeInTree(node)
    if read:
        print str(read.name())
        if os.path.exists(read['file'].getEvaluatedValue()):
            print str(nuke.frame())
            print str(read.name()), 'the file '+str(read['file'].getEvaluatedValue())+' exists ...'
Ejemplo n.º 49
0
def frame_hold_set(node):
  if not node:
    return
  elif not node.Class() == 'FrameHold':
    return
  else:
    node['first_frame'].setValue(nuke.frame())
    tab_knob = nuke.Tab_Knob("SetThisFrame", "SetThisFrame")
    node.addKnob(tab_knob)
    script_btn = nuke.PyScript_Knob("SetThisFrame", "SetThisFrame")
    node.addKnob(script_btn)
    node.knob("SetThisFrame").setCommand(SET_CMD)
Ejemplo n.º 50
0
def transformFromMatrix(node, frame = nuke.frame(), SetScale = False):
    #Takes: node as nuke node reference
    #Performs: populates translate, rotate, and scale knobs on node from it's matrix values
    #          sets useMatrix to false to allow for gui transformations
    #Returns: translate, rotate, and scale values
    nuke.frame(frame)
    worldMatrix = node.knob('world_matrix')
    worldMatrixAt = node.knob('world_matrix').getValueAt(frame)

    matrix = nuke.math.Matrix4()

    worldMatrix = node.knob('world_matrix')
    matrix = nuke.math.Matrix4()
    for y in range(worldMatrix.height()):
        for x in range(worldMatrix.width()):
            matrix[x+(y*worldMatrix.width())] = worldMatrixAt[y+worldMatrix.width()*x]
  
    transM = nuke.math.Matrix4(matrix)
    transM.translationOnly()
    rotM = nuke.math.Matrix4(matrix)
    rotM.rotationOnly()
    scaleM = nuke.math.Matrix4(matrix)
    scaleM.scaleOnly()
  
    if SetScale == True:
        scale = (scaleM.xAxis().x, float(scaleM.yAxis().y)*-1, float(scaleM.zAxis().z)*-1)
    else:
        scale = (scaleM.xAxis().x, scaleM.yAxis().y, scaleM.zAxis().z)
    rot = rotM.rotationsZXY()
    rotate = (math.degrees(rot[0]), math.degrees(rot[1]), math.degrees(rot[2]))
    translate = (transM[12], transM[13], transM[14])
          
    node['translate'].setValue(translate)
    node['rotate'].setValue(rotate)
    node['scaling'].setValue(scale)
    node['useMatrix'].setValue(False)
    return translate, rotate, scale
Ejemplo n.º 51
0
    def before_frame(self):
        """Function call before frame render in the Write node.

        This function sets up the output file target matched to frame number,
        enables monitoring, and twiddles the clock bit to force upstream cook.
        """
        if self._enable:
            framestring = '{frm:0' + str(self._padding) + 'd}.txt'
            framestring = framestring.format(frm=nuke.frame() + 1)
            for fc in self._catchers:
                fc['frame_fragment'].setValue(framestring)
                fc['monitor_enable'].setValue(True)
                fc['write_enable'].setValue(True)
                fc['disable'].setValue(False)
                fc['clock'].setValue(not fc['clock'].value())
Ejemplo n.º 52
0
    def allSyncUpdate (self) :
        if (not self.running) :
            return

        if (self.syncReadChanges) :

            readNodes = [ n.name() for n in nuke.allNodes() 
                    if (type(n).__name__ == "Node" and
                    (n.Class() == "Read" or n.Class() == "Write")) ]
            if (readNodes) :
                self.queueCommand ("self.viewReadsInRv(%s)" % str(readNodes))

            self.queueCommand ("self.removeObsoleteReads()")

        if (self.syncSelection) :
            self.updateAndSyncSelection (True)

        if (self.syncFrameChange) :
            self.queueCommand ("self.changeFrame(%d)" % nuke.frame())
Ejemplo n.º 53
0
def  FreezeFrom():

  for n in nuke.selectedNodes():
    CurFrame = nuke.frame()
    ## Copy all animation in the 'from' knob over to the the 'to' knob
    nuke.selectedNode().knob('from1').fromScript(nuke.selectedNode().knob('to1').toScript())
    nuke.selectedNode().knob('from2').fromScript(nuke.selectedNode().knob('to2').toScript())
    nuke.selectedNode().knob('from3').fromScript(nuke.selectedNode().knob('to3').toScript())
    nuke.selectedNode().knob('from4').fromScript(nuke.selectedNode().knob('to4').toScript())

    n.knob('from1').fromScript(n.knob('to1').toScript())
    n.knob('from2').fromScript(n.knob('to2').toScript())
    n.knob('from3').fromScript(n.knob('to3').toScript())
    n.knob('from4').fromScript(n.knob('to4').toScript())
    nuke.Knob.clearAnimated(nuke.selectedNode().knob('from1'))
    nuke.Knob.clearAnimated(nuke.selectedNode().knob('from2'))
    nuke.Knob.clearAnimated(nuke.selectedNode().knob('from3'))
    nuke.Knob.clearAnimated(nuke.selectedNode().knob('from4'))
    n['label'].setValue(str(CurFrame))
Ejemplo n.º 54
0
 def __init__(self):
     
     try:
         basecamera = nuke.selectedNode()
     except:
         basecamera = None
         
     frame = nuke.frame()
     
     if basecamera and basecamera.Class() in ['Camera', 'Camera2', 'hubCamera']:
         
         basecamera.knob('selected').setValue(0)
         knobs = self.getCameraKnobs(basecamera, frame)
         xform = self.getWorldMatrix(basecamera, frame)
         
         projCamera = self.createProjectionCamera(basecamera, frame, knobs, xform)
         
     else:
         nuke.message("please select a render camera ('Camera', 'Camera2', 'hubCamera')")
Ejemplo n.º 55
0
    def updateAndSyncSelection (self, force=False) :

        nodes = nuke.selectedNodes()

        if (len(nodes) == 1) :

            node = nodes[0]

            if (node.Class() == "Viewer") :
                node = node.input (int(nuke.knob (node.name() + ".input_number")))

            if (not node) :
                return

            log ("updateAndSyncSelection old %s new %s" % (self.selectedNode, node.name()))
            if (force or node.name() != self.selectedNode) :
                self.selectedNode = node.name()
                self.queueCommand ("self.selectCurrentByNodeName()")
                self.queueCommand ("self.changeFrame(%d)" % nuke.frame())
        else :
            self.selectedNode = None
Ejemplo n.º 56
0
def getMinMax( srcNode, channel='depth.Z' ):
    '''
    Return the min and max values of a given node's image as a tuple
    args:
       srcNode  - node to analyse
       channels  - channels to analyse. This can either be a channel or layer name
    '''
    MinColor = nuke.nodes.MinColor( channels=channel, target=0, inputs=[srcNode] )
    Inv = nuke.nodes.Invert( channels=channel, inputs=[srcNode])
    MaxColor = nuke.nodes.MinColor( channels=channel, target=0, inputs=[Inv] )
    
    curFrame = nuke.frame()
    nuke.execute( MinColor, curFrame, curFrame )
    minV = -MinColor['pixeldelta'].value()
    
    nuke.execute( MaxColor, curFrame, curFrame )
    maxV = MaxColor['pixeldelta'].value() + 1
    
    for n in ( MinColor, MaxColor, Inv ):
        nuke.delete( n )
    return minV, maxV
Ejemplo n.º 57
0
def camProjSingle():
	#Retrieve selected 'Camera' node and 'img' input node
	camSelect = nuke.selectedNodes( "Camera2" )
	imgSelect = nuke.selectedNodes()
	
	#Retrieve current frame in Viewer
	curFrame = nuke.frame()
	
	#Specify 'ProjCam' type
	camType = "S"
	
	#Specify node and GL color ( Hexadecimal Value )
	camColor = 4283190527L
	
	#Create 'ProjCamS' node
	projCam = camProjCreate( camSelect, imgSelect, curFrame, camType, camColor )
	
	if projCam !="":
		#Show properties panel for node
		projCam.showControlPanel()
	
	return
Ejemplo n.º 58
0
def createCheckpoint () :

    nodes = nuke.selectedNodes()

    if (len(nodes) != 1) :
        nuke.message ("Please select a node to checkpoint.")
        return

    node = nodes[0]

    if (type(node).__name__ != "Node" and type(node).__name__ != "Viewer") :
        nuke.message ("Node '%s' is not renderable, pleases select a node that can be rendered." % node.name())
        return

    if (node.Class() == "Read" or node.Class() == "Write") :
        nuke.message ("There's no need to checkpoint Read or Write nodes, since they can be viewed directly in RV.")
        return

    log ("createCheckpoint %s" % node.name())
    rvmon = initRvMon()
    rvmon.initializeRvSide()

    if node.Class() == "Viewer":
        node = node.input (int (nuke.knob (node.name() + ".input_number")))

    dateStr = rvmon.prepForRender (node, "checkpoint")

    f = nuke.frame()

    if (nuke.views() == ['left', 'right']) :
        stereo = "stereo"
    else :
        stereo = "mono"

    rvmon.queueCommand("self.initRenderRun('%s', %d, %d, %d, \"%s\", %g, %d, '%s', '%s', '%s', '%s')" % (
            node.name(), f, f, 1, "", 0.0, f, encodeNL (node["label"].value()), dateStr, "checkpoint", stereo)) 

    """
Ejemplo n.º 59
0
def thumbnailer():
    selNodes = []
    selNodes = nuke.selectedNodes('Read')
    if not selNodes:
        selNodes = nuke.allNodes('Read')
        
    for readNode in selNodes:
        readNode.knob('postage_stamp').setValue(False)
        
        depNodes = readNode.dependent()
        
        isThumbnailed = False
        
        for node in depNodes:
            if node.Class() == 'FrameHold' and node.knob('name').value() == '%s_stamp' % ( readNode.name() ):
                node.knob('first_frame').setValue( nuke.frame() )
                isThumbnailed = True
        
        if not isThumbnailed:
            nameMask = '%s_stamp' % ( readNode.name() )
            thumbnailer = nuke.nodes.FrameHold( name = nameMask, postage_stamp = True, first_frame = nuke.frame(), tile_color = 4294967295)
            thumbnailer.setInput( 0, readNode )
            thumbnailer.setXYpos( readNode.xpos(), readNode.ypos()-80 )