Example #1
0
def end_game():
    # Showing the winner
    userAllRevealed = True

    for row in coord_objects:
        for element in row:

            if element.get_has_boat(
                    USER) and not element.get_is_revealed(USER):
                userAllRevealed = False

    if userAllRevealed:
        nuke.message('<b><font size=5>GAME OVER\n<font color = red>COM WINS')
    else:
        nuke.message('<b><font size=5>GAME OVER\n<font color = green>YOU WIN')

    # Scene restoration
    nuke.toNode('preferences')['DAGBackColor'].setValue(dagColor)

    # Deletion of nodes
    for node in nuke.allNodes():
        if "bShip" in node['name'].value() or node.Class() == 'NoOp':
            nuke.delete(node)

    nuke.tprint(
        '\n\n---------------------\n+++++ GAME OVER +++++\n---------------------'
    )
Example #2
0
def loadMochaimport(base_dir):
    """
    adds the correct plugin path for this version of NUKE
    @param basepath:
    @return:
    """
    supportedMagicNumbers = ['03f30d0a', 'd1f20d0a']
    try:
        magicNumberOfThisVersion = imp.get_magic().encode('hex')
        if magicNumberOfThisVersion in supportedMagicNumbers:
            pathToThisVersion = replace_path(
                os.path.join(
                    base_dir, "python/mamoworld/mochaImportPlus/version_" +
                    magicNumberOfThisVersion))
            nuke.pluginAddPath(pathToThisVersion)
        else:
            raise Exception(
                "MochaImport+ for NUKE: unsupported version of Python:" +
                sys.version + "(magic number:" + magicNumberOfThisVersion +
                ")")
    except Exception as e:
        import traceback
        nuke.tprint(traceback.format_exc())  # Just in case
        msg = 'ERROR: %s' % e
        if nuke.GUI:
            nuke.message(msg)
        else:
            nuke.tprint(msg)
Example #3
0
def run():
    """Add animatedSnap3D menu items under the Axis Menu"""
    try:
        axis_menu = nuke.menu('Axis').findItem('Snap')
    except AttributeError:  # Could not find Axis menu
        nuke.tprint(
            "Could not find 'Axis' menu to append animatedSnap3D commands. "
            "animatedSnap3D will not be available through menus.")
        return
    else:
        if not axis_menu:  # Found Axis, could not find Snap
            nuke.tprint(
                "Could not find 'Snap' item of sub-menu 'Axis' to append "
                "animatedSnap3D commands. animatedSnap3D will not be available "
                "through menus.")
            return

    axis_menu.addSeparator()
    axis_menu.addCommand('Match animated selection position',
                         'animatedSnap3D.animated_snap()')
    axis_menu.addCommand(
        'Match animated selection position, orientation',
        'animatedSnap3D.animated_snap(["translate", "rotate"])')
    axis_menu.addCommand(
        'Match animated selection position, orientation, size',
        'animatedSnap3D.animated_snap(["translate", "rotate", "scaling"])')
Example #4
0
    def __init__(self, parent=None):
        """ Description """
        QMainWindow.__init__(self, parent)

        _uiFilename_ = 'projectExplorer_nuke.ui'
        _uiFilePath_ = modulepath + '/ui/' + _uiFilename_

        # Check is ui file exists?
        if not os.path.isfile(_uiFilePath_):
            nuke.tprint('File ui not found.')

        # ---- LoadUI -----
        loader = QUiLoader()
        currentDir = os.path.dirname(__file__)
        file = QFile(_uiFilePath_)
        file.open(QFile.ReadOnly)
        self.ui = loader.load(file, parentWidget=self)
        file.close()
        # -----------------

        self.ui.setWindowTitle('Project Explorer v.' + str(__app_version__))

        nuke.tprint("\n====== Project Explorer Start ======")

        self._initConnect()
        self._initUI()
def submitNukeCmdline_render(executeNodes=''):
    '''launch the qubegui submit dialog for nuke'''
    allNodes = nuke.allNodes()
    allNodes_Write  = [str(i.name()) for i in allNodes if i.Class() == 'Write'] 
    allNodes_Viewer = [str(i.name()) for i in allNodes if i.Class() == 'Viewer'] 
    nuke.tprint(allNodes_Write)
    nuke.tprint(allNodes_Viewer)
    range = '%s-%s' % (int(nuke.animationStart()), int(nuke.animationEnd()))
    rangeInc = int(nuke.animationIncrement())
    if rangeInc > 1:
        range += 'x%s' % rangeInc

    submitDict = {
        'name'      : 'nuke '+os.path.basename(str(nuke.root().name())),
        'prototype' : 'cmdrange',
        'env': {'NUKE_PATH': os.environ['NUKE_PATH']},
        'priority': 500,
        'cpus': 10,
        'reservations': 'global.nuke=1,host.processors=1',
        'groups': 'RENDERBOX',
        'package' : {
            'simpleCmdType': 'Nuke (cmdline)',
            'script': str(nuke.root().name()),
            'range' : range,
            'executeNodes' : executeNodes,
            'allNodes_Write' : ','.join(allNodes_Write),
            'allNodes_Viewer' : ','.join(allNodes_Viewer),
            'executable': 'C:\\Program Files\\Nuke9.0v5\\Nuke9.0.exe',
            } 
        }
    return launchgui(submitDict=submitDict)
def callPanel():
    plate = nuke.selectedNode()
    if plate.Class() == "Read":
        return setProjectFrameRange().showPanel()
    else:
        nuke.tprint("Selected node must be a Read node.")
        nuke.message("Selected node must be a Read node.")
