Mating Automation Techniques: Pros and Cons

You can’t talk about assemblies long without talking about mating. Consequently, if we’re going to automate assembly creation then we better have a darn good strategy for automating the mating process. While I can’t say that automating mating is easy, it is definitely possible. Best of all, several options are available to us to pull it off. Before we look at those options, however, lets consider what steps are actually necessary to add mates via the API:
1. Finding the entities used in the mate
2. Selecting those entities using IEntity::Select4 or IModelDocExtension::SelectByID2
3. Creating the mate with IAssemblyDoc::AddMate3
Note that step 2 is necessary because IAssemblyDoc::AddMate3 requires that the entities be selected.
Locating Entities
The first step is quite possibly the most difficult, or at least the most intimidating. Let’s say we need to mate two flanges together. This will require a coincident and concentric mate. Since each of those mates requires two entities, we will need to programmatically find four entities total for mating. Here’s four ways to do that.
Search for geometry/topology
If finding entities is analogous to cracking someone’s password, we might call this method the “brute force attack”. If we need to locate a face, for example, our code needs to search every single face in a component until it finds one that matches a particular geometric criteria. Considering the above example, coming up with a criterion is pretty easy: the largest cylindrical face on each component. Eyeing the flange, it isn’t obvious whether that face is the inside face or the outside face, but the great thing is that it doesn’t matter. Both are concentric about the same axis, so either one would work. Next, for the coincident mates, we need to locate the hub face that extends ever slightly past the flange. It is pretty easy to see that this face is the second largest planar face on the component, so that will be our criterion.
Pros: Doesn’t require any additional work on the part of the designer to prepare the part for mating.
Cons: Makes many assumptions about the component geometry. Our code may work fine if we keep using flanges of roughly the same proportions, but if your code needs more versatility then check out the next option.
Note that this is the method used to mate handles to a drawer front in Lesson 5.1 of our VBA course.
Search for named entities
If the first approach is not practical, an excellent alternative is to have the part designer or part automation macro name the entities used to create the mates. (Tip: To manually name an entity such as an edge or face, just right click, go to Edge/Face Properties, and specify a name. To programmatically name an entity, use IPartDoc::SetEntityName.) For example, in our flange example, the circular faces could be named “concentric” since they are used to create the concentric mate. The assembly automation macro can then traverse all edges/faces in a component until it finds the edge/face with the name “concentric”. This is done using IModelDoc2::GetEntityName.
Pros: Greater reliability during the mating process than searching geometry/topology.
Cons: Requires additional work for the part designer or the programmer who is creating the part automation macro. Moreover, existing parts will require modification before they can be used in the assembly automation process.
Note that this is the method used to mate the handle to the arm in the “99 Must Know Members of the SolidWorks API” video tutorial.
Get named reference geometry
This approach is similar to the second approach, or could be used in combination with any of the other approaches. If one or more of the mate entities could be reference geometry, then the second step of finding the mate entity can be eliminated entirely by using IModelDocExtension::SelectByID2. Consider our flange example. Inside of creating a concentric mate between the faces, center axes with known names could be used instead. So, for example, if this axis is called Axis1 then steps two and tree are accomplished in one line:
swModel.Extension.SelectByID2 "Axis1", "AXIS", 0, 0, 0, False, 0, Nothing, 0
Pros: Simpler code, greater reliability than searching geometry/topology.
Cons: More work on the part of the designer.
Get mate reference entities
This approach is similar to the second except the entities necessary for mating are found in the mate references. Extracting this data is somewhat complex, which is why I would not recommend this approach unless the assembly automation process involves a large number of existing parts with the needed entities contained in the mate references. See this example for a macro that could form the basis for mate automation using mate references.
Also note that programmatically inserting a component with mate references does not cause it to instantly “snap” into place, which happens sometimes when such a component is manually inserted and a possible entity match for the mate reference is found.
Pros: No advantage over the earlier techniques, unless mate references already exist in the part or the other techniques aren’t an option.
Cons: Complex code.
Transforms + fixing
“Wait a second… I thought we were only covering four mating techniques?” That’s because the fifth technique doesn’t involve mating but might still solve your problem. A lot of engineers mate components together not because they actually care about the mate relationships themselves but just because they need to get components in a particular position quickly so it looks in a drawing or a rendered image. If that’s the case, mates might be overkill. After all, adding and rebuilding is very performance instensive, plus mates make the assembly file MUCH larger. So why not consider this option: instead of using the cumbersome IAssemblyDoc::AddMate3 to position components, why not use transforms to move them in position and then fix them in place using IAssemblyDoc::FixComponent? Your likely answer is, “Because I don’t know how to use transforms!” Well, head on over to Lesson 5.3 and change that. You’ll end up with a macro that finishes much faster. This approach also has the advantage of not requiring you to search for entities anymore. Instead, transforming a component only requires its IComponent2 pointer, which is very easy to get using IAssemblyDoc::GetComponentByName.
Pros: Faster automation process, less bulky assembly files, faster rebuild times.
Cons: Complex code. Doesn’t actually add mates, which might be necessary.
Alignment Issues
Another issue encountered in mating automation is proper alignment. Alignment is controlled in IAssemblyDoc::AddMate3 through the AlignFromEnum argument, which gives us three options: swMateAlignALIGNED, swMateAlignANTI_ALIGNED, and swMateAlignCLOSEST. The last, as I understand it, will simply default to the easiest alignment solution depending on the current rotation of the components, although this has no value in assembly automation. Using the swMateAlignALIGNED option, then, our code to add a coincident mate between two selected planar faces looks like this:
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swAssy As SldWorks.AssemblyDoc
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swAssy = swModel
swAssy.AddMate3 swMateCOINCIDENT, swMateAlignALIGNED, False, Empty, Empty, Empty, _
Empty, Empty, Empty, Empty, Empty, False, Empty
swModel.EditRebuild3
End Sub
Try running this code on two components. Did you get the alignment you wanted? If not, then you must need swMateAlignANTI_ALIGNED, so you would modify the above code. This is pretty standard procedure for programming macros that automate mating: test what works and modify the code accordingly. This procedure has two significant assumptions, however. First, it is assumes that we know the direction (e.g., +Y) of the base extrude. If this assumption is unreliable, however, then we can’t consistently use the same alignment and expect good results.
The solution, then, is to programmatically determine whether the alignment was correct. For example, let’s consider our flange example again. If IAssemblyDoc::AddMate3 executed and both mating faces were pointing in the same direction then those face normals would have the exact same values. If we wanted the X axis going through the center of the flanges, then both flanges would have normal values of <1,0,0> or <1,0,0>, whereas if our alignment was correct then one should have <1,0,0> and the other should have <1,0,0>. So what we need is code that tests the normals of those faces, and if they are identical in the X direction, flips the alignment of the coincident mate.
To get the face normal we use IFace2::Normal. However, that gives us the normal in part coordinates. We need to use transforms to convert it to assembly coordinates. Once we’ve ran a comparison showing that the X values are identical, we need to use IAssemblyDoc::EditMate2 to flip the mate alignment. If you want to see a step-by-step tutorial on mating and alignment automation then check out Lesson 5.1 of our course Automating SolidWorks With VBA. Here is a clip of that macro in action. Note that if I did not have the code in place to flip the alignment, the handle would have been upside down the second time I ran the macro.
Happy automating,
Keith
Want to keep up with new blog posts, videos, and macros we create each month? Sign up for our newsletter!
Video: The 99 Must-Know SolidWorks API Calls
Did you know that there are probably over 10,000 API calls available in SolidWorks? Yet less than 1% of them are necessary for creating even very complicated automation macros and add-ins. To prove this, I created a macro that would satisfy the specifications of a mock case study involving part, assembly, and drawing automation using only 99 unique SolidWorks API calls. A line-by-line look at how this macro works was presented At SolidWorks World 2012 in a session called “Goldmember: 99 Must-Know Methods and Properties of the SolidWorks API”.
Here is a list of those API calls, in the order that they are first used. (Some of them are used more than once.)
1. ISldWorks::GetOpenFileName
2. ISldWorks::SendMsgToUser2
3. ISldWorks::ActiveDoc
4. IModelDoc2::GetType
5. IModelDoc2::ActiveView
6. IModelView::EnableGraphicsUpdate
7. ISketchManager::AddToDB
8. ISldWorks::SetUserPreferenceToggle
9. IModelDocExtension::SelectByID2
10. ISketchManager::InsertSketch
11. ISketchManager::CreateCircleByRadius
12. IModelDoc2::AddDimension2
13. IFeatureManager::FeatureExtrusion2
14. IModelDoc2::FirstFeature
15. IFeature::GetTypeName
16. IFeature::GetNextFeature
17. IFeature::Select2
18. IFeatureManager::FeatureCut3
19. IPartDoc::GetBodies2
20. IBody2::GetFaces
21. IFace2::GetSurface
22. ISurface::IsCylinder
23. IFace2::GetArea
24. IEntity::Select4
25. IFeatureMananger::FeatureFillet
26. IPartDoc::SetEntityName
27. IBody2::GetEdges
28. IEdge::GetCurveParams3
29. ICurveParamData::StartPoint
30. IModelDoc2::AddConfiguration3
31. IModelDoc2::DeleteConfiguration2
32. IPartDoc::SetMaterialPropertyName2
33. IModelDocExtension::SetMaterialPropertyValues
34. IModelDocExtension::CustomPropertyManager
35. ICustomPropertyManager::GetNames
36. ICustomPropertyManager::Get3
37. ICustomPropertyManager::Set
38. ICustomPropertyManager::Add2
39. IModelDocExtension::SaveAs
40. IModelDoc2::OpenDoc6
41. IAssemblyDoc::AddComponent4
42. IAssemblyDoc::GetComponentByName
43. IComponent2::GetBodies3
44. IModelDoc2::GetEntityName
45. IAssemblyDoc::AddMate3
46. IAssemblyDoc::GetComponents
47. IEntity::GetComponent
48. IComponent2::ReferencedConfiguration
49. IComponent2::FeatureByName
50. IComponent2::Select4
51. IAssemblyDoc::EditPart2
52. IFeature::GetDefinition
53. IExtrudeFeatureData2::GetDepth
54. IExtrudeFeatureData2::SetDepth
55. IFeature::ModifyDefinition
56. IAssemblyDoc::EditAssembly
57. IComponent2::GetModelDoc2
58. IModelDoc2::SelectionManager
59. ISelectionManager::GetSelectedObjectType3
60. ISelectionManager::GetSelectedObject6
61. IDisplayDimension::GetDimension2
62. IDimension::SetSystemValue3
63. IModelDoc2::ForceRebuild3
64. IModelDoc2::ShowNamedView2
65. IModelDoc2::ViewZoomtofit2
66. ISldWorks::GetUserPreferenceStringValue
67. ISldWorks::NewDocument
68. IDrawingDoc::SetupSheet5
69. IDrawingDoc::CreateDrawViewFromModelView3
70. IDrawingDoc::ViewDisplayShaded
71. IView::ScaleDecimal
72. IDrawingDoc::FeatureByName
73. IDrawingDoc::AutoBalloon4
74. INote::GetAnnotation
75. IAnnotation::GetPosition
76. IAnnotation::SetPosition
77. IView::InsertBomTable3
78. IView::GetVisibleComponents
79. IDrawingDoc::NewSheet3
80. IDrawingDoc::GetSheetNames
81. IDrawingDoc::Sheet
82. IDrawingDoc::ActivateSheet
83. ISheet::SetName
84. IComponent2::Name2
85. IDrawingDoc::Create3rdAngleViews2
86. ISheet::GetViews
87. IView::GetReferencedModelName
88. IView::ReferencedConfiguration
89. IDrawingDoc::InsertModelAnnotations3
90. IModelDoc2::ClearSelection2
91. IView::GetFirstDisplayDimension5
92. IDisplayDimension::GetNameForSelection
93. IDisplayDimension::GetNext5
94. IModelDocExtension::AlignDimensions
95. IModelDocExtension::GetPackAndGo
96. IModelDoc2::GetPathName
97. IPackAndGo::SetSaveToName
98. IModelDocExtension::SavePackAndGo
99. ISldWorks::CloseAllDocuments
The presentation was very well received. Here is some of the feedback emailed to me afterward:
[quote author=”James” website=”UtilX”]Your “Goldmember” presentation was the best API session I’ve attended in 8 SWW events!”[/quote] [quote author=”Steve” website=”Harsco Industrial”]Just left your “Goldmember” class you gave at Solidworks World 2012. Thank you for coming and offering these classes! You have opened a new world to me that I feel I can dive into… Thank you![/quote] [quote author=”Michael” website=”WL Gore & Associates”]Hello Keith. I was in your excellent course on Tuesday. I was pretty impressed with how you got through all 99 right in the allotted time. Thanks for the great course and insight.[/quote]This presentation also works as a great refresher for those who have worked with the API in the past but may need to quickly brush-up on the API by hitting only the highlights.
Although it was not recorded at SolidWorks World, I later recorded myself giving the entire presentation again. Premium members can watch it here. The lesson page also includes the code itself.
What API calls do you consider “must-know”? Please share in the comments below!
Keith
Want to keep up with new blog posts, videos, and macros we create each month? Sign up for our newsletter!
Video : Create Custom Features with the SolidWorks API
Did you know that you can create completely custom features that behave just like regular SolidWorks features? This is possible with macro features. Just like a standard SolidWorks feature, macro features reside in the FeatureManager tree and can do anything a standard feature can do an more. Using a macro features you can do the following:
- Create or edit bodies
- Perform tasks during every feature rebuild
- Use PropertyManager pages as a user interface, complete with temporary body previews
- Prevent tampering by disabling the ability to suppress, edit, or delete
As demonstrated in the embedded video, this all makes for a feature that looks and feels like it came right out of the box. Best of all, since the code controlling the macro feature remains in the source macro file, modifications can be made to the source code that will reflect in every instance of the macro feature. It’s just like when you update a model and the change is reflected in all drawings referencing that model.
A word of warning, however: Macro features certainly fall under the category of “advanced” functionality, and for that reason they are the topic of the very last lesson in my course. Indeed, if I would consider any part of one’s API knowledge the “crown jewel” it would be the ability to write macro features. And until now, no tutorials existed to ease the learning of this powerful aspect of the API.
In my 43 minute lesson, Lesson 7.5 in our VBA course, I walk you through the creation of a complex macro feature from beginning to end. No stone is left un-turned. To help organize the procedure for creating macro features, I break the video up into several steps:
Part A: Macro feature basics
Part B: Creating a new body
Part C: Replacing an existing body
Part D: Implementing a PropertyManager page (PMP) as a user interface
Part E: Adding additional PMP controls for the body’s dimensions
Part F: Implementing edit definition
Part G: Remembering PMP control values
Part H: Implementing temporary body previews
Part I: Spike Creator demonstration
Parts A through H cover the essentials of creating a robust macro feature without any unnecessary bells or whistles. In the last part, I present to you the final iteration of the Spike Creator macro—the basics of which we developed two lessons earlier. Specifically, I give more detail on how the merge functionality of the Spike Creator macro feature works. Also provided on the lesson page is the source code for the second macro shown in the YouTube promo, so you can see exactly how to update custom properties or run any other code you want during rebuild.
Personally, I love that SolidWorks is so customizable, right down to the most basic building block of a model—the feature. If anyone has any cool ideas for a macro feature, I’d love to hear it. Just share in the comments below.
Keith
Want to keep up with new blog posts, videos, and macros we create each month? Sign up for our newsletter!
