Ejemplo n.º 1
0
    def thumb_snap(self):
        self.check_for_tmp()

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

            writeNode = nuke.nodes.Write( file = self.shot_thumb, name = 'tmpWrite2' , file_type = 'jpg')
            writeNode.setInput(0,reformatNode)
            curFrame = int(nuke.knob("frame"))
        
            nuke.execute(writeNode.name(), curFrame, curFrame)
            nuke.delete(writeNode)
            nuke.delete(reformatNode)
            
            self.update_thumb()
        else:
            #print 'not snapping for current shot'
            nuke.message('not snapping for current shot')
Ejemplo n.º 2
0
def activePointsTo3D():
    # Make a list of all PointsTo3D
    pt3_nodes = []
    active_viewer = nuke.activeViewer().activeInput()
    # Use opened panel to determine which PointsTo3D to affect
    for name in nuke.openPanels():
        node = nuke.toNode(name)
        if node.Class() == "PointsTo3D":
            pt3_nodes.append(node)
    # If there's no PointsTo3D properties open, check if viewer is looking at one
    if len(pt3_nodes) == 0:
        node = nuke.activeViewer().node().input(active_viewer)
        if node.Class() == "PointsTo3D":
            node.showControlPanel()
            pt3_nodes.append(node)
    # If there's still no eligible PointsTo3D, check selected nodes
    if len(pt3_nodes) == 0:
        for node in nuke.selectedNodes():
            if node.Class() == "PointsTo3D":
                node.showControlPanel()
                pt3_nodes.append(node)
    # At this point we're just gonna make one
    if len(pt3_nodes) == 0:
        node = nuke.nodes.PointsTo3D()
        node.setInput(0, nuke.activeViewer().node().input(active_viewer))
        node.showControlPanel()
        nuke.zoom(3, [node.xpos(), node.ypos()])
        pt3_nodes.append(node)

    # Return the PointsTo3D nodes list
    return pt3_nodes
Ejemplo n.º 3
0
def fileOutRFW(noDirectory):
    defViewerConnect = settingCheck()
    print defViewerConnect
    n = nuke.selectedNode()
    xo = int(n['xpos'].value())
    yo = int(n['ypos'].value())

    index = n['file'].value().find('_v')
    version = n['file'].value()[index + 1:index + 6]
    n['label'].setValue(version)
    n.setSelected(True)
    n.setXYpos(xo, yo + 85)
    ### moving old results down
    a = nuke.allNodes("Read")
    a.remove(n)
    for node in a:
        y = int(node['ypos'].value())
        x = int(node['xpos'].value())
        if x > xo - 40 and x < xo + 40 and y > yo:
            node.setXYpos(x, y + 60)
            node.setSelected(False)
    if "ignore" not in defViewerConnect:
        nukescripts.connect_selected_to_viewer(int(defViewerConnect) - 1)
    n.setSelected(True)
    nuke.activeViewer().node().setSelected(False)
Ejemplo n.º 4
0
def viewerSelectedPoint():
    #If the viewer is connected to a node we will use input 0 for ref. Else we just use the viewer itself.
    if nuke.activeViewer().node().input(0):
        myNode = nuke.activeViewer().node().input(0)
        if not nuke.selectedNodes(
        ):  #Trying to be smart by assuming that you don't want to add a node to nothing.
            myNode.setSelected(1)
    else:
        myNode = nuke.activeViewer().node()
    bboxinfo = nuke.activeViewer().node()['colour_sample_bbox'].value(
    )  #Get the position info from the colour sample bbox
    aspect = float(myNode.width() * myNode.pixelAspect()) / float(
        myNode.height()
    )  #Calcualte the aspect (thanks Tom van Dop for notifying and Jelmen Palsterman for the correction!)
    cornerA = [
        (bboxinfo[0] * 0.5 + 0.5) * myNode.width(),
        (((bboxinfo[1] * 0.5) + (0.5 / aspect)) * aspect) * myNode.height()
    ]  #Get the button left corner
    cornerB = [
        (bboxinfo[2] * 0.5 + 0.5) * myNode.width(),
        (((bboxinfo[3] * 0.5) + (0.5 / aspect)) * aspect) * myNode.height()
    ]  #Get the top right corner
    area_WH = [cornerB[0] - cornerA[0],
               cornerB[1] - cornerA[1]]  #Get the width and height of the bbox
    area_Mid = [cornerA[0] + (area_WH[0] / 2),
                cornerA[1] + (area_WH[1] / 2)]  #Get the center of the bbox
    return [area_Mid[0], area_Mid[1]]
Ejemplo n.º 5
0
def connect_selected_to_unlocked_viewer(i):
    if i == 0:
        item = nuke.menu('Nuke').findItem(
            'Viewer/Connect to A Side/Using Input 10')
    else:
        item = nuke.menu('Nuke').findItem(
            'Viewer/Connect to A Side/Using Input {}'.format(i))

    # get the node
    try:
        vn = nuke.activeViewer().node()
    except AttributeError:
        # no viewer exists, use default behaviour which creaetes one
        item.invoke()
        vn = nuke.activeViewer().node()
    # check buffers then call the default action
    try:
        buffer_lock = vn['lock_buffer_{}'.format(i)].value()
        if not nuke.selectedNodes() or nuke.selectedNode().Class() == 'Viewer':
            # no nodes are selected or only a viewer node is selected - use default behaviour
            item.invoke()
        elif (vn['lock_all_buffers'].value() or buffer_lock):
            # viewer is locked
            if not buffer_lock:
                message = '{} is locked.'.format(vn.name())
            else:
                message = 'Buffer {} in {} is locked.'.format(i, vn.name())
            nuke.message(message)
        else:
            # viewer is unlocked
            item.invoke()
    except NameError:
        __create_knobs(vn)
        item.invoke()
Ejemplo n.º 6
0
def nuke_viewerSnapshot(img_path=DEFAULT_PATH):
    LOG.info("nuke_viewerSnapshot")
    import nuke
    viewer = nuke.activeViewer()
    viewNode = nuke.activeViewer().node()

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

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

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

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

    # look up current frame
    curFrame = int(nuke.knob("frame"))
    # start the render
    nuke.execute(write1.name(), curFrame, curFrame)
    # clean up
    for n in [write1]:
        nuke.delete(n)
Ejemplo n.º 7
0
def bakeTrackTo3D():
    firstframe = nuke.Root()['first_frame'].value()
    lastframe = nuke.Root()['last_frame'].value()
    framelist = []
    xtm = firstframe
    while xtm <= lastframe:
        framelist.append(xtm)
        xtm += 1
    print framelist
    This = nuke.thisNode()
    xps = This['xpos'].value()
    yps = This['ypos'].value()
    This.end()
    target = nuke.nodes.Axis2(name=(This.knob('name').value()) + '_Baked',
                              xpos=xps + 100,
                              ypos=yps + 100)

    try:
        camerainput = This.input(1)
        target.setInput(0, camerainput)
        target['hide_input'].setValue(True)
    except:
        pass
    targetT = target.knob('translate')
    targetT.setAnimated()
    nuke.activeViewer().frameControl(-6)
    for each in framelist:
        xn0 = This['OUTPUT'].getValueAt(each)[0]
        xn1 = This['OUTPUT'].getValueAt(each)[1]
        xn2 = This['OUTPUT'].getValueAt(each)[2]
        targetT.setValueAt(xn0, each, 0)
        targetT.setValueAt(xn1, each, 1)
        targetT.setValueAt(xn2, each, 2)
