Esempio n. 1
0
def partOneMain(mesh, camera):
	lx.eval('scene.open \"E:\\Prizmiq\\Shoes.com\\July\\New Balance W1980\\Geometry\\newBalanceW1980_zExport_v001.OBJ\" import')

	lx.eval('select.item %s add' % mesh)
	lx.eval('view3d.projection cam')
	lx.eval('view3d.cameraItem %s' % camera)
	lx.eval('camera.fit true false')
def setShaderEffect(imageItemList=None):
    """Set the shader effect of imported textures.
    Textures must have the $CHANNEL tag set as metadata and the user values of $CHANNELS must be set correctly.
    Three modes:
    - Modify selection in shader tree
    - No selection -> modify all
    - Modify given imageMap item list -> optional
    
    Following effects are supported:
    diffColor
    specAmount
    reflAmount
    bump
    displace
    normal.
    """
    # $CHANNEL user values
    chan_diff = lx.eval("user.value MARI_TOOLS_CHAN_diff ?")
    chan_spec = lx.eval("user.value MARI_TOOLS_CHAN_spec ?")
    chan_refl = lx.eval("user.value MARI_TOOLS_CHAN_refl ?")
    chan_bump = lx.eval("user.value MARI_TOOLS_CHAN_bump ?")
    chan_dspl = lx.eval("user.value MARI_TOOLS_CHAN_displ ?")
    chan_nrml = lx.eval("user.value MARI_TOOLS_CHAN_normal ?")
    
    # Mapping from user values to shader effects #
    chan_values = {chan_diff:"diffColor",
                   chan_spec:"specAmount",
                   chan_refl:"reflAmount",
                   chan_bump:"bump",
                   chan_dspl:"displace",
                   chan_nrml:"normal"
                   }
    
    sceneservice.select("selection", "imageMap")
    selection = sceneservice.queryN("selection")
    
    if selection and imageItemList is None:
        itemList = getItemTags('imageMap')
        
        # remove not found items
        for imageID, value in getItemTags('imageMap').iteritems():
            if imageID not in selection:
                del itemList[imageID]
        
    elif imageItemList is None and not selection:
        itemList = getItemTags('imageMap')
    
    elif imageItemList is not None:
        itemList = imageItemList
    
    for imageID, tags in itemList.iteritems():
        try:
            chan_image = tags[CHANNEL]
        except:
            continue
        
        sceneservice.select("item.type", str(imageID))
        if chan_image in chan_values:
            lx.eval("select.subItem {%s} set textureLayer" %imageID)
            lx.eval("shader.setEffect {%s}" %chan_values[chan_image])
	def character(self):

		# checks if pass group exists and creates it
		if len(self.passgroup.passes) == 0:
			beautypass = self.passgroup.addPass(name="%s" % self.name)
			self.bakepass = self.passgroup.addPass(name="%s_bake" % self.name)	

		for p in self.passgroup.passes:
			if self.name == p.name:
				beautypass = p
			if self.name+'_bake' == p.name:
				self.bakepass = p


		# sets visibility of the render outputs
		beautypass.active = True
		for group in scene.items('mask'):
			if 'Outputs_' in group.name:
				group.channel("enable").set(False)
			if group.name == 'Outputs':
				group.channel("enable").set(True)
		lx.eval('edit.apply')
		beautypass.active = False
		
		self.bakepass.active = True
		for group in scene.items('mask'):
			if group.name == 'Outputs_bake':
				group.channel("enable").set(True)
			elif '_bake' not in group.name and 'Outputs' in group.name:
				group.channel("enable").set(False)
		lx.eval('edit.apply')
		self.bakepass.active = False

		return self.passgroup
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
Esempio n. 5
0
    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 loadShader(self, asset):

		import os

		scene = modo.scene.current()
		basepath = 	r'W:\RTS\_Library'
		endpath = r'sha\publish\modo\lxp'

		versions = []


		name = asset.name.split('_')[1]
		if 'PRP_' in asset.name:
			path = os.path.join(basepath,'Prop',name,endpath)
			for file in os.listdir(path):
				if file.endswith(".lxp") and name+'_' in file:
					versions.append(int(file.replace('.lxp', '').split('_')[-1].replace('v', '')))
			lastversion = str(max(versions)).zfill(3)

			shaderfile = os.path.join(path, name + '_sha_sha_' + 'v' + lastversion + '.lxp')

			print shaderfile

			if os.path.exists(shaderfile):
				lx.eval('preset.dropShader $LXP "%s" {} %s add' % (shaderfile, scene.renderItem.name))
				
				# clean the imported utility group
				for g in scene.groups:
					if name in g.name:
						scene.removeItems(g)
def set_overrides_visibility(passgroups, overrides):

	# sets the defaults visibility for all overrides
	lx.eval('group.current {} pass')

	# get all action clips (passes)
	actionclips = []
	for group in passgroups:
		passes = group.children()
		for passe in passes:
			actionclips.append(passe)

	for clip in actionclips:
		clip.active = True
		clipname = clip.name
		clipname = clipname.strip('_bake')
		masks = []
		for mask in overrides:
			if (clipname + ' (override)') != mask.name:
				masks.append(mask)
			elif (clipname + ' (override)') == mask.name:
				mask.channel('enable').set(True)

		for msk in masks:
			msk.channel('enable').set(False)
		lx.eval('edit.apply')
		clip.active = False

	for grp in overrides:
		grp.channel('enable').set(False)
Esempio n. 8
0
def dump():
    try:
        os.makedirs(DUMP_PATH)
    except:
        pass
    
    for module in DUMP:
        html = '<html>' + n()
        html += '<head>' + n()
        html += '<link rel="stylesheet" type="text/css" href="reset.css">' + n()
        html += '<link rel="stylesheet" type="text/css" href="style.css">' + n()
        html += '</head>' + n()
        html += '<body>' + n()
        html += dive(sys.modules[__name__],module)
        html += "</body></html>"
        target = open(os.path.join(DUMP_PATH,module+EXT),'w')
        target.write(html)
        target.close()
        
    reload(sceneservice)
    sceneservice.sceneserviceRef()
        
    reload(layerservice)
    layerservice.layerserviceRef()
        
    #reload(commandservice)
    #commandservice.commandserviceRef()
    
    reload(imagesavers)
    imagesavers.imagesaversRef(DUMP_PATH)
    
    reload(symbols)
    symbols.symbolDump(DUMP_PATH)
    
    lx.eval('python.dumpAPI {%s}' % os.path.join(DUMP_PATH,"dummy"))
def vmunselect():
    vmaps=lx.evalN("query layerservice vmaps ? selected")
    ctd={"weight":"wght","texture":"txuv","subvweight":"subd","morph":"morf","absmorpf":"spot","rgb":"rgb","rgba":"rgba","pick":"pick"}
    for vm in vmaps:
        name=lx.eval("query layerservice vmap.name ? %s" % vm)
        type=ctd[lx.eval("query layerservice vmap.type ? %s" % vm)]
        lx.eval("select.vertexMap \"%s\" %s remove" % (name,type))
def setValue(main,vt,u,v):
	p=lx.eval("query layerservice vert.polyList ? %s" % vt)
	uv=lx.eval("query layerservice uv.pos ? (%s,%s)" % (p[0],vt))
	du=u-uv[0]
	dv=v-uv[1]
	lx.command("select.element",layer=main,type="vertex",mode="set",index=int(vt))
	uvtrans(du,dv)
def set_overrides_visibility(passgroups, overrides):

    for group in passgroups:
        for mask in overrides:
            group.addChannel("enable", item=mask)

    # get all action clips (passes)
    for clip in scene.items('actionclip'):
        clip.active = True
        clipname = clip.name
        clipname = clipname.strip('_bake')
        masks = []
        for mask in overrides:
            if clipname not in mask.name:
                masks.append(mask)
            elif clipname in mask.name:
                mask.channel('enable').set(True)

        for msk in masks:
            msk.channel('enable').set(False)
        lx.eval('edit.apply')
        clip.active = False

    for grp in overrides:
        grp.channel('enable').set(False)
def create_overrides(passgroups):

    overridegroup = []

    upgroups = []
    for grp in scene.items('mask'):
        if grp.parent == scene.renderItem:
            upgroups.append(grp)
    index = len(upgroups)+1

    for currentgroup in passgroups:
        # adds the override main group, the one whose visibility will be affected by the render passes
        groupname = currentgroup.name.strip('RN_') + ' (override)'
        uppergroup = scene.addMaterial('mask', groupname)
        overridegroup.append(uppergroup)

        for othergroup in passgroups:
            if othergroup != currentgroup:
                othergroupname = othergroup.name.strip('RN_')
                lowergroup = scene.addMaterial('mask', othergroupname)

                for grp in scene.items('groupLocator'):
                    if grp.name == "CHARACTERS":
                        for child in grp.children(recursive=True, itemType='groupLocator'):
                            if othergroupname in child.name:
                                scene.select(lowergroup)
                                lx.eval('mask.setMesh %s' % child.name)

                lowergroup.setParent(newParent=uppergroup)

        uppergroup.channel('enable').set(False)
        uppergroup.setParent(newParent=scene.renderItem, index=index-2)
        scene.select(uppergroup)

    return overridegroup
Esempio n. 13
0
def lightList():
	lList = []
	for i in range(lx.eval('query sceneservice item.N ?')):
	    type = lx.eval('query sceneservice item.type ? %s' % i)
	    if (type == "light"):
	    	lList.append(lx.eval('query sceneservice item.id ? %s' % i))
	return lList
def sortST(selection, item_type):
    '''Sort specific shader tree items alphabetically. Structure is maintained.'''
    # Check if something is selected
    if selection and len(selection) > 0:    
        # Look up exposed item names and sort them in alphabetic order
        itemList = []
        for item in selection:
            sceneservice.select('item', item)
            itemList.append(sceneservice.query('item.name'))
        itemList = sorted(itemList, key=str.lower)
        
        # Check the item type and find the items position in shader tree
        # Dict structure: {parent:[[indices],[items]]}
        data = {}
        for item in itemList:
            lx.out('test: {%s}' %item)
            itemID = lx.eval('query sceneservice item.id ? {%s}' %item)
            if sceneservice.query('item.type') == item_type:
                parent = sceneservice.query('item.parent')
                try:
                    data[parent][0].append(get_shaderTreeIndex(parent, itemID))
                    data[parent][1].append(item)
                except:
                    data[parent] = [[get_shaderTreeIndex(parent, itemID)],[itemID]]
        lx.out(data)        
        # Sort the items in the shader tree
        for parent, value in data.iteritems():
            bottomItem = (min(value[0]))
            itemList = value[1]
            for item in itemList:
                lx.eval('select.item {%s}' %(item))
                lx.eval('texture.parent {%s} {%s}' %(parent, bottomItem))
    else:
        lx.out('Nothing selected. Or wrong type defined')
def create_render_pass_shadow(ground):
	outgrps = []
	passgroup = scene.addRenderPassGroup(name="RN_%s" % ground)

	# creates all the passes
	shadowpass = passgroup.addPass(name="%s" % ground)

	# identifies the output groups
	for grp in scene.items(itype='mask'):
		if grp.name == "Outputs_fin":
			outputs_fin = grp
			outgrps.append(grp)
		if grp.name == "Outputs_bke":
			outputs_bke = grp
			outgrps.append(grp)

	# adds channels to the passes
	for group in outgrps:
		passgroup.addChannel("enable", item=group)

	# sets the effects per pass
	shadowpass.active = True
	outputs_bke.channel("enable").set(False)
	outputs_fin.channel("enable").set(False)
	lx.eval('edit.apply')

	return passgroup
	def basic_Execute(self, msg, flags):
		selection = self.scn.selected

		self.initial_active_pass = self.get_current_renderpass()

		if len(selection) < 3:
			self.init_message("error", 'Invalid Selection Count', 'Select at least one item, and one render pass item')
			return None

		for o in selection:
			if o.type == 'render':
				rpg = o
				continue
			elif o.type == 'actionclip':
				self.passes.append(o)
				continue
			else:
				self.object = o

		for p in self.passes:
			p.active = True
			
			lx.eval('channel.paste')
			lx.eval('edit.apply')
			
			p.active = False

		if self.initial_active_pass is not None:
			self.initial_active_pass.active = True
    def export_selection(self, output_path, export_format):
        lx.eval('!scene.saveAs "%s" "%s" true' % (output_path[0], export_format))

        self.export_log(os.path.basename(output_path[0]))

        if self.exportCageMorph_sw:
            self.export_cage(output_path[1], export_format)
Esempio n. 18
0
def storepreview(path):
    lx.eval('iview.saveImage filename:%s' % path)
    lx.eval('select.itemPattern tmpPreviews')
    folderID = pym.Item_ID_Get('tmpPreviews')
    lx.eval('clip.addStill %s' % path)
    lx.eval('clip.replace filename:%s type:videoStill' % path)
    lx.eval('item.parent {preview03:videoStill001} %s 0' % folderID)
    def freeze_sca(self, force=False):
        if self.freezeSca_sw or force:
            if not force:
                self.transform_log("Freeze Scale")

            lx.eval('transform.freeze scale')
            lx.eval('vertMap.updateNormals')
Esempio n. 20
0
	def shadows(self):

		selnames = []
		passnames = []
		counter = 0

		# get the names of the passes
		for p in self.passgroup.passes:
			passnames.append(p.name)

		# get the names of the selection
		for s in self.selection:
			name = s.name.replace('_GRD', '')
			selnames.append(name)
		
		# creates the passes if they don't exist
		for name in selnames:
			if name+'_AO' not in passnames:
				self.passgroup.addPass(name="%s_AO" % name)
			if name+'_DIR' not in passnames:	
				self.passgroup.addPass(name="%s_DIR" % name)
				
		if len(self.passgroup.passes) > 0:
			for p in self.passgroup.passes:
					p.active = True
					for group in scene.items('mask'):
						if 'Outputs_' in group.name:
							group.channel("enable").set(False)
						if group.name == 'Outputs_shadows':
							group.channel("enable").set(True)
							
					lx.eval('edit.apply')
					p.active = False

		return self.passgroup
    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())
Esempio n. 22
0
	def arrangeClips(self):

		import re


		allassets = []
		allfolders = []

		# gets all image folders
		for f in scene.items('imageFolder'):
			allfolders.append(f.name)

		# scan image clips and detects which asset they belong to
		for c in scene.items('videoStill'):
			path = c.channel('filename').get()
			try:
				asset = path.split('\\')[4]
				allassets.append(asset)
			except:
				pass

		# creates folders for the different assets and put the corresponding textures in them
		for a in set(allassets):
			if a not in allfolders:
				scene.deselect()
				lx.eval('clip.newFolder')
				lx.eval('clip.name %s' % a)
				currentfolder = scene.selected[0]

				currentfolder.setParent()

				for c in scene.items('videoStill'):
					filename = c.channel('filename').get()
					if re.search(currentfolder.name, filename):
						c.setParent(currentfolder)
def main():

    scene = modo.Scene()
    stored_selection = item = scene.selected

    # Grab last selected item and normalize output

    if len(item) > 1:

        item = item[-1]

    elif len(item) == 0:

        item = scene.sceneItem

    else:

        item = item[0]

    pyperclip.copy(item.name)

    lx.eval("user.defNew name string momentary")
    lx.eval("user.value name")

    name = lx.eval("user.value name ?")

    locator = scene.addItem("locator", name)

    locator.setParent(item, -1)

    scene.select(stored_selection)
def makes_path(pathfile):
    """
    Check to make sure destination directory exists.
    If it doesn't create the directory.
    """
    path = os.path.dirname(pathfile)

    try:
        exists = os.path.exists(path)
        if exists:
            lx.out(
                "Tried creating folder \"" + path + "\", but it already exists.")
        else:
            try:
                os.makedirs(path)
                lx.out("Created folder: " + str(path))
            except OSError:
                if not os.path.isdir(path):
                    raise

    except:
        lx.eval('layout.createOrClose EventLog "Event Log_layout" '
                'title:@macros.layouts@EventLog@ width:600 height:600 persistent:true '
                'open:true')
        lx.out("ERROR creating path for " + path, sys.exc_info())
    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))
Esempio n. 26
0
def meshList():
	mList = []
	for i in range(lx.eval('query sceneservice item.N ?')):
	    type = lx.eval('query sceneservice item.type ? %s' % i)
	    if (type == "mesh"):
	    	mList.append(lx.eval('query sceneservice item.id ? %s' % i))
	return mList
Esempio n. 27
0
def sceneserviceRef():

    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 sceneservice "" ?')

    text += '<h1>sceneservice:</h1>\n\n'
    text += '<p><em>query sceneservice "" ?</em></p>'

    text += '<ul>\n'
    for attribute in attributesArray:
        text += '<li>'+attribute+'</li>\n'
    text += '</ul>\n'

    text += '\n\n<h2>attributes:</h2>\n\n'

    for attribute in attributesArray:
        attributesArrayList = '<ul>\n'

        #if (attribute.startswith('attribute.')) and (attribute.startswith('attribute.argArgTypes') == 0) and (attribute.startswith('attribute.toggleArg') == 0):
        query = '!!query sceneservice %s ?' % (attribute)
        try:
            q = lx.eval(query)
            if isinstance(q,(list,tuple)):
                attributesArrayList += '\t<li><strong>%s</strong><br />\n<span class="light">query sceneservice %s ?</span>\n\t\t<ul>' % (attribute,attribute)
                for v in q:
                    if v == '': v = '(n/a)'
                    try:
                        attributesArrayList += '\n\t\t\t<li>%s</li>\n' % (v)
                    except:
                        attributesArrayList += '\n\t\t\t<li>(error)</li>'
                attributesArrayList += '\n\t\t</ul>\n\t</li>\n'
            else:
                try:
                    if (str(q) != '') and (str(q) != 'None') and (str(q) != '0'):
                        attributesArrayList += '\t<li><strong>'+attribute+':</strong><br />'
                        attributesArrayList += str(q)+'</li>\n'
                except:
                    attributesArrayList += '<!--error reading %s--></li>\n' % attribute
        except:
            lx.out('FAILED: %s' % query)


        attributesArrayList += '</ul>\n'

        if attributesArrayList != '<ul></ul>\n':
            text += attributesArrayList+'\n\n\n'

    text += '</body>\n</html>'

    kit_path  = lx.eval("query platformservice alias ? {kit_MODDER:}")
    f = open(os.path.join(kit_path,'html','sceneservice.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)
Esempio n. 28
0
	def locatorList(self):
		lList = []
		for i in range(lx.eval('query sceneservice item.N ?')):
		    type = lx.eval('query sceneservice item.type ? %s' % i)
		    if (type == "locator"):
		    	lList.append(lx.eval('query sceneservice item.id ? %s' % i))
		return lList
Esempio n. 29
0
def cameraList():
	cList = []
	for i in range(lx.eval('query sceneservice item.N ?')):
	    type = lx.eval('query sceneservice item.type ? %s' % i)
	    if (type == "camera"):
	    	cList.append(lx.eval('query sceneservice item.id ? %s' % i))
	return cList
Esempio n. 30
0
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)
Esempio n. 31
0
def customfile(type, title, format, uname, ext, save_ext=None, path=None):
    '''
		Open a file requester for a custom file type and return result
		type - open or save dialog (fileOpen or fileSave)
		title - dialog title
		format - file format
		uname - format username
		ext - file extension in the form '*.ext'
		save_ext - (optional)
		path - (optional) Default path to open dialog with
		
		examples:
			file = customfile('fileOpen', 'Open JPEG file', 'JPG', 'JPEG File', '*.jpg;*.jpeg')
			file = customfile('fileSave', 'Save Text file', 'TXT', 'Text File', '*.txt', 'txt')
	
	'''
    lx.eval('dialog.setup %s' % type)
    lx.eval('dialog.title {%s}' % (title))
    lx.eval('dialog.fileTypeCustom {%s} {%s} {%s} {%s}' %
            (format, uname, ext, save_ext))
    if type == 'fileSave' and save_ext != None:
        lx.eval('dialog.fileSaveFormat %s' % save_ext)
    if path != None:
        lx.eval('dialog.result {%s}' % (path + 'Scenes'))
    try:
        lx.eval('dialog.open')
        return lx.eval('dialog.result ?')
    except:
        return None
Esempio n. 32
0
def getPolysFromVerts(vertex_index_list):
    polygon_list = set()
    for source_vertex in vertex_index_listt:
        vert_polys = lx.eval("query layerservice vert.polyList ? " + str(source_vertex))
        polygon_list = polygon_list.union(vert_polys)
    return list(polygon_list)
Esempio n. 33
0
def getPartPolys(part):
    lx.eval("select.drop polygon")
    lx.eval("select.polygon add part face " + str(part))
    return lx.eval("query layerservice polys ? selected")
Esempio n. 34
0
def queryUserValue(user_val):
    if lx.eval("query scriptsysservice userValue.isdefined ? " + str(user_val)):
        return lx.eval("user.value " + str(user_val) + " ?")
    else:
        return None
#python
# -*- coding: utf-8 -*-

import lx

#================================================================
# Defaults
#================================================================

#Application
lx.eval("pref.value application.indexStyle uscore")

# Image & Painting
lx.eval("pref.value application.imageAA false")
lx.eval("pref.value application.imageThumbnails true")

#UI
lx.eval("pref.value remapping.baseProficiency advanced")
lx.eval("pref.value uiimages.uiimageMax 400")
lx.eval("pref.value uiimages.uiimageCacheSize 1073741824")
lx.eval("pref.value uiimages.uiimageThumbSize 256")
lx.eval("pref.value remapping.toolPropsType inline")

#================================================================
# Display
#================================================================

#3D Information Overlays
lx.eval("pref.value overlays.toolSnap true")
lx.eval("pref.value overlays.UVCoverage true")
    def locator_at_zero():
        lx.out("Nothing selected, creating locator at workplane 0,0,0")

        # ----- CUSTOM LOCATOR CREATION -----

        # Create locator
        lx.eval("item.create locator")

        # Apply dimensions to locator size
        lx.eval("item.channel locator$size " + str(mysize))

        # Apply shape, replace and solid
        lx.eval("item.channel locator$drawShape custom")
        lx.eval("item.channel locator$isStyle replace")
        lx.eval("item.channel locator$isSolid true")

        # Define temporarily as box to introduce XYZ dimensions
        lx.eval("item.channel locator$isShape box")
        lx.eval("item.channel locator$isSize.X " + str(mysize))
        lx.eval("item.channel locator$isSize.Y " + str(mysize))
        lx.eval("item.channel locator$isSize.Z " + str(mysize))

        # Define temporarily as circle to introduce radius
        lx.eval("item.channel locator$isShape circle")
        lx.eval("item.channel locator$isRadius " + str(mysize * 0.5))

        # Apply axis and align
        lx.eval("item.channel locator$isAxis " + myaxis)
        lx.eval("item.channel locator$isAlign " + myalig)

        # Apply final form shape
        lx.eval("item.channel locator$isShape " + myform)

        # Finally, decide between default or custom shape
        # I introduce this final step to “store” shape dimensions
        # even if you create a Default locator and then you decide
        # to change to a custom shape
        lx.eval("item.channel locator$drawShape " + myshap)

        # ---------------------------------

        lx.eval("item.matchWorkplanePos")
def selectConectedUV():
    lx.eval('!!select.3DElementUnderMouse set')
    lx.eval('ffr.selectconnecteduv')
Esempio n. 38
0
def main():
    scene = modo.Scene()
    instances, replacement_mesh, original_mesh = get_meshes(scene)
    duplicate_original = scene.duplicateItem(original_mesh)
    duplicate_original.name = replacement_mesh.name + "_RI"
    duplicate_instances = []
    for i in instances:
        item = scene.duplicateItem(duplicate_original, True)
        item.name = i.name + "_RI"
        duplicate_instances.append(item)
        # update the xforms to match those of the original instance
    update_xforms(instances, duplicate_instances)
    # replace the duplicate original with the replacement mesh
    scene.select(replacement_mesh)
    lx.eval("select.typeFrom polygon")
    lx.eval("select.all")
    lx.eval("copy")
    scene.select(duplicate_original)
    lx.eval("select.all")
    lx.eval("delete")
    lx.eval("paste")
    # put them into a group
    grp = scene.addItem(modo.constants.GROUPLOCATOR_TYPE,
                        name=replacement_mesh.name + "_RI_GROUP")
    duplicate_original.setParent(grp)
    for i in duplicate_instances:
        i.setParent(grp)
    # select the new group we just added so they know what happened
    scene.select(grp)
Esempio n. 39
0
#! /usr/bin/python

import lx
lx.eval('log.toConsole true')
lx.eval('log.toConsoleRolling true')
args = lx.arg().split()
lx.out('Starting GS Modo Init')

# attempt to set the muster submit ui
# NOT WORKING, I THINK script is run before the sheet is created in modo,
# maybe there is a way to runn the commands defferred until after startup completes
#lx.out('Adding Render Submit UI')
#lx.eval('select.attr {49634997570:sheet} set')
#lx.eval('attr.parent {frm_modomodes_render:sheet} 19')
Esempio n. 40
0
def error(titleString, errorString):
    lx.eval("dialog.setup error")
    lx.eval("dialog.title \"%s\"" % titleString)
    lx.eval("dialog.msg \"%s\"" % errorString)
    lx.eval("dialog.open")
Esempio n. 41
0

hide = False
collapse = False
collapseAll = False

args = lx.args()
for arg in args:
    if arg == "collapse":
        collapse = True
    if arg == "collapseAll":
        collapseAll = True
    if arg == "hide":
        hide = True

fg = lx.eval("query layerservice layers ? fg")
layer_name = lx.eval("query layerservice layer.name ? fg")
layer_id = lx.eval("query layerservice layer.id ? fg")

if collapse:
    parent_layer = lx.eval("query layerservice layer.parent ? fg")
    lx.out(parent_layer)
    if parent_layer == -1:
        sys.exit("LXe_ABORT")
    lx.eval("select.all")
    lx.eval("cut")
    lx.out(parent_layer)
    lx.eval("select.layer number:" + str(parent_layer + 1) + " mode:set")
    parent_id = lx.eval("query layerservice layer.id ? fg")
    lx.eval("paste")
    lx.eval("select.subItem item:" + layer_id + " mode:set mask:mesh")
Esempio n. 42
0
def modoRenderPath():
    # lista los objetos que son renderOutput
    itemNum = lx.eval("query sceneservice item.N ? ")
    itemNumList = range(0, itemNum)
    renderOutputList = []
    for item in itemNumList:
        itemType = lx.eval("query sceneservice item.type ? %s" % item)
        itemName = lx.eval("query sceneservice item.name ? %s" % item)
        if itemType == "renderOutput":
            renderOutputList.append(itemName)


########################
# busca y crea la ruta correspondiente donde guardar los render, y si no existe la crea
    currentfile = modoClasses.modoScene.currentFile()
    dirname, name = os.path.split(currentfile)
    endName = name.split("_")
    endName = endName[-1].split(".lxo")[0]
    name = name.split(".lxo")[0]
    name = name + "_"
    subFolderList = dirname.split("\\")
    for obj in ["Z:", "episodios", "secuencias", "shots", "Lighting"]:
        subFolderList.remove(obj)
    path = "Z:\\INTERNO\\MEDIA"
    for obj in subFolderList:
        path = path + "\\" + obj
        try:
            os.mkdir(path)
        except Exception:
            pass
    path = path + "\\modo"
    try:
        os.mkdir(path)
    except Exception:
        pass
    path = path + "\\" + endName
    lx.out(path)
    lx.out("tendria que ser parche")
    try:
        os.mkdir(path)
    except Exception:
        pass
    lx.out(path)
    path = path + "\\borrar"
    try:
        os.mkdir(path)
    except Exception:
        pass

    pathFull = path
    path = os.path.join(path)
    contador1 = 0
    contador2 = 0
    if os.path.exists(path):
        path = os.path.join(os.path.dirname(path), name)
        try:
            renderOutputList.remove("Alpha Output (2)")
            renderOutputList.remove("Alpha Output")
            renderOutputList.remove("Alpha Output2")
        except Exception:
            pass
        for renOutp in renderOutputList:
            if str(renOutp) != "Alpha Output (2)" or str(
                    renOutp) != "Alpha Output":
                if len(renOutp.split(" ")) < 2:
                    lx.eval(
                        "select.subItem %s set textureLayer;render;environment;light;camera;scene;replicator;bake;mediaClip;txtrLocator"
                        % renOutp)
                    lx.eval('item.channel renderOutput$filename "%s"' % path)
                    lx.eval('item.channel renderOutput$format openexr')
                    contador1 = contador1 + 1
                else:
                    QtGui.QMessageBox.warning(
                        None, u' Error de Nomenclatura',
                        ' espacios o caracteres especiales en la nomenclatura de '
                        + renOutp + "     ")
                    contador2 = contador2 + 1
        if contador1 != 0 and contador2 == 0:
            QtGui.QMessageBox.warning(None, u' Grositud',
                                      "Proceso terminado sin errores")
    else:
        print(" parece que no existe  dirMedia ")
    shutil.rmtree(pathFull)
Esempio n. 43
0
def set_renderCam(camera, renderItem):
    """
    Set render camera and adjust frame range if camera has a clip attached
    """
    lx.eval('render.camera %s' % camera.id)
    set_range_from_clip(renderItem)
Esempio n. 44
0
def get_user_values():
    return {
        "optimizationRatio": lx.eval('user.value pc_optimizationRatio ?'),
        "progressiveRatio": lx.eval('user.value pc_progressiveRatio ?'),
        "borderMode": lx.eval('user.value pc_borderMode ?'),
        "cornerMode": lx.eval('user.value pc_cornerMode ?'),
        "keepMaterialBoundaries":
        lx.eval('user.value pc_keepMaterialBoundaries ?'),
        "materialBoundaryMode":
        lx.eval('user.value pc_materialBoundaryMode ?'),
        "keepTextures": lx.eval('user.value pc_keepTextures ?'),
        "uvMode": lx.eval('user.value pc_uvMode ?'),
        "uvTolerance": lx.eval('user.value pc_uvTolerance ?'),
        "keepVertexColors": lx.eval('user.value pc_keepVertexColors ?'),
        "vcMode": lx.eval('user.value pc_vcMode ?'),
        "vcTolerance": lx.eval('user.value pc_vcTolerance ?'),
        "keepNormals": lx.eval('user.value pc_keepNormals ?'),
        "normalMode": lx.eval('user.value pc_normalMode ?'),
        "thresholdAngle": lx.eval('user.value pc_thresholdAngle ?'),
        "favorCompactFaces": lx.eval('user.value pc_favorCompactFaces ?'),
        "preventFlippedNormals":
        lx.eval('user.value pc_preventFlippedNormals ?'),
        "stopAutomatically": lx.eval('user.value pc_stopAutomatically ?'),
        "lockVertexPosition": lx.eval('user.value pc_lockVertexPosition ?'),
        "appPath": os.path.normpath(lx.eval('user.value pc_appPath ?'))
    }
def selectConectedUV():
    lx.eval('!!select.3DElementUnderMouse set')
    lx.eval('ffr.selectconnecteduv')


selType = lx.eval1('query layerservice selmode ?')

if selType == 'polygon':
    p_hover = lx.eval1('query view3dservice element.over ? poly')
    p_sel = lx.evalN('query layerservice uv ? selected')
    if isinstance(p_hover, str):
        selectConectedUV()
    else:
        if len(p_sel) > 0:
            lx.eval('ffr.selectconnecteduv')
        else:
            lx.eval('select.all')

elif selType == 'edge':
    lx.eval('select.type polygon')
    e_hover = lx.eval1('query view3dservice element.over ? poly')
    if isinstance(e_hover, str):
        selectConectedUV()
    else:
        lx.eval('select.all')

elif selType == 'vertex':
    lx.eval('select.type polygon')
    v_hover = lx.eval1('query view3dservice element.over ? poly')
    if isinstance(v_hover, str):
Esempio n. 46
0
def set_fbx_export_preset_values():
    """set the fbx presets and export the fbx temp file"""
    print 'setting scripts fbx preset values'
    lx.eval('user.value sceneio.fbx.save.exportToASCII true')
    lx.eval('user.value sceneio.fbx.save.exportType FBXExportSelection')
    lx.eval('user.value sceneio.fbx.save.animationOnly false')
    lx.eval('user.value sceneio.fbx.save.geometry true')
    lx.eval('user.value sceneio.fbx.save.materials true')
    lx.eval('user.value sceneio.fbx.save.cameras false')
    lx.eval('user.value sceneio.fbx.save.lights false')
    lx.eval('user.value sceneio.fbx.save.animation false')
    lx.eval('user.value sceneio.fbx.save.surfaceRefining FBXExportPolygons')
    lx.eval('user.value sceneio.fbx.save.polygonParts true')
    lx.eval('user.value sceneio.fbx.save.selectionSets false')
    lx.eval('user.value sceneio.fbx.save.smoothingGroups true')
    lx.eval('user.value sceneio.fbx.save.morphMaps false')
    lx.eval('user.value sceneio.fbx.save.tangentsBitangents true')
    lx.eval('user.value sceneio.fbx.save.units default')
    lx.eval('user.value sceneio.fbx.save.scale 1.0')
    lx.eval('user.value sceneio.fbx.save.exportRgbaAsDiffCol false')
    lx.eval('user.value sceneio.fbx.save.pbrMaterials false')
    lx.eval('user.value sceneio.fbx.save.sampleAnimation false')
    lx.eval(
        'user.value sceneio.fbx.save.sampleAnimFpsMultiplier FBXAnimSampleRate_x1'
    )
    lx.eval('user.value sceneio.fbx.save.exportActionType FBXExportNoActions')
def main(comment=False, commentstring=""):
    start_timer = bd_helpers.timer()

    scene = modo.Scene()
    regex = "(.+)_v(\d+)(\w+)?"  # Grab anything that has a character sequence followed by a _v and some number

    filepath = scene.filename
    if filepath:
        filename = os.path.splitext(os.path.basename(filepath))
        filepath = os.path.dirname(filepath)
        fileextension = filename[1]
        filename = filename[0]

        match = re.match(regex, filename)
        if match:
            version = match.group(2)
            filename = match.group(1)
            filecomment = match.group(3)

            result = "yes"
        else:
            message = "The provided file ({}{}) contains no version info (we are looking for a '_v000' here).\n\n" \
                      "Do you want to start versioning this file?".format(filename, fileextension)
            result = modo.dialogs.yesNo("Missing Version", message)

            if result == "yes":
                version = "00"

        if result == "yes":

            print('Current file "{}" is at Version {}.'.format(filename, version))

            created = False
            zfill = len(version)

            if comment:
                filecomment = commentstring.replace(" ","_").lower()
                filecomment = bd_helpers.format_filename(filecomment)
            else:
                filecomment = False

            while created is False:

                version = str(int(version) + 1).zfill(zfill)

                if filecomment:
                    newfile = os.path.join(filepath, "{}_v{}_{}{}".format(filename, version, filecomment, fileextension))
                else:
                    newfile = os.path.join(filepath, "{}_v{}{}".format(filename, version, fileextension))

                if os.path.isfile(newfile):
                    print("Version " + version + " already exists. Increasing version count.")
                    pass
                else:
                    print("Saving as Version " + version)
                    try:
                        lx.eval('scene.saveAs {%s}' % newfile)
                    except:
                        lx.eval('layout.createOrClose EventLog "Event Log_layout" '
                                'title:@macros.layouts@EventLog@ width:600 height:600 persistent:true '
                                'open:true')
                        print("ERROR Scene save failed with ", sys.exc_info())

                    created = True

    else:
        message = "The provided file has not been saved yet."
        modo.dialogs.alert("Missing Version!",
                           message,
                           dtype='error')

    bd_helpers.timer(start_timer, ' Overall')
#    — If COMPONENTS are selected, add a new Locator in the center of bounding box
#    — If NOTHING is selected, add a new Locator at Workplane Origin

# Example: @add_new_locator.py circle 0.1 z 1 custom

import lx

# Defining arguments
myform = lx.args()[0]  # box, plane, circle, etc
mysize = float(lx.args()[1])  # size in meters
myaxis = lx.args()[2]  # axis xyz
myalig = lx.args()[3]  # align true or false
myshap = lx.args()[4]  # shape default or custom

# Enable Locators visibility, just in case it was disable
lx.eval("view3d.showLocators true")

try:

    # Function that puts locator at workplane zero

    def locator_at_zero():
        lx.out("Nothing selected, creating locator at workplane 0,0,0")

        # ----- CUSTOM LOCATOR CREATION -----

        # Create locator
        lx.eval("item.create locator")

        # Apply dimensions to locator size
        lx.eval("item.channel locator$size " + str(mysize))
Esempio n. 49
0
def store_fbx_preset_user_values():
    """store the users current FBX preset values"""
    print 'storing user fbx preset values'
    return {
        "exportToASCII":
        lx.eval('user.value sceneio.fbx.save.exportToASCII ?'),
        "exportType":
        lx.eval('user.value sceneio.fbx.save.exportType ?'),
        "animationOnly":
        lx.eval('user.value sceneio.fbx.save.animationOnly ?'),
        "geometry":
        lx.eval('user.value sceneio.fbx.save.geometry ?'),
        "materials":
        lx.eval('user.value sceneio.fbx.save.materials ?'),
        "cameras":
        lx.eval('user.value sceneio.fbx.save.cameras ?'),
        "lights":
        lx.eval('user.value sceneio.fbx.save.lights ?'),
        "animation":
        lx.eval('user.value sceneio.fbx.save.animation ?'),
        "surfaceRefining":
        lx.eval('user.value sceneio.fbx.save.surfaceRefining ?'),
        "polygonParts":
        lx.eval('user.value sceneio.fbx.save.polygonParts ?'),
        "selectionSets":
        lx.eval('user.value sceneio.fbx.save.selectionSets ?'),
        "smoothingGroups":
        lx.eval('user.value sceneio.fbx.save.smoothingGroups ?'),
        "morphMaps":
        lx.eval('user.value sceneio.fbx.save.morphMaps ?'),
        "tangentsBitangents":
        lx.eval('user.value sceneio.fbx.save.tangentsBitangents ?'),
        "units":
        lx.eval('user.value sceneio.fbx.save.units ?'),
        "scale":
        lx.eval('user.value sceneio.fbx.save.scale ?'),
        "exportRgbaAsDiffCol":
        lx.eval('user.value sceneio.fbx.save.exportRgbaAsDiffCol ?'),
        "pbrMaterials":
        lx.eval('user.value sceneio.fbx.save.pbrMaterials ?'),
        "sampleAnimation":
        lx.eval('user.value sceneio.fbx.save.sampleAnimation ?'),
        "sampleAnimFpsMultiplier":
        lx.eval('user.value sceneio.fbx.save.sampleAnimFpsMultiplier ?'),
        "exportActionType":
        lx.eval('user.value sceneio.fbx.save.exportActionType ?'),
    }
Esempio n. 50
0
    frames = list(set([first, middle, last]))

    try:
        file_path = modo.dialogs.fileSave('image',
                                          'png',
                                          title='Save Render',
                                          path=None)
    except:
        print 'Abort'
    else:
        render(file_path, frames)

if arg == 'xframes':
    """
    Render a sequence n frames. E.g. sequence 1-20 and number 10 will render
    only every second frame of the sequence.
    """

    frames = range(first, last + 1)
    # for some reason we need to substract one from the number of frames
    number = lx.eval('user.value LIGHTBOX_renderFrames_number ?') - 1
    frames = frames[::frames[-1] / number]
    try:
        file_path = modo.dialogs.fileSave('image',
                                          'png',
                                          title='Save Render',
                                          path=None)
    except:
        lx.out('Abort')
    else:
        render(file_path, frames)
#python

# File: mc_lxRename_removeX.py
# Author: Matt Cox
# Description: Bulk renames a selection of items, removing X amount of characters from the start or the end. Based upon the user variable removeX.

import lx
import re

lxRRemoveXString = lx.eval( "user.value mcRename.removeX ?" )
lxRRemoveXArgs = lx.args()
lxRRemoveXArg = lxRRemoveXArgs[0]

if lxRRemoveXString < 0:
    lxRRemoveXString = 0
try:
    lxRSelectedItems = lx.evalN('query sceneservice selection ? all')
    
    for x in lxRSelectedItems:
        lx.eval('select.Item %s' %str(x))
        lxRMeshNameM = lx.eval('query sceneservice item.name ? %s' %str(x))
        try:
            if lxRRemoveXArg == "start":
                lxRNewNameM = lxRMeshNameM[lxRRemoveXString:]
            else:
                lxRNewNameM = lxRMeshNameM[:-lxRRemoveXString]
            lx.eval('item.name "%s"'%(lxRNewNameM))
        except:
            lx.eval('dialog.setup error')
            lx.eval('dialog.title {Error}')
            lx.eval('dialog.msg {Unable to rename items.}')
def main(arbitrary=False, name=""):
    scene = modo.Scene()

    # Initialize values
    index = 10000000000000000000000  # Set the index to something very high so we can find the lowest index
    firstFrame = scene.renderItem.channel('first').get() / scene.fps
    func_name = BLEND_COMMAND
    blend_type = lx.eval("user.value bd.blend_type_pref ?")

    # Find the topmost spot below the renderOutputs
    for item in scene.renderItem.children():
        if item.type == "renderOutput":
            if index > item.parentIndex:
                index = item.parentIndex

    parentIndex = index

    if arbitrary:
        selected = scene.selected
        blend_name = '{1}_{0}'.format(name, func_name)
    else:
        selected = scene.selected[-1:]
        blend_name = '{1}_{0}'.format(selected[0].name, func_name)

    # Generate the complete hierarchy from the parent down and add it to a group
    hierarchy = []

    for select in selected:
        if select.type == "mesh":
            hierarchy.append(select)
        if select.type == "meshInst":
            hierarchy.append(select)
        for item in select.children(recursive=True):
            hierarchy.append(item)

    print hierarchy

    blend_group_name = '{0}_grp'.format(blend_name)

    try:

        scene.item(blend_group_name)
        modo.dialogs.alert(
            'Warning',
            '{0} already has a {1} group. Not creating a new one.'.format(
                selected[0].name, func_name),
            dtype='warning')

    except:
        answer = "yes"
        groups = []
        dups = []
        check = False
        for item in hierarchy:
            for group in scene.getGroups('{0}'.format(func_name)):
                if group.hasItem(item):
                    check = True
                    groups.append(group.name)

            dups.append("Item: {0} - Groups: {1}".format(item.name, groups))

        if check:

            answer = modo.dialogs.yesNo(
                'Warning',
                'Some items are already in groups. Do you still want to add them to '
                'another group?')

        if answer == "no":
            None
        else:
            blend_group = scene.addGroup(name=blend_group_name,
                                         gtype='{0}'.format(func_name))
            blend_group.addItems(hierarchy)

            # Create a shading group, a shader and a constant
            mask = scene.addItem('mask', name='{0}_msk'.format(blend_name))
            shader = scene.addItem('defaultShader',
                                   name='{0}_shdr'.format(blend_name))
            constant = scene.addItem('constant',
                                     name='{0}_cnstnt'.format(blend_name))

            # Parent everything to the shading group
            shader.setParent(mask)
            constant.setParent(mask, index=0)
            mask.setParent(scene.renderItem, index=parentIndex)

            # Set the correct Shading Effect
            constant.channel('effect').set(blend_type)
            #constant.channel('value').set(0.0, time=firstFrame, key=True)

            # Adjust the Item dropdown in the shading group
            # (yes, it is reverse, we are actually setting the input of the group to be the shading group)
            blend_group.itemGraph('shadeLoc').connectInput(mask)

            # Check if the Channel Set exist if not create it and add our new blend channel to it
            chan_set = False
            for group in scene.getGroups(gtype='chanset'):

                if group.name == '{}_channel_set'.format(func_name):
                    chan_set = True

            if not chan_set:
                chan_set = scene.addGroup(
                    name='{}_channel_set'.format(func_name), gtype='chanset')
            else:
                chan_set = scene.item('{}_channel_set'.format(func_name))

            chan_set.addChannel('value', constant)
Esempio n. 53
0
# This is a python conversion of seneca's "script_goodSubroutines" perl library, plus some of my own stuff

import lx
import modomath
import os
import string
import random
import re
import math

layer = lx.eval("query layerservice layers ? main")
numbersp = re.compile(r"\d+")

def queryUserValue(user_val):
    if lx.eval("query scriptsysservice userValue.isdefined ? " + str(user_val)):
        return lx.eval("user.value " + str(user_val) + " ?")
    else:
        return None

def getLayerNames():
    layer_list = []
    for i in range(1, lx.eval("query layerservice layer.N ? all") ):
        layer_list.append(lx.eval("query layerservice layer.name ? " + str(i)))
    return layer_list

def idGenerator(size=6, chars=string.ascii_letters + string.digits):
    return string.join(random.sample(chars,size),"")

def getUniqueSelSetName(polys):
    sel_sets = set()
    for poly in polys:
Esempio n. 54
0
def selectConectedUV():
    lx.eval('!!select.3DElementUnderMouse set')
    lx.eval('select.polygonConnect m3d false')


selType = lx.eval1('query layerservice selmode ?')

if selType == 'polygon':
    p_hover = lx.eval1('query view3dservice element.over ? poly')
    p_sel = lx.evalN('query layerservice polys ? selected')
    if isinstance(p_hover, str):
        selectConectedUV()
    else:
        if len(p_sel) > 0:
            lx.eval('select.polygonConnect m3d false')
        else:
            lx.eval('select.all')

elif selType == 'edge':
    lx.eval('select.type polygon')
    e_hover = lx.eval1('query view3dservice element.over ? poly')
    if isinstance(e_hover, str):
        selectConectedUV()
    else:
        lx.eval('select.all')

elif selType == 'vertex':
    lx.eval('select.type polygon')
    v_hover = lx.eval1('query view3dservice element.over ? poly')
    if isinstance(v_hover, str):
Esempio n. 55
0
def getLayerNames():
    layer_list = []
    for i in range(1, lx.eval("query layerservice layer.N ? all") ):
        layer_list.append(lx.eval("query layerservice layer.name ? " + str(i)))
    return layer_list
Esempio n. 56
0
def selectConectedUV():
    lx.eval('!!select.3DElementUnderMouse set')
    lx.eval('select.polygonConnect m3d false')
Esempio n. 57
0
def getVertsFromPolys(polygon_index_list):
    vertex_list = set()
    for source_polygon in polygon_index_list:
        poly_verts = lx.eval("query layerservice poly.vertList ? " + str(source_polygon))
        vertex_list = vertex_list.union(poly_verts)
    return list(vertex_list)
Esempio n. 58
0
 def basic_Enable(self, msg):
     if lx.eval('replay.record query:?'):
         return False
     if replay.Macro().is_empty:
         return False
     return all(node.canEval() for node in replay.Macro().selected_descendants)
Esempio n. 59
0
import shutil

import modo
from PySide import QtGui

import lasp.modo.mddImport as mddImport

reload(mddImport)
import lasp.modo.modoDialogs as modoDialogs

reload(modoDialogs)
import lasp.modo.modoClasses as modoClasses

reload(modoClasses)

lx.eval("pref.value application.indexStyle none")


def modoRenderPath():
    # lista los objetos que son renderOutput
    itemNum = lx.eval("query sceneservice item.N ? ")
    itemNumList = range(0, itemNum)
    renderOutputList = []
    for item in itemNumList:
        itemType = lx.eval("query sceneservice item.type ? %s" % item)
        itemName = lx.eval("query sceneservice item.name ? %s" % item)
        if itemType == "renderOutput":
            renderOutputList.append(itemName)


########################
Esempio n. 60
0
def fn_dialogCaution():
    try:
        # Set up the dialog
        lx.eval('dialog.setup yesNo')
        lx.eval('dialog.title {Eterea Add Locator to Middle of Selected}')
        lx.eval('dialog.msg {You have %s %s selected. That is a big amount\n\
				and could be slow to process. Are you sure of this?\n\
				 \n\
				Press "Yes" to Continue or "No" to Cancel... to select less.}' %
                (selected_N, plural_dict[mySelMode]))
        lx.eval('dialog.result ok')
        # Open the dialog and see which button was pressed
        lx.eval('dialog.open')
        result = lx.eval('dialog.result ?')
    except:
        sys.exit()