コード例 #1
0
ファイル: nim_houdini.py プロジェクト: rohtau/nim_connectors
def mk_proj(path='', renPath=''):
    'Creates a show project structure'
    import hou
    workspaceExists = False

    #  Variables :
    projDirs = [
        'abc', 'audio', 'comp', 'desk', 'flip', 'geo', 'hda', 'render',
        'scripts', 'sim', 'tex', 'video'
    ]

    projectName = os.path.basename(os.path.normpath(path))
    P.info('Project Folder: %s' % projectName)

    #  Create Houdini project directories :
    if os.path.isdir(path):
        for projDir in projDirs:
            _dir = os.path.normpath(
                os.path.join(path, projDir).replace('\\', '/'))
            if not os.path.isdir(_dir):
                P.info("DIR: %s" % _dir)
                try:
                    os.mkdir(_dir)
                except Exception, e:
                    P.error('Failed creating the directory: %s' % _dir)
                    P.error('    %s' % traceback.print_exc())
                    return False
コード例 #2
0
def mk_proj(path='', renPath=''):
    'Creates a show project structure'
    workspaceExists = False

    #  Variables :
    projDirs = [
        'assets', 'autosave', 'cache', 'cache/nCache', 'cache/nCache/fluid',
        'cache/particles', 'clips', 'data', 'images', 'movies', 'renderData',
        'renderData/depth', 'renderData/fur', 'renderData/fur/furAttrMap',
        'renderData/fur/furEqualMap', 'renderData/fur/furFiles',
        'renderData/fur/furImages', 'renderData/fur/furShadowMap',
        'renderData/iprImages', 'renderData/shaders', 'scenes', 'scenes/edits',
        'scripts', 'sound', 'sourceimages', 'sourceimages/3dPaintTextures'
    ]

    #  Create Maya project directories :
    path = os.path.normpath(path)
    if os.path.isdir(path):
        P.info('Creating Project Folders...')
        for projDir in projDirs:
            _dir = os.path.normpath(os.path.join(path, projDir))
            if not os.path.isdir(_dir):
                try:
                    os.mkdir(_dir)
                except Exception, e:
                    P.error('Failed creating the directory: %s' % _dir)
                    P.error('    %s' % traceback.print_exc())
                    return False
        P.info('Complete')
コード例 #3
0
def mk_proj(path='', renPath=''):
    'Creates a show project structure'
    import MaxPlus
    mpPM = MaxPlus.PathManager
    workspaceExists = False

    #  Variables :
    projDirs = [
        'sceneassets', 'sceneassets/animations', 'archives', 'autoback',
        'proxies', 'downloads', 'export', 'express', 'sceneassets/images',
        'import', 'materiallibraries', 'scenes', 'sceneassets\photometric',
        'previews', 'sceneassets/renderassets', 'renderoutput',
        'renderpresets', 'sceneassets/sound', 'vpost'
    ]

    projectName = os.path.basename(os.path.normpath(path))
    P.info('Project Folder: %s' % projectName)

    #  Create 3dsMax project directories :
    if os.path.isdir(path):
        for projDir in projDirs:
            _dir = os.path.normpath(
                os.path.join(path, projDir).replace('\\', '/'))
            if not os.path.isdir(_dir):
                P.info("DIR: %s" % _dir)
                try:
                    os.mkdir(_dir)
                except Exception, e:
                    P.error('Failed creating the directory: %s' % _dir)
                    P.error('    %s' % traceback.print_exc())
                    return False
コード例 #4
0
def read():
    'Reads and stores preferences'

    #P.info('nim_prefs.read')

    prefsFile = get_path()
    _prefs = {}

    #  Create preferences, if necessary :
    if not os.path.isfile(prefsFile):
        result = mk_default()
        if not result:
            P.error('Unable to create default preferences.')
            return False
    try:
        #  Read NIM preferences file :
        for line in open(prefsFile):
            name, var = line.partition("=")[::2]
            #  Changed "rstrip" method to "replace", so as not to replace spaces at the end
            var = var.replace('\n', '')
            var = var.replace('\r', '')
            if name != '' and name != '\n':
                _prefs[name.strip()] = var
        #  Remove empty dictionary entries :
        prefs = dict([(k, v) for k, v in _prefs.items() if len(k) > 0])
        return prefs
    except Exception, e:
        P.error('Unable to read preferences.')
        return False
コード例 #5
0
ファイル: nim_win.py プロジェクト: rohtau/nim_connectors
def userInfo( url='', apiUser='', newUser=False ) :
    'Retrieves the User ID to use for the window'
    
    user, userID, userList='', '', []
    
    isGUI = False
    try :
        #Validate Against DCC Environment
        if F.get_app() is not None :
            isGUI = True
    except :
        pass

    if isGUI :
        user=popup( title='Enter NIM Login', msg='Please enter your NIM username:'******'input', defaultInput=apiUser )
    else :
        user=raw_input('Please enter your NIM username: '******'q': 'getUserID', 'u': user}, debug=False, nimURL=url )
            print("userID: %s" % userID)
        else :
            userID=Api.get( sqlCmd={ 'q': 'getUserID', 'u': user}, debug=False )
            print("userID: %s" % userID)

        if type(userID)==type(list()) and len(userID)==1 :
            try :
                userID=userID[0]['ID']
                P.info( 'User set to "%s" (ID #%s)' % (user, userID) )
                if newUser == False:
                    #  Update Preferences :
                    Prefs.update( attr='NIM_User', value=user )
                    if isGUI :
                        popup( title='NIM User Set', msg='The NIM user has been set to %s.' % user)
                    else :
                        print('The NIM user has been set to %s.' % user)
                return (user, userID)
            except :
                return False
        else :
            P.error( 'Failed to find NIM user.' )
            if isGUI :
                response = popup( title='User Not Found', msg='The username entered is not a valid NIM user.\n\n Would you like to enter a new username?', type='okCancel')
            else :
                response=raw_input('The username entered is not a valid NIM user. Would you like to enter a new username? (Y/N)')
                if response == 'Y' or response == 'y' :
                    response = 'OK'

            if(response=='OK'):
                userInfo( url=url, newUser=newUser )
            else :
                return False
コード例 #6
0
def _prefsFail():
    'Determines course of action, after a user has input an invalid NIM URL'
    msg = 'Sorry, specified NIM URL is invalid.'
    P.error(msg)
    msg += '\n    Would you like to enter another one?'
    result = Win.popup(title='NIM - URL Error', msg=msg, type='okCancel')
    #P.info( 'WINDOW RESULT: %s' % result)
    if result == 'OK':
        url = _inputURL()
        test = _verifyURL(url)
        P.info('NIM URL Verified: %s' % test)
        if test: return [result, url]
    return [result, False]
コード例 #7
0
ファイル: nim.py プロジェクト: rohtau/nim_connectors
    def ingest_prefs(self):
        'Sets NIM dictionary from preferences'
        self.app = F.get_app()
        self.prefs = Prefs.read()

        if not self.prefs:
            return False

        P.info('Preferences being read...')

        #  Set User Information :
        user = self.prefs['NIM_User']
        userID = Api.get(sqlCmd={'q': 'getUserID', 'u': user}, debug=False)
        if userID:
            if type(userID) == type(list()) and len(userID) == 1:
                userID = userID[0]['ID']
            try:
                self.nim['user'] = {'name': user, 'ID': str(userID)}
            except:
                self.nim['user'] = {'name': '', 'ID': ''}
                P.warning('Unable to set User information in NIM!')

            #  Get Show/Shot Prefs :
            try:
                self.set_name(elem='job', name=self.prefs[self.app + '_Job'])
                self.set_name(elem='asset',
                              name=self.prefs[self.app + '_Asset'])
                self.set_tab(_type=self.prefs[self.app + '_Tab'])
                self.set_name(elem='show', name=self.prefs[self.app + '_Show'])
                self.set_name(elem='shot', name=self.prefs[self.app + '_Shot'])
                self.set_name(elem='filter',
                              name=self.prefs[self.app + '_Filter'])
                self.set_name(elem='task', name=self.prefs[self.app + '_Task'])
                self.set_name(elem='base',
                              name=self.prefs[self.app + '_Basename'])
                self.set_name(elem='ver',
                              name=self.prefs[self.app + '_Version'])
            except:
                P.error(
                    'Sorry, unable to get NIM preferences, cannot run NIM GUI')
                P.error('    %s' % traceback.print_exc())
                win.popup(
                    title='NIM Error',
                    msg=
                    'Sorry, unable to get NIM preferences, cannot run NIM GUI')
                return False
            return self
        else:
            return False
コード例 #8
0
def makeProject(projectLocation='', renderPath=''):
    'Create the new project and workspace setup'

    createDirectories = True

    # Get list of all standard file rules
    fileRules = mm.eval('np_getDefaultFileRuleWidgets')
    try:
        #Update with NIM Render Directory
        if renderPath:
            imageRuleIndex = fileRules.index(u'images'.replace('\\', '/'))
            fileRules[imageRuleIndex + 1] = unicode(renderPath)
    except:
        P.error('Could not set NIM render path in workspace.')

    mc.workspace(projectLocation, openWorkspace=True)

    if createDirectories:
        print "Creating Directories"
        # Set workspace current directory to the workspace root so relative paths created with -create are located correctly
        mc.workspace(dir=mc.workspace(q=True, rootDirectory=True))

    items = len(fileRules)
    for i in range(0, items - 1, 2):
        # each rule has 2 entries: rulename, value
        ruleName = fileRules[i]
        ruleValue = fileRules[i + 1]
        mc.workspace(fr=(ruleName, ruleValue))
        if createDirectories:
            mc.workspace(create=ruleValue)

    #Adding images folder to project
    mc.workspace(create='images')

    mc.workspace(saveWorkspace=True)
    mc.workspace(projectLocation, o=True)
    mm.eval(
        'if (`window -ex projectWindow`){print "Window Open"; deleteUI projectWindow;projectWindow;}'
    )
    mm.eval('np_resetBrowserPrefs;')

    return True