Ejemplo n.º 8
0
def create_viewer_input():
    for n in nuke.selectedNodes():
        n['selected'].setValue(False)

    grp = nuke.createNode("Group", inpanel=False)
    grp.begin()
    inp = nuke.createNode("Input", inpanel=False)
    cs = nuke.createNode("OCIOColorSpace", inpanel=False)
    cs['out_colorspace'].setValue("AlexaV3LogC")
    cdl = nuke.createNode("OCIOCDLTransform", inpanel=False)
    cdl['read_from_file'].setValue(True)
    lut = nuke.createNode("OCIOFileTransform", inpanel=False)
    out = nuke.createNode("Output", inpanel=False)
    # set file paths
    cdlfile = None
    lutfile = None
    try:
        cdlfile = os.path.join(
            "%s" % nuke.root().knob('txt_ih_shot_path').value(), "data", "cdl",
            "%s.ccc" % nuke.root().knob('txt_ih_shot').value())
        lutfile = os.environ['IH_SHOW_CFG_LUT']
        cdl['file'].setValue(cdlfile)
        lut['file'].setValue(lutfile)
    except:
        print "Caught exception when trying to set .ccc and .cube file paths"
    grp.end()
    grp.setName("VIEWER_INPUT")
    nuke.activeViewer().node().knob('viewerProcess').setValue('None')
Ejemplo n.º 9
0
    def clicked(self):
        modifiers = QtGuiWidgets.QApplication.keyboardModifiers()

        if modifiers == QtCore.Qt.ShiftModifier:
            channel = self.sender().text()

            if channel in self.shuffle_list:
                self.shuffle_list.remove(channel)
                self.sender().setStyleSheet(
                    "background-color: #282828; font: 13px")
            else:
                self.shuffle_list.append(channel)
                self.sender().setStyleSheet(
                    "background-color: #1EB028; font: 13px")

        elif modifiers == QtCore.Qt.ControlModifier:
            node = nuke.toNode(nuke.activeViewer().node().input(
                nuke.activeViewer().activeInput()).name())
            self.close()
            node.setSelected(True)
            grade = nuke.createNode("Grade")
            grade['channels'].setValue(self.sender().text())

        else:
            nuke.activeViewer().node()['channels'].setValue(
                self.sender().text())
            self.close()
Ejemplo n.º 10
0
def refreshViewer():
    # Acquire original viewer and its active input
    viewer = nuke.activeViewer().node()
    acInput = nuke.activeViewer().activeInput()
    viewerName = viewer.name()
    print('Viewer data recorded.')

    for node in nuke.allNodes():
        node['selected'].setValue(0)
    viewer['selected'].setValue(1)  # Copy viewer only
    nukescripts.node_copypaste()
    print('Viewer duplicated.')

    newViewer = nuke.selectedNode()

    # Set new viewer's inputs to same as old
    inputs = range(viewer.inputs())
    for vInput in inputs:
        newViewer.setInput(vInput, viewer.input(vInput))
    print('Complete setting viewer\'s inputs')

    # Match old viewer's position and delete the old
    newViewer.setXYpos(viewer.xpos(), viewer.ypos())
    nuke.delete(viewer)
    print('Old viewer deleted.')
    # Rename new viewer to original
    newViewer['name'].setValue(viewerName)
    # Set active input to original
    nukescripts.connect_selected_to_viewer(acInput)
Ejemplo n.º 11
0
	def handleFootageImport(self, files=[]):
		if not files:
			files = nuke.getFilename('Import footage', pattern=' '.join(IngestPanel.FOOTAGE_FORMATS), multiple=True)

		if not files:
			return

		for file in files:
			if file in self.footage:
				return

			self.footage.append(file)
			self.ui.LST_files.addItem(file)

			read = nuke.nodes.Read()

			read['file'].fromUserText(file)

			fps = self.ui.CMB_fps.currentText()
			viewerNode = nuke.activeViewer().node()
			viewerStart, viewerEnd = viewerNode.knob('frame_range').value().split('-')

			viewerNode.knob('frame_range').setValue('0-{}'.format(viewerEnd)) # Set viewer so start frame is 0
			nuke.activeViewer().frameControl(-6) # Set it so the viewer is actually at 0 prior to querying the timecode metadata

			frameOffset = Timecode(fps, read.metadata().get('r3d/absolute_time_code', '00:00:00:00')).frame_number

			self.reads[file] = (read, frameOffset)
Ejemplo n.º 12
0
    def knobChanged(self, knob):
        if knob == self.frameList:
            self.frameListMode.setValue("Custom")

        if knob == self.dependenciesButton:
            GetDependenciesFromDeadline()

        if knob == self.frameListMode:
            # In Custom mode, don't change anything
            if self.frameListMode.value() != "Custom":
                startFrame = nuke.Root().firstFrame()
                endFrame = nuke.Root().lastFrame()
                if self.frameListMode.value() == "Input":
                    try:
                        activeInput = nuke.activeViewer().activeInput()
                        startFrame = nuke.activeViewer().node().input(
                            activeInput).frameRange().first()
                        endFrame = nuke.activeViewer().node().input(
                            activeInput).frameRange().last()
                    except:
                        pass

                if startFrame == endFrame:
                    self.frameList.setValue(str(startFrame))
                else:
                    self.frameList.setValue(
                        str(startFrame) + "-" + str(endFrame))
Ejemplo n.º 13
0
 def keyPressEvent(self, e):
     if e.key() == QtCore.Qt.Key_Escape:
         self.close()
     elif e.key() == QtCore.Qt.Key_Alt:
         nuke.activeViewer().node()['channels'].setValue('rgba')
         self.close()
     elif e.key() == QtCore.Qt.Key_Shift:
         self.first_release = True
Ejemplo n.º 14
0
def bm_JumpToKeyframe(arg):

    if arg == "next":
        nuke.activeViewer().frameControl(-4)
    elif arg == "prev":
        nuke.activeViewer().frameControl(+4)
    else:
        nuke.message("No keyframes to jump between")
    def __init__(self):
        super(HotBox, self).__init__()

        self.active_viewer = nuke.activeViewer().node()
        viewer = self.active_viewer.input(nuke.activeViewer().activeInput())

        layers = list(set([layers.split('.')[0] for layers in viewer.channels()]))
        layers.sort()

        if 'rgba' in layers:
            layers.remove('rgba')
            layers.insert(0, 'rgba')
            if 'rgb' in layers:
                layers.remove('rgb')
                layers.insert(1, 'rgb')
                if 'alpha' in layers:
                    layers.remove('alpha')
                    layers.insert(2, 'alpha')
            elif 'alpha' in layers:
                layers.remove('alpha')
                layers.insert(1, 'alpha')

        length = math.ceil(math.sqrt(len(layers) + 1))
        width, height = length * 200, length * 50
        self.setFixedSize(width, height)
        offset = QtCore.QPoint(width * 0.5, height * 0.5)
        self.move(QtGui.QCursor.pos() - offset)

        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        grid = QtGuiWidgets.QGridLayout()
        self.setLayout(grid)

        column_counter = 0
        row_counter = 0
        button_width = width / length

        for layer in layers:
            button = LayerButton(layer, button_width)
            button.clicked.connect(self.clicked)
            grid.addWidget(button, row_counter, column_counter)

            if column_counter > length:
                row_counter += 1
                column_counter = 0

            else:
                column_counter += 1

        self.input = LineEdit(self, layers)
        grid.addWidget(self.input, row_counter, column_counter)
        self.input.setFocus()
        self.input.returnPressed.connect(self.line_enter)
 def takeScreenshot(self, fileName):
     fileName = fileName.replace('\\', '/')
     viewer = nuke.activeViewer()
     actInput = nuke.ViewerWindow.activeInput(viewer)
     viewNode = nuke.activeViewer().node()
     selInput = nuke.Node.input(viewNode, actInput)
     write = nuke.nodes.Write(file=fileName, name='tmpWrite', file_type='jpg')
     write.setInput(0, selInput)
     curFrame = int(nuke.knob("frame"))
     nuke.execute(write.name(), curFrame, curFrame)
     nuke.delete(write)
