Finding max and min for each axis of body

I have need to calculate the "box" that a part would fit in so that I know how it's dimensions in all three axis. There is a GetBox method on many object types in the SolidWorks API but the API help warns not to rely on this for anything but the roughest estimate. I tried it and the warning is well founded. I need a closer estimate. Here is a typical warning:

IMPORTANT: The values returned are approximate and should  not be used for comparison or calculation purposes. Furthermore, the bounding  box may vary after rebuilding the model.

Pouring over the help files I see two possiblilties:

1) Tesselation. There are some methods that return triangles, normals and TriStripEdges that seem to be used for rendering.

2) Extract my own geometry. In the method IComponent2  Interface : GetTessTriangles Method (IComponent2) there is a note that states:

These triangles are intended for graphics display purposes and do not  represent a tessellation that could be used, for example, by a machining  application. If you need the type of accuracy associated with a machining  product, we recommend that you traverse the body faces and extract the topology  and geometry data to create your own faceting.

My question is how?

SolidworksApi macros
Answers 38
BL
BL 2011-01-25 Best Answer

Hey Eric,

You can check my thread here but the truth is that I still haven't got a good solution.

All the solutions that I've found is not relative to the body's axis but to the part's axis and if the body is not located on one of the part's axis (x/y/z) the calculation isn't good. If you find the good way to do that, i will be glad too :-)

Cheers,

Bnaya Livne

FV
FV 2011-01-26

Hi Eric,

I'm currently using both GetBox methods for assemblies and parts...and they work pretty good for me. I'm only using the values for displaying information on paperwork, nothing that needs to be too accurate..but I've managed to get it pretty accurate (within 1/64). Check your calculations and variable types. Watch out for when calculating the points and converting from the system value using your conversion factor, that your variable type is not truncating the number, you want it with as much precision as possible (I used Double). Initially, I thought this wasn't working, until I realized my conversion factor was getting truncated (instead of 0.0254 I was getting 0.03 for example, and that changed my results drastically, almost by 1 inch in some instances...).

I can share my code if you like to give it a try...let me know.

Cheers

ES
ES 2011-01-26

Filipe:

I would love to have a look at your code! I tried the box method and it wasn't even close (off by 90%). It was so far off it seemed useless. Now I wonder if I was having a conversion issue or if I possibly swapped one of the axis. I am typically modeling parts that are 2" x 20" x 0.175" and need to identify the sizes to within 0.003" or so.

FV
FV 2011-01-26

Hey Eric,

I'm not so sure about 3 thou accuracy...it works for me...but we do sheet metal..and precision never goes to that degree.

Here's my code anyhow...the usage is quite simple..it's just a function that will return a string like L" x W" x H" ...it's currently converting to fractional...but you can use the RetOpt (Return Option) to chose to return an array of 3 doubles with the calculated values.

Usage: BoxSize(Model as ModelDoc2, Config as String, RetOpt as Integer)

Hope this works for you!

Cheers

ES
ES 2011-01-26

Wow. Awesome! I tried it on three different models and it was accurate to 0.001".

ES
ES 2011-01-26

Sorry...the fourth one I tried it on was off in thickness. Should have been 0.218" but returned a value of 0.398". Hmmmmm...I guess I'll try the tessellation triangles next. I still wonder what the comments in the docs meant when it says:

we recommend that you traverse the body faces and extract the topology  and geometry data to create your own faceting.
FV
FV 2011-01-27

Hey Eric, forgot to mention..that those boundary dimensions are actually along x,y,z only...so, a plate modeled on the x/y plane will have z thickness...once you go off the planes, the boundary box is projected.

Cheers

BL
BL 2011-01-27

Hey Filipe,

I have the problem, I'm trying to get the dimensions of a plat (Sheet metal). When it's on one of the planes the boundary box is fine, but when it's not on the boundary box the dimensions I get are not what I need. Do you have a solution for that?

Thanks,

Bnaya

ES
ES 2011-01-27

Bnaya:

Here is some code that I played with at the end of the day yesterday. It gets the tessellation triangles and loops through them to get the max and min x,y and z values. It seems to be accurate on the two I've tried this on so I don't know just how accurate the tessellation triangles are at this point. At the end of this loop the maxX and minX will hold the minimum and maximum X values, etc.