コード例 #9
0
def os_filePath(path='', nim=None, serverID=None):
    'Returns the platform specific path to a filepath.'
    filePath, fp_noServer, server = '', '', ''

    #P.info("os_filePath PATH: %s" % path)
    #  Error Checking :
    if not nim.ID('job'):
        P.warning('Unable to find a platform specific OS path')
        return path

    if not serverID:
        serverDict = Api.get_serverInfo(nim.server(get='ID'))
    else:
        serverDict = Api.get_serverInfo(serverID)
    #P.info("serverDict: %s" % serverDict)

    if not serverDict or not len(serverDict):
        P.warning('Unable to find a platform specific OS path')
        return path

    if nim.server():
        fp_noServer = path[len(nim.server()):]

    # The following removed - redundant
    '''
    if nim.tab()=='SHOT' :
        serverDict=Api.get_jobServers( nim.ID('job') )
    elif nim.tab()=='ASSET' :
        serverDict=Api.get_jobServers( nim.ID('job') )
    '''

    #if serverDict and len(serverDict)>0 :      # removed to only compare to single server
    if serverDict and len(
            serverDict
    ) == 1:  # failed if more than one server found in serverDict

        #  Substitute Windows Paths :
        if serverDict[0]['winPath']:
            #P.info('Reading Window Path...')
            if re.search('^' + serverDict[0]['winPath'], path):
                fp_noServer = path[len(serverDict[0]['winPath']):]
            elif re.search('^' + serverDict[0]['winPath'],
                           path.replace('\\', '/')):
                fp_noServer = path[len(serverDict[0]['winPath']):]
            elif re.search('^' + serverDict[0]['winPath'],
                           path.replace('/', '\\')):
                fp_noServer = path[len(serverDict[0]['winPath']):]

        #  Substitute Mac paths :
        if serverDict[0]['osxPath']:
            #P.info('Reading OSX Path...')
            if re.search('^' + serverDict[0]['osxPath'], path):
                fp_noServer = path[len(serverDict[0]['osxPath']):]
            elif re.search('^' + serverDict[0]['osxPath'],
                           path.replace('\\', '/')):
                fp_noServer = path[len(serverDict[0]['osxPath']):]
            elif re.search('^' + serverDict[0]['osxPath'],
                           path.replace('/', '\\')):
                fp_noServer = path[len(serverDict[0]['osxPath']):]

        #  Substitute Linux Paths :
        if serverDict[0]['path']:
            #P.info('Reading Linux Path...')
            if re.search('^' + serverDict[0]['path'], path):
                fp_noServer = path[len(serverDict[0]['path']):]
            elif re.search('^' + serverDict[0]['path'],
                           path.replace('\\', '/')):
                fp_noServer = path[len(serverDict[0]['path']):]
            elif re.search('^' + serverDict[0]['path'],
                           path.replace('/', '\\')):
                fp_noServer = path[len(serverDict[0]['path']):]

        #  Store file path :
        if _os.lower() in ['windows', 'win32']:
            server = serverDict[0]['winPath']
            path = server + fp_noServer
            filePath = path.replace('/', '\\')
            return filePath
        elif _os.lower() in ['darwin', 'mac']:
            server = serverDict[0]['osxPath']
            path = server + fp_noServer
            filePath = path.replace('\\', '/')
            return filePath
        elif _os.lower() in ['linux', 'linux2']:
            server = serverDict[0]['path']
            path = server + fp_noServer
            filePath = path.replace('\\', '/')
            return filePath
        else:
            P.info(
                'Operating system, %s, not in valid list of operating systems'
                % _os)
            return False

        P.info('Filepath set to - %s' % filePath)

    else:
        P.error('Unable to convert filepath by platform!')
        return False

    return filePath
コード例 #10
0
def mk_default(recreatePrefs=False, notify_success=True):
    'Makes default preferences'

    global apps
    global nim_api
    global nim_user, nim_userID
    global nim_URL

    isGUI = False
    try:
        #Validate Against DCC Environment
        if F.get_app() is not None:
            isGUI = True
    except:
        pass

    nimHome = mk_home()
    prefsFile = get_path()
    apps = F.get_apps()
    #nim_user=F.get_user()
    url, userID = 1, ''

    #  Create home dir, if necessary :
    mk_home()

    #  Check to see if preferences need to be re-created :
    if os.path.exists(prefsFile):
        #  If preferences have missing attributes, add those attributes to prefs file:
        prefs_check = check()
        if prefs_check:
            #  Open NIM prefs file for appending :
            _prefFile = open(prefsFile, 'a')
            _prefFile.write('\n')
            #  Write NIM preferences :
            nim_prefs = _nimPrefs()
            missing_at_least_one_nim_pref = False
            for key in prefs_check:
                if key in nim_prefs:
                    missing_at_least_one_nim_pref = True
                    _prefFile.write(key + '=' + nim_prefs[key] + '\n')
            if missing_at_least_one_nim_pref:
                _prefFile.write('\n')
            #  Write Application Preferences :
            for app in apps:
                app_prefs = _appPrefs(app)
                for key in prefs_check:
                    if key in app_prefs:
                        _prefFile.write(key + '=' + app_prefs[key] + '\n')
                _prefFile.write('\n')
            #  Close file :
            _prefFile.close()
        else:
            #  Ask to recreate existing preferences :
            if recreatePrefs:
                if isGUI:
                    recreate=Win.popup( title=winTitle+' - Prefs Exist', \
                        msg='Preferences already exist.\nWould you like to re-create your preferences?', \
                        type='okCancel' )
                else:
                    recreate = raw_input(
                        "Preferences already exist. Would you like to re-create your preferences? (Y\N) "
                    )
                    if recreate == 'Y' or recreate == 'y':
                        recreate = 'OK'

                if recreate == 'OK':
                    P.info('Deleting previous preferences file...')
                    try:
                        os.remove(prefsFile)
                    except Exception, e:
                        P.error('Unable to delete preferences')
                        P.error('    %s' % traceback.print_exc())
                        return False
                else:
                    return prefsFile
            else:
                return prefsFile
コード例 #11
0
                break
            else:
                msg = 'The NIM API URL entered is invalid :\n %s \nTry Again?' % url
                if isGUI:
                    keepGoing = Win.popup(title=winTitle + ' - Get URL',
                                          msg=msg,
                                          type='okCancel')
                else:
                    keepGoing = raw_input(
                        'The NIM API URL entered is invalid. Try Again? (Y/N):'
                    )
                    if keepGoing == 'Y' or keepGoing == 'y':
                        keepGoing = 'OK'

                if keepGoing != 'OK':
                    P.error('Exiting without setting NIM Preferences.')
                    search_for_url = False
                    search_for_user = False
                    return False

        #  Verify User :
        if search_for_user:
            P.info('Searching for NIM User')
            #Force input of username at preference creation
            result = get_userInfo(url=nim_URL)
            if type(result) == type(tuple()) and len(result) == 2:
                nim_user = result[0]
                nim_userID = result[1]

        #  Notify of failure if there is information missing :
        if not nim_URL or not nim_user or not nim_userID:
コード例 #12
0
ファイル: nim_win.py プロジェクト: rohtau/nim_connectors
def popup( title='', msg='', type='ok', defaultInput='', pyside=False, _list=[], selNum=0, winPrnt=None ) :
    'Attempts to build a simple dialog window in either native application calls, or PySide'
    app=F.get_app()
    userInput=''
    
    #  Create PySide window :
    if pyside :
        try :
            if type=='comboBox' :
                userInput, ok=QtGui.QInputDialog.getItem( winPrnt, title, msg, _list, 0, False )
                if not ok :
                    userInput=None
        except :
            P.error( 'Sorry, problem loading the dialog.' )
    
    # Cinesync Window :        
    elif app == 'Cinesync':
        try:
            if type == 'input' or type == 'okCancel':
                userInput, ok = QtGui.QInputDialog.getText(winPrnt, title, msg, QtGui.QLineEdit.Normal, defaultInput)
                if not ok:
                    userInput = None

        except Exception as err:
            P.error('Error with dialog: %s' % str(err))
    
    #  Maya Window :
    elif app=='Maya' :
        import maya.cmds as mc
        if type=='ok' :
            userInput=mc.confirmDialog( title=title, message=msg, button=['OK'], \
                defaultButton='OK' )
        elif type=='okCancel' :
            userInput=mc.confirmDialog( title=title, message=msg, button=['OK', 'Cancel'], \
                defaultButton='OK', cancelButton='Cancel', dismissString='Cancel' )
        elif type=='input' :
            userInput=mc.promptDialog( title=title, message=msg, text=defaultInput, \
                button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel' )
            if userInput=='OK' :
                userInput=str(mc.promptDialog( query=True, text=True ))
            else :
                userInput=''
    
    #  Nuke Window :
    elif app=='Nuke' :
        import nuke
        if type=='ok' :
            userInput=nuke.message( msg )
        elif type=='okCancel' :
            userInput=nuke.ask( msg )
            if userInput :
                userInput='OK'
            else :
                userInput='Cancel'
        elif type=='input' :
            userInput=nuke.getInput( msg, defaultInput )
    
    #  Hiero Window :
    elif app=='Hiero' :
        import hiero.ui
        from hiero.core import log
        if type=='ok' :
            dialog=QtGui.QMessageBox.information( hiero.ui.mainWindow(), title, msg, \
                QtGui.QMessageBox.Ok)
            if dialog==QtGui.QMessageBox.Ok :
                userInput='OK'
        elif type=='okCancel' :
            dialog=QtGui.QMessageBox.question( hiero.ui.mainWindow(), title, msg, \
                QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Ok )
            if dialog==QtGui.QMessageBox.Ok :
                userInput='OK'
            elif dialog==QtGui.QMessageBox.Cancel :
                userInput='Cancel'
        elif type=='input' :
            dialog=QtGui.QInputDialog.getText( QtGui.QInputDialog(), title, msg, \
                QtGui.QLineEdit.Normal )
            if dialog[1] :
                userInput=dialog[0]
            else :
                userInput=None
    
    #  C4D Window :
    elif app=='C4D' :
        import c4d
        from c4d import gui
        if type=='ok' :
            userInput=gui.MessageDialog( msg )
        elif type=='okCancel' :
            userInput=gui.QuestionDialog( text=msg )
            if userInput : userInput='OK'
        elif type=='input' :
            userInput=gui.InputDialog( msg )
    
    #  3dsMax :
    elif app=='3dsMax' :
        import MaxPlus
        #maxWin=MaxPlus.Win32_GetMAXHWnd()

        if type=='ok' :
            dialog=QtGui.QMessageBox.information( None, title, msg, \
                QtGui.QMessageBox.Ok)
            if dialog==QtGui.QMessageBox.Ok :
                userInput='OK'
        elif type=='okCancel' :
            dialog=QtGui.QMessageBox.question( None, title, msg, \
                QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Ok )
            if dialog==QtGui.QMessageBox.Ok :
                userInput='OK'
            elif dialog==QtGui.QMessageBox.Cancel :
                userInput='Cancel'
        elif type=='input' :
            dialog=QtGui.QInputDialog.getText( QtGui.QInputDialog(), title, msg, \
                QtGui.QLineEdit.Normal )
            if dialog[1] :
                userInput=dialog[0]
            else :
                userInput=None

    #  Houdini :
    elif app=='Houdini' :
        import hou
        if type=='ok' :
            dialog=QtGui.QMessageBox.information( None, title, msg, \
                QtGui.QMessageBox.Ok)
            if dialog==QtGui.QMessageBox.Ok :
                userInput='OK'
        elif type=='okCancel' :
            dialog=QtGui.QMessageBox.question( None, title, msg, \
                QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Ok )
            if dialog==QtGui.QMessageBox.Ok :
                userInput='OK'
            elif dialog==QtGui.QMessageBox.Cancel :
                userInput='Cancel'
        elif type=='input' :
            inputFont = QtGui2.QFont()
            inputFont.setFamily("Ariel")
            inputFont.setPointSize(20)
            inputDialog = QtGui.QInputDialog(None)
            inputDialog.setStyleSheet( "* {background-color: #333333; color: white;}" );
            inputDialog.setInputMode(QtGui.QInputDialog.TextInput)
            inputDialog.setWindowTitle(title)
            inputDialog.setLabelText(msg)
            inputDialog.setFont(inputFont)
            ok = inputDialog.exec_()
            if(ok):
                userInput = inputDialog.textValue()
            else :
                userInput = None

    #  Flame :
    elif app=='Flame' :
        if type=='ok' :
            dialog=QtGui.QMessageBox.information( None, title, msg, \
                QtGui.QMessageBox.Ok)
            if dialog==QtGui.QMessageBox.Ok :
                userInput='OK'
        elif type=='okCancel' :
            dialog=QtGui.QMessageBox.question( None, title, msg, \
                QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Ok )
            if dialog==QtGui.QMessageBox.Ok :
                userInput='OK'
            elif dialog==QtGui.QMessageBox.Cancel :
                userInput='Cancel'
        elif type=='input' :
            dialog=QtGui.QInputDialog.getText( QtGui.QInputDialog(), title, msg, \
                QtGui.QLineEdit.Normal )
            if dialog[1] :
                userInput=dialog[0]
            else :
                userInput=None

    #P.info('Returning PopUP INFO: %s' % userInput)
    return userInput
コード例 #13
0
def set_vars(nim=None):
    'Add variables to 3dsMax Globals'

    P.info('\n3dsMax - Setting Globals variables...')

    makeGlobalAttrs = False
    try:
        #TEST FOR EXISTING NIM DATA
        MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_user")
    except:
        makeGlobalAttrs = True

    if makeGlobalAttrs:
        P.info("NIM DATA Not Found.\nAdding Global Attributes")
        nimAttrCmd = 'sceneDataCADef = attributes sceneDataCADef version:1 attribID:#(0x4fb91dfa, 0x73284f9e) \n\
                        (   \n\
                            parameters main rollout:params \n\
                            ( \n\
                                nim_user type:#string ui:nim_user default:"" \n\
                                nim_userID type:#string ui:nim_userID default:"" \n\
                                nim_class type:#string ui:nim_class default:"" \n\
                                nim_server type:#string ui:nim_server default:"" \n\
                                nim_serverID type:#string ui:nim_serverID default:"" \n\
                                nim_jobName type:#string ui:nim_jobName default:"" \n\
                                nim_jobID type:#string ui:nim_jobID default:"" \n\
                                nim_showName type:#string ui:nim_showName default:"" \n\
                                nim_showID type:#string ui:nim_showID default:"" \n\
                                nim_shot type:#string ui:nim_shot default:"" \n\
                                nim_shotID type:#string ui:nim_shotID default:"" \n\
                                nim_asset type:#string ui:nim_asset default:"" \n\
                                nim_assetID type:#string ui:nim_assetID default:"" \n\
                                nim_fileID type:#string ui:nim_fileID default:"" \n\
                                nim_name type:#string ui:nim_name default:"" \n\
                                nim_basename type:#string ui:nim_basename default:"" \n\
                                nim_type type:#string ui:nim_type default:"" \n\
                                nim_typeID type:#string ui:nim_typeID default:"" \n\
                                nim_typeFolder type:#string ui:nim_typeFolder default:"" \n\
                                nim_tag type:#string ui:nim_tag default:"" \n\
                                nim_fileType type:#string ui:nim_fileType default:"" \n\
                            ) \n\
                            rollout params "Scene Data Parameters" \n\
                            (  \n\
                                edittext nim_user "NIM nim_user" \n\
                                edittext nim_userID "NIM UserID" \n\
                                edittext nim_class "NIM nim_class" \n\
                                edittext nim_server "NIM nim_server" \n\
                                edittext nim_serverID "NIM ServerID" \n\
                                edittext nim_jobName "NIM nim_jobName" \n\
                                edittext nim_jobID "NIM JobID" \n\
                                edittext nim_showName "NIM nim_showName" \n\
                                edittext nim_showID "NIM ShowID" \n\
                                edittext nim_shot "NIM nim_shot" \n\
                                edittext nim_shotID "NIM nim_shotID" \n\
                                edittext nim_asset "NIM nim_asset" \n\
                                edittext nim_assetID "NIM nim_assetID" \n\
                                edittext nim_fileID "NIM nim_fileID" \n\
                                edittext nim_name "NIM nim_name" \n\
                                edittext nim_basename "NIM nim_basename" \n\
                                edittext nim_type "NIM nim_type" \n\
                                edittext nim_typeID "NIM nim_typeID" \n\
                                edittext nim_typeFolder "NIM nim_typeFolder" \n\
                                edittext nim_tag "NIM nim_tag" \n\
                                edittext nim_fileType "NIM nim_fileType" \n\
                            ) \n\
                        ) \n\
                        thescene = (refs.dependents rootnode)[1] \n\
                        rootNodeDataCA = undefined \n\
                        if (custattributes.add rootnode sceneDataCADef) do \n\
                            rootNodeDataCA = rootnode.custAttributes[rootnode.custAttributes.count] \n\
                        sceneDataCA = undefined \n\
                        if (custattributes.add thescene sceneDataCADef) do \n\
                            sceneDataCA = thescene.custAttributes[thescene.custAttributes.count] \n'

        try:
            MaxPlus.Core.EvalMAXScript(nimAttrCmd)
            P.info("Root and Scene attributes added")
        except:
            P.error("Failed to create global attributes")
            return

    P.info("Reading Global Attributes")
    nimAttrReadCmd = 'thescene = (refs.dependents rootnode)[1] \n\
                      rootNodeDataCA = undefined \n\
                      if(rootnode.custAttributes.count != 0) do \n\
                         rootNodeDataCA = rootnode.custAttributes[rootnode.custAttributes.count] \n\
                      sceneDataCA = undefined \n\
                      if(thescene.custAttributes.count != 0) do \n\
                         sceneDataCA = thescene.custAttributes[thescene.custAttributes.count] \n'

    try:
        MaxPlus.Core.EvalMAXScript(nimAttrReadCmd)
    except:
        P.error('Failed to read global attributes')
        return

    #  User :
    userInfo = nim.userInfo()
    '''
    if not mc.attributeQuery( 'nim_user', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_user', dt='string' )
    mc.setAttr( 'defaultRenderGlobals.nim_user', userInfo['name'], type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_user="******"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_user="******"')

    #  User ID :
    '''
    if not mc.attributeQuery( 'nim_userID', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_userID', dt='string' )
    mc.setAttr( 'defaultRenderGlobals.nim_userID', userInfo['ID'], type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_userID="' +
                               str(userInfo['ID']) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_userID="' +
                               str(userInfo['ID']) + '"')

    #  Tab/Class :
    '''
    if not mc.attributeQuery( 'nim_class', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_class', dt='string' )
    mc.setAttr( 'defaultRenderGlobals.nim_class', nim.tab(), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_class="' + str(nim.tab()) +
                               '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_class="' + str(nim.tab()) +
                               '"')

    #  Server :
    '''
    if not mc.attributeQuery( 'nim_server', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_server', dt="string")
    mc.setAttr( 'defaultRenderGlobals.nim_server', nim.server(), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_server="' +
                               str(nim.server()) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_server="' + str(nim.server()) +
                               '"')

    #  Server ID :
    '''
    if not mc.attributeQuery( 'nim_serverID', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_serverID', dt="string")
    mc.setAttr( 'defaultRenderGlobals.nim_serverID', str(nim.ID('server')), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_serverID="' +
                               str(nim.ID('server')) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_serverID="' +
                               str(nim.ID('server')) + '"')

    #  Job :
    '''
    if not mc.attributeQuery( 'nim_jobName', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_jobName', dt="string")
    mc.setAttr( 'defaultRenderGlobals.nim_jobName', nim.name('job'), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_jobName="' +
                               str(nim.name('job')) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_jobName="' +
                               str(nim.name('job')) + '"')

    #  Job ID :
    '''
    if not mc.attributeQuery( 'nim_jobID', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_jobID', dt="string")
    mc.setAttr( 'defaultRenderGlobals.nim_jobID', str(nim.ID('job')), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_jobID="' +
                               str(nim.ID('job')) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_jobID="' + str(nim.ID('job')) +
                               '"')

    #  Show :
    '''
    if not mc.attributeQuery( 'nim_showName', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_showName', dt="string")
    mc.setAttr( 'defaultRenderGlobals.nim_showName', nim.name('show'), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_showName="' +
                               str(nim.name('show')) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_showName="' +
                               str(nim.name('show')) + '"')

    #  Show ID :
    '''
    if nim.tab()=='SHOT' :
        if not mc.attributeQuery( 'nim_showID', node='defaultRenderGlobals', exists=True) :
            mc.addAttr( 'defaultRenderGlobals', longName='nim_showID', dt="string")
        mc.setAttr( 'defaultRenderGlobals.nim_showID', str(nim.ID('show')), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_showID="' +
                               str(nim.ID('show')) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_showID="' +
                               str(nim.ID('show')) + '"')

    #  Shot :
    '''
    if not mc.attributeQuery( 'nim_shot', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_shot', dt="string")
    mc.setAttr( 'defaultRenderGlobals.nim_shot', str(nim.name('shot')), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_shot="' +
                               str(nim.name('shot')) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_shot="' +
                               str(nim.name('shot')) + '"')

    #  Shot ID :
    '''
    if not mc.attributeQuery( 'nim_shotID', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_shotID', dt="string")
    mc.setAttr( 'defaultRenderGlobals.nim_shotID', str(nim.ID('shot')), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_shotID="' +
                               str(nim.ID('shot')) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_shotID="' +
                               str(nim.ID('shot')) + '"')

    #  Asset :
    '''
    if nim.tab()=='ASSET' :
        if not mc.attributeQuery( 'nim_asset', node='defaultRenderGlobals', exists=True) :
            mc.addAttr( 'defaultRenderGlobals', longName='nim_asset', dt="string")
        mc.setAttr( 'defaultRenderGlobals.nim_asset', str(nim.name('asset')), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_asset="' +
                               str(nim.name('asset')) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_asset="' +
                               str(nim.name('asset')) + '"')

    #  Asset ID :
    '''
    if nim.tab()=='ASSET' :
        if not mc.attributeQuery( 'nim_assetID', node='defaultRenderGlobals', exists=True) :
            mc.addAttr( 'defaultRenderGlobals', longName='nim_assetID', dt="string")
        mc.setAttr( 'defaultRenderGlobals.nim_assetID', str(nim.ID('asset')), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_assetID="' +
                               str(nim.ID('asset')) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_assetID="' +
                               str(nim.ID('asset')) + '"')

    #  File ID :
    '''
    if not mc.attributeQuery( 'nim_fileID', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_fileID', dt="string")
    mc.setAttr( 'defaultRenderGlobals.nim_fileID', str(nim.ID('ver')), type='string' )
    '''
    P.info("FileID: %s" % str(nim.ID('ver')))
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_fileID="' +
                               str(nim.ID('ver')) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_fileID="' +
                               str(nim.ID('ver')) + '"')

    #  Shot/Asset Name :
    '''
    if not mc.attributeQuery( 'nim_name', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_name', dt="string")
    '''
    if nim.tab() == 'SHOT':
        #mc.setAttr( 'defaultRenderGlobals.nim_name', nim.name('shot'), type='string' )
        MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_name="' +
                                   str(nim.name('shot')) + '"')
        MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_name="' +
                                   str(nim.name('shot')) + '"')
    elif nim.tab() == 'ASSET':
        #mc.setAttr( 'defaultRenderGlobals.nim_name', nim.name('asset'), type='string' )
        MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_name="' +
                                   str(nim.name('asset')) + '"')
        MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_name="' +
                                   str(nim.name('asset')) + '"')

    #  Basename :
    '''
    if not mc.attributeQuery( 'nim_basename', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_basename', dt="string")
    mc.setAttr( 'defaultRenderGlobals.nim_basename', nim.name('base'), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_basename="' +
                               str(nim.name('base')) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_basename="' +
                               str(nim.name('base')) + '"')

    #  Task :
    '''
    if not mc.attributeQuery( 'nim_type', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_type', dt="string")
    mc.setAttr( 'defaultRenderGlobals.nim_type', nim.name( elem='task' ), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_type="' +
                               str(nim.name(elem='task')) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_type="' +
                               str(nim.name(elem='task')) + '"')

    #  Task ID :
    '''
    if not mc.attributeQuery( 'nim_typeID', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_typeID', dt="string")
    mc.setAttr( 'defaultRenderGlobals.nim_typeID', str(nim.ID( elem='task' )), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_typeID="' +
                               str(nim.ID(elem='task')) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_typeID="' +
                               str(nim.ID(elem='task')) + '"')

    #  Task Folder :
    '''
    if not mc.attributeQuery( 'nim_typeFolder', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_typeFolder', dt="string")
    mc.setAttr( 'defaultRenderGlobals.nim_typeFolder', str(nim.taskFolder()), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_typeFolder="' +
                               str(nim.taskFolder()) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_typeFolder="' +
                               str(nim.taskFolder()) + '"')

    #  Tag :
    '''
    if not mc.attributeQuery( 'nim_tag', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_tag', dt="string")
    mc.setAttr( 'defaultRenderGlobals.nim_tag', nim.name('tag'), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_tag="' +
                               str(nim.name('tag')) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_tag="' + str(nim.name('tag')) +
                               '"')

    #  File Type :
    '''
    if not mc.attributeQuery( 'nim_fileType', node='defaultRenderGlobals', exists=True) :
        mc.addAttr( 'defaultRenderGlobals', longName='nim_fileType', dt="string")
    mc.setAttr( 'defaultRenderGlobals.nim_fileType', nim.fileType(), type='string' )
    '''
    MaxPlus.Core.EvalMAXScript('rootNodeDataCA.nim_fileType="' +
                               str(nim.fileType()) + '"')
    MaxPlus.Core.EvalMAXScript('sceneDataCA.nim_fileType="' +
                               str(nim.fileType()) + '"')

    P.info('    Completed setting NIM attributes root node.')
    #nim.Print()

    return
コード例 #14
0
def get_vars(nim=None):
    'Gets NIM settings from the defaultRenderGlobals node in 3dsMax.'
    P.info(
        '3dsMax Getting information from NIM attributes on the defaultRenderGlobals node...'
    )

    #  User :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_user' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_user' )
        P.debug( 'User = %s' % value )
        nim.set_user( userName=value )
    '''
    nim_user = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_user", nim_user)
    if success:
        nim.set_user(nim_user.Get())
        P.info('Reading userName')
    else:
        P.error('Failed reading userName')

    #  User ID :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_userID' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_userID' )
        P.debug( 'User ID = %s' % value )
        nim.set_userID( userID=value )
    '''
    nim_userID = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_userID",
                                         nim_userID)
    if success:
        nim.set_userID(nim_userID.Get())
        P.error('Reading nim_userID')
    else:
        P.error('Failed reading nim_userID')

    #  Tab/Class :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_class' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_class' )
        P.debug( 'Tab = %s' % value )
        nim.set_tab( value )
    '''
    nim_class = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_class", nim_class)
    if success:
        nim.set_tab(nim_class.Get())
        P.error('Reading nim_class')
    else:
        P.error('Failed reading nim_class')

    #  Server :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_server' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_server' )
        P.debug( 'Server = %s' % value )
        nim.set_server( path=value )
    '''
    nim_server = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_server",
                                         nim_server)
    if success:
        nim.set_server(path=nim_server.Get())
        P.error('Reading nim_server')
    else:
        P.error('Failed reading nim_server')

    #  Server ID :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_serverID' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_serverID' )
        P.debug( 'Server ID = %s' % value )
        nim.set_ID( elem='server', ID=value )
    '''
    nim_serverID = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_serverID",
                                         nim_serverID)
    if success:
        nim.set_ID(elem='server', ID=nim_serverID.Get())
        P.error('Reading nim_serverID')
    else:
        P.error('Failed reading nim_serverID')

    #  Job :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_jobName' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_jobName' )
        P.debug( 'Job = %s' % value )
        nim.set_name( elem='job', name=value )
    '''
    nim_jobName = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_jobName",
                                         nim_jobName)
    if success:
        nim.set_name(elem='job', name=nim_jobName.Get())
        P.error('Reading nim_jobName')
    else:
        P.error('Failed reading nim_jobName')

    #  Job ID :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_jobID' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_jobID' )
        P.debug( 'Job ID = %s' % value )
        nim.set_ID( elem='job', ID=value )
    '''
    nim_jobID = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_jobID", nim_jobID)
    if success:
        nim.set_ID(elem='job', ID=nim_jobID.Get())
        P.error('Reading nim_jobID')
    else:
        P.error('Failed reading nim_jobID')

    #  Show :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_showName' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_showName' )
        P.debug( 'Show = %s' % value )
        nim.set_name( elem='show', name=value )
    '''
    nim_showName = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_showName",
                                         nim_showName)
    if success:
        nim.set_name(elem='show', name=nim_showName.Get())
        P.error('Reading nim_showName')
    else:
        P.error('Failed reading nim_showName')

    #  Show ID :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_showID' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_showID' )
        P.debug( 'Show ID = %s' % value )
        nim.set_ID( elem='show', ID=value )
    '''
    nim_showID = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_showID",
                                         nim_showID)
    if success:
        nim.set_ID(elem='show', ID=nim_showID.Get())
        P.error('Reading nim_showID')
    else:
        P.error('Failed reading nim_showID')

    #  Shot :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_shot' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_shot' )
        P.debug( 'Shot = %s' % value )
        nim.set_name( elem='shot', name=value )
    '''
    nim_shot = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_shot", nim_shot)
    if success:
        nim.set_name(elem='shot', name=nim_shot.Get())
        P.error('Reading nim_shot')
    else:
        P.error('Failed reading nim_shot')

    #  Shot ID :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_shotID' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_shotID' )
        P.debug( 'Shot ID = %s' % value )
        nim.set_ID( elem='shot', ID=value )
    '''
    nim_shotID = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_shotID",
                                         nim_shotID)
    if success:
        nim.set_ID(elem='shot', ID=nim_shotID.Get())
        P.error('Reading nim_shotID')
    else:
        P.error('Failed reading nim_shotID')

    #  Asset :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_asset' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_asset' )
        P.debug( 'Asset = %s' % value )
        nim.set_name( elem='asset', name=value )
    '''
    nim_asset = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_asset", nim_asset)
    if success:
        nim.set_name(elem='asset', name=nim_asset.Get())
        P.error('Reading nim_asset')
    else:
        P.error('Failed reading nim_asset')

    #  Asset ID :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_assetID' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_assetID' )
        P.debug( 'Asset ID = %s' % value )
        nim.set_ID( elem='asset', ID=value )
    '''
    nim_assetID = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_assetID",
                                         nim_assetID)
    if success:
        nim.set_ID(elem='asset', ID=nim_assetID.Get())
        P.error('Reading nim_assetID')
    else:
        P.error('Failed reading nim_assetID')

    #  File ID :
    '''
    if mc.attributeQuery( 'defaultRenderGlobals.nim_fileID' ) :
        value=mc.attributeQuery( 'nim_fileID', node='defaultRenderGlobals' )
        P.debug( 'Class = %s' % value )
        nim.set_tab( tab=value )
    '''
    #TODO: Check if Maya code is error or intentional
    nim_fileID = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_fileID",
                                         nim_fileID)
    if success:
        #nim.set_ID( elem='file', ID=nim_fileID.Get() )
        #nim.set_tab( tab=nim_fileID.Get() )
        #P.error('Reading nim_fileID')
        pass
    else:
        P.error('Failed reading nim_fileID')

    #  Shot/Asset Name :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_name' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_name' )
        #  Determine what the tab is set to :
        if nim.tab()=='SHOT' :
            P.debug( 'Shot Name = %s' % value )
            #  No corresponding NIM attribute :
            #nim.set_tab( value )
        elif nim.tab()=='ASSET' :
            P.debug( 'Asset Name = %s' % value )
            #  No corresponding NIM attribute :
            #nim.set_tab( value )
    '''
    nim_name = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_name", nim_name)
    if success:
        if nim.tab() == 'SHOT':
            P.debug('Shot Name = %s' % nim_name.Get())
            #nim.set_tab( nim_name.Get() )
        elif nim.tab() == 'ASSET':
            P.debug('Asset Name = %s' % nim_name.Get())
            #nim.set_tab( nim_name.Get() )
    else:
        P.error('Failed reading nim_name')

    #  Basename :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_basename' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_basename' )
        P.debug( 'Basename = %s' % value )
        nim.set_name( elem='base', name=value )
    
    '''
    nim_basename = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_basename",
                                         nim_basename)
    if success:
        nim.set_name(elem='base', name=nim_basename.Get())
        P.error('Reading nim_basename')
    else:
        P.error('Failed reading nim_basename')

    #  Task :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_type' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_type' )
        P.debug( 'Task = %s' % value )
        nim.set_name( elem='task', name=value )
    
    '''
    nim_type = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_type", nim_type)
    if success:
        nim.set_name(elem='task', name=nim_type.Get())
        P.error('Reading nim_type')
    else:
        P.error('Failed reading nim_type')

    #  Task ID :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_typeID' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_typeID' )
        P.debug( 'Task ID = %s' % value )
        nim.set_ID( elem='task', ID=value )
    
    '''
    nim_typeID = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_typeID",
                                         nim_typeID)
    if success:
        nim.set_ID(elem='task', ID=nim_typeID.Get())
        P.error('Reading nim_typeID')
    else:
        P.error('Failed reading nim_typeID')

    #  Task Folder :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_typeFolder' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_typeFolder' )
        P.debug( 'Task Folder = %s' % value )
        nim.set_taskFolder( folder=value )
    
    '''
    nim_typeFolder = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_typeFolder",
                                         nim_typeFolder)
    if success:
        nim.set_taskFolder(folder=nim_typeFolder.Get())
        P.error('Reading nim_typeFolder')
    else:
        P.error('Failed reading nim_typeFolder')

    #  Tag :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_tag' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_tag' )
        P.debug( 'Tag = %s' % value )
        nim.set_name( elem='tag', name=value )
    
    '''
    nim_tag = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_tag", nim_tag)
    if success:
        nim.set_name(elem='tag', name=nim_tag.Get())
        P.error('Reading nim_tag')
    else:
        P.error('Failed reading nim_tag')

    #  File Type :
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_fileType' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_fileType' )
        P.debug( 'File Type = %s' % value )
        nim.set_name( elem='file', name=value )
    '''
    nim_fileType = MaxPlus.FPValue()
    success = MaxPlus.Core.EvalMAXScript("rootNodeDataCA.nim_fileType",
                                         nim_fileType)
    if success:
        nim.set_name(elem='file', name=nim_fileType.Get())
        P.error('Reading nim_fileType')
    else:
        P.error('Failed reading nim_fileType')

    #  Print dictionary :
    #P.info('\nNIM Dictionary from get vars...')
    #nim.Print()

    return
コード例 #15
0
def verUp(nim=None,
          padding=2,
          selected=False,
          win_launch=False,
          pub=False,
          symLink=True):
    'Versions up a file - Does NOT add it to the NIM API'

    #  Variables :
    cur_filePath, cur_fileDir, cur_fileName = '', '', ''
    scenePath, assetName, shotName = '', '', ''
    server, fileBase, nimDir, fileDir, ext, verNum = '', '', '', '', '', None
    renDir, compPath = '', ''

    #  Get current file information :
    if not nim:
        #  Initialize NIM dictionary :
        nim = Nim.NIM()
        nim.ingest_prefs()
        if pub: nim.set_name(elem='filter', name='Published')
        else: nim.set_name(elem='filter', name='Work')

    #P.info("SERVER ID: %s" % str(nim.server(get='ID')))
    # Get Server OS Path from server ID
    serverOsPathInfo = Api.get_serverOSPath(nim.server(get='ID'),
                                            platform.system())
    P.info("Server OS Path: %s" % serverOsPathInfo)
    serverOSPath = serverOsPathInfo[0]['serverOSPath']
    nim.set_server(path=serverOSPath)

    #  Attempt to get current file information :
    if nim.filePath():
        cur_filePath = nim.filePath()
        cur_fileDir = nim.fileDir()
        cur_fileName = nim.fileName()

    #  Basename :
    nim.set_name(elem='base', name=Api.to_basename(nim=nim))
    basename = nim.name('base')

    #  Directory to save to :
    api_fileDir = Api.to_fileDir(nim)
    if api_fileDir and not cur_fileDir:
        fileDir = api_fileDir
    elif not api_fileDir and cur_fileDir:
        fileDir = cur_fileDir
    elif api_fileDir and cur_fileDir:
        fileDir = api_fileDir

    #  Project Directory :
    if fileDir[-6:] == 'scenes': projDir = fileDir[:-6]
    else: projDir = fileDir

    #  Convert file directory :
    #P.info("fileDir: %s" % fileDir)
    fileDir = os_filePath(path=fileDir, nim=nim)
    P.info('File Directory = %s' % fileDir)
    projDir = os_filePath(path=projDir, nim=nim)
    P.info('Project Directory = %s' % projDir)

    #  Version Number :
    baseInfo = ''
    if nim.tab() == 'SHOT':
        baseInfo = Api.get_baseVer(shotID=nim.ID('shot'),
                                   basename=nim.name('base'))
    elif nim.tab() == 'ASSET':
        baseInfo = Api.get_baseVer(assetID=nim.ID('asset'),
                                   basename=nim.name('base'))
    if baseInfo:
        ver_baseInfo = baseInfo[0]['version']
        verNum = int(ver_baseInfo) + 1
    else:
        verNum = 1
    try:
        for f in [
                f for f in os.listdir(fileDir)
                if os.path.isfile(os.path.join(fileDir, f))
        ]:
            verSrch = re.search(basename + '_v[0-9]+', f)
            if verSrch:
                numSrch = re.search('[0-9]+$', verSrch.group())
                if numSrch:
                    if int(numSrch.group()) > verNum:
                        verNum = int(numSrch.group())
    except:
        pass
    nim.set_version(version=str(verNum))

    #  Set Extension :
    ext = nim.name('fileExt')
    if not ext:
        P.debug('Getting Extension')
        ext = get_ext()

    P.debug('Extension = %s' % ext)

    #  Error Checking :
    if not fileDir or not basename:
        msg='Sorry, you must either: Save the file from the NIM File GUI, or\n'+\
            '    save the file in the appropriate folders, with the correct name.\n\n'+\
            'File NOT saved.'
        P.error(msg)
        Win.popup(title='NIM - Version Up Error', msg=msg)
        return False

    #  Construct new File Name :
    if not pub:
        new_fileName = '%s_v%s%s' % (basename, str(verNum).zfill(
            int(padding)), ext)
    elif pub:
        verNum -= 1
        new_fileName = '%s_v%s_PUB%s' % (basename, str(verNum).zfill(
            int(padding)), ext)

    #  Construct new File Path :
    temp_filePath = os.path.normpath(os.path.join(fileDir, new_fileName))
    new_filePath = os_filePath(path=temp_filePath, nim=nim)

    #  Construct Render Directory :
    if nim.tab() == 'SHOT' and nim.ID('shot'):
        pathInfo = Api.get({
            'q': 'getPaths',
            'type': 'shot',
            'ID': str(nim.ID('shot'))
        })
    elif nim.tab() == 'ASSET' and nim.ID('asset'):
        pathInfo = Api.get({
            'q': 'getPaths',
            'type': 'asset',
            'ID': str(nim.ID('asset'))
        })
    if pathInfo and type(pathInfo) == type(dict()) and 'renders' in pathInfo:
        renDir = os.path.normpath(
            os.path.join(nim.server(), pathInfo['renders']))
    else:
        #  Use old method, if path information can't be derived :
        renDir = Api.to_renPath(nim)
    renDir = os_filePath(path=renDir, nim=nim)

    #  Comp Path :
    if pathInfo and type(pathInfo) == type(dict()) and 'comps' in pathInfo:
        compPath = os.path.normpath(
            os.path.join(nim.server(), pathInfo['comps']))
        nim.set_compPath(compPath=compPath)
    compPath = os_filePath(path=compPath, nim=nim)

    P.info('\nVariables:')
    P.info('  Initial File Path = %s' % cur_filePath)
    P.info('  Basename = %s' % basename)
    P.info('  Project Directory = %s' % projDir)
    P.info('  New File Path = %s' % new_filePath)
    P.info('  Render Directory = %s' % renDir)
    P.info('  Comp Directory = %s\n' % compPath)

    #  Directories :
    #===---------------

    #  Make basename directory :
    if projDir and not os.path.isdir(projDir):
        P.info('Creating basename directory within...\n    %s' % projDir)
        og_umask = os.umask(0)
        os.makedirs(projDir)
        os.umask(og_umask)
        if os.path.isdir(projDir):
            P.info('  Successfully created the basename directory!')
        else:
            P.warning('  Unable to create basename directory')

    #  Make render directory :
    if renDir and not os.path.isdir(renDir):
        P.info('Creating render directory...\n      %s' % renDir)

        og_umask = os.umask(0)
        os.makedirs(renDir)
        os.umask(og_umask)

        if os.path.isdir(renDir):
            P.info('    Successfully created the render directory!')
        else:
            P.warning('    Unable to create project directories.')
    elif renDir:
        P.debug('Render directory already exists.\n')

    #  Make Maya Project directory :
    if os.path.isdir(projDir) and nim.app() == 'Maya':
        import nim_maya as M
        if M.makeProject(projectLocation=projDir, renderPath=renDir):
            P.info('Created Maya project directorires within...\n    %s' %
                   projDir)
        else:
            P.warning('    Unable to create Maya project directories.')
    elif nim.app() == 'Maya':
        P.warning('Didn\'t create Maya project directories.')

    #  Make 3dsMax Project directory :
    if os.path.isdir(projDir) and nim.app() == '3dsMax':
        import nim_3dsmax as Max
        if Max.mk_proj(path=projDir, renPath=renDir):
            P.info('Created 3dsMax project directorires within...\n    %s' %
                   projDir)
        else:
            P.warning('    Unable to create 3dsMax project directories.')
    elif nim.app() == '3dsMax':
        P.warning('Didn\'t create 3dsMax project directories.')

    #  Make Houdini Project directory :
    if os.path.isdir(projDir) and nim.app() == 'Houdini':
        import nim_houdini as Houdini
        if Houdini.mk_proj(path=projDir, renPath=renDir):
            P.info('Created Houdini project directorires within...\n    %s' %
                   projDir)
        else:
            P.warning('    Unable to create Houdini project directories.')
    elif nim.app() == 'Houdini':
        P.warning('Didn\'t create Houdini project directories.')

    #  Save :
    #===------
    P.info('APP = %s' % nim.app())

    #  Maya :
    if nim.app() == 'Maya':
        import maya.cmds as mc

        #  Save File :
        if not selected:
            #  Set Vars :
            import nim_maya as M
            M.set_vars(nim=nim)

            P.info('Saving file as %s \n' % new_filePath)
            mc.file(rename=new_filePath)
            if ext == '.mb':
                mc.file(save=True, type='mayaBinary')
            elif ext == '.ma':
                mc.file(save=True, type='mayaAscii')
        else:
            P.info('Saving selected items as %s \n' % new_filePath)
            if ext == '.mb':
                mc.file(new_filePath, exportSelected=True, type='mayaBinary')
            elif ext == '.ma':
                mc.file(new_filePath, exportSelected=True, type='mayaAscii')

    #  Nuke :
    elif nim.app() == 'Nuke':

        import nuke

        #  Save File :
        if not selected:
            #  Set Vars :
            import nim_nuke as N
            N.set_vars(nim=nim)
            P.info('Saving file as %s \n' % new_filePath)
            nuke.scriptSaveAs(new_filePath)
        elif selected:
            P.info('Saving selected items as %s \n' % new_filePath)
            try:
                nuke.nodeCopy(new_filePath)
            except RuntimeError:
                P.info(
                    'Failed to selected items... Possibly no items selected.')
                return False

    #  Cinema 4D :
    elif nim.app() == 'C4D':
        import c4d

        #  Set Vars :
        nim_plugin_ID = 1032427

        #  Save File :
        if not selected:
            P.info('Saving file as %s \n' % new_filePath)
            import nim_c4d as C
            C.set_vars(nim=nim, ID=nim_plugin_ID)
            doc = c4d.documents.GetActiveDocument()
            doc.SetDocumentName(new_fileName)
            doc.SetDocumentPath(fileDir)
            c4d.documents.SaveDocument(doc, str(new_filePath),
                                       c4d.SAVEDOCUMENTFLAGS_DIALOGSALLOWED,
                                       c4d.FORMAT_C4DEXPORT)
            P.info('Saving File Complete')
        #  Save Selected :
        else:
            P.info('Saving selected items as %s \n' % new_filePath)
            doc = c4d.documents.GetActiveDocument()
            sel = doc.GetActiveObjects(False)
            baseDoc = c4d.documents.IsolateObjects(doc, sel)
            c4d.documents.SaveDocument(baseDoc, str(new_filePath),
                                       c4d.SAVEDOCUMENTFLAGS_DIALOGSALLOWED,
                                       c4d.FORMAT_C4DEXPORT)

    #  Hiero :
    elif nim.app() == 'Hiero':
        import hiero.core
        projects = hiero.core.projects()
        proj = projects[0]
        curFilePath = proj.path()
        proj.saveAs(new_filePath)
        #proj=hiero.core.project( projName )
        #proj=hiero.core.Project
        #proj=self._get_current_project()

    #  3dsMax :
    if nim.app() == '3dsMax':
        import MaxPlus
        maxFM = MaxPlus.FileManager
        #  Save File :
        if not selected:
            #  Set Vars :
            import nim_3dsmax as Max
            Max.set_vars(nim=nim)
            #Save File
            P.info('Saving file as %s \n' % new_filePath)
            maxFM.Save(new_filePath)
        else:
            #Save Selected Items
            P.info('Saving selected items as %s \n' % new_filePath)
            maxFM.SaveSelected(new_filePath)

    #  Houdini :
    if nim.app() == 'Houdini':
        import hou
        #  Save File :
        if not selected:
            #  Set Vars :
            import nim_houdini as Houdini
            Houdini.set_vars(nim=nim)

            #Save File
            if _os.lower() in ['windows', 'win32']:
                new_filePath = new_filePath.replace('\\', '/')

            P.info('Saving file as %s \n' % new_filePath)
            try:
                hou.hipFile.save(file_name=str(new_filePath))
                P.info('Houdini successfully save the file.')
            except hou.OperationFailed:
                P.info('Houdini failed to save the file.')
                P.info(hou.OperationFailed.description())

            #Set $HIP var to location of current file
            if _os.lower() in ['windows', 'win32']:
                projDir = projDir.replace('\\', '/')

            hou.hscript("set -g HIP = '" + str(projDir) + "'")

            #Set $HIPNAME var to current file
            hipName = os.path.splitext(new_fileName)[0]
            hou.hscript("set -g HIPNAME = '" + str(hipName) + "'")

        else:
            #Save Selected Items
            if _os.lower() in ['windows', 'win32']:
                new_filePath = new_filePath.replace('\\', '/')
            P.info('Saving selected items as %s \n' % new_filePath)

            try:
                tmp_filePath = new_filePath + "." + time.strftime(
                    '%Y%m%d_%H%M%S') + ".tmp"
                parentNode = "hou.node('/obj/')"
                selected = hou.selectedNodes()
                selectedParent = selected[0].parent()
                selectedParent.saveItemsToFile(selected,
                                               file_name=str(tmp_filePath))
                P.info('Houdini saved items to file.')
            except hou.OperationFailed:
                P.info('Houdini failed to save selected items to file.')
                P.info(hou.OperationFailed.description())

            saveCode = '"' + "import os, time; newParent = " + parentNode + "; newParent.loadChildrenFromFile('" + tmp_filePath + "'); hou.hipFile.save('" + new_filePath + "')" + '"'
            pyCmd = os.environ["HFS"] + '/bin/hython -c ' + saveCode

            try:
                os.system(pyCmd)
            except:
                P.info('Failed to run hython for external Houini save.')

            try:
                os.remove(tmp_filePath)
            except OSError:
                pass

    #  Make a copy of the file, if publishing :
    if pub and not symLink:
        pub_fileName = basename + ext
        pub_fileDir = Api.to_nimDir(nim=nim)
        pub_filePath = os.path.join(pub_fileDir, pub_fileName)
        #  Delete any pre-existing published file :
        if os.path.isfile(pub_filePath):
            os.chmod(pub_filePath, stat.S_IWRITE)
            os.remove(pub_filePath)
        #  Copy file and make it read-only :
        shutil.copyfile(new_filePath, pub_filePath)
        os.chmod(pub_filePath, stat.S_IREAD)

    #  Print save success :
    P.info('\nFile successfully saved to...\n    %s\n' % new_filePath)

    #  [AS]  returning nim object with current dictionary settings
    #return new_filePath
    return {'filepath': new_filePath, 'nim': nim}
コード例 #16
0
ファイル: nim_win.py プロジェクト: rohtau/nim_connectors
def setApiKey( url='' ) :
    'Sets the NIM user API Key'
    #print('setApiKey::')
    nim_apiKey = ''
    
    connect_info = Api.get_connect_info()
    api_url = connect_info['nim_apiURL']
    api_user = connect_info['nim_apiUser']

    app=F.get_app()

    isGUI = False
    try :
        #Validate Against DCC Environment
        if F.get_app() is not None :
            isGUI = True
    except :
        pass

    if isGUI :
        if app == 'C4D' :
            api_key=popup( title='Enter NIM API Key', msg='Enter the NIM API Key for your user:'******'input', defaultInput='' )
        else :
            api_key=popup( title='Enter NIM API Key', msg='Failed to validate user.\n\n \
                            NIM Security is set to require the use of API Keys.\n \
                            Please obtain a valid NIM API KEY from your NIM Administrator.\n\n \
                            Enter the NIM API Key for your user:'******'input', defaultInput='' )
    else :
        print('Failed to validate user.\n \
                NIM Security is set to require the use of API Keys.\n \
                Please obtain a valid NIM API KEY from your NIM Administrator.')
        api_key=raw_input('Enter the NIM API Key for your user: '******'Cancel' :
        return False
    else :
        #  Get user ID :
        if api_url :
            testAPI = Api.testAPI(nimURL=api_url, nim_apiUser=api_user, nim_apiKey=api_key)
            if type(testAPI[0])==type(dict()) :
                if testAPI[0]['error'] != '':
                    P.error( testAPI[0]['error'] )
                    if isGUI :
                        response = popup( title='NIM API Invalid', msg='The NIM API Key entered is invalid.\n\nRe-enter API Key?', type='okCancel')
                    else :
                        print('The NIM API Key entered is invalid.')
                        response=raw_input('Re-enter API Key? (Y/N): ')
                        if response == 'Y' or response == 'y' :
                            response = 'OK'

                    if(response=='OK'):
                        setApiKey( url=url )
                    else :
                        return False
                else :
                    #  Update NIM Key File :
                    print "Key Valid: %s" % testAPI[0]['keyValid']
                    if testAPI[0]['keyValid'] == 'true' :
                        try :
                            keyFile = os.path.normpath( os.path.join( Prefs.get_home(), 'nim.key' ) )
                            print keyFile
                            ''' #Python 2.7
                            with open(keyFile, 'r+') as f:
                                f.seek(0)
                                f.write(api_key)
                                f.truncate()
                            '''
                            # Using Python2.6 for compatibiity
                            keyFO = open(keyFile, "w")
                            keyFO.seek(0)
                            keyFO.write(api_key)
                            keyFO.truncate()
                            keyFO.close()
                            if isGUI :
                                popup( title='NIM API Key Set', msg='The NIM API Key has been set.\n\nPlease retry your last command.')
                            else :
                                print('The NIM API Key has been set.\nPlease retry your last command.')
                            return True
                        except :
                            P.error('Failed writing NIM Key file.')
                            P.error( '    %s' % traceback.print_exc() )
                            if isGUI :
                                popup(title='Error', msg='Failed writing NIM Key File.')
                            else :
                                print('Failed writing NIM Key File.')
                            return False
                    else :
                        P.error( 'Failed to validate NIM API.' )
                        if isGUI :
                            response = popup( title='NIM API Invalid', msg='The NIM API Key entered is invalid.\n\nRe-enter API Key?', type='okCancel')
                        else :
                            print('The NIM API Key entered is invalid.')
                            response=raw_input('Re-enter API Key? (Y/N): ')
                            if response == 'Y' or response == 'y' :
                                response = 'OK'

                        if(response=='OK'):
                            setApiKey( url=url )
                        else :
                            return False
            else :
                P.error( 'Failed to validate NIM API.' )
                if isGUI :
                    response = popup( title='NIM API Invalid', msg='The NIM API Key entered is invalid.\n\nRe-enter API Key?', type='okCancel')
                else :
                    print('The NIM API Key entered is invalid.')
                    response=raw_input('Re-enter API Key? (Y/N): ')
                    if response == 'Y' or response == 'y' :
                        response = 'OK'

                if(response=='OK'):
                    setApiKey( url=url )
                else :
                    return False
        else :
            return None
コード例 #17
0
ファイル: nim_houdini.py プロジェクト: rohtau/nim_connectors
def get_vars(nim=None):
    'Gets NIM settings from the root node in Houdini.'
    P.info('Getting information from NIM attributes on the root node...')

    h_root = hou.node("/")

    #  User :
    nim_user = h_root.userData("nim_user")
    if nim_user is not None:
        nim.set_user(userName=nim_user)
        P.info('Reading userName')
    else:
        P.error('Failed reading userName')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_user' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_user' )
        P.debug( 'User = %s' % value )
        nim.set_user( userName=value )
    '''

    #  User ID :
    nim_userID = h_root.userData("nim_userID")
    if nim_userID is not None:
        nim.set_userID(userID=nim_userID)
        P.info('Reading userID')
    else:
        P.error('Failed reading userID')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_userID' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_userID' )
        P.debug( 'User ID = %s' % value )
        nim.set_userID( userID=value )
    '''

    #  Tab/Class :
    nim_class = h_root.userData("nim_class")
    if nim_class is not None:
        nim.set_tab(nim_class)
        P.info('Reading nim_class')
    else:
        P.error('Failed reading nim_class')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_class' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_class' )
        P.debug( 'Tab = %s' % value )
        nim.set_tab( value )
    '''

    #  Server :
    nim_server = h_root.userData("nim_server")
    if nim_server is not None:
        nim.set_server(path=nim_server)
        P.info('Reading nim_server')
    else:
        P.error('Failed reading nim_server')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_server' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_server' )
        P.debug( 'Server = %s' % value )
        nim.set_server( path=value )
    '''

    #  Server ID :
    nim_serverID = h_root.userData("nim_serverID")
    if nim_serverID is not None:
        nim.set_ID(elem='server', ID=nim_serverID)
        P.info('Reading nim_serverID')
    else:
        P.error('Failed reading nim_serverID')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_serverID' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_serverID' )
        P.debug( 'Server ID = %s' % value )
        nim.set_ID( elem='server', ID=value )
    '''

    #  Job :
    nim_jobName = h_root.userData("nim_jobName")
    if nim_jobName is not None:
        nim.set_name(elem='job', name=nim_jobName)
        P.info('Reading nim_jobName')
    else:
        P.error('Failed reading nim_jobName')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_jobName' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_jobName' )
        P.debug( 'Job = %s' % value )
        nim.set_name( elem='job', name=value )
    '''

    #  Job ID :
    nim_jobID = h_root.userData("nim_jobID")
    if nim_jobID is not None:
        nim.set_ID(elem='job', ID=nim_jobID)
        P.info('Reading nim_jobID')
    else:
        P.error('Failed reading nim_jobID')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_jobID' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_jobID' )
        P.debug( 'Job ID = %s' % value )
        nim.set_ID( elem='job', ID=value )
    '''

    #  Show :
    nim_showName = h_root.userData("nim_showName")
    if nim_showName is not None:
        nim.set_name(elem='show', name=nim_showName)
        P.info('Reading nim_showName')
    else:
        P.error('Failed reading nim_showName')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_showName' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_showName' )
        P.debug( 'Show = %s' % value )
        nim.set_name( elem='show', name=value )
    '''

    #  Show ID :
    nim_showID = h_root.userData("nim_showID")
    if nim_showID is not None:
        nim.set_ID(elem='show', ID=nim_showID)
        P.info('Reading nim_showID')
    else:
        P.error('Failed reading nim_showID')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_showID' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_showID' )
        P.debug( 'Show ID = %s' % value )
        nim.set_ID( elem='show', ID=value )
    '''

    #  Shot :
    nim_shot = h_root.userData("nim_shot")
    if nim_shot is not None:
        nim.set_name(elem='shot', name=nim_shot)
        P.info('Reading nim_shot')
    else:
        P.error('Failed reading nim_shot')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_shot' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_shot' )
        P.debug( 'Shot = %s' % value )
        nim.set_name( elem='shot', name=value )
    '''

    #  Shot ID :
    nim_shotID = h_root.userData("nim_shotID")
    if nim_shotID is not None:
        nim.set_ID(elem='shot', ID=nim_shotID)
        P.info('Reading nim_shotID')
    else:
        P.error('Failed reading nim_shotID')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_shotID' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_shotID' )
        P.debug( 'Shot ID = %s' % value )
        nim.set_ID( elem='shot', ID=value )
    '''

    #  Asset :
    nim_asset = h_root.userData("nim_asset")
    if nim_asset is not None:
        nim.set_name(elem='asset', name=nim_asset)
        P.info('Reading nim_asset')
    else:
        P.error('Failed reading nim_asset')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_asset' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_asset' )
        P.debug( 'Asset = %s' % value )
        nim.set_name( elem='asset', name=value )
    '''

    #  Asset ID :
    nim_assetID = h_root.userData("nim_assetID")
    if nim_assetID is not None:
        nim.set_ID(elem='asset', ID=nim_assetID)
        P.info('Reading nim_assetID')
    else:
        P.error('Failed reading nim_assetID')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_assetID' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_assetID' )
        P.debug( 'Asset ID = %s' % value )
        nim.set_ID( elem='asset', ID=value )
    '''

    #  File ID :
    '''
    if mc.attributeQuery( 'defaultRenderGlobals.nim_fileID' ) :
        value=mc.attributeQuery( 'nim_fileID', node='defaultRenderGlobals' )
        P.debug( 'Class = %s' % value )
        nim.set_tab( tab=value )
    '''
    #TODO: Check if Maya code is error or intentional

    #  Shot/Asset Name :
    nim_name = h_root.userData("nim_name")
    if nim_name is not None:
        if nim.tab() == 'SHOT':
            P.debug('Shot Name = %s' % nim_name)
            #nim.set_tab( nim_name.Get() )
        elif nim.tab() == 'ASSET':
            P.debug('Asset Name = %s' % nim_name)
            #nim.set_tab( nim_name.Get() )
    else:
        P.error('Failed reading nim_name')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_name' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_name' )
        #  Determine what the tab is set to :
        if nim.tab()=='SHOT' :
            P.debug( 'Shot Name = %s' % value )
            #  No corresponding NIM attribute :
            #nim.set_tab( value )
        elif nim.tab()=='ASSET' :
            P.debug( 'Asset Name = %s' % value )
            #  No corresponding NIM attribute :
            #nim.set_tab( value )
    '''

    #  Basename :
    nim_basename = h_root.userData("nim_basename")
    if nim_basename is not None:
        nim.set_name(elem='base', name=nim_basename)
        P.info('Reading nim_basename')
    else:
        P.error('Failed reading nim_basename')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_basename' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_basename' )
        P.debug( 'Basename = %s' % value )
        nim.set_name( elem='base', name=value )
    
    '''

    #  Task :
    nim_type = h_root.userData("nim_type")
    if nim_type is not None:
        nim.set_name(elem='task', name=nim_type)
        P.info('Reading nim_type')
    else:
        P.error('Failed reading nim_type')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_type' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_type' )
        P.debug( 'Task = %s' % value )
        nim.set_name( elem='task', name=value )
    
    '''

    #  Task ID :
    nim_typeID = h_root.userData("nim_typeID")
    if nim_typeID is not None:
        nim.set_ID(elem='task', ID=nim_typeID)
        P.info('Reading nim_typeID')
    else:
        P.error('Failed reading nim_typeID')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_typeID' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_typeID' )
        P.debug( 'Task ID = %s' % value )
        nim.set_ID( elem='task', ID=value )
    
    '''

    #  Task Folder :
    nim_typeFolder = h_root.userData("nim_typeFolder")
    if nim_typeFolder is not None:
        nim.set_taskFolder(folder=nim_typeFolder)
        P.info('Reading nim_typeFolder')
    else:
        P.error('Failed reading nim_typeFolder')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_typeFolder' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_typeFolder' )
        P.debug( 'Task Folder = %s' % value )
        nim.set_taskFolder( folder=value )
    
    '''

    #  Tag :
    nim_tag = h_root.userData("nim_tag")
    if nim_tag is not None:
        nim.set_name(elem='tag', name=nim_tag)
        P.info('Reading nim_tag')
    else:
        P.error('Failed reading nim_tag')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_tag' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_tag' )
        P.debug( 'Tag = %s' % value )
        nim.set_name( elem='tag', name=value )
    
    '''

    #  File Type :
    nim_fileType = h_root.userData("nim_fileType")
    if nim_fileType is not None:
        nim.set_name(elem='file', name=nim_fileType)
        P.info('Reading nim_fileType')
    else:
        P.error('Failed reading nim_fileType')
    '''
    if mc.objExists( 'defaultRenderGlobals.nim_fileType' ) :
        value=mc.getAttr( 'defaultRenderGlobals.nim_fileType' )
        P.debug( 'File Type = %s' % value )
        nim.set_name( elem='file', name=value )
    '''

    #  Print dictionary :
    #P.info('\nNIM Dictionary from get vars...')
    #nim.Print()

    return
コード例 #18
0
ファイル: nim.py プロジェクト: rohtau/nim_connectors
    def set_dict(self, elem='job', pub=False):
        'Sets the dictionary for a given element'
        #print "set_dict: %s" % elem
        dic = {}

        if elem == 'job':
            #  Only update Job if the dictionary hasn't been set yet :
            if not self.nim[elem]['Dict'] or not len(self.nim[elem]['Dict']):
                self.nim[elem]['Dict'] = Api.get_jobs(
                    userID=self.nim['user']['ID'])
                if self.nim[elem]['Dict'] == False:
                    P.error("Failed to Set NIM Dictionary")
                    return False
        elif elem == 'asset':
            if self.nim['job']['ID']:
                self.nim[elem]['Dict'] = Api.get_assets(self.nim['job']['ID'])
        elif elem == 'show':
            if self.nim['job']['ID']:
                self.nim[elem]['Dict'] = Api.get_shows(self.nim['job']['ID'])
        elif elem == 'shot':
            if self.nim['show']['ID']:
                self.nim[elem]['Dict'] = Api.get_shots(self.nim['show']['ID'])
        elif elem == 'filter':
            if self.nim['mode'] and self.nim['mode'].lower() in [
                    'load', 'open', 'file'
            ]:
                if self.nim['class'] == 'SHOT':
                    if self.nim['shot']['name']:
                        self.nim[elem]['Dict'] = ['Published', 'Work']
                elif self.nim['class'] == 'ASSET':
                    if self.nim['asset']['name']:
                        if self.nim['mode'].lower() not in ['file', 'open']:
                            self.nim[elem]['Dict'] = [
                                'Asset Master', 'Published', 'Work'
                            ]
                        else:
                            self.nim[elem]['Dict'] = ['Published', 'Work']
            else:
                self.nim[elem]['Dict'] = ['Work']

        elif elem == 'task':
            #REMOVED AS REDUNDANT
            #if self.nim['mode'] and self.nim['mode'].lower() in ['load', 'open', 'file'] :

            # WAS INSIDE IF
            if self.nim['filter']['name'] not in [
                    'Select...', 'None', ''
            ] and self.nim['filter']['name'] != 'Asset Master':

                #NOT INCLUDING CLASS WHEN LOADING TASKS
                #self.nim[elem]['Dict']=Api.get( {'q': 'getTaskTypes', 'app': self.nim['app'].upper()} )

                #print "Loading %s tasks" % self.nim['class']

                if self.nim['class'] == 'SHOT':
                    if self.nim['shot']['name'] not in [
                            'Select...', 'None', ''
                    ]:
                        #self.nim[elem]['Dict']=Api.get( {'q': 'getTaskTypes', 'app': self.nim['app'].upper()} )
                        self.nim[elem]['Dict'] = Api.get_tasks(
                            app=self.nim['app'].upper(),
                            shotID=self.nim['shot']['ID'])
                elif self.nim['class'] == 'ASSET':
                    if self.nim['asset']['name'] not in [
                            'Select...', 'None', ''
                    ]:
                        #self.nim[elem]['Dict']=Api.get( {'q': 'getTaskTypes', 'app': self.nim['app'].upper()} )
                        self.nim[elem]['Dict'] = Api.get_tasks(
                            app=self.nim['app'].upper(),
                            assetID=self.nim['asset']['ID'])

            elif self.nim['filter']['name'] == 'Asset Master':
                self.nim[elem]['Dict'] = {}

            # REMOVED AS REDUNDANT
            #else :
            #    if self.nim['class']=='SHOT' :
            #        if self.nim['shot']['name'] not in ['Select...', 'None', ''] :
            #            #self.nim[elem]['Dict']=Api.get( {'q': 'getTaskTypes', 'app': self.nim['app'].upper()} )
            #            self.nim[elem]['Dict']=Api.get_tasks(app=self.nim['app'].upper(), shotID=self.nim['shot']['ID'])
            #    elif self.nim['class']=='ASSET' :
            #        if self.nim['asset']['name'] not in ['Select...', 'None', ''] :
            #            #self.nim[elem]['Dict']=Api.get( {'q': 'getTaskTypes', 'app': self.nim['app'].upper()} )
            #            self.nim[elem]['Dict']=Api.get_tasks(app=self.nim['app'].upper(), assetID=self.nim['asset']['ID'])

        elif elem == 'base':
            if self.nim['filter']['name'] == 'Published':
                if self.nim['class'] == 'SHOT' and self.nim['task']['name']:
                    self.nim[elem]['Dict'] = Api.get_basesAllPub(
                        shotID=self.nim['shot']['ID'],
                        taskID=self.nim['task']['ID'],
                        username=self.userInfo()['name'])
                elif self.nim['class'] == 'ASSET' and self.nim['task']['name']:
                    self.nim[elem]['Dict'] = Api.get_basesAllPub(
                        assetID=self.nim['asset']['ID'],
                        taskID=self.nim['task']['ID'],
                        username=self.userInfo()['name'])
            else:
                if self.nim['class'] == 'SHOT' and self.nim['task']['name']:
                    self.nim[elem]['Dict'] = Api.get_bases(
                        shotID=self.nim['shot']['ID'],
                        taskID=self.nim['task']['ID'])
                elif self.nim['class'] == 'ASSET' and self.nim['task']['name']:
                    self.nim[elem]['Dict'] = Api.get_bases(
                        assetID=self.nim['asset']['ID'],
                        taskID=self.nim['task']['ID'])
        elif elem == 'ver':
            if self.nim['filter']['name'] == 'Published':
                if self.nim['mode'] and self.nim['mode'].lower() == 'load':
                    if self.nim['class'] == 'SHOT' and self.nim['base']['name']:
                        self.nim[elem]['Dict'] = Api.get_basesPub(
                            shotID=self.nim['shot']['ID'],
                            basename=self.nim['base']['name'],
                            username=self.userInfo()['name'])
                    elif self.nim['class'] == 'ASSET' and self.nim['base'][
                            'name']:
                        self.nim[elem]['Dict'] = Api.get_basesPub(
                            assetID=self.nim['asset']['ID'],
                            basename=self.nim['base']['name'],
                            username=self.userInfo()['name'])
                elif self.nim['mode'] and self.nim['mode'].lower() in [
                        'open', 'file'
                ]:
                    if self.nim['class'] == 'SHOT' and self.nim['base']['name']:
                        self.nim[elem]['Dict'] = Api.get_vers(
                            shotID=self.nim['shot']['ID'],
                            basename=self.nim['base']['name'],
                            pub=True,
                            username=self.userInfo()['name'])
                    elif self.nim['class'] == 'ASSET' and self.nim['base'][
                            'name']:
                        self.nim[elem]['Dict'] = Api.get_vers(
                            assetID=self.nim['asset']['ID'],
                            basename=self.nim['base']['name'],
                            pub=True,
                            username=self.userInfo()['name'])
            elif self.nim['filter']['name'] == 'Asset Master':
                assetInfo = Api.get_assetInfo(assetID=self.ID('asset'))
                amrPath = os.path.normpath(assetInfo[0]['AMR_path'])
                fileName = assetInfo[0]['AMR_filename']
                fileDir = os.path.normpath(
                    os.path.join(self.server(get='path'), amrPath))
                filePath = os.path.normpath(os.path.join(fileDir, fileName))
                self.nim[elem]['Dict'] = [{
                    'username': '',
                    'filepath': fileDir,
                    'userID': '',
                    'filename': fileName,
                    'basename': '',
                    'ext': '',
                    'version': '',
                    'date': '',
                    'note': '',
                    'serverID': '',
                    'fileID': ''
                }]
            else:
                if self.nim['class'] == 'SHOT' and self.nim['base']['name']:
                    self.nim[elem]['Dict'] = Api.get_vers(
                        shotID=self.nim['shot']['ID'],
                        basename=self.nim['base']['name'],
                        username=self.userInfo()['name'])
                elif self.nim['class'] == 'ASSET' and self.nim['base']['name']:
                    self.nim[elem]['Dict'] = Api.get_vers(
                        assetID=self.nim['asset']['ID'],
                        basename=self.nim['base']['name'],
                        username=self.userInfo()['name'])

        return