Ejemplo n.º 17
0
    def keyPressEvent(self, event):  # pylint: disable=invalid-name
        """Route key press event to certain behaviors.

        Args:
            event (QtGui.QEvent): PySide key press event.

        """
        if event.key() == QtCore.Qt.Key_Escape:
            self.close()
        elif event.key() == QtCore.Qt.Key_Alt:
            nuke.activeViewer().node()['channels'].setValue('rgba')
            self.close()
Ejemplo n.º 18
0
def saveFrame(filePath = ""):
    viewer = nuke.activeViewer()
    inputNode = nuke.ViewerWindow.activeInput(viewer)
    viewNode = nuke.activeViewer().node()

    if inputNode != None:
        selInput = nuke.Node.input(viewNode, inputNode)

        if filePath == "":
            filePath = nuke.getFilename('Save File', "*.png *.jpg *.tga *.exr *.dpx", type = 'save')
        
        filePath = os.path.normpath(filePath)
Ejemplo n.º 19
0
def allNodesWithGeoSelectKnob():
    if nuke.activeViewer():
        preferred_nodes = [
            n for n in nuke.activeViewer().getGeometryNodes()
            if 'geo_select' in n.knobs()
        ]
    else:
        preferred_nodes = []
    nodes = preferred_nodes + [
        n for n in allNodes()
        if 'geo_select' in n.knobs() and n not in preferred_nodes
    ]
    return nodes
Ejemplo n.º 20
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 - %s" % (timeIn, timeOut))
        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.º 21
0
def viewer_update_and_undo_stop():
    """Lock viewer from updating and stop recording undo steps"""
    try:
        # nuke = getattr(sys.modules["__main__"], "nuke", None)
        # lock all connections between nodes
        # nuke.Root().knob('lock_connections').setValue(1)

        # stop active viewer to update any change
        nuke.activeViewer().stop()
        nuke.Undo.disable()
        yield
    finally:
        # nuke.Root().knob('lock_connections').setValue(0)
        # nuke.activeViewer().start()
        nuke.Undo.enable()
Ejemplo n.º 22
0
def apply_preset():
    '''apply presets
	@idx: (int), index for preset to apply
	'''

    node = nuke.thisNode()
    thisPreset = eval(nuke.thisKnob().tooltip())

    for k, v in thisPreset.iteritems():
        if k == 'lut':
            nuke.activeViewer().node()['viewerProcess'].setValue(v)
        elif k == 'cdl' and v != None:
            node[k].setValue(v)
        else:
            node[k].setValue(v)
    def clicked ( self):

        modifiers = QtGui.QApplication.keyboardModifiers()

        if modifiers == QtCore.Qt.ControlModifier:
            node = nuke.toNode(nuke.activeViewer ().node(). input(nuke.activeViewer ().activeInput()).name())
            shuffle = nuke.nodes.Shuffle ( xpos =(  node.xpos() +100), ypos = ( node.ypos()), label = self.sender ().text() )
            shuffle['in'].setValue(self.sender ().text() )
            shuffle.setInput ( 0, node )
            super(HotBox, self).close()

        else:

            nuke.activeViewer ().node()['channels'].setValue( self.sender ().text() )
            super(HotBox, self).close()
 def _setFrameRangeFromSource(self, source):
     if (source == "input"):
         try:
             activeInput = nuke.activeViewer().activeInput()
             self._frameRange.setValue(
                 str(nuke.activeViewer().node().input(
                     activeInput).frameRange()))
         except:
             self._frameRange.setValue(str(nuke.root().frameRange()))
     elif (source == "global"):
         self._frameRange.setValue(str(nuke.root().frameRange()))
     elif (source == "custom"):
         pass
     else:
         self._frameRangeFromViewer(source)
Ejemplo n.º 25
0
def goToActiveNthNode(nth):
    av = nuke.activeViewer()
    if nth - 1 < 0:
        avn = av.node().input(9)
    else:
        avn = av.node().input(nth - 1)
    nuke.zoom(1, [avn.xpos(), avn.ypos()])
Ejemplo n.º 26
0
def navUp():
    av = nuke.activeViewer()
    ai = av.activeInput()
    avn = av.node()
    curr = avn.input(ai)
    prev = curr.input(0)
    nuke.connectViewer(ai, prev)
Ejemplo n.º 27
0
def newFlixPanelFromCurrentViewerImage(nukeStudioViewer = True):
    print "Adding a new FLIX panel from current Viewer"
    uniquePath = getFlixTempFolder()+"flix_"+getUniqueString()+"_"

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

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

    fileRef_out.write("<image originalFile='"+getActiveDocumentFilename()+"' dialogue='I do not believe in Fairies' imageFile='"+tempFilePath+"'/>\n");
    fileRef_out.write("</flixImport>\n");
    fileRef_out.close()
    sendFileToFlix(filePath)
Ejemplo n.º 28
0
def newFlixPanelFromCurrentViewerImage(nukeStudioViewer=True):
    print "Adding a new FLIX panel from current Viewer"
    uniquePath = getFlixTempFolder() + "flix_" + getUniqueString() + "_"

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

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

    fileRef_out.write("<image originalFile='" + getActiveDocumentFilename() +
                      "' dialogue='I do not believe in Fairies' imageFile='" +
                      tempFilePath + "'/>\n")
    fileRef_out.write("</flixImport>\n")
    fileRef_out.close()
    sendFileToFlix(filePath)
Ejemplo n.º 29
0
def add_preset():
    '''create preset buttons adds data to tooltip'''
    node = nuke.thisNode()
    node_viewer = nuke.activeViewer().node()

    # Get knob values
    dict_knobs = {}

    dict_knobs['lut'] = node_viewer['viewerProcess'].value()
    dict_knobs['cdl'] = node['cdl'].value() if 'cdl' in node.knobs() else None
    ls_knobs = ['exp', 'y', 'sat', 'd_exp', 'd_y', 'd_sat']
    for k in ls_knobs:
        dict_knobs[k] = node[k].value()

    # Build knob for this preset
    this_preset_idx = preset_idx()
    preset_latest = PRESET_STR + str(this_preset_idx)

    ## Label input
    this_preset_label = nuke.getInput(
        'Preset Label (keep it short)',
        preset_latest.replace(PRESET_STR, PRESET_STR + ': '))

    if this_preset_label:
        cmd = "mod_IP.apply_preset()"
        k_preset = nuke.PyScript_Knob(preset_latest, this_preset_label, cmd)
        k_preset.setTooltip(str(dict_knobs))
        # if this_preset_idx > 1:
        # 	k_preset.clearFlag(nuke.STARTLINE)
        node.addKnob(k_preset)
        k_preset.setFlag(nuke.STARTLINE)
Ejemplo n.º 30
0
def save_dag_pos(preset):
    # Save current dag zoom and position as a preset on the active viewer
    zoom = nuke.zoom()
    pos = nuke.center()
    viewer = nuke.activeViewer()
    if not viewer:
        nuke.message(
            'Error: please create a viewer to store the dag positions on...')
        return
    else:
        viewer = viewer.node()
    if 'dagpos' not in viewer.knobs():
        viewer.addKnob(
            nuke.String_Knob(
                'dagpos', 'dagpos',
                '0,0,0:0,0,0:0,0,0:0,0,0:0,0,0:0,0,0:0,0,0:0,0,0:0,0,0:0,0,0'))
        dagpos_knob = viewer['dagpos']
        dagpos_knob.setFlag(nuke.STARTLINE)
        dagpos_knob.setEnabled(False)
    else:
        dagpos_knob = viewer['dagpos']
    dagpos_vals = dagpos_knob.getValue().split(':')
    dagpos_vals.pop(preset - 1)
    new_dagpos = ','.join([str(zoom), str(pos[0]), str(pos[1])])
    dagpos_vals.insert(preset - 1, new_dagpos)
    dagpos_knob.setValue(':'.join(dagpos_vals))