<p>Dim swDoc As ModelDoc2 = Nothing<br>        Dim swPart As PartDoc = Nothing<br>        Dim swDrawing As DrawingDoc = Nothing<br>        Dim swAssembly As AssemblyDoc = Nothing<br>        Dim maxX As Single<br>        Dim maxY As Single<br>        Dim maxZ As Single<br>        Dim minX As Single<br>        Dim minY As Single<br>        Dim minZ As Single<br>        Dim i As Integer</p><p></p><p><br>        swDoc = CType(swApp.ActiveDoc, ModelDoc2)<br>        swPart = CType(swDoc, PartDoc)</p><p></p><p>        'Get the triangles<br>        Dim triangles As Object = swPart.GetTessTriangles(False)</p><p></p><p>        'Initialize the max, min values with the first triangle x,y,z<br>        maxX = triangles(0)<br>        maxY = triangles(1)<br>        maxZ = triangles(2)<br>        minX = triangles(0)<br>        minY = triangles(1)<br>        minZ = triangles(2)</p><p></p><p>        'Loop through the triangles and examine for max and min<br>        i = 3<br>        While i < triangles.getUpperBound(0)</p><p></p><p>            If maxX < triangles(i) Then<br>                maxX = triangles(i)<br>            ElseIf triangles(i) < minX Then<br>                minX = triangles(i)<br>            End If<br>            i += 1</p><p></p><p>            If maxY < triangles(i) Then<br>                maxY = triangles(i)<br>            ElseIf triangles(i) < minY Then<br>                minY = triangles(i)<br>            End If<br>            i += 1</p><p></p><p>            If maxZ < triangles(i) Then<br>                maxZ = triangles(i)<br>            ElseIf triangles(i) < minZ Then<br>                minZ = triangles(i)<br>            End If<br>            i += 1</p><p></p><p>        End While</p>

My computer seems to loop through these values pretty fast.

BL
BL 2011-01-27

Eric first of all, thank you for your help.

I have made almost exactly the function but for bodies instead of parts.

The problems is that when it's not on the part's axis, the returned info is not good.

I get the maxX and maxY but how do i calculates in the right way the height and the width?

x = maxX - minX
y = maxY - minY
z = maxZ - minZ

Works great when the part (body, in my case) is on one of the axis. but when it's not,  get the wrong results, as attached:

The height and the width that i have marked in red are what I get, because that's the max/min points. But how can I overcome this and get the real width/height/depth (150x180x10 in the above sketch)?

Cheers,

Bnaya

comment imagecomment image
FV
FV 2011-01-28

Bnaya, this is a good question...I have no idea...lol.

BL
BL 2011-01-29

I know that Filipe, I'm working on it for few weeks.

And it's getting better when then body is not on any of the axis...

How do you overcome this?

Currently I'm saving only the depth in the custom properties for each plat, but we want to make it better to save all the dimenstions.

I'm working on a add-in that can make cut lists and partnumbers for bodies in assemblies, not like solidworks able to do in each part seprately, and then create relative-to-model drawings of all the bodies (which by hand can take days and isn't accurate).

I'm allmost done, but most of the current problems is the plat dimensions.

Have a good weekend,

Bnaya Livne

ES
ES 2011-01-31

Bnaya:

What if you put in a Coordinate System? Look at ICoordinateSystemFeatureData Interface. There are a couple of methods:

OriginEntity

Transform

I am not sure how SolidWorks transforms objects but I'll bet this object has something to do with that. Possibly you could look into using the Coordinate System object to perform a transform of either the part or the triangle vertices.

Sorry I only have a clue and not the answer.

I look forward to seeing what you figure out.

SF
SF 2011-01-31

I'm thinking the same thing because even with the built in bounding boxes, there is still the need to call a "grain direction" reference.

BL
BL 2011-01-31

Thanks Eric for the help, Can you help me understand how can I create the coordinate system for a body?

Thanks,

Bnaya

ES
ES 2011-01-31

Insert > Reference Geometry > Coordinate System

The click on a vertex and possible edges for each axis.

BL
BL 2011-01-31

Thanks but I'm trying to solve it using api only