Example #7
0
def thisActualGroup(debug=False):
    groupName = nuke.thisGroup().fullName()
    if not nuke.thisGroup().fullName() == 'root':
        groupName = 'root.' + groupName
    if debug == True:
        nuke.tprint(groupName)
    return nuke.toNode(groupName)
Example #8
0
def CM_Analyse(node):
	#Activate the analyse button
	try:
	    node['solveGainCompensation'].execute()   
	except Exception as e:
	    nuke.tprint('Error Analysing - ', e)
	    sys.exit(1)
def launchgui(qubeguiPath='', submitDict={}, guiargs=''):
    '''launch the QubeGUI with the specified parameters'''
    # Construct parameter list
    cmdDict = {
                'qubeguiPath': qubeguiPath,
                'qubeguiArgString': '',
              }
    if len(submitDict) > 0:  cmdDict['qubeguiArgString'] += ' --submitDict "%s"'%submitDict
    if len(guiargs) > 0   :  cmdDict['qubeguiArgString'] += ' '+guiargs

    # Construct command for the specific platforms        
    if sys.platform[:3] == 'win':
        if cmdDict['qubeguiPath'] == '': cmdDict['qubeguiPath'] = 'C:/Program Files/pfx/qube/bin/qube.exe'
        if not os.path.exists(cmdDict['qubeguiPath']):
            cmdDict['qubeguiPath'] = 'C:/Program Files (x86)/pfx/qube/bin/qube.exe'
        cmd = r'start "QubeGUI Console" /B "%(qubeguiPath)s" %(qubeguiArgString)s'% cmdDict
    elif sys.platform == 'darwin':
        if cmdDict['qubeguiPath'] == '': cmdDict['qubeguiPath'] = '/Applications/pfx/qube/qube.app'
        cmd = r'%(qubeguiPath)s/Contents/MacOS/qube %(qubeguiArgString)s >/dev/null 2>&1  &'% cmdDict
    elif sys.platform[:5] == 'linux':
        if cmdDict['qubeguiPath'] == '': cmdDict['qubeguiPath'] = '/usr/local/pfx/qube/bin/qube'
        cmd = r'%(qubeguiPath)s %(qubeguiArgString)s >/dev/null 2>&1  &'% cmdDict
    else:
        raise "Unknown platform"
    
    # Run command
    print("COMMAND: %s"%cmd)
    nuke.tprint("COMMAND: %s"%cmd)
    #nuke.message("COMMAND: %s"%cmd)
    os.system(cmd)
Example #10
0
def backup_autosave():
    global next_autosave_version
    #get autosave file
    autosave_file = nuke.toNode("preferences")["AutoSaveName"].evaluate()
    #compute next autosave file name
    file = autosave_file + str(next_autosave_version)
    #check if original autosave file exists 
    if os.path.exists(autosave_file):
        try:
            shutil.copy(autosave_file, file)
        except:
            pass
            # A message box every time it can't find an autosave file is irritating AF
            # nuke.message("Attention! Autosave file could not be copied!")
        nuke.tprint("Copied autosave file to: %s"%file)
        #start from the beginning if max files are reached
        if next_autosave_version==max_autosave_files:
            next_autosave_version=0
        else:
            next_autosave_version+=1
    elif nuke.Root()['name'].value():
        #warn if there is no autosave at all
        has_autosave=False
        for i in range(max_autosave_files):
            if os.path.exists(autosave_file + str(i)):
                has_autosave=True
                
        if not has_autosave and nuke.modified():
            pass
Example #11
0
def load():
    supportedMagicNumbers = ['03f30d0a', 'd1f20d0a', '420d0d0a']

    try:
        if nuke.NUKE_VERSION_STRING.startswith('13'):
            magicNumberOfThisVersion = imp.get_magic().hex()
        else:
            magicNumberOfThisVersion = imp.get_magic().encode('hex')
        if magicNumberOfThisVersion in supportedMagicNumbers:
            pathToThisVersion = "python/mamoworld/mochaImportPlus/version_" + magicNumberOfThisVersion
            nuke.pluginAddPath(pathToThisVersion)
            print('**--**-*-*-*-*' + magicNumberOfThisVersion)
        else:
            raise Exception(
                "MochaImport+ for NUKE: unsupported version of Python:" +
                sys.version + "(magic number:" + magicNumberOfThisVersion +
                ")")

    except Exception as e:
        import traceback
        nuke.tprint(traceback.format_exc())  # Just in case
        msg = 'ERROR: %s' % e
        if nuke.GUI:
            nuke.message(msg)
        else:
            nuke.tprint(msg)
Example #12
0
def CS_matchCameras(node):
	#Match Cameras
	try:
	    node['matchCameras'].execute()
	except Exception as e:
	    nuke.tprint('Error Matching - ', e)
	    sys.exit(1)
Example #13
0
def CS_setKeyNum(node, num):
	try:
		node['keyStep'].setValue(num)
		node['addAllAnalysisKeys'].execute()
	except Exception as e:
	    nuke.tprint('Error setting number of frames - ', e)
	    sys.exit(1)