Ejemplo n.º 31
0
def anySelectedVertexInfo(selectionThreshold=0.5):
    '''
  anySelectedVertexInfo(selectionThreshold) -> VertexInfo

  Returns a single VertexInfo for a selected point. If more than one point is
  selected, one of them will be chosen arbitrarily.

  The selectionThreshold parameter is used when working with a soft selection.
  Only points with a selection level >= the selection threshold will be
  returned by this function.
  '''
    if not nuke.activeViewer():
        return None

    for n in allNodesWithGeoSelectKnob():
        geoSelectKnob = n['geo_select']
        sel = geoSelectKnob.getSelection()
        objs = geoSelectKnob.getGeometry()
        for o in xrange(len(sel)):
            objSelection = sel[o]
            objPoints = objs[o].points()
            objTransform = objs[o].transform()
            for p in xrange(len(objSelection)):
                value = objSelection[p]
                if value >= selectionThreshold:
                    pos = objPoints[p]
                    tPos = objTransform * _nukemath.Vector4(
                        pos.x, pos.y, pos.z, 1.0)
                    return VertexInfo(
                        o, p, value, _nukemath.Vector3(tPos.x, tPos.y, tPos.z))
    return None
Ejemplo n.º 32
0
    def _addViewKnob(self):
        oc = nuke.OutputContext()
        self._views = [oc.viewname(i) for i in xrange(1, oc.viewcount())]
        if (oc.viewcount() > 2):
            supportedViews = self._selectedFlipbook().capabilities(
            )["maximumViews"]
            if (int(supportedViews) > 1):
                self._viewSelection = nuke.MultiView_Knob("views", "Views")
            else:
                self._viewSelection = nuke.OneView_Knob(
                    "views", "View", self._views)
            activeView = nuke.activeViewer().view()
            if activeView == "":
                activeView = self._views[0]

            # Retrieve previous view selection or default to selecting all available views
            previousViews = self._state.getValue(
                self._viewSelection.name(), " ".join(self._views)).split()
            # Get the intersection of the previous selection and the available views
            viewsToRestore = set(self._views).intersection(previousViews)
            if viewsToRestore:
                self._viewSelection.setValue(" ".join(viewsToRestore))
            else:
                self._viewSelection.setValue(activeView)
            self.addKnob(self._viewSelection)
            self._viewSelection.clearFlag(nuke.NO_MULTIVIEW)
Ejemplo n.º 33
0
def setViewer(mode='restore'):
    '''set and restore viewer input pipes
    mode='restore': restore set inputs
    mode='set': record exsisting inputs
    '''

    node_viewer = nuke.activeViewer().node()

    if mode == 'set':
        label = ''
        num_inputs = node_viewer.inputs()
        
        for i in range( num_inputs ):
            node_thisInput = node_viewer.input(i).name() if node_viewer.input(i) else None
            label += "%s:%sn" % (i+1, node_thisInput)
        node_viewer['label'].setValue(label)
        print( label )

    if mode == 'restore':
        label = node_viewer['label'].value()
        ls_restore = [i.split(':') for i in label.split('n')[:-1]]

        for n in ls_restore:
            node_viewer.setInput(int(n[0])-1, nuke.toNode(n[1]))
            print("%s:%s" % (n[0], n[1]))
Ejemplo n.º 34
0
def selectedVertexInfos(selectionThreshold=0.5):
    '''
  selectedVertexInfos(selectionThreshold) -> iterator

  Return an iterator which yields a tuple of the index and position of each
  point currently selected in the Viewer in turn.

  The selectionThreshold parameter is used when working with a soft selection.
  Only points with a selection level >= the selection threshold will be
  returned by this function.
  '''
    if not nuke.activeViewer():
        return

    for n in allNodesWithGeoSelectKnob():
        geoSelectKnob = n['geo_select']
        sel = geoSelectKnob.getSelection()
        objs = geoSelectKnob.getGeometry()
        for o in xrange(len(sel)):
            objSelection = sel[o]
            objPoints = objs[o].points()
            objTransform = objs[o].transform()
            for p in xrange(len(objSelection)):
                value = objSelection[p]
                if value >= selectionThreshold:
                    pos = objPoints[p]
                    tPos = objTransform * _nukemath.Vector4(
                        pos.x, pos.y, pos.z, 1.0)
                    yield VertexInfo(o, p, value,
                                     _nukemath.Vector3(tPos.x, tPos.y, tPos.z))
Ejemplo n.º 35
0
def cycleContactSheet():

    options = nuke.allNodes('LayerContactSheet')
    if not options: return
    
    viewer = nuke.activeViewer().node()
    idx = 0
    
    try:
        node = viewer.input(9)
    except ValueError:
        node = None
    
    if node:
        idx = options.index(node)
        idx = (idx + 1)%len(options)
    
    viewer.setInput(9, options[idx])
    nuke.activeViewer().activateInput(9)
Ejemplo n.º 36
0
def do():
	"""main"""
	sns =  nuke.selectedNodes()
	for sn in sns:
		filepath = nuke.filename(sn)
		if filepath is not None:
			filepath = 'file:' + os.path.dirname(filepath)
			currentView = nuke.activeViewer().view()
			filepath = filepath.replace(r'%v', currentView[0])
			filepath = filepath.replace(r'%V', currentView)
			print filepath
			openurl.start(filepath)
Ejemplo n.º 37
0
def _useAsInputProcess():
  n = nuke.selectedNode()
  [i['selected'].setValue(False) for i in nuke.allNodes()]
  # FIXME: these two calls should have the arguments in the same order, or even better change the node bindings so they can go.
  if nuke.dependencies([n], nuke.INPUTS | nuke.HIDDEN_INPUTS) or nuke.dependentNodes(nuke.INPUTS | nuke.HIDDEN_INPUTS, [n]):
    m = nuke.createNode(n.Class())
  else:
    m = n
  if m is not n: _copyKnobsFromScriptToScript(n, m)
  viewer = nuke.activeViewer().node()
  viewer['input_process'].setValue(True)
  viewer['input_process_node'].setValue(m.name())
Ejemplo n.º 38
0
    def addSnip(self, vName=None, frame=None, bName=None):
        addFromDB = 1
        if vName is None:
            addFromDB = 0
            vName = nuke.activeViewer().node().name()
        if frame is None:
            frame = nuke.activeViewer().node().knob("frame").value()
            frame = str(int(frame))

        if debug:
            print vName, frame
        if vName not in self.data.keys():
            frameTabObj = QtGui.QWidget()
            frameTabObjLay = QtGui.QHBoxLayout()
            frameTabObj.setLayout(frameTabObjLay)
            self.dynTab.addTab(frameTabObj, vName)
            self.data[vName] = {}
            self.js_data[vName] = {}
            self.data[vName]["frame"] = {}
            self.js_data[vName]["frame"] = {}
            self.data[vName]["lay"] = frameTabObjLay
            self.data[vName]["obj"] = frameTabObj
            if debug:
                print self.js_data, self.data

        if frame not in self.data[vName]["frame"].keys():
            if bName is None:
                bName = self.getName()
            if bName != None:
                b = self.createButton("%s : %s" % (frame, bName), self.frameDo)
                b.setMaximumWidth(300)
                self.data[vName]["frame"][frame] = b
                self.js_data[vName]["frame"][frame] = bName
                self.data[vName]["lay"].addWidget(b)
                self.frameButtons[b] = (vName, frame)
                if debug:
                    print self.js_data, self.data

        if not addFromDB:
            self.proDataSave()