I could have 1000 bodies in the assembly.

Bnaya

ES
ES 2011-02-01

Wow. That is wayyyyyyy to many to add by hand. Can you see a programming strategy like identifying the largest surface on the body using surface area and then use a corner vertex of that surface to insert a Coordinate System on that vertex?

-OR-

What if you wrote a script that tried to insert a coordinate system at any vertex that you selected? That way at least all the tedious work of managing the Coordinate System creation dialog box would be done away with.

I don't know, just trying to think of ideas that might be workable.

BL
BL 2011-02-01

I think that I've managed to insert the coordinate system for each body, something like this:

           
<div id="_mcePaste">          bodies = pDoc.GetBodies2(swBodyType_e.swAllBodies, False)</div><div id="_mcePaste">          For i = 0 To UBound(bodies)</div><div id="_mcePaste">                body = bodies(i)</div><div id="_mcePaste">                face = Helper.maxFace(body)</div><div id="_mcePaste">                edge = Helper.maxEdgeObj(face)</div><div id="_mcePaste">                curve = edge.GetCurve</div><div id="_mcePaste">                pnts = edge.GetCurveParams2</div><div id="_mcePaste">                length = curve.GetLength2(pnts(6), pnts(7)) * 1000.0#</div><div id="_mcePaste">                sVertex = edge.GetStartVertex</div><div id="_mcePaste">                entArr(0) = edge</div><div id="_mcePaste">                swFeat = swFeatMgr.CreateCoordinateSystem(sVertex, entArr, Nothing, Nothing)</div><div id="_mcePaste">                coordSys = swFeat.GetDefinition</div><div id="_mcePaste">                swXform = coordSys.Transform</div><div>            Next (i)</div>
But now what?

How does the coordinate system helps me?

Cheers,

Bnaya

ES
ES 2011-02-01

Can you use the coordinate system to transform the body to the x,y,z axis, calculate the max and min and thgen transform the body back?

BL
BL 2011-02-01

But how can I do that?

Dimensions should be so easy, I don't believe that there is no easier way.

Bnaya

BL
BL 2011-02-03

Hey,

Do you know how to force solidworks to use the coordinate system that I've just created?

I find it only for MassProperties but I need it for GetBox functions to get the boundry box.

Cheers,

Bnaya

BL
BL 2011-02-04

Hey,

No one have a solution for that? Do I need to invent the wheel? That should be super-easy to get the dimensions.

Bnaya

MC
MC 2011-02-05

Try this one.  It uses the principal axes to determine the tighest bounding box.  This code is only tested for one body and of course then only one density.  It ends up drawing a 3d sketch of the edges of the box.

Option Explicit

Public Enum swMassAxes_e
    X = 0
    Y = 1
    Z = 2
End Enum
  