Example #14
0
    def _setScriptVersionList(self):
        ''' Setup script listWidget '''

        current_seq = self.ui.comboBox_sequence.currentText()
        current_shot = self.ui.listWidget_scriptShot.currentItem().text()

        # Setup current path
        currentPath = getInfo.nukeScriptsPath + '/' + "{seq}_{shot}".format(
            seq=current_seq, shot=current_shot)
        self.ui.label_currentPath.setText(currentPath)

        versionlist = core.listAllVersion(
            nukeScriptsPath=getInfo.nukeScriptsPath,
            seq=current_seq,
            shot=current_shot)

        self.ui.listWidget_scriptVersion.clear()

        for fileName in versionlist:
            item = QListWidgetItem(fileName)
            item.setData(Qt.UserRole,
                         core.objString(currentPath + '/' + fileName))

            self.ui.listWidget_scriptVersion.addItem(item)

        # show thumbnail
        try:
            thumbnailPath = core.getThumbnail(shotDirPath=currentPath,
                                              perfile=False)
            self._setThumbnail(thumbnailPath)
        except Exception as e:
            nuke.tprint(str(e))
 def _source_roto_template(self, step_name, proj_format):
     """
     Prompts user if they want to import the set Roto template for the New File.
     """
     if step_name == "Roto":
         roto_template = nuke.ask(
             "Source the default Nuke template for the <i style='color:magenta'><b><br>SSVFX Roto</b></i> workflow?"
         )
         if not roto_template:
             pass
         else:
             tk = self.parent.engine.sgtk
             roto_template_script = tk.templates["workfile_templates"]
             fields = {}
             roto_template_script_path = os.path.normpath(
                 roto_template_script.apply_fields(fields) +
                 "\\pipeline_task\\roto\\roto_rgb_template.nk")
             roto_template_script_path = roto_template_script_path.replace(
                 "/", os.path.sep)
             if os.path.exists(roto_template_script_path):
                 nuke.tprint("Importing Roto template:",
                             roto_template_script_path)
                 nuke.scriptSource(roto_template_script_path)
                 nuke.zoom(0.0)
                 try:
                     nuke.Root().knob('format').setValue(proj_format)
                 except:
                     nuke.tprint("!!! No proj_format called %s" %
                                 proj_format)
Example #16
0
def CS_solveCameras(node):
	#Solve Cameras
	try:
	    node['solveCameras'].execute()
	except Exception as e:
	    nuke.tprint('Error Solving - ', e)
	    sys.exit(1)
Example #17
0
def exportSelection(node):
	#Export the chosen option
	try:
	    node['exportButton'].execute()   
	except Exception as e:
	    nuke.tprint('Error Exporting - ', e)
	    sys.exit(1)
Example #18
0
def run():
    """Add animatedSnap3D menu items under the Axis Menu"""
    try:
        axis_menu = nuke.menu('Axis').findItem('Snap')
    except AttributeError:  # Could not find Axis menu
        nuke.tprint(
            "Could not find 'Axis' menu to append animatedSnap3D commands. "
            "animatedSnap3D will not be available through menus."
        )
        return
    else:
        if not axis_menu:  # Found Axis, could not find Snap
            nuke.tprint(
                "Could not find 'Snap' item of sub-menu 'Axis' to append "
                "animatedSnap3D commands. animatedSnap3D will not be available "
                "through menus."
            )
            return

    axis_menu.addSeparator()
    axis_menu.addCommand(
        'Match animated selection position',
        'animatedSnap3D.animated_snap()'
    )
    axis_menu.addCommand(
        'Match animated selection position, orientation',
        'animatedSnap3D.animated_snap(["translate", "rotate"])'
    )
    axis_menu.addCommand(
        'Match animated selection position, orientation, size',
        'animatedSnap3D.animated_snap(["translate", "rotate", "scaling"])'
    )
Example #19
0
def submitNukeCmdline_render(executeNodes=''):
    '''launch the qubegui submit dialog for nuke'''
    allNodes = nuke.allNodes()
    allNodes_Write  = [str(i.name()) for i in allNodes if i.Class() == 'Write'] 
    allNodes_Viewer = [str(i.name()) for i in allNodes if i.Class() == 'Viewer'] 
    scenefile = '[NUKE NOPIPE] %s' % os.path.basename(str(nuke.root().name()))
    nuke.tprint(allNodes_Write)
    nuke.tprint(allNodes_Viewer)
    range = '%s-%s' % (int(nuke.animationStart()), int(nuke.animationEnd()))
    rangeInc = int(nuke.animationIncrement())
    if rangeInc > 1:
        range += 'x%s' % rangeInc
    submitDict = {
        'name'      : scenefile,
        'prototype' : 'cmdrange',
        'package' : {
            'simpleCmdType': 'Nuke (cmdline)',
            'script': str(nuke.root().name()),
            'range' : range,
            'executeNodes' : executeNodes,
            'allNodes_Write' : ','.join(allNodes_Write),
            'allNodes_Viewer' : ','.join(allNodes_Viewer),
	    'executable' : '/atomo/apps/linux/x86_64/nuke/8.0v3/Nuke8.0',
            },
	'reservations' : 'host.processors=1+,license.nuke',
        'groups' : 'pipe',
        'cpus' : 6,
        'omithosts' : 'rhradec.local',
	'env': {'FOUNDRY_LICENSE_FILE':'[email protected]','NUKE_PATH':'/atomo/pipeline/tools/nuke/script:/atomo/pipeline/tools/nuke/gizmo','NUKE_TEMP_DIR':'/tmp/nuke_farm'}
        }
    return launchgui(submitDict=submitDict)
Example #20
0
def executeRender(node, start, end):
	try:
		nuke.execute(node, start, end)
		sys.exit(0)
	except Exception as e:
		nuke.tprint('Failed to render range')
		sys.exit(1)
Example #21
0
def loadSolvedImage():
	try:
		img = nuke.nodes.Read(file = '/Users/macadmin/Desktop/Solve_Test.%V.exr')
		img['noprefix'].setValue(1)
		return img
	except Exception as e:
		nuke.tprint ('Error creating read node', e)
		sys.exit(1)