Ejemplo n.º 39
0
def restoreCheckpoint (nukeScript, nodeName, date) :
    log ("restoreCheckpoint %s %s %s" % (nukeScript, nodeName, date))

    #  We ask on rv side now, since otherwise dialog can come up behind rv.
    #
    # ans = nuke.ask ("Restore checkpoint: %s, %s ?" % (nodeName, date))
    # log ("    ans %s" % ans)

    log ("    reading checkpoint script")
    nuke.Undo().begin("Restore %s, %s" % (nodeName, date))
    try :
        nukescripts.misc.clear_selection_recursive()

        try :
            v = nuke.activeViewer().node().name()
        except :
            v = None

        if (rvmon) :
            rvmon.restoreBegin()

        nodes = nuke.root().nodes()
        for n in nodes:
            #log ("    deleting %s %s %s" % (n.name(), type(n).__name__, n.Class()))
            nuke.delete(n)
        nuke.scriptReadFile (nukeScript)

        if (v) :
            n = nuke.toNode(v)
            if (n) :
                nuke.show (n)

        if (rvmon) :
            rvmon.restoreComplete()

        log ("    checkpoint restore complete")

    except Exception, msg:
        nuke.message("Checkpoint restore failed:\n%s" % (msg,))
Ejemplo n.º 40
0
def nk_get_roto_from_color():
    """
	Reveal Roto
	SS Shift+v
	"""

    def colorSum(node):
        color = node["color"].value()
        if isinstance(color, list):
            return sum([int(i * 10000) for i in color][0:3])
        else:
            return color

    viewPortSum = colorSum(nuke.activeViewer().node())
    lower, upper = viewPortSum - 10, viewPortSum + 10
    c = [C.dependent() for C in nuke.allNodes("Constant") if (lower <= colorSum(C) <= upper)]
    cccc = []
    for cc in c:
        for ccc in cc:
            if ccc.Class() == "RotoPaint":
                cccc.append(ccc)
    [(p.setSelected(True), p.showControlPanel()) for p in cccc]
Ejemplo n.º 41
0
  def submit(self, username=None, password=None):
    """
    Does the work to submit the current Nuke script to Zync,
    given that the parameters on the dialog are set.
    """

    if self.existing_project.value().strip() == '' and self.new_project.value().strip() == '':
      nuke.message('Project name cannot be blank. Please either choose ' +
        'an existing project from the dropdown or enter the desired ' +
        'project name in the New Project field.')
      return

    if self.skip_check.value():
      skip_answer = nuke.ask('You\'ve asked Zync to skip the file check ' +
        'for this job. If you\'ve added new files to your script this ' +
        'job WILL error. Your nuke script will still be uploaded. Are ' +
        'you sure you want to continue?')
      if not skip_answer:
        return

    # prompt for login 
    msg = 'Zync Login'
    pw_prompt = PasswordPrompt(title=msg, user_default=self.usernameDefault)
    try:
      login_type, user, pw = pw_prompt.get_authentication_info()
    except Exception:
      msg = 'You must have a Zync account to submit a job.'
      raise Exception(msg)

    selected_write_names = []
    selected_write_nodes = []
    for k in self.writeNodes:
      if k.value():
        selected_write_names.append(k.label())
        selected_write_nodes.append(nuke.toNode(k.label()))

    active_viewer = nuke.activeViewer()
    if active_viewer:
      viewer_input = active_viewer.activeInput()
      if viewer_input == None:
        viewed_node = None
      else:
        viewed_node = active_viewer.node().input(viewer_input)
    else:
      viewer_input, viewed_node = None, None

    new_script = ZYNC.generate_file_path(nuke.root().knob('name').getValue())
    with WriteChanges(new_script):
      # The WriteChanges context manager allows us to save the
      # changes to the current session to the given script, leaving
      # the current session unchanged once the context manager is
      # exited.
      preflight_result = preflight()

      #
      #   Nuke 7.0v1 through 7.0v8 broke its own undo() functionality, so this will only
      #   run on versions other than those.
      #
      if nuke.NUKE_VERSION_MAJOR != 7 or nuke.NUKE_VERSION_MINOR > 0 or nuke.NUKE_VERSION_RELEASE > 8:
        #
        #   Remove all nodes that aren't connected to the Write
        #   nodes being rendered.
        #
        select_deps(selected_write_nodes)
        for node in nuke.allNodes():
          if node.isSelected():
            node.setSelected(False)
          else:
            node.setSelected(True)
        nuke.nodeDelete()
        #
        #   Freeze expressions on all nodes. Catch errors for Nuke
        #   versions that don't support the recurseGroups option.
        #
        try:
          node_list = nuke.allNodes(recurseGroups=True)
        except:
          node_list = nuke.allNodes()
        for node in node_list: 
          freeze_node(node)
      
    if not preflight_result:
      return

    # reconnect the viewer
    if viewer_input != None and viewed_node != None:
      nuke.connectViewer(viewer_input, viewed_node)

    # exec before render
    #nuke.callbacks.beforeRenders

    try:
      if login_type == 'google':
        ZYNC.login_with_google()
      else:
        ZYNC.login(username=user, password=pw)
    except zync.ZyncAuthenticationError as e:
      raise Exception('Zync Login Failed:\n\n%s' % (str(e),))

    try:
      render_params = self.get_params()
      if render_params == None:
        return
      ZYNC.submit_job('nuke', new_script, ','.join(selected_write_names), render_params)
    except zync.ZyncPreflightError as e:
      raise Exception('Preflight Check Failed:\n\n%s' % (str(e),))

    nuke.message('Job submitted to ZYNC.')
 def lineEnter (self):
     nuke.activeViewer ().node()['channels'].setValue( self.input.text() )
     self.close()
Ejemplo n.º 43
0
	def createNodeSet(self,apple,sCount):
		print 'apple.Class() : apple.name() ',apple.Class(), apple.name() ,'sCount ',sCount,'\n'
		i = 0

		bdN_Val_X = -1000
		bdN_Val_Y = -1000

		apple.setXYpos( (bdN_Val_X + self.Incr + 50), ( bdN_Val_Y + 100 ) )	# this group node is taken from user

		self.sNoteA = nuke.createNode('StickyNote', inpanel=False)
		self.sNoteA['label'].setValue('Roto layer loads here')
		self.sNoteA.setXYpos( ( bdN_Val_X + self.Incr + 50 ), ( bdN_Val_Y  + 140) )

		self.dotA = nuke.createNode("Dot",inpanel=False)
		self.dIncr = self.dIncr + 500 
		self.dotA.setXYpos( bdN_Val_X  + (self.dIncr - 466) , bdN_Val_Y + (-58) )
		self.dotA.setInput(0,self.camera)

		self.copy = nuke.createNode("Copy", inpanel=False)
		self.copy.setXYpos( (bdN_Val_X + self.Incr - 100), ( bdN_Val_Y + 100 ) )
		self.copy.setInput(0,apple)

		self.prem = nuke.createNode('Premult', inpanel=False)
		self.prem.setXYpos( (bdN_Val_X + self.Incr - 100), (bdN_Val_Y + 200) )
		self.prem.setInput(0,self.copy)

		self.p3d = nuke.createNode("Project3D", inpanel=False)
		self.p3d.setXYpos( (bdN_Val_X + self.Incr - 100), (bdN_Val_Y + 300) )

		self.p3d.setInput(0,self.prem)

		self.p3d.setInput(1,self.dotA)

		self.am = nuke.createNode("ApplyMaterial", inpanel=False)               # apply material
		self.am.setXYpos( (bdN_Val_X + self.Incr - 100),  (bdN_Val_Y + 400) )

		self.rGeo = nuke.createNode("ReadGeo", inpanel=False)

		self.rGeo.setXYpos( (bdN_Val_X + self.Incr + 50) ,  (bdN_Val_Y + 400) )

		self.am.setInput(0,self.rGeo)
		self.am.setInput(1,self.p3d)

		self.sNoteB = nuke.createNode('StickyNote', inpanel=False)
		self.sNoteB['label'].setValue('fbx export loads here')
		self.sNoteB.setXYpos( (bdN_Val_X + self.Incr + 50), (bdN_Val_Y + 440) )

		self.dotB = nuke.createNode("Dot", inpanel=False)
		self.dotB.setXYpos( (bdN_Val_X + self.Incr - 60)  , (bdN_Val_Y + 500) )
		self.dotB.setInput(0,self.am)
		self.scene.setInput(sCount,self.dotB)

		self.Incr = self.Incr + 500