Sub main()
    Dim swApp As SldWorks.SldWorks
    Dim swModel As SldWorks.ModelDoc2
    Dim swPart As SldWorks.PartDoc
    Dim selMgr As SldWorks.SelectionMgr
    Dim swMassProp As SldWorks.MassProperty
    Dim swBody As SldWorks.Body2
    Dim swMathUtil As SldWorks.MathUtility
    Dim swSkSeg As SldWorks.SketchSegment
    Dim skSegs As Variant
   
    Dim lStatus As Long
    Dim iStatus As Integer
    Dim bStatus As Boolean
    Dim i As Integer
   
    Dim vBodies As Variant
    Dim centerOfMass As SldWorks.MathPoint
   
    Dim Ix As SldWorks.MathVector
    Dim Iy As SldWorks.MathVector
    Dim Iz As SldWorks.MathVector
   
    Dim xLimits(1) As Double
    Dim yLimits(1) As Double
    Dim zLimits(1) As Double
    Dim dist As Double
    Dim tempDist(1) As Double
   
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    Set swPart = swModel
    Set swMathUtil = swApp.GetMathUtility
   
    Set swMassProp = swModel.Extension.CreateMassProperty
   
    Set centerOfMass = swMathUtil.CreatePoint(swMassProp.centerOfMass)
    Set Ix = swMathUtil.CreateVector(swMassProp.PrincipleAxesOfInertia(swMassAxes_e.X))
    Set Iy = swMathUtil.CreateVector(swMassProp.PrincipleAxesOfInertia(swMassAxes_e.Y))
    Set Iz = swMathUtil.CreateVector(swMassProp.PrincipleAxesOfInertia(swMassAxes_e.Z))
   
    vBodies = swPart.GetBodies2(SwConst.swBodyType_e.swSolidBody, True)
   
    If Not IsEmpty(vBodies) Then
        Set swBody = vBodies(0)
        xLimits(0) = GetExtremeDistanceAlongAxis(swBody, centerOfMass, Ix)
        xLimits(1) = GetExtremeDistanceAlongAxis(swBody, centerOfMass, Ix.Scale(-1))
        yLimits(0) = GetExtremeDistanceAlongAxis(swBody, centerOfMass, Iy)
        yLimits(1) = GetExtremeDistanceAlongAxis(swBody, centerOfMass, Iy.Scale(-1))
        zLimits(0) = GetExtremeDistanceAlongAxis(swBody, centerOfMass, Iz)
        zLimits(1) = GetExtremeDistanceAlongAxis(swBody, centerOfMass, Iz.Scale(-1))
       
        For i = 1 To UBound(vBodies)
            Set swBody = vBodies(i)
            tempDist(0) = GetExtremeDistanceAlongAxis(swBody, centerOfMass, Ix)
            tempDist(1) = GetExtremeDistanceAlongAxis(swBody, centerOfMass, Ix.Scale(-1))
            If tempDist(0) > xLimits(0) Then xLimits(0) = tempDist(0)
            If tempDist(1) > xLimits(1) Then xLimits(1) = tempDist(1)
           
            tempDist(0) = GetExtremeDistanceAlongAxis(swBody, centerOfMass, Iy)
            tempDist(1) = GetExtremeDistanceAlongAxis(swBody, centerOfMass, Iy.Scale(-1))
            If tempDist(0) > yLimits(0) Then yLimits(0) = tempDist(0)
            If tempDist(1) > yLimits(1) Then yLimits(1) = tempDist(1)
           
            tempDist(0) = GetExtremeDistanceAlongAxis(swBody, centerOfMass, Iz)
            tempDist(1) = GetExtremeDistanceAlongAxis(swBody, centerOfMass, Iz.Scale(-1))
            If tempDist(0) > zLimits(0) Then zLimits(0) = tempDist(0)
            If tempDist(1) > zLimits(1) Then zLimits(1) = tempDist(1)
        Next
   
    End If
   
    Set Ix = Ix.Normalise
    Set Iy = Iy.Normalise
    Set Iz = Iz.Normalise
    Dim Vert1 As SldWorks.MathPoint
    Dim Vert2 As SldWorks.MathPoint
    Dim Vert3 As SldWorks.MathPoint
    Dim Vert4 As SldWorks.MathPoint
    Dim Vert5 As SldWorks.MathPoint
    Dim Vert6 As SldWorks.MathPoint
    Dim Vert7 As SldWorks.MathPoint
    Dim Vert8 As SldWorks.MathPoint
    Dim V As SldWorks.MathVector
   
    Set V = Ix.Scale(xLimits(1) * -1#).Add(Iy.Scale(yLimits(1) * -1#)).Add(Iz.Scale(zLimits(0)))
    Set Vert1 = centerOfMass.AddVector(V)
   
    Set V = Ix.Scale(xLimits(0)).Add(Iy.Scale(yLimits(1) * -1#)).Add(Iz.Scale(zLimits(0)))
    Set Vert2 = centerOfMass.AddVector(V)
   
    Set V = Ix.Scale(xLimits(0)).Add(Iy.Scale(yLimits(0))).Add(Iz.Scale(zLimits(0)))
    Set Vert3 = centerOfMass.AddVector(V)
   
    Set V = Ix.Scale(xLimits(1) * -1#).Add(Iy.Scale(yLimits(1))).Add(Iz.Scale(zLimits(0)))
    Set Vert4 = centerOfMass.AddVector(V)
   
    Set V = Ix.Scale(xLimits(1) * -1#).Add(Iy.Scale(yLimits(1) * -1#)).Add(Iz.Scale(zLimits(1) * -1#))
    Set Vert5 = centerOfMass.AddVector(V)
   
    Set V = Ix.Scale(xLimits(0)).Add(Iy.Scale(yLimits(1) * -1#)).Add(Iz.Scale(zLimits(1) * -1#))
    Set Vert6 = centerOfMass.AddVector(V)
   
    Set V = Ix.Scale(xLimits(0)).Add(Iy.Scale(yLimits(0))).Add(Iz.Scale(zLimits(1) * -1#))
    Set Vert7 = centerOfMass.AddVector(V)
   
    Set V = Ix.Scale(xLimits(1) * -1#).Add(Iy.Scale(yLimits(1))).Add(Iz.Scale(zLimits(1) * -1#))
    Set Vert8 = centerOfMass.AddVector(V)
   
    swModel.SketchManager.Insert3DSketch True
    skSegs = swModel.SketchManager.Create3PointCornerRectangle(Vert1.ArrayData(0), Vert1.ArrayData(1), Vert1.ArrayData(2), _
        Vert2.ArrayData(0), Vert2.ArrayData(1), Vert2.ArrayData(2), _
        Vert3.ArrayData(0), Vert3.ArrayData(1), Vert3.ArrayData(2))

    swModel.ClearSelection2 True
   
    skSegs = swModel.SketchManager.Create3PointCornerRectangle(Vert5.ArrayData(0), Vert5.ArrayData(1), Vert5.ArrayData(2), _
        Vert6.ArrayData(0), Vert6.ArrayData(1), Vert6.ArrayData(2), _
        Vert7.ArrayData(0), Vert7.ArrayData(1), Vert7.ArrayData(2))
       
    Set swSkSeg = swModel.SketchManager.CreateLine(Vert1.ArrayData(0), Vert1.ArrayData(1), Vert1.ArrayData(2), _
        Vert5.ArrayData(0), Vert5.ArrayData(1), Vert5.ArrayData(2))
       
    Set swSkSeg = swModel.SketchManager.CreateLine(Vert2.ArrayData(0), Vert2.ArrayData(1), Vert2.ArrayData(2), _
        Vert6.ArrayData(0), Vert6.ArrayData(1), Vert6.ArrayData(2))
       
    Set swSkSeg = swModel.SketchManager.CreateLine(Vert3.ArrayData(0), Vert3.ArrayData(1), Vert3.ArrayData(2), _
        Vert7.ArrayData(0), Vert7.ArrayData(1), Vert7.ArrayData(2))
       
    Set swSkSeg = swModel.SketchManager.CreateLine(Vert4.ArrayData(0), Vert4.ArrayData(1), Vert4.ArrayData(2), _
        Vert8.ArrayData(0), Vert8.ArrayData(1), Vert8.ArrayData(2))
       
    swModel.ClearSelection2 True
   
    swModel.SketchManager.Insert3DSketch True
   
End Sub

Function GetExtremeDistanceAlongAxis(swBody As SldWorks.Body2, origin As SldWorks.MathPoint, axis As SldWorks.MathVector) As Double
    Dim swApp As SldWorks.SldWorks
    Dim swMathUtil As SldWorks.MathUtility
    Dim bStatus As Boolean
    Dim extCoord(2) As Double
    Dim extPt As SldWorks.MathPoint
    Dim extVector As SldWorks.MathVector
   
    Set swApp = Application.SldWorks
    Set swMathUtil = swApp.GetMathUtility
   
    bStatus = swBody.GetExtremePoint(axis.ArrayData(0), axis.ArrayData(1), axis.ArrayData(2), extCoord(0), extCoord(1), extCoord(2))
       
        If bStatus Then
            Set extPt = swMathUtil.CreatePoint(extCoord)
            Set extVector = extPt.Subtract(origin)
            GetExtremeDistanceAlongAxis = extVector.Dot(axis)
        End If

End Function

BL
BL 2011-02-05

Thank you Matthew,

Can you help me understand what is going on in this code so I can adjust it to my needs?

I do not need to draw a sketch, but only the dimensions,

Thanks,

Bnaya

BL
BL 2011-02-05

It's better but not perfect, look at the screenshot:

The boundry box isn't so tight

comment imagecomment image
MC
MC 2011-02-07

It gets the principal axis of rotation Ixx, Iyy, Izz and uses those to define the coordinate system to find the body max and min locations along.  Then it gets the extreme point along those axes by looping thru all the bodies in the part.  Finally it draws a box in a 3d sketch.  You are correct that wont find the minimum bounding box but it is better than just using vectors along the global cartesian coordinate system.

DM
DM 2011-02-25

Bnaya or anyone:

I am working on a similar problem here. The return value is accurate enough for our use until the part is not on the part planes. I am thinking of “InsertMoveCopybody2” to align the flat pattern with the planes. I can then close the part with out saving the changes. Has anyone come up with a better solution to the part not being parallel with the planes?

Thanks

Dan Miel

BL
BL 2011-02-26

It seems to be the best workout to copy the body to the new part, but it could take a lot of resources.

Can you show me the peace of code you are using to copy the body to the empty part file that he would be parallel with the planes and not like he is on the original part?

I am trying to solve this problem for asseblies with 1k+ bodies.

Currently we are thinking on change all the extrude to sheetmetal features which SW auto-generate them custom properties, but still I want to solve it to other bodies such as extrude so my AddIn could be more generic.

You can also check Sean Phillips's answer at Facebook SW API group:

http://www.facebook.com/topic.php?topic=14668&post=69099&uid=2353904721

Cheers,

Bnaya Livne

DM
DM 2011-02-26

Banya

I do not have the code for moving the parts yet. We just have single body parts. At present I am sending the information to a spread sheet and if the smallest bounding box size is more than 3 times the sheet metal thickness I report a problem.  I am not planning to copy the body to another part, I’m thinking of just rotating it to the planes. To do this I’m thinking that when a thickness problem is spotted , the program can be paused and a person will need to select which two surfaces to use for the X and Y planes. Those surfaces can then be made parallel to the planes.

            The other option I see is to create a drawing with the Flat Pattern and take the bonding box of the view and multiply by the sheet metal thickness. I think the part in the flat pattern may still be skewed.

Dan Miel

BL
BL 2011-02-26

Hey,

After he selects the parallel surfaces as the x/y planes, How can you use it to get the right bounding box?

Alsom you can do the surface select automatic and check if they are parallel using the Measure tool.

I really want to solve it, that makes me nuts for too long time I thought it would be so easy.

Cheers,

Bnaya

DM
DM 2011-02-26

The two surfaces selected would need to be perpendicular to each other. One surfaces would be mated to the x plane and the other to the y plane. You could then use the bounding box as you normally would. If two surfaces were picked at random and they were chamfers the part may still be turned at an angle and not give the smallest bounding box.

Dan

BL
BL 2011-02-26

How do you mate them to the x/y planes? The user does it manually too?

ES
ES 2011-02-26

Sorry, I am out of the office but it seems that the easiest solution would be:

1) determine how many degrees of difference there is between the three planes od the part and the front, righ and top plane.

2) Get the center of gravity of the part.

3) Use trig to "rotate" the x, y and z of each triangle vertex using the degrees we calculated in step 1 above.

Warning, my trig is lousy but I think that this stuff is done all the time with GPS type measurements. It seems that this would be a lot easier than acutaully moving the bodies.

Just my 2 cents...

DM
DM 2011-02-27

Eric:

I’m not sure what “Part axis” you are thinking of comparing to the planes.

Bnaya:

I have attached a sample sheet metal part and a macro to demonstrate what I am thinking of. I think it will work in my situation. There is no error checking. At the beginning you need to select two perpendicular surfaces.  You will need to use the attached file since the flat pattern name and plane name are hard coded in. The flat pattern must be unsuppressed and any Move-Copy features in the tree must be deleted.

I hope this helps.

Dan

SF
SF 2015-01-09

Hi. Did you have this code on C#. Or maybe you can halp me understand how convert this code in C#

JG
JG 2015-05-04

Matthew,

Thanks for the code.

It works when the part is skewed or tilted.

Is it possible to modify the code to get a length, width and thickness property taking the dimensions from the 3D sketch and add to the part properties?

TB
TB 2016-10-03

I like your code, but it either gives a good result or a goofy one.  I'm not sure why or when to expect it.  Here are a couple files that it doesn't handle well.