Example #22
0
def refreshReads():
    allNodes = nuke.allNodes()
    for readNode in allNodes:
        if readNode.Class() == 'Read':
            readNode.knob('reload').execute()
            nuke.tprint ('%s is refreshed' % readNode.knob('file').value())
        else:
            pass
Example #23
0
 def addNkList(self):
     if not os.path.exists(self.libpath):
         nuke.message(self.libpath + "경로가 존재하지 않습니다.")
     for i in os.listdir(self.libpath):
         nuke.tprint(i)
         base, ext = os.path.splitext(i)
         if ext != ".nk":
             continue
         self.nklist.addItem(QListWidgetItem(i))
Example #24
0
	def writeOut(self, node):
		deselectAllViews()
		reformatNode = self.createReformat(node)
		reformatNode.connectInput(1, node)
		write, pathToCompare = createWriteNode(self.fileName)
		write.connectInput(1, reformatNode)
		nuke.execute(write, 1, 1)
		nuke.tprint("Asserted that WRITE EXECUTED SUCCESSFULLY.")
		return pathToCompare
Example #25
0
    def _openExplorer(self):
        ''' open in explorer '''

        currentPath = self.ui.label_currentPath.text()

        if os.path.exists(currentPath):
            core.openExplorer(currentPath)
        else:
            nuke.tprint("Path not exists : " + currentPath)
Example #26
0
	def listProjects(self):
		projectPath = self.getConfigData('PATH_TEMPLATE').split("${_PROJECTSNAME}")[0]
		nuke.tprint("PROJECTS : %s"%projectPath)

		if not os.path.exists(projectPath) :
			nuke.tprint("ERROR : Path not found \"%s\""%projectPath)
			return []

		return [item for item in os.listdir(projectPath) if os.path.isdir("%s/%s"%(projectPath, item))]
Example #27
0
def addIncrementalFolder(filename):
	
    fileList = list(os.path.split(filename))
    fileList.insert(1,'.nukeAutoSave')
    filename = os.path.join(*fileList)
    if not os.path.exists(os.path.dirname(filename)):
        try:
            os.makedirs(os.path.dirname(filename))
        except Exception,e:
              nuke.tprint(e)
Example #28
0
def main():
    nodes = nuke.selectedNodes()
    if len(nodes) != 1:
        nuke.message("select one node only")
        return
    nuke.tprint(nodes[0])
    path = os.path.dirname(nodes[0]["file"].value())
    nuke.tprint(path)
    browser(path)
    return
Example #29
0
def tri_env2path(nodes):
    for n in nodes:
        nuke.tprint(">>", n.name(), n.Class())
        if 'triwrite_gizmo' in n.knobs():
            tri_env2path([n.node('result'), n.node('dailies')])
        else:
            if 'file' in n.knobs():
                p = n['file'].value()
                nuke.tprint("<<", "[python tri_path()]", p)
                p = p.replace("[python tri_path()]", tri_path())
                n['file'].setValue(p)
Example #30
0
def CS_chooseRigPreset(node, preset):
	try:
		node['rigPreset'].setValue(preset)
	except Exception as e:
	    nuke.tprint('Error choosing the rig preset - ', e)
	    sys.exit(1)
	try:
		node['setupRig'].execute()
	except Exception as e:
	    nuke.tprint('Error setting the rig preset - ', e)
	    sys.exit(1)
Example #31
0
def print_available_coords():

    nuke.tprint('\nAVAILABLE COORDS:\n-----------------')
    available_coords = ''

    for row in coord_objects:
        for element in row:

            if not element.get_is_discarded(USER):
                available_coords += element.get_name() + ','

    nuke.tprint(available_coords)
Example #32
0
def tri_path2env(nodes):
    templ = tri_path()
    for n in nodes:
        nuke.tprint(">>", n.name(), n.Class())
        if 'triwrite_gizmo' in n.knobs():
            tri_path2env([n.node('result'), n.node('dailies')])
        else:
            if 'file' in n.knobs():
                p = n['file'].value()
                nuke.tprint(">>", p, templ)
                p = p.replace(templ, "[python tri_path()]")
                n['file'].setValue(p)
    def _find_sequence_range(self, path):
        """
        Helper method attempting to extract sequence information.

        Using the toolkit template system, the path will be probed to
        check if it is a sequence, and if so, frame information is
        attempted to be extracted.

        :param path: Path to file on disk.
        :returns: None if no range could be determined, otherwise (min, max)
        """
        # find a template that matches the path:
        template = None
        try:
            template = self.parent.sgtk.template_from_path(path)
        except sgtk.TankError:
            pass

        if not template:
            # If we don't have a template to take advantage of, then
            # we are forced to do some rough parsing ourself to try
            # to determine the frame range.
            return self._sequence_range_from_path(path)

        # get the fields and find all matching files:
        fields = template.get_fields(path)
        if not "SEQ" in fields:
            return None

        files = self.parent.sgtk.paths_from_template(template, fields)

        # Somthing has gone wrong
        # despite having valid templates, no files were returned
        # so we'll pretend no template was found
        if files == []:
            try:
                sequence_range = self._sequence_range_from_path(path)
                return sequence_range
            except:
                nuke.tprint(">>>>> SOMETHING WENT WRONG")

        # find frame numbers from these files:
        frames = []
        for file in files:
            fields = template.get_fields(file)
            frame = fields.get("SEQ")
            if frame != None:
                frames.append(frame)
        if not frames:
            return None

        # return the range
        return (min(frames), max(frames))