# put validation for viewer
		curViewer = nuke.activeViewer()
		if not isinstance(curViewer,NoneType):
			viewerNode = curViewer.node()
			viewer = viewerNode.name()                                          # viewer node
			viewerNode.setInput(0,self.scene)                                   # connect scene to viewer
			viewerNode.setXYpos( -85, 20 )
			
		return 1			
Ejemplo n.º 44
0
### Lockviewer
l = LockViewer()

def onScriptLoadCallback():
	for n in nuke.allNodes():
		if n.Class() == "Viewer":
			if n.knob('locked0'):
				for i in range(10):
					if n.input(i) != None:
						l.lockInput(True, i, n, n.input(i))

nuke.addOnScriptLoad(onScriptLoadCallback)

m = nuke.menu( 'Nuke' ).addMenu('Sap Tools')
subm = m.addMenu('Lock Selected Node to Viewer')
subm.addCommand( 'lockViewer1', lambda: l.lockInput(True,0,nuke.activeViewer().node(),nuke.selectedNode()), '#1')
subm.addCommand( 'unlockViewer1', lambda: l.lockInput(False,0,nuke.activeViewer().node(),None), '^#1')
subm.addCommand( 'lockViewer2', lambda: l.lockInput(True,1,nuke.activeViewer().node(),nuke.selectedNode()), '#2')
subm.addCommand( 'unlockViewer2', lambda: l.lockInput(False,1,nuke.activeViewer().node(),None), '^#2')
subm.addCommand( 'lockViewer3', lambda: l.lockInput(True,2,nuke.activeViewer().node(),nuke.selectedNode()), '#3')
subm.addCommand( 'unlockViewer3', lambda: l.lockInput(False,2,nuke.activeViewer().node(),None), '^#3')
subm.addCommand( 'lockViewer4', lambda: l.lockInput(True,3,nuke.activeViewer().node(),nuke.selectedNode()), '#4')
subm.addCommand( 'unlockViewer4', lambda: l.lockInput(False,3,nuke.activeViewer().node(),None), '^#4')
subm.addCommand( 'lockViewer5', lambda: l.lockInput(True,4,nuke.activeViewer().node(),nuke.selectedNode()), '#5')
subm.addCommand( 'unlockViewer5', lambda: l.lockInput(False,4,nuke.activeViewer().node(),None), '^#5')
subm.addCommand( 'lockViewer6', lambda: l.lockInput(True,5,nuke.activeViewer().node(),nuke.selectedNode()), '#6')
subm.addCommand( 'unlockViewer6', lambda: l.lockInput(False,5,nuke.activeViewer().node(),None), '^#6')
subm.addCommand( 'lockViewer7', lambda: l.lockInput(True,6,nuke.activeViewer().node(),nuke.selectedNode()), '#7')
subm.addCommand( 'unlockViewer7', lambda: l.lockInput(False,6,nuke.activeViewer().node(),None), '^#7')
subm.addCommand( 'lockViewer8', lambda: l.lockInput(True,7,nuke.activeViewer().node(),nuke.selectedNode()), '#8')
subm.addCommand( 'unlockViewer8', lambda: l.lockInput(False,7,nuke.activeViewer().node(),None), '^#8')
    def __init__(self):
        super ( HotBox ,self ).__init__()

        av = nuke.activeViewer ().node()
        vn = av. input(nuke.activeViewer ().activeInput()).name()


        channels = nuke.toNode(vn).channels()
        layer = list( set([c.split('.')[0] for c in channels]) )
        layer.sort()

        if 'rgba' in layer:
            layer.remove('rgba')
            layer.insert(0, 'rgba')
            if 'rgb' in layer:
                layer.remove('rgb')
                layer.insert(1, 'rgb')
                if 'alpha' in layer:
                    layer.remove('alpha')
                    layer.insert(2, 'alpha')
            elif 'alpha' in layer:
                layer.remove('alpha')
                layer.insert(1, 'alpha')



        length = math.ceil (math.sqrt ( len ( layer ) +1 ) )

        width = length*200
        height = length*50
        point = QtGui.QCursor.pos()
        offsetX = width * 0.5
        offsetY = height * 0.5

        offset = QtCore.QPoint ( offsetX, offsetY )
        point -= offset

        self.setMinimumSize (width, height)
        self.setMaximumSize (width, height)
        self.move ( point )
        self.setWindowTitle ( 'Hotbox' )
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        #self.setAttribute(QtCore.Qt.WA_TranslucentBackground)

        grid = QtGui.QGridLayout ()
        self.setLayout ( grid )

        length = math.ceil (math.sqrt ( len ( layer ) +1 ) )
        columnCounter = 0
        rowCounter = 0
        butWidth = width/length

        for i in layer:

            button = LayerButton ( i, butWidth)
            button.clicked.connect(self.clicked, )
            button.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Expanding)
            grid. addWidget (button, rowCounter, columnCounter)

            if columnCounter >  length:
                rowCounter = rowCounter +1
                columnCounter = 0
            else:
                columnCounter = columnCounter +1

            self.input=LineEdit(self, layer)
            self.input.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Expanding)
            grid.addWidget (self.input,   rowCounter, columnCounter)
            self.input.returnPressed.connect(self.lineEnter)
            self.input.setFocus()
Ejemplo n.º 46
0
  def submit(self):
    """Does the work to submit the current Nuke script to Zync, given that the parameters on the dialog are set."""

    selected_write_names = []
    selected_write_nodes = []
    for k in self.writeNodes:
      if k.value():
        selected_write_names.append(k.label())
        selected_write_nodes.append(nuke.toNode(k.label()))

    active_viewer = nuke.activeViewer()
    if active_viewer:
      viewer_input = active_viewer.activeInput()
      if viewer_input is None:
        viewed_node = None
      else:
        viewed_node = active_viewer.node().input(viewer_input)
    else:
      viewer_input, viewed_node = None, None

    script_path = nuke.root().knob('name').getValue()
    new_script = self.maybe_correct_path_separators(script_path)
    write_node_to_user_path_map = dict()
    read_dependencies = []

    with WriteChanges(new_script):
      # Nuke 7.0v1 through 7.0v8 broke its own undo() functionality, so this will only run on versions other than those.
      if nuke.NUKE_VERSION_MAJOR != 7 or nuke.NUKE_VERSION_MINOR > 0 or nuke.NUKE_VERSION_RELEASE > 8:
        # Remove all nodes that aren't connected to the Write nodes being rendered.
        select_deps(selected_write_nodes)
        for node in nuke.allNodes():
          if node.isSelected():
            node.setSelected(False)
          else:
            node.setSelected(True)
        nuke.nodeDelete()
        # Freeze expressions on all nodes. Catch errors for Nuke versions that don't support the recurseGroups option.
        try:
          node_list = nuke.allNodes(recurseGroups=True)
        except:
          node_list = nuke.allNodes()
        for node in node_list:
          freeze_node(node)

        _collect_write_node_paths(selected_write_names, write_node_to_user_path_map)
        read_nodes = [read_node for read_node in node_list if read_node.Class() == 'Read']
        _collect_read_node_paths(read_nodes, read_dependencies)

    # reconnect the viewer
    if viewer_input is not None and viewed_node is not None:
      nuke.connectViewer(viewer_input, viewed_node)

    # exec before render
    # nuke.callbacks.beforeRenders

    try:
      render_params = self.get_params()
      if render_params is None:
        return
      render_params['scene_info']['write_node_to_output_map'] = write_node_to_user_path_map
      render_params['scene_info']['files'] = read_dependencies
      self.zync_conn.submit_job('nuke', new_script, ','.join(selected_write_names), render_params)
    except zync.ZyncPreflightError as e:
      raise Exception('Preflight Check Failed:\n\n%s' % (str(e),))

    nuke.message('Job submitted to ZYNC.')
