Beispiel #1
0
 def basic_Execute(self, msg, flags):
     try:
         lx.bless(Gui, 'Multimatte')
     except:
         pass
     lx.eval('layout.create width:300 height:300 style:palette')
     lx.eval('customview.view Multimatte')
        return lx.symbol.fTMOD_I0_ATTRHAUL
 
    def tmod_Initialize(self,vts,adjust,flags):
        '''
            This is called when the tool is activated. We use it to simply
            set the attribute that we hauling back to the default.
        '''
        adj_tool = lx.object.AdjustTool(adjust)
        adj_tool.SetFlt(0, 1.0)
 
    def tmod_Haul(self,index):
        '''
            Hauling is dependent on the direction of the haul. So a vertical
            haul can drive a different parameter to a horizontal haul. The
            direction of the haul is represented by an index, with 0
            representing horizontal and 1 representing vertical. The function
            simply returns the name of the attribute to drive, given it's index.
            As we only have one attribute, we'll set horizontal hauling to
            control it and vertical hauling to do nothing.
        '''
        if index == 0:
            return "size"
        else:
            return 0
 
'''
    "Blessing" the class promotes it to a fist class server. This basically
    means that modo will now recognize this plugin script as a tool plugin.
'''
lx.bless(Plane_Tool, "prim.plane")
            lx.eval('!!select.polygon remove type face 0')
            if lx.eval('!!query layerservice polys ? selected'):
                target = "face"
            else:
                target = "psubdiv"

            lx.eval('!!select.useSet extendedSel replace')
            lx.eval('!!poly.convert %s face toggle:false' % target)
            lx.eval('!!poly.align')
            lx.eval('!!select.drop polygon')

            if originalPolySel:
                lx.eval('!!select.useSet originalPolySel replace')
            lx.eval('!!select.deleteSet originalPolySel')
            lx.eval('!!select.deleteSet extendedSel')

            selMode(originalMode)

            if originalMode in ['vertex', 'edge', 'polygon']:
                lx.eval('!!select.drop %s' % originalMode)
                if originalSel:
                    lx.eval('!!select.useSet originalSel replace')

                lx.eval('!!select.deleteSet originalSel')

        except:
            pass


lx.bless(CMD_tabbyCat_tabKey, NAME_CMD_tabKey)
		if pane == None:
			return False

		custPane = lx.object.CustomPane(pane)

		if custPane.test() == False:
			return False

		# Get the parent QWidget
		parent = custPane.GetParent()
		parentWidget = lx.getQWidget(parent)

		# Check that it suceeds
		if parentWidget != None:
			layout = QGridLayout()
			layout.setContentsMargins(1,1,1,1)
			self.form = projectmanager.ProjectManager()
			layout.addWidget(self.form)
			parentWidget.setLayout(layout)
			return True

		return False


#----------------------------------------------------------------------------------------------------------------------
# BLESS THIS MESS!
lx.bless( ShowProjectManager, "pm.open" )
lx.bless( ExploreProjectFolder, "pm.exploreCurrent" )
lx.bless( ExploreSceneFolder, "pm.exploreSceneFolder" )
lx.bless( ProjectManager_CustomView, "ProjectManager" )
Beispiel #5
0
################################################################################

import lx
import lxifc
import lxu.command
import symfix


class SymFixCmd(lxu.command.BasicCommand):
    def __init__(self):
        lxu.command.BasicCommand.__init__(self)

    def cmd_Flags(self):
        return lx.symbol.fCMD_MODEL | lx.symbol.fCMD_UNDO

    def basic_Enable(self, msg):
        return True

    def cmd_Interact(self):
        pass

    def basic_Execute(self, msg, flags):
        reload(symfix)
        symfix.main()

    def cmd_Query(self, index, vaQuery):
        lx.notimpl()


lx.bless(SymFixCmd, "csp.symfix")
V0.1 Initial Release - 2017-02-20

"""

import babylondreams
import lx

from bd_tools import bd_blend_hierarchy

__author__ = "Alexander Kucera"
__copyright__ = "Copyright 2017, BabylonDreams - Alexander & Monika Kucera GbR"
__credits__ = ["Alexander Kucera"]
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Alexander Kucera"
__email__ = "*****@*****.**"
__status__ = "Development"


class CommandClass(babylondreams.CommanderClass):
    _commander_last_used = []

    def commander_execute(self, msg, flags):

        reload(bd_blend_hierarchy)

        bd_blend_hierarchy.main()


lx.bless(CommandClass, 'bd.blend_hierarchy')
        # Iterate all selected paths and add comment for each
        for path_idx in xrange(0, len(self.m_paths)):
            # path - path of command to modify
            path = self.m_paths[path_idx]
            # Store line count of old comment for restoring in undo
            self.m_line_counts_before[path_idx] = len(
                macro.node_for_path(path).user_comment_before)
            # Add # before each line in comment and append it
            for line in self.m_comment.split('\n'):
                macro.node_for_path(path).user_comment_before.append(line)

        self.finalize_command(macro)

    def undo_Reverse(self):
        macro = replay.Macro()
        # Iterate all selected indices and remove previously added comments
        for path_idx in xrange(0, len(self.m_paths)):
            # Get path of selected item
            path = self.m_paths[path_idx]
            # Get count of lines in comment before adding new ones
            line_count_before = self.m_line_counts_before[path_idx]
            # Cat comment to restore previous state
            macro.node_for_path(
                path).user_comment_before = macro.node_for_path(
                    path).user_comment_before[:line_count_before]

        self.finalize_command(macro)


lx.bless(CommandClass, 'replay.lineComment')
    def cmd_Interact(self):
        '''
        Boilerplate
        '''

    def cmd_Flags(self):
        '''
        Provide an undo context
        '''
        return lx.symbol.fCMD_MODEL | lx.symbol.fCMD_UNDO

    def basic_Execute(self, msg, flags):
        '''
        Display the pop-up search field.
        '''
        self.popup = Popup(self.dyna_String(0))

        # Move the dialog to the cursor's position
        self.popup.move( QCursor().pos() )

        # Using exec_() causes instabilities, so we'll use show() instead
        # and set the dialog as modal in its constructor.
        self.popup.show()


# Bless this mess!
parse_all_the_things()
lx.bless(CreateItem, "popup.createItem")
lx.bless(GetItem, "popup.getItem")

    def cmd_Interact(self):
        """
        This prevents bogus stack trace errors
        """
        pass

    def returnSafeString(self, sVal = None):
        """
        When this function is passed a string, it will attempt to strip most
        illegal characters and return a happy string
        """

        sVal = sVal.replace(' ', '_')

        illegalChars = ['^', '<', '>', '/', '\\', '{', '}', '[', ']',
                        '~', '`', '$', '.', '?', '%', '&', '@', '*',
                        '(', ')', '!', '+', '#', '\'', '\"', ':']

        if sVal:
            for i in illegalChars:
                if i in sVal:
                    sVal = sVal.replace(i, '_')

        # If you passed in only illegal characters, you have just ended up with an empty string
        if sVal:
            return sVal
        else:
            return None

lx.bless(RenameSel, "item.renameSel")
        # add = add to selection. We have a clean selection, and want to select
        # all masks.
        #
        # comSvc.ExecuteArgString:
        # Allows you to call a command.
        # This is similar to lx.eval, but allows you to edit extra stuff.
        # -1 = call with parent arguments. This is what would be edited most.
        # iCTAG_NULL = ?? I've never known.
        # last is the command.
        #
        # last selSvc:
        # drop anything that is selected (all the masks) after unlocking them.
        curScn = lxu.select.SceneSelection().current()
        scnSvc = lx.service.Scene()
        comSvc = lx.service.Command()
        selSvc = lx.service.Selection()
        
        selSvc.Drop(selSvc.LookupType(lx.symbol.sSELTYP_ITEM))                

        nMasks = curScn.ItemList(scnSvc.ItemTypeLookup(lx.symbol.sITYPE_MASK))
        for mask in nMasks:
            lxu.select.ItemSelection().select(mask.UniqueName(), add=True)

        comSvc.ExecuteArgString(-1, lx.symbol.iCTAG_NULL, 'shader.unlock')
        selSvc.Drop(selSvc.LookupType(lx.symbol.sSELTYP_ITEM))            
        
    def cmd_Interact(self):
        pass
    
lx.bless(UnlockAllGroupMasksCMD, 'unlock.GroupMasks')
Beispiel #11
0
            pass
            #custpane = lx.object.CustomPane(pane)
            # TODO: what state needs to be saved ?


        def customview_Cleanup(self, pane):
            try:
                self.customview_StoreState(pane)
            except RuntimeError, e:
                if e.message == "Internal C++ object (ShotgunWidget) already deleted.":
                    if hasattr(lx, "shotgun_widget"):
                        lx.shotgun_widget.destroy()


    log("blessing shotgun.eval")
    lx.bless(ShotgunCmd, "shotgun.eval")
    log("blessing shotgun.startup")
    lx.bless(ShotgunStartupCmd, "shotgun.startup")
    tags = {}
    try:
        tags = { lx.symbol.sCUSTOMVIEW_TYPE: "vpeditors SCED shotgun @shotgun.view@Shotgun@", }
    except:
        pass


    event_listener.register()

    if no_embedded_qt_mode():
        app = ModoApplication([])
        _shotgun_panel = ShotgunWidget()
        _shotgun_panel.show()
	def customview_Cleanup (self, pane):
		'''
		Close the viewport and shut down the listener.
		'''
		lx.out('LightBank closed -  removing Scene Item Listener...')
		lx.service.Listener().RemoveListener(self.com_listener)


class ShowLightBank ( lxu.command.BasicCommand ):
	'''
	Modo Command to display LightBank in a new window.
	'''

	def __init__(self):
		lxu.command.BasicCommand.__init__(self)

	def cmd_Interact(self):
		''' '''
		pass

	def basic_Execute(self, msg, flags):
		'''
		Display LightBank in a floating palette.
		'''
		lx.eval("layout.createOrClose lightBankCookie LightBankLayout width:400 height:600 class:normal title:{LightBank}")


# BLESS THIS MESS!
lx.bless(LightBank_CustomView, "LightBank")
lx.bless(ShowLightBank, "lightbank.show")
Beispiel #13
0
            by comparing the GUID that is being passed as an argument against
            the GUID of the interfaces that we know our Instance inherits from.
            As our Instance inherits from PackageInstance and ViewItem3D, we
            need to return True for both of them.
        '''
        return (lx.service.GUID().Compare(guid, lx.symbol.u_PACKAGEINSTANCE) == 0) or (lx.service.GUID().Compare(guid, lx.symbol.u_VIEWITEM3D) == 0)
        
    def cui_UIHints(self,channelName,hints):
        '''
            The UIHints method is provided by the ChannelUI interface that our
            Package class inherits from. This allows us to specify various
            hints for a channel, such as Min and Max. Ideally, we'd do this when
            creating the channel using the SetHints() method, however, that's
            currently impossible in Python.
        '''
        hints = lx.object.UIHints(hints)
        
        if channelName == CHAN_RADIUS:
            hints.MinFloat(0.0)
            hints.MaxFloat(10.0)
        elif channelName == CHAN_SIDES:
            hints.MinInt(3)
            hints.MaxInt(128)

'''
    Finally, bless the item package so that it is registered as a plugin inside
    of modo. As this is a package that is added to another item and not a full
    item in itself, we won't define a supertype.
'''
lx.bless(Package, PACKAGE_NAME)
			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 cmd_Query(self, index, vaQuery):
		lx.notimpl()


lx.bless(CmdPasteChannelsInSelectedRenderPass, "tila.pastechannelsinselectedrenderpass")

    pass

import modo

from bd_tools import bd_version_up
from bd_tools.var import *

__author__ = "Alexander Kucera"
__copyright__ = "Copyright 2017, BabylonDreams - Alexander & Monika Kucera GbR"
__credits__ = ["Alexander Kucera"]
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Alexander Kucera"
__email__ = "*****@*****.**"
__status__ = "Development"


class CommandClass(babylondreams.CommanderClass):
    _commander_last_used = []

    def commander_arguments(self):
        return [{'name': 'comment', 'label': "Comment", 'datatype': 'string'}]

    def commander_execute(self, msg, flags):
        arguments = self.commander_args()
        reload(bd_version_up)
        bd_version_up.main(comment=True, commentstring=arguments['comment'])


lx.bless(CommandClass, 'bd.version_up_comment')
Beispiel #16
0
                        "name": name,
                        "type": datatype,
                        "size": size
                    })
                else:
                    lx.throw(lx.result.NOTFOUND)

            else:
                lx.throw(lx.result.NOTFOUND)

        self.end_header = self.filehandle.tell()

        info = lx.object.LoaderInfo(loadInfo)
        info.SetClass(lx.symbol.u_SCENE)

        self.load_target = lx.object.SceneLoaderTarget()
        self.load_target.set(loadInfo)
        self.load_target.SetRootType(lx.symbol.sITYPE_MESH)

        return lx.result.OK  # Tell Modo we've recognized the file.


tags = {
    lx.symbol.sLOD_CLASSLIST: lx.symbol.a_SCENE,
    lx.symbol.sLOD_DOSPATTERN: "*.ply",
    lx.symbol.sLOD_MACPATTERN: "*.ply",
    lx.symbol.sSRV_USERNAME: "******"
}

lx.bless(PLYLoader, "ply_Loader", tags)
        def basic_Execute (self, msg, flags):
        	
        	'''
        		As the name suggests, the execute method is called
        		when the command is executed. We can at this point get
        		the value of any arguments and do what we need to do.
        		Success or failure is handled through an ILxMessage
        		object which can be initialized using the second
        		argument to the function.
        	'''
        	
        	message = lx.object.Message (msg)
        	
        	item_sel = lxu.select.ItemSelection ().current ()
        	chan_write = lx.object.ChannelWrite (self.scene.Channels (lx.symbol.s_ACTIONLAYER_EDIT, self.sel_svc.GetTime ())
        	
        	'''
        		Read the size argument. This is done by index, in the
        		order they were added to the command in the constructor.
        	'''
        	
        	if self.dyna_IsSet (0) != True:
			message.SetCode (lx.result.CMD_MISSING_ARGS)
        		return
		
		arg_value = self.attr_GetFlt(0)

		'''
			Loop through the items and set their size channel.
		'''

        	for item in item_sel:
        		if item.TestType (self.locator_type) == True:
        			channel = item.ChannelLookup (lx.symbol.sICHAN_LOCATOR_SIZE)
        			chan_write.Double (item, channel, size_arg)

	def cmd_Query (self, index, vaQuery):
		
		'''
			The query functions is called when a particular
			argument is queried. The index function argument
			is the index of the command argument that is being
			queried. the vaQuery is an ILxValueArray object
			that we use to return an array of values. If the
			values are mixed (for example a multiple selection),
			modo will return "(mixed)", otherwise it will return
			the value that we return in the value array.
		'''
		
		val_array = lx.object.ValueArray (vaQuery)
		
		item_sel = lxu.select.ItemSelection ().current ()
        	chan_read = self.scene.Channels (lx.symbol.s_ACTIONLAYER_EDIT, self.sel_svc.GetTime ()

		'''
			If the index doesn't match one of our queryable
			arguments, return early, because who knows what
			they're trying to query.
		'''
		
		if index != 0:
			return

		'''
			Loop through the items and get their size channel,
			add the value to the value array.
		'''

        	for item in item_sel:
        		if item.TestType (self.locator_type) == True:
        			channel = item.ChannelLookup (lx.symbol.sICHAN_LOCATOR_SIZE)
        			value = chan_read.Double (item, channel)
        			val_array.AddFloat (value)
        			
	def cmd_NotifyAddClient (self, argument, object):
        
        	'''
        		Add a single notifier to the command. This will
        		send disable events when the item selection changes.
        	'''
        
		self.notifier = self.not_svc.Spawn ("select.event", "item +d")
        	self.notifier.AddClient (object)
        
    	def cmd_NotifyRemoveClient (self, object):
        
        	'''
            		Remove the notifier.
        	'''
        
        	self.notifier.RemoveClient (object)

'''
	Bless the class, initializing the server.
'''
lx.bless (Command, SERVER_NAME)
Beispiel #18
0
        macro = replay.Macro()
        undo_svc = lx.service.Undo()

        if undo_svc.State() != lx.symbol.iUNDO_INVALID:
            # Execute primary command and store indices for undo
            self.m_prev_path, self.m_next_path = macro.run_next_line()
        else:
            # This means undo_Forward is executing second time and user doing redo
            # operations. In this case since redo of executed operation will do actual
            # job we only need to move primary node one step down.
            macro.node_for_path(self.m_next_path).selected = True
            macro.node_for_path(self.m_prev_path).selected = False
        macro.refresh_view()

        notifier = replay.Notifier()
        notifier.Notify(lx.symbol.fCMDNOTIFY_CHANGE_ALL)

    def undo_Reverse(self):
        macro = replay.Macro()
        # Undo of executed operation will revert the modifications
        # so we only need to move primary node one step up
        macro.node_for_path(self.m_prev_path).selected = True
        macro.node_for_path(self.m_next_path).selected = False

        macro.refresh_view()
        notifier = replay.Notifier()
        notifier.Notify(lx.symbol.fCMDNOTIFY_CHANGE_ALL)


lx.bless(CommandClass, 'replay.step')
    lx.eval('select.polygon remove type face 0')
    if lx.eval('query layerservice polys ? selected'):
      target = "face"
    else:
      target = "psubdiv"

    lx.eval('select.useSet extendedSel replace')
    lx.eval('poly.convert %s face toggle:false' % target)
    lx.eval('!poly.align')
    lx.eval('select.drop polygon')



    if originalPolySel:
      lx.eval('select.useSet originalPolySel replace')
    lx.eval('select.deleteSet originalPolySel')
    lx.eval('select.deleteSet extendedSel')

    selMode(originalMode)

    if originalMode in ['vertex','edge','polygon']:
      lx.eval('select.drop %s' % originalMode)
      if originalSel:
        lx.eval('select.useSet originalSel replace')

      lx.eval('select.deleteSet originalSel')



lx.bless(CMD_tabbyCat_tabKey, NAME_CMD_tabKey)
                            float(lines[morphMap[1] + 1 + i].split(" ")[2])
                        ])

            #Apply UV Maps
            for uvMap in uvMaps:
                uvm = geo.vmaps.addMap(lx.symbol.i_VMAP_TEXTUREUV, uvMap[0][0])
                count = 0
                for i in range(int(uvMap[0][1])):
                    line = lines[uvMap[1] + 1 + count]
                    split = line.split(":")
                    if len(
                            split
                    ) > 3:  #check the format to see if it has a point and poly classifier, determining with that, whether the uv is discontinuous or continuous
                        geo.polygons[int(split[2])].setUV(
                            (float(split[0].split(" ")[0]),
                             float(split[0].split(" ")[1])),
                            geo.vertices[int(split[4])], uvm)
                    else:
                        pass
                    count += 1

            geo.setMeshEdits()
        else:
            print "No Data File Available."

    def cmd_Query(self, index, vaQuery):
        lx.notimpl()


lx.bless(OD_PasteFromExternal, "OD_PasteFromExternal")
 
    def arg_UIValueHints(self, index):
        # create an instance of our pop-up list object passing it the
        # list of commands.
        if index == 0:
            return UnitsPopup(units)
 
    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):
            lx.eval('user.value {CmdMyPopUpCommand_val} {%s}' % self.dyna_String(0))
 
    def cmd_Query(self,index,vaQuery):
        # In the query method we need to retrieve the value we stored in the execute
        # method and add it to a ValueArray object to be returned by the query.
        va = lx.object.ValueArray()
        # Initialise the ValueArray
        va.set(vaQuery)
        if index == 0:
            # retrieve the value we stored earlier and add it to the ValueArray
            va.AddString(lx.eval('user.value {CmdMyPopUpCommand_val} ?'))
        return lx.result.OK
 
# bless() the command to register it as a plugin
lx.bless(CmdMyPopUpCommand, "choose.me")
Beispiel #22
0
import babylondreams
import lx

import modo

from bd_tools import bd_bake_camera
from bd_tools.var import *

__author__ = "Alexander Kucera"
__copyright__ = "Copyright 2017, BabylonDreams - Alexander & Monika Kucera GbR"
__credits__ = ["Alexander Kucera"]
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Alexander Kucera"
__email__ = "*****@*****.**"
__status__ = "Development"


class CommandClass(babylondreams.CommanderClass):
    _commander_last_used = []

    def commander_execute(self, msg, flags):
        arguments = self.commander_args()

        reload(bd_bake_camera)
        bd_bake_camera.main()


lx.bless(CommandClass, 'bd.bake_camera')
Beispiel #23
0
                    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 cmd_Query(self,index,vaQuery):
        # In the query method we need to retrieve the value we stored in the execute
        # method and add it to a ValueArray object to be returned by the query.
        va = lx.object.ValueArray()
        # Initialise the ValueArray
        va.set(vaQuery)
        if index == 0:
            # retrieve the value we stored earlier and add it to the ValueArray
            va.AddString(self.dyna_String(0))
        return lx.result.OK

# bless() the command to register it as a plugin
lx.bless(snippetsPopupCmd, "modder.snippetsPopup")
Beispiel #24
0
            {
                'name': 'mode',
                'datatype': 'boolean',
                'flags': ['query', 'optional']
            }
        ]

    def commander_execute(self, msg, flags):
        mode = not self.commander_arg_value(0)

        fusion_items = modo.Scene().items('sdf.item')

        if mode is None:
            mode = True
            for i in fusion_items:
                if i.channel('FusionOn').get():
                    mode = False
                    break

        for i in fusion_items:
            i.channel('FusionOn').set(mode)

    def commander_query(self, index):
        strip_items = modo.Scene().items('sdf.item')
        for i in strip_items:
            if i.channel('FusionOn').get():
                return False
        return True

lx.bless(CommandClass, 'noodles.toggleFusion')
    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)

lx.bless(copyNamesToClipboard, 'modo.copyNamesToClipboard')
#!/usr/bin/env python
# coding=utf-8
u"""
stu.renameコマンドを作成する
"""
from __future__ import absolute_import, division, print_function

import lx
import lxu.command


class NodeRename(lxu.command.BasicCommand):
    def basic_Execute(self, msg, flags):
        cmd = [
            u"layout.createOrClose", u"cookie:COOKIE_stuRename",
            u"layout:stuRenameLayout", u'title:"stuRename"', u"width:300",
            u"height:300", u"persistent:1", u"style:palette"
        ]
        lx.eval(" ".join(cmd))


lx.bless(NodeRename, u"stu.node.rename")
            bbox = boundingBoxMax(bboxes)
            currentSize = bbox[1][0] - bbox[0][0]
            ratio = targetSize / currentSize

            originalRef = lx.eval("item.refSystem ?")

            lx.eval("item.refSystem")
            lx.eval("select.typeFrom polygon;edge;vertex;item;pivot;center;ptag true")
            lx.eval("tool.set actr.origin on")

            lx.eval("tool.set TransformScale on")
            lx.eval("tool.attr xfrm.transform SX %s" % str(float(ratio)))
            lx.eval("tool.attr xfrm.transform SY %s" % str(float(ratio)))
            lx.eval("tool.attr xfrm.transform SZ %s" % str(float(ratio)))
            lx.eval("tool.apply")
            lx.eval("tool.set TransformScale off")

            if originalRef:
                lx.eval("item.refSystem {%s}" % originalRef)
            else:
                lx.eval("item.refSystem {}")

            lx.eval("tool.clearTask axis")
            lx.eval("select.typeFrom item;pivot;center;edge;polygon;vertex;ptag true")

        except:
            traceback.print_exc()


lx.bless(CMD_kelvin, NAME_CMD)
													averageNormal = self.vectorAdd(averageNormal, vN)
													proceededPolygons = proceededPolygons + (p,)
													i += 1

								i = float(i)

								averageNormal = self.vectorScalarMultiply(averageNormal , 1/i)
								#averageNormal = self.vectorNormalize(averageNormal)
								vMaps = item.geometry.vmaps

								for v in selectedVertices:
									normalMap.setNormal(averageNormal, v)
								item.geometry.setMeshEdits(lx.symbol.f_MESHEDIT_MAP_OTHER)

						# Item Mode
						else:
							self.init_message('error', 'Component mode Needed', 'Need to be in component mode')

						n += 1
			else:
				self.init_message('error', 'Select a mesh first', 'Select a mesh first.')
		except:
			lx.out(traceback.format_exc())

	def cmd_Query(self, index, vaQuery):
		lx.notimpl()


lx.bless(CmdFlattenNormals, "tila.flattennormals")

        lxu.command.BasicCommand.__init__(self)

    def cmd_Interact(self):
        '''
        Boilerplate
        '''

    def cmd_Flags(self):
        '''
        Provide an undo context
        '''
        return lx.symbol.fCMD_MODEL | lx.symbol.fCMD_UNDO

    def basic_Execute(self, msg, flags):
        '''
        Display the pop-up search field.
        '''
        self.popup = Popup()

        # Move the dialog to the cursor's position
        self.popup.move( QCursor().pos() )

        # Using exec_() causes instabilities, so we'll use show() instead
        # and set the dialog as modal in its constructor.
        self.popup.show()


# Bless this mess!
lx.bless(GetMaterial, "popup.getMaterial")

    def commander_execute(self, msg, flags):
        paste(tagger.MATERIAL, self.commander_arg_value(0))


class PastePartCommandClass(tagger.CommanderClass):
    #_commander_default_values = []

    def commander_arguments(self):
        return [_scope_popup]

    def commander_execute(self, msg, flags):
        paste(tagger.PART, self.commander_arg_value(0))


class PastePickCommandClass(tagger.CommanderClass):
    #_commander_default_values = []

    def commander_arguments(self):
        return [_scope_popup]

    def commander_execute(self, msg, flags):
        paste(tagger.PICK, self.commander_arg_value(0))


lx.bless(CopyCommandClass, tagger.CMD_PTAG_COPY)
lx.bless(CopyMaskCommandClass, tagger.CMD_PTAG_COPYMASK)
lx.bless(PasteDialogCommandClass, tagger.CMD_PTAG_PASTE_DIALOG)
lx.bless(PasteMaterialCommandClass, tagger.CMD_PTAG_PASTE_MAT)
lx.bless(PastePartCommandClass, tagger.CMD_PTAG_PASTE_PART)
lx.bless(PastePickCommandClass, tagger.CMD_PTAG_PASTE_SET)
				channel.set(p.getValue(channel), action=new_passe.name)

			new_passe.active = False
			p.active = False

		new_rpg.deselect()

	def duplicatePresetGroup(self, presetGrp):
		new_presetGrp = self.scn.addGroup(presetGrp.name, compatible_type['PRESET'])
		new_presetGrp.select()

		for channel in presetGrp.groupChannels:
			new_presetGrp.addChannel(channel)

		new_presetGrp.deselect()

	def duplicateChannelGroup(self, chanGrp):
		new_chanGrp = self.scn.addGroup(chanGrp.name, compatible_type['CHANSET'])
		new_chanGrp.select()

		for channel in chanGrp.groupChannels:
			new_chanGrp.addChannel(channel)

		new_chanGrp.deselect()

	def cmd_Query(self, index, vaQuery):
		lx.notimpl()


lx.bless(CmdMyCustomCommand, "tila.duplicateGroup")
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Alexander Kucera"
__email__ = "*****@*****.**"
__status__ = "Development"


class CommandClass(babylondreams.CommanderClass):
    _commander_last_used = []

    def commander_arguments(self):
        return [
            {
                'name': 'draw_style',
                'datatype': 'string',
                'default': 'custom',
                'values_list_type': 'popup',
                'values_list': [('custom', 'Bounding Box'),
                                ('default', 'Default')]
            },
        ]

    def commander_execute(self, msg, flags):
        arguments = self.commander_args()

        reload(bd_bbox_toggle)
        bd_bbox_toggle.main(state=arguments['draw_style'])


lx.bless(CommandClass, 'bd.bbox_toggle')
Beispiel #33
0
		parentWidget.setLayout(layout)

class ShowCustomView(lxu.command.BasicCommand):
	'''
	MODO command to display the custom viewport.
	'''
	def __init__(self):
		lxu.command.BasicCommand.__init__(self)

		# define path as a require string parameter
		self.dyna_Add('Script Path', lx.symbol.sTYPE_STRING)

	def basic_Execute(self, msg, flags):
		'''
		Displays PysideWrapper in a floating palette.
		'''
		scriptPath = self.dyna_String(0)
		if not scriptPath:
			return False

		global moduleName
		# add root directory to PATH
		sys.path.insert(0, os.path.dirname(scriptPath))
		# turns /foo/bar/someScript.py into someScript
		moduleName, ext = os.path.splitext(os.path.basename(scriptPath))

		lx.eval('layout.createOrClose pysideLaunchCookie pysideLaunchLayout width:600 height:600 class:normal title:{{{0}}}'.format(moduleName))

lx.bless(PysideWrapper, 'PysideWrapper')
lx.bless(ShowCustomView, 'pyside.launch')
class CommandClass(babylondreams.CommanderClass):
    _commander_last_used = []

    def commander_arguments(self):
        return [
            {
                'name': 'new_instance_source',
                'datatype': 'string',
                'default': 'newMesh',
                'values_list_type': 'sPresetText',
                'values_list': self.list_meshes
            },
        ]

    def list_meshes(self):
        scene = modo.Scene()
        meshes = []
        for item in scene.items(itype='mesh', superType=True):
            meshes.append(item.name)
        return meshes

    def commander_execute(self, msg, flags):

        new_source = self.commander_arg_value(0)

        reload(bd_instance_reroute)
        bd_instance_reroute.main(new_source)


lx.bless(CommandClass, 'bd.instance_reroute')
    def cmd_Flags(self):
        return lx.symbol.fCMD_MODEL | lx.symbol.fCMD_UNDO

    def basic_Enable(self, msg):
        return True

    def cmd_Interact(self):
        pass

    def basic_Execute(self, msg, flags):
        reload(opGen)
        reload(opGen.opSetup)


        #   Create a new layer to hold the ocean plane and rename the layer
        lx.eval('layer.new')
        lx.eval('item.name oceanPlane mesh')

        #   Create the basic plane
        opgs.create_basic_plane(50,50,100,100)



    #def cmd_Query(self, index, vaQuery):
    #    lx.notimpl()


lx.bless(CmdOceanPlaneGenerator, "op.generate")

			
			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 cmd_Query(self, index, vaQuery):
		lx.notimpl()


lx.bless(CmdApplyMorphMap, "tila.applyMorphMap")
        if s:
            return s
        lx.notimpl()

    def basic_PreExecute(self, msg):
        """Pre-Execution: failure is trapped by the message object."""
        pass

    def cmd_PreExecute(self):
        try:
            self.basic_PreExecute(self._msg)
        except:
            lx.outEx("basic_PreExecute failed")
            self._msg.SetCode(lx.result.FAILED)
            raise  # outEx doesn't work -- only way to see the error is to raise it again

    def basic_Execute(self, msg, flags):
        """Execution: failure is trapped by the message object."""
        lx.notimpl()

    def cmd_Execute(self, flags):
        try:
            self.basic_Execute(self._msg, flags)
        except:
            lx.outEx("basic_Execute failed")
            self._msg.SetCode(lx.result.FAILED)
            raise  # outEx doesn't work -- only way to see the error is to raise it again


lx.bless(myGreatCommand, "mecco.myGreatCommand")
        '''
            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 cmd_Query (self, index, vaQuery):
        '''
            This function is called when the command is queried. We'll read the
            value of the path argument and store it in the global variable, so
            that it can be used when building the popup.
        '''
        
        global path_argument_value
        
        if self.dyna_IsSet (0):
            path_argument_value = self.dyna_String (0)
        
        return
 
'''
    Finally, we bless the Command class. This promotes it to be a first class
    plugin within modo.
'''

lx.bless (Command, SERVER_NAME)
Beispiel #39
0
import babylondreams


class CommandClass(babylondreams.CommanderClass):
    _commander_default_values = []

    def commander_arguments(self):
        return [{
            'name':
            'blend_type',
            'label':
            'Blend Type',
            'datatype':
            'string',
            'default':
            lx.eval("user.value bd.blend_type_pref ?"),
            'values_list_type':
            'popup',
            'values_list': [('tranAmount', 'Transparency'),
                            ('dissolve', 'Dissolve')],
            'flags': ['query']
        }]

    def commander_execute(self, msg, flags):
        lx.eval("user.value bd.blend_type_pref %s" %
                self.commander_arg_value(0))
        lx.out("Set Blend Type to ", self.commander_arg_value(1))


lx.bless(CommandClass, 'bd.prefs_blend_type')
Beispiel #40
0
        _island_enumerator = 0
        island_counter = IslandCounterClass(args, [lx.symbol.f_MESHEDIT_POL_TAGS])
        island_counter.do_mesh_read()

        if _island_enumerator > tagger.MAX_PTAG_ISLANDS:
            try:
                modo.dialogs.alert(
                    tagger.DIALOGS_TOO_MANY_ISLANDS[0],
                    tagger.DIALOGS_TOO_MANY_ISLANDS[1] % (tagger.MAX_PTAG_ISLANDS, _island_enumerator)
                )
            except:
                pass

        else:
            _island_enumerator = 0
            mesh_editor = MeshEditorClass(args, [lx.symbol.f_MESHEDIT_POL_TAGS])
            mesh_editor.do_mesh_edit()

            try:
                modo.dialogs.alert(
                    tagger.DIALOGS_TAGGED_POLY_ISLANDS_COUNT[0],
                    tagger.DIALOGS_TAGGED_POLY_ISLANDS_COUNT[1] % (mesh_editor.poly_count, _island_enumerator)
                    )
            except:
                pass

        notifier = tagger.Notifier()
        notifier.Notify(lx.symbol.fCMDNOTIFY_DATATYPE)

lx.bless(CommandClass, CMD_NAME)
			if self.dyna_IsSet(1):
				self.cleanMorph = self.dyna_Bool(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 cmd_Query(self, index, vaQuery):
		lx.notimpl()


lx.bless(CmdApplyCompensateMorphMap, "tila.applyCompensateMorphMap")
#python

import lx, lxu

NAME_CMD = "komodo.symbolsearch"

class CMD_DUI(lxu.command.BasicCommand):
  
  def __init__(self):
    lxu.command.BasicCommand.__init__(self)
    self.dyna_Add('search', lx.symbol.sTYPE_STRING)
  
  def basic_Execute(self, msg, flags):
    text = self.dyna_String(0)
    
    # Create a dict of all symbols and their values
    dict = {str( getattr( lx.symbol, i) ) : i for i in dir(lx.symbol) }
    # Filter for keyword
    results = [(k, v) for k, v in dict.items() if (
        text.lower() in k.lower() or
        text.lower() in v.lower()
      )]
    for r in results:
        lx.out('%s\n%s' % (r[1],r[0]))

lx.bless(CMD_DUI, NAME_CMD)
		# convert to PySide QWidget
		widget = lx.getQWidget(parent)

		# Check that it succeeds
		if widget is not None:

			# Here we create a new layout and add a button to it
			layout = PySide.QtGui.QVBoxLayout()
			exportGrpButton = QPushButton("Export material group")
			createGrpButton = QPushButton("Create material group")
		# Increasing the font size for the button
		# f = exportGrpButton.font()
		# f.setPointSize(30)
		# exportGrpButton.setFont(f)

		# This connects the "clicked" signal of the button to the onClicked function above
		exportGrpButton.clicked.connect(exportMatGrp)
		createGrpButton.clicked.connect(createMatGrp)

		# Adds the button to our layout and adds the layout to our parent widget
		layout.addWidget(exportGrpButton)
		layout.addWidget(createGrpButton)
		layout.setContentsMargins(2, 2, 2, 2)
		widget.setLayout(layout)
		return True

		return False

# Finally, register the new custom view server to Modo
lx.bless(qt_test01, "qt_test01")
Beispiel #44
0
# python

import lx, lxifc, modo, replay
import pyperclip
"""A simple example of a blessed MODO command using the commander module.
https://github.com/adamohern/commander for details"""


class CommandClass(replay.commander.CommanderClass):
    """Deletes the currently-selected command from the `Macro()` object."""
    def commander_execute(self, msg, flags):

        lxm = replay.Macro().render_LXM_selected()
        pyperclip.copy(lxm)

    def basic_Enable(self, msg):
        if lx.eval('replay.record query:?'):
            return False

        if len(replay.Macro().selected_descendants) == 0:
            return False

        for command in replay.Macro().selected_descendants:
            if not command.can_copy():
                return False

        return True


lx.bless(CommandClass, 'replay.clipboardCopy')
		if not point_back.test ():
			return

		meshmap_fore = lx.object.MeshMap (mesh_fore.MeshMapAccessor ())
		meshmap_back = lx.object.MeshMap (mesh_back.MeshMapAccessor ())
		if not meshmap_fore.test () or not meshmap_back.test ():
			return

		# Get a list of the weight maps shared by the foreground and the background meshes.
		visitor = ListWeightMaps (meshmap_fore, meshmap_back)
		meshmap_fore.FilterByType (lx.symbol.i_VMAP_WEIGHT)
		meshmap_fore.Enumerate (lx.symbol.iMARK_ANY, visitor, 0)
		meshmap_IDs = tuple(visitor.meshmap_IDs)
		meshmap_fore.FilterByType (0)

		# Go through each point and copy the values of each weight map from the background mesh to the foreground mesh.
		visitor = CopyWeights (point_fore, point_back, polygon_back, meshmap_IDs)
		point_fore.Enumerate (lx.symbol.iMARK_ANY, visitor, 0)

		# Apply changes.
		layer_scan.SetMeshChange (primary_layer_index, lx.symbol.f_MESHEDIT_MAP_OTHER | lx.symbol.f_MESHEDIT_MAP_CONTINUITY)
		
		layer_scan.Apply ()

		# except:
		# 	lx.out(traceback.format_exc())

#________________________________________________________________________________________ BLESS FUNCTION AS MODO COMMAND

lx.bless (CopyWeights_Cmd, 'ffr.copyweights')
Beispiel #46
0
        def basic_Execute (self, msg, flags):
        	
        	'''
        		As the name suggests, the execute method is called
        		when the command is executed. We can at this point get
        		the value of any arguments and do what we need to do.
        		Success or failure is handled through an ILxMessage
        		object which can be initialized using the second
        		argument to the function.
        	'''
        	
        	message = lx.object.Message (msg)
        	
        	item_sel = lxu.select.ItemSelection ().current ()
        	chan_write = lx.object.ChannelWrite (self.scene.Channels (lx.symbol.s_ACTIONLAYER_EDIT, self.sel_svc.GetTime ())
        	
        	'''
        		Read the size argument. This is done by index, in the
        		order they were added to the command in the constructor.
        	'''
        	
        	if self.dyna_IsSet (0) != True:
			message.SetCode (lx.result.CMD_MISSING_ARGS)
        		return
		
		arg_value = self.attr_GetFlt(0)

		'''
			Loop through the items and set their size channel.
		'''

        	for item in item_sel:
        		if item.TestType (self.locator_type) == True:
        			channel = item.ChannelLookup (lx.symbol.sICHAN_LOCATOR_SIZE)
        			chan_write.Double (item, channel, size_arg)

	def cmd_Query (self, index, vaQuery):
		
		'''
			The query functions is called when a particular
			argument is queried. The index function argument
			is the index of the command argument that is being
			queried. the vaQuery is an ILxValueArray object
			that we use to return an array of values. If the
			values are mixed (for example a multiple selection),
			modo will return "(mixed)", otherwise it will return
			the value that we return in the value array.
		'''
		
		val_array = lx.object.ValueArray (vaQuery)
		
		item_sel = lxu.select.ItemSelection ().current ()
        	chan_read = self.scene.Channels (lx.symbol.s_ACTIONLAYER_EDIT, self.sel_svc.GetTime ()

		'''
			If the index doesn't match one of our queryable
			arguments, return early, because who knows what
			they're trying to query.
		'''
		
		if index != 0:
			return

		'''
			Loop through the items and get their size channel,
			add the value to the value array.
		'''

        	for item in item_sel:
        		if item.TestType (self.locator_type) == True:
        			channel = item.ChannelLookup (lx.symbol.sICHAN_LOCATOR_SIZE)
        			value = chan_read.Double (item, channel)
        			val_array.AddFloat (value)
        			
	def cmd_NotifyAddClient (self, argument, object):
        
        	'''
        		Add a single notifier to the command. This will
        		send disable events when the item selection changes.
        	'''
        
		self.notifier = self.not_svc.Spawn ("select.event", "item +d")
        	self.notifier.AddClient (object)
        
    	def cmd_NotifyRemoveClient (self, object):
        
        	'''
            		Remove the notifier.
        	'''
        
        	self.notifier.RemoveClient (object)

'''
	Bless the class, initializing the server.
'''
lx.bless (Command, SERVER_NAME)
Beispiel #47
0
                'datatype': 'boolean',
                'label': i[1],
                'default': True
            })

        return args

    def commander_execute(self, msg, flags):
        args = self.commander_args()

        if True not in [v for k, v in args.iteritems()]:
            modo.dialogs.alert("Abort", "Nothing was selected. Nothing will be deleted.")
            return

        if modo.dialogs.yesNo("Confirmation", "Are you sure you want to permanently delete your saved preferences?") == "yes":

            clearCmd = 'lifesaver.clearPrefs'
            for i in lifesaver.KEEPERS:
                clearCmd += " " + str(lx.eval('lifesaver.preference %s ?' % i[3]))

            lx.eval(clearCmd)

            modo.dialogs.alert("Preferences Deleted", "Backup configs deleted. Changes take effect the next time MODO restarts.")

        else:
            modo.dialogs.alert("Abort", "Preferences reset aborted. Nothing will be deleted.")
            return


lx.bless(ResetPrefsCommandClass, 'lifesaver.resetPrefsSafety')
Beispiel #48
0
 
                if point_dist == 0:
                    continue
 
                scale = target_dist / point_dist
                point_newPos = ((point_pos[0]*scale),(point_pos[1]*scale),(point_pos[2]*scale))
 
                '''
                    Now that we have calculated the new position, we want to set
                    the point position on the mesh.
                '''
                point_loc.SetPos(point_newPos)
 
            '''
                Before we move on to the next layer, we need to tell modo that we
                have made edits to this mesh.
            '''
            layer_scan.SetMeshChange(n, lx.symbol.f_MESHEDIT_POINTS)
 
        '''
            Finally, we need to call apply on the LayerScan interface. This tells
            modo to perform all the mesh edits.
        '''
        layer_scan.Apply()
 
'''
    "Blessing" the class promotes it to a fist class server. This basically
    means that modo will now recognize this plugin script as a command plugin.
'''
lx.bless(Spherize_Cmd, "layer.spherize")
Beispiel #49
0

class CommandClass(mikalais_config_cit.CommanderClass):
    _commander_last_used = []

    def commander_arguments(self):
        return [{
            'name': 'dish1',
            'datatype': 'string',
            'label': 'First Dish',
            'default': 'bacon',
            'values_list_type': 'popup',
            'values_list': ['bacon', 'quinoa']
        }, {
            'name': 'dish2',
            'datatype': 'string',
            'label': 'Second Dish',
            'default': 'eggs',
            'values_list_type': 'sPresetText',
            'values_list': ['eggs', 'kale']
        }]

    def commander_execute(self, msg, flags):
        dish1 = self.commander_arg_value(0)
        dish2 = self.commander_arg_value(1)

        modo.dialogs.alert("breakfast", ' and '.join([dish1, dish2]))


lx.bless(CommandClass, 'mikalais_config_cit.breakfast')
Beispiel #50
0
from bd_tools import bd_update_render_paths
from bd_tools.var import *

__author__ = "Alexander Kucera"
__copyright__ = "Copyright 2017, BabylonDreams - Alexander & Monika Kucera GbR"
__credits__ = ["Alexander Kucera"]
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Alexander Kucera"
__email__ = "*****@*****.**"
__status__ = "Development"


class CommandClass(babylondreams.CommanderClass):
    _commander_last_used = []

    #def commander_arguments(self):
    #    return [
    #         arg_commander
    #    ]

    def commander_execute(self, msg, flags):
        #arguments = self.commander_args()

        reload(bd_update_render_paths)
        bd_update_render_paths.main()


lx.bless(CommandClass, 'bd.update_render_paths')
Beispiel #51
0
import lx

import cs_cry_export.export_selected as export_selected
from cs_cry_export.commander import CommanderClass


class ExportSelected(CommanderClass):
    def commander_execute(self, msg, flags):
        reload(export_selected)
        export_selected.main()


lx.bless(ExportSelected, "cs_cry_export.export")
Beispiel #52
0
    def basic_Execute(self, msg, flags):

        if not self.dyna_IsSet(0):
            format = "win32"

        format = self.dyna_String(0, "")
        unix_path = "/Volumes/ProjectsRaid/WorkingProjects"
        win_path = "Z:\AzureSync\CloudComputing\WorkingProjects"

        scene = modo.Scene()

        for i in scene.iterItemsFast('renderOutput'):
            filename = i.channel('filename').get()

            if format == "win32":
                filename = filename.replace(unix_path, win_path)
                filename = filename.replace('/', '\\')
                return filename
            elif format == "darwin":
                filename = filename.replace(win_path, unix_path)
                filename = filename.replace('\\', '/')

            i.channel('filename').set(filename)

        else:
            print("ERROR no valid OS given for path transform")


lx.bless(MyCommand_Cmd, 'bd.format_filename')
Beispiel #53
0
    def cmd_Flags (self):
	
		#Command is undoable
        return lx.symbol.fCMD_MODEL | lx.symbol.fCMD_UNDO
		
    def cmd_DialogInit (self):
	
        #Set default argument values
        self.attr_SetFlt(0, 1.0)
        self.attr_SetFlt(1, 1.0)
        
    def CMD_EXE(self, msg, flags):
	
		#Get arguments and assign
		eagleScale = self.dyna_Float(0, 1.0)
		barrelScale = self.dyna_Float(1, 1.0)
		
		#Run the script
		lx.eval("@idiot.py %s %s" % (eagleScale,barrelScale))
		
    def basic_Execute(self, msg, flags):
        try:
            self.CMD_EXE(msg, flags)
        except Exception:
            lx.out(traceback.format_exc())
		
    def basic_Enable(self,msg):
        return True
        
lx.bless(eagle, "mecco.idiot")
Beispiel #54
0
import lx

import cs_cry_export.create_crymat_from_selection as create_crymat
from cs_cry_export.commander import CommanderClass


class CreateCryMatFromSelection(CommanderClass):
    def commander_execute(self, msg, flags):
        reload(create_crymat)
        create_crymat.main()


lx.bless(CreateCryMatFromSelection,
         "cs_cry_export.create_crymat_from_selection")
Beispiel #55
0
        self.masterList[event.__peekobj__()] = event

    def noti_RemoveClient(self, event):
        '''
        Removes event from masterlist

        Args:
            event (???): event to be removed

        Returns:
            None
        '''
        del self.masterList[event.__peekobj__()]

    def Notify(self, flags):
        '''
        Fire each event in masterlist with given flags

        Args:
            flags (???): event flags

        Returns:
            None
        '''
        for event in self.masterList:
            evt = lx.object.CommandEvent(self.masterList[event])
            evt.Event(flags)


lx.bless(Notifier, "replay.notifier")
									if p not in proceededPolygons:
										normal = p.normal
										if self.areaWeighting:
											normal = self.vectorScalarMultiply(normal, p.area)
										averageNormal = self.vectorAdd(averageNormal, normal)
										proceededPolygons = proceededPolygons + (p,)
										i += 1
								i = float(i)

								averageNormal = self.vectorScalarMultiply(averageNormal , 1/i)
								normalMap.setNormal(averageNormal, v)

							item.geometry.setMeshEdits(lx.symbol.f_MESHEDIT_MAP_OTHER)

						# Item Mode
						else:
							self.init_message('error', 'Component mode Needed', 'Need to be in component mode')

						n += 1
			else:
				self.init_message('error', 'Select a mesh first', 'Select a mesh first.')
		except:
			lx.out(traceback.format_exc())

	def cmd_Query(self, index, vaQuery):
		lx.notimpl()


lx.bless(CmdAverageNormals, "tila.averagenormals")

                elif shape == "circle":

                    #customize locator
                    lx.eval('item.channel locator$drawShape custom')
                    lx.eval('item.channel locator$isStyle replace')
                    lx.eval('item.channel locator$isShape %s' % shape)
                    lx.eval('item.help add label "%s"' % label)
                    lx.eval('item.channel locator$isSolid %s' % solid)
                    lx.eval('item.channel locator$isAlign %s' % align)
                    lx.eval('item.channel locator$isAxis %s' % axis)

                    lx.eval('item.channel locator$isRadius %f' % radius)

                    lx.eval('item.draw add locator')
                    lx.eval('item.channel locator$wireOptions user')
                    lx.eval('item.channel locator$wireColor {%s}' % wcolor)

                    lx.eval('item.channel locator$fillOptions user')
                    lx.eval('item.channel locator$fillColor {%s}' % fcolor)

                    #switch back to vert mode for next vert in list
                    lx.eval('select.typeFrom vertex')

        except:
            lx.out(traceback.format_exc())


#This final command registers it as a plug in
lx.bless(Command, "pp.LocatorDrop")
Beispiel #58
0
                            uvs.append([
                                geo.polygons[p].getUV(vert, uvMap), p,
                                vert.index
                            ])
                    f.write("UV:" + uvMap.name + ":" + str(len(uvs)) + "\n")
                    for uv in uvs:
                        f.write(
                            str(uv[0][0]) + " " + str(uv[0][1]) + ":PLY:" +
                            str(uv[1]) + ":PNT:" + str(uv[2]) + "\n")

                #close File
                f.close()
        else:
            modo.dialogs.alert(
                "No Mesh Selected",
                "You need to select the mesh Item you want to copy", "info")

        if fusion == 1:
            #delete converted item
            scene.removeItems(scene.selected[0])
            #select the duplicated meshfusion item
            x = scene.select(itemname)
            #change name of of the duplicate to the original meshfusion name
            scene.selected[0].SetName(itemname)

    def cmd_Query(self, index, vaQuery):
        lx.notimpl()


lx.bless(OD_CopyToExternal, "OD_CopyToExternal")
# I've no idea what any of this means,
# but apparently it needs to be there.
class modderNotifier(lxifc.Notifier,lxifc.CommandEvent):
    masterList = {}
    def noti_Name(self):
        return NAME_NOTIFIER
    def noti_AddClient(self,event):
        self.masterList[event.__peekobj__()] = event
    def noti_RemoveClient(self,event):
        del self.masterList[event.__peekobj__()]
    def Notify(self, flags):
        for event in self.masterList:
            evt = lx.object.CommandEvent(self.masterList[event])
            evt.Event(flags)

lx.bless(modderNotifier, NAME_NOTIFIER)


# Manual update command.
class cmd_modderNotify(lxu.command.BasicCommand):
    def __init__(self):
        lxu.command.BasicCommand.__init__(self)
    def basic_Execute(self, msg, flags):
        # We get an instance of the notifier,
        # and then we call its Notify method,
        # telling it to update everything.
        notifier = modderNotifier()
        notifier.Notify(lx.symbol.fCMDNOTIFY_CHANGE_ALL)
    def cmd_Flags(self):
        # fCMD_UI since it's a UI command, and fCMD_INTERNAL
        # to prevent it from appearing in the command list.