Example #34
0
def getFileName(inputFile):
	try:
		if platform.system() == 'Darwin':
			iF = inputFile.rsplit("/", 1)
		elif platform.system() == 'Windows':
			iF = inputFile.rsplit("\\", 1)
		else:
			nuke.tprint('Broken on platform recognition')

		filename = iF[1].split('.py')
		return filename[0]
	except Exception as e:
		nuke.tprint('Error getting the file name from BCTC' , e)
Example #35
0
 def checkInstances(self):
     nuke.tprint ('new instance:', self)
     for widget in QApplication.allWidgets():
         name = widget.objectName()
         if 'uk.co.thefoundry.NukeConnectGui' in name:
             nuke.tprint ("instance already present:", self)
             p = widget.parentWidget()
             while p:
                 if p.parent() and isinstance(p.parent(), QStackedWidget):
                     p.parent().removeWidget(p)
                     p = None
                 else:
                     p = p.parentWidget()
Example #36
0
	def saveIncrement(self, project, shot):

		if not project or not shot :
			nuke.tprint("Please select shot")
			return False

		savePath = _replaceData(self.getConfigData("PATH_TEMPLATE"), project, shot)
		filename = os.path.basename(_replaceData(self.getConfigData("SCRIPTNAME_TEMPLATE"), project, shot, get_lastversion(savePath)))
		savePath = savePath.replace("${_SCRIPTNAME}", filename)

		nuke.scriptSaveAs(savePath)
		nuke.tprint("Save file : %s" %(savePath))
		return savePath
Example #37
0
def ueOpen():
    p = nukescripts.registerWidgetAsPanel("ueCommonOpen.Open", "ueOpen",
                                          "ue.panel.ueOpen", create=True)
    p.setMinimumSize(600, 940)
    ueCommonOpen.setClasses(__ueclasses__)

    if p.showModalDialog():
        spec = ueCommonOpen.getValues()
        version = ueAssetUtils.getVersions(spec)[spec.vers-1]
        nuke.scriptOpen(os.path.join(version["path"], version["file_name"]+".nk"))
        nuke.tprint("Opened %s" % spec)

    nukescripts.unregisterPanel("ue.panel.ueOpen", lambda: "return")
Example #38
0
def tri_project_init():
    nuke.tprint("*START project setup")
    
    # add new Write menu shortcut
    nuke.menu('Nodes').findItem('Image').addCommand("TriWrite", "nuke.createNode(\"TriWrite\")", "", icon="Write.png")
    
    if os.getenv('TRI_PROJECT_PATH') is None or os.getenv('TRI_PROJECT_ID') is None:
        nuke.tprint(" NO project env")
        return
#    else:
#        nuke.tprint(" INIT", os.getenv('TRI_PROJECT_PATH'))
    
    if 'tri_project_id' in nuke.root().knobs():
        tri_update_setup()
    else:
        tri_new_setup()
Example #39
0
def createWriteDirs(nodes=[]):
  '''
  create write directories for selected write nodes
  supports stereo view notation with %v or %V
  '''
  # if no nodes are specified then look for selected nodes
  if not nodes:
    nodes = nuke.selectedNodes()

  # if nodes is still empty no nodes are selected
  if not nodes:
    nuke.message('ERROR: No node(s) selected.')
    return

  EXISTING = []

  for entry in nodes:
    _class = entry.Class()
    if _class == "Write":
      path = nuke.filename(entry)
      output_paths = []
      if path is None:
        continue
      all_views = curnode.knob('views').value() # look for views in the write node
      all_views = all_views.split() # split them out
      for view in all_views:
        if '%v' in path:
          output_paths.append(path.replace('%v',view[:1]))
        if '%V' in path:
          output_paths.append(path.replace('%V',view))
        if not len(output_paths):
          output_paths.append(path)
        for output_path in output_paths:
          root_path = os.path.dirname(output_path)
          if os.path.exists(root_path) == True:
            nuke.tprint('Path Exists: {0}'.format(root_path))
            return
          try:
            os.mkdir(root_path)
            os.chmod(root_path,0775)
          except:
            if nuke.ask('Create Path? \n{0}'.format(root_path)):
              os.makedirs(root_path)
              os.chmod(root_path,0775)
            else:
              return
  return
Example #40
0
def FileHandler( dropdata ):
	filePath = dropdata
	if os.path.basename(filePath).startswith('.') or os.path.basename(filePath).endswith('~'):
		return
	log_( filePath )
	fileRange = ''

	if not os.path.isfile(filePath):
		filePath, sep, fileRange = filePath.rpartition(' ')

 	fileName, fileExt = os.path.splitext(filePath)
 	fileExt = fileExt.lower()

 	if fileExt == '.obj':
 		r = nuke.createNode("ReadGeo2", inpanel=False)		
 		r['file'].fromUserText(dropdata)
 		#r['file'].setValue(dropdata)
 		r['selected'].setValue(0)
 		return

 	if fileExt == '.fbx':
 		r = nuke.createNode("ReadGeo2", inpanel=False)	
 		r['file'].fromUserText(dropdata)
 		r['all_objects'].setValue(True)
 		r['selected'].setValue(0)
 		nuke.tprint(dropdata)	

 		camNode = nuke.createNode('Camera2', 'read_from_file 1 file '+dropdata, inpanel=True)
		#c = nuke.createNode('Camera2', inpanel=True)
		#c['read_from_file'].setValue(1)
		#c['file'].setValue(dropdata)
		camNode['fbx_node_name'].setValue(7)
 		camNode['selected'].setValue(0)
 		return

 	if fileExt == '.abc':
   		try:
   			r = nuke.createNode('ReadGeo2', inpanel=False) 			
   			r['file'].fromUserText(dropdata)
   			r['read_on_each_frame'].setValue(1)
   			r['sub_frame'].setValue(1)
   			r['selected'].setValue(0)
   			return
   		except Exception, e:
   			log_('DEBUG: NUKE_VERSION_MAJOR > 7? %s' % e)
