#include "macro.hpp" #include #include namespace macrogen { using geom::dot; using geom::normalize; using geom::Vec3; static std::string f(double v) { // format a number in metres with enough precision std::ostringstream s; s.setf(std::ios::fixed); s.precision(7); s << v; return s.str(); } std::string generateVBA(const builder::BuildParams& bp, const std::string& stepOutWinPath) { const auto& d = bp.datum; Vec3 u = normalize(d.u), v = normalize(d.v); const double MM = 0.001; // SolidWorks API works in metres // footprint in datum-local (u,v), mm double umin = 1e300, umax = -1e300, vmin = 1e300, vmax = -1e300; for (const auto& h : bp.holes) { Vec3 r = h.center - d.origin; double cu = dot(r, u), cv = dot(r, v), rr = h.diameter * 0.5; umin = std::min(umin, cu - rr); umax = std::max(umax, cu + rr); vmin = std::min(vmin, cv - rr); vmax = std::max(vmax, cv + rr); } umin -= bp.margin; umax += bp.margin; vmin -= bp.margin; vmax += bp.margin; std::ostringstream o; o << "' ==================================================================\n"; o << "' SolidWorks parametric part — generated by scan2cad\n"; o << "' Plate datum + " << bp.holes.size() << " hole(s). Units: metres (SW API).\n"; o << "' Tested shape targets SW 2020+ with English default part template.\n"; o << "' Tools > Macro > New, paste this, then Run.\n"; o << "' ==================================================================\n"; o << "Dim swApp As SldWorks.SldWorks\n"; o << "Dim swModel As SldWorks.ModelDoc2\n"; o << "Dim swFeat As SldWorks.Feature\n"; o << "Dim swSketchMgr As SldWorks.SketchManager\n"; o << "Dim swFeatMgr As SldWorks.FeatureManager\n"; o << "Dim boolstatus As Boolean\n\n"; o << "Sub main()\n"; o << " Set swApp = Application.SldWorks\n"; o << " Dim partTemplate As String\n"; o << " partTemplate = swApp.GetUserPreferenceStringValue(swDefaultTemplatePart)\n"; o << " Set swModel = swApp.NewDocument(partTemplate, 0, 0, 0)\n"; o << " If swModel Is Nothing Then\n"; o << " MsgBox \"Could not create a new part. Check your default part template.\"\n"; o << " Exit Sub\n"; o << " End If\n"; o << " Set swSketchMgr = swModel.SketchManager\n"; o << " Set swFeatMgr = swModel.FeatureManager\n\n"; o << " ' ---- Base plate (boss-extrude on Front Plane) ----\n"; o << " boolstatus = swModel.Extension.SelectByID2(\"Front Plane\", \"PLANE\", 0, 0, 0, " "False, 0, Nothing, 0)\n"; o << " swSketchMgr.InsertSketch True\n"; o << " swSketchMgr.CreateCornerRectangle " << f(umin * MM) << ", " << f(vmin * MM) << ", 0, " << f(umax * MM) << ", " << f(vmax * MM) << ", 0\n"; o << " swModel.ClearSelection2 True\n"; o << " swSketchMgr.InsertSketch True\n"; // close the sketch o << " Set swFeat = swFeatMgr.FeatureExtrusion3(True, False, False, 0, 0, " << f(bp.thickness * MM) << ", 0.0, False, False, False, False, " "0.01745329, 0.01745329, False, False, False, False, True, True, True, 0, 0, False)\n"; o << " swModel.ClearSelection2 True\n\n"; o << " ' ---- Holes (one sketch + cut per hole so through and blind depths are " "honoured) ----\n"; o << " ' swEndCondThroughAll = 1, swEndCondBlind = 0\n"; for (size_t i = 0; i < bp.holes.size(); ++i) { const auto& h = bp.holes[i]; Vec3 r = h.center - d.origin; double cu = dot(r, u), cv = dot(r, v), rad = h.diameter * 0.5; o << " ' hole " << (i + 1); if (!h.thread.empty()) o << " thread " << h.thread; o << " (d=" << h.diameter << " mm, " << (h.through ? "through)" : ("blind depth " + f(h.depth) + " mm)")) << "\n"; o << " boolstatus = swModel.Extension.SelectByID2(\"Front Plane\", \"PLANE\", " "0, 0, 0, False, 0, Nothing, 0)\n"; o << " swSketchMgr.InsertSketch True\n"; o << " swSketchMgr.CreateCircleByRadius " << f(cu * MM) << ", " << f(cv * MM) << ", 0, " << f(rad * MM) << "\n"; o << " swModel.ClearSelection2 True\n"; o << " swSketchMgr.InsertSketch True\n"; // close sketch // T1: 1 = through all, 0 = blind (D1 = depth in metres). Cut runs into the plate. const int t1 = h.through ? 1 : 0; const std::string d1 = h.through ? "0.01" : f(h.depth * MM); o << " Set swFeat = swFeatMgr.FeatureCut4(True, False, False, " << t1 << ", 0, " << d1 << ", 0.01, False, False, False, False, 0.01745329, 0.01745329, " "False, False, False, False, False, True, True, True, True, False, False, " "0, 0, False, False)\n"; o << " If swFeat Is Nothing Then\n"; o << " MsgBox \"scan2cad: cut failed for hole " << (i + 1) << ".\"\n"; o << " Exit Sub\n"; o << " End If\n"; o << " swModel.ClearSelection2 True\n"; } o << "\n"; // thread notes bool anyThread = false; for (const auto& h : bp.holes) if (!h.thread.empty()) anyThread = true; if (anyThread) { o << " ' ---- Thread notes ----\n"; o << " ' The following holes were tagged with thread specs from real-world\n"; o << " ' measurements. Apply a Cosmetic Thread or Hole Wizard tap manually,\n"; o << " ' or extend this macro with InsertCosmeticThread:\n"; for (size_t i = 0; i < bp.holes.size(); ++i) if (!bp.holes[i].thread.empty()) o << " ' hole " << (i + 1) << ": " << bp.holes[i].thread << "\n"; o << "\n"; } o << " swModel.ViewZoomtofit2\n"; o << " swModel.EditRebuild3\n"; if (!stepOutWinPath.empty()) { o << " ' ---- Export a clean STEP from SolidWorks itself ----\n"; std::string esc; for (char c : stepOutWinPath) { if (c == '\\') esc += "\\"; esc += c; } o << " Dim errs As Long, warns As Long\n"; o << " boolstatus = swModel.Extension.SaveAs(\"" << stepOutWinPath << "\", 0, 1, Nothing, errs, warns)\n"; } o << " MsgBox \"scan2cad: part built with " << bp.holes.size() << " hole(s).\"\n"; o << "End Sub\n"; return o.str(); } static std::string mm(double v) { // format a raw millimetre value for comments std::ostringstream s; s.setf(std::ios::fixed); s.precision(2); s << v; return s.str(); } std::string generateInterfaceVBA(const std::vector& holes, const builder::RefFrame& fr) { const double MM = 0.001; // SolidWorks API works in metres const double stub = 15.0; // per-hole axis stub half-length, mm std::ostringstream o; o << "' ==================================================================\n"; o << "' scan2cad — mounting-hole INTERFACE for bracket design\n"; o << "' A 3D sketch with a point at each hole centre and a construction line\n"; o << "' along each hole axis, plus the bolt pattern in a hole-derived frame.\n"; o << "' Build your bracket against these reference points/axes.\n"; o << "' Tools > Macro > New, paste this, then Run. Units: metres (SW API).\n"; o << "' ==================================================================\n"; o << "Dim swApp As SldWorks.SldWorks\n"; o << "Dim swModel As SldWorks.ModelDoc2\n"; o << "Dim swSketchMgr As SldWorks.SketchManager\n"; o << "Dim boolstatus As Boolean\n\n"; o << "Sub main()\n"; o << " Set swApp = Application.SldWorks\n"; o << " Dim partTemplate As String\n"; o << " partTemplate = swApp.GetUserPreferenceStringValue(swDefaultTemplatePart)\n"; o << " Set swModel = swApp.NewDocument(partTemplate, 0, 0, 0)\n"; o << " If swModel Is Nothing Then\n"; o << " MsgBox \"Could not create a new part. Check your default part template.\"\n"; o << " Exit Sub\n"; o << " End If\n"; o << " Set swSketchMgr = swModel.SketchManager\n\n"; o << " ' ---- Hole centres + axis stubs as a 3D sketch ----\n"; o << " swSketchMgr.Insert3DSketch True\n"; for (size_t i = 0; i < holes.size(); ++i) { const auto& h = holes[i]; Vec3 ax = normalize(h.axis); Vec3 a = h.center - ax * stub, b = h.center + ax * stub; o << " ' hole " << (i + 1) << " Ø" << mm(h.diameter) << " mm" << (h.thread.empty() ? "" : (" thread " + h.thread)) << "\n"; o << " swSketchMgr.CreatePoint " << f(h.center.x * MM) << ", " << f(h.center.y * MM) << ", " << f(h.center.z * MM) << "\n"; o << " swSketchMgr.CreateLine " << f(a.x * MM) << ", " << f(a.y * MM) << ", " << f(a.z * MM) << ", " << f(b.x * MM) << ", " << f(b.y * MM) << ", " << f(b.z * MM) << "\n"; } o << " swSketchMgr.Insert3DSketch True\n\n"; // close the sketch // Reference frame + pattern, as comments (mm) — the numbers you dimension against. o << " ' ---- Reference frame (derived from the bolt pattern) ----\n"; o << " ' origin (mm): " << mm(fr.origin.x) << ", " << mm(fr.origin.y) << ", " << mm(fr.origin.z) << "\n"; o << " ' x axis: " << mm(fr.x.x) << ", " << mm(fr.x.y) << ", " << mm(fr.x.z) << "\n"; o << " ' y axis: " << mm(fr.y.x) << ", " << mm(fr.y.y) << ", " << mm(fr.y.z) << "\n"; o << " ' z (bolt-up): " << mm(fr.z.x) << ", " << mm(fr.z.y) << ", " << mm(fr.z.z) << "\n"; o << " ' ---- Hole centres in the frame (mm: x-right, y-up, z-along bolt) ----\n"; for (size_t i = 0; i < holes.size(); ++i) { Vec3 d = holes[i].center - fr.origin; o << " ' hole " << (i + 1) << ": x=" << mm(dot(d, fr.x)) << " y=" << mm(dot(d, fr.y)) << " z=" << mm(dot(d, fr.z)) << " Ø" << mm(holes[i].diameter) << "\n"; } o << " ' ---- Bolt pattern (centre-to-centre spacing, mm) ----\n"; for (size_t i = 0; i < holes.size(); ++i) for (size_t j = i + 1; j < holes.size(); ++j) { Vec3 d = holes[i].center - holes[j].center; o << " ' hole " << (i + 1) << "<->" << (j + 1) << ": " << mm(std::sqrt(dot(d, d))) << "\n"; } // Coordinate system from the chosen scan features: origin + a +X point + a +Y point, // 30 mm out along the frame axes, selected by coordinate (marks 1/2/4) then built. Vec3 O = fr.origin, Xp = fr.origin + fr.x * 30.0, Yp = fr.origin + fr.y * 30.0; auto pt = [&](const Vec3& p) { return f(p.x * MM) + ", " + f(p.y * MM) + ", " + f(p.z * MM); }; o << " ' ---- Coordinate system (origin/X/Y from the chosen holes) ----\n"; o << " swSketchMgr.Insert3DSketch True\n"; o << " swSketchMgr.CreatePoint " << pt(O) << "\n"; o << " swSketchMgr.CreatePoint " << pt(Xp) << "\n"; o << " swSketchMgr.CreatePoint " << pt(Yp) << "\n"; o << " swSketchMgr.Insert3DSketch True\n"; o << " swModel.ClearSelection2 True\n"; o << " ' origin=mark 1, +X point=mark 2, +Y point=mark 4\n"; o << " boolstatus = swModel.Extension.SelectByID2(\"\", \"EXTSKETCHPOINT\", " << pt(O) << ", False, 1, Nothing, 0)\n"; o << " boolstatus = swModel.Extension.SelectByID2(\"\", \"EXTSKETCHPOINT\", " << pt(Xp) << ", True, 2, Nothing, 0)\n"; o << " boolstatus = swModel.Extension.SelectByID2(\"\", \"EXTSKETCHPOINT\", " << pt(Yp) << ", True, 4, Nothing, 0)\n"; o << " boolstatus = swModel.InsertCoordinateSystem(False, False, False)\n"; o << " swModel.ClearSelection2 True\n"; o << "\n swModel.ViewZoomtofit2\n"; o << " MsgBox \"scan2cad: interface with " << holes.size() << " mounting hole(s) + coordinate system placed.\"\n"; o << "End Sub\n"; return o.str(); } static std::string vbaString(const std::string& s) { std::string out; for (char c : s) { if (c == '"') out += '"'; // VBA escapes a quote by doubling it out += c; } return out; } std::string generateAssemblyVBA(const std::string& winDir) { std::ostringstream o; o << "' ==================================================================\n"; o << "' scan2cad — SolidWorks interface + scan-context assembly\n"; o << "' Put scan2cad_interface.step and scan2cad_scan.stl in FOLDER below.\n"; o << "' This imports each file as a part and builds scan2cad_assembly.sldasm.\n"; o << "' The mesh and solids share the scan coordinate frame, so no mates are\n"; o << "' needed: both components are inserted and fixed at the origin.\n"; o << "' SolidWorks 2020+ with an English default assembly template.\n"; o << "' Tools > Macro > New, paste this, then Run.\n"; o << "' ==================================================================\n"; o << "Const FOLDER = \"" << vbaString(winDir) << "\"\n"; o << "Const STEP_FILE = \"scan2cad_interface.step\"\n"; o << "Const MESH_FILE = \"scan2cad_scan.stl\"\n"; o << "' Compatibility aliases for the version-sensitive ImportAs property.\n"; o << "Private Const swImportStlVrmlDataAsGraphicsBody As Long = 0\n"; o << "Private Const swImportStlVrmlDataAsSolidBody As Long = 2\n\n"; o << "Dim swApp As SldWorks.SldWorks\n"; o << "Dim stepModel As SldWorks.ModelDoc2\n"; o << "Dim meshModel As SldWorks.ModelDoc2\n"; o << "Dim asmModel As SldWorks.ModelDoc2\n"; o << "Dim swAssy As SldWorks.AssemblyDoc\n"; o << "Dim stepComp As SldWorks.Component2\n"; o << "Dim meshComp As SldWorks.Component2\n"; o << "Dim boolstatus As Boolean\n\n"; o << "Sub main()\n"; o << " Set swApp = Application.SldWorks\n"; o << " Dim stepPath As String, meshPath As String\n"; o << " Dim stepPartPath As String, meshPartPath As String, asmPath As String\n"; o << " stepPath = FOLDER & \"\\\" & STEP_FILE\n"; o << " meshPath = FOLDER & \"\\\" & MESH_FILE\n"; o << " stepPartPath = FOLDER & \"\\scan2cad_interface.sldprt\"\n"; o << " meshPartPath = FOLDER & \"\\scan2cad_scan.sldprt\"\n"; o << " asmPath = FOLDER & \"\\scan2cad_assembly.sldasm\"\n\n"; o << " Dim errs As Long, warns As Long, firstErrs As Long\n"; o << " Dim importStepData As SldWorks.ImportStepData\n\n"; o << " ' ---- Step A: import the interface STEP and save it as a native part ----\n"; o << " ' LoadFile4 is the supported foreign-file route. With 3D Interconnect on,\n"; o << " ' SolidWorks may ignore the import-data settings and create a linked part.\n"; o << " On Error Resume Next\n"; o << " Set importStepData = swApp.GetImportFileData(stepPath)\n"; o << " On Error GoTo 0\n"; o << " errs = 0\n"; o << " warns = 0\n"; o << " Set stepModel = swApp.LoadFile4(stepPath, \"r\", importStepData, errs)\n"; o << " firstErrs = errs\n"; o << " If stepModel Is Nothing Then\n"; o << " ' 3D Interconnect fallback: ask OpenDoc6 to open the STEP as a part.\n"; o << " errs = 0\n"; o << " warns = 0\n"; o << " Set stepModel = swApp.OpenDoc6(stepPath, swDocPART, _\n"; o << " swOpenDocOptions_Silent, \"\", errs, warns)\n"; o << " End If\n"; o << " If stepModel Is Nothing Then\n"; o << " MsgBox \"scan2cad: could not import \" & stepPath & vbCrLf & _\n"; o << " \"LoadFile4 errors: \" & firstErrs & vbCrLf & _\n"; o << " \"OpenDoc6 errors: \" & errs & \", warnings: \" & warns\n"; o << " Exit Sub\n"; o << " End If\n"; o << " errs = 0\n"; o << " warns = 0\n"; o << " boolstatus = stepModel.Extension.SaveAs(stepPartPath, _\n"; o << " swSaveAsCurrentVersion, swSaveAsOptions_Silent, Nothing, errs, warns)\n"; o << " If Not boolstatus Then\n"; o << " MsgBox \"scan2cad: could not save \" & stepPartPath & vbCrLf & _\n"; o << " \"Errors: \" & errs & \", warnings: \" & warns\n"; o << " Exit Sub\n"; o << " End If\n\n"; o << " ' ---- Step B: import the STL as a graphics body and save a native part ----\n"; o << " Dim importMeshData As Object\n"; o << " Dim oldStlUnits As Long, oldStlModelType As Long\n"; o << " Dim unitsCaptured As Boolean, modelTypeCaptured As Boolean\n"; o << " ' IMPORTANT: if the mesh imports 1000x too big/small set\n"; o << " ' Tools>Options>Import>STL/VRML units to mm.\n"; o << " ' These preferences are the documented SolidWorks 2020+ STL controls.\n"; o << " On Error Resume Next\n"; o << " Err.Clear\n"; o << " oldStlUnits = swApp.GetUserPreferenceIntegerValue(swImportStlVrmlUnits)\n"; o << " unitsCaptured = (Err.Number = 0)\n"; o << " Err.Clear\n"; o << " oldStlModelType = swApp.GetUserPreferenceIntegerValue(swImportStlVrmlModelType)\n"; o << " modelTypeCaptured = (Err.Number = 0)\n"; o << " Err.Clear\n"; o << " boolstatus = swApp.SetUserPreferenceIntegerValue(swImportStlVrmlUnits, swMM)\n"; o << " boolstatus = swApp.SetUserPreferenceIntegerValue(swImportStlVrmlModelType, _\n"; o << " swImportStlVrmlModelType_Graphics)\n"; o << " Set importMeshData = swApp.GetImportFileData(meshPath)\n"; o << " ' API-CONFIDENCE: ImportStlVrmlData.ImportAs is version-sensitive and is\n"; o << " ' late-bound here; the documented preferences above remain the fallback.\n"; o << " If Not importMeshData Is Nothing Then\n"; o << " importMeshData.ImportAs = swImportStlVrmlDataAsGraphicsBody\n"; o << " ' importMeshData.ImportAs = swImportStlVrmlDataAsSolidBody\n"; o << " End If\n"; o << " Err.Clear\n"; o << " On Error GoTo 0\n\n"; o << " errs = 0\n"; o << " warns = 0\n"; o << " Set meshModel = swApp.LoadFile4(meshPath, \"r\", importMeshData, errs)\n"; o << " firstErrs = errs\n"; o << " If meshModel Is Nothing Then\n"; o << " ' Retry without the optional import-data object; preferences still apply.\n"; o << " errs = 0\n"; o << " Set meshModel = swApp.LoadFile4(meshPath, \"r\", Nothing, errs)\n"; o << " End If\n"; o << " ' Always restore the user's STL import settings, even when loading failed.\n"; o << " On Error Resume Next\n"; o << " If unitsCaptured Then\n"; o << " boolstatus = swApp.SetUserPreferenceIntegerValue(swImportStlVrmlUnits, _\n"; o << " oldStlUnits)\n"; o << " End If\n"; o << " If modelTypeCaptured Then\n"; o << " boolstatus = swApp.SetUserPreferenceIntegerValue(swImportStlVrmlModelType, _\n"; o << " oldStlModelType)\n"; o << " End If\n"; o << " On Error GoTo 0\n"; o << " If meshModel Is Nothing Then\n"; o << " MsgBox \"scan2cad: could not import \" & meshPath & vbCrLf & _\n"; o << " \"First LoadFile4 errors: \" & firstErrs & vbCrLf & _\n"; o << " \"Retry errors: \" & errs & \", warnings: \" & warns\n"; o << " Exit Sub\n"; o << " End If\n"; o << " errs = 0\n"; o << " warns = 0\n"; o << " boolstatus = meshModel.Extension.SaveAs(meshPartPath, _\n"; o << " swSaveAsCurrentVersion, swSaveAsOptions_Silent, Nothing, errs, warns)\n"; o << " If Not boolstatus Then\n"; o << " MsgBox \"scan2cad: could not save \" & meshPartPath & vbCrLf & _\n"; o << " \"Errors: \" & errs & \", warnings: \" & warns\n"; o << " Exit Sub\n"; o << " End If\n\n"; o << " ' ---- Step C: insert both native parts at the origin and fix them ----\n"; o << " Dim asmTemplate As String\n"; o << " asmTemplate = swApp.GetUserPreferenceStringValue(swDefaultTemplateAssembly)\n"; o << " Set asmModel = swApp.NewDocument(asmTemplate, 0, 0, 0)\n"; o << " If asmModel Is Nothing Then\n"; o << " MsgBox \"scan2cad: could not create an assembly. Check your default \" & _\n"; o << " \"assembly template.\"\n"; o << " Exit Sub\n"; o << " End If\n"; o << " Set swAssy = asmModel\n"; o << " Set stepComp = swAssy.AddComponent5(stepPartPath, _\n"; o << " swAddComponentConfigOptions_CurrentSelectedConfig, \"\", False, \"\", _\n"; o << " 0#, 0#, 0#)\n"; o << " If stepComp Is Nothing Then\n"; o << " MsgBox \"scan2cad: could not add \" & stepPartPath & \" to the assembly.\"\n"; o << " Exit Sub\n"; o << " End If\n"; o << " asmModel.ClearSelection2 True\n"; o << " boolstatus = stepComp.Select2(False, 0)\n"; o << " If Not boolstatus Then\n"; o << " MsgBox \"scan2cad: could not select the interface component to fix it.\"\n"; o << " Exit Sub\n"; o << " End If\n"; o << " swAssy.FixComponent\n"; o << " If Not stepComp.IsFixed() Then\n"; o << " MsgBox \"scan2cad: interface component did not remain fixed.\"\n"; o << " Exit Sub\n"; o << " End If\n"; o << " asmModel.ClearSelection2 True\n\n"; o << " Set meshComp = swAssy.AddComponent5(meshPartPath, _\n"; o << " swAddComponentConfigOptions_CurrentSelectedConfig, \"\", False, \"\", _\n"; o << " 0#, 0#, 0#)\n"; o << " If meshComp Is Nothing Then\n"; o << " MsgBox \"scan2cad: could not add \" & meshPartPath & \" to the assembly.\"\n"; o << " Exit Sub\n"; o << " End If\n"; o << " asmModel.ClearSelection2 True\n"; o << " boolstatus = meshComp.Select2(False, 0)\n"; o << " If Not boolstatus Then\n"; o << " MsgBox \"scan2cad: could not select the mesh component to fix it.\"\n"; o << " Exit Sub\n"; o << " End If\n"; o << " swAssy.FixComponent\n"; o << " If Not meshComp.IsFixed() Then\n"; o << " MsgBox \"scan2cad: mesh component did not remain fixed.\"\n"; o << " Exit Sub\n"; o << " End If\n"; o << " asmModel.ClearSelection2 True\n\n"; o << " asmModel.EditRebuild3\n"; o << " asmModel.ViewZoomtofit2\n"; o << " errs = 0\n"; o << " warns = 0\n"; o << " boolstatus = asmModel.Extension.SaveAs(asmPath, _\n"; o << " swSaveAsCurrentVersion, swSaveAsOptions_Silent, Nothing, errs, warns)\n"; o << " If Not boolstatus Then\n"; o << " MsgBox \"scan2cad: assembly was built but could not be saved to \" & _\n"; o << " asmPath & vbCrLf & \"Errors: \" & errs & \", warnings: \" & warns\n"; o << " Exit Sub\n"; o << " End If\n"; o << " MsgBox \"scan2cad: interface + scan assembly built and saved to \" & asmPath\n"; o << "End Sub\n"; return o.str(); } } // namespace macrogen