Rebuild Curve

From The Foundry MODO SDK wiki
Jump to: navigation, search

This example shows how to create a command which can read curve attributes. It is made up of the command itself, as well as a visitor object which we use to scan a mesh layer for curve polygons.

import lx
import lxu.command
import lxifc
from math import floor
def dSqr(vec1, vec2):
    '''Quick function to get the distance squared between two points'''
    dist = 0.0
    for i in range(3):
        dist += (vec2[i] - vec1[i])**2
    return dist
class CurveFinder(lxifc.Visitor):
    '''This visitor object will scan through selected polygons and
    create a dictionary of those polygons who are curves.  The ID of the
    polygon will be the key, and the value will be the position or its root
    vertex.  Later, we'll compare this position to the position of curve
    objects we get to make sure we're only affecting the curves the user intends.'''
    def __init__(self, polyAccessor, pointAccessor):
        self.poly = polyAccessor
        self.point = pointAccessor
        self.curves = {}
    def vis_Evaluate(self):
        if self.poly.Type() == lx.symbol.iPTYP_CURVE:
            p = self.poly.VertexByIndex(0)
            pos = self.point.Pos()
            ID = self.poly.ID()
            self.curves[ID] = pos
class CurvePoints(lxu.command.BasicCommand):
    def __init__(self):
        '''After initializing the command, arguments are added one by one.  These
        arguments can then be referenced later by the order they were added, so
        the first argument will be index 0, the second index 1, etc.'''
        self.dyna_Add('mode', lx.symbol.sTYPE_BOOLEAN)
        self.dyna_Add('remove', lx.symbol.sTYPE_BOOLEAN)
        self.dyna_Add('count', lx.symbol.sTYPE_INTEGER)
        self.basic_SetFlags(2, lx.symbol.fCMDARG_OPTIONAL)
        self.dyna_Add('distance', lx.symbol.sTYPE_DISTANCE)
        self.basic_SetFlags(3, lx.symbol.fCMDARG_OPTIONAL)
        '''Adding a argument requires an internal string name for the argument, and
        a type for the argument.  By default all arguments are required, but we can
        use the basic_SetFlags method to change that if we need to'''
    def fire(self, CMD):
        '''Call commands without lx.eval'''
        lx.service.Command().ExecuteArgString(-1, lx.symbol.iCTAG_NULL, CMD)
    def cmd_ArgUserName(self,index):
        '''This sets the user name for the argument of a given index.  Ideally, these
        user names should exist in a message table inside of a config, but for this
        example it's not really all that important'''
        argNames = ['Use Spacing Distance', 'Remove Original Curve', 
                    'Point Count', 'Point Spacing']
        return argNames[index]
    def cmd_UserName(self):
        '''This sets the user name for the command itself.  Again, we should 
        ideally use a message table, but we will just use a string for simplicity'''
        return 'Rebuild Curve'        
    def cmd_DialogInit(self):
        '''If the user doesn't provide all required arguments, modo opens a dialog
        to ask for them.  When this happens, the cmd_DialogInit is called which 
        allows us to set default values for our the command arguments'''
        self.attr_SetInt(0, 0)
        self.attr_SetInt(1, 1)
        self.attr_SetInt(2, 10)
        self.attr_SetFlt(3, .05)
    def cmd_ArgEnable(self,arg):
        '''When the command dialog opens and when the user interacts with it,
        modo calls this method for each of our arguments.  That gives us a chance
        to read what the current values for arguments are, and choose if we need
        to disable an argument'''        
        if self.attr_GetInt(0) and arg == 2:
        elif not self.attr_GetInt(0) and arg == 3:
        return lx.symbol.e_OK
    def cmd_Flags(self):
        '''cmd_Flags tells modo what kind of command we have.  Since we're changing
        the state of the scene by altering geometry, we need to make this an undoable
        return lx.symbol.fCMD_MODEL | lx.symbol.fCMD_UNDO
    def getCurve(self, layerScan):
        '''For organization, the command is split into two parts.  This method grabs
        a curve object from the current mesh layer and returns it to the main execution
        method.  If a curve is selected, we find which curve in the curve Group is the 
        same as the selected one, and return it.  Otherwise, we return all curves
        we find.'''
        # Layerscan lets us get the mesh as an item object, and as an editable mesh.
        curveItem = layerScan.MeshItem(0)
        self.mesh = layerScan.MeshEdit(0)
        self.poly = self.mesh.PolygonAccessor()
        self.points = self.mesh.PointAccessor()
        '''Getting a curve Group object from an item requires reading the 
        crvGroup channel, casting the channel's value object as a value
        reference, and finally casting the object from the value reference as
        a curve group.  The curve group is an item which contains all the curves 
        within the provided item.  We access an individual curve by using the 
        ByIndex() method''' 
        chanRead = self.scene.Channels(None,0)
        crvChan = curveItem.ChannelLookup('crvGroup')
        crvValObj = chanRead.ValueObj(curveItem, crvChan)
        valRef = lx.object.ValueReference(crvValObj)
        curveGroup = lx.object.CurveGroup(valRef.GetObject())
        if curveGroup.Count()<1:
            return None
        '''We use our visitor to scan through any selected polygons and check if
        they are curves.  If so, we make a dictionary with those curve IDs and
        the root vertex position.'''
        curveVis = CurveFinder(self.poly, self.points)
        selM = lx.service.Mesh().ModeCompose('select', None)            
        self.poly.Enumerate(selM, curveVis, 0)
        '''For every curve that the visitor found, we want to pair it with a 
        curve object from the curve group.  We'll make a new dictionary, where
        the curve's ID is the key again, but the value will be the curve object
        retCurves = {}
        for selCurve in curveVis.curves:
            dist = 9**99
            '''There are no direct links to find which curve in the curve group
            belongs to a specific polygon in a mesh, so we need to compare the root
            position of the curve with the root vertices position.  We assume the
            curve object with a root position closest to a given root vertex is the
            same curve.'''
            for i in range(curveGroup.Count()):
                curve = curveGroup.ByIndex(i)
                pos = curve.Position()
                tmpD = dSqr(curveVis.curves[selCurve], pos)
                if tmpD < dist:
                    dist = tmpD
                    idx = i
            retCurves[selCurve] = curveGroup.ByIndex(idx)
        return retCurves            
    def basic_Execute(self, msg, flags):
        '''Even though the point count and spacing distance arguments are both
        optional, one of them has to be set.  We check that first.'''
        if self.dyna_IsSet(2) or self.dyna_IsSet(3):
            mode = self.attr_GetInt(0)
            '''Next we need to make sure we didn't get a spacing distance of 0
            or less, or a point count of less than 2'''
            if mode:
                dist = self.attr_GetFlt(3)
                if dist <= 0:
                    return lx.symbol.e_ABORT
                ptCount = self.attr_GetInt(2)
                if ptCount <2:
                    return lx.symbol.e_ABORT
            '''Finally, we can get a layerscan object in order to check if there
            are curves in the mesh.'''
            self.scene =        
            ls = lx.service.Layer()
            lscan = ls.ScanAllocate(lx.symbol.f_LAYERSCAN_EDIT | lx.symbol.f_LAYERSCAN_MARKPOLYS)
            curves = self.getCurve(lscan)
            if not curves:
                return lx.symbol.e_ABORT
            '''All our tests passed, and we have at least 1 curve object to rebuild'''
            killSwitch = self.attr_GetInt(1)
            for ID in curves:
                curve = curves[ID]
                '''First we get a list of all the positions we want to form
                our curve from.  Then we generate points there using a Point object'''   
                if mode:
                    ptCount = int(floor(curve.Length()/dist))
                pts = []
                for i in range(ptCount):
                ptList = []
                for i in pts:
                '''We need to add the IDs from each newly created point into a
                storage object, and using that storage object we can create a polygon'''                    
                pBuf ='p')
                polyID = self.poly.New(lx.symbol.iPTYP_CURVE, pBuf, len(ptList), 0)
                '''Finally we check if the user wants to remove the original curve.
                If they do, we need to remove each of the verts, and then the polygon'''
                if killSwitch:
                    for i in range(self.poly.VertexCount()):
    '''These error dialogs catch known cases of failures earlier in the process'''
    def e_NOCURVE(self):'dialog.setup error')'dialog.title {Rebuild Curve}')'dialog.msg {No curve was found in the current mesh layer.}')'')
    def e_BADDIST(self):'dialog.setup error')'dialog.title {Rebuild Curve}')'dialog.msg {Distance must be greater than 0}')'')
    def e_BADPTS(self):'dialog.setup error')'dialog.title {Rebuild Curve}')'dialog.msg {A minimum of 2 points must be used}')'')
lx.bless(CurvePoints, "curve.rebuild")