// main.cpp — scan2cad localhost server. // Serves the web UI and exposes mesh-fitting + reconstruction endpoints. #include #include #include #include #include #include #include #include #include #include #include #include #include #include "../third_party/httplib.h" #include "../third_party/json.hpp" #include "align.hpp" #include "builder.hpp" #include "discover.hpp" #include "fit.hpp" #include "geom.hpp" #include "history.hpp" #include "macro.hpp" #include "mesh.hpp" #include "meshedit.hpp" #include "prim.hpp" #include "zipw.hpp" #include "surface.hpp" using json = nlohmann::json; using geom::Vec3; namespace { std::mutex g_mtx; mesh::Mesh g_mesh; history::History g_history(512ull * 1024 * 1024); meshedit::Analysis g_meshAnalysis; bool g_meshAnalysisValid = false; std::vector g_cloud; // raw scanner point cloud, in the mesh's frame align::Mat3 g_frameR{1, 0, 0, 0, 1, 0, 0, 0, 1}; geom::Vec3 g_frameT{0, 0, 0}; // cumulative mesh_from_scanner rigid transform std::string g_outDir = "output"; std::vector g_selVerts; // one active Extract Primitives selection std::vector g_prims; // baked primitive entries, in creation order int g_nextPrimId = 1; std::unordered_map g_surfaces; std::unordered_set g_surfaceExported; Vec3 vecOf(const json& a, Vec3 fallback = {0, 0, 0}) { if (a.is_array() && a.size() == 3) return {a[0].get(), a[1].get(), a[2].get()}; return fallback; } json arr(const Vec3& v) { return json::array({v.x, v.y, v.z}); } json arr(const align::Mat3& R) { json out = json::array(); for (double value : R) out.push_back(value); return out; } align::Mat3 multiply(const align::Mat3& a, const align::Mat3& b) { align::Mat3 out{}; for (int row = 0; row < 3; ++row) for (int col = 0; col < 3; ++col) for (int k = 0; k < 3; ++k) out[3 * row + col] += a[3 * row + k] * b[3 * k + col]; return out; } void composeFrame(const align::Mat3& R, const Vec3& t) { g_frameT = align::transformDirection(R, g_frameT) + t; g_frameR = multiply(R, g_frameR); } json selectionResponse() { json preview = json::array(); size_t stride = std::max(1, (g_selVerts.size() + 19999) / 20000); for (size_t k = 0; k < g_selVerts.size(); k += stride) { int i = g_selVerts[k]; if (i < 0 || i >= (int)g_mesh.verts.size()) continue; const auto& p = g_mesh.verts[i]; preview.push_back(p.x); preview.push_back(p.y); preview.push_back(p.z); } return {{"ok", true}, {"nsel", (int)g_selVerts.size()}, {"preview", std::move(preview)}}; } const json* registeredPrim(int id) { for (const auto& p : g_prims) if (p.value("id", -1) == id) return &p; return nullptr; } struct AlignmentRequest { align::Result frame; std::string error; }; // Point-based 3-2-1: {points:[[x,y,z] x3|5|6], rule:"ZZZ-YY-X", values:[6 mm], // flipPlane, flipLine, planeHint?, translate?}. AlignmentRequest buildPointsAlignmentRequest(const json& body) { AlignmentRequest request; try { align::PointsSpec spec; for (const json& p : body["points"]) { if (!p.is_array() || p.size() != 3) { request.error = "each point must be [x,y,z]"; return request; } spec.points.push_back(vecOf(p)); } spec.rule = body.value("rule", std::string("ZZZ-YY-X")); if (body.contains("values")) { const json& vals = body["values"]; if (!vals.is_array() || vals.size() != 6) { request.error = "values must hold 6 numbers"; return request; } for (int k = 0; k < 6; ++k) spec.values[k] = vals[k].get(); } spec.flipPlane = body.value("flipPlane", false); spec.flipLine = body.value("flipLine", false); if (body.contains("planeHint")) spec.planeHint = vecOf(body["planeHint"]); if (body.contains("translate") && (!body["translate"].is_array() || body["translate"].size() != 3)) { request.error = "translate must be [x,y,z]"; return request; } Vec3 translate = body.contains("translate") ? vecOf(body["translate"]) : Vec3{0, 0, 0}; request.frame = align::buildFrameFromPoints(spec, translate); if (!request.frame.ok) request.error = request.frame.error; } catch (...) { request.error = "invalid alignment request"; } return request; } AlignmentRequest buildAlignmentRequest(const json& body) { // Direct rigid edit of an existing frame: {rigid:{rot90:"X|Y|Z"?, shift:[x,y,z]?}} // rotates about the world origin, then shifts. if (body.is_object() && body.contains("rigid") && body["rigid"].is_object()) { AlignmentRequest request; const json& rg = body["rigid"]; if (rg.contains("shift") && (!rg["shift"].is_array() || rg["shift"].size() != 3)) { request.error = "shift must be [x,y,z]"; return request; } try { request.frame = align::fromRigid(align::rot90(rg.value("rot90", std::string())), rg.contains("shift") ? vecOf(rg["shift"]) : Vec3{}); } catch (...) { request.error = "invalid rigid move"; } return request; } if (body.is_object() && body.contains("points") && body["points"].is_array()) return buildPointsAlignmentRequest(body); AlignmentRequest request; if (!body.is_object() || !body.contains("slots") || !body["slots"].is_array() || body["slots"].empty() || body["slots"].size() > 3) { request.error = "slots must contain one to three entries"; return request; } std::vector features; std::vector slots; features.reserve(body["slots"].size()); slots.reserve(body["slots"].size()); try { for (const json& item : body["slots"]) { if (!item.is_object() || !item.contains("id") || !item["id"].is_number_integer()) { request.error = "each slot needs an integer id"; return request; } int id = item["id"].get(); const json* registered = registeredPrim(id); if (!registered) { request.error = "unknown primitive id " + std::to_string(id); return request; } std::string kind = registered->value("kind", std::string()); if (kind == "surface") { request.error = "surface primitives cannot be used for alignment"; return request; } align::Feature feature; feature.id = id; if (kind == "plane") { feature.kind = align::FeatureKind::Plane; feature.anchor = vecOf((*registered)["origin"]); feature.direction = vecOf((*registered)["normal"]); } else if (kind == "line") { feature.kind = align::FeatureKind::LineLike; feature.anchor = vecOf((*registered)["p"]); feature.direction = vecOf((*registered)["d"]); } else if (kind == "cylinder") { feature.kind = align::FeatureKind::LineLike; feature.anchor = vecOf((*registered)["center"]); feature.direction = vecOf((*registered)["axis"]); } else if (kind == "cone") { feature.kind = align::FeatureKind::LineLike; feature.anchor = vecOf((*registered)["apex"]); feature.direction = vecOf((*registered)["axis"]); } else if (kind == "point") { feature.kind = align::FeatureKind::PointLike; feature.anchor = vecOf((*registered)["p"]); } else if (kind == "sphere") { feature.kind = align::FeatureKind::PointLike; feature.anchor = vecOf((*registered)["center"]); } else { request.error = "unsupported primitive kind " + kind; return request; } features.push_back(feature); align::Slot slot; slot.primId = id; slot.target = item.value("target", std::string()); slot.flip = item.value("flip", false); slots.push_back(std::move(slot)); } Vec3 translate = body.contains("translate") ? vecOf(body["translate"]) : Vec3{0, 0, 0}; if (body.contains("translate") && (!body["translate"].is_array() || body["translate"].size() != 3)) { request.error = "translate must be [x,y,z]"; return request; } request.frame = align::buildFrame(features, slots, translate); if (!request.frame.ok) request.error = request.frame.error; } catch (...) { request.error = "invalid alignment request"; } return request; } // Carry the whole Prims-step registry into a STEP: fitted planes as their // minimal-rectangle faces, reference/axis lines as edges, points (and sphere // centres) as vertices. CAD then has every datum the user extracted. builder::RefGeometry collectRefGeometry() { builder::RefGeometry refs; double refLen = std::max(g_mesh.bboxDiag() * 0.35, 25.0); for (const auto& p : g_prims) { const std::string kind = p.value("kind", ""); if (kind == "plane" && p.contains("rect") && p["rect"].is_array() && p["rect"].size() == 4) { std::array rc; for (int k = 0; k < 4; ++k) rc[k] = vecOf(p["rect"][k]); refs.planeRects.push_back(rc); } else if (kind == "line") { Vec3 o = vecOf(p["p"]), d = geom::normalize(vecOf(p["d"])); refs.lines.push_back({o - d * refLen, o + d * refLen}); } else if (kind == "cylinder" || kind == "cone") { // the fitted axis segment is itself a usable datum axis if (p.contains("p1") && p.contains("p2")) refs.lines.push_back({vecOf(p["p1"]), vecOf(p["p2"])}); else if (kind == "cone") { Vec3 apex = vecOf(p["apex"]), d = geom::normalize(vecOf(p["axis"])); refs.lines.push_back({apex + d * p.value("h1", 0.0), apex + d * p.value("h2", 0.0)}); } } else if (kind == "point") { refs.points.push_back(vecOf(p["p"])); } else if (kind == "sphere") { refs.points.push_back(vecOf(p["center"])); } } return refs; } json alignmentResponse(const align::Result& frame) { json axes = {{"x", arr(frame.axes[0])}, {"y", arr(frame.axes[1])}, {"z", arr(frame.axes[2])}}; return {{"ok", true}, {"R", arr(frame.R)}, {"t", arr(frame.t)}, {"rotLocked", frame.rotLocked}, {"transLocked", frame.transLocked}, {"fullyDefined", frame.fullyDefined}, {"overconstrained", frame.overconstrained}, {"origin", arr(frame.origin)}, {"axes", std::move(axes)}}; } void transformJsonVector(json& entry, const char* key, const align::Mat3& R, const Vec3& t, bool direction) { auto it = entry.find(key); if (it == entry.end() || !it->is_array() || it->size() != 3) return; Vec3 value = vecOf(*it); *it = arr(direction ? align::transformDirection(R, value) : align::transformPoint(R, t, value)); } void transformPrimitiveRegistry(const align::Mat3& R, const Vec3& t) { static const char* pointFields[] = { "origin", "center", "p1", "p2", "apex", "p"}; static const char* directionFields[] = { "normal", "u", "v", "axis", "d"}; for (json& entry : g_prims) { for (const char* field : pointFields) transformJsonVector(entry, field, R, t, false); for (const char* field : directionFields) transformJsonVector(entry, field, R, t, true); auto rect = entry.find("rect"); if (rect != entry.end() && rect->is_array()) for (json& corner : *rect) if (corner.is_array() && corner.size() == 3) corner = arr(align::transformPoint(R, t, vecOf(corner))); } } void transformSurfaceRegistry(const align::Mat3& R, const Vec3& t) { for (auto& item : g_surfaces) { surface::Fit& fit = item.second; for (Vec3& pole : fit.poles) pole = align::transformPoint(R, t, pole); fit.rectOrigin = align::transformPoint(R, t, fit.rectOrigin); fit.axisU = align::transformDirection(R, fit.axisU); fit.axisV = align::transformDirection(R, fit.axisV); fit.planeNormal = align::transformDirection(R, fit.planeNormal); for (Vec3& point : fit.preview.positions) point = align::transformPoint(R, t, point); std::string path = g_outDir + "/surface_" + std::to_string(item.first) + ".step"; std::remove(path.c_str()); } g_surfaceExported.clear(); } void invalidateMeshAnalysis() { g_meshAnalysis = {}; g_meshAnalysisValid = false; } const meshedit::Analysis& meshAnalysis() { if (!g_meshAnalysisValid) { g_meshAnalysis = meshedit::analyze(g_mesh); g_meshAnalysisValid = true; } return g_meshAnalysis; } json meshStatus() { const auto& a = meshAnalysis(); json components = json::array(); std::size_t componentCap = std::min(200, a.components.size()); for (std::size_t i = 0; i < componentCap; ++i) components.push_back({{"id", (int)i}, {"ntris", a.components[i].ntris}, {"area", a.components[i].area}}); json holes = json::array(); std::size_t holeCap = std::min(500, a.holes.size()); for (std::size_t i = 0; i < holeCap; ++i) { const auto& h = a.holes[i]; // Downsampled boundary polyline so the viewer can trace the actual rim — // a center+radius alone reads as a huge disc on long thin seam gaps. json loop = json::array(); std::size_t stride = std::max(1, h.vertices.size() / 48); for (std::size_t k = 0; k < h.vertices.size(); k += stride) loop.push_back(arr(g_mesh.verts[h.vertices[k]])); holes.push_back({{"id", (int)i}, {"nedges", h.nedges}, {"center", arr(h.center)}, {"radius", h.radius}, {"loop", std::move(loop)}}); } return {{"nverts", (int)g_mesh.verts.size()}, {"ntris", (int)g_mesh.tris.size()}, {"boundaryEdges", a.boundaryEdges}, {"nonManifoldEdges", a.nonManifoldEdges}, {"watertight", a.watertight}, {"components", std::move(components)}, {"holes", std::move(holes)}}; } // Timestamped server log line, flushed immediately so ./run.sh shows it live // even when stdout is a pipe (block-buffered by default). void logf(const char* fmt, ...) { time_t t = time(nullptr); struct tm tmv; localtime_r(&t, &tmv); char ts[16]; strftime(ts, sizeof ts, "%H:%M:%S", &tmv); printf("[%s] ", ts); va_list ap; va_start(ap, fmt); vprintf(fmt, ap); va_end(ap); printf("\n"); fflush(stdout); } bool samePositions(const history::Verts& a, const history::Verts& b) { return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin(), [](const Vec3& x, const Vec3& y) { return x.x == y.x && x.y == y.y && x.z == y.z; }); } json restoreHistory(const history::Snapshot& snap, const std::string& label) { bool meshChanged = !samePositions(g_mesh.verts, *snap.verts) || g_mesh.tris != *snap.tris; bool cloudChanged = !samePositions(g_cloud, *snap.cloud); // Invalidate exports for both the departing and arriving registries. auto deleteExport = [](int id) { std::string path = g_outDir + "/surface_" + std::to_string(id) + ".step"; std::remove(path.c_str()); }; for (const auto& item : g_surfaces) deleteExport(item.first); for (const auto& item : *snap.surfaces) deleteExport(item.first); for (int id : g_surfaceExported) deleteExport(id); g_surfaceExported.clear(); g_mesh.verts = *snap.verts; g_mesh.tris = *snap.tris; g_cloud = *snap.cloud; g_frameR = snap.frameR; g_frameT = snap.frameT; g_selVerts = *snap.selVerts; g_prims = *snap.prims; g_nextPrimId = snap.nextPrimId; g_surfaces = *snap.surfaces; g_mesh.computeBounds(); g_mesh.computeNormals(); g_mesh.adj.clear(); g_mesh.curv.clear(); invalidateMeshAnalysis(); return {{"ok", true}, {"history", g_history.meta()}, {"label", label}, {"ui", snap.ui}, {"meshChanged", meshChanged}, {"cloudChanged", cloudChanged}, {"bbMin", arr(g_mesh.bbMin)}, {"bbMax", arr(g_mesh.bbMax)}, {"ntris", g_mesh.tris.size()}, {"offset", arr(g_frameT)}, {"frameR", arr(g_frameR)}, {"prims", g_prims}, {"nsel", g_selVerts.size()}, {"selPreview", selectionResponse()["preview"]}, {"ncloud", g_cloud.size()}}; } // pick scale-aware default query radius from the model bbox if caller passes <= 0 double autoRadius(double given) { if (given > 0) return given; Vec3 d = g_mesh.bbMax - g_mesh.bbMin; double diag = geom::norm(d); return diag > 0 ? diag * 0.03 : 5.0; } } // namespace int main(int argc, char** argv) { int port = 8765; std::string webRoot = "web"; // 127.0.0.1 by default: the API is unauthenticated, so exposing it is opt-in. // --host 0.0.0.0 lets a VM (e.g. SolidWorks in Parallels, host = 10.211.55.2 // from the guest) call the measurement API. std::string host = "127.0.0.1"; for (int i = 1; i < argc; ++i) { std::string a = argv[i]; if (a == "--port" && i + 1 < argc) port = std::stoi(argv[++i]); else if (a == "--web" && i + 1 < argc) webRoot = argv[++i]; else if (a == "--out" && i + 1 < argc) g_outDir = argv[++i]; else if (a == "--history-mb") { try { if (i + 1 >= argc) throw std::invalid_argument("missing value"); std::string value = argv[++i]; std::size_t end = 0; auto mb = std::stoull(value, &end); if (value.empty() || value[0] == '-' || end != value.size() || mb > std::numeric_limits::max() / (1024ull * 1024)) throw std::invalid_argument("invalid budget"); g_history = history::History(mb * 1024ull * 1024); } catch (const std::exception&) { fprintf(stderr, "--history-mb requires a non-negative integer MB budget\n"); return 1; } } else if (a == "--host" && i + 1 < argc) host = argv[++i]; } httplib::Server srv; srv.set_payload_max_length(512ull * 1024 * 1024); // big scans // One line per request (static files included), so a silent terminal means // the browser genuinely isn't talking to us. Endpoint handlers add detail lines. srv.set_logger([](const httplib::Request& req, const httplib::Response& res) { logf("%s %s -> %d (%zu B)", req.method.c_str(), req.path.c_str(), res.status, res.body.size()); }); if (!srv.set_mount_point("/", webRoot)) { fprintf(stderr, "warning: cannot mount web root '%s'\n", webRoot.c_str()); } // Forbid caching everywhere. The app is index.html + app.js loaded as a pair; // with heuristic caching a server restart can hand the browser a NEW html and // an OLD cached app.js (or vice versa), and the id mismatches kill the page // script. Localhost bandwidth is free — always serve fresh. srv.set_post_routing_handler([](const httplib::Request&, httplib::Response& res) { res.set_header("Cache-Control", "no-store"); }); // ---- upload a mesh ---- srv.Post("/api/upload", [](const httplib::Request& req, httplib::Response& res) { auto file = req.get_file_value("file"); if (file.content.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no file"})", "application/json"); return; } std::string ext; auto dot = file.filename.find_last_of('.'); if (dot != std::string::npos) ext = file.filename.substr(dot + 1); std::lock_guard lk(g_mtx); std::string err; mesh::Mesh m; if (!mesh::loadFromMemory(file.content, ext, m, err)) { logf("upload: %s (%zu B) FAILED: %s", file.filename.c_str(), file.content.size(), err.c_str()); res.status = 400; res.set_content(json({{"ok", false}, {"error", err}}).dump(), "application/json"); return; } // Recenter scan coords at the origin (UI passes recenter=1) so the part // sits on the grid; the viewer recenters by the same bbox-centre, keeping // picks/fits in one frame. validate.py omits the flag to preserve absolute coords. geom::Vec3 off{0, 0, 0}; if (!req.get_file_value("recenter").content.empty()) { off = (m.bbMin + m.bbMax) * 0.5; for (auto& v : m.verts) v = v - off; m.computeBounds(); } g_mesh = std::move(m); g_history.reset(); invalidateMeshAnalysis(); g_cloud.clear(); // a new mesh defines a new frame; old cloud is stale g_frameR = {1, 0, 0, 0, 1, 0, 0, 0, 1}; g_frameT = off * -1.0; g_selVerts.clear(); g_prims.clear(); g_surfaces.clear(); g_surfaceExported.clear(); g_nextPrimId = 1; logf("upload: %s (%zu B) -> %zu verts, %zu tris, bbox %.1fx%.1fx%.1f mm%s", file.filename.c_str(), file.content.size(), g_mesh.verts.size(), g_mesh.tris.size(), g_mesh.bbMax.x - g_mesh.bbMin.x, g_mesh.bbMax.y - g_mesh.bbMin.y, g_mesh.bbMax.z - g_mesh.bbMin.z, geom::norm(off) > 0 ? " (recentered)" : ""); json r = {{"ok", true}, {"name", file.filename}, {"nverts", (int)g_mesh.verts.size()}, {"ntris", (int)g_mesh.tris.size()}, {"offset", arr(g_frameT)}, {"bbMin", arr(g_mesh.bbMin)}, {"bbMax", arr(g_mesh.bbMax)}}; res.set_content(r.dump(), "application/json"); }); srv.Get("/api/history", [](const httplib::Request&, httplib::Response& res) { std::lock_guard lk(g_mtx); res.set_content(json({{"ok", true}, {"history", g_history.meta()}}).dump(), "application/json"); }); srv.Post("/api/history/commit", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } json b = json::parse(req.body, nullptr, false); if (!b.is_object() || !b.contains("label") || !b["label"].is_string() || (b.contains("step") && !b["step"].is_string()) || (b.contains("detail") && !b["detail"].is_string())) { res.status = 400; res.set_content(R"({"ok":false,"error":"invalid history entry"})", "application/json"); return; } g_history.commit(b["label"], b.value("step", ""), b.value("detail", ""), g_mesh.verts, g_mesh.tris, g_cloud, g_selVerts, g_prims, g_surfaces, g_frameR, g_frameT, g_nextPrimId, b.value("ui", json())); logf("history_commit: \"%s\" entries=%zu bytes=%.1fMB", b["label"].get().c_str(), g_history.entries().size(), g_history.bytes() / (1024.0 * 1024)); res.set_content(json({{"ok", true}, {"history", g_history.meta()}}).dump(), "application/json"); }); for (const std::string action : {"undo", "redo", "goto"}) { srv.Post("/api/history/" + action, [action](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); const history::Snapshot* snap = nullptr; std::string label; if (action == "undo") { if (g_history.canUndo()) label = g_history.entries()[g_history.cursor()].label; snap = g_history.undo(); } else if (action == "redo") { snap = g_history.redo(); } else { json b = json::parse(req.body, nullptr, false); if (!b.is_object() || !b.contains("index") || !b["index"].is_number_integer()) { res.status = 400; res.set_content(R"({"ok":false,"error":"index must be an integer"})", "application/json"); return; } // Compare before narrowing, including arbitrarily large JSON integers. if (b["index"] >= 0 && b["index"] < g_history.entries().size()) snap = g_history.go(b["index"].get()); } if (!snap) { res.status = 409; std::string error = action == "goto" ? "invalid history index" : "nothing to " + action; res.set_content(json({{"ok", false}, {"error", error}}).dump(), "application/json"); return; } if (action != "undo") label = g_history.entries()[g_history.cursor()].label; json r = restoreHistory(*snap, label); logf("history_%s: \"%s\" entries=%zu bytes=%.1fMB", action.c_str(), label.c_str(), g_history.entries().size(), g_history.bytes() / (1024.0 * 1024)); res.set_content(r.dump(), "application/json"); }); } // Fitted-surface preview grid for one surface primitive, so the viewer can // redraw it after a history restore (same shape as /api/surface/fit's preview). srv.Get("/api/surface/preview", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); int id = req.has_param("id") ? std::atoi(req.get_param_value("id").c_str()) : -1; auto it = g_surfaces.find(id); if (it == g_surfaces.end()) { res.status = 404; res.set_content(R"({"ok":false,"error":"unknown surface id"})", "application/json"); return; } const surface::Preview& p = it->second.preview; json pos = json::array(), dev = json::array(); for (const Vec3& v : p.positions) { pos.push_back(v.x); pos.push_back(v.y); pos.push_back(v.z); } for (double d : p.deviations) { if (std::isfinite(d)) dev.push_back(d); else dev.push_back(nullptr); } json preview = {{"nu", p.nu}, {"nv", p.nv}, {"pos", std::move(pos)}, {"dev", std::move(dev)}}; res.set_content(json({{"ok", true}, {"preview", std::move(preview)}}).dump(), "application/json"); }); srv.Get("/api/cloud/current", [](const httplib::Request&, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_cloud.empty()) { res.status = 404; res.set_content(R"({"ok":false,"error":"no cloud"})", "application/json"); return; } std::string data; data.reserve(g_cloud.size() * 12); for (const auto& p : g_cloud) { for (double coordinate : {p.x, p.y, p.z}) { float value = static_cast(coordinate); std::uint32_t bits; static_assert(sizeof(value) == sizeof(bits), "float32 required"); std::memcpy(&bits, &value, sizeof(bits)); for (int shift = 0; shift < 32; shift += 8) data.push_back(static_cast((bits >> shift) & 0xff)); } } res.set_content(std::move(data), "application/octet-stream"); }); // ---- mesh editing / repair ---- srv.Get("/api/mesh/status", [](const httplib::Request&, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } res.set_content(json({{"ok", true}, {"status", meshStatus()}}).dump(), "application/json"); }); srv.Post("/api/mesh/decimate", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } json b = json::parse(req.body, nullptr, false); if (b.is_discarded() || !b.is_object()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json"})", "application/json"); return; } bool haveCount = b.contains("count") && b["count"].is_number_integer(); bool havePercent = b.contains("percent") && b["percent"].is_number(); if (haveCount == havePercent) { res.status = 400; res.set_content(R"({"ok":false,"error":"provide count or percent"})", "application/json"); return; } std::size_t before = g_mesh.tris.size(); std::size_t target = before; double percent = 0; if (haveCount) { long long count = b["count"].get(); if (count <= 0) { res.status = 400; res.set_content(R"({"ok":false,"error":"count must be positive"})", "application/json"); return; } target = (std::size_t)count; } else { percent = b["percent"].get(); if (!(percent > 0 && percent < 100)) { res.status = 400; res.set_content(R"({"ok":false,"error":"percent must be between 0 and 100"})", "application/json"); return; } target = std::max( 1, (std::size_t)std::llround(before * percent / 100.0)); } if (target >= before) { res.set_content(json({{"ok", true}, {"status", meshStatus()}}).dump(), "application/json"); return; } bool checkDeviation = b.contains("tolerance") && b["tolerance"].is_number(); double tolerance = checkDeviation ? b["tolerance"].get() : 0; if (tolerance < 0) { res.status = 400; res.set_content(R"({"ok":false,"error":"tolerance must be non-negative"})", "application/json"); return; } mesh::Mesh original; if (checkDeviation) { original.verts = g_mesh.verts; original.tris = g_mesh.tris; original.computeBounds(); } auto started = std::chrono::steady_clock::now(); std::size_t after = meshedit::decimate(g_mesh, target); invalidateMeshAnalysis(); json r = {{"ok", true}, {"status", meshStatus()}}; if (checkDeviation) { meshedit::TriangleGrid grid(original); auto d = meshedit::deviationStats(g_mesh, grid, tolerance); r["deviation"] = {{"max", d.max}, {"rms", d.rms}, {"pctWithin", d.pctWithin}}; } double ms = std::chrono::duration( std::chrono::steady_clock::now() - started) .count(); logf("mesh_decimate: target=%zu%s%s %zu -> %zu tris in %.0f ms", target, havePercent ? " percent=" : "", havePercent ? std::to_string(percent).c_str() : "", before, after, ms); res.set_content(r.dump(), "application/json"); }); srv.Post("/api/mesh/fill_holes", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } json b = json::parse(req.body, nullptr, false); if (b.is_discarded() || !b.is_object() || !b.contains("holes")) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json or missing holes"})", "application/json"); return; } std::string method = b.value("method", std::string("auto")); if (method != "auto" && method != "tangent" && method != "curvature") { res.status = 400; res.set_content(R"({"ok":false,"error":"bad fill method"})", "application/json"); return; } const auto& a = meshAnalysis(); std::vector selected; bool all = b["holes"].is_string() && b["holes"].get() == "all"; int maxEdges = b.value("maxEdges", 0); if (all) { for (const auto& h : a.holes) if (maxEdges <= 0 || h.nedges <= maxEdges) selected.push_back(h); } else if (b["holes"].is_array()) { std::unordered_set seen; for (const auto& item : b["holes"]) { if (!item.is_number_integer()) { res.status = 400; res.set_content(R"({"ok":false,"error":"hole ids must be integers"})", "application/json"); return; } int id = item.get(); if (id < 0 || id >= (int)a.holes.size()) { res.status = 404; res.set_content(R"({"ok":false,"error":"bad hole id"})", "application/json"); return; } if (seen.insert(id).second) selected.push_back(a.holes[id]); } } else { res.status = 400; res.set_content(R"({"ok":false,"error":"holes must be an id array or all"})", "application/json"); return; } std::size_t before = g_mesh.tris.size(); int filled = 0; auto started = std::chrono::steady_clock::now(); if (!selected.empty()) { filled = meshedit::fillHoles(g_mesh, selected, method); if (filled) { invalidateMeshAnalysis(); } } double ms = std::chrono::duration( std::chrono::steady_clock::now() - started) .count(); logf("mesh_fill_holes: method=%s requested=%zu filled=%d %zu -> %zu tris in %.0f ms", method.c_str(), selected.size(), filled, before, g_mesh.tris.size(), ms); json r = {{"ok", true}, {"filled", filled}, {"status", meshStatus()}}; res.set_content(r.dump(), "application/json"); }); srv.Post("/api/mesh/remove_components", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } json b = json::parse(req.body, nullptr, false); if (b.is_discarded() || !b.is_object()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json"})", "application/json"); return; } int selectors = (int)b.contains("ids") + (int)b.contains("minTris") + (int)b.contains("minArea") + (int)b.contains("keepLargest"); if (selectors != 1) { res.status = 400; res.set_content(R"({"ok":false,"error":"provide exactly one removal rule"})", "application/json"); return; } meshedit::RemoveOptions options; if (b.contains("ids")) { if (!b["ids"].is_array()) { res.status = 400; res.set_content(R"({"ok":false,"error":"ids must be an array"})", "application/json"); return; } for (const auto& item : b["ids"]) { if (!item.is_number_integer()) { res.status = 400; res.set_content(R"({"ok":false,"error":"component ids must be integers"})", "application/json"); return; } int id = item.get(); if (id < 0 || id >= (int)meshAnalysis().components.size()) { res.status = 404; res.set_content(R"({"ok":false,"error":"bad component id"})", "application/json"); return; } options.ids.push_back(id); } } else if (b.contains("minTris") && b["minTris"].is_number_integer()) { options.minTris = b["minTris"].get(); } else if (b.contains("minArea") && b["minArea"].is_number()) { options.minArea = b["minArea"].get(); } else if (b.contains("keepLargest") && b["keepLargest"].is_boolean() && b["keepLargest"].get()) { options.keepLargest = true; } else { res.status = 400; res.set_content(R"({"ok":false,"error":"bad removal rule"})", "application/json"); return; } if (options.minTris < -1 || options.minArea < -1) { res.status = 400; res.set_content(R"({"ok":false,"error":"threshold must be non-negative"})", "application/json"); return; } std::size_t before = g_mesh.tris.size(); auto started = std::chrono::steady_clock::now(); int removed = meshedit::removeComponents(g_mesh, meshAnalysis(), options); if (removed) { invalidateMeshAnalysis(); } double ms = std::chrono::duration( std::chrono::steady_clock::now() - started) .count(); logf("mesh_remove_components: removed=%d %zu -> %zu tris in %.0f ms", removed, before, g_mesh.tris.size(), ms); json r = {{"ok", true}, {"removed", removed}, {"status", meshStatus()}}; res.set_content(r.dump(), "application/json"); }); srv.Get("/api/mesh/current", [](const httplib::Request&, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } res.set_content(mesh::binarySTL(g_mesh), "application/octet-stream"); }); // ---- planes-only export: world datum planes sized to the (aligned) part ---- srv.Get("/api/align/datums", [](const httplib::Request&, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } std::string path = g_outDir + "/datums.step"; builder::RefGeometry refs = collectRefGeometry(); builder::BuildResult r = builder::exportDatums(g_mesh.bbMin, g_mesh.bbMax, path, &refs); std::ifstream f(path, std::ios::binary); if (!r.ok || !f) { logf("align_datums: FAILED: %s", r.error.c_str()); res.status = 500; res.set_content(json({{"ok", false}, {"error", r.error}}).dump(), "application/json"); return; } logf("align_datums: wrote %s", path.c_str()); std::string data((std::istreambuf_iterator(f)), std::istreambuf_iterator()); res.set_header("Content-Disposition", "attachment; filename=\"scan2cad_datums.step\""); res.set_content(data, "application/step"); }); srv.Get("/api/mesh/component", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } if (!req.has_param("id")) { res.status = 404; res.set_content(R"({"ok":false,"error":"bad component id"})", "application/json"); return; } std::string idText = req.get_param_value("id"); char* end = nullptr; long id = std::strtol(idText.c_str(), &end, 10); const auto& a = meshAnalysis(); if (!end || *end != '\0' || id < 0 || id >= (long)a.components.size()) { res.status = 404; res.set_content(R"({"ok":false,"error":"bad component id"})", "application/json"); return; } std::vector triangles; triangles.reserve(a.components[(std::size_t)id].ntris); for (int ti = 0; ti < (int)a.triangleComponent.size(); ++ti) if (a.triangleComponent[ti] == id) triangles.push_back(ti); res.set_content(mesh::binarySTL(g_mesh, triangles), "application/octet-stream"); }); // ---- upload the raw scanner point cloud (merged into fits, same frame) ---- srv.Post("/api/upload_cloud", [](const httplib::Request& req, httplib::Response& res) { auto file = req.get_file_value("file"); if (file.content.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no file"})", "application/json"); return; } std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"load the mesh first - the cloud aligns to its frame"})", "application/json"); return; } std::string ext; auto dot = file.filename.find_last_of('.'); if (dot != std::string::npos) ext = file.filename.substr(dot + 1); std::string err; std::vector pts; if (!mesh::loadPointsFromMemory(file.content, ext, pts, err)) { logf("upload_cloud: %s FAILED: %s", file.filename.c_str(), err.c_str()); res.status = 400; res.set_content(json({{"ok", false}, {"error", err}}).dump(), "application/json"); return; } for (auto& p : pts) p = align::transformPoint(g_frameR, g_frameT, p); g_cloud = std::move(pts); logf("upload_cloud: %s -> %zu points (merged into fits)", file.filename.c_str(), g_cloud.size()); json r = {{"ok", true}, {"name", file.filename}, {"npts", (int)g_cloud.size()}, // Legacy `shift` remains the subtracted vector for the old // translation-only case; `offset` is the actual transform T. {"shift", arr(g_frameT * -1.0)}, {"offset", arr(g_frameT)}}; res.set_content(r.dump(), "application/json"); }); // ---- fit the hole-seat plane (box region or 3 rim points, optional parallel lock) ---- srv.Post("/api/fit_seat", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } json b = json::parse(req.body, nullptr, false); if (b.is_discarded()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json"})", "application/json"); return; } Vec3 view = vecOf(b.value("viewDir", json::array())); fit::SeatFit sf; std::string mode; std::vector patchIds; if (b.contains("paint") && b["paint"].is_object()) { // Painted selection: brush-stroke sample centers + brush radius. The // plane is fitted from exactly the painted vertices (walls/outliers // auto-rejected), so strokes across several coplanar surfaces define // one plane through all of them. std::vector centers; for (const auto& c : b["paint"].value("centers", json::array())) centers.push_back(vecOf(c)); double prad = b["paint"].value("radius", 0.0); if (prad <= 0) prad = autoRadius(0) * 0.5; sf = fit::fitSeatFromPaint(g_mesh, g_cloud, centers, prad, view, &patchIds); mode = "paint"; } else if (b.contains("points") && b["points"].is_array() && !b["points"].empty()) { std::vector picks; for (const auto& p : b["points"]) picks.push_back(vecOf(p)); if (g_mesh.adj.empty()) g_mesh.buildAdjacency(); sf = fit::fitSeatFromPoints(g_mesh, g_cloud, picks, view, &patchIds); mode = "points"; } else if (b.contains("region") && b["region"].is_array()) { std::vector> region; for (const auto& pl : b["region"]) if (pl.is_array() && pl.size() == 4) region.push_back({pl[0].get(), pl[1].get(), pl[2].get(), pl[3].get()}); sf = fit::fitPlaneRegion(g_mesh, g_cloud, region, view); mode = "region"; } else if (b.contains("rim") && b["rim"].is_array() && b["rim"].size() == 3) { sf = fit::fitPlaneRim(g_mesh, g_cloud, vecOf(b["rim"][0]), vecOf(b["rim"][1]), vecOf(b["rim"][2]), view); mode = "rim"; } else { res.status = 400; res.set_content(R"({"ok":false,"error":"need region [4 planes] or rim [3 points]"})", "application/json"); return; } if (!sf.ok) { logf("fit_seat(%s): FAILED (too few usable points)", mode.c_str()); res.set_content(R"({"ok":false,"error":"seat fit failed — too few usable points in the selection"})", "application/json"); return; } // Optional: lock the seat parallel to another surface (point + capture radius). json par; if (b.contains("parallelTo") && b["parallelTo"].is_object()) { Vec3 pp = vecOf(b["parallelTo"].value("point", json::array())); double prad = b["parallelTo"].value("radius", 0.0); if (prad <= 0) prad = autoRadius(0); auto ref = fit::fitPlane(g_mesh, pp, prad, view); if (!ref.ok) { res.set_content(R"({"ok":false,"error":"parallel reference fit failed"})", "application/json"); return; } sf = fit::refitSeatParallel(g_mesh, g_cloud, sf, ref.normal); par = {{"normal", arr(ref.normal)}, {"rms", ref.rms}, {"npts", ref.npts}}; } logf("fit_seat(%s): n=(%.3f,%.3f,%.3f) rms=%.3f mm, %d mesh + %d cloud pts%s", mode.c_str(), sf.normal.x, sf.normal.y, sf.normal.z, sf.rms, sf.npts, sf.ncloud, par.is_null() ? "" : " (parallel-locked)"); json r = {{"ok", true}, {"mode", mode}, {"origin", arr(sf.origin)}, {"normal", arr(sf.normal)}, {"u", arr(sf.u)}, {"v", arr(sf.v)}, {"rms", sf.rms}, {"npts", sf.npts}, {"ncloud", sf.ncloud}}; if (!par.is_null()) r["parallel"] = par; // Decimated patch positions so the UI can paint the accepted surface. if (!patchIds.empty()) { json flat = json::array(); size_t stride = std::max(1, patchIds.size() / 3000); for (size_t k = 0; k < patchIds.size(); k += stride) { const auto& v = g_mesh.verts[patchIds[k]]; flat.push_back(v.x); flat.push_back(v.y); flat.push_back(v.z); } r["patch"] = std::move(flat); r["npatch"] = (int)patchIds.size(); } res.set_content(r.dump(), "application/json"); }); // ---- auto-discover every round gap in the seat surface ---- srv.Post("/api/detect_holes_auto", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } json b = json::parse(req.body, nullptr, false); if (b.is_discarded()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json"})", "application/json"); return; } Vec3 seed = vecOf(b.value("seed", json::array())); Vec3 origin = vecOf(b.value("origin", json::array())); Vec3 normal = vecOf(b.value("normal", json::array()), {0, 0, 1}); double minD = b.value("minDiameterMM", 0.0); double maxD = b.value("maxDiameterMM", 0.0); if (g_mesh.adj.empty()) g_mesh.buildAdjacency(); auto holes = fit::detectHolesInSeat(g_mesh, g_cloud, origin, normal, seed, minD, maxD); logf("detect_holes_auto: %zu hole(s) on the seat surface (D window %.1f..%.1f)", holes.size(), minD, maxD); Vec3 n = geom::normalize(normal); const int meshOrient = mesh::windingOrientation(g_mesh); json list = json::array(); for (const auto& hd : holes) { Vec3 hn = geom::normalize(hd.normal); // Canonical axis sign: point out of the material (p1 = center - axis*depth // then reaches into the part). The detected normal follows the vertex // normals, so the winding polarity settles it; the occupancy probe is the // fallback for meshes too open for the volume test. if (meshOrient < 0) hn = hn * -1.0; else if (meshOrient == 0 && fit::materialSide(g_mesh, hd.center, hn, hd.diameter * 0.75, hd.diameter * 2.0) > 0) hn = hn * -1.0; double depth = hd.depth > 0.5 ? hd.depth : hd.diameter * 1.5; list.push_back({{"center", arr(hd.center)}, {"axis", arr(hn)}, {"diameter", hd.diameter}, {"radius", hd.diameter / 2.0}, {"depth", depth}, {"depthMeasured", hd.depth > 0.5}, {"p1", arr(hd.center - hn * depth)}, {"p2", arr(hd.center)}, {"coverage", hd.coverage}, {"rms", hd.rms}}); logf(" auto hole: D=%.2f at (%.1f,%.1f,%.1f) cov %.0f%%", hd.diameter, hd.center.x, hd.center.y, hd.center.z, hd.coverage * 100); } (void)n; res.set_content(json({{"ok", true}, {"holes", list}}).dump(), "application/json"); }); // ---- detect a hole as a data gap in the seat plane (no bore data needed) ---- srv.Post("/api/detect_hole", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } json b = json::parse(req.body, nullptr, false); if (b.is_discarded()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json"})", "application/json"); return; } Vec3 hint = vecOf(b.value("point", json::array())); Vec3 origin = vecOf(b.value("origin", json::array())); Vec3 normal = vecOf(b.value("normal", json::array()), {0, 0, 1}); double searchR = autoRadius(b.value("radius", 0.0)); double known = b.value("knownDiameter", 0.0); double minD = b.value("minDiameterMM", 0.0); double maxD = b.value("maxDiameterMM", 0.0); // The default auto radius is scaled to the whole model — far too wide for a // single hole (it drags in unrelated surfaces). The Ø window bounds it. if (maxD > 0) searchR = std::min(searchR, maxD * 1.2 + 4.0); else if (known > 0) searchR = std::min(searchR, known * 1.5 + 4.0); // Assist mode: 1–3 user picks inside the hole. Hint = their centroid; the // search widens with the spread; the found circle must contain the picks. std::vector inside; if (b.contains("points") && b["points"].is_array()) { for (const auto& p : b["points"]) inside.push_back(vecOf(p)); if (!inside.empty()) { Vec3 c{0, 0, 0}; for (const auto& p : inside) c = c + p; hint = c / (double)inside.size(); double spread = 0; for (const auto& p : inside) spread = std::max(spread, geom::norm(p - hint)); searchR = std::max({searchR, spread * 2.5 + 3.0, maxD > 0 ? maxD * 0.75 : 0.0}); } } auto hd = fit::detectHoleInSeat(g_mesh, g_cloud, origin, normal, hint, searchR, known, minD, maxD); if (hd.ok && inside.size() > 1) { Vec3 n2 = geom::normalize(hd.normal); for (const auto& p : inside) { Vec3 d = p - hd.center; if (geom::norm(d - n2 * geom::dot(d, n2)) > hd.diameter * 0.62) { hd.ok = false; // circle doesn't contain the user's picks — wrong gap break; } } } if (!hd.ok) { logf("detect_hole: none found near (%.1f,%.1f,%.1f) r=%.1f D=[%.1f..%.1f] (%d band pts, cov %.0f%%)", hint.x, hint.y, hint.z, searchR, minD, maxD, hd.npts, hd.coverage * 100); res.set_content(R"({"ok":false,"error":"no round gap in the seat plane there - check the min/max hole bounds"})", "application/json"); return; } logf("detect_hole: D=%.2f mm at (%.1f,%.1f,%.1f), coverage %.0f%%, rim rms %.3f, depth %.1f", hd.diameter, hd.center.x, hd.center.y, hd.center.z, hd.coverage * 100, hd.rms, hd.depth); Vec3 n = geom::normalize(hd.normal); // locally refined at the hole // Canonical axis sign: point out of the material (p1 = center - axis*depth // then reaches into the part). The detected normal follows the vertex normals, // so the winding polarity settles it; the occupancy probe is the fallback for // meshes too open for the volume test. const int meshOrient = mesh::windingOrientation(g_mesh); if (meshOrient < 0) n = n * -1.0; else if (meshOrient == 0 && fit::materialSide(g_mesh, hd.center, n, hd.diameter * 0.75, hd.diameter * 2.0) > 0) n = n * -1.0; double depth = hd.depth > 0.5 ? hd.depth : hd.diameter * 1.5; // display default json r = {{"ok", true}, {"center", arr(hd.center)}, {"axis", arr(n)}, {"diameter", hd.diameter}, {"radius", hd.diameter / 2.0}, {"depth", depth}, {"depthMeasured", hd.depth > 0.5}, {"p1", arr(hd.center - n * depth)}, {"p2", arr(hd.center)}, {"coverage", hd.coverage}, {"rms", hd.rms}, {"npts", hd.npts}, {"radiusFixed", known > 0}, {"method", "gap"}}; res.set_content(r.dump(), "application/json"); }); // ---- construct or apply a sequential datum (3-2-1) frame ---- srv.Post("/api/align/frame", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); json body = json::parse(req.body, nullptr, false); if (body.is_discarded()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json"})", "application/json"); return; } AlignmentRequest request = buildAlignmentRequest(body); if (!request.error.empty()) { logf("align_frame: FAILED: %s", request.error.c_str()); res.status = 400; res.set_content( json({{"ok", false}, {"error", request.error}}).dump(), "application/json"); return; } logf("align_frame: %s=%zu fullyDefined=%s overconstrained=%zu", body.contains("rigid") ? "rigid" : body.contains("points") ? "points" : "slots", body.contains("rigid") ? std::size_t{1} : body.contains("points") ? body["points"].size() : body["slots"].size(), request.frame.fullyDefined ? "true" : "false", request.frame.overconstrained.size()); res.set_content(alignmentResponse(request.frame).dump(), "application/json"); }); srv.Post("/api/align/apply", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } json body = json::parse(req.body, nullptr, false); if (body.is_discarded()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json"})", "application/json"); return; } AlignmentRequest request = buildAlignmentRequest(body); if (!request.error.empty()) { logf("align_apply: FAILED: %s", request.error.c_str()); res.status = 400; res.set_content( json({{"ok", false}, {"error", request.error}}).dump(), "application/json"); return; } int nverts = static_cast(g_mesh.verts.size()); int ncloud = static_cast(g_cloud.size()); align::applyTo(g_mesh, request.frame.R, request.frame.t); for (Vec3& point : g_cloud) point = align::transformPoint(request.frame.R, request.frame.t, point); transformPrimitiveRegistry(request.frame.R, request.frame.t); transformSurfaceRegistry(request.frame.R, request.frame.t); composeFrame(request.frame.R, request.frame.t); invalidateMeshAnalysis(); logf("align_apply: %s=%zu moved=%d verts,%d cloud " "fullyDefined=%s overconstrained=%zu", body.contains("rigid") ? "rigid" : body.contains("points") ? "points" : "slots", body.contains("rigid") ? std::size_t{1} : body.contains("points") ? body["points"].size() : body["slots"].size(), nverts, ncloud, request.frame.fullyDefined ? "true" : "false", request.frame.overconstrained.size()); json response = {{"ok", true}, {"prims", g_prims}, {"moved", {{"nverts", nverts}, {"ncloud", ncloud}}}}; res.set_content(response.dump(), "application/json"); }); // ---- redefine the origin: translate the mesh so `point` becomes (0,0,0) ---- srv.Post("/api/set_origin", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } json b = json::parse(req.body, nullptr, false); if (b.is_discarded()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json"})", "application/json"); return; } Vec3 p = vecOf(b.value("point", json::array())); const align::Mat3 identity{1, 0, 0, 0, 1, 0, 0, 0, 1}; Vec3 translation = p * -1.0; align::applyTo(g_mesh, identity, translation); for (Vec3& point : g_cloud) point = point + translation; transformPrimitiveRegistry(identity, translation); transformSurfaceRegistry(identity, translation); composeFrame(identity, translation); invalidateMeshAnalysis(); logf("set_origin: translated by (%.3f,%.3f,%.3f)", translation.x, translation.y, translation.z); json r = {{"ok", true}, {"bbMin", arr(g_mesh.bbMin)}, {"bbMax", arr(g_mesh.bbMax)}}; res.set_content(r.dump(), "application/json"); }); // ---- fit a datum plane ---- srv.Post("/api/fit_plane", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } json b = json::parse(req.body, nullptr, false); if (b.is_discarded()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json"})", "application/json"); return; } Vec3 pt = vecOf(b.value("point", json::array())); Vec3 view = vecOf(b.value("viewDir", json::array())); double radius = autoRadius(b.value("radius", 0.0)); auto pf = fit::fitPlane(g_mesh, pt, radius, view); if (!pf.ok) { logf("fit_plane: FAILED at (%.1f,%.1f,%.1f) r=%.1f", pt.x, pt.y, pt.z, radius); res.set_content(R"({"ok":false,"error":"plane fit failed"})", "application/json"); return; } logf("fit_plane: n=(%.3f,%.3f,%.3f) rms=%.3f mm, %d pts", pf.normal.x, pf.normal.y, pf.normal.z, pf.rms, pf.npts); json r = {{"ok", true}, {"origin", arr(pf.origin)}, {"normal", arr(pf.normal)}, {"u", arr(pf.u)}, {"v", arr(pf.v)}, {"rms", pf.rms}, {"npts", pf.npts}, {"radius", radius}}; res.set_content(r.dump(), "application/json"); }); // ---- fit a cylinder (hole) ---- srv.Post("/api/fit_cylinder", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } json b = json::parse(req.body, nullptr, false); if (b.is_discarded()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json"})", "application/json"); return; } Vec3 pt = vecOf(b.value("point", json::array())); double radius = autoRadius(b.value("radius", 0.0)); double known = b.value("knownDiameter", 0.0); Vec3 axisHint = vecOf(b.value("axisHint", json::array())); Vec3 axisLock = vecOf(b.value("axisLock", json::array())); bool locked = geom::norm(axisLock) > 1e-6; Vec3 seatOrigin; bool haveSeat = false; if (b.contains("axisOrigin") && b["axisOrigin"].is_array()) { seatOrigin = vecOf(b["axisOrigin"]); haveSeat = true; } auto cf = locked ? fit::fitCylinderLocked(g_mesh, g_cloud, pt, radius, known, axisLock, haveSeat ? &seatOrigin : nullptr) : fit::fitCylinder(g_mesh, pt, radius, known, axisHint); if (!cf.ok) { logf("fit_cylinder%s: FAILED at (%.1f,%.1f,%.1f) r=%.1f", locked ? "(locked)" : "", pt.x, pt.y, pt.z, radius); res.set_content(R"({"ok":false,"error":"cylinder fit failed"})", "application/json"); return; } logf("fit_cylinder%s: D=%.2f mm rms=%.3f, %d pts%s", locked ? "(locked)" : "", cf.diameter, cf.rms, cf.npts, cf.radiusFixed ? " (known D)" : ""); json r = {{"ok", true}, {"center", arr(cf.axisPoint)}, {"axis", arr(cf.axisDir)}, {"diameter", cf.diameter}, {"radius", cf.radius}, {"depth", cf.tMax - cf.tMin}, {"p1", arr(cf.p1)}, {"p2", arr(cf.p2)}, {"rms", cf.rms}, {"npts", cf.npts}, {"radiusFixed", cf.radiusFixed}, {"queryRadius", radius}}; res.set_content(r.dump(), "application/json"); }); // ---- QuickSurface-style selected-region primitive extraction ---- srv.Post("/api/prim/select", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); auto started = std::chrono::steady_clock::now(); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } json b = json::parse(req.body, nullptr, false); if (b.is_discarded() || !b.is_object()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json"})", "application/json"); return; } std::string mode = b.value("mode", std::string()); std::vector selected; if (mode == "clear") { g_selVerts.clear(); } else if (mode == "wand") { if (!b.contains("seed") || !b["seed"].is_array() || b["seed"].size() != 3) { res.status = 400; res.set_content(R"({"ok":false,"error":"wand needs seed [x,y,z]"})", "application/json"); return; } double angle = b.value("angleDeg", 15.0); if (!(angle > 0 && angle <= 180)) { res.status = 400; res.set_content(R"({"ok":false,"error":"angleDeg must be between 0 and 180"})", "application/json"); return; } prim::wandSelect(g_mesh, vecOf(b["seed"]), angle, selected); } else if (mode == "paint") { if (!b.contains("centers") || !b["centers"].is_array()) { res.status = 400; res.set_content(R"({"ok":false,"error":"paint needs centers"})", "application/json"); return; } std::vector centers; for (const auto& c : b["centers"]) { if (!c.is_array() || c.size() != 3) { res.status = 400; res.set_content(R"({"ok":false,"error":"paint centers must be [x,y,z]"})", "application/json"); return; } centers.push_back(vecOf(c)); } double radius = b.value("radius", 0.0); if (centers.empty() || radius <= 0) { res.status = 400; res.set_content(R"({"ok":false,"error":"paint needs centers and positive radius"})", "application/json"); return; } prim::paintSelect(g_mesh, centers, radius, selected); } else { res.status = 400; res.set_content(R"({"ok":false,"error":"mode must be wand, paint, or clear"})", "application/json"); return; } if (mode != "clear") { bool add = b.value("add", false); if (!add) { g_selVerts = std::move(selected); } else { std::vector have(g_mesh.verts.size(), 0); for (int i : g_selVerts) if (i >= 0 && i < (int)have.size()) have[i] = 1; for (int i : selected) if (!have[i]) { have[i] = 1; g_selVerts.push_back(i); } } } double ms = std::chrono::duration( std::chrono::steady_clock::now() - started) .count(); logf("prim_select: type=%s npts=%zu rms=0 ms=%.1f", mode.c_str(), g_selVerts.size(), ms); res.set_content(selectionResponse().dump(), "application/json"); }); srv.Post("/api/prim/fit", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); auto started = std::chrono::steady_clock::now(); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } json b = json::parse(req.body, nullptr, false); if (b.is_discarded() || !b.is_object()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json"})", "application/json"); return; } std::string type = b.value("type", std::string()); if (type != "plane" && type != "cylinder" && type != "cone" && type != "sphere") { res.status = 400; res.set_content(R"({"ok":false,"error":"type must be plane, cylinder, cone, or sphere"})", "application/json"); return; } if (g_selVerts.size() < 30) { res.status = 400; res.set_content(R"({"ok":false,"error":"select more of the surface"})", "application/json"); return; } std::vector points, normals; points.reserve(g_selVerts.size()); normals.reserve(g_selVerts.size()); for (int i : g_selVerts) { if (i < 0 || i >= (int)g_mesh.verts.size()) continue; points.push_back(g_mesh.verts[i]); normals.push_back(g_mesh.vnormals[i]); } if (points.size() < 30) { res.status = 400; res.set_content(R"({"ok":false,"error":"select more of the surface"})", "application/json"); return; } json entry; std::string error; double fitRms = 0; int fitNpts = 0; if (type == "plane") { auto f = prim::fitPlane(points, normals); if (!f.ok) error = f.err; else { json rect = json::array(); for (const auto& p : f.rect) rect.push_back(arr(p)); entry = {{"id", g_nextPrimId}, {"kind", "plane"}, {"origin", arr(f.origin)}, {"normal", arr(f.normal)}, {"u", arr(f.u)}, {"v", arr(f.v)}, {"rect", std::move(rect)}, {"rms", f.rms}, {"npts", f.npts}}; fitRms = f.rms; fitNpts = f.npts; } } else if (type == "cylinder") { auto f = prim::fitCylinder(points, normals); if (!f.ok) error = f.err; else { entry = {{"id", g_nextPrimId}, {"kind", "cylinder"}, {"center", arr(f.center)}, {"axis", arr(f.axis)}, {"radius", f.radius}, {"p1", arr(f.p1)}, {"p2", arr(f.p2)}, {"rms", f.rms}, {"npts", f.npts}}; fitRms = f.rms; fitNpts = f.npts; } } else if (type == "cone") { auto f = prim::fitCone(points, normals); if (!f.ok) error = f.err; else { entry = {{"id", g_nextPrimId}, {"kind", "cone"}, {"apex", arr(f.apex)}, {"axis", arr(f.axis)}, {"halfAngleDeg", f.halfAngleDeg}, {"h1", f.h1}, {"h2", f.h2}, {"rms", f.rms}, {"npts", f.npts}}; fitRms = f.rms; fitNpts = f.npts; } } else { auto f = prim::fitSphere(points); if (!f.ok) error = f.err; else { entry = {{"id", g_nextPrimId}, {"kind", "sphere"}, {"center", arr(f.center)}, {"radius", f.radius}, {"rms", f.rms}, {"npts", f.npts}}; fitRms = f.rms; fitNpts = f.npts; } } double ms = std::chrono::duration( std::chrono::steady_clock::now() - started) .count(); if (!error.empty()) { logf("prim_fit: type=%s npts=%zu rms=0 ms=%.1f FAILED: %s", type.c_str(), points.size(), ms, error.c_str()); res.status = 400; res.set_content(json({{"ok", false}, {"error", error}}).dump(), "application/json"); return; } ++g_nextPrimId; g_prims.push_back(entry); logf("prim_fit: type=%s npts=%d rms=%.4f ms=%.1f", type.c_str(), fitNpts, fitRms, ms); res.set_content(json({{"ok", true}, {"prim", entry}}).dump(), "application/json"); }); srv.Post("/api/surface/fit", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); auto started = std::chrono::steady_clock::now(); if (g_selVerts.size() < 100) { res.status = 400; res.set_content( R"({"ok":false,"error":"select a region first"})", "application/json"); return; } json b = req.body.empty() ? json::object() : json::parse(req.body, nullptr, false); if (b.is_discarded() || !b.is_object()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json"})", "application/json"); return; } surface::Params params; try { params.nu = b.value("u", params.nu); params.nv = b.value("v", params.nv); params.smooth = b.value("smooth", params.smooth); params.extend = b.value("extend", params.extend); params.automatic = b.value("auto", params.automatic); params.tol = b.value("tol", params.tol); } catch (...) { res.status = 400; res.set_content(R"({"ok":false,"error":"invalid surface parameters"})", "application/json"); return; } if ((!params.automatic && (params.nu < 4 || params.nu > 50 || params.nv < 4 || params.nv > 50)) || params.smooth < 0 || params.smooth > 1 || params.extend < 0 || !std::isfinite(params.extend) || !(params.tol > 0)) { res.status = 400; res.set_content(R"({"ok":false,"error":"invalid surface parameters"})", "application/json"); return; } surface::Fit fitted = surface::fit(g_mesh, g_selVerts, params); double ms = std::chrono::duration( std::chrono::steady_clock::now() - started) .count(); if (!fitted.ok) { logf("surface_fit: %dx%d npts=%d rms=0 ms=%.1f FAILED: %s", fitted.nu, fitted.nv, fitted.npts, ms, fitted.error.c_str()); res.status = 400; res.set_content( json({{"ok", false}, {"error", fitted.error}}).dump(), "application/json"); return; } int id = g_nextPrimId++; json entry = {{"id", id}, {"kind", "surface"}, {"u", fitted.nu}, {"v", fitted.nv}, {"rms", fitted.rms}, {"max", fitted.max}, {"pctWithin", fitted.pctWithin}, {"npts", fitted.npts}}; g_surfaces.emplace(id, fitted); g_surfaceExported.erase(id); g_prims.push_back(entry); json pos = json::array(); for (const Vec3& p : fitted.preview.positions) { pos.push_back(p.x); pos.push_back(p.y); pos.push_back(p.z); } json dev = json::array(); for (double d : fitted.preview.deviations) { if (std::isfinite(d)) dev.push_back(d); else dev.push_back(nullptr); } json preview = {{"nu", fitted.preview.nu}, {"nv", fitted.preview.nv}, {"pos", std::move(pos)}, {"dev", std::move(dev)}}; logf("surface_fit: %dx%d npts=%d rms=%.4f ms=%.1f", fitted.nu, fitted.nv, fitted.npts, fitted.rms, ms); res.set_content( json({{"ok", true}, {"prim", std::move(entry)}, {"preview", std::move(preview)}}) .dump(), "application/json"); }); srv.Get("/api/surface/step", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); int id = -1; if (req.has_param("id")) { try { std::size_t used = 0; std::string text = req.get_param_value("id"); id = std::stoi(text, &used); if (used != text.size()) id = -1; } catch (...) { id = -1; } } auto it = g_surfaces.find(id); if (it == g_surfaces.end()) { res.status = 404; res.set_content(R"({"ok":false,"error":"unknown surface id"})", "application/json"); return; } std::string path = g_outDir + "/surface_" + std::to_string(id) + ".step"; if (!g_surfaceExported.count(id)) { std::string error; if (!surface::writeSTEP(it->second, path, &error)) { res.status = 500; res.set_content( json({{"ok", false}, {"error", error}}).dump(), "application/json"); return; } g_surfaceExported.insert(id); } std::ifstream file(path, std::ios::binary); if (!file) { res.status = 500; res.set_content(R"({"ok":false,"error":"surface STEP is unavailable"})", "application/json"); return; } std::string data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); std::string name = "surface_" + std::to_string(id) + ".step"; res.set_header("Content-Disposition", ("attachment; filename=\"" + name + "\"").c_str()); res.set_content(data, "application/octet-stream"); }); srv.Post("/api/prim/construct", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); auto started = std::chrono::steady_clock::now(); json b = json::parse(req.body, nullptr, false); if (b.is_discarded() || !b.is_object() || !b.contains("ids") || !b["ids"].is_array()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json or missing ids"})", "application/json"); return; } std::string kind = b.value("kind", std::string()); std::string how = b.value("how", std::string()); std::vector inputs; for (const auto& item : b["ids"]) { if (!item.is_number_integer()) { res.status = 400; res.set_content(R"({"ok":false,"error":"ids must be integers"})", "application/json"); return; } const json* p = registeredPrim(item.get()); if (!p) { res.status = 400; res.set_content(R"({"ok":false,"error":"unknown primitive id"})", "application/json"); return; } inputs.push_back(p); } auto lineOf = [](const json& p, bool cylindersOnly) { std::string k = p.value("kind", std::string()); if (k == "line" && !cylindersOnly) return prim::axisLine(vecOf(p["p"]), vecOf(p["d"])); if (k == "cylinder") { Vec3 midpoint = (vecOf(p["p1"]) + vecOf(p["p2"])) * 0.5; return prim::axisLine(midpoint, vecOf(p["axis"])); } return prim::Line{}; }; auto planeOrigin = [](const json& p) { return vecOf(p["origin"]); }; auto planeNormal = [](const json& p) { return vecOf(p["normal"]); }; json entry; std::string error; if (kind == "line") { prim::Line line; if (how == "planes") { if (inputs.size() != 2 || inputs[0]->value("kind", std::string()) != "plane" || inputs[1]->value("kind", std::string()) != "plane") { error = "planes needs two plane ids"; } else { line = prim::lineFromPlanes( planeOrigin(*inputs[0]), planeNormal(*inputs[0]), planeOrigin(*inputs[1]), planeNormal(*inputs[1])); } } else if (how == "axis") { if (inputs.size() != 1) { error = "axis needs one cylinder or cone id"; } else if (inputs[0]->value("kind", std::string()) == "cylinder") { Vec3 midpoint = (vecOf((*inputs[0])["p1"]) + vecOf((*inputs[0])["p2"])) * 0.5; line = prim::axisLine(midpoint, vecOf((*inputs[0])["axis"])); } else if (inputs[0]->value("kind", std::string()) == "cone") { Vec3 axis = vecOf((*inputs[0])["axis"]); double hm = ((*inputs[0])["h1"].get() + (*inputs[0])["h2"].get()) * 0.5; line = prim::axisLine(vecOf((*inputs[0])["apex"]) + axis * hm, axis); } else { error = "axis needs one cylinder or cone id"; } } else if (how == "average") { if (inputs.size() < 2) { error = "average needs at least two cylinders or lines"; } else { std::vector lines; for (const json* p : inputs) { std::string k = p->value("kind", std::string()); if (k != "line" && k != "cylinder") { error = "average accepts only cylinders and lines"; break; } lines.push_back(lineOf(*p, false)); } if (error.empty()) line = prim::averageLines(lines); } } else if (how == "project") { if (inputs.size() != 2 || inputs[0]->value("kind", std::string()) != "line" || inputs[1]->value("kind", std::string()) != "plane") { error = "project needs a line id then a plane id"; } else { line = prim::projectLine( lineOf(*inputs[0], false), planeOrigin(*inputs[1]), planeNormal(*inputs[1])); } } else { error = "unknown line construction"; } if (error.empty() && !line.ok) error = line.err; if (error.empty()) entry = {{"id", g_nextPrimId}, {"kind", "line"}, {"p", arr(line.p)}, {"d", arr(line.d)}}; } else if (kind == "point") { prim::Point point; if (how == "lineplane") { if (inputs.size() != 2 || inputs[0]->value("kind", std::string()) != "line" || inputs[1]->value("kind", std::string()) != "plane") { error = "lineplane needs a line id then a plane id"; } else { point = prim::linePlanePoint( lineOf(*inputs[0], false), planeOrigin(*inputs[1]), planeNormal(*inputs[1])); } } else if (how == "threeplanes") { if (inputs.size() != 3 || inputs[0]->value("kind", std::string()) != "plane" || inputs[1]->value("kind", std::string()) != "plane" || inputs[2]->value("kind", std::string()) != "plane") { error = "threeplanes needs three plane ids"; } else { std::array origins = { planeOrigin(*inputs[0]), planeOrigin(*inputs[1]), planeOrigin(*inputs[2])}; std::array normals = { planeNormal(*inputs[0]), planeNormal(*inputs[1]), planeNormal(*inputs[2])}; point = prim::threePlanesPoint(origins, normals); } } else if (how == "midpoint") { if (inputs.size() == 2 && inputs[0]->value("kind", std::string()) == "point" && inputs[1]->value("kind", std::string()) == "point") { point = prim::midpointPoints(vecOf((*inputs[0])["p"]), vecOf((*inputs[1])["p"])); } else if (inputs.size() == 1 && inputs[0]->value("kind", std::string()) == "line") { point = prim::midpointLine(lineOf(*inputs[0], false)); } else { error = "midpoint needs two points or one line"; } } else if (how == "center") { if (inputs.size() != 1 || inputs[0]->value("kind", std::string()) != "sphere") error = "center needs one sphere id"; else point = prim::sphereCenter(vecOf((*inputs[0])["center"])); } else { error = "unknown point construction"; } if (error.empty() && !point.ok) error = point.err; if (error.empty()) entry = {{"id", g_nextPrimId}, {"kind", "point"}, {"p", arr(point.p)}}; } else { error = "kind must be line or point"; } double ms = std::chrono::duration( std::chrono::steady_clock::now() - started) .count(); if (!error.empty()) { logf("prim_construct: type=%s/%s npts=%zu rms=0 ms=%.1f FAILED: %s", kind.c_str(), how.c_str(), inputs.size(), ms, error.c_str()); res.status = 400; res.set_content(json({{"ok", false}, {"error", error}}).dump(), "application/json"); return; } ++g_nextPrimId; g_prims.push_back(entry); logf("prim_construct: type=%s/%s npts=%zu rms=0 ms=%.1f", kind.c_str(), how.c_str(), inputs.size(), ms); res.set_content(json({{"ok", true}, {"prim", entry}}).dump(), "application/json"); }); srv.Get("/api/prim/list", [](const httplib::Request&, httplib::Response& res) { std::lock_guard lk(g_mtx); auto started = std::chrono::steady_clock::now(); double ms = std::chrono::duration( std::chrono::steady_clock::now() - started) .count(); logf("prim_list: type=all npts=%zu rms=0 ms=%.1f", g_prims.size(), ms); res.set_content(json({{"ok", true}, {"prims", g_prims}}).dump(), "application/json"); }); srv.Post("/api/prim/delete", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); auto started = std::chrono::steady_clock::now(); json b = json::parse(req.body, nullptr, false); if (b.is_discarded() || !b.is_object() || !b.contains("id") || !b["id"].is_number_integer()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json or missing id"})", "application/json"); return; } int id = b["id"].get(); auto it = std::find_if(g_prims.begin(), g_prims.end(), [id](const json& p) { return p.value("id", -1) == id; }); double ms = std::chrono::duration( std::chrono::steady_clock::now() - started) .count(); if (it == g_prims.end()) { logf("prim_delete: type=id:%d npts=0 rms=0 ms=%.1f FAILED: unknown id", id, ms); res.status = 404; res.set_content(R"({"ok":false,"error":"unknown primitive id"})", "application/json"); return; } g_surfaces.erase(id); g_surfaceExported.erase(id); g_prims.erase(it); logf("prim_delete: type=id:%d npts=1 rms=0 ms=%.1f", id, ms); res.set_content(R"({"ok":true})", "application/json"); }); // ---- automatic feature discovery ---- srv.Post("/api/discover", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); if (g_mesh.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"no mesh"})", "application/json"); return; } json b = json::parse(req.body, nullptr, false); discover::Params p; if (!b.is_discarded() && b.is_object()) { p.angTolDeg = b.value("angTolDeg", p.angTolDeg); p.curvSeed = b.value("curvSeed", p.curvSeed); p.minPlanePts = b.value("minPlanePts", p.minPlanePts); p.minCylPts = b.value("minCylPts", p.minCylPts); p.minRadiusMM = b.value("minRadiusMM", p.minRadiusMM); p.cylRmsRatio = b.value("cylRmsRatio", p.cylRmsRatio); p.smoothPasses = b.value("smoothPasses", p.smoothPasses); p.curvCap = b.value("curvCap", p.curvCap); p.minCoverage = b.value("minCoverage", p.minCoverage); p.minDiameterMM = b.value("minDiameterMM", p.minDiameterMM); p.maxDiameterMM = b.value("maxDiameterMM", p.maxDiameterMM); p.holesOnly = b.value("holesOnly", p.holesOnly); if (b.contains("region") && b["region"].is_array()) { for (const auto& pl : b["region"]) { if (pl.is_array() && pl.size() == 4) p.region.push_back({pl[0].get(), pl[1].get(), pl[2].get(), pl[3].get()}); } } } auto D = discover::discover(g_mesh, p); logf("discover: %zu planes, %zu cyls in %.0f ms (D=%.1f-%.1f mm%s%s)%s%s", D.planes.size(), D.cyls.size(), D.ms, p.minDiameterMM, p.maxDiameterMM, p.holesOnly ? ", holes only" : "", p.region.empty() ? "" : ", boxed", D.note.empty() ? "" : " note: ", D.note.c_str()); json planes = json::array(); for (const auto& pl : D.planes) planes.push_back({{"origin", arr(pl.origin)}, {"normal", arr(pl.normal)}, {"u", arr(pl.u)}, {"v", arr(pl.v)}, {"umin", pl.umin}, {"umax", pl.umax}, {"vmin", pl.vmin}, {"vmax", pl.vmax}, {"npts", pl.npts}, {"rms", pl.rms}}); json cyls = json::array(); for (const auto& c : D.cyls) cyls.push_back({{"center", arr(c.center)}, {"axis", arr(c.axis)}, {"diameter", c.diameter}, {"depth", c.depth}, {"p1", arr(c.p1)}, {"p2", arr(c.p2)}, {"npts", c.npts}, {"rms", c.rms}, {"coverage", c.coverage}, {"isHole", c.isHole}}); json r = {{"ok", true}, {"planes", planes}, {"cyls", cyls}, {"datumIndex", D.datumIndex}, {"nverts", D.nverts}, {"ntris", D.ntris}, {"ms", D.ms}, {"note", D.note}, {"dbg", {{"planesRejected", D.dbgPlanesRejected}, {"maxRegion", D.dbgMaxRegion}, {"leftover", D.dbgLeftover}, {"components", D.dbgComponents}, {"cylRejFit", D.dbgCylRejFit}, {"cylRejRadius", D.dbgCylRejRadius}, {"cylRejRms", D.dbgCylRejRms}, {"cylRejSmall", D.dbgCylRejSmall}}}}; res.set_content(r.dump(), "application/json"); }); // ---- build STEP + macro ---- srv.Post("/api/build", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); json b = json::parse(req.body, nullptr, false); if (b.is_discarded()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json"})", "application/json"); return; } builder::BuildParams bp; auto dj = b.value("datum", json::object()); bp.datum.origin = vecOf(dj.value("origin", json::array())); bp.datum.normal = vecOf(dj.value("normal", json::array()), {0, 0, 1}); bp.datum.u = vecOf(dj.value("u", json::array()), {1, 0, 0}); bp.datum.v = vecOf(dj.value("v", json::array()), {0, 1, 0}); bp.thickness = b.value("thickness", 6.0); bp.margin = b.value("margin", 8.0); for (const auto& hj : b.value("holes", json::array())) { builder::Hole h; h.center = vecOf(hj.value("center", json::array())); h.axis = vecOf(hj.value("axis", json::array()), {0, 0, 1}); h.diameter = hj.value("diameter", 0.0); h.through = hj.value("through", true); h.depth = hj.value("depth", 0.0); h.thread = hj.value("thread", std::string()); h.label = hj.value("label", std::string()); if (h.diameter > 0) bp.holes.push_back(h); } if (bp.holes.empty()) { res.set_content(R"({"ok":false,"error":"no valid holes"})", "application/json"); return; } std::string stepPath = g_outDir + "/part.step"; auto br = builder::buildAndExport(bp, stepPath); if (!br.ok) { logf("build: FAILED: %s", br.error.c_str()); res.set_content(json({{"ok", false}, {"error", br.error}}).dump(), "application/json"); return; } logf("build: %d hole(s) cut -> %s", br.holesCut, stepPath.c_str()); std::string stepWin = b.value("stepWinPath", std::string()); std::string vba = macrogen::generateVBA(bp, stepWin); std::string macroPath = g_outDir + "/solidworks_macro.vba"; { std::ofstream f(macroPath); f << vba; } json r = {{"ok", true}, {"holesCut", br.holesCut}, {"step", "/api/download?f=step"}, {"macro", "/api/download?f=macro"}, {"stepPath", stepPath}, {"macroPath", macroPath}}; res.set_content(r.dump(), "application/json"); }); // ---- export the mounting-hole interface as reference geometry (for brackets) ---- srv.Post("/api/interface", [](const httplib::Request& req, httplib::Response& res) { std::lock_guard lk(g_mtx); json b = json::parse(req.body, nullptr, false); if (b.is_discarded()) { res.status = 400; res.set_content(R"({"ok":false,"error":"bad json"})", "application/json"); return; } std::vector holes; std::vector bossDirs; // per hole: +1 boss along axis, -1 against, 0 auto for (const auto& hj : b.value("holes", json::array())) { builder::Hole h; h.center = vecOf(hj.value("center", json::array())); h.axis = vecOf(hj.value("axis", json::array()), {0, 0, 1}); h.diameter = hj.value("diameter", 0.0); h.thread = hj.value("thread", std::string()); h.label = hj.value("label", std::string()); if (h.diameter > 0) { holes.push_back(h); int bd = hj.value("bossDir", 0); bossDirs.push_back(bd > 0 ? 1 : bd < 0 ? -1 : 0); } } if (holes.empty()) { res.set_content(R"({"ok":false,"error":"no valid holes"})", "application/json"); return; } std::string ferr; builder::RefFrame fr = builder::frameFromHoles(holes, b.value("originHole", -1), b.value("xHole", -1), b.value("zHole", -1), ferr); if (!ferr.empty()) { res.set_content(json({{"ok", false}, {"error", ferr}}).dump(), "application/json"); return; } // mount options double bossHeight = b.value("bossHeight", 5.0); double bossExtra = b.value("bossExtraDiameter", 6.0); // boss Ø = hole Ø + this double cropMargin = b.value("cropMargin", 25.0); // frame-mesh crop half-extent bool haveMesh = !g_mesh.empty(); // Build a Mount per hole: fit the local mount-face plane from the mesh (falls back // to the hole axis when no mesh is loaded), seat the boss on it, coaxial hole. std::vector mounts; std::vector mountDirs; // per mount: "user" | "material" | "ambiguous" // Per-mount seat-fit support points, pooled later for the coplanar joint fit. std::vector> mountPts(holes.size()), mountNrm(holes.size()); const int meshOrient = haveMesh ? mesh::windingOrientation(g_mesh) : 0; for (size_t i = 0; i < holes.size(); ++i) { const auto& h = holes[i]; builder::Mount mt; double holeR = h.diameter * 0.5; double faceR = std::max(3.0 * holeR, 12.0); double bossR = (h.diameter + bossExtra) * 0.5; Vec3 axis = geom::normalize(h.axis); Vec3 seat = h.center; bool pfOk = false; Vec3 pfN{0, 0, 0}; // seat-patch normal, oriented along the vertex normals if (haveMesh) { // Slab-restricted fit: a spherical query at a through hole swallows the // far side of the plate and the fit settles mid-thickness. auto pf = fit::fitPlaneSlab(g_mesh, h.center, faceR, h.axis, 1.5, &mountPts[i], &mountNrm[i]); if (pf.ok) { pfOk = true; pfN = pf.normal; axis = pf.normal; if (geom::dot(axis, h.axis) < 0) axis = axis * -1.0; // keep hole-axis sense seat = h.center - axis * geom::dot(h.center - pf.origin, axis); // project } else { mountPts[i].clear(); mountNrm[i].clear(); } } // The incoming axis sign is arbitrary (the seat fit orients it toward // whatever camera picked it). The boss grows along +axis from the seat and // must stay inside the scanned part. Decision order: // 1. an explicit user choice (bossDir) always wins; // 2. the seat patch's vertex normals x the mesh's winding polarity — a // local signal that neighbouring walls can't out-vote; // 3. the occupancy probe (which side of the seat holds mesh points); // 4. keep the hole-axis sense and report "ambiguous" so the UI asks. std::string dir = "ambiguous"; if (bossDirs[i] != 0) { if (bossDirs[i] < 0) axis = axis * -1.0; dir = "user"; } else if (pfOk && meshOrient != 0) { axis = pfN * (double)(-meshOrient); // -outward = into the material dir = "material"; } else if (haveMesh) { int side = fit::materialSide(g_mesh, seat, axis, bossR * 1.2, std::max(bossHeight * 2.0, 10.0)); if (side < 0) axis = axis * -1.0; if (side != 0) dir = "material"; // Open sheet-metal scans defeat both global signals: the winding // test needs a closed-enough volume and the occupancy probe needs // material depth, but a stamped bracket is 2-3 mm of wall with air // on both sides. The seat patch's own vertex normals still know // which side is outside — scanners orient them off the surface — // so a decisive majority points the boss the other way. if (dir == "ambiguous" && pfOk && !mountNrm[i].empty()) { int agree = 0; for (const auto& vn : mountNrm[i]) if (geom::dot(vn, pfN) > 0) ++agree; double frac = (double)agree / mountNrm[i].size(); if (frac > 0.8 || frac < 0.2) { Vec3 outward = frac > 0.5 ? pfN : pfN * -1.0; axis = outward * -1.0; dir = "normals"; } } } logf("interface: %s boss dir %s", h.label.c_str(), dir == "user" ? "set by user" : dir == "material" ? "into material (probed)" : dir == "normals" ? "into material (surface normals)" : "ambiguous - kept hole-axis sense"); mountDirs.push_back(dir); mt.seat = seat; mt.axis = axis; mt.holeDiameter = h.diameter; mt.bossDiameter = h.diameter + bossExtra; mt.bossHeight = bossHeight; mt.faceHalfSize = std::max(2.0 * holeR, 8.0); mt.label = h.label.empty() ? "mount" : h.label; mounts.push_back(mt); } // ---- coplanar snap ---- // Seats that are ONE machined plane on the real part come back from the // per-hole refits fractions of a degree/mm apart (scan ripple). Cluster the // refit planes within tolerance, joint-fit one plane through each cluster's // pooled support points, and re-seat every member on it — the STEP then // shows one plane carrying N bosses instead of N near-identical planes. const double copAngDeg = b.value("coplanarAngleDeg", 2.0); const double copOffMM = b.value("coplanarOffsetMM", 0.75); json planesOut = json::array(); if (copAngDeg > 0 && mounts.size() > 1) { const double cosTol = std::cos(copAngDeg * M_PI / 180.0); struct Cluster { std::vector members; Vec3 n; Vec3 o; }; std::vector clusters; for (size_t i = 0; i < mounts.size(); ++i) { if (mountPts[i].empty()) continue; // no mesh-backed seat fit — leave alone Vec3 ni = geom::normalize(mounts[i].axis); bool joined = false; for (auto& c : clusters) { if (std::fabs(geom::dot(ni, c.n)) < cosTol) continue; // plane-to-plane offset, checked against both normals so a pair // of tilted-but-crossing planes far apart can't sneak in double d1 = std::fabs(geom::dot(mounts[i].seat - c.o, c.n)); double d2 = std::fabs(geom::dot(c.o - mounts[i].seat, ni)); if (std::max(d1, d2) > copOffMM) continue; c.members.push_back((int)i); joined = true; break; } if (!joined) clusters.push_back({{(int)i}, ni, mounts[i].seat}); } int gid = 0; for (const auto& c : clusters) { if (c.members.size() < 2) continue; std::vector pts, nrm; for (int i : c.members) { pts.insert(pts.end(), mountPts[i].begin(), mountPts[i].end()); nrm.insert(nrm.end(), mountNrm[i].begin(), mountNrm[i].end()); } auto jf = fit::fitPlanePoints(pts, nrm, c.n); if (!jf.ok) continue; std::string names; for (int i : c.members) { auto& mt = mounts[i]; Vec3 n2 = jf.normal; if (geom::dot(n2, mt.axis) < 0) n2 = n2 * -1.0; // keep boss direction // Re-seat on the joint plane along the bore axis (= the new normal), // so the boss stays coaxial with the detected hole. mt.seat = holes[i].center - jf.normal * geom::dot(holes[i].center - jf.origin, jf.normal); mt.axis = n2; mt.group = gid; names += (names.empty() ? "" : "+") + mt.label; } logf("interface: coplanar snap: %s share one plane (joint rms %.3f mm, %d pts)", names.c_str(), jf.rms, jf.npts); planesOut.push_back({{"normal", arr(jf.normal)}, {"origin", arr(jf.origin)}, {"rms", jf.rms}, {"npts", jf.npts}, {"members", c.members}}); ++gid; } } // Carry the whole Prims-step registry into the STEP: fitted planes as // their minimal-rectangle faces, reference/axis lines as edges, points // (and sphere centres) as vertices. CAD then has every datum the user // extracted, not just the per-mount seat patches. builder::RefGeometry refs = collectRefGeometry(); if (!refs.planeRects.empty() || !refs.lines.empty() || !refs.points.empty()) logf("interface: + reference geometry: %zu plane(s), %zu line(s), %zu point(s)", refs.planeRects.size(), refs.lines.size(), refs.points.size()); std::string stepPath = g_outDir + "/interface.step"; auto br = builder::exportMounts(mounts, fr, stepPath, &refs); if (!br.ok) { logf("interface: FAILED: %s", br.error.c_str()); res.set_content(json({{"ok", false}, {"error", br.error}}).dump(), "application/json"); return; } logf("interface: %zu mount(s) -> %s", mounts.size(), stepPath.c_str()); // Crop the frame surface around the mounts to a mesh body for context. int meshTris = 0; if (haveMesh) { Vec3 lo = holes[0].center, hi = holes[0].center; for (const auto& h : holes) { lo.x = std::min(lo.x, h.center.x); hi.x = std::max(hi.x, h.center.x); lo.y = std::min(lo.y, h.center.y); hi.y = std::max(hi.y, h.center.y); lo.z = std::min(lo.z, h.center.z); hi.z = std::max(hi.z, h.center.z); } Vec3 m{cropMargin, cropMargin, cropMargin}; meshTris = mesh::writeSTLRegion(g_outDir + "/interface_mesh.stl", g_mesh, lo - m, hi + m); } std::string vba = macrogen::generateInterfaceVBA(holes, fr); { std::ofstream f(g_outDir + "/interface_macro.vba"); f << vba; } std::string winDir = b.value("winDir", "C:\\temp"); std::string assemblyVba = macrogen::generateAssemblyVBA(winDir); { std::ofstream f(g_outDir + "/interface_assembly.vba"); f << assemblyVba; } auto V = [](const geom::Vec3& v) { return json::array({v.x, v.y, v.z}); }; json holesInFrame = json::array(); for (const auto& h : holes) { geom::Vec3 d = h.center - fr.origin; holesInFrame.push_back({{"x", geom::dot(d, fr.x)}, {"y", geom::dot(d, fr.y)}, {"z", geom::dot(d, fr.z)}, {"diameter", h.diameter}}); } json mountsOut = json::array(); for (size_t i = 0; i < mounts.size(); ++i) mountsOut.push_back({{"seat", V(mounts[i].seat)}, {"axis", V(mounts[i].axis)}, {"bossDiameter", mounts[i].bossDiameter}, {"bossHeight", mounts[i].bossHeight}, {"dir", mountDirs[i]}, {"plane", mounts[i].group}}); json r = {{"ok", true}, {"holes", (int)holes.size()}, {"meshTris", meshTris}, {"frame", {{"origin", V(fr.origin)}, {"x", V(fr.x)}, {"y", V(fr.y)}, {"z", V(fr.z)}}}, {"holesInFrame", holesInFrame}, {"mounts", mountsOut}, {"planes", planesOut}, {"step", "/api/download?f=istep"}, {"macro", "/api/download?f=imacro"}, {"asm", "/api/download?f=iasm"}}; if (meshTris > 0) r["mesh"] = "/api/download?f=imesh"; res.set_content(r.dump(), "application/json"); }); // ---- one-stop SolidWorks package: everything the assembly macro needs ---- srv.Get("/api/interface/package", [](const httplib::Request&, httplib::Response& res) { std::lock_guard lk(g_mtx); auto slurp = [](const std::string& p) { std::ifstream f(p, std::ios::binary); return f ? std::string((std::istreambuf_iterator(f)), std::istreambuf_iterator()) : std::string(); }; std::string step = slurp(g_outDir + "/interface.step"); std::string asmVba = slurp(g_outDir + "/interface_assembly.vba"); std::string ifVba = slurp(g_outDir + "/interface_macro.vba"); if (step.empty() || asmVba.empty()) { res.status = 400; res.set_content(R"({"ok":false,"error":"export the interface first"})", "application/json"); return; } std::string readme = "scan2cad SolidWorks package\n" "===========================\n\n" "1. Extract ALL files into the folder the export screen showed\n" " (default C:\\temp) - the macro looks for them there by name.\n" "2. In SolidWorks: Tools > Macro > New, paste scan2cad_assembly.vba, Run.\n" " (Menus hidden? Hover the SOLIDWORKS logo top-left, pin the menu bar.)\n" " It imports the STEP (mount solids + reference planes/axes/points)\n" " and the scan mesh, then builds scan2cad_assembly.sldasm with both\n" " fixed at the origin - they share the scan's coordinate frame.\n\n" "Files:\n" " scan2cad_interface.step mount bosses + your reference geometry\n" " scan2cad_scan.stl the scan mesh (as edited in the Mesh step)\n" " scan2cad_assembly.vba builds the assembly (run this one)\n" " scan2cad_interface.vba optional: hole centres/axes as a 3D sketch\n"; std::vector> files = { {"scan2cad_interface.step", std::move(step)}, {"scan2cad_scan.stl", mesh::binarySTL(g_mesh)}, {"scan2cad_assembly.vba", std::move(asmVba)}, {"README.txt", std::move(readme)}, }; if (!ifVba.empty()) files.push_back({"scan2cad_interface.vba", std::move(ifVba)}); std::string zip = zipw::makeZip(files); logf("interface package: %zu files, %zu B zip", files.size(), zip.size()); res.set_header("Content-Disposition", "attachment; filename=\"scan2cad_solidworks.zip\""); res.set_content(zip, "application/zip"); }); // ---- download generated artifacts ---- srv.Get("/api/download", [](const httplib::Request& req, httplib::Response& res) { std::string which = req.has_param("f") ? req.get_param_value("f") : ""; std::string path, name, mime; if (which == "step") { path = g_outDir + "/part.step"; name = "scan2cad_part.step"; mime = "application/step"; } else if (which == "macro") { path = g_outDir + "/solidworks_macro.vba"; name = "scan2cad_macro.vba"; mime = "text/plain"; } else if (which == "istep") { path = g_outDir + "/interface.step"; name = "scan2cad_interface.step"; mime = "application/step"; } else if (which == "imacro") { path = g_outDir + "/interface_macro.vba"; name = "scan2cad_interface.vba"; mime = "text/plain"; } else if (which == "iasm") { path = g_outDir + "/interface_assembly.vba"; name = "scan2cad_assembly.vba"; mime = "text/plain"; } else if (which == "imesh") { path = g_outDir + "/interface_mesh.stl"; name = "scan2cad_scan.stl"; mime = "application/sla"; } else { res.status = 400; res.set_content("bad f", "text/plain"); return; } std::ifstream f(path, std::ios::binary); if (!f) { res.status = 404; res.set_content("not built yet", "text/plain"); return; } std::string data((std::istreambuf_iterator(f)), std::istreambuf_iterator()); res.set_header("Content-Disposition", ("attachment; filename=\"" + name + "\"").c_str()); res.set_content(data, mime.c_str()); }); printf("scan2cad listening on http://%s:%d (web: %s, out: %s)\n", host.c_str(), port, webRoot.c_str(), g_outDir.c_str()); srv.listen(host.c_str(), port); return 0; }