Ejemplo n.º 47
0
def view(view = 'result', layer = ('rgba','none')):
    '''
    Mimics the behavior of the Flame Viewer: F1 displays your A layers, F2 your B layers, F3 your mask, and F4 the result (F4 is similar to regular viewer, but doesn't reassign a view)

    @param view: Which view to display (front/back/matte/result)
  @param layer: which layer was last seen, and what was the latest mask layer viewed. Allows us to switch back to the right layer when pressing F1/F2/F4 after viewing the matte
    @return: same tuple as the @param layer, for next time.
    '''
    try:
        node = nuke.selectedNode()
    except ValueError:
        print 'No node selected'
        return layer
    viewer = nuke.activeViewer().node()

    #Find Current Input
    currentInput = None
    for i in range(0,node.inputs()):
        if node.input(i) == viewer.input(10):
            currentInput = i
            break

    #Find Mask Input. Thanks to Ean Carr for the help here.
    if node.Class() == 'Merge2':
        maskInput = 2
    elif node.knobs().has_key('maskChannelMask') or node.knobs().has_key('maskChannel'):
        maskInput = node.minInputs() - 1
    else:
        maskInput = None

    #find the layer that we want to be reverting back to after viewing the mask
    fvlayer = viewer.knob('channels').value()
    lastLayer = layer[0]
    mask = layer[1]
    if fvlayer == mask or 'none':
        fvlayer = lastLayer

    #find what we want to see depending on the view
    if view == 'front':
        if maskInput == 1 or node.inputs() == 1:
            viewer.knob('channels').setValue('none')
        else:
            #check if current input is a front
            if currentInput != 0 and currentInput != maskInput and currentInput != None:
                front = currentInput + 1
                if front == maskInput:
                    front += 1
                if front >= node.inputs():
                    front = 1
            else:
                front = 1

            viewer.setInput(10,node.input(front))
            viewer.knob('channels').setValue(lastLayer)

    elif view == 'back':
        viewer.setInput(10,node.input(0))
        viewer.knob('channels').setValue(lastLayer)

    elif view == 'matte':
        if maskInput:
            #if mask input is connected take the value from that knob, otherwise connect to node and take value from knob "mask"
            if node.input(maskInput):
                if node.knobs().has_key('maskChannelMask'):
                    mask = node.knob('maskChannelMask').value()
                else:
                    mask = node.knob('maskChannel').value()
                viewer.setInput(10,node.input(maskInput))
            else:
                mask = node.knob('mask').value()
                viewer.setInput(10,node)
        else:
            mask = 'none'
            viewer.setInput(10,node)
        viewer.knob('channels').setValue(mask)

    elif view == 'result':
        viewer.setInput(10,node)
        viewer.knob('channels').setValue(lastLayer)

    else:
        return layer

    #activate that view
    viewer.knob('input_number').setValue(10)
    return (fvlayer, mask)
 def clicked(self):
     nuke.activeViewer ().node()['channels'].setValue( self.text() )
Ejemplo n.º 49
0
	def createNodeSet(self,apple, appleParent, sCount):
		print 'apple ',apple , 'appleParent ',appleParent.name() ,'sCount ', sCount,'\n'

		i = 0

		bdN_Val_X = -1000
		bdN_Val_Y = -1000

#		self.bDrop = nuke.createNode('BackdropNode', inpanel=False)
#		self.bDrop['label'].setValue('These are the imported roto and maya object files. Number of copies of these depends on number of stereo layers defined in xml file.  ')
		self.bDrop = nuke.nodes.BackdropNode(label="These are the imported roto and maya object files")
		self.bDrop.setXYpos( (bdN_Val_X + self.Incr), bdN_Val_Y )
		self.bDrop['bdwidth'].setValue(bdN_Val_X + 1200)
		self.bDrop['bdheight'].setValue(bdN_Val_Y + 1500)


		appleParent.setXYpos( (bdN_Val_X + self.Incr + 50), ( bdN_Val_Y + 100 ) )	# this group node is taken from user

#		self.sNoteA = nuke.createNode('StickyNote', inpanel=False)
#		self.sNoteA['label'].setValue('Roto layer loads here')
		self.sNoteA = nuke.nodes.StickyNote(label="Roto layer loads here")
		self.sNoteA.setXYpos( ( bdN_Val_X + self.Incr + 50 ), ( bdN_Val_Y  + 140) )

#		self.dotA = nuke.createNode("Dot",inpanel=False)
		self.dotA = nuke.nodes.Dot()
		self.dIncr = self.dIncr + 500 
		self.dotA.setXYpos( bdN_Val_X  + (self.dIncr - 466) , bdN_Val_Y + (-58) )
		self.dotA.setInput(0,self.camera)
		
#		self.copy = nuke.createNode("Copy", inpanel=False)
		self.copy = nuke.nodes.Copy()
		self.copy.setXYpos( (bdN_Val_X + self.Incr - 100), ( bdN_Val_Y + 100 ) )
		self.copy.setInput(0,appleParent)

#		self.prem = nuke.createNode('Premult', inpanel=False)
		self.prem = nuke.nodes.Premult()
		self.prem.setXYpos( (bdN_Val_X + self.Incr - 100), (bdN_Val_Y + 200) )
		self.prem.setInput(0,self.copy)

#		self.p3d = nuke.createNode("Project3D", inpanel=False)
		self.p3d = nuke.nodes.Project3D()
		self.p3d.setXYpos( (bdN_Val_X + self.Incr - 100), (bdN_Val_Y + 300) )

		self.p3d.setInput(0,self.prem)
		self.p3d.setInput(1,self.dotA)

#		self.am = nuke.createNode("ApplyMaterial", inpanel=False)               # apply material
		self.am = nuke.nodes.ApplyMaterial()
		self.am.setXYpos( (bdN_Val_X + self.Incr - 100),  (bdN_Val_Y + 400) )
		print 'apple ',apple,'\n'
#		self.rGeo = nuke.createNode("ReadGeo", inpanel=False)
		self.rGeo = nuke.nodes.ReadGeo()
#		self.rGeo['file'].setValue(apple)
		fileKnob = self.rGeo.knob("file")
		fileKnob.setValue(apple)
		self.rGeo.setXYpos( (bdN_Val_X + self.Incr + 50) ,  (bdN_Val_Y + 400) )

		self.am.setInput(0,self.rGeo)
		self.am.setInput(1,self.p3d)

