def act_project_create(self): ''' Create a Modo project at the destination specified by the user via File Dialog. ''' # create the project with the standard template try: lx.eval('?projdir.instantiate') folderPicked = True except: folderPicked = False if folderPicked: # get the path we just set platform = lx.service.Platform() for idx in range(platform.PathCount()): if platform.PathNameByIndex(idx) == "project": folder = platform.PathByIndex(idx) # update the project list file self.write_projectListFile(folder) # update the project list in the UI self.projects_getExisting() # log and inform lx.out('PROJECT MANAGER: A new project was created: %s' %folder) self.dialog_info('Project Manager', "Project '%s' was created!" %os.path.basename(folder))
def commander_execute(self, msg, flags): for hotkey in HOTKEYS: key = hotkey["key"] for context_list in hotkey["contexts"]: mapping = context_list[0] state = context_list[1] region = context_list[2] context = context_list[3] default = context_list[4] if default is None: try: lx.eval('!cmds.clearKey {%s} {%s} {%s} {%s} {%s}' % (key, mapping, state, region, context)) except: lx.out("Could not clear mapping for '%s'." % key) else: try: lx.eval( '!cmds.mapKey {%s} {%s} {%s} {%s} {%s} {%s}' % (key, default, mapping, state, region, context)) except: lx.out("Could not set '%s' to '%s'." % (default, key)) modo.dialogs.alert( "Reverted TabbyCat Hotkeys", "Reverted %s TabbyCat hotkeys to defaults." % len(HOTKEYS))
def mesh_edit(self, read_only=False): """Adapted from James O'Hare's excellent code: https://gist.github.com/Farfarer/31148a78f392a831239d9b018b90330c""" if read_only: scan_allocate = lx.symbol.f_LAYERSCAN_ACTIVE | lx.symbol.f_LAYERSCAN_MARKPOLYS if not read_only: scan_allocate = lx.symbol.f_LAYERSCAN_EDIT layer_svc = lx.service.Layer() layer_scan = lx.object.LayerScan(layer_svc.ScanAllocate(scan_allocate)) self.mesh_svc = lx.service.Mesh() if not layer_scan.test(): return for n in xrange(layer_scan.Count()): if read_only: self.mesh = lx.object.Mesh(layer_scan.MeshBase(n)) if not read_only: self.mesh = lx.object.Mesh(layer_scan.MeshEdit(n)) if not self.mesh.test(): continue polygon_count = self.mesh.PolygonCount() if polygon_count == 0: continue self.polygon_accessor = lx.object.Polygon( self.mesh.PolygonAccessor()) if not self.polygon_accessor.test(): continue self.edge_accessor = lx.object.Edge(self.mesh.EdgeAccessor()) if not self.edge_accessor.test(): continue self.point_accessor = lx.object.Point(self.mesh.PointAccessor()) if not self.point_accessor.test(): continue self.meshmap_accessor = lx.object.MeshMap( self.mesh.MeshMapAccessor()) if not self.meshmap_accessor.test(): continue try: if read_only: self.mesh_read_action() if not read_only: self.mesh_edit_action() except: lx.out(traceback.print_exc()) break if self.mesh_edit_flags and not read_only: layer_scan.SetMeshChange(n, reduce(ior, self.mesh_edit_flags)) layer_scan.Apply()
def getPlanarPolys(poly_indices,threshold): poly_areas = [] poly_normals = [] for poly in poly_indices: poly_verts_pos = [] poly_normal = lx.eval("query layerservice poly.normal ? " + str(poly)) poly_normals.append(poly_normal) poly_verts = lx.eval("query layerservice poly.vertList ? " + str(poly)) for vert in poly_verts: poly_verts_pos.append(lx.eval("query layerservice vert.pos ? " + str(vert))) try: poly_areas.append(modomath.area3D_Polygon(poly_verts_pos, poly_normal)) except: lx.out("Bad polygon detected") lx.out("Polygon index: " + poly) poly_areas.append(0) planar_normals_set = [poly_normals[0]] planar_poly_set = [[poly_indices[0]]] planar_area_set = [poly_areas[0]] for x in (range(1,len(poly_indices))): new_poly = True for y in (range(len(planar_normals_set))): # lx.out(str(planar_normals_set[y]) + " " + str(poly_indices[x]) + " " + str(math.degrees(vecAngle(poly_normals[x],planar_normals_set[y])))) if modomath.vecAngle(poly_normals[x],planar_normals_set[y]) < threshold: planar_poly_set[y].append(poly_indices[x]) planar_area_set[y] = planar_area_set[y] + poly_areas[x] new_poly = False break if new_poly: planar_poly_set.append ([poly_indices[x]]) planar_normals_set.append(poly_normals[x]) planar_area_set.append (poly_areas[x]) return planar_poly_set, planar_normals_set, planar_area_set
def animationExtract(startLine, endLine, keyarray, valuearray): global content ''' Expecting a structure in content list like : Channel 0 { Envelope 2 Key -2 0 0 0 0 0 0 0 0 Key -4 0.033333333333333332871 0 0 0 0 -1.9834710743801653443 0 0 Behaviors 1 1 } startLine should be { Envelope endLine should be } ''' if (content[startLine] != '{ Envelope'): reportError('Start line not matched') if (content[endLine] != '}'): reportError('End line not matched') numberOfKeys = int(content[startLine + 1]) lx.out('Found %d keys' % numberOfKeys) lineCounter = startLine + 2 for i in range(numberOfKeys): tempLine = content[lineCounter] if(tempLine.startswith(' Key')): lineArray = content[lineCounter].split(' ') keyarray.append(lineArray[4]) valuearray.append(lineArray[3]) lx.out('Key %d : %s at time %s' % (i, lineArray[3], lineArray[4])) else: reportError('Key line not found') lineCounter += 1
def ui_buildFileTypeFilterMenu(self): ''' Build and display the filetype filters menu. This menu will stay open until you click off of it. ''' # create a new menu self.ui.filtersMenu = QMenu() # inherit the stylesheet from main ui self.ui.filtersMenu.setStyleSheet(self.styleSheet()) # set up the menu's event filter and action self.ui.evFilter = StickyMenu() self.ui.filtersMenu.installEventFilter(self.ui.evFilter) self.ui.filtersMenu.aboutToHide.connect(self.ui_closeFileTypeFilterMenu) # load prevous selection if possible data = False if os.path.exists(FILTERSPATH): try: data = pickle.load(open(FILTERSPATH, 'r')) except IOError: lx.out('PROJECT MANAGER: Unable to apply previous filters. Data incorrectly serialized.') # populate the list of filetype options fileTypes = self.ui_getFileTypes() for i in sorted(fileTypes): action = self.ui.filtersMenu.addAction(i) action.setCheckable(True) if data: if i in data: action.setChecked(True) # apply the menu to the button self.ui.filtersBtn.setMenu(self.ui.filtersMenu)
def getItemTags(item_type='all', selection=None): '''Find item tags in scene created from the MARI Tool Kit. Default: all items are searched. A selection can also be given Returns {item.id{tagType:tag,}}''' # {item.id:{ENTITY:name,UDIM:1001,CHANNEL:diffuse}} data = {} if selection: lx.out('selection: ',selection) if isinstance(selection, str) == True: selection = [selection] for i in selection: sceneservice.select('item.id', str(i)) itemID = sceneservice.query('item.id') try: itemTagTypes = sceneservice.queryN('item.tagTypes') itemTags = sceneservice.queryN('item.tags') if '$MTK' in itemTagTypes: data[itemID] = dict(zip(itemTagTypes, itemTags)) except: pass else: sceneservice.select('item.N', 'all') item_num = sceneservice.query('item.N') for item in xrange(item_num): sceneservice.select('item.id', str(item)) itemID = sceneservice.query('item.id') if sceneservice.query('item.type') == item_type or item_type == 'all': try: itemTagTypes = sceneservice.queryN('item.tagTypes') itemTags = sceneservice.queryN('item.tags') if '$MTK' in itemTagTypes: data[itemID] = dict(zip(itemTagTypes, itemTags)) except: pass return data
def restoreSelection(listSelections): """ Used together with: global save_selection save_selection = lx.evalN("query sceneservice selection ? all") to save and later restore a selection in modo with bd_utils.restoreSelection(save_selection) """ try: # lx.out(listSelections) first = True for x in listSelections: lx.out("Restoring Selection: " + x) if first: lx.eval("select.item {%s} set" % x) else: lx.eval("select.item {%s} add" % x) first = False except: lx.eval('layout.createOrClose EventLog "Event Log_layout" ' 'title:@macros.layouts@EventLog@ width:600 height:600 persistent:true ' 'open:true') lx.out("ERROR restoreSelection failed with ", sys.exc_info()) return None
def restoreSelection(listSelections): """ Used together with: global save_selection save_selection = lx.evalN("query sceneservice selection ? all") to save and later restore a selection in modo with bd_helpers.restoreSelection(save_selection) """ try: # lx.out(listSelections) first = True for x in listSelections: if first: lx.eval("select.item {%s} set" % x) else: lx.eval("select.item {%s} add" % x) first = False print('Restored selection!') except: lx.eval( 'layout.createOrClose EventLog "Event Log_layout" ' 'title:@macros.layouts@EventLog@ width:600 height:600 persistent:true ' 'open:true') lx.out("ERROR restoreSelection failed with ", sys.exc_info()) return None
def basic_Execute(self, msg, flags): try: scn = modo.Scene() currScn = modo.scene.current() userSelection = scn.selected userSelectionCount = len(userSelection) currPath = currScn.filename if currPath is None: currPath = "" fbxExportType = lx.eval1('user.value sceneio.fbx.save.exportType ?') fbxTriangulate = False scnIndex = lx.eval('query sceneservice scene.index ? current') upAxis = lx.eval('pref.value units.upAxis ?') iUpAxis = upAxis userValues = self.query_User_Values() tbe = TilaBacthExport tbe.process_items(tbe(userSelection, userSelectionCount, scn, currScn, currPath, scnIndex, upAxis, iUpAxis, fbxExportType, fbxTriangulate, self.dyna_Bool(0), self.dyna_Bool(1), bool(userValues[2]), bool(userValues[3]), bool(userValues[4]), bool(userValues[5]), bool(userValues[6]), bool(userValues[7]), bool(userValues[8]), bool(userValues[9]), bool(userValues[10]), bool(userValues[11]), bool(userValues[12]), bool(userValues[13]), bool(userValues[14]), userValues[15], userValues[16], userValues[17], userValues[18], userValues[19], userValues[20], userValues[21], userValues[22], userValues[23], bool(userValues[24]), userValues[25], bool(userValues[26]), userValues[27], bool(userValues[28]), bool(userValues[29]), bool(userValues[30]), bool(userValues[31]), bool(userValues[32]), bool(userValues[33]), bool(userValues[34]), bool(userValues[35]), bool(userValues[36]), bool(userValues[37]), bool(userValues[38]), userValues[39], bool(userValues[40]), bool(userValues[41]), userValues[42])) except: lx.out(traceback.format_exc())
def register_plugins(): # Register accompanying plugins package_path = os.path.dirname(pyblish_modo.__file__) plugin_path = os.path.join(package_path, 'plugins') pyblish.api.register_plugin_path(plugin_path) lx.out("Registered %s" % plugin_path)
def basic_Execute(self, msg, flags): try: if self.scn != modo.Scene(): self.scn = modo.Scene() if self.dyna_IsSet(0): self.morphTarget = self.dyna_String(0) if self.dyna_IsSet(1): self.morphAmount = self.dyna_Float(1) self.initialSelection = self.scn.selectedByType('mesh') if len(self.initialSelection)<1: result = self.init_message('yesNo','No mesh selected', 'No mesh selected. \n Do you want to proceed to all mesh items in the scene ?') if result: self.initialSelection = self.scn.items('mesh') else: self.init_message('info', 'Aborded', 'Operation aborded by the user') return self.morphMapName = self.getSelectedMorphMap() if self.morphMapName is None: self.printLog('No morphMap selected') self.init_message('info', 'No Morph Map selected', 'Select one morph map') return self.applyMorphMap(self.morphMapName) except: lx.out(traceback.format_exc())
def basic_Execute(self, msg, flags): reload(t) reload(batch_export) try: scn = modo.Scene() currScn = modo.scene.current() userSelection = scn.selected userSelectionCount = len(userSelection) currPath = currScn.filename if currPath is None: currPath = "" scnIndex = lx.eval('query sceneservice scene.index ? current') userValues = user_value.query_User_Values(self, t.kit_prefix) tbe = batch_export.TilaBacthExport userValues[1] = True if userValues[3]: tbe.batch_folder( tbe(userSelection, userSelectionCount, scn, currScn, currPath, scnIndex, userValues)) elif userValues[2]: tbe.batch_files( tbe(userSelection, userSelectionCount, scn, currScn, currPath, scnIndex, userValues)) except: lx.out(traceback.format_exc())
def basic_Execute(self, msg, flags): try: compatible_selection = self.get_compatible_type(self.scn.selected) if not len(compatible_selection): # Is any RenderPassGroup selected message = 'please select at least one item of type :' for c in compatible_type.itervalues(): message += '\n{}'.format(c) modo.dialogs.alert('No compatible item selected', message) sys.exit() else: # Loop over all selected RenderPassGroup for grp in compatible_selection: if grp.type == compatible_type['RENDER']: self.duplicateRenderPassGroup(grp) elif grp.type == compatible_type['PRESET']: self.duplicatePresetGroup(grp) elif grp.type == compatible_type['CHANSET']: self.duplicateChannelGroup(grp) else: self.duplicateGroup(grp) self.deselectAllGroups() except: lx.out(traceback.format_exc())
def cmd_Execute(self,flags): # in the execute method we're going to store the current value of our # attribute so that it can be retrieved by the query method later. There's # no way to permanently store this information inside the command class # itself as the command is created & destroyed between each use. Normally # we'd want to be using persistent storage but for simplicity in this # example we'll use a UserValue. if self.dyna_IsSet(0): if self.dyna_String(0) == NEW: lx.eval('@modder.newSnippet.py') elif self.dyna_String(0) == DIV: pass elif self.dyna_IsSet(1) and self.dyna_String(1) == 'scripteditor': if modder.scripteditor.exists(): modder.scripteditor.clear_output() path = join(modder.path.expand_alias('kit_MODDER:'),'assets','snippets',self.dyna_String(0)) modder.scripteditor.append_output('loading %s' % path) try: with open(path, 'r') as script_file: modder.scripteditor.insert_script(re.sub('^#.*python\n*','',script_file.read())) except: modder.scripteditor.append_output('File could not be opened.') else: lx.out('No script editor available.') else: lx.eval('file.open {kit_MODDER:assets/snippets/%s}' % self.dyna_String(0))
def update_render_output(renderoutput): """ Updates the Render Output path to work on Azure or OS X depending on the OS we are on. """ try: lx.eval(r"select.Item %s" % renderoutput) oldpath = lx.eval("item.channel renderOutput$filename ?") if oldpath is not None: lx.out(renderoutput + " has a set output path: " + oldpath) newpath = format_filename(oldpath) lx.out("Turned output path it into " + osType + " Path: " + newpath) if oldpath is not newpath: lx.eval(r'item.channel renderOutput$filename "%s"' % newpath) # MakePath bd_utils.makes_path(newpath) else: lx.out("Old and new path are identical. No change necessary.") elif oldpath is None: lx.out(str(renderoutput) + " has no active filename. Not touching anything.") except: bd_utils.restoreSelection(save_selection) lx.eval('layout.createOrClose EventLog "Event Log_layout" ' 'title:@macros.layouts@EventLog@ width:600 height:600 persistent:true') lx.out("ERROR Command updateRenderOutput failed with ", sys.exc_info()) return None
def prepareLocatorList(): global fslocator_IDList global fslocator_NameList locatorNames = [] locatorIDs = [] lx.out('Prepping locator list') numberOfSceneItems = lx.eval('query sceneservice item.N ?') monitor = lx.Monitor(numberOfSceneItems) for i in range(numberOfSceneItems): type = lx.eval('query sceneservice item.type ? %s' % i) if (type == "locator"): locatorIDs.append(lx.eval('query sceneservice item.id ? %s' % i)) locatorNames.append( lx.eval('query sceneservice item.name ? %s' % i)) monitor.step() monitor = lx.Monitor(len(locatorIDs)) for index in range(len(locatorIDs)): myParentID = lx.eval('query sceneservice item.parent ? {%s}' % locatorIDs[index]) if (myParentID != None): myParentName = lx.eval('query sceneservice item.name ? {%s}' % myParentID) if (myParentName == "Blendshapes"): fslocator_IDList.append( lx.eval('query sceneservice item.id ? {%s}' % locatorIDs[index])) fslocator_NameList.append( lx.eval('query sceneservice item.name ? {%s}' % locatorNames[index])) monitor.step()
def parseTarget(targetFile): global fsMorphs global assetMorphs with open(targetFile) as f: content = f.read().splitlines() # Let's find the beginning of our relationship definition section. line = 0 while (not content[line].startswith('bs')): if (line == len(content)): # Didn't find anything, we'll exit lx.out('Could not find data in file!') sys.exit() line += 1 # OK, we found something. # Each line now should be of the form : bs = EyeSquint_R = Victoria4_unwelded_blendShape.head.PHMEyeSquintR = 2 monitor = lx.Monitor( len(content) ) monitor.step() while (line < len(content)): tempArray = content[line].split(' = ') faceShiftMorph = tempArray[1] myAssetMorph = tempArray[2] # take our *_blendShape. off the front. myAssetMorph = myAssetMorph[(myAssetMorph.index('.') + 1):] # OK. We can't use dictionaries here because each morph can appear more than once. So we use a pair of matched arrays fsMorphs.append(faceShiftMorph) assetMorphs.append(myAssetMorph) line += 1 monitor.step() for item in range(len(fsMorphs)): lx.out("fsmorph {%s} matched to assetmorph {%s}" % (fsMorphs[item], assetMorphs[item]))
def basic_Execute(self, msg, flags): command = self.dyna_String(0) try: exec command in SHOTGUN_LOCALS, SHOTGUN_LOCALS except: lx.out('SHOTGUN ERROR : {0} {1} {2}'.format(command, msg,flags)) raise
def get_ids(itemtype): """ Get a list of item IDs of type 'type' Returns a list of item IDs or None if there are no items of the specified type or if there's an error. Error printed is to Event log. type - the type of item to be returned (mesh, camera etc) """ try: itemlist = [] numitems = lx.eval('!!query sceneservice ' + itemtype + '.N ?') if numitems == 0: return None else: for x in xrange(numitems): itemlist.append( lx.eval('query sceneservice ' + itemtype + '.ID ? %s' % x)) lx.out("Found " + str(numitems) + " " + itemtype + "s: " + ", ".join( itemlist)) return itemlist except: lx.eval('layout.createOrClose EventLog "Event Log_layout" ' 'title:@macros.layouts@EventLog@ width:600 height:600 persistent:true ' 'open:true') lx.out("ERROR get_ids(" + itemtype + ") failed with ", sys.exc_info()) return None
def selevent_Add(self, type, subtType): SceneService = lx.service.Scene() type_id = SceneService.ItemTypeSuper(subtType) if modo.constants.LIGHT_TYPE == type_id: scene = modo.Scene() selected = scene.selectedByType(subtType)[0] lx.out('Selected Light: %s' % selected.id)
def main(): global osType global unix_path global win_path global save_selection lx.trace(False) osType = platform.system() lx.out("TYPE OS: " + osType) unix_path = "/Volumes/ProjectsRaid/WorkingProjects" win_path = "Z:\AzureSync\CloudComputing\WorkingProjects" save_selection = lx.evalN("query sceneservice selection ? all") renderoutputs = bd_utils.get_ids("renderOutput") if renderoutputs: for x in renderoutputs: update_render_output(x) bd_utils.restoreSelection(save_selection) else: bd_utils.restoreSelection(save_selection)
def makes_path(pathFile, createFolder): if (createFolder == 1): lx.out("CREATE FOLDER: " + pathFile) try: os.makedirs(pathFile) except: lx.out("Alredy exist :" + pathFile)
def onFrame(self, values): #called on each frame try: if self.frameMode == "AdaptToBVH" or self.frameMode == "UseSceneFrameRate": lx.eval("select.time [%s f] [0] [0]" % self.currentframe) else: lx.eval("select.time %s" % self.currentTime) #lx.out("Frame: %s, Time: %s" % (self.currentframe,self.currentTime)) self.applyMotion(self.root, values) self.currentframe += 1 self.currentTime += self.dt monitor.step() except: lx.out("User Aborted") if self.frameMode == "AdaptToBVH" or self.frameMode == "UseSceneFrameRate": lx.eval("time.range current out:[%s f] [0] [0]" % self.currentframe) else: lx.eval("time.range current out:%s" % (self.dt * self.currentframe)) sys.exit()
def layerserviceRef(): text = '<html>\n<body>\n' text += '<head><link rel="stylesheet" type="text/css" href="reset.css"><link rel="stylesheet" type="text/css" href="style.css"></head>' attributesArray = lx.eval('query layerservice "" ?') text += '<h1>layerservice (**depricated**):</h1>\n\n' text += '<p><em>query layerservice "" ?</em></p>' text += '<ul>\n' for attribute in attributesArray: text += '<li>'+attribute+'</li>\n' text += '</ul>\n' text += '</body>\n</html>' kit_path = lx.eval("query platformservice alias ? {kit_KOMODO:}") f = open(os.path.join(kit_path,'html','layerservice.html'),'w') fpath = os.path.abspath(f.name) try: f.write(text) lx.out('saved to %s' % fpath) except: lx.out('could not save to %s' % fpath)
def basic_Execute(self, msg, flags): try: scene = modo.Scene() clipboard = QtGui.QClipboard() # The QtGui.QClipboard gives you access # to your operating system's Copy/Paste Clipboard text = None if len(scene.selected) == 0: # If you have nothing selected, don't do anything pass elif len(scene.selected) == 1: # If you have a single item selected text = scene.selected[0].name # set text to that item's name elif len(scene.selected) > 1: # If you have more than one item selected selItemsAsNames = [item.name for item in scene.selected] # Create a list and grab just the names # This join command allows you to take a list text = ', '.join(selItemsAsNames) # and turn it in to a single long string. # Very useful for displaying lists in a non-python way if text is not None: # Only the above elifs were accessed, will this be true clipboard.setText(text) lx.out('Text copied to clipboard: %s' %(text)) except Exception as e: lx.out(e)
def parseTarget(targetFile): global fsMorphs global assetMorphs with open(targetFile) as f: content = f.read().splitlines() # Let's find the beginning of our relationship definition section. line = 0 while (not content[line].startswith('bs')): if (line == len(content)): # Didn't find anything, we'll exit lx.out('Could not find data in file!') sys.exit() line += 1 # OK, we found something. # Each line now should be of the form : bs = EyeSquint_R = Victoria4_unwelded_blendShape.head.PHMEyeSquintR = 2 monitor = lx.Monitor(len(content)) monitor.step() while (line < len(content)): tempArray = content[line].split(' = ') faceShiftMorph = tempArray[1] myAssetMorph = tempArray[2] # take our *_blendShape. off the front. myAssetMorph = myAssetMorph[(myAssetMorph.index('.') + 1):] # OK. We can't use dictionaries here because each morph can appear more than once. So we use a pair of matched arrays fsMorphs.append(faceShiftMorph) assetMorphs.append(myAssetMorph) line += 1 monitor.step() for item in range(len(fsMorphs)): lx.out("fsmorph {%s} matched to assetmorph {%s}" % (fsMorphs[item], assetMorphs[item]))
def makes_path(pathFile,createFolder): if (createFolder ==1): lx.out("CREATE FOLDER: "+pathFile) try: os.makedirs(pathFile) except: lx.out("Alredy exist :"+pathFile)
def basic_Execute(self, msg, flags): jobId = lx.eval('deadlineDBR.jobID ?') servers = CallDeadlineCommand( ["GetMachinesRenderingJob", jobId, "false"]) servers = servers.splitlines() lx.out("Completing ModoDBR job: %s" % jobId) CallDeadlineCommand(["CompleteJob", jobId]) if not lx.eval('user.value deadlineDBRrenderVRay ?'): # Disables slaves we used as there is no way to go through the list to disable all try: for server in servers: lx.eval('hostlist.enable false {%s}' % server) except: pass lx.eval('deadlineDBR.jobID {}') lx.eval('deadlineDBR.jobStatus {}') lx.eval('deadlineDBR.activeServers {}') lx.eval('user.value deadlineDBRAreServersReserved false') notifier = DeadlineDBRUINotifier() notifier.Notify(lx.symbol.fCMDNOTIFY_VALUE | lx.symbol.fCMDNOTIFY_DISABLE)
def basic_Execute(self, msg, flags): command = self.dyna_String(0) #print 1/0 try: lx.out('SHOTGUN Startup '+ command) except: lx.out('SHOTGUN ERROR : {0} {1} {2}'.format(command, msg,flags)) raise
def filterClips(clipID, clip_size= 'w:8'): '''Delete a clip which has a given pixel size''' layerservice.select('clip.N', 'all') for num in xrange(layerservice.query('clip.N')): layerservice.select('clip.id', str(num)) if clipID == layerservice.query('clip.id') and clip_size in layerservice.query('clip.info').split(' '): lx.eval('clip.delete') lx.out('8x8 clip deleted:', clipID)
def set_range_from_clip(renderItem): clip = get_backdrop(scene.renderCamera) if clip: scene.sceneRange = clip['range'] scene.currentRange = clip['range'] lx.out('frame range: %s - %s' % clip['range']) renderItem.channel(lx.symbol.sICHAN_POLYRENDER_FIRST).set(clip['range'][0]) renderItem.channel(lx.symbol.sICHAN_POLYRENDER_LAST).set(clip['range'][1])
def basic_Execute(self, msg, flags): for n, argument in enumerate(self.commander_arguments()): self._commander_default_values[n] = self.commander_arg_value(n) try: self.commander_execute(msg, flags) except: lx.out(traceback.format_exc())
def basic_Execute(self, msg, flags): command = self.dyna_String(0) try: exec command in SHOTGUN_LOCALS, SHOTGUN_LOCALS except: lx.out('SHOTGUN ERROR : {0} {1} {2}'.format( command, msg, flags)) raise
def runUnitTest(): moc_stdout = StringIO() runner = unittest.TextTestRunner(moc_stdout) suite = loader.loadTestsFromTestCase(TestMacroCommand) runner.run(suite) suite = loader.loadTestsFromTestCase(ParserTest) runner.run(suite) lx.out(moc_stdout.getvalue())
def validatePath(path): global originalPathList global replacementPathList global contentDir_LW lx.out(path) validPath = os.path.isfile(contentDir_LW + os.sep + path) if (validPath == True): return(contentDir_LW + os.sep + path) else: # Mac LW can be very annoying. Let's see if we have such a case here. colonIndex = path.index(':') if (colonIndex > 2): # Mac does VolumeName:myDir/myFile.lwo, so the corresponding file would be /Volumes/VolumeName/myDir/myFile.lwo testPath = '/Volumes/' + string.replace(path,':','/',1) validPath = os.path.isfile(testPath) if (validPath == True): return testPath lastPathSep = path.rfind('\\') if (lastPathSep == -1): # Not found lastPathSep = path.rfind('/') separator = path[lastPathSep] workingReplacement = False # Let's check whether we have encountered this path before and have a potential replacement. try: # We can have more than one replacement path for a given original path. We'll need to check all cases as appropriate. # We look for each matching instance for the original path and then populate a replacement path temporary array for use later. rpTempArray = [] for entry in range(len(originalPathList)): if (originalPathList[entry] == path[:lastPathSep]): rpTempArray.append(replacementPathList[entry]) # Walk our replacement path temporary array to see if any instance delivers a valid path to our asset for entry in range(len(rpTempArray)): newPath = rpTempArray[entry] + os.sep + path[lastPathSep+1:] # Let's see if this is actually a valid file workingReplacement = os.path.isfile(newPath) if(workingReplacement == True): break except: pass if (workingReplacement == False): brokenObject = path[lastPathSep + 1:] replacementFileString = "Locate " + brokenObject newPath = customfile('fileOpen', replacementFileString, 'lwo', 'LWO', '*.lwo', contentDir_LW) if (newPath == None): reportError("Aborting since replacement path not defined") sys.exit() # First time encountering this path. Let's store it and the replacement in case we hit this again and can handle it cleanly. originalPathList.append(path[:lastPathSep]) lastPathSep = newPath.rfind(os.sep) replacementPathList.append(newPath[:lastPathSep]) return newPath
def noti_RemoveClient(self, event): serversReserved = lx.eval('user.value deadlineDBRAreServersReserved ?') jobId = CheckEmptyString('deadlineDBRJobID') if serversReserved and jobId != "": lx.out('Submit To Deadline window closed, completing job: %s' % jobId) CallDeadlineCommand(["CompleteJob", jobId]) del self.masterList[event.__peekobj__()]
def set_gamma(value): """Set gamma with given value for selected images.""" sceneservice.select('selection', 'imageMap') selection = sceneservice.queryN('selection') if selection: for i in selection: lx.eval("item.channel imageMap$gamma %s" %value) else: lx.out("MARI ToolKit: nothing selected")
def write(self, content_to_write): ''' ''' if content_to_write and content_to_write != '\n': if (content_to_write.startswith('Moopy Log') or content_to_write.startswith('Moopy Script Log')): lx.out(content_to_write) else: lx.out('Moopy Print: %s' % content_to_write)
def get_backdrop(camera): for clip in scene.items(itype = lx.symbol.sITYPE_VIDEOSEQUENCE): for cam in clip.itemGraph('shadeLoc').reverse(): if cam == camera: lx.out('Camera: %s' % cam.name) file_path = clip.channel('pattern').get() first_fame = clip.channel(lx.symbol.sICHAN_VIDEOSEQUENCE_FIRSTFRAME).get() last_frame = clip.channel(lx.symbol.sICHAN_VIDEOSEQUENCE_LASTFRAME).get() return {'range':(first_fame, last_frame), 'filePath':file_path, 'clipObj':clip}
def sil_ItemRemove(self, item): # Bail out if there is no undo context. Must be checked if not LightListener.undoService.State() == lx.symbol.iUNDO_ACTIVE: return item = lx.object.Item(item) if item.TestType(modo.constants.LIGHT_TYPE): lx.out('Deleted Light: ', item.Ident())
def scalePos(axis): try: getPos=lx.eval("item.channel pos.%s ?" %(axis)) lx.out(getPos) scaledPos=getPos/100 lx.eval("transform.channel pos.%s %s" %( axis, scaledPos)) except: lx.eval("transform.channel pos.%s 0" %(axis))
def basic_Execute(self, msg, flags): command = self.dyna_String(0) #print 1/0 try: lx.out('SHOTGUN Startup ' + command) except: lx.out('SHOTGUN ERROR : {0} {1} {2}'.format( command, msg, flags)) raise
def debug(string): if not lx.eval('user.value mecco_tagger.debugMode ?'): return frame = _getframe(1) caller = frame.f_globals['__name__'] line = frame.f_lineno lx.out('Tagger Debug: %s (%s, line %s)' % (string, caller, line))
def basic_Execute(self, msg, flags): reload(t) reload(batch_export) try: scn = modo.Scene() currScn = modo.scene.current() userSelection = scn.selected userSelectionCount = len(userSelection) olderSelection = [] currPath = currScn.filename if currPath is None: currPath = '' scnIndex = lx.eval('query sceneservice scene.index ? current') userValues = user_value.query_User_Values(self, t.kit_prefix) tbe = batch_export.TilaBacthExport userValues[1] = True userValues[2] = False tbe.export_at_least_one_format(tbe(userSelection, userSelectionCount, scn, currScn, currPath, scnIndex, userValues)) if bool(userValues[0]): olderSelection = userSelection userSelection = tbe.select_visible_items(tbe(userSelection, userSelectionCount, scn, currScn, currPath, scnIndex, userValues)) userSelectionCount = len(userSelection) tbe.batch_export(tbe(userSelection, userSelectionCount, scn, currScn, currPath, scnIndex, userValues)) if bool(userValues[0]): scn.select(olderSelection) except: lx.out(traceback.format_exc())
def linkMorphs(meshID): global assetMorphs global fsMorphs global morphInfluenceIDs global fslocator_IDList global fslocator_NameList # We need a list of locators that match our expectations for the faceShift imported dataset. # This populates our fslocator_IDList and fslocator_NameList lists prepareLocatorList() # Now we need the morph influences against our selected mesh item # This populates our morphInfluenceIDs list findMorphInfluences(meshID) # OK so we need by morph deformers and check that the associated morph map property matches our faceShift-associated morph. monitor = lx.Monitor(len(morphInfluenceIDs)) lx.out('Processing morph influences') for index in range(len(morphInfluenceIDs)): lx.out("Number of influences in total {%s}" % len(morphInfluenceIDs)) morphID = morphInfluenceIDs[index] # We need to extract our map name from this deformer. lx.eval('select.deformer {%s} set' % morphID) morphMapName = lx.eval('item.channel mapName ? {%s}' % morphID) # So we have a valid deformer and the associated map. # Let's see if the morph map was used in faceShift # morphIndices will hold the position(s) of the map in the assetMorphs array. morphIndices = indices(assetMorphs, morphMapName) if (len(morphIndices) > 0): lx.out('morphs to process : {%d}' % len(morphIndices)) for index in range(len(morphIndices)): # Retrieve the corresponding faceshift morph name fsMorphName = fsMorphs[morphIndices[index]] # Retrieve the locator ID from the matched array based on the name fsLink_Locator_ID = fslocator_IDList[fslocator_NameList.index( fsMorphName)] # We need the xfrmScl locator for this locator. scl_xfrm_item = lx.eval( 'query sceneservice item.xfrmScl ? {%s}' % fsLink_Locator_ID) # Select our driver channel first lx.out('Selecting locator {%s} channel scl.Z' % scl_xfrm_item) lx.eval('select.channel {%s:%s} set' % (scl_xfrm_item, "scl.Z")) # Select our morph influence strength channel next. lx.out('Selecting morph {%s} channel strength' % morphID) lx.eval('select.channel {%s:%s} add' % (morphID, "strength")) # Link them together lx.eval('channel.link toggle') monitor.step()
def start_meshlabserver_with_flags(app_path, flags): """Start Polygon Cruncher with a set of flags waits until it exits and report any failures""" try: process = subprocess.Popen(app_path + ' ' + flags) process.wait() except Exception, e: lx.out( "meshlabserver application launch failed check app path and try again!" ) print e
def main(): global contentDir_LW lx.out("{%s %s} started" % (script_name, script_ver)) contentDir_LW = lx.eval('pref.value lwio.lwoContentDir ?') lwsFile = customfile('fileOpen', 'Load LWS file', 'lws', 'LWS', '*.lws', contentDir_LW) if (lwsFile != None): preflightChecks() parser_main(lwsFile) else: sys.exit()
def importLWO(path): lx.out(path) path = validatePath(path) # Load referenced LWO from scene file. try: lx.eval('scene.open {%s} import' % path) except: # File import failed. Add an empty mesh and move on. lx.eval('item.create mesh') lx.eval('item.name {%s}' % path)
def cmd_Execute (self, flags): ''' This function is called when the user executes the command. Either manually from the command line or from selecting an option in the list. You could do anything you want here, but for now, we'll simply read the value they selected and print it out to the event log. ''' if self.dyna_IsSet (1): lx.out('Filename: %s' % self.dyna_String (1))
def set_range_from_clip(renderItem): clip = get_backdrop(scene.renderCamera) if clip: scene.sceneRange = clip['range'] scene.currentRange = clip['range'] lx.out('frame range: %s - %s' % clip['range']) renderItem.channel(lx.symbol.sICHAN_POLYRENDER_FIRST).set( clip['range'][0]) renderItem.channel(lx.symbol.sICHAN_POLYRENDER_LAST).set( clip['range'][1])
def basic_Execute(self, msg, flags): cmd_string = self.dyna_String(0, "") log_path = self.dyna_String(1, "") lx.out(cmd_string) if log_path != "": with open(log_path, "a+") as log: log.write("{} - {}\r\n".format( time.strftime("%Y-%m-%d %H:%M:%S"), cmd_string)) log.close
def vis_Evaluate(self): try: p1, p2 = self.edge.Endpoints() self.point.Select(p1) self.points.append(self.point.Pos()) self.point.Select(p2) self.points.append(self.point.Pos()) except: lx.out(traceback.format_exc())
def startBake(self): '''This kicks off the xNormal worker thread''' self.set_user_values() config_file = self.writeXML() # Try To Kick off the xNormal worker fail silently try: subprocess.Popen( str(self.xpath + ' ' + self.settings_file + '_bake')) return config_file except: lx.out("Bake Failed Please Check Settings and try again")
def markJobAsFinished(renderJobId,success): #get job assigned to this node, there can only be one conn = sqlite3.connect(pathToDB) cur = conn.cursor() lx.out("Finishing assigned job: id %d" % renderJobId) if success: cur.execute('UPDATE renderJobs SET status="----finished----" WHERE id=%d' % renderJobId) else: cur.execute('UPDATE renderJobs SET status="****ERROR****" WHERE id=%d' % renderJobId) conn.commit() conn.close()
def setVisibilityItem(listItem, visibilty=0): """ rend visible ou invilible la liste des elements """ try: for x in listItem: lx.eval("shader.setVisible %s %s" % (x, visibilty)) except: #exc_log() lx.out("ERROR VISIBILITY") return None
def __init__(self, verts=None, polys=None): lx.out(verts) lx.out(polys) if not verts and polys: verts = getVertsFromPolys(polys) if not polys and verts: polys = getPolysFromVerts(verts) self.render_vert_indices = list(verts) self.render_poly_indices = list(polys) self.updateVecPos()