Example #41
0
def findChangedKnob():
    knob = nuke.thisKnob()
    node = nuke.thisNode()
    if knob.name() == 'renderType':
	output_type = knob.value()
	if output_type == 'matte':
	    nuke.tprint ('matte selected')
	    output_path = '[value dirName]/[value renderType]/[value fileName]/[value fileName].%04d.tiff'
	    node['file'].setValue(output_path)
	    node['file_type'].setValue('tiff')
	    node['datatype'].setValue('8')
	    node['colorspace'].setValue('srgb')
	    node['channels'].setValue('alpha')
	elif output_type in ['slapcomp', 'prerender', 'cleanup']:
	    output_path = "[value dirName]/[value renderType]/[value fileName]/[value fileName].%04d.dpx"
	    node['file'].setValue(output_path)
	    node['file_type'].setValue('dpx')
	    node['colorspace'].setValue('linear')
	    node['datatype'].setValue('10')
	    node['channels'].setValue('rgb')
Example #42
0
def load():
    supportedMagicNumbers = ['03f30d0a', 'd1f20d0a']

    try:
        magicNumberOfThisVersion = imp.get_magic().encode('hex')
        if magicNumberOfThisVersion in supportedMagicNumbers:
            pathToThisVersion = "python/mamoworld/mochaImportPlus/version_" + magicNumberOfThisVersion
            nuke.pluginAddPath(pathToThisVersion)
        else:
            raise Exception(
                "MochaImport+ for NUKE: unsupported version of Python:" + sys.version + "(magic number:" + magicNumberOfThisVersion + ")")

    except Exception as e:
        import traceback
        nuke.tprint(traceback.format_exc())  # Just in case
        msg = 'ERROR: %s' % e
        if nuke.GUI:
            nuke.message(msg)
        else:
            nuke.tprint(msg)
Example #43
0
def jopsFileHandler(dropdata):
    filePath=dropdata
    fileRange= ''
    
    if not os.path.isfile(filePath):
        filePath, sep, fileRange = filePath.rpartition(' ')

    fileName, fileExt = os.path.splitext(filePath)

    if fileExt == '.obj':
        r = nuke.createNode("ReadGeo2", inpanel=False)
        r["file"].fromUserText(dropdata)
        r["selected"].setValue(0)
        return True

    if fileExt == '.fbx':
        r = nuke.createNode("ReadGeo2", inpanel=False)
        r["file"].fromUserText(dropdata)
        r["selected"].setValue(0) 
        nuke.tprint(dropdata)
        r = nuke.createNode("Camera2", 'read_from_file 1 file '+dropdata, inpanel=False)
        r["selected"].setValue(0)
        r = nuke.createNode("Light2", 'read_from_file 1 file '+dropdata, inpanel=False)
        r["selected"].setValue(0)        
        return True
    
    if fileExt == '.3dl' or fileExt == '.blur' or fileExt == '.csp' or fileExt == '.cub' or fileExt == '.cube' or fileExt == '.vf' or fileExt == '.vfz':
        r = nuke.createNode("Vectorfield", inpanel=False)
        r["vfield_file"].setValue(dropdata)
        r["selected"].setValue(0)
        return True

    if fileExt == '.chan':
        r = nuke.createNode("Camera2", inpanel=False)
        nuke.tcl('in %s {import_chan_file %s }' %(r.name(), dropdata))
        r["selected"].setValue(0)
        return True

    r = nuke.createNode("Read", inpanel=False)
    r["file"].fromUserText(dropdata)
    return True
Example #44
0
def markThisNode(node, expr):
    """Mark the given node in an obvoius way so any potential problem is 
    obvoius. That means make it red and put a warning in the node's label.
    
    TODO: Genericize this for other markings besides expressions. Hidden 
    inputs are another good application.

    node is the target node
    expr is the offending expression
    
    """

    if node.knob('tile_color').value() != warning_color:
        node.knob('tile_color').setValue(warning_color)
    label_text = '*** expression-driven ***\n*** ' + expr + ' ***'
    # Escape $
    label_text = label_text.replace('$', '\$')
    label_contents = node.knob('label').toScript()
    if label_text not in label_contents:
        nuke.tprint("Marking " + node.fullName() + " as potentially dangerous.")             
        node.knob('label').fromScript( label_contents + '\n' + label_text)
def createWriteDirs(nodes=[]):
    '''
    Makes directories for selected write nodes
    '''
    # if no nodes are specified then look for selected nodes
    if not nodes:
        nodes = nuke.selectedNodes()

    # if nodes is still empty no nodes are selected
    if not nodes:
        nuke.message('ERROR: No node(s) selected.')
        return

    EXISTING = []

    for node in nodes:
        _class = node.Class()
        if _class == "Write":

            path = nuke.filename(node)

            if path is None:
                nuke.tprint('No path attribute.')
                continue
            root_path = os.path.dirname(path)

            if os.path.exists(root_path) == True:
                nuke.tprint('Path Exists: {}'.format(root_path) )
            try:
                os.mkdir(root_path)
                os.chmod(root_path,0775)
                nuke.tprint('Path created: {}'.format(root_path) )
            except:
                if nuke.ask('Create Path?\n {}'.format(root_path)):
                    os.makedirs(root_path)
                    os.chmod(root_path,0775)
                    nuke.tprint('Path created: {}'.format(root_path) )
                else:
                    nuke.tprint('Path creation cancelled for: {}'.format(root_path))
    return