#		self.sNoteB = nuke.createNode('StickyNote', inpanel=False)
		self.sNoteB = nuke.nodes.StickyNote()
		self.sNoteB['label'].setValue('fbx export loads here')
		self.sNoteB.setXYpos( (bdN_Val_X + self.Incr + 50), (bdN_Val_Y + 440) )
		
#		self.dotB = nuke.createNode("Dot", inpanel=False)
		self.dotB = nuke.nodes.Dot()
		self.dotB.setXYpos( (bdN_Val_X + self.Incr - 60)  , (bdN_Val_Y + 500) )
		self.dotB.setInput(0,self.am)
		self.scene.setInput(sCount,self.dotB)

		self.Incr = self.Incr + 500

# put validation for viewer
		curViewer = nuke.activeViewer()
		if not isinstance(curViewer,NoneType):
			viewerNode = curViewer.node()
			viewer = viewerNode.name()                                          # viewer node
			viewerNode.setInput(0,self.scene)                                   # connect scene to viewer
			viewerNode.setXYpos( -85, 20 )

		return 1
Ejemplo n.º 50
0
  def submit(self):
    """
    Does the work to submit the current Nuke script to Zync,
    given that the parameters on the dialog are set.
    """

    selected_write_names = []
    selected_write_nodes = []
    for k in self.writeNodes:
      if k.value():
        selected_write_names.append(k.label())
        selected_write_nodes.append(nuke.toNode(k.label()))

    active_viewer = nuke.activeViewer()
    if active_viewer:
      viewer_input = active_viewer.activeInput()
      if viewer_input == None:
        viewed_node = None
      else:
        viewed_node = active_viewer.node().input(viewer_input)
    else:
      viewer_input, viewed_node = None, None

    new_script = self.zync_conn.generate_file_path(nuke.root().knob('name').getValue())
    with WriteChanges(new_script):
      # The WriteChanges context manager allows us to save the
      # changes to the current session to the given script, leaving
      # the current session unchanged once the context manager is
      # exited.
      preflight_result = preflight()

      #
      #   Nuke 7.0v1 through 7.0v8 broke its own undo() functionality, so this will only
      #   run on versions other than those.
      #
      if nuke.NUKE_VERSION_MAJOR != 7 or nuke.NUKE_VERSION_MINOR > 0 or nuke.NUKE_VERSION_RELEASE > 8:
        #
        #   Remove all nodes that aren't connected to the Write
        #   nodes being rendered.
        #
        select_deps(selected_write_nodes)
        for node in nuke.allNodes():
          if node.isSelected():
            node.setSelected(False)
          else:
            node.setSelected(True)
        nuke.nodeDelete()
        #
        #   Freeze expressions on all nodes. Catch errors for Nuke
        #   versions that don't support the recurseGroups option.
        #
        try:
          node_list = nuke.allNodes(recurseGroups=True)
        except:
          node_list = nuke.allNodes()
        for node in node_list:
          freeze_node(node)

    if not preflight_result:
      return

    # reconnect the viewer
    if viewer_input != None and viewed_node != None:
      nuke.connectViewer(viewer_input, viewed_node)

    # exec before render
    #nuke.callbacks.beforeRenders

    try:
      render_params = self.get_params()
      if render_params == None:
        return
      self.zync_conn.submit_job('nuke', new_script, ','.join(selected_write_names), render_params)
    except zync.ZyncPreflightError as e:
      raise Exception('Preflight Check Failed:\n\n%s' % (str(e),))

    nuke.message('Job submitted to ZYNC.')
Ejemplo n.º 51
0
 def LockThisViewer9():
     nuke.activeViewer().node().setInput(8, nuke.toNode(selectednodename))
Ejemplo n.º 52
0
def nukePlay():
    """play a la maya"""
    nuke.activeViewer().play(1)
Ejemplo n.º 53
0
    def submit(self, username=None, password=None):
        """
        Does the work to submit the current Nuke script to ZYNC,
        given that the parameters on the dialog are set.

        TODO: factor the bulk of this out of the ZyncRenderPanel object
        """

        if self.existing_project.value().strip() == '' and self.new_project.value().strip() == '':
            nuke.message('Project name cannot be blank. Please either choose an existing project from the dropdown or enter the desired project name in the New Project field.')
            return

        if self.skip_check.value():
            skip_answer = nuke.ask( "You've asked ZYNC to skip the file check for this job. If you've added new files to your script this job WILL error. Your nuke script will still be uploaded. Are you sure you want to continue?" )
            if not skip_answer:
                return

        if not username and not password:
            if hasattr(nuke, 'zync_creds') and nuke.zync_creds.get('user'):
                # get username and password
                user = nuke.zync_creds.get('user')
                pw = nuke.zync_creds.get('pw')
            else:
                # prompt username and password:
                msg = 'Enter your ZYNC Render Username/Password'
                pw_prompt = PasswordPrompt( title=msg, user_default=self.usernameDefault )
                try:
                    user, pw = pw_prompt.get_password()
                except Exception:
                    msg = 'You must have a ZYNC account to submit!'
                    raise Exception(msg)
                else:
                    nuke.zync_creds = dict(user=user, pw=pw)

        #selected_write = self.writeListNames[int(self.writeNode.getValue())]
        selected_write_names = []
        selected_write_nodes = []
        for k in self.writeNodes:
            if k.value():
                selected_write_names.append( k.label() )
                selected_write_nodes.append( nuke.toNode( k.label() ) )

        active_viewer = nuke.activeViewer()
        if active_viewer:
            viewer_input = active_viewer.activeInput()
            if viewer_input == None:
                viewed_node = None
            else:
                viewed_node = active_viewer.node().input(viewer_input)
        else:
            viewer_input, viewed_node = None, None

        new_script = generate_script_path()
        with WriteChanges(new_script):
            # The WriteChanges context manager allows us to save the
            # changes to the current session to the given script, leaving
            # the current session unchanged once the context manager is
            # exited.
            preflight_result = preflight()

            #
            #   Nuke 7.0v1 through 7.0v8 broke its own undo() functionality, so this will only
            #   run on versions other than those.
            #
            if nuke.NUKE_VERSION_MAJOR != 7 or nuke.NUKE_VERSION_MINOR > 0 or nuke.NUKE_VERSION_RELEASE > 8:
                #
                #   Remove all nodes that aren't connected to the Write
                #   nodes being rendered.
                #
                select_deps(selected_write_nodes)
                for node in nuke.allNodes():
                    if node.isSelected():
                        node.setSelected(False)
                    else:
                        node.setSelected(True)
                nuke.nodeDelete()
                #
                #   Freeze expressions on all nodes. Catch errors for Nuke
                #   versions that don't support the recurseGroups option.
                #
                try:
                    node_list = nuke.allNodes(recurseGroups=True)
                except:
                    node_list = nuke.allNodes()
                for node in node_list: 
                    freeze_node(node)
            
        if not preflight_result:
            return

        # reconnect the viewer
        if viewer_input != None and viewed_node != None:
            nuke.connectViewer(viewer_input, viewed_node)

        # exec before render
        #nuke.callbacks.beforeRenders

        try:
            ZYNC.login( username=user, password=pw )
        except zync.ZyncAuthenticationError as e:
            nuke.zync_creds['user'] = None
            nuke.zync_creds['pw'] = None
            raise Exception('ZYNC Login Failed:\n\n%s' % (str(e),))

        try:
            render_params = self.get_params()
            if render_params == None:
                return
            ZYNC.submit_job('nuke', new_script, ','.join( selected_write_names ), render_params)
        except zync.ZyncPreflightError as e:
            raise Exception('Preflight Check Failed:\n\n%s' % (str(e),))

        nuke.message('Job submitted to ZYNC.')