#include "builder.hpp" #include "solid.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace builder { using geom::dot; using geom::normalize; using geom::Vec3; static gp_Pnt P(const Vec3& v) { return gp_Pnt(v.x, v.y, v.z); } static gp_Dir D(const Vec3& v) { return gp_Dir(v.x, v.y, v.z); } TopoDS_Shape buildSolid(const BuildParams& bp, int& holesCut, std::string& err) { holesCut = 0; if (bp.holes.empty()) { err = "no holes provided"; return TopoDS_Shape(); } Vec3 n = normalize(bp.datum.normal); Vec3 u = normalize(bp.datum.u); Vec3 v = normalize(bp.datum.v); const Vec3& o = bp.datum.origin; if (!(bp.thickness > 0)) { err = "plate thickness must be greater than 0"; return TopoDS_Shape(); } // Validate every hole up front so both the STEP and the macro (which share these // params) agree and neither is built from bad geometry. Holes are modeled exactly // perpendicular to the datum; a fitted axis more than perpTolDeg off-normal is an // oblique bore, which is out of scope, so reject it with the offending hole named. const double perpTolDeg = 10.0; const double perpCos = std::cos(perpTolDeg * M_PI / 180.0); for (size_t i = 0; i < bp.holes.size(); ++i) { const auto& h = bp.holes[i]; std::string tag = h.label.empty() ? ("hole " + std::to_string(i + 1)) : h.label; double c = std::fabs(dot(normalize(h.axis), n)); // axis sign is arbitrary if (c < perpCos) { double deg = std::acos(std::min(1.0, c)) * 180.0 / M_PI; char buf[64]; std::snprintf(buf, sizeof buf, "%.1f", deg); err = tag + " axis is " + buf + "\xc2\xb0 off the datum normal; angled holes are unsupported"; return TopoDS_Shape(); } if (!h.through && !(h.depth > 0 && h.depth < bp.thickness)) { err = tag + " blind depth must be greater than 0 and less than the plate thickness"; return TopoDS_Shape(); } } // footprint of the holes in datum-local (u,v), expanded by margin double umin = 1e300, umax = -1e300, vmin = 1e300, vmax = -1e300; for (const auto& h : bp.holes) { Vec3 d = h.center - o; double cu = dot(d, u), cv = dot(d, v), r = h.diameter * 0.5; umin = std::min(umin, cu - r); umax = std::max(umax, cu + r); vmin = std::min(vmin, cv - r); vmax = std::max(vmax, cv + r); } umin -= bp.margin; umax += bp.margin; vmin -= bp.margin; vmax += bp.margin; if (umax - umin <= 0 || vmax - vmin <= 0) { err = "degenerate plate footprint"; return TopoDS_Shape(); } try { // Plate from explicit world-space corners, prism'd along -normal. Vec3 c0 = o + u * umin + v * vmin; Vec3 c1 = o + u * umax + v * vmin; Vec3 c2 = o + u * umax + v * vmax; Vec3 c3 = o + u * umin + v * vmax; BRepBuilderAPI_MakePolygon poly(P(c0), P(c1), P(c2), P(c3), Standard_True); BRepBuilderAPI_MakeFace mkFace(poly.Wire(), Standard_True); gp_Vec extrude(n.x * -bp.thickness, n.y * -bp.thickness, n.z * -bp.thickness); TopoDS_Shape solid = BRepPrimAPI_MakePrism(mkFace.Face(), extrude).Shape(); const double overshoot = std::max(1.0, bp.thickness * 0.25); for (const auto& h : bp.holes) { // Accepted holes are modeled exactly perpendicular: drill along the datum // normal, not the noisy fitted axis (validated within perpTolDeg above). Vec3 ax = n; Vec3 d = h.center - o; Vec3 top = h.center - n * dot(d, n); // project center onto datum plane double len = h.through ? (bp.thickness + 2 * overshoot) : (h.depth + overshoot); Vec3 start = top + ax * overshoot; gp_Ax2 cylAx(P(start), D(ax * -1.0)); TopoDS_Shape cyl = BRepPrimAPI_MakeCylinder(cylAx, h.diameter * 0.5, len).Shape(); BRepAlgoAPI_Cut cut(solid, cyl); cut.Build(); if (!cut.IsDone()) { err = "boolean cut failed for a hole"; return TopoDS_Shape(); } solid = cut.Shape(); ++holesCut; } return solid; } catch (const std::exception& e) { err = std::string("exception: ") + e.what(); return TopoDS_Shape(); } catch (...) { err = "unknown OpenCASCADE exception during build"; return TopoDS_Shape(); } } BuildResult buildAndExport(const BuildParams& bp, const std::string& stepPath) { BuildResult res; if (bp.holes.empty()) { res.error = "no holes provided"; return res; } int holesCut = 0; TopoDS_Shape solid = buildSolid(bp, holesCut, res.error); if (solid.IsNull()) return res; res.holesCut = holesCut; try { // --- STEP export, units in millimetres --- Interface_Static::SetCVal("write.step.unit", "MM"); Interface_Static::SetIVal("write.step.schema", 3); // AP214 STEPControl_Writer writer; if (writer.Transfer(solid, STEPControl_AsIs) != IFSelect_RetDone) { res.error = "STEP transfer failed"; return res; } if (writer.Write(stepPath.c_str()) != IFSelect_RetDone) { res.error = "STEP write failed"; return res; } } catch (const std::exception& e) { res.error = std::string("exception: ") + e.what(); return res; } catch (...) { res.error = "unknown OpenCASCADE exception during build"; return res; } res.ok = true; res.stepPath = stepPath; return res; } RefFrame frameFromHoles(const std::vector& holes, int originIdx, int xIdx, int zIdx, std::string& err) { RefFrame fr; const int n = (int)holes.size(); if (n == 0) { err = "no holes to define a frame"; return fr; } // z: a named hole's axis, else the average hole axis (each flipped into a common // hemisphere so they don't cancel). Vec3 ref = normalize(holes[0].axis); if (zIdx >= 0 && zIdx < n) { fr.z = normalize(holes[zIdx].axis); } else { Vec3 zsum{0, 0, 0}; for (const auto& h : holes) { Vec3 a = normalize(h.axis); if (dot(a, ref) < 0) a = a * -1.0; zsum = zsum + a; } fr.z = (std::sqrt(dot(zsum, zsum)) > 1e-9) ? normalize(zsum) : ref; } // origin: named hole, else the pattern centroid. if (originIdx >= 0 && originIdx < n) { fr.origin = holes[originIdx].center; } else { Vec3 c{0, 0, 0}; for (const auto& h : holes) c = c + h.center; fr.origin = c / (double)n; } // +x points toward the named hole (else the hole farthest from origin), projected // perpendicular to z so the frame is orthonormal. Vec3 target = fr.origin; if (xIdx >= 0 && xIdx < n) { target = holes[xIdx].center; } else { double best = -1; for (const auto& h : holes) { Vec3 d = h.center - fr.origin; double dd = dot(d, d); if (dd > best) { best = dd; target = h.center; } } } Vec3 xdir = target - fr.origin; xdir = xdir - fr.z * dot(xdir, fr.z); if (std::sqrt(dot(xdir, xdir)) < 1e-6) { // degenerate: any perpendicular will do Vec3 uu, vv; geom::basisFromNormal(fr.z, uu, vv); xdir = uu; } fr.x = normalize(xdir); fr.y = normalize(cross(fr.z, fr.x)); fr.x = normalize(cross(fr.y, fr.z)); // re-orthonormalize return fr; } BuildResult exportInterface(const std::vector& holes, const RefFrame& fr, const std::string& stepPath) { BuildResult res; if (holes.empty()) { res.error = "no holes provided"; return res; } try { BRep_Builder bb; TopoDS_Compound comp; bb.MakeCompound(comp); double ext = 0; for (const auto& h : holes) { Vec3 d = h.center - fr.origin; ext = std::max(ext, std::sqrt(dot(d, d))); } const double axisLen = std::max(ext * 1.2, 20.0); // coordinate-triad arm length const double stub = 15.0; // per-hole axis stub half-length auto addEdge = [&](const Vec3& a, const Vec3& b) { bb.Add(comp, BRepBuilderAPI_MakeEdge(P(a), P(b)).Edge()); }; // coordinate triad + origin marker addEdge(fr.origin, fr.origin + fr.x * axisLen); addEdge(fr.origin, fr.origin + fr.y * axisLen); addEdge(fr.origin, fr.origin + fr.z * axisLen); bb.Add(comp, BRepBuilderAPI_MakeVertex(P(fr.origin)).Vertex()); // per hole: centre vertex, axis stub, diameter circle for (const auto& h : holes) { Vec3 ax = normalize(h.axis); bb.Add(comp, BRepBuilderAPI_MakeVertex(P(h.center)).Vertex()); addEdge(h.center - ax * stub, h.center + ax * stub); if (h.diameter > 0) { gp_Circ circ(gp_Ax2(P(h.center), D(ax)), h.diameter * 0.5); bb.Add(comp, BRepBuilderAPI_MakeEdge(circ).Edge()); } } Interface_Static::SetCVal("write.step.unit", "MM"); Interface_Static::SetIVal("write.step.schema", 3); STEPControl_Writer writer; if (writer.Transfer(comp, STEPControl_AsIs) != IFSelect_RetDone) { res.error = "STEP transfer failed"; return res; } if (writer.Write(stepPath.c_str()) != IFSelect_RetDone) { res.error = "STEP write failed"; return res; } } catch (const std::exception& e) { res.error = std::string("exception: ") + e.what(); return res; } catch (...) { res.error = "unknown OpenCASCADE exception during interface export"; return res; } res.ok = true; res.stepPath = stepPath; res.holesCut = (int)holes.size(); return res; } BuildResult exportMounts(const std::vector& mounts, const RefFrame& fr, const std::string& stepPath, const RefGeometry* refs) { BuildResult res; if (mounts.empty()) { res.error = "no mounts provided"; return res; } try { BRep_Builder bb; TopoDS_Compound comp; bb.MakeCompound(comp); double ext = 0; for (const auto& mt : mounts) { Vec3 d = mt.seat - fr.origin; ext = std::max(ext, std::sqrt(dot(d, d))); } const double axisLen = std::max(ext * 1.2, 20.0); // coordinate triad + origin marker auto addEdge = [&](const Vec3& a, const Vec3& b) { bb.Add(comp, BRepBuilderAPI_MakeEdge(P(a), P(b)).Edge()); }; addEdge(fr.origin, fr.origin + fr.x * axisLen); addEdge(fr.origin, fr.origin + fr.y * axisLen); addEdge(fr.origin, fr.origin + fr.z * axisLen); bb.Add(comp, BRepBuilderAPI_MakeVertex(P(fr.origin)).Vertex()); int built = 0; for (const auto& mt : mounts) { Vec3 ax = normalize(mt.axis); double holeR = mt.holeDiameter * 0.5; double bossR = std::max(mt.bossDiameter * 0.5, holeR + 0.5); double bh = std::max(mt.bossHeight, 0.5); // Boss: solid cylinder seated on the plane, grown along +axis. gp_Ax2 bossAx(P(mt.seat), D(ax)); TopoDS_Shape boss = BRepPrimAPI_MakeCylinder(bossAx, bossR, bh).Shape(); // Coaxial hole: cut a full-length bore (overshoot both ends for a clean cut). Vec3 hstart = mt.seat - ax * 1.0; gp_Ax2 holeAx(P(hstart), D(ax)); TopoDS_Shape bore = BRepPrimAPI_MakeCylinder(holeAx, holeR, bh + 2.0).Shape(); BRepAlgoAPI_Cut cut(boss, bore); cut.Build(); if (!cut.IsDone()) { res.error = "boolean cut failed for " + mt.label; return res; } bb.Add(comp, cut.Shape()); ++built; // Reference mount-face patch (a small square planar face on the seat // plane). Mounts in a coplanar group share one merged face instead. if (mt.faceHalfSize > 0 && mt.group < 0) { Vec3 uu, vv; geom::basisFromNormal(ax, uu, vv); double s = mt.faceHalfSize; Vec3 c0 = mt.seat + uu * -s + vv * -s; Vec3 c1 = mt.seat + uu * s + vv * -s; Vec3 c2 = mt.seat + uu * s + vv * s; Vec3 c3 = mt.seat + uu * -s + vv * s; BRepBuilderAPI_MakePolygon poly(P(c0), P(c1), P(c2), P(c3), Standard_True); bb.Add(comp, BRepBuilderAPI_MakeFace(poly.Wire(), Standard_True).Face()); } } // One shared reference face per coplanar group: its mounts sit on a single // plane, so the STEP states that with a single face spanning all of them — // not N near-identical planes fractions of a degree apart. std::map> byGroup; for (const auto& mt : mounts) if (mt.group >= 0) byGroup[mt.group].push_back(&mt); for (const auto& kv : byGroup) { const auto& ms = kv.second; Vec3 n = normalize(ms[0]->axis); Vec3 uu, vv; geom::basisFromNormal(n, uu, vv); const Vec3& o = ms[0]->seat; double umin = 1e300, umax = -1e300, vmin = 1e300, vmax = -1e300, pad = 0; for (const Mount* mp : ms) { Vec3 d = mp->seat - o; double a = dot(d, uu), b2 = dot(d, vv); umin = std::min(umin, a); umax = std::max(umax, a); vmin = std::min(vmin, b2); vmax = std::max(vmax, b2); pad = std::max(pad, mp->faceHalfSize); } if (pad <= 0) pad = 8.0; umin -= pad; umax += pad; vmin -= pad; vmax += pad; Vec3 c0 = o + uu * umin + vv * vmin; Vec3 c1 = o + uu * umax + vv * vmin; Vec3 c2 = o + uu * umax + vv * vmax; Vec3 c3 = o + uu * umin + vv * vmax; BRepBuilderAPI_MakePolygon poly(P(c0), P(c1), P(c2), P(c3), Standard_True); bb.Add(comp, BRepBuilderAPI_MakeFace(poly.Wire(), Standard_True).Face()); } // User reference geometry: every extracted plane/line/point rides along, // so CAD gets the same datums the user aligned and measured against. if (refs) { for (const auto& rc : refs->planeRects) { BRepBuilderAPI_MakePolygon poly(P(rc[0]), P(rc[1]), P(rc[2]), P(rc[3]), Standard_True); if (poly.IsDone()) bb.Add(comp, BRepBuilderAPI_MakeFace(poly.Wire(), Standard_True).Face()); } for (const auto& seg : refs->lines) { Vec3 d = seg[1] - seg[0]; if (dot(d, d) > 1e-12) bb.Add(comp, BRepBuilderAPI_MakeEdge(P(seg[0]), P(seg[1])).Edge()); } for (const auto& p : refs->points) bb.Add(comp, BRepBuilderAPI_MakeVertex(P(p)).Vertex()); } Interface_Static::SetCVal("write.step.unit", "MM"); Interface_Static::SetIVal("write.step.schema", 3); STEPControl_Writer writer; if (writer.Transfer(comp, STEPControl_AsIs) != IFSelect_RetDone) { res.error = "STEP transfer failed"; return res; } if (writer.Write(stepPath.c_str()) != IFSelect_RetDone) { res.error = "STEP write failed"; return res; } res.holesCut = built; } catch (const std::exception& e) { res.error = std::string("exception: ") + e.what(); return res; } catch (...) { res.error = "unknown OpenCASCADE exception during mount export"; return res; } res.ok = true; res.stepPath = stepPath; return res; } BuildResult exportDatums(const Vec3& bbMin, const Vec3& bbMax, const std::string& stepPath, const RefGeometry* refs) { BuildResult res; try { // per-axis span, grown to include the origin and padded 10% double lo[3] = {std::min(bbMin.x, 0.0), std::min(bbMin.y, 0.0), std::min(bbMin.z, 0.0)}; double hi[3] = {std::max(bbMax.x, 0.0), std::max(bbMax.y, 0.0), std::max(bbMax.z, 0.0)}; double span = 0; for (int k = 0; k < 3; ++k) span = std::max(span, hi[k] - lo[k]); double pad = std::max(span * 0.1, 5.0); for (int k = 0; k < 3; ++k) { lo[k] -= pad; hi[k] += pad; } auto at = [](int a, double va, int b, double vb) { double v[3] = {0, 0, 0}; v[a] = va; v[b] = vb; return Vec3{v[0], v[1], v[2]}; }; BRep_Builder bb; TopoDS_Compound comp; bb.MakeCompound(comp); // plane spanned by axes (a, b): XY, YZ, XZ const int planes[3][2] = {{0, 1}, {1, 2}, {0, 2}}; for (const auto& pl : planes) { int a = pl[0], b = pl[1]; BRepBuilderAPI_MakePolygon poly(P(at(a, lo[a], b, lo[b])), P(at(a, hi[a], b, lo[b])), P(at(a, hi[a], b, hi[b])), P(at(a, lo[a], b, hi[b])), Standard_True); bb.Add(comp, BRepBuilderAPI_MakeFace(poly.Wire(), Standard_True).Face()); } for (int k = 0; k < 3; ++k) bb.Add(comp, BRepBuilderAPI_MakeEdge(P({0, 0, 0}), P(at(k, hi[k], (k + 1) % 3, 0))).Edge()); bb.Add(comp, BRepBuilderAPI_MakeVertex(P({0, 0, 0})).Vertex()); if (refs) { for (const auto& rc : refs->planeRects) { BRepBuilderAPI_MakePolygon poly(P(rc[0]), P(rc[1]), P(rc[2]), P(rc[3]), Standard_True); if (poly.IsDone()) bb.Add(comp, BRepBuilderAPI_MakeFace(poly.Wire(), Standard_True).Face()); } for (const auto& seg : refs->lines) { Vec3 d = seg[1] - seg[0]; if (dot(d, d) > 1e-12) bb.Add(comp, BRepBuilderAPI_MakeEdge(P(seg[0]), P(seg[1])).Edge()); } for (const auto& p : refs->points) bb.Add(comp, BRepBuilderAPI_MakeVertex(P(p)).Vertex()); } Interface_Static::SetCVal("write.step.unit", "MM"); Interface_Static::SetIVal("write.step.schema", 3); STEPControl_Writer writer; if (writer.Transfer(comp, STEPControl_AsIs) != IFSelect_RetDone) { res.error = "STEP transfer failed"; return res; } if (writer.Write(stepPath.c_str()) != IFSelect_RetDone) { res.error = "STEP write failed"; return res; } } catch (const std::exception& e) { res.error = std::string("exception: ") + e.what(); return res; } catch (...) { res.error = "unknown OpenCASCADE exception during datum export"; return res; } res.ok = true; res.stepPath = stepPath; return res; } } // namespace builder