Example #46
0
    def parseColorCorrectionIDs( self, rootelem ):
        """Grabs ColorCorrection and ColorCorrectionRef children of rootelem, and bungs IDs into colourcorrectionvalues
        dict keys, with associated internal or external (ref) information as under a 'type' tag in the corresponding
        colourcorrectionvalue value dict.
        
        ColorCorrection tags define a CDL transfer function contained within that XML element.
        ColorCorrectionRef tags define a CDL transfer function by ID, which is contained within some other CCC file. Ref
        elements should theoretically only be present in CDL files.
        
        Rootelem should be a element tree element, with all desired colour correction and colour correction ref tags as
        direct children.
        
        Writes error message to terminal if no colourcorrection/ref elements found.
        
        """
        
        iter=rootelem.findall(self.ASCCDLNS+"ColorCorrection")
        iterref=rootelem.findall(self.ASCCDLNS+"ColorCorrectionRef")
        if iter==0 and iterref==0:
            nuke.tprint("No colour corrections found in file")
        
        cdlcorrectionlist=[]
        cccname=0
         
        # Get internal CCC container ID's
        for element in iter:
            if element.keys():
               for name, value in element.items():
                    cccname=value
                                   
            self.cdlcorrectionvalues[cccname]=dict({"type": "int"})

        # Get external CCC container ID's (theoretically should only be present in CDLs)
        for element in iterref:
            if element.keys():
               for name, value in element.items():
                    cccname=value
                                   
            self.cdlcorrectionvalues[cccname]=dict({"type": "ext"})
        return
Example #47
0
def tri_path_check(nodes, top=True):
    PATH = tri_path()
    LDIR = "/usr/pipeline/software/nuke/N6/SCRIPTS/trigraph"
    PENV = "[python tri_path()]"
    report = ""
    for n in nodes:
        if n.Class() == "Group":
            report += tri_path_check(n.nodes(), False)
        if 'file' in n.knobs():
            if n['file'].value().startswith(PATH) or \
               n['file'].value().startswith(LDIR) or \
               n['file'].value().startswith(PENV):
                report += " OK node: " + n.fullName() + " (..." + n['file'].value()[-30:] + ")\n"
            else:
                report += "BAD node: " + n.fullName() + " (..." + n['file'].value()[-30:] + ")\n"
    if top:
        nuke.tprint("REPORT")
        nuke.tprint(report)
        nuke.message("REPORT \n" + report)
        return None
    else:
        return rep
Example #48
0
def tri_update_setup():
    nuke.tprint(" UPDATE project setup")
    root = nuke.root()
    
    path = tri_path() + "/" + root['tri_comp'].value()                  # TRI_PATH + _cmp
    
    if 'tri_project_scene_id' in nuke.root().knobs():
        # create write dis
        pData = etree.fromstring(root['tri_project_xml_formats'].value())
        tri_create_write_path(pData.find('result'))
        tri_create_write_path(pData.find('dailies'))
        
        # add new Write menu shortcut
        nuke.menu('Nodes').findItem('Image').addCommand("TriWrite", "nuke.createNode(\"TriWrite\")", "w", icon="Write.png")
    
    # create cmp dirs
    try:
        if not os.path.exists(path):
            if nuke.ask("Dir: " + path + " not exists. Create?"):
                pass
                os.makedirs(path)
    except:
        nuke.message("Cannot create\n" + path)
Example #49
0
def tri_writeGizmo_init():
    nuke.tprint("  START TriWrite")
    if not 'triwrite_gizmo' in nuke.thisNode().knobs():
        return
    
    nuke.thisNode()['artist'].setValue(artistName())

    if nuke.thisNode()['notes'].value() == "":
        nuke.thisNode()['notes'].setValue(sceneComment())
    
    if not 'tri_project_xml_formats' in nuke.root().knobs():
        return
    
    nuke.tprint("  INIT ", nuke.thisNode().name(), nuke.thisNode().Class())
    
    root = nuke.root()
    pData = etree.fromstring(root['tri_project_xml_formats'].value())
    nuke.thisNode()['_dailies_format'].setValue(root['tri_project_id'].value() + " DAILIES")
    
    if 'tri_project_scene_id' in root.knobs():
        # create write dis
        tri_create_write_path(pData.find('result'))
        tri_create_write_path(pData.find('dailies'))
        # setup results/dailies params
        tri_filename_init(nuke.thisGroup().node('result'), pData.find('result'))
        tri_filename_init(nuke.thisGroup().node('dailies'), pData.find('dailies'))
        
        nuke.thisGroup()['_render'].setEnabled(True)
        nuke.thisGroup()['write_result'].setEnabled(True)
        nuke.thisGroup()['write_dailies'].setEnabled(True)
        nuke.thisGroup()['slate'].setEnabled(True)
    
    if nuke.thisGroup().inputs > 0:
        nuke.autoplace(nuke.thisGroup())
    
    pData = None
Example #50
0
def initGizmos():
    allgizmos = toolbar.addMenu('all_gizmos', icon=icons.ico['animagrad'])
    gizmos = os.path.join(nuke_path, 'gizmos').replace('\\','/')
    nuke.tprint('============== CUSTOM GIZMOS: %s' % gizmos)
    for d, dirs, files in os.walk(gizmos):
        for file in files:
            gizmo_name, ext = os.path.splitext(file)
            if ext == '.gizmo':
                allgizmos.addCommand(gizmo_name, "nuke.createNode(\"" + gizmo_name + '\")' )
                nuke.tprint(gizmo_name)
    nuke.tprint('==============')
Example #51
0
  def _recursiveAddGizmoPaths(self, folder, crawlData, foldersOnly=False):
    # If we're in GUI mode, also store away data in _crawlData to to be used
    # later by addGizmoMenuItems
    if not os.path.isdir(folder):
      return

    if nuke.GUI:
      if 'files' not in crawlData:
        crawlData['gizmos'] = {}
      if 'dirs' not in crawlData:
        crawlData['dirs'] = {}

    # avoid an infinite loop due to symlinks...
    canonicalPath = self.canonicalPath(folder)
    if canonicalPath in self._visited:
      return
    self._visited.add(canonicalPath)

    for subItem in sorted(os.listdir(canonicalPath)):
      if self.exclude and self.exclude.search(subItem):
        continue
      subPath = os.path.join(canonicalPath, subItem)
      if os.path.isdir(subPath):
        nuke.pluginAppendPath(subPath)
        nuke.pluginAppendPath(os.path.join(subPath,'icons'))
        if DEBUG:
          nuke.tprint('GIZMO PATH: %s' % subPath)
        subData = {}
        if nuke.GUI:
          crawlData['dirs'][subItem] = subData
        self._recursiveAddGizmoPaths(subPath, subData)
      elif nuke.GUI and (not foldersOnly) and os.path.isfile(subPath):
        name, ext = os.path.splitext(subItem)
        if ext == '.gizmo':
          if re.match('[0-9]{3}', name[-3:]):
            gizmoName = name[:-4]
            version = name[-3:]
          else:
            gizmoName = name
            version = '000'
          crawlData['gizmos'][gizmoName]=[]
          crawlData['gizmos'][gizmoName].append(int(version))
          if DEBUG:
            nuke.tprint('GIZMO NAME: %s' % name)
            nuke.tprint('GIZMO VERS: %s' % version )
Example #52
0
  def _recursiveAddGizmoMenuItems(self, toolbar, crawlData, defaultSubMenu=None, topLevel=False):
    for name, versions in crawlData['gizmos'].items():
      niceName = name
      filename = "%s_%03d" % (name, max(versions))
      niceName = name.replace('_',' ')
      niceName = unCamel(niceName,' ',False,True)
      if DEBUG:
        nuke.tprint('GIZMO NAME: %s' % name)
        nuke.tprint('GIZMO VERS: %s' % ('%03d' % max(versions)) )
        nuke.tprint('GIZMO NICENAME: %s' % niceName)
      toolbar.addCommand(niceName,"nuke.createNode('%s')" % filename, '%s.png' % name )

    for folder, data in crawlData.get('dirs', {}).iteritems():
      import sys
      subMenu = toolbar.findItem(folder)
      if subMenu is None:
        if defaultSubMenu:
          subMenu = toolbar.findItem(defaultSubMenu)
          subMenu.addCommand("-", "", "")
        else:
          subMenu = toolbar.addMenu(folder, "%s.png" % folder)
      subMenu.addCommand("-", "", "")
      self._recursiveAddGizmoMenuItems(subMenu, data)
Example #53
0
import nuke
nuke.tprint('Loading RotopaintToSplineWarp_v2.py')
try:
    from RotopaintToSplineWarp_v2 import *
except:
    pass

#===============================================================================
# BVFX ToolBar Menu definitions
#===============================================================================
toolbar = nuke.menu("Nodes")
bvfxt = toolbar.addMenu("BoundaryVFX Tools", "BoundaryVFX.png")
bvfxt.addCommand('Rotopaint to SplineWarp Nukev7', 'Roto_to_WarpSpline_v2()', 'F8', icon='bvfx_SplineW.png')
def errorMsg(message):
    "Prints an error message to the terminal and script editor output."
    message = str(message)
    nuke.tprint(message)
    print message
Example #55
0
import logging

import nuke

logging.basicConfig(level=logging.INFO)

try:
    __import__("pyblish_nuke")

except ImportError as e:
    nuke.tprint("pyblish: Could not load integration: %s " % e)

else:

    import pyblish_nuke.lib

    # Setup integration
    pyblish_nuke.lib.setup()
Example #56
0
import nuke, os, sys
from amg import icons

nuke.tprint('============== init.py is running\n')

# nuke root
NUKE_PATH = os.path.join(os.getenv('AMG_ROOT'), 'scripts', 'nuke')

#add plugin path
nuke.pluginAddPath(os.path.join(NUKE_PATH, 'gizmos').replace('\\','/'))
nuke.pluginAddPath(os.path.join(NUKE_PATH, 'icons').replace('\\','/'))
nuke.pluginAddPath(os.path.join(os.getenv('AMG_PLUGINS'), 'nuke'))

# python
os.environ['PYTHONPATH'] = os.path.join(NUKE_PATH, 'python')

#favorites

nuke.addFavoriteDir( 'AMG', '[getenv AMG_ROOT]', nuke.IMAGE | nuke.GEO | nuke.FONT | nuke.PYTHON, icon=icons.ico['animagrad'] )


Example #57
0
import nuke
nuke.tprint('Loading freezeSplineWarp_v2.py')
try:
    from freezeSplineWarp_v2 import *
except:
    pass

#===============================================================================
# BVFX ToolBar Menu definitions
#===============================================================================
toolbar = nuke.menu("Nodes")
bvfxt = toolbar.addMenu("BoundaryVFX Tools", "BoundaryVFX.png")
bvfxt.addCommand('FreezeWarp for Nukev7', 'freezeWarp_v2()','shift+F8', icon='bvfx_SplineF.png')