Skip to main content

Solidworks API Programming: Centerline Macro

Solidworks API Programming Part 2:
Sketching the cross center line on random rectangular surface

Precisely speaking, this program is for the random surface which has even number of edges. Nevertheless, this program is used to draw centerline within sketch on the surface. No matter how it forms angle with front, top or right plane, program should sketch the centerline correctly. So it's not simple. To do so, I need to consider transformation between 3D space and 2D sketch coordinates. Of course This kind of transformation function is supported by Solidworks API. Way to go!

1. Make new macro
Just click Tools - Macro - New

2. Source code analysis
In VBA, Comment symbol is ' (single quotation) and Continuation symbol is _ (underscore).


'--------------------------------------
'
' Preconditions:
'       (1) Part or assembly is open.
'       (2) Face is selected.
'
' Postconditions: Plane or face on which
'                 selected sketch was drawn is selected.
'
'--------------------------------------

Option Explicit

Sub main()

    Dim pSWApp   As SldWorks.SldWorks
    Dim pModel   As SldWorks.ModelDoc2
    Dim pSelMgr   As SldWorks.SelectionMgr
    Dim pSketch   As SldWorks.Sketch
    Dim pSketchSeg  As SldWorks.SketchSegment
    Dim pFace   As SldWorks.Face2
    Dim swLoop   As SldWorks.Loop2
    Dim swEdge   As SldWorks.Edge
    Dim vEdgeArr  As Variant
    Dim vEdge   As Variant
    Dim swCurve   As SldWorks.Curve
    Dim swSketch  As SldWorks.Sketch
    Dim swSketchSeg  As SldWorks.SketchSegment
    Dim swXForm  As SldWorks.MathTransform
    Dim swMathUtil  As SldWorks.MathUtility
    Dim swMathStartPt As SldWorks.MathPoint
    Dim swMathEndPt  As SldWorks.MathPoint

    Dim vMidPts   As Variant
    Dim vCurveParam  As Variant
    Dim nStartPt(2)  As Double
    Dim nEndPt(2)  As Double
    Dim nEdgeCount  As Long
    Dim i    As Long
    Dim j    As Long
    Dim bRet   As Boolean
    Dim boolstatus  As Boolean


    Set pSWApp = CreateObject("SldWorks.Application")
    Set pModel = pSWApp.ActiveDoc
    Set pSelMgr = pModel.SelectionManager
    Set pFace = pSelMgr.GetSelectedObject6(1, 0)

    If pFace Is Nothing Then
        boolstatus = pSWApp.SendMsgToUser2("Please select a face", _
                                            swMbWarning, swMbOk)
        Exit Sub
    End If

    pModel.InsertSketch2 True
    pModel.SetAddToDB True

    
    'Doesn't show the changes during the program execution 
    pModel.SetDisplayWhenAdded False 
            
    Set pSketch = pModel.GetActiveSketch2
    Set swXForm = pSketch.ModelToSketchTransform 'Transform from model to sketch
    Set swMathUtil = pSWApp.GetMathUtility

    
    'Find loops of closed edges on the selected surface
    Set swLoop = pFace.GetFirstLoop   
    While Not swLoop Is Nothing        
        i = i + 1        
        Debug.Print "Loop(" & i & ")"       
        Debug.Print "  IsOuter    = " & swLoop.IsOuter       
        Debug.Print "  IsSingular = " & swLoop.IsSingular        
        Debug.Print ""
    
        
        'Find the outer loop       
        If swLoop.IsOuter Then            
        vEdgeArr = swLoop.GetEdges: Debug.Assert UBound(vEdgeArr) >= 0            
        nEdgeCount = swLoop.GetEdgeCount
            
            
            'Even number of edges are available here.
            If Not nEdgeCount Mod 2 = 0 Then               
                boolstatus = pSWApp.SendMsgToUser2( _
                   "Please select the rectangular face...", _
                    swMbWarning, swMbOk)
                pModel.InsertSketch2 True
                bRet = pModel.EditRebuild3: Debug.Assert bRet
                Exit Sub
            End If
         
            
            'Finding edges
            '4 for rectangle
            '6 for hexagon
            '0 for circle
            i = 0
            ReDim vMidPts(nEdgeCount * 3)
            For Each vEdge In vEdgeArr
                Set swEdge = vEdge
                vCurveParam = swEdge.GetCurveParams2
      
                
                'vCurveParam is a array which contains 11 double type data as follows
                'StartPtX, StartPtY, StartPtZ,
                'EndPtX, EndPtY, EndPtZ,
                'StartUParam, EndUParam,
                'PackDouble1, PackDouble2, PackDouble3
                For j = 0 To 2
                    nStartPt(j) = vCurveParam(j)
                    nEndPt(j) = vCurveParam(j + 3)
                Next j
              
                 
                'If you use 3D sketch, you don't have to do this kind of transformation
                'Using sketch let us need to do the transformation
                '3D coordinate values of array(nStartPt) are
                'assigned to vector (swMathStartPt)
                'and then, 3D values are transformed into 2D values
                'swXForm = pSketch.ModelToSketchTransform is
                'the transfromation function of API to do so.
                Set swMathStartPt = swMathUtil.CreatePoint((nStartPt))
                Set swMathStartPt = swMathStartPt.MultiplyTransform(swXForm)
                Set swMathEndPt = swMathUtil.CreatePoint((nEndPt))
                Set swMathEndPt = swMathEndPt.MultiplyTransform(swXForm)                
          
                
                'Transformed vector values are assinged to new array(vMidPts).
               For j = 0 To 2
                    vMidPts(i) = (swMathStartPt.ArrayData(j) + _
                                        swMathEndPt.ArrayData(j)) / 2#
                    i = i + 1
               Next j
            Next vEdge
            
         
            'In vMidPts
            '1st edge mid-point:0,1,2
            '2nd edge mid-point:3,4,5
            '3rd edge mid-point:6,7,8
            '...
            'saved like this.
            'mid-points are connected skipping the right next points.
            'so, practically centerline is formed only on the rectangle


         
            'If you want to apply this program to skewed surface, you can test as follows.
            'Draw (0,0)-(1,0), (0,0)-(0,1)
            'You can check the sketch and space coordinates in this way.
            On Error Resume Next
            For i = 0 To nEdgeCount / 2 - 1
                Set swSketchSeg = pModel.CreateLine2( _
                    vMidPts(i * 3 + 0), vMidPts(i * 3 + 1), 0, _
                    vMidPts(i * 3 + nEdgeCount * 3 / 2), vMidPts(i * 3 + nEdgeCount * 3 / 2 + 1), 0)
                swSketchSeg.ConstructionGeometry = True
                Debug.Print "vMidPts-from (" & i & ") = " & _
                    Format$(vMidPts(i * 3 + 0) * 1000#, "0.0000") & "," & _
                    Format$(vMidPts(i * 3 + 1) * 1000#, "0.0000") & " mm"
                Debug.Print "vMidPts-to   (" & i & ") = " & _
                    Format$(vMidPts(i * 3 + nEdgeCount * 3 / 2) * 1000#, "0.0000") & "," & _
                    Format$(vMidPts(i * 3 + nEdgeCount * 3 / 2 + 1) * 1000#, "0.0000") & " mm"
            Next i
            On Error GoTo 0
        End If
        Set swLoop = swLoop.GetNext
    Wend

    

    'All changes are reflected on the screen.
    pModel.SetDisplayWhenAdded True
    pModel.SetAddToDB False

    

    'If you want to continue to do something within sketch mode, 
    'comment out the following code this way.
    'pModel.InsertSketch2 True
    'bRet = pModel.EditRebuild3: Debug.Assert bRet
End Sub

Comments

Unknown said…
I want to transform whole 2dSketch in 3d space(Model space) in solidworks.Is there any API call related to this.I am working on c++
xignite said…
Small bits of content which are explained in details,helps me understand the topic, thank you!

GetFundRedemptionFees

Popular posts from this blog

How to use pySW - a Python Solidworks VBA API wrapper

 Recently I found a python package called "pySW" to be useful for those who are interested in both Solidworks API programming and python language. If you are familiar with Visual Studio Code and shell command in the terminal, you can easily install and play with it. You may want to visit its author's github repository and try his sample test program. I modified a little to read the lens template and generate the variants. It is almost identical to his box generation sample program. It looks like pySW project has never been updated for last 3 years though. Once the package is installed, you need modify a few lines to make it work. Let me explain one by one.  The web page link PySW 1.4 project in PyPI:  https://pypi.org/project/pySW/ Github repository:  https://github.com/kalyanpi4/pySW Package installation and test program workaround Install pySW Run the following command. You should install other dependent python packages.  pip install pySW ...

Solidworks API Programming: Macro Recording and Editing

Solidworks API Programming, Part 1:  Automatically generated VBA source code analysis Let's start Solidworks API Programming with macro source code analysis. I just explain what I have done in person. Although I have not read the book, "Automating SOLIDWORKS 2006 using MACROS ( http://www.amazon.com/Automating-SOLIDWORKS-2006-using-MACROS/dp/1585032638 )", I think it could be a good reference for serious users. If you know better or best book for Solidworks API Programming, please leave the comment. 1. Macro Recording: Tools - Macro - Record This is the common function of MS-based programs which support VBA just like Excel. This function record the user action itself converting it into VBA source code. 1) Just click Tools - Macro - Record 2) Do what you want to do within solidworks like sketching and extruding 3) After finishing your work, just click Stop 4) Save window pops up. Write the filename and save it. 2. Macro Editing: Tools - Macro - Edit... L...

Solidworks API Programming

From now on, I am going to talk about famous 3D modeling tool Solidworks from the scratch. Specifically speaking, this talk is about Solidworks API 2006 Programming. At first, I recommend you scrutinize API Help and establish the architecture of API in mind. Let's start. Go to http://www.solidworks.com/pages/services/APIDownloads.html and download Solidworks 2006 Online Help. Run apihelp.chm Browse Solidworks API Help in the Contents tab. - Programmer's Guide: Must read !! - Getting Started Standalone Application and Add-in Application .NET (VB, C#, C++), ATL COM C++ Solidworks Macro and VBA script - Solidworks API Object Model: Must check !! Sldworks (Solidworks itself) ModelDoc2 (Modeling Files) PartDoc / AssemblyDoc / DrawingDoc - Examples and Projects: Very helpful example snippets and complete code for VBA and VB. But, insufficient for VB.NET, C# and particularly ATL COM C++. You can look for examples at solidworks.com's api support...