Skip to content

Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.

Garments part 1: pattern panels at real size, even triangulation, seams, arrangement, SVG/DXF, garment_* commands

islandmedf836b5d8d8e7
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 83b4c793..20608d3a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -64,6 +64,10 @@ add_library(sculptforge_core STATIC
src/core/ScreenSelect.cpp
src/core/Parts.cpp
src/core/Units.cpp
+ src/core/Garment.cpp
+ src/core/GarmentMesh.cpp
+ src/core/GarmentFiles.cpp
+ src/core/GarmentCommands.cpp
src/core/ExtractMirror.cpp
src/core/MeshTransform.cpp
src/core/Deform.cpp
diff --git a/changes/feat-garment-patterns.md b/changes/feat-garment-patterns.md
new file mode 100644
index 00000000..9a51c70a
--- /dev/null
+++ b/changes/feat-garment-patterns.md
@@ -0,0 +1,15 @@
+---
+added: **Garments, part 1** (scripting and the AI assistant for now; the Pattern window follows): pattern panels at
+ real size (millimetres, curves, notches, grain line, seam allowance) saved in the project, a T-shirt template
+ (front, back, two sleeves, sewn), seams with length and direction checks, even triangulation at a chosen particle
+ distance with seams matched point for point, placement around the body (front, back, sides, arms found from its
+ shape), export as a real-size SVG for printing and sewing (with a 50 mm scale square) or DXF for cutters, and
+ SVG panels read back in. Commands: garment_new, garment_info, garment_add_panel, garment_sew, garment_place,
+ garment_export, garment_import and more.
+testers:
+ - Any OS: `sculptforge-cli -c "garment_new; garment_export path=shirt.svg"`; open the SVG in a
+ browser or print it at 100%: the square is 50 mm, the front is 52 cm wide.
+---
+Part 1 of 3 (garments agent). Core only: no UI, no simulation yet (Drape comes from the cloth agent's solver,
+docs/design/cloth.md section 7). Tests: tests/test_garment.cpp (a sewn T-shirt welds into one consistently
+oriented surface with exactly four openings; SVG reader fuzzed).
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index af1ef556..96d528bb 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -35,6 +35,7 @@
#include "core/Project.h"
#include "core/QRemesh.h"
#include "core/ForgeSpheres.h"
+#include "core/Garment.h"
#include "core/Deform.h"
#include "core/Sculptable.h"
#include "core/Splats.h"
@@ -884,6 +885,7 @@ CommandRegistry::CommandRegistry() {
registerBlenderCommands(*this); // blender_send/receive (io/BlenderCommands.cpp)
registerMayaCommands(*this); // maya_send/receive (io/MayaCommands.cpp)
registerBakeCommands(*this); // bake (core/Bake.cpp)
+ registerGarmentCommands(*this); // garment_* (core/GarmentCommands.cpp)
registerFaceCommands(*this); // face_shapes_generate, face_weights, ... (core/FaceCommands.cpp)
registerStarterMeshCommands(*this); // new_starter_mesh (core/StarterMeshes.h)
registerPackCommands(*this); // pack_install, pack_list, pack_remove, ... (core/Pack.h)
diff --git a/src/core/Garment.cpp b/src/core/Garment.cpp
new file mode 100644
index 00000000..6328eead
--- /dev/null
+++ b/src/core/Garment.cpp
@@ -0,0 +1,1207 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Garments: pattern panels, their edits, seams, the body arrangement, the Part made after the simulation, the
+// T-shirt template and the project JSON (core/Garment.h). Triangulation is in GarmentMesh.cpp, files in
+// GarmentFiles.cpp.
+#include "core/Garment.h"
+
+#include "core/Document.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <cctype>
+#include <limits>
+#include <numeric>
+
+namespace sf::garment {
+
+namespace {
+
+constexpr float kPi = 3.14159265358979f;
+
+glm::vec2 bezier(glm::vec2 p0, glm::vec2 c1, glm::vec2 c2, glm::vec2 p1, float u) {
+ const float v = 1.0f - u;
+ return v * v * v * p0 + 3.0f * v * v * u * c1 + 3.0f * v * u * u * c2 + u * u * u * p1;
+}
+
+uint32_t count(const Panel& p) { return uint32_t(p.points.size()); }
+glm::vec2 startOf(const Panel& p, uint32_t e) { return p.points[e]; }
+glm::vec2 endOf(const Panel& p, uint32_t e) { return p.points[(e + 1) % count(p)]; }
+const EdgeCurve& curveOf(const Panel& p, uint32_t e) {
+ static const EdgeCurve straight;
+ return e < p.curves.size() ? p.curves[e] : straight;
+}
+
+// The edge sampled finely with each sample's Bezier parameter and arc length (for exact t <-> parameter maps).
+struct Samples {
+ std::vector<glm::vec2> pts;
+ std::vector<float> u, len;
+};
+Samples sampleEdge(const Panel& p, uint32_t e, int n) {
+ Samples s;
+ const EdgeCurve& c = curveOf(p, e);
+ const glm::vec2 a = startOf(p, e), b = endOf(p, e);
+ if (!c.curved) n = 1;
+ s.pts.reserve(size_t(n) + 1);
+ float total = 0.0f;
+ for (int i = 0; i <= n; ++i) {
+ const float u = float(i) / float(n);
+ const glm::vec2 q = c.curved ? bezier(a, c.c1, c.c2, b, u) : glm::mix(a, b, u);
+ if (i) total += glm::length(q - s.pts.back());
+ s.pts.push_back(q);
+ s.u.push_back(u);
+ s.len.push_back(total);
+ }
+ return s;
+}
+int fineCount(const Panel& p, uint32_t e) {
+ const EdgeCurve& c = curveOf(p, e);
+ if (!c.curved) return 1;
+ const float hull = glm::length(c.c1 - startOf(p, e)) + glm::length(c.c2 - c.c1) + glm::length(endOf(p, e) - c.c2);
+ return std::clamp(int(std::ceil(hull / 1.0f)), 16, 2048);
+}
+// The Bezier parameter at arc-length fraction t.
+float paramAt(const Samples& s, float t) {
+ const float total = s.len.back();
+ if (total <= 0.0f) return t;
+ const float want = std::clamp(t, 0.0f, 1.0f) * total;
+ const auto it = std::lower_bound(s.len.begin(), s.len.end(), want);
+ const size_t i = size_t(std::max<ptrdiff_t>(1, it - s.len.begin()));
+ if (i >= s.len.size()) return 1.0f;
+ const float l0 = s.len[i - 1], l1 = s.len[i];
+ const float f = l1 > l0 ? (want - l0) / (l1 - l0) : 0.0f;
+ return s.u[i - 1] + (s.u[i] - s.u[i - 1]) * f;
+}
+
+float cross2(glm::vec2 a, glm::vec2 b) { return a.x * b.y - a.y * b.x; }
+
+bool segmentsCross(glm::vec2 a, glm::vec2 b, glm::vec2 c, glm::vec2 d) {
+ const float d1 = cross2(b - a, c - a), d2 = cross2(b - a, d - a);
+ const float d3 = cross2(d - c, a - c), d4 = cross2(d - c, b - c);
+ return ((d1 > 0) != (d2 > 0)) && ((d3 > 0) != (d4 > 0)) && d1 != 0 && d2 != 0 && d3 != 0 && d4 != 0;
+}
+
+// Reverses a panel's direction (points, curves, notches); edge j becomes edge n - 1 - j, t becomes 1 - t.
+void reverseInPlace(Panel& p, std::vector<Seam>* seams, uint32_t self) {
+ const uint32_t n = count(p);
+ if (n < 2) return;
+ std::vector<glm::vec2> pts(n);
+ std::vector<EdgeCurve> cur(n);
+ for (uint32_t k = 0; k < n; ++k) {
+ pts[k] = p.points[(n - k) % n];
+ const EdgeCurve& c = curveOf(p, n - 1 - k);
+ cur[k] = {c.curved, c.c2, c.c1};
+ }
+ p.points = std::move(pts);
+ p.curves = std::move(cur);
+ for (Notch& nt : p.notches) {
+ nt.edge = n - 1 - nt.edge;
+ nt.t = 1.0f - nt.t;
+ }
+ if (seams)
+ for (Seam& s : *seams)
+ for (SeamSide* side : {&s.a, &s.b})
+ if (side->panel == self) {
+ side->edge = n - 1 - side->edge;
+ const float t0 = 1.0f - side->t1, t1 = 1.0f - side->t0;
+ side->t0 = t0;
+ side->t1 = t1;
+ }
+}
+
+void fixPanels(std::vector<Seam>& seams, uint32_t removed) {
+ seams.erase(std::remove_if(seams.begin(), seams.end(),
+ [&](const Seam& s) { return s.a.panel == removed || s.b.panel == removed; }),
+ seams.end());
+ for (Seam& s : seams) {
+ if (s.a.panel > removed) --s.a.panel;
+ if (s.b.panel > removed) --s.b.panel;
+ }
+}
+
+Slot mirroredSlot(Slot s) {
+ switch (s) {
+ case Slot::Left: return Slot::Right;
+ case Slot::Right: return Slot::Left;
+ case Slot::LeftArm: return Slot::RightArm;
+ case Slot::RightArm: return Slot::LeftArm;
+ default: return s;
+ }
+}
+
+bool overlaps(const SeamSide& x, const SeamSide& y) {
+ return x.panel == y.panel && x.edge == y.edge && x.t0 < y.t1 - 1e-4f && y.t0 < x.t1 - 1e-4f;
+}
+
+} // namespace
+
+// ---------------------------------------------------------------------------
+// Slots
+// ---------------------------------------------------------------------------
+
+const char* slotId(Slot s) {
+ static const char* ids[] = {"front", "back", "left", "right", "left_arm", "right_arm", "free"};
+ return s < Slot::Count ? ids[int(s)] : "free";
+}
+const char* slotLabel(Slot s) {
+ static const char* labels[] = {"Front", "Back", "Left side", "Right side", "Left arm", "Right arm", "Free"};
+ return s < Slot::Count ? labels[int(s)] : "Free";
+}
+bool slotFromId(const std::string& id, Slot& out) {
+ for (int i = 0; i < int(Slot::Count); ++i)
+ if (id == slotId(Slot(i))) {
+ out = Slot(i);
+ return true;
+ }
+ return false;
+}
+
+// ---------------------------------------------------------------------------
+// Panel geometry
+// ---------------------------------------------------------------------------
+
+void normalizePanel(Panel& p) {
+ p.curves.resize(p.points.size());
+ const uint32_t n = count(p);
+ p.notches.erase(std::remove_if(p.notches.begin(), p.notches.end(),
+ [&](const Notch& nt) { return nt.edge >= n || !(nt.t >= 0.0f && nt.t <= 1.0f); }),
+ p.notches.end());
+ if (n >= 3 && panelArea(p) < 0.0f) reverseInPlace(p, nullptr, 0);
+}
+
+std::vector<glm::vec2> edgePolyline(const Panel& p, uint32_t e, float tolerance) {
+ const EdgeCurve& c = curveOf(p, e);
+ if (!c.curved) return {startOf(p, e), endOf(p, e)};
+ // Segments for a flattening error under `tolerance`: a cubic's chord error falls with the square of the count.
+ const glm::vec2 a = startOf(p, e), b = endOf(p, e);
+ const float bend = std::max(glm::length(a - 2.0f * c.c1 + c.c2), glm::length(c.c1 - 2.0f * c.c2 + b));
+ const int n = std::clamp(int(std::ceil(std::sqrt(0.75f * bend / std::max(tolerance, 0.01f)))), 4, 512);
+ std::vector<glm::vec2> out;
+ out.reserve(size_t(n) + 1);
+ for (int i = 0; i <= n; ++i) out.push_back(bezier(a, c.c1, c.c2, b, float(i) / float(n)));
+ return out;
+}
+
+float edgeLength(const Panel& p, uint32_t e) {
+ if (e >= count(p)) return 0.0f;
+ return sampleEdge(p, e, fineCount(p, e)).len.back();
+}
+
+glm::vec2 edgePoint(const Panel& p, uint32_t e, float t, glm::vec2* tangent) {
+ if (e >= count(p)) return glm::vec2(0.0f);
+ const EdgeCurve& c = curveOf(p, e);
+ const glm::vec2 a = startOf(p, e), b = endOf(p, e);
+ if (!c.curved) {
+ if (tangent) *tangent = glm::length(b - a) > 0 ? glm::normalize(b - a) : glm::vec2(1, 0);
+ return glm::mix(a, b, std::clamp(t, 0.0f, 1.0f));
+ }
+ const float u = paramAt(sampleEdge(p, e, fineCount(p, e)), t);
+ if (tangent) {
+ const float v = 1.0f - u;
+ const glm::vec2 d = 3.0f * v * v * (c.c1 - a) + 6.0f * v * u * (c.c2 - c.c1) + 3.0f * u * u * (b - c.c2);
+ *tangent = glm::length(d) > 0 ? glm::normalize(d) : glm::normalize(b - a + glm::vec2(1e-6f));
+ }
+ return bezier(a, c.c1, c.c2, b, u);
+}
+
+std::vector<glm::vec2> outline(const Panel& p, float tolerance) {
+ std::vector<glm::vec2> out;
+ for (uint32_t e = 0; e < count(p); ++e) {
+ std::vector<glm::vec2> pl = edgePolyline(p, e, tolerance);
+ out.insert(out.end(), pl.begin(), pl.end() - 1);
+ }
+ return out;
+}
+
+float panelArea(const Panel& p) {
+ const std::vector<glm::vec2> o = outline(p, 0.5f);
+ double a = 0.0;
+ for (size_t i = 0; i < o.size(); ++i) a += double(cross2(o[i], o[(i + 1) % o.size()]));
+ return float(a * 0.5);
+}
+
+float perimeter(const Panel& p) {
+ float l = 0.0f;
+ for (uint32_t e = 0; e < count(p); ++e) l += edgeLength(p, e);
+ return l;
+}
+
+glm::vec2 panelMin(const Panel& p) {
+ glm::vec2 m(std::numeric_limits<float>::max());
+ for (glm::vec2 q : outline(p, 0.5f)) m = glm::min(m, q);
+ return p.points.empty() ? glm::vec2(0.0f) : m;
+}
+glm::vec2 panelMax(const Panel& p) {
+ glm::vec2 m(std::numeric_limits<float>::lowest());
+ for (glm::vec2 q : outline(p, 0.5f)) m = glm::max(m, q);
+ return p.points.empty() ? glm::vec2(0.0f) : m;
+}
+
+bool validPanel(const Panel& p, std::string& error) {
+ if (p.points.size() < 3) {
+ error = p.name + " needs at least 3 points";
+ return false;
+ }
+ for (glm::vec2 q : p.points)
+ if (!std::isfinite(q.x) || !std::isfinite(q.y) || std::abs(q.x) > 1e6f || std::abs(q.y) > 1e6f) {
+ error = p.name + " has a point out of range";
+ return false;
+ }
+ for (uint32_t e = 0; e < count(p); ++e)
+ if (edgeLength(p, e) < 1.0f) {
+ error = p.name + ": edge " + std::to_string(e + 1) + " is shorter than 1 mm";
+ return false;
+ }
+ if (std::abs(panelArea(p)) < 1.0f) {
+ error = p.name + " has no area";
+ return false;
+ }
+ const std::vector<glm::vec2> o = outline(p, 0.5f);
+ const size_t n = o.size();
+ if (n > 20000) {
+ error = p.name + " has too many points";
+ return false;
+ }
+ for (size_t i = 0; i < n; ++i)
+ for (size_t j = i + 2; j < n; ++j) {
+ if (i == 0 && j == n - 1) continue;
+ if (segmentsCross(o[i], o[(i + 1) % n], o[j], o[(j + 1) % n])) {
+ error = p.name + "'s outline crosses itself";
+ return false;
+ }
+ }
+ return true;
+}
+
+std::vector<glm::vec2> offsetOutline(const Panel& p, float d) {
+ std::vector<glm::vec2> o = outline(p, 0.2f);
+ const size_t n = o.size();
+ std::vector<glm::vec2> out;
+ if (n < 3) return o;
+ const float sign = panelArea(p) >= 0 ? 1.0f : -1.0f;
+ for (size_t i = 0; i < n; ++i) {
+ const glm::vec2 a = o[(i + n - 1) % n], b = o[i], c = o[(i + 1) % n];
+ auto normal = [&](glm::vec2 u, glm::vec2 v) {
+ glm::vec2 t = v - u;
+ const float l = glm::length(t);
+ t = l > 0 ? t / l : glm::vec2(1, 0);
+ return sign * glm::vec2(t.y, -t.x); // outward for a counter-clockwise outline
+ };
+ const glm::vec2 n1 = normal(a, b), n2 = normal(b, c);
+ glm::vec2 m = n1 + n2;
+ const float ml = glm::length(m);
+ if (ml < 1e-4f) {
+ out.push_back(b + n1 * d);
+ continue;
+ }
+ m /= ml;
+ const float cosHalf = glm::dot(m, n1);
+ if (cosHalf < 0.5f) { // sharper than 120 degrees: a bevel instead of a long spike
+ out.push_back(b + n1 * d);
+ out.push_back(b + n2 * d);
+ } else {
+ out.push_back(b + m * (d / cosHalf));
+ }
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Edits
+// ---------------------------------------------------------------------------
+
+void mirrorPanel(Pattern& pat, uint32_t i) {
+ if (i >= pat.panels.size()) return;
+ Panel& p = pat.panels[i];
+ const float cx = (panelMin(p).x + panelMax(p).x) * 0.5f;
+ auto flip = [&](glm::vec2& q) { q.x = 2.0f * cx - q.x; };
+ for (glm::vec2& q : p.points) flip(q);
+ for (EdgeCurve& c : p.curves) {
+ flip(c.c1);
+ flip(c.c2);
+ }
+ p.grainDegrees = 180.0f - p.grainDegrees;
+ reverseInPlace(p, &pat.seams, i);
+}
+
+uint32_t duplicatePanel(Pattern& pat, uint32_t i, glm::vec2 offset, const std::string& name) {
+ if (i >= pat.panels.size()) return 0;
+ Panel p = pat.panels[i];
+ for (glm::vec2& q : p.points) q += offset;
+ for (EdgeCurve& c : p.curves) {
+ c.c1 += offset;
+ c.c2 += offset;
+ }
+ p.name = name.empty() ? p.name + " 2" : name;
+ pat.panels.push_back(std::move(p));
+ return uint32_t(pat.panels.size() - 1);
+}
+
+uint32_t mirroredCopy(Pattern& pat, uint32_t i, const std::string& name) {
+ if (i >= pat.panels.size()) return 0;
+ const float w = panelMax(pat.panels[i]).x - panelMin(pat.panels[i]).x;
+ const uint32_t j = duplicatePanel(pat, i, {w + 40.0f, 0.0f}, name);
+ // Mirror the copy only (it has no seams yet, so the pattern's seams are untouched).
+ Pattern one;
+ one.panels.push_back(pat.panels[j]);
+ mirrorPanel(one, 0);
+ pat.panels[j] = std::move(one.panels[0]);
+ pat.panels[j].place.slot = mirroredSlot(pat.panels[j].place.slot);
+ pat.panels[j].place.offset.x = -pat.panels[j].place.offset.x;
+ return j;
+}
+
+bool unfoldPanel(Pattern& pat, uint32_t i, uint32_t e, std::string& error) {
+ if (i >= pat.panels.size() || e >= count(pat.panels[i])) {
+ error = "No such edge";
+ return false;
+ }
+ Panel& p = pat.panels[i];
+ if (curveOf(p, e).curved) {
+ error = "The fold line must be a straight edge";
+ return false;
+ }
+ const uint32_t n = count(p);
+ const glm::vec2 a = startOf(p, e), b = endOf(p, e);
+ const glm::vec2 dir = glm::normalize(b - a);
+ auto reflect = [&](glm::vec2 q) {
+ const glm::vec2 r = q - a;
+ return a + 2.0f * glm::dot(r, dir) * dir - r;
+ };
+ // Old edges e+1 .. e-1 (in order) then their mirror images in reverse.
+ Panel out = p;
+ out.points.clear();
+ out.curves.clear();
+ out.notches.clear();
+ std::vector<uint32_t> order;
+ for (uint32_t k = 1; k < n; ++k) order.push_back((e + k) % n);
+ for (uint32_t j : order) {
+ out.points.push_back(startOf(p, j));
+ out.curves.push_back(curveOf(p, j));
+ }
+ for (auto it = order.rbegin(); it != order.rend(); ++it) {
+ const EdgeCurve& c = curveOf(p, *it);
+ out.points.push_back(reflect(endOf(p, *it)));
+ out.curves.push_back({c.curved, reflect(c.c2), reflect(c.c1)});
+ }
+ const uint32_t m = n - 1; // edges in each half
+ for (const Notch& nt : p.notches) {
+ if (nt.edge == e) continue;
+ const uint32_t k = (nt.edge + n - e - 1) % n;
+ out.notches.push_back({k, nt.t});
+ out.notches.push_back({2 * m - 1 - k, 1.0f - nt.t});
+ }
+ // Seams: the fold edge's go, the others follow their edge.
+ pat.seams.erase(std::remove_if(pat.seams.begin(), pat.seams.end(),
+ [&](const Seam& s) {
+ return (s.a.panel == i && s.a.edge == e) || (s.b.panel == i && s.b.edge == e);
+ }),
+ pat.seams.end());
+ for (Seam& s : pat.seams)
+ for (SeamSide* side : {&s.a, &s.b})
+ if (side->panel == i) side->edge = (side->edge + n - e - 1) % n;
+ p = std::move(out);
+ normalizePanel(p);
+ return true;
+}
+
+void removePanel(Pattern& pat, uint32_t i) {
+ if (i >= pat.panels.size()) return;
+ pat.panels.erase(pat.panels.begin() + i);
+ fixPanels(pat.seams, i);
+}
+
+void splitEdge(Pattern& pat, uint32_t i, uint32_t e, float t) {
+ if (i >= pat.panels.size() || e >= count(pat.panels[i]) || !(t > 0.001f && t < 0.999f)) return;
+ Panel& p = pat.panels[i];
+ p.curves.resize(p.points.size());
+ const EdgeCurve c = curveOf(p, e);
+ const glm::vec2 a = startOf(p, e), b = endOf(p, e);
+ glm::vec2 mid;
+ EdgeCurve first, second;
+ if (c.curved) {
+ const float u = paramAt(sampleEdge(p, e, fineCount(p, e)), t);
+ // de Casteljau at u
+ const glm::vec2 p01 = glm::mix(a, c.c1, u), p12 = glm::mix(c.c1, c.c2, u), p23 = glm::mix(c.c2, b, u);
+ const glm::vec2 q0 = glm::mix(p01, p12, u), q1 = glm::mix(p12, p23, u);
+ mid = glm::mix(q0, q1, u);
+ first = {true, p01, q0};
+ second = {true, q1, p23};
+ } else {
+ mid = glm::mix(a, b, t);
+ }
+ p.points.insert(p.points.begin() + e + 1, mid);
+ p.curves[e] = first;
+ p.curves.insert(p.curves.begin() + e + 1, second);
+ for (Notch& nt : p.notches) {
+ if (nt.edge > e) ++nt.edge;
+ else if (nt.edge == e) {
+ if (nt.t < t) nt.t /= t;
+ else {
+ nt.t = (nt.t - t) / (1.0f - t);
+ ++nt.edge;
+ }
+ }
+ }
+ std::vector<Seam> kept;
+ for (Seam s : pat.seams) {
+ bool keep = true;
+ for (SeamSide* side : {&s.a, &s.b}) {
+ if (side->panel != i) continue;
+ if (side->edge > e) ++side->edge;
+ else if (side->edge == e) {
+ if (side->t1 <= t + 1e-4f) {
+ side->t0 /= t;
+ side->t1 = std::min(1.0f, side->t1 / t);
+ } else if (side->t0 >= t - 1e-4f) {
+ side->t0 = std::max(0.0f, (side->t0 - t) / (1.0f - t));
+ side->t1 = (side->t1 - t) / (1.0f - t);
+ ++side->edge;
+ } else {
+ keep = false; // a seam across the new point: sew the two edges again
+ }
+ }
+ }
+ if (keep) kept.push_back(s);
+ }
+ pat.seams = std::move(kept);
+}
+
+bool removePoint(Pattern& pat, uint32_t i, uint32_t k) {
+ if (i >= pat.panels.size()) return false;
+ Panel& p = pat.panels[i];
+ const uint32_t n = count(p);
+ if (n <= 3 || k >= n) return false;
+ p.curves.resize(n);
+ const uint32_t before = (k + n - 1) % n; // edge ending at k: becomes the merged straight edge
+ auto gone = [&](const SeamSide& s) { return s.panel == i && (s.edge == before || s.edge == k); };
+ pat.seams.erase(std::remove_if(pat.seams.begin(), pat.seams.end(),
+ [&](const Seam& s) { return gone(s.a) || gone(s.b); }),
+ pat.seams.end());
+ p.notches.erase(std::remove_if(p.notches.begin(), p.notches.end(),
+ [&](const Notch& nt) { return nt.edge == before || nt.edge == k; }),
+ p.notches.end());
+ p.curves[before] = {};
+ p.points.erase(p.points.begin() + k);
+ p.curves.erase(p.curves.begin() + k);
+ auto shift = [&](uint32_t& edge) {
+ if (k == 0) {
+ if (edge > 0) --edge; // edge n-1 (now n-2) is the merged one
+ } else if (edge > k) {
+ --edge;
+ }
+ };
+ for (Notch& nt : p.notches) shift(nt.edge);
+ for (Seam& s : pat.seams)
+ for (SeamSide* side : {&s.a, &s.b})
+ if (side->panel == i) shift(side->edge);
+ return true;
+}
+
+// ---------------------------------------------------------------------------
+// Seams
+// ---------------------------------------------------------------------------
+
+float seamSideLength(const Pattern& pat, const SeamSide& s) {
+ if (s.panel >= pat.panels.size()) return 0.0f;
+ return edgeLength(pat.panels[s.panel], s.edge) * std::max(0.0f, s.t1 - s.t0);
+}
+
+std::string edgeName(const Pattern& pat, uint32_t panel, uint32_t edge) {
+ if (panel >= pat.panels.size()) return "?";
+ return pat.panels[panel].name + " " + std::to_string(edge + 1);
+}
+
+bool addSeam(Pattern& pat, const Seam& seam, std::string& error) {
+ for (const SeamSide* s : {&seam.a, &seam.b}) {
+ if (s->panel >= pat.panels.size() || s->edge >= count(pat.panels[s->panel])) {
+ error = "The seam's edge is not in the pattern";
+ return false;
+ }
+ if (!(s->t0 >= 0.0f && s->t1 <= 1.0f && s->t1 - s->t0 > 0.001f)) {
+ error = "The seam's range along " + edgeName(pat, s->panel, s->edge) + " is empty";
+ return false;
+ }
+ for (const Seam& o : pat.seams)
+ if (overlaps(*s, o.a) || overlaps(*s, o.b)) {
+ error = edgeName(pat, s->panel, s->edge) + " is already sewn there";
+ return false;
+ }
+ }
+ if (overlaps(seam.a, seam.b)) {
+ error = "A seam can't sew an edge to itself";
+ return false;
+ }
+ pat.seams.push_back(seam);
+ return true;
+}
+
+SeamCheck checkSeam(const Pattern& pat, const Seam& seam) {
+ SeamCheck c;
+ c.lengthA = seamSideLength(pat, seam.a);
+ c.lengthB = seamSideLength(pat, seam.b);
+ const float diff = std::abs(c.lengthA - c.lengthB);
+ c.lengthsMatch = diff <= std::max(3.0f, 0.02f * std::max(c.lengthA, c.lengthB));
+ c.twisted = seam.flipped;
+ char buf[160];
+ std::snprintf(buf, sizeof buf, "%s <-> %s: %.0f / %.0f mm", edgeName(pat, seam.a.panel, seam.a.edge).c_str(),
+ edgeName(pat, seam.b.panel, seam.b.edge).c_str(), double(c.lengthA), double(c.lengthB));
+ c.text = buf;
+ if (!c.lengthsMatch) c.text += " (eased in)";
+ if (c.twisted) c.text += " (twisted)";
+ return c;
+}
+
+std::vector<std::string> patternProblems(const Pattern& pat) {
+ std::vector<std::string> out;
+ std::string error;
+ for (const Panel& p : pat.panels)
+ if (!validPanel(p, error)) out.push_back(error);
+ for (size_t i = 0; i < pat.seams.size(); ++i) {
+ const Seam& s = pat.seams[i];
+ if (s.a.panel >= pat.panels.size() || s.b.panel >= pat.panels.size()) {
+ out.push_back("Seam " + std::to_string(i + 1) + " sews a panel that is gone");
+ continue;
+ }
+ const SeamCheck c = checkSeam(pat, s);
+ if (c.twisted) out.push_back(c.text + ": the fabric turns over along it (Flip the seam)");
+ else if (!c.lengthsMatch) out.push_back(c.text + ": the sides differ in length");
+ for (size_t j = i + 1; j < pat.seams.size(); ++j)
+ for (const SeamSide* x : {&s.a, &s.b})
+ for (const SeamSide* y : {&pat.seams[j].a, &pat.seams[j].b})
+ if (overlaps(*x, *y)) out.push_back(edgeName(pat, x->panel, x->edge) + " is sewn twice");
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Arrangement
+// ---------------------------------------------------------------------------
+
+BodyFrame defaultBody() {
+ BodyFrame b;
+ b.bounds.min = {-0.85f, 0.0f, -0.13f};
+ b.bounds.max = {0.85f, 1.75f, 0.13f};
+ b.shoulderY = 1.45f;
+ b.torsoHalfWidth = 0.17f;
+ b.torsoFrontZ = 0.11f;
+ b.torsoBackZ = -0.11f;
+ b.arms = true;
+ b.leftShoulder = {0.17f, 1.40f, 0.0f};
+ b.rightShoulder = {-0.17f, 1.40f, 0.0f};
+ b.armRadius = 0.05f;
+ return b;
+}
+
+BodyFrame analyzeBody(const Mesh& body) {
+ BodyFrame f;
+ if (body.positions.empty()) return defaultBody();
+ for (const glm::vec3& p : body.positions) f.bounds.expand(p);
+ const float h = f.bounds.extent().y;
+ const float y0 = f.bounds.min.y;
+ f.centerX = f.bounds.center().x;
+ f.centerZ = f.bounds.center().z;
+ if (!(h > 1e-6f)) return defaultBody();
+ // Torso width: x coverage of the chest band by triangles (not vertices: a coarse mesh has gaps between
+ // them), from the middle out to the first empty gap (arms held away).
+ const float binW = h / 175.0f; // 1 cm on a 1.75 m figure
+ const int bins = 400;
+ std::vector<int> occ(bins, 0);
+ const float bandLo = y0 + 0.58f * h, bandHi = y0 + 0.70f * h;
+ auto cover = [&](float xa, float xb) {
+ // Both sides of the middle fold onto |x - centre|.
+ const float lo = xa - f.centerX, hi = xb - f.centerX;
+ const float a = (lo <= 0.0f && hi >= 0.0f) ? 0.0f : std::min(std::abs(lo), std::abs(hi));
+ const float b = std::max(std::abs(lo), std::abs(hi));
+ for (int k = int(a / binW); k <= int(b / binW) && k < bins; ++k) ++occ[size_t(k)];
+ };
+ for (const glm::uvec3& t : body.triangles) {
+ if (t.x >= body.positions.size() || t.y >= body.positions.size() || t.z >= body.positions.size()) continue;
+ const glm::vec3 a = body.positions[t.x], b = body.positions[t.y], c = body.positions[t.z];
+ const float ylo = std::min({a.y, b.y, c.y}), yhi = std::max({a.y, b.y, c.y});
+ if (yhi < bandLo || ylo > bandHi) continue;
+ const float xlo = std::min({a.x, b.x, c.x}), xhi = std::max({a.x, b.x, c.x});
+ if (xlo < f.centerX && xhi > f.centerX) {
+ cover(xlo, f.centerX);
+ cover(f.centerX, xhi);
+ } else {
+ cover(xlo, xhi);
+ }
+ }
+ if (body.triangles.empty())
+ for (const glm::vec3& p : body.positions)
+ if (p.y >= bandLo && p.y <= bandHi) cover(p.x, p.x);
+ int edge = 0;
+ for (int k = 0; k < bins; ++k) {
+ if (occ[size_t(k)]) edge = k;
+ else if (edge > 0 || k > 2) break;
+ }
+ f.torsoHalfWidth = std::max(binW, (float(edge) + 1.0f) * binW);
+ // Depth: the front and back of the chest band near the middle.
+ float front = f.centerZ, back = f.centerZ;
+ bool any = false;
+ for (const glm::vec3& p : body.positions)
+ if (p.y >= bandLo && p.y <= bandHi && std::abs(p.x - f.centerX) < 0.5f * f.torsoHalfWidth) {
+ front = any ? std::max(front, p.z) : p.z;
+ back = any ? std::min(back, p.z) : p.z;
+ any = true;
+ }
+ f.torsoFrontZ = front;
+ f.torsoBackZ = back;
+ if (any) f.centerZ = 0.5f * (front + back);
+ // Shoulders: the highest point over the outer half of the torso's width (the neck and head are narrower,
+ // arms held out are further out), below the top of the head.
+ f.shoulderY = y0 + 0.83f * h;
+ float top = -std::numeric_limits<float>::max();
+ for (const glm::vec3& p : body.positions) {
+ const float dx = std::abs(p.x - f.centerX);
+ if (dx >= 0.5f * f.torsoHalfWidth && dx <= f.torsoHalfWidth && p.y > bandLo && p.y < y0 + 0.95f * h) top = std::max(top, p.y);
+ }
+ if (top > bandLo) f.shoulderY = top;
+ // Arms: vertices well outside the torso above the waist, one slab near the shoulder and one further out.
+ f.armRadius = 0.03f * h;
+ for (int side = 0; side < 2; ++side) {
+ const float s = side == 0 ? 1.0f : -1.0f;
+ const float x1 = 1.4f * f.torsoHalfWidth, x2 = x1 + 0.15f * h, slab = 0.08f * h;
+ glm::dvec3 m1(0.0), m2(0.0);
+ size_t n1 = 0, n2 = 0;
+ for (const glm::vec3& p : body.positions) {
+ if (p.y < y0 + 0.5f * h) continue;
+ const float dx = s * (p.x - f.centerX);
+ if (dx >= x1 && dx < x1 + slab) {
+ m1 += glm::dvec3(p);
+ ++n1;
+ } else if (dx >= x2 && dx < x2 + slab) {
+ m2 += glm::dvec3(p);
+ ++n2;
+ }
+ }
+ if (n1 < 8) continue;
+ const glm::vec3 p1 = glm::vec3(m1 / double(n1));
+ glm::vec3 dir(s, 0.0f, 0.0f);
+ if (n2 >= 8) dir = glm::normalize(glm::vec3(m2 / double(n2)) - p1);
+ if (dir.x * s < 0.3f) continue; // not an arm held out
+ // Radius: the mean distance of the near slab's vertices from the arm's line.
+ double r = 0.0;
+ for (const glm::vec3& p : body.positions) {
+ if (p.y < y0 + 0.5f * h) continue;
+ const float dx = s * (p.x - f.centerX);
+ if (dx >= x1 && dx < x1 + slab) {
+ const glm::vec3 d = p - p1;
+ r += double(glm::length(d - glm::dot(d, dir) * dir));
+ }
+ }
+ const float radius = float(r / double(n1));
+ // The shoulder: back along the arm to the torso's side.
+ const float back = (s * (p1.x - f.centerX) - f.torsoHalfWidth) / std::max(0.3f, std::abs(dir.x));
+ const glm::vec3 shoulder = p1 - dir * back;
+ f.arms = true;
+ f.armRadius = side == 0 ? radius : 0.5f * (f.armRadius + radius);
+ (side == 0 ? f.leftShoulder : f.rightShoulder) = shoulder;
+ (side == 0 ? f.leftArmDir : f.rightArmDir) = dir;
+ }
+ if (!f.arms) { // arms down or none: sleeves start at the shoulders, pointing out and down
+ f.leftShoulder = {f.centerX + f.torsoHalfWidth, f.shoulderY - 0.03f * h, f.centerZ};
+ f.rightShoulder = {f.centerX - f.torsoHalfWidth, f.shoulderY - 0.03f * h, f.centerZ};
+ f.leftArmDir = glm::normalize(glm::vec3(0.3f, -1.0f, 0.0f));
+ f.rightArmDir = glm::normalize(glm::vec3(-0.3f, -1.0f, 0.0f));
+ }
+ return f;
+}
+
+void autoSlots(Pattern& pat) {
+ auto has = [](std::string s, const char* w) {
+ std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+ return s.find(w) != std::string::npos;
+ };
+ int sleeves = 0;
+ for (Panel& p : pat.panels) {
+ if (p.place.slot != Slot::Front) continue; // chosen already
+ if (has(p.name, "back")) p.place.slot = Slot::Back;
+ else if (has(p.name, "sleeve") || has(p.name, "arm")) {
+ const bool right = has(p.name, "right") || (!has(p.name, "left") && sleeves % 2 == 1);
+ p.place.slot = right ? Slot::RightArm : Slot::LeftArm;
+ ++sleeves;
+ } else if (has(p.name, "side")) {
+ p.place.slot = has(p.name, "right") ? Slot::Right : Slot::Left;
+ }
+ }
+}
+
+namespace {
+
+// Arc length of an ellipse quarter from angle 0, tabulated, so a panel's x (arc length) maps to an angle.
+struct EllipseArc {
+ float a, b; // semi-axes along S and R0
+ std::vector<float> len; // at angles i / N * pi
+ static constexpr int N = 128;
+ EllipseArc(float aa, float bb) : a(aa), b(bb), len(N + 1) {
+ float l = 0.0f;
+ glm::vec2 prev(0.0f, b);
+ for (int i = 0; i <= N; ++i) {
+ const float th = float(i) / float(N) * kPi;
+ const glm::vec2 q(a * std::sin(th), b * std::cos(th));
+ if (i) l += glm::length(q - prev);
+ prev = q;
+ len[size_t(i)] = l;
+ }
+ }
+ // (along S, along R0) at arc length x from the front point (x < 0 goes the other way; past half: straight on).
+ glm::vec2 at(float x) const {
+ const float s = x < 0 ? -1.0f : 1.0f;
+ const float want = std::abs(x);
+ if (want >= len.back()) return {s * 0.0f, -b - (want - len.back())}; // (never this far in practice)
+ const auto it = std::lower_bound(len.begin(), len.end(), want);
+ const size_t i = size_t(std::max<ptrdiff_t>(1, it - len.begin()));
+ const float f = len[i] > len[i - 1] ? (want - len[i - 1]) / (len[i] - len[i - 1]) : 0.0f;
+ const float th = (float(i - 1) + f) / float(N) * kPi;
+ return {s * a * std::sin(th), b * std::cos(th)};
+ }
+};
+
+struct SlotFrame {
+ glm::vec3 c, axis, out, side; // panel top centre on the axis; +y of the panel; facing; +x of the panel
+ float across = 0.1f, depth = 0.1f; // ellipse semi-axes (side, out)
+};
+
+SlotFrame slotFrame(const Panel& p, const BodyFrame& b, float gap) {
+ SlotFrame f;
+ const glm::vec3 up(0.0f, 1.0f, 0.0f);
+ const float frontD = std::max(0.02f, b.torsoFrontZ - b.centerZ), backD = std::max(0.02f, b.centerZ - b.torsoBackZ);
+ const glm::vec3 torso(b.centerX, b.shoulderY, b.centerZ);
+ switch (p.place.slot) {
+ case Slot::Front: f = {torso, up, {0, 0, 1}, {}, b.torsoHalfWidth, frontD}; break;
+ case Slot::Back: f = {torso, up, {0, 0, -1}, {}, b.torsoHalfWidth, backD}; break;
+ case Slot::Left: f = {torso, up, {1, 0, 0}, {}, std::max(frontD, backD), b.torsoHalfWidth}; break;
+ case Slot::Right: f = {torso, up, {-1, 0, 0}, {}, std::max(frontD, backD), b.torsoHalfWidth}; break;
+ case Slot::LeftArm:
+ case Slot::RightArm: {
+ const bool left = p.place.slot == Slot::LeftArm;
+ const glm::vec3 dir = glm::normalize(left ? b.leftArmDir : b.rightArmDir);
+ f.c = left ? b.leftShoulder : b.rightShoulder;
+ f.axis = -dir; // the sleeve's top (cap) points back to the shoulder
+ glm::vec3 o = up - glm::dot(up, f.axis) * f.axis;
+ if (glm::length(o) < 1e-3f) o = glm::vec3(0, 0, 1) - glm::dot(glm::vec3(0, 0, 1), f.axis) * f.axis;
+ f.out = glm::normalize(o);
+ f.across = f.depth = b.armRadius;
+ break;
+ }
+ default: f = {torso + glm::vec3(0, 0, b.torsoFrontZ - b.centerZ + 0.25f), up, {0, 0, 1}, {}, 0, 0}; break;
+ }
+ f.side = glm::cross(f.axis, f.out); // so that (side x axis) faces out: counter-clockwise panels face away
+ f.across += gap + p.place.offset.z;
+ f.depth += gap + p.place.offset.z;
+ return f;
+}
+
+} // namespace
+
+glm::vec3 placePoint(const Panel& p, glm::vec2 flat, const BodyFrame& body, float gap) {
+ const glm::vec2 lo = panelMin(p), hi = panelMax(p);
+ const float x = (flat.x - 0.5f * (lo.x + hi.x)) * 0.001f + p.place.offset.x;
+ const float y = (flat.y - hi.y) * 0.001f + p.place.offset.y;
+ const SlotFrame f = slotFrame(p, body, gap);
+ if (!p.place.wrap || p.place.slot == Slot::Free) return f.c + f.axis * y + f.out * f.depth + f.side * x;
+ const EllipseArc arc(f.across, f.depth);
+ const glm::vec2 q = arc.at(x);
+ return f.c + f.axis * y + f.side * q.x + f.out * q.y;
+}
+
+void placePattern(const Pattern& pat, const GarmentMesh& m, const BodyFrame& body, std::vector<glm::vec3>& placed,
+ std::vector<glm::vec3>& rest, float gap) {
+ placed.resize(m.flat.size());
+ rest.resize(m.flat.size());
+ // One frame and arc table per panel (placePoint would rebuild them per vertex).
+ for (size_t pi = 0; pi + 1 < m.panelFirstVertex.size() && pi < pat.panels.size(); ++pi) {
+ const Panel& p = pat.panels[pi];
+ const glm::vec2 lo = panelMin(p), hi = panelMax(p);
+ const SlotFrame f = slotFrame(p, body, gap);
+ const EllipseArc arc(f.across, f.depth);
+ const bool wrap = p.place.wrap && p.place.slot != Slot::Free;
+ for (uint32_t v = m.panelFirstVertex[pi]; v < m.panelFirstVertex[pi + 1]; ++v) {
+ const glm::vec2 q = m.flat[v];
+ const float x = (q.x - 0.5f * (lo.x + hi.x)) * 0.001f + p.place.offset.x;
+ const float y = (q.y - hi.y) * 0.001f + p.place.offset.y;
+ if (wrap) {
+ const glm::vec2 e = arc.at(x);
+ placed[v] = f.c + f.axis * y + f.side * e.x + f.out * e.y;
+ } else {
+ placed[v] = f.c + f.axis * y + f.out * f.depth + f.side * x;
+ }
+ rest[v] = glm::vec3(q * 0.001f, 0.0f);
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// The Part
+// ---------------------------------------------------------------------------
+
+Mesh garmentToMesh(const GarmentMesh& gm, const std::vector<glm::vec3>& positions, float thicknessMm) {
+ Mesh out;
+ const size_t n = gm.flat.size();
+ if (positions.size() != n || gm.triangles.empty()) return out;
+ // Weld the seams: union-find over the links, the smallest index represents its set.
+ std::vector<uint32_t> parent(n);
+ std::iota(parent.begin(), parent.end(), 0u);
+ auto find = [&](uint32_t v) {
+ while (parent[v] != v) v = parent[v] = parent[parent[v]];
+ return v;
+ };
+ for (const SeamLink& l : gm.links) {
+ if (l.a >= n || l.b >= n) continue;
+ const uint32_t a = find(l.a), b = find(l.b);
+ if (a != b) parent[std::max(a, b)] = std::min(a, b);
+ }
+ std::vector<uint32_t> remap(n, ~0u);
+ std::vector<glm::dvec3> sum;
+ std::vector<int> cnt;
+ for (uint32_t v = 0; v < n; ++v) {
+ const uint32_t r = find(v);
+ if (remap[r] == ~0u) {
+ remap[r] = uint32_t(sum.size());
+ sum.emplace_back(0.0);
+ cnt.push_back(0);
+ }
+ remap[v] = remap[r];
+ sum[remap[v]] += glm::dvec3(positions[v]);
+ ++cnt[remap[v]];
+ }
+ out.positions.resize(sum.size());
+ for (size_t i = 0; i < sum.size(); ++i) out.positions[i] = glm::vec3(sum[i] / double(cnt[i]));
+ // UVs: the whole sheet in 0..1 (the longer side), so texel density is the same on every panel.
+ glm::vec2 lo(std::numeric_limits<float>::max()), hi(std::numeric_limits<float>::lowest());
+ for (glm::vec2 q : gm.flat) {
+ lo = glm::min(lo, q);
+ hi = glm::max(hi, q);
+ }
+ const float span = std::max(1e-3f, std::max(hi.x - lo.x, hi.y - lo.y)) * 1.02f;
+ const glm::vec2 base = lo - glm::vec2(0.01f * span);
+ for (size_t t = 0; t < gm.triangles.size(); ++t) {
+ const glm::uvec3 tri = gm.triangles[t];
+ const glm::uvec3 w(remap[tri.x], remap[tri.y], remap[tri.z]);
+ if (w.x == w.y || w.y == w.z || w.x == w.z) continue;
+ out.triangles.push_back(w);
+ for (int k = 0; k < 3; ++k) out.uvs.push_back((gm.flat[tri[k]] - base) / span);
+ out.facegroups.push_back(gm.panelOf[tri.x] + 1);
+ }
+ out.rebuildTopology();
+ out.recomputeAllNormals();
+ const float t = thicknessMm * 0.001f;
+ if (!(t > 0.0f)) return out;
+ // Thicken outward (the inner side stays where the simulation left it, off the body): the outer surface is the
+ // inner one moved along its normals; the inner one is wound the other way; a rim of quads joins their borders.
+ const size_t nv = out.positions.size(), nt = out.triangles.size();
+ Mesh s;
+ s.positions.resize(2 * nv);
+ for (size_t v = 0; v < nv; ++v) {
+ s.positions[v] = out.positions[v] + out.normals[v] * t;
+ s.positions[nv + v] = out.positions[v];
+ }
+ s.triangles = out.triangles;
+ s.uvs = out.uvs;
+ s.facegroups = out.facegroups;
+ for (size_t i = 0; i < nt; ++i) {
+ const glm::uvec3 tri = out.triangles[i];
+ s.triangles.push_back(glm::uvec3(tri.x, tri.z, tri.y) + glm::uvec3(uint32_t(nv)));
+ s.uvs.push_back(out.uvs[3 * i]);
+ s.uvs.push_back(out.uvs[3 * i + 2]);
+ s.uvs.push_back(out.uvs[3 * i + 1]);
+ s.facegroups.push_back(0x8000u + out.facegroups[i]);
+ }
+ // Border edges: used by one triangle, in that triangle's direction.
+ std::vector<std::pair<uint64_t, size_t>> edges; // (key, triangle * 3 + corner)
+ edges.reserve(nt * 3);
+ for (size_t i = 0; i < nt; ++i)
+ for (int k = 0; k < 3; ++k) {
+ const uint32_t a = out.triangles[i][k], b = out.triangles[i][(k + 1) % 3];
+ edges.push_back({uint64_t(std::min(a, b)) << 32 | std::max(a, b), i * 3 + size_t(k)});
+ }
+ std::sort(edges.begin(), edges.end());
+ for (size_t i = 0; i < edges.size();) {
+ size_t j = i;
+ while (j < edges.size() && edges[j].first == edges[i].first) ++j;
+ if (j - i == 1) {
+ const size_t tri = edges[i].second / 3;
+ const int k = int(edges[i].second % 3);
+ const uint32_t a = out.triangles[tri][k], b = out.triangles[tri][(k + 1) % 3];
+ const glm::vec2 ua = out.uvs[3 * tri + size_t(k)], ub = out.uvs[3 * tri + size_t((k + 1) % 3)];
+ const uint32_t fg = 0x8000u + out.facegroups[tri];
+ // Outer a->b is wound one way: the rim quad (b, a, a', b') faces out of the border.
+ const uint32_t ia = a + uint32_t(nv), ib = b + uint32_t(nv);
+ s.triangles.push_back({b, a, ia});
+ s.triangles.push_back({b, ia, ib});
+ for (glm::vec2 uv : {ub, ua, ua, ub, ua, ub}) s.uvs.push_back(uv);
+ s.facegroups.push_back(fg);
+ s.facegroups.push_back(fg);
+ }
+ i = j;
+ }
+ s.rebuildTopology();
+ s.recomputeAllNormals();
+ return s;
+}
+
+// ---------------------------------------------------------------------------
+// Templates
+// ---------------------------------------------------------------------------
+
+Panel rectanglePanel(const std::string& name, float w, float h, glm::vec2 at) {
+ Panel p;
+ p.name = name;
+ p.points = {at, at + glm::vec2(w, 0), at + glm::vec2(w, h), at + glm::vec2(0, h)};
+ p.curves.resize(4);
+ return p;
+}
+
+namespace {
+
+// A body panel (front or back) centred on x = cx, hem at y = 0: hem, side, armhole, shoulder, neckline, shoulder,
+// armhole, side (edges 0-7).
+Panel bodyPanel(const std::string& name, float cx, float half, float length, float neckDepth) {
+ const float shoulderHalf = half - 30.0f, neckHalf = 85.0f, drop = 45.0f, armholeY = length - 270.0f;
+ Panel p;
+ p.name = name;
+ auto P = [&](float x, float y) { return glm::vec2(cx + x, y); };
+ p.points = {P(-half, 0), P(half, 0), P(half, armholeY), P(shoulderHalf, length - drop),
+ P(neckHalf, length), P(-neckHalf, length), P(-shoulderHalf, length - drop), P(-half, armholeY)};
+ p.curves.resize(8);
+ const float in = half - 45.0f;
+ p.curves[2] = {true, P(in, armholeY), P(in, armholeY + 130.0f)};
+ p.curves[6] = {true, P(-in, armholeY + 130.0f), P(-in, armholeY)};
+ const float cy = length - 8.0f * neckDepth / 6.0f;
+ p.curves[4] = {true, P(neckHalf - 5.0f, cy), P(-neckHalf + 5.0f, cy)};
+ p.notches = {{1, 0.5f}, {7, 0.5f}};
+ return p;
+}
+
+// A short sleeve centred on x = cx: hem (0), underarm (1), cap (2, from the +x underarm over the top), underarm (3).
+Panel sleevePanel(const std::string& name, float cx, float capLength) {
+ const float half = 190.0f, hemHalf = 170.0f, underarmY = 200.0f;
+ Panel p;
+ p.name = name;
+ p.points = {{cx - hemHalf, 0}, {cx + hemHalf, 0}, {cx + half, underarmY}, {cx - half, underarmY}};
+ p.curves.resize(4);
+ // Cap height chosen so the cap is `capLength` long (bisection on the control points' height).
+ float lo = 0.0f, hi = 400.0f;
+ for (int it = 0; it < 40; ++it) {
+ const float m = 0.5f * (lo + hi);
+ p.curves[2] = {true, {cx + 0.55f * half, underarmY + m}, {cx - 0.55f * half, underarmY + m}};
+ (edgeLength(p, 2) < capLength ? lo : hi) = m;
+ }
+ p.notches = {{2, 0.5f}};
+ return p;
+}
+
+} // namespace
+
+Pattern tshirtPattern(float chestMm, float lengthMm) {
+ Pattern pat;
+ const float half = std::clamp((chestMm + 80.0f) * 0.25f, 120.0f, 1000.0f); // 8 cm ease
+ const float length = std::clamp(lengthMm, 300.0f, 1500.0f);
+ pat.panels.push_back(bodyPanel("Front", 0.0f, half, length, 90.0f));
+ pat.panels.push_back(bodyPanel("Back", 2.0f * half + 60.0f, half, length, 20.0f));
+ pat.panels[1].place.slot = Slot::Back;
+ // Each armhole (front + back) is the cap's length, plus 2% ease.
+ const float armhole = edgeLength(pat.panels[0], 2) + edgeLength(pat.panels[1], 6);
+ const float sx = 3.0f * half + 120.0f + 190.0f; // 60 mm right of the back
+ pat.panels.push_back(sleevePanel("Left sleeve", sx, armhole * 1.02f));
+ pat.panels.push_back(sleevePanel("Right sleeve", sx + 440.0f, armhole * 1.02f));
+ pat.panels[2].place.slot = Slot::LeftArm;
+ pat.panels[3].place.slot = Slot::RightArm;
+ std::string error;
+ auto sew = [&](uint32_t pa, uint32_t ea, float a0, float a1, uint32_t pb, uint32_t eb, float b0, float b1) {
+ addSeam(pat, {{pa, ea, a0, a1}, {pb, eb, b0, b1}, false}, error);
+ };
+ // Sides and shoulders: front +x (the wearer's left) meets the back's -x edge.
+ sew(0, 1, 0, 1, 1, 7, 0, 1);
+ sew(0, 7, 0, 1, 1, 1, 0, 1);
+ sew(0, 3, 0, 1, 1, 5, 0, 1);
+ sew(0, 5, 0, 1, 1, 3, 0, 1);
+ // Left sleeve (on +X): its +x half of the cap faces back. Right sleeve: its +x half faces front.
+ sew(0, 2, 0, 1, 2, 2, 0.5f, 1);
+ sew(1, 6, 0, 1, 2, 2, 0, 0.5f);
+ sew(0, 6, 0, 1, 3, 2, 0, 0.5f);
+ sew(1, 2, 0, 1, 3, 2, 0.5f, 1);
+ // Underarm seams close each sleeve into a tube.
+ sew(2, 1, 0, 1, 2, 3, 0, 1);
+ sew(3, 1, 0, 1, 3, 3, 0, 1);
+ return pat;
+}
+
+// ---------------------------------------------------------------------------
+// JSON
+// ---------------------------------------------------------------------------
+
+namespace {
+
+Json num(float v) { return Json(double(std::round(double(v) * 1000.0) / 1000.0)); }
+float fnum(const Json& j, float fallback) {
+ const double d = j.asNumber(fallback);
+ return std::isfinite(d) && std::abs(d) < 1e7 ? float(d) : fallback;
+}
+Json sideJson(const SeamSide& s) {
+ Json j = Json::array();
+ j.push(int(s.panel));
+ j.push(int(s.edge));
+ j.push(num(s.t0));
+ j.push(num(s.t1));
+ return j;
+}
+bool sideFromJson(const Json& j, SeamSide& s) {
+ if (!j.isArray() || j.size() != 4) return false;
+ const double p = j[0].asNumber(-1), e = j[1].asNumber(-1);
+ if (!(p >= 0 && p < 1e6 && e >= 0 && e < 1e6)) return false;
+ s = {uint32_t(p), uint32_t(e), fnum(j[2], 0.0f), fnum(j[3], 1.0f)};
+ return true;
+}
+
+} // namespace
+
+Json patternToJson(const Pattern& pat) {
+ Json j = Json::object();
+ j.set("version", 1);
+ j.set("particle_mm", num(pat.particleDistance));
+ j.set("fabric", pat.fabric);
+ j.set("thickness_mm", num(pat.thickness));
+ Json panels = Json::array();
+ for (const Panel& p : pat.panels) {
+ Json pj = Json::object();
+ pj.set("name", p.name);
+ Json pts = Json::array();
+ for (glm::vec2 q : p.points) {
+ pts.push(num(q.x));
+ pts.push(num(q.y));
+ }
+ pj.set("points", std::move(pts));
+ Json curves = Json::array();
+ for (size_t e = 0; e < p.curves.size(); ++e) {
+ const EdgeCurve& c = p.curves[e];
+ if (!c.curved) continue;
+ Json cj = Json::array();
+ cj.push(int(e));
+ for (float v : {c.c1.x, c.c1.y, c.c2.x, c.c2.y}) cj.push(num(v));
+ curves.push(std::move(cj));
+ }
+ pj.set("curves", std::move(curves));
+ Json notches = Json::array();
+ for (const Notch& nt : p.notches) {
+ Json nj = Json::array();
+ nj.push(int(nt.edge));
+ nj.push(num(nt.t));
+ notches.push(std::move(nj));
+ }
+ pj.set("notches", std::move(notches));
+ pj.set("grain", num(p.grainDegrees));
+ pj.set("allowance_mm", num(p.seamAllowance));
+ pj.set("slot", slotId(p.place.slot));
+ Json off = Json::array();
+ for (int k = 0; k < 3; ++k) off.push(num(p.place.offset[k]));
+ pj.set("offset", std::move(off));
+ pj.set("wrap", p.place.wrap);
+ panels.push(std::move(pj));
+ }
+ j.set("panels", std::move(panels));
+ Json seams = Json::array();
+ for (const Seam& s : pat.seams) {
+ Json sj = Json::object();
+ sj.set("a", sideJson(s.a));
+ sj.set("b", sideJson(s.b));
+ if (s.flipped) sj.set("flipped", true);
+ seams.push(std::move(sj));
+ }
+ j.set("seams", std::move(seams));
+ return j;
+}
+
+bool patternFromJson(const Json& j, Pattern& out, std::string& error) {
+ if (!j.isObject() || !j["panels"].isArray()) {
+ error = "Not a garment pattern";
+ return false;
+ }
+ if (j["version"].asNumber(1) > 1) {
+ error = "The garment pattern was saved by a newer SculptForge";
+ return false;
+ }
+ Pattern pat;
+ pat.particleDistance = std::clamp(fnum(j["particle_mm"], 15.0f), 2.0f, 200.0f);
+ if (j["fabric"].isString()) pat.fabric = j["fabric"].asString().substr(0, 32);
+ pat.thickness = std::clamp(fnum(j["thickness_mm"], 2.0f), 0.0f, 100.0f);
+ std::vector<int> index; // old panel index -> new (-1: left out)
+ size_t totalPoints = 0;
+ for (const Json& pj : j["panels"].items()) {
+ index.push_back(-1);
+ if (pat.panels.size() >= 512) break;
+ Panel p;
+ if (pj["name"].isString()) p.name = pj["name"].asString().substr(0, 128);
+ const Json& pts = pj["points"];
+ if (!pts.isArray() || pts.size() % 2 || pts.size() < 6 || totalPoints + pts.size() / 2 > 20000) {
+ error += (error.empty() ? "" : "; ") + p.name + " left out (bad points)";
+ continue;
+ }
+ for (size_t k = 0; k + 1 < pts.size(); k += 2) p.points.push_back({fnum(pts[k], 0.0f), fnum(pts[k + 1], 0.0f)});
+ totalPoints += p.points.size();
+ p.curves.resize(p.points.size());
+ for (const Json& cj : pj["curves"].items()) {
+ if (!cj.isArray() || cj.size() != 5) continue;
+ const double e = cj[0].asNumber(-1);
+ if (!(e >= 0 && e < double(p.points.size()))) continue;
+ p.curves[size_t(e)] = {true, {fnum(cj[1], 0), fnum(cj[2], 0)}, {fnum(cj[3], 0), fnum(cj[4], 0)}};
+ }
+ for (const Json& nj : pj["notches"].items())
+ if (nj.isArray() && nj.size() == 2 && nj[0].asNumber(-1) >= 0 && nj[0].asNumber(-1) < 1e6)
+ p.notches.push_back({uint32_t(nj[0].asNumber(0)), fnum(nj[1], 0.5f)});
+ p.grainDegrees = fnum(pj["grain"], 90.0f);
+ p.seamAllowance = std::clamp(fnum(pj["allowance_mm"], 10.0f), 0.0f, 200.0f);
+ Slot s;
+ if (pj["slot"].isString() && slotFromId(pj["slot"].asString(), s)) p.place.slot = s;
+ if (pj["offset"].isArray() && pj["offset"].size() == 3)
+ for (int k = 0; k < 3; ++k) p.place.offset[k] = std::clamp(fnum(pj["offset"][size_t(k)], 0.0f), -10.0f, 10.0f);
+ p.place.wrap = pj["wrap"].asBool(true);
+ normalizePanel(p);
+ std::string why;
+ if (!validPanel(p, why)) {
+ error += (error.empty() ? "" : "; ") + why + " (left out)";
+ continue;
+ }
+ index.back() = int(pat.panels.size());
+ pat.panels.push_back(std::move(p));
+ }
+ for (const Json& sj : j["seams"].items()) {
+ Seam s;
+ if (!sideFromJson(sj["a"], s.a) || !sideFromJson(sj["b"], s.b)) continue;
+ if (s.a.panel >= index.size() || s.b.panel >= index.size() || index[s.a.panel] < 0 || index[s.b.panel] < 0)
+ continue;
+ s.a.panel = uint32_t(index[s.a.panel]);
+ s.b.panel = uint32_t(index[s.b.panel]);
+ s.flipped = sj["flipped"].asBool(false);
+ std::string why;
+ addSeam(pat, s, why); // (unusable seams are dropped)
+ }
+ out = std::move(pat);
+ return true;
+}
+
+bool documentPattern(const Document& doc, Pattern& out) {
+ if (!doc.projectSettings.isObject() || !doc.projectSettings.has("garment")) return false;
+ std::string error;
+ return patternFromJson(doc.projectSettings["garment"], out, error);
+}
+
+void setDocumentPattern(Document& doc, const Pattern& pat) {
+ if (!doc.projectSettings.isObject()) doc.projectSettings = Json::object();
+ if (pat.empty()) {
+ if (!doc.projectSettings.has("garment")) return;
+ Json copy = Json::object();
+ for (const auto& [k, v] : doc.projectSettings.members())
+ if (k != "garment") copy.set(k, v);
+ doc.projectSettings = std::move(copy);
+ } else {
+ doc.projectSettings.set("garment", patternToJson(pat));
+ }
+ doc.modified = true;
+}
+
+} // namespace sf::garment
diff --git a/src/core/Garment.h b/src/core/Garment.h
new file mode 100644
index 00000000..9c64aed3
--- /dev/null
+++ b/src/core/Garment.h
@@ -0,0 +1,248 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Garments (docs/design/cloth.md): clothing made the way it is sewn. Pattern panels are flat pieces of fabric drawn
+// at real size (millimetres); seams say which edges are sewn together; each panel is placed around the body; the
+// cloth solver (core/Cloth.h, Drape) pulls the seams closed and lets the garment settle; the result becomes a Part
+// whose UVs are the flat panel layout.
+//
+// - Panel: a closed outline of points, counter-clockwise as seen from the right side (outside) of the fabric.
+// Edge i runs from point i to point i + 1 (the last edge back to point 0), straight or a cubic curve. Notches
+// mark matching points for sewing, the grain line the fabric's warp direction, the seam allowance the margin
+// added around the outline when it is cut (export only: the simulation uses the outline, the sewing line).
+// - Seam: a range of one panel edge sewn to a range of another (or the same panel's). Positions along an edge are
+// fractions of its length (0 = its start point, 1 = its end). Sewn the right way the two ranges run in opposite
+// directions (as two neighbouring faces of a surface share an edge), so side a's start meets side b's end;
+// `flipped` sews start to start, which twists the fabric (seamReport warns).
+// - Triangulation (triangulatePattern): every panel becomes even, nearly equilateral triangles at the particle
+// distance (a lattice along the grain, a constrained Delaunay triangulation of it with the outline as
+// constraints, then smoothing); both sides of a seam get the same number of points, so the seam's particles pair
+// one to one and weld cleanly after the simulation.
+// - Arrangement (analyzeBody, placePattern): slots around the body (front, back, sides, arms) found from its
+// shape, each panel wrapped around the torso or an arm so the seams start close.
+//
+// The pattern is saved in the project (Document::projectSettings["garment"]); SVG export writes the panels at real
+// size (with seam allowance, notches, grain lines) for printing and sewing, DXF the outlines for cutters.
+#pragma once
+
+#include "core/Json.h"
+#include "core/Mesh.h"
+
+#include <glm/glm.hpp>
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+struct Document;
+class CommandRegistry;
+
+// garment_new, garment_info, garment_sew, garment_export, ... (core/GarmentCommands.cpp)
+void registerGarmentCommands(CommandRegistry& registry);
+
+namespace garment {
+
+// A panel edge's shape: straight, or a cubic Bezier from its start point through c1, c2 to its end point (mm).
+struct EdgeCurve {
+ bool curved = false;
+ glm::vec2 c1{0.0f}, c2{0.0f};
+};
+
+// A matching mark on an edge, `t` (0..1) along it.
+struct Notch {
+ uint32_t edge = 0;
+ float t = 0.5f;
+};
+
+// Where a panel goes around the body (placePattern).
+enum class Slot : uint8_t { Front, Back, Left, Right, LeftArm, RightArm, Free, Count };
+const char* slotId(Slot s); // "front", "back", "left", "right", "left_arm", "right_arm", "free"
+const char* slotLabel(Slot s); // "Front", ...
+bool slotFromId(const std::string& id, Slot& out);
+
+struct Placement {
+ Slot slot = Slot::Front;
+ // Metres in the slot's frame: x across the panel (around the body), y along it (+ up), z away from the body.
+ glm::vec3 offset{0.0f};
+ bool wrap = true; // bent around the torso or the arm (false: flat, facing out of the slot)
+};
+
+struct Panel {
+ std::string name = "Panel";
+ std::vector<glm::vec2> points; // mm, the sewing line, counter-clockwise from the right side
+ std::vector<EdgeCurve> curves; // one per edge (same count as points)
+ std::vector<Notch> notches;
+ float grainDegrees = 90.0f; // warp direction, degrees from +x (90 = up the panel)
+ float seamAllowance = 10.0f; // mm
+ Placement place;
+};
+
+struct SeamSide {
+ uint32_t panel = 0, edge = 0;
+ float t0 = 0.0f, t1 = 1.0f; // the sewn range along the edge, t0 < t1
+};
+
+struct Seam {
+ SeamSide a, b;
+ bool flipped = false; // a's start meets b's start (twists the fabric)
+};
+
+struct Pattern {
+ std::vector<Panel> panels;
+ std::vector<Seam> seams;
+ float particleDistance = 15.0f; // mm between neighbouring particles (triangle edge length)
+ std::string fabric = "cotton"; // a core/Cloth.h fabric preset id
+ float thickness = 2.0f; // mm, given to the Part made by Convert (0 = a single surface)
+ bool empty() const { return panels.empty(); }
+};
+
+// --- Panel geometry (all in mm) ---
+
+// Fixes up a panel: one curve per point, counter-clockwise outline (reversing points, curves and notches if not),
+// notches on real edges.
+void normalizePanel(Panel& p);
+// Edge `e` as a polyline from its start point to its end point (curves flattened to within `tolerance` mm).
+std::vector<glm::vec2> edgePolyline(const Panel& p, uint32_t e, float tolerance = 0.2f);
+float edgeLength(const Panel& p, uint32_t e);
+// The point `t` (0..1 of its length) along edge `e`, and the edge's direction there.
+glm::vec2 edgePoint(const Panel& p, uint32_t e, float t, glm::vec2* tangent = nullptr);
+// The whole outline as one closed polyline (no repeated first point).
+std::vector<glm::vec2> outline(const Panel& p, float tolerance = 0.2f);
+float panelArea(const Panel& p); // mm^2, > 0 when counter-clockwise
+float perimeter(const Panel& p);
+glm::vec2 panelMin(const Panel& p);
+glm::vec2 panelMax(const Panel& p);
+// False (with a reason) for fewer than 3 points, a zero-area or self-crossing outline, or edges shorter than 1 mm.
+bool validPanel(const Panel& p, std::string& error);
+// The outline grown outward by `distance` mm (the cutting line), as a closed polyline.
+std::vector<glm::vec2> offsetOutline(const Panel& p, float distance);
+
+// --- Pattern edits (each keeps seams pointing at the right panels and edges) ---
+
+// Flips a panel left to right about its own centre (still counter-clockwise; seams on it keep their edges).
+void mirrorPanel(Pattern& pat, uint32_t panel);
+// A copy of the panel `offsetMm` to the right, named "<name> 2" (or `name`); returns its index.
+uint32_t duplicatePanel(Pattern& pat, uint32_t panel, glm::vec2 offsetMm, const std::string& name = {});
+// A mirrored copy (the other sleeve, the other half): mirrored about its centre and moved beside it; its slot is
+// the mirrored one (left arm <-> right arm, left <-> right). Returns its index.
+uint32_t mirroredCopy(Pattern& pat, uint32_t panel, const std::string& name = {});
+// Unfolds a panel drawn as a half about straight edge `edge` (the fold line): the panel becomes the whole shape,
+// the fold edge disappears. False when the edge is curved.
+bool unfoldPanel(Pattern& pat, uint32_t panel, uint32_t edge, std::string& error);
+void removePanel(Pattern& pat, uint32_t panel); // and its seams
+// Splits edge `e` at `t` with a new point (curves split exactly); seams and notches on the edge move with it.
+void splitEdge(Pattern& pat, uint32_t panel, uint32_t edge, float t);
+// Removes point `i` (the two edges beside it become one straight edge); false when the panel would have < 3.
+bool removePoint(Pattern& pat, uint32_t panel, uint32_t point);
+
+// --- Seams ---
+
+// Adds a seam; false (with the reason) when a side's range is empty or overlaps another seam on the same edge.
+bool addSeam(Pattern& pat, const Seam& seam, std::string& error);
+struct SeamCheck {
+ float lengthA = 0.0f, lengthB = 0.0f; // mm
+ bool lengthsMatch = true; // within 2% (and 3 mm): more is eased or gathered in
+ bool twisted = false; // flipped: the fabric turns over along the seam
+ std::string text; // "Front.right <-> Back.left: 412 / 412 mm"
+};
+SeamCheck checkSeam(const Pattern& pat, const Seam& seam);
+float seamSideLength(const Pattern& pat, const SeamSide& s);
+// "Front", or "Front edge 3" when the panel has no name for it.
+std::string edgeName(const Pattern& pat, uint32_t panel, uint32_t edge);
+// Problems the pattern has (invalid panels, overlapping or twisted seams, mismatched lengths), one line each.
+std::vector<std::string> patternProblems(const Pattern& pat);
+
+// --- Triangulation ---
+
+struct SeamLink {
+ uint32_t a = 0, b = 0; // particles (vertices) sewn together
+};
+
+struct GarmentMesh {
+ std::vector<glm::vec2> flat; // mm, pattern sheet coordinates
+ std::vector<uint32_t> panelOf; // per vertex
+ std::vector<glm::uvec3> triangles; // counter-clockwise in the sheet (seen from the right side)
+ std::vector<uint8_t> border; // per vertex: 1 on a panel outline
+ std::vector<SeamLink> links; // seam particle pairs (one per point along each seam)
+ std::vector<uint32_t> panelFirstVertex, panelFirstTriangle; // where each panel starts (+ one past the end)
+ size_t vertexCount() const { return flat.size(); }
+};
+
+// Triangulates every panel at the pattern's particle distance. False (with the reason) when a panel is invalid or
+// a seam is unusable.
+bool triangulatePattern(const Pattern& pat, GarmentMesh& out, std::string& error);
+// Quality numbers for tests and the stats readout: the shortest/longest edge over the particle distance, the
+// smallest angle in degrees.
+struct MeshQuality {
+ float minEdge = 0.0f, maxEdge = 0.0f, minAngle = 0.0f;
+};
+MeshQuality meshQuality(const GarmentMesh& m, float particleDistance);
+
+// --- Arrangement ---
+
+// What placePattern needs to know about the body, found from its vertices (Y up, facing +Z, metres).
+struct BodyFrame {
+ AABB bounds;
+ float centerX = 0.0f, centerZ = 0.0f;
+ float shoulderY = 0.0f; // the top of the torso panels
+ float torsoHalfWidth = 0.15f; // x
+ float torsoFrontZ = 0.1f, torsoBackZ = -0.1f;
+ bool arms = false; // arms held out (T or A pose) were found
+ glm::vec3 leftShoulder{0.0f}, rightShoulder{0.0f}; // where each arm starts (character's left = +X)
+ glm::vec3 leftArmDir{1.0f, 0.0f, 0.0f}, rightArmDir{-1.0f, 0.0f, 0.0f};
+ float armRadius = 0.05f;
+};
+BodyFrame analyzeBody(const Mesh& body);
+// A body frame for no body: a 1.75 m figure standing at the origin.
+BodyFrame defaultBody();
+
+// Gives panels without a chosen slot one from their names (front, back, sleeve/arm with left/right, side).
+void autoSlots(Pattern& pat);
+// The 3D position (metres) of pattern point `flat` (mm) of panel `p` placed on `body`; `gap` metres off it.
+glm::vec3 placePoint(const Panel& p, glm::vec2 flat, const BodyFrame& body, float gap = 0.03f);
+// Every vertex of `m` placed around the body (placed) and the flat rest shape in 3D (rest: sheet x, y, z = 0, in
+// metres): what the cloth solver starts from.
+void placePattern(const Pattern& pat, const GarmentMesh& m, const BodyFrame& body, std::vector<glm::vec3>& placed,
+ std::vector<glm::vec3>& rest, float gap = 0.03f);
+
+// --- After the simulation ---
+
+// The garment as a Part: seam pairs welded, the panel layout as UVs (the whole sheet fit into 0..1, aspect kept),
+// one face group per panel (1, 2, ...), thickened by `thicknessMm` outward-inward (0 = a single surface: the
+// inner side and rim get face group 0x8000 + panel).
+Mesh garmentToMesh(const GarmentMesh& m, const std::vector<glm::vec3>& positions, float thicknessMm);
+
+// --- Templates ---
+
+// A T-shirt pattern (front, back, two sleeves, all seams sewn, slots set): `chestMm` the body's chest girth,
+// `lengthMm` the body length from the shoulder.
+Pattern tshirtPattern(float chestMm = 960.0f, float lengthMm = 700.0f);
+// A simple rectangle panel (`w` x `h` mm, lower-left corner at `at`).
+Panel rectanglePanel(const std::string& name, float w, float h, glm::vec2 at = {0.0f, 0.0f});
+
+// --- Saving ---
+
+Json patternToJson(const Pattern& pat);
+// False (pattern untouched) when `j` is not a pattern; bad panels are left out with a note in `error`.
+bool patternFromJson(const Json& j, Pattern& out, std::string& error);
+// The document's pattern (projectSettings["garment"]); false when there is none.
+bool documentPattern(const Document& doc, Pattern& out);
+// Stores the pattern in the document (an empty pattern removes it) and marks the document modified.
+void setDocumentPattern(Document& doc, const Pattern& pat);
+
+// --- Files ---
+
+// The pattern at real size: each panel's sewing line (solid), cutting line (seam allowance, dashed), notches,
+// grain line and name, laid out as in the pattern sheet. Width and height in mm.
+std::string patternToSvg(const Pattern& pat);
+// The outlines (sewing and cutting lines) as an ASCII DXF in millimetres (LWPOLYLINE, layers SEW and CUT).
+std::string patternToDxf(const Pattern& pat);
+// Panels from SVG: every closed path, polygon, polyline or rect (in the document's real units: mm, cm, in, or px
+// at 96 per inch; the y axis flipped up). Curves stay curves (quadratics as cubics). Returns the panel count
+// added to `out`; 0 with `error` when nothing usable was found. At most 4 MB of text, 512 panels, 20,000 points.
+int panelsFromSvg(const std::string& svg, std::vector<Panel>& out, std::string& error);
+
+} // namespace garment
+} // namespace sf
diff --git a/src/core/GarmentCommands.cpp b/src/core/GarmentCommands.cpp
new file mode 100644
index 00000000..48da577e
--- /dev/null
+++ b/src/core/GarmentCommands.cpp
@@ -0,0 +1,349 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// garment_* commands (core/Garment.h): make and edit the scene's garment pattern, sew it, place it around the
+// body, write and read pattern files. The pattern lives in the project (Document::projectSettings["garment"]).
+#include "core/Commands.h"
+#include "core/Garment.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <cctype>
+#include <limits>
+#include <fstream>
+#include <sstream>
+
+namespace sf {
+
+namespace {
+
+using namespace garment;
+using T = ParamSpec::Type;
+
+std::string lower(std::string s) {
+ std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+ return s;
+}
+
+// A panel by name (any case) or 1-based number.
+bool findPanel(const Pattern& pat, const std::string& ref, uint32_t& out, std::string& error) {
+ for (uint32_t i = 0; i < pat.panels.size(); ++i)
+ if (lower(pat.panels[i].name) == lower(ref)) {
+ out = i;
+ return true;
+ }
+ char* end = nullptr;
+ const long n = std::strtol(ref.c_str(), &end, 10);
+ if (!ref.empty() && end && *end == 0 && n >= 1 && size_t(n) <= pat.panels.size()) {
+ out = uint32_t(n - 1);
+ return true;
+ }
+ error = "No panel \"" + ref + "\" in the pattern";
+ return false;
+}
+
+bool loadOrFail(const Document& doc, Pattern& pat, CommandResult& r) {
+ if (documentPattern(doc, pat)) return true;
+ r = {false, "No garment pattern: run garment_new first"};
+ return false;
+}
+
+std::string summary(const Pattern& pat) {
+ std::ostringstream s;
+ s << pat.panels.size() << " panels, " << pat.seams.size() << " seams";
+ GarmentMesh m;
+ std::string error;
+ if (!pat.panels.empty() && triangulatePattern(pat, m, error))
+ s << ", " << m.vertexCount() << " particles at " << pat.particleDistance << " mm";
+ return s.str();
+}
+
+bool writeText(const std::string& path, const std::string& text, std::string& error) {
+ std::ofstream f(path, std::ios::binary);
+ if (!f || !f.write(text.data(), std::streamsize(text.size()))) {
+ error = "Could not write " + path;
+ return false;
+ }
+ return true;
+}
+
+CommandResult seamCommand(Document& doc, const Args& a) {
+ CommandResult r;
+ Pattern pat;
+ if (!loadOrFail(doc, pat, r)) return r;
+ Seam s;
+ std::string error;
+ for (int side = 0; side < 2; ++side) {
+ const std::string p = side ? "b_" : "a_";
+ SeamSide& sd = side ? s.b : s.a;
+ if (!findPanel(pat, argString(a, p + "panel"), sd.panel, error)) return {false, error};
+ const double e = argNumber(a, p + "edge", 0);
+ if (!(e >= 1 && e <= double(pat.panels[sd.panel].points.size())))
+ return {false, "No edge " + std::to_string(int(e)) + " on " + pat.panels[sd.panel].name};
+ sd.edge = uint32_t(e) - 1;
+ sd.t0 = float(std::clamp(argNumber(a, p + "from", 0.0), 0.0, 1.0));
+ sd.t1 = float(std::clamp(argNumber(a, p + "to", 1.0), 0.0, 1.0));
+ }
+ s.flipped = argBool(a, "flipped", false);
+ if (!addSeam(pat, s, error)) return {false, error};
+ setDocumentPattern(doc, pat);
+ const SeamCheck c = checkSeam(pat, s);
+ return {true, "Sewed " + c.text};
+}
+
+} // namespace
+
+void registerGarmentCommands(CommandRegistry& reg) {
+ reg.add({"garment_new",
+ "Garments: start a garment pattern in the scene (saved with the project). template: tshirt (front, back "
+ "and two sleeves, sewn and placed: ready to drape) or empty.",
+ {{"template", T::String, "tshirt (default) or empty", false},
+ {"chest_mm", T::Number, "T-shirt: the body's chest girth in mm (default 960)", false},
+ {"length_mm", T::Number, "T-shirt: length from the shoulder in mm (default 700)", false},
+ {"particle_mm", T::Number, "Distance between the cloth's particles in mm (default 15)", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const std::string t = lower(argString(a, "template", "tshirt"));
+ Pattern pat;
+ if (t == "tshirt" || t == "t-shirt")
+ pat = tshirtPattern(float(argNumber(a, "chest_mm", 960.0)), float(argNumber(a, "length_mm", 700.0)));
+ else if (t != "empty")
+ return {false, "Unknown template \"" + t + "\" (tshirt or empty)"};
+ pat.particleDistance = float(std::clamp(argNumber(a, "particle_mm", pat.particleDistance), 2.0, 200.0));
+ if (pat.empty()) {
+ doc.projectSettings.set("garment", patternToJson(pat)); // an empty pattern to draw in
+ doc.modified = true;
+ return {true, "New empty garment pattern"};
+ }
+ setDocumentPattern(doc, pat);
+ return {true, "New garment pattern: " + summary(pat)};
+ }});
+ reg.add({"garment_info", "Garments: the pattern's panels, seams (with their lengths) and any problems.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ CommandResult r;
+ Pattern pat;
+ if (!loadOrFail(doc, pat, r)) return r;
+ std::ostringstream s;
+ s << summary(pat);
+ for (size_t i = 0; i < pat.panels.size(); ++i) {
+ const Panel& p = pat.panels[i];
+ const glm::vec2 size = panelMax(p) - panelMin(p);
+ char buf[200];
+ std::snprintf(buf, sizeof buf, "\n%zu. %s: %.0f x %.0f mm, %zu edges, %s", i + 1, p.name.c_str(),
+ double(size.x), double(size.y), p.points.size(), slotLabel(p.place.slot));
+ s << buf;
+ }
+ for (const Seam& sm : pat.seams) s << "\nSeam " << checkSeam(pat, sm).text;
+ for (const std::string& pr : patternProblems(pat)) s << "\nProblem: " << pr;
+ return {true, s.str()};
+ }});
+ reg.add({"garment_add_panel",
+ "Garments: add a pattern panel from its outline: points as JSON [x0, y0, x1, y1, ...] in mm (y up), "
+ "or a rectangle from width_mm and height_mm.",
+ {{"name", T::String, "Panel name (front, back, sleeve... also picks its place around the body)", false},
+ {"points", T::String, "Outline as JSON [x0, y0, x1, y1, ...] in mm, 3 points or more", false},
+ {"width_mm", T::Number, "Rectangle width (when no points)", false},
+ {"height_mm", T::Number, "Rectangle height (when no points)", false},
+ {"slot", T::String, "front, back, left, right, left_arm, right_arm or free (default: from the name)", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Pattern pat;
+ documentPattern(doc, pat);
+ Panel p;
+ const std::string pts = argString(a, "points");
+ const std::string name = argString(a, "name", "Panel " + std::to_string(pat.panels.size() + 1));
+ if (!pts.empty()) {
+ Json j;
+ std::string error;
+ if (!Json::parse(pts, j, error) || !j.isArray() || j.size() % 2 || j.size() < 6)
+ return {false, "points must be a JSON array [x0, y0, x1, y1, ...] of 3 points or more"};
+ for (size_t k = 0; k + 1 < j.size() && k < 40000; k += 2)
+ p.points.push_back({float(j[k].asNumber()), float(j[k + 1].asNumber())});
+ p.curves.resize(p.points.size());
+ p.name = name;
+ } else {
+ const float w = float(argNumber(a, "width_mm", 0.0)), h = float(argNumber(a, "height_mm", 0.0));
+ if (!(w >= 1.0f && h >= 1.0f && w < 1e5f && h < 1e5f)) return {false, "Give points or width_mm and height_mm"};
+ float x = 0.0f;
+ for (const Panel& q : pat.panels) x = std::max(x, panelMax(q).x + 60.0f);
+ p = rectanglePanel(name, w, h, {x, 0.0f});
+ }
+ normalizePanel(p);
+ std::string error;
+ if (!validPanel(p, error)) return {false, error};
+ Slot slot;
+ if (const std::string s = argString(a, "slot"); !s.empty()) {
+ if (!slotFromId(lower(s), slot)) return {false, "Unknown slot \"" + s + "\""};
+ p.place.slot = slot;
+ pat.panels.push_back(std::move(p));
+ } else {
+ pat.panels.push_back(std::move(p));
+ Pattern one;
+ one.panels.push_back(pat.panels.back());
+ autoSlots(one);
+ pat.panels.back().place.slot = one.panels[0].place.slot;
+ }
+ setDocumentPattern(doc, pat);
+ return {true, "Added " + pat.panels.back().name + " (" + slotLabel(pat.panels.back().place.slot) + "): " + summary(pat)};
+ }});
+ reg.add({"garment_remove_panel", "Garments: remove a panel (and its seams).",
+ {{"panel", T::String, "Panel name or number", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ CommandResult r;
+ Pattern pat;
+ if (!loadOrFail(doc, pat, r)) return r;
+ uint32_t i;
+ std::string error;
+ if (!findPanel(pat, argString(a, "panel"), i, error)) return {false, error};
+ const std::string name = pat.panels[i].name;
+ removePanel(pat, i);
+ setDocumentPattern(doc, pat);
+ return {true, "Removed " + name};
+ }});
+ reg.add({"garment_mirror_copy",
+ "Garments: add a mirrored copy of a panel (the other sleeve or side), placed on the other side of the body.",
+ {{"panel", T::String, "Panel name or number", true}, {"name", T::String, "The copy's name", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ CommandResult r;
+ Pattern pat;
+ if (!loadOrFail(doc, pat, r)) return r;
+ uint32_t i;
+ std::string error;
+ if (!findPanel(pat, argString(a, "panel"), i, error)) return {false, error};
+ const uint32_t j = mirroredCopy(pat, i, argString(a, "name"));
+ setDocumentPattern(doc, pat);
+ return {true, "Added " + pat.panels[j].name + " (" + slotLabel(pat.panels[j].place.slot) + ")"};
+ }});
+ reg.add({"garment_sew",
+ "Garments: sew an edge range of one panel to an edge range of another (or the same) panel. Edges are "
+ "numbered from 1 (edge 1 runs from point 1 to point 2); from/to are fractions of the edge (0-1). Sewn "
+ "the right way, a's start meets b's end; flipped=true sews start to start (twists the fabric).",
+ {{"a_panel", T::String, "First panel (name or number)", true},
+ {"a_edge", T::Number, "Its edge (1-based)", true},
+ {"a_from", T::Number, "Range start along it (default 0)", false},
+ {"a_to", T::Number, "Range end (default 1)", false},
+ {"b_panel", T::String, "Second panel", true},
+ {"b_edge", T::Number, "Its edge (1-based)", true},
+ {"b_from", T::Number, "Range start (default 0)", false},
+ {"b_to", T::Number, "Range end (default 1)", false},
+ {"flipped", T::Bool, "Sew start to start (default false)", false}},
+ seamCommand});
+ reg.add({"garment_unsew", "Garments: remove a seam.", {{"seam", T::Number, "Seam number (1-based, see garment_info)", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ CommandResult r;
+ Pattern pat;
+ if (!loadOrFail(doc, pat, r)) return r;
+ const double n = argNumber(a, "seam", 0);
+ if (!(n >= 1 && n <= double(pat.seams.size()))) return {false, "No such seam"};
+ pat.seams.erase(pat.seams.begin() + long(n - 1));
+ setDocumentPattern(doc, pat);
+ return {true, "Removed seam " + std::to_string(int(n))};
+ }});
+ reg.add({"garment_set", "Garments: the pattern's simulation settings.",
+ {{"particle_mm", T::Number, "Distance between particles in mm (2-200; smaller = finer folds, slower)", false},
+ {"fabric", T::String, "silk, cotton, denim or leather", false},
+ {"thickness_mm", T::Number, "Thickness of the Part made from the garment (0 = a single surface)", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ CommandResult r;
+ Pattern pat;
+ if (!loadOrFail(doc, pat, r)) return r;
+ if (a.count("particle_mm")) pat.particleDistance = float(std::clamp(argNumber(a, "particle_mm", 15), 2.0, 200.0));
+ if (a.count("thickness_mm")) pat.thickness = float(std::clamp(argNumber(a, "thickness_mm", 2), 0.0, 100.0));
+ if (a.count("fabric")) {
+ const std::string f = lower(argString(a, "fabric"));
+ if (f != "silk" && f != "cotton" && f != "denim" && f != "leather") return {false, "Unknown fabric \"" + f + "\""};
+ pat.fabric = f;
+ }
+ setDocumentPattern(doc, pat);
+ return {true, "Garment: " + summary(pat) + ", " + pat.fabric};
+ }});
+ reg.add({"garment_place", "Garments: where a panel goes around the body.",
+ {{"panel", T::String, "Panel name or number", true},
+ {"slot", T::String, "front, back, left, right, left_arm, right_arm or free", false},
+ {"x", T::Number, "Offset across (around) the body, metres", false},
+ {"y", T::Number, "Offset up, metres", false},
+ {"z", T::Number, "Offset away from the body, metres", false},
+ {"wrap", T::Bool, "Bend around the torso or arm (default true)", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ CommandResult r;
+ Pattern pat;
+ if (!loadOrFail(doc, pat, r)) return r;
+ uint32_t i;
+ std::string error;
+ if (!findPanel(pat, argString(a, "panel"), i, error)) return {false, error};
+ Placement& pl = pat.panels[i].place;
+ if (const std::string s = argString(a, "slot"); !s.empty() && !slotFromId(lower(s), pl.slot))
+ return {false, "Unknown slot \"" + s + "\""};
+ pl.offset.x = float(std::clamp(argNumber(a, "x", pl.offset.x), -10.0, 10.0));
+ pl.offset.y = float(std::clamp(argNumber(a, "y", pl.offset.y), -10.0, 10.0));
+ pl.offset.z = float(std::clamp(argNumber(a, "z", pl.offset.z), -10.0, 10.0));
+ pl.wrap = argBool(a, "wrap", pl.wrap);
+ setDocumentPattern(doc, pat);
+ return {true, pat.panels[i].name + ": " + slotLabel(pl.slot)};
+ }});
+ reg.add({"garment_export",
+ "Garments: write the pattern at real size for sewing: svg (sewing and cutting lines, notches, grain "
+ "lines, names, a 50 mm scale square; print at 100%) or dxf (outlines in mm).",
+ {{"path", T::String, "File to write (.svg or .dxf)", true}, {"format", T::String, "svg or dxf (default: from the path)", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ CommandResult r;
+ Pattern pat;
+ if (!loadOrFail(doc, pat, r)) return r;
+ if (pat.empty()) return {false, "The pattern has no panels"};
+ const std::string path = argString(a, "path");
+ std::string fmt = lower(argString(a, "format"));
+ if (fmt.empty()) fmt = lower(path).size() > 4 && lower(path).substr(lower(path).size() - 4) == ".dxf" ? "dxf" : "svg";
+ std::string error;
+ if (!writeText(path, fmt == "dxf" ? patternToDxf(pat) : patternToSvg(pat), error)) return {false, error};
+ return {true, "Wrote " + std::to_string(pat.panels.size()) + " panels to " + path};
+ }});
+ reg.add({"garment_import", "Garments: add panels from an SVG (every closed shape, at the file's real size).",
+ {{"path", T::String, "SVG file", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const std::string path = argString(a, "path");
+ std::ifstream f(path, std::ios::binary);
+ if (!f) return {false, "Could not open " + path};
+ f.seekg(0, std::ios::end);
+ const std::streamoff size = f.tellg();
+ if (size < 0 || size > 4 * 1024 * 1024) return {false, "The SVG is larger than 4 MB"};
+ f.seekg(0);
+ std::string text(size_t(size), '\0');
+ f.read(text.data(), size);
+ Pattern pat;
+ documentPattern(doc, pat);
+ std::vector<Panel> panels;
+ std::string error;
+ const int n = panelsFromSvg(text, panels, error);
+ if (!n) return {false, error};
+ // Beside what's there already.
+ float x = 0.0f;
+ for (const Panel& q : pat.panels) x = std::max(x, panelMax(q).x + 60.0f);
+ float minX = std::numeric_limits<float>::max(), minY = minX;
+ for (const Panel& p : panels) {
+ minX = std::min(minX, panelMin(p).x);
+ minY = std::min(minY, panelMin(p).y);
+ }
+ const glm::vec2 shift(x - minX, -minY);
+ for (Panel& p : panels) {
+ for (glm::vec2& q : p.points) q += shift;
+ for (EdgeCurve& c : p.curves) {
+ c.c1 += shift;
+ c.c2 += shift;
+ }
+ }
+ const size_t first = pat.panels.size();
+ pat.panels.insert(pat.panels.end(), panels.begin(), panels.end());
+ Pattern added;
+ added.panels.assign(pat.panels.begin() + long(first), pat.panels.end());
+ autoSlots(added);
+ std::copy(added.panels.begin(), added.panels.end(), pat.panels.begin() + long(first));
+ setDocumentPattern(doc, pat);
+ return {true, "Imported " + std::to_string(n) + " panels" + (error.empty() ? "" : " (" + error + ")")};
+ }});
+ reg.add({"garment_clear", "Garments: remove the garment pattern from the scene.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ setDocumentPattern(doc, Pattern{});
+ return {true, "Garment pattern removed"};
+ }});
+}
+
+} // namespace sf
diff --git a/src/core/GarmentFiles.cpp b/src/core/GarmentFiles.cpp
new file mode 100644
index 00000000..8ba7292d
--- /dev/null
+++ b/src/core/GarmentFiles.cpp
@@ -0,0 +1,620 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Pattern files (core/Garment.h): SVG at real size for printing and sewing, DXF outlines for cutters, and SVG
+// panels read back in. The SVG reader is small and strict on purpose (the file may come from anywhere): no
+// entities, no external references, no scripts are ever followed; it only reads the shapes' geometry, in bounded
+// amounts.
+#include "core/Garment.h"
+
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <cstdio>
+#include <cctype>
+#include <limits>
+#include <cstring>
+
+namespace sf::garment {
+
+namespace {
+
+// --- Writing ---
+
+std::string fmt(double v) {
+ char b[32];
+ std::snprintf(b, sizeof b, "%.2f", std::abs(v) < 0.005 ? 0.0 : v);
+ std::string s = b;
+ while (s.size() > 1 && s.back() == '0') s.pop_back();
+ if (!s.empty() && s.back() == '.') s.pop_back();
+ return s;
+}
+
+std::string xmlEscape(const std::string& s) {
+ std::string o;
+ for (char c : s) {
+ switch (c) {
+ case '&': o += "&amp;"; break;
+ case '<': o += "&lt;"; break;
+ case '>': o += "&gt;"; break;
+ case '"': o += "&quot;"; break;
+ default:
+ if (static_cast<unsigned char>(c) >= 0x20 || c == '\t') o += c;
+ }
+ }
+ return o;
+}
+
+struct Sheet {
+ glm::vec2 lo{0.0f}, hi{0.0f};
+ float margin = 10.0f;
+ glm::vec2 map(glm::vec2 p) const { return {p.x - lo.x + margin, hi.y - p.y + margin}; } // y down
+ float width() const { return hi.x - lo.x + 2.0f * margin; }
+ float height() const { return hi.y - lo.y + 2.0f * margin; }
+};
+
+Sheet sheetOf(const Pattern& pat) {
+ Sheet s;
+ glm::vec2 lo(std::numeric_limits<float>::max()), hi(std::numeric_limits<float>::lowest());
+ for (const Panel& p : pat.panels)
+ for (glm::vec2 q : offsetOutline(p, std::max(0.0f, p.seamAllowance))) {
+ lo = glm::min(lo, q);
+ hi = glm::max(hi, q);
+ }
+ if (pat.panels.empty()) lo = hi = glm::vec2(0.0f);
+ hi.y += 70.0f; // room for the 50 mm scale square above the panels
+ s.lo = lo;
+ s.hi = hi;
+ return s;
+}
+
+} // namespace
+
+std::string patternToSvg(const Pattern& pat) {
+ const Sheet sh = sheetOf(pat);
+ std::string o;
+ o += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
+ o += "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"" + fmt(sh.width()) + "mm\" height=\"" + fmt(sh.height()) +
+ "mm\" viewBox=\"0 0 " + fmt(sh.width()) + " " + fmt(sh.height()) + "\">\n";
+ o += "<!-- SculptForge garment pattern, 1 unit = 1 mm. Print at 100% (no fit to page): the square is 50 mm. "
+ "Solid: sewing line. Dashed: cutting line (seam allowance). -->\n";
+ o += "<g fill=\"none\" stroke=\"#000\" stroke-width=\"0.4\" font-family=\"sans-serif\">\n";
+ // The scale square, top left.
+ o += "<rect x=\"" + fmt(sh.margin) + "\" y=\"" + fmt(sh.margin) + "\" width=\"50\" height=\"50\"/>\n";
+ o += "<text x=\"" + fmt(sh.margin + 55.0f) + "\" y=\"" + fmt(sh.margin + 28.0f) +
+ "\" font-size=\"8\" fill=\"#000\" stroke=\"none\">50 mm</text>\n";
+ for (size_t i = 0; i < pat.panels.size(); ++i) {
+ const Panel& p = pat.panels[i];
+ if (p.points.size() < 3) continue;
+ o += "<g id=\"panel-" + std::to_string(i + 1) + "\">\n";
+ if (p.seamAllowance > 0.0f) {
+ const std::vector<glm::vec2> cut = offsetOutline(p, p.seamAllowance);
+ o += "<polygon class=\"cut\" stroke-dasharray=\"4 2\" points=\"";
+ for (glm::vec2 q : cut) {
+ const glm::vec2 m = sh.map(q);
+ o += fmt(m.x) + "," + fmt(m.y) + " ";
+ }
+ o.back() = '"';
+ o += "/>\n";
+ }
+ // The sewing line, curves exact.
+ o += "<path class=\"sew\" data-name=\"" + xmlEscape(p.name) + "\" stroke-width=\"0.6\" d=\"";
+ glm::vec2 m = sh.map(p.points[0]);
+ o += "M" + fmt(m.x) + " " + fmt(m.y);
+ for (size_t e = 0; e < p.points.size(); ++e) {
+ const glm::vec2 b = sh.map(p.points[(e + 1) % p.points.size()]);
+ const EdgeCurve& c = e < p.curves.size() ? p.curves[e] : EdgeCurve{};
+ if (c.curved) {
+ const glm::vec2 c1 = sh.map(c.c1), c2 = sh.map(c.c2);
+ o += " C" + fmt(c1.x) + " " + fmt(c1.y) + " " + fmt(c2.x) + " " + fmt(c2.y) + " " + fmt(b.x) + " " + fmt(b.y);
+ } else if (e + 1 < p.points.size()) {
+ o += " L" + fmt(b.x) + " " + fmt(b.y);
+ }
+ }
+ o += " Z\"/>\n";
+ // Notches: a short tick across the seam allowance.
+ for (const Notch& nt : p.notches) {
+ glm::vec2 tan;
+ const glm::vec2 at = edgePoint(p, nt.edge, nt.t, &tan);
+ const glm::vec2 out(tan.y, -tan.x);
+ const float len = std::max(5.0f, p.seamAllowance);
+ const glm::vec2 a = sh.map(at - out * 2.0f), b = sh.map(at + out * len);
+ o += "<line class=\"notch\" x1=\"" + fmt(a.x) + "\" y1=\"" + fmt(a.y) + "\" x2=\"" + fmt(b.x) + "\" y2=\"" + fmt(b.y) + "\"/>\n";
+ }
+ // Grain line: an arrow through the middle along the warp, half the panel's height.
+ const glm::vec2 lo = panelMin(p), hi = panelMax(p), c = 0.5f * (lo + hi);
+ const float g = p.grainDegrees * 3.14159265f / 180.0f;
+ const glm::vec2 d(std::cos(g), std::sin(g));
+ const float half = 0.25f * std::min(hi.y - lo.y, hi.x - lo.x) + 0.0f;
+ const glm::vec2 g0 = sh.map(c - d * half), g1 = sh.map(c + d * half);
+ const glm::vec2 side(-d.y, d.x);
+ const glm::vec2 h1 = sh.map(c + d * (half - 6.0f) + side * 3.0f), h2 = sh.map(c + d * (half - 6.0f) - side * 3.0f);
+ o += "<path class=\"grain\" d=\"M" + fmt(g0.x) + " " + fmt(g0.y) + " L" + fmt(g1.x) + " " + fmt(g1.y) + " M" + fmt(h1.x) + " " +
+ fmt(h1.y) + " L" + fmt(g1.x) + " " + fmt(g1.y) + " L" + fmt(h2.x) + " " + fmt(h2.y) + "\"/>\n";
+ const glm::vec2 t = sh.map(c + glm::vec2(0.0f, -0.12f * (hi.y - lo.y)));
+ o += "<text x=\"" + fmt(t.x) + "\" y=\"" + fmt(t.y) + "\" font-size=\"10\" text-anchor=\"middle\" fill=\"#000\" stroke=\"none\">" +
+ xmlEscape(p.name) + "</text>\n";
+ o += "</g>\n";
+ }
+ o += "</g>\n</svg>\n";
+ return o;
+}
+
+std::string patternToDxf(const Pattern& pat) {
+ std::string o;
+ auto pair = [&](int code, const std::string& v) { o += std::to_string(code) + "\n" + v + "\n"; };
+ pair(0, "SECTION");
+ pair(2, "HEADER");
+ pair(9, "$INSUNITS");
+ pair(70, "4"); // millimetres
+ pair(0, "ENDSEC");
+ pair(0, "SECTION");
+ pair(2, "ENTITIES");
+ auto polyline = [&](const std::vector<glm::vec2>& pts, const char* layer) {
+ pair(0, "POLYLINE");
+ pair(8, layer);
+ pair(66, "1");
+ pair(70, "1"); // closed
+ for (glm::vec2 q : pts) {
+ pair(0, "VERTEX");
+ pair(8, layer);
+ pair(10, fmt(q.x));
+ pair(20, fmt(q.y));
+ }
+ pair(0, "SEQEND");
+ pair(8, layer);
+ };
+ for (const Panel& p : pat.panels) {
+ if (p.points.size() < 3) continue;
+ polyline(outline(p, 0.1f), "SEW");
+ if (p.seamAllowance > 0.0f) polyline(offsetOutline(p, p.seamAllowance), "CUT");
+ const glm::vec2 c = 0.5f * (panelMin(p) + panelMax(p));
+ pair(0, "TEXT");
+ pair(8, "LABEL");
+ pair(10, fmt(c.x));
+ pair(20, fmt(c.y));
+ pair(40, "10");
+ std::string name;
+ for (char ch : p.name) name += (ch == '\n' || ch == '\r') ? ' ' : ch;
+ pair(1, name);
+ }
+ pair(0, "ENDSEC");
+ pair(0, "EOF");
+ return o;
+}
+
+// ---------------------------------------------------------------------------
+// SVG import
+// ---------------------------------------------------------------------------
+
+namespace {
+
+struct Affine { // x' = a x + c y + e, y' = b x + d y + f (SVG's matrix(a b c d e f))
+ double a = 1, b = 0, c = 0, d = 1, e = 0, f = 0;
+ glm::dvec2 apply(glm::dvec2 p) const { return {a * p.x + c * p.y + e, b * p.x + d * p.y + f}; }
+ Affine then(const Affine& m) const { // m applied after this
+ return {m.a * a + m.c * b, m.b * a + m.d * b, m.a * c + m.c * d, m.b * c + m.d * d, m.a * e + m.c * f + m.e,
+ m.b * e + m.d * f + m.f};
+ }
+};
+
+// Numbers the SVG way: "1.5.5" is 1.5 and .5, "-1-2" is -1 and -2, exponents allowed. Locale-independent.
+struct Numbers {
+ const char* p;
+ const char* end;
+ void skip() {
+ while (p < end && (*p == ' ' || *p == ',' || *p == '\t' || *p == '\n' || *p == '\r')) ++p;
+ }
+ bool number(double& out) {
+ skip();
+ const char* s = p;
+ double sign = 1.0;
+ if (p < end && (*p == '+' || *p == '-')) sign = *p++ == '-' ? -1.0 : 1.0;
+ double v = 0.0;
+ bool digits = false;
+ while (p < end && *p >= '0' && *p <= '9') {
+ v = v * 10.0 + (*p++ - '0');
+ digits = true;
+ }
+ if (p < end && *p == '.') {
+ ++p;
+ double scale = 0.1;
+ while (p < end && *p >= '0' && *p <= '9') {
+ v += (*p++ - '0') * scale;
+ scale *= 0.1;
+ digits = true;
+ }
+ }
+ if (!digits) {
+ p = s;
+ return false;
+ }
+ if (p < end && (*p == 'e' || *p == 'E') && p + 1 < end &&
+ ((p[1] >= '0' && p[1] <= '9') || ((p[1] == '-' || p[1] == '+') && p + 2 < end && p[2] >= '0' && p[2] <= '9'))) {
+ ++p;
+ int es = 1;
+ if (*p == '+' || *p == '-') es = *p++ == '-' ? -1 : 1;
+ int ex = 0;
+ while (p < end && *p >= '0' && *p <= '9') ex = std::min(400, ex * 10 + (*p++ - '0'));
+ v *= std::pow(10.0, es * ex);
+ }
+ out = sign * v;
+ return std::isfinite(out);
+ }
+ bool flag(double& out) { // arc flags may be written without separators ("a1 1 0 01 ...")
+ skip();
+ if (p < end && (*p == '0' || *p == '1')) {
+ out = *p++ - '0';
+ return true;
+ }
+ return false;
+ }
+};
+
+// One closed outline: points and the curve of the edge leaving each.
+struct Shape {
+ std::vector<glm::dvec2> pts;
+ std::vector<std::array<glm::dvec2, 2>> ctrl;
+ std::vector<bool> curved;
+ bool closed = false;
+ std::string name;
+};
+
+std::vector<Shape> parsePath(const std::string& d, size_t& budget) {
+ std::vector<Shape> out;
+ Numbers n{d.data(), d.data() + d.size()};
+ Shape cur;
+ glm::dvec2 pos(0.0), start(0.0), lastCtrl(0.0);
+ char cmd = 0, prev = 0;
+ auto finish = [&](bool closed) {
+ if (cur.pts.size() >= 2) {
+ // A last point back on the first closes it too.
+ if (glm::length(cur.pts.back() - cur.pts.front()) < 1e-6 * (1.0 + glm::length(cur.pts.front()))) {
+ cur.pts.pop_back();
+ closed = true;
+ } else {
+ cur.ctrl.pop_back();
+ cur.curved.pop_back();
+ cur.ctrl.push_back({glm::dvec2(0.0), glm::dvec2(0.0)});
+ cur.curved.push_back(false);
+ }
+ cur.closed = closed;
+ cur.ctrl.resize(cur.pts.size());
+ cur.curved.resize(cur.pts.size());
+ if (cur.pts.size() >= 2) out.push_back(cur); // (two points: a D shape, split when made a panel)
+ }
+ cur = {};
+ };
+ // Adds the edge from `pos` to `to` (curved with c1, c2 when given).
+ auto edge = [&](glm::dvec2 to, bool curvedEdge, glm::dvec2 c1, glm::dvec2 c2) {
+ if (cur.pts.empty()) {
+ cur.pts.push_back(pos);
+ cur.ctrl.push_back({});
+ cur.curved.push_back(false);
+ }
+ cur.ctrl.back() = {c1, c2};
+ cur.curved.back() = curvedEdge;
+ cur.pts.push_back(to);
+ cur.ctrl.push_back({});
+ cur.curved.push_back(false);
+ pos = to;
+ };
+ while (true) {
+ n.skip();
+ if (n.p >= n.end) break;
+ if (budget == 0) break;
+ --budget;
+ const char c = *n.p;
+ if (std::isalpha(static_cast<unsigned char>(c))) {
+ cmd = c;
+ ++n.p;
+ } else if (!cmd) {
+ break;
+ }
+ const bool rel = std::islower(static_cast<unsigned char>(cmd)) != 0;
+ const glm::dvec2 o = rel ? pos : glm::dvec2(0.0);
+ double v[7];
+ auto nums = [&](int k) {
+ for (int i = 0; i < k; ++i)
+ if (!n.number(v[i])) return false;
+ return true;
+ };
+ switch (std::toupper(static_cast<unsigned char>(cmd))) {
+ case 'M':
+ if (!nums(2)) return out;
+ finish(false);
+ pos = start = o + glm::dvec2(v[0], v[1]);
+ cmd = rel ? 'l' : 'L'; // following pairs are lines
+ break;
+ case 'L':
+ if (!nums(2)) return out;
+ edge(o + glm::dvec2(v[0], v[1]), false, {}, {});
+ break;
+ case 'H':
+ if (!nums(1)) return out;
+ edge({(rel ? pos.x : 0.0) + v[0], pos.y}, false, {}, {});
+ break;
+ case 'V':
+ if (!nums(1)) return out;
+ edge({pos.x, (rel ? pos.y : 0.0) + v[0]}, false, {}, {});
+ break;
+ case 'C':
+ if (!nums(6)) return out;
+ lastCtrl = o + glm::dvec2(v[2], v[3]);
+ edge(o + glm::dvec2(v[4], v[5]), true, o + glm::dvec2(v[0], v[1]), lastCtrl);
+ break;
+ case 'S': {
+ if (!nums(4)) return out;
+ const char pu = char(std::toupper(static_cast<unsigned char>(prev)));
+ const glm::dvec2 c1 = (pu == 'C' || pu == 'S') ? 2.0 * pos - lastCtrl : pos;
+ lastCtrl = o + glm::dvec2(v[0], v[1]);
+ edge(o + glm::dvec2(v[2], v[3]), true, c1, lastCtrl);
+ break;
+ }
+ case 'Q':
+ case 'T': {
+ glm::dvec2 q, to;
+ if (std::toupper(static_cast<unsigned char>(cmd)) == 'Q') {
+ if (!nums(4)) return out;
+ q = o + glm::dvec2(v[0], v[1]);
+ to = o + glm::dvec2(v[2], v[3]);
+ } else {
+ if (!nums(2)) return out;
+ const char pu = char(std::toupper(static_cast<unsigned char>(prev)));
+ q = (pu == 'Q' || pu == 'T') ? 2.0 * pos - lastCtrl : pos;
+ to = o + glm::dvec2(v[0], v[1]);
+ }
+ lastCtrl = q;
+ const glm::dvec2 from = pos;
+ edge(to, true, from + (q - from) * (2.0 / 3.0), to + (q - to) * (2.0 / 3.0));
+ break;
+ }
+ case 'A': { // arcs: radii, rotation, flags, end point; drawn as a straight edge to the end point
+ if (!nums(3)) return out;
+ double f1, f2;
+ if (!n.flag(f1) || !n.flag(f2) || !n.number(v[5]) || !n.number(v[6])) return out;
+ edge(o + glm::dvec2(v[5], v[6]), false, {}, {});
+ break;
+ }
+ case 'Z':
+ if (!cur.pts.empty()) {
+ if (glm::length(pos - start) > 1e-9) edge(start, false, {}, {});
+ finish(true);
+ }
+ pos = start;
+ cmd = 0;
+ break;
+ default: return out;
+ }
+ prev = cmd ? cmd : 'Z';
+ }
+ finish(false);
+ return out;
+}
+
+// The value of attribute `name` in tag text `tag` ("" when absent). Exact names only (so "d" never matches "id").
+std::string attr(const std::string& tag, const char* name) {
+ const size_t nl = std::strlen(name);
+ for (size_t i = 0; i + nl < tag.size(); ++i) {
+ if (tag.compare(i, nl, name) != 0) continue;
+ if (i > 0 && !std::isspace(static_cast<unsigned char>(tag[i - 1]))) continue;
+ size_t j = i + nl;
+ while (j < tag.size() && std::isspace(static_cast<unsigned char>(tag[j]))) ++j;
+ if (j >= tag.size() || tag[j] != '=') continue;
+ ++j;
+ while (j < tag.size() && std::isspace(static_cast<unsigned char>(tag[j]))) ++j;
+ if (j >= tag.size() || (tag[j] != '"' && tag[j] != '\'')) continue;
+ const char q = tag[j];
+ const size_t e = tag.find(q, j + 1);
+ if (e == std::string::npos) return {};
+ return tag.substr(j + 1, e - j - 1);
+ }
+ return {};
+}
+
+Affine parseTransform(const std::string& t) {
+ Affine m;
+ size_t i = 0;
+ while (i < t.size()) {
+ const size_t open = t.find('(', i);
+ if (open == std::string::npos) break;
+ const size_t close = t.find(')', open);
+ if (close == std::string::npos) break;
+ std::string fn = t.substr(i, open - i);
+ fn.erase(std::remove_if(fn.begin(), fn.end(), [](char c) { return std::isspace(static_cast<unsigned char>(c)) || c == ','; }), fn.end());
+ const std::string args = t.substr(open + 1, close - open - 1);
+ Numbers n{args.data(), args.data() + args.size()};
+ double v[6];
+ int k = 0;
+ while (k < 6 && n.number(v[k])) ++k;
+ Affine s;
+ if (fn == "matrix" && k == 6) s = {v[0], v[1], v[2], v[3], v[4], v[5]};
+ else if (fn == "translate" && k >= 1) s = {1, 0, 0, 1, v[0], k > 1 ? v[1] : 0.0};
+ else if (fn == "scale" && k >= 1) s = {v[0], 0, 0, k > 1 ? v[1] : v[0], 0, 0};
+ else if (fn == "rotate" && k >= 1) {
+ const double r = v[0] * 3.14159265358979 / 180.0, cs = std::cos(r), sn = std::sin(r);
+ const double cx = k >= 3 ? v[1] : 0.0, cy = k >= 3 ? v[2] : 0.0;
+ s = Affine{1, 0, 0, 1, -cx, -cy}.then({cs, sn, -sn, cs, 0, 0}).then({1, 0, 0, 1, cx, cy});
+ }
+ m = s.then(m); // the rightmost transform applies first: this one is applied before those before it
+ i = close + 1;
+ }
+ // (Each later function in the list applies first, so the composition above builds left * right.)
+ return m;
+}
+
+// Millimetres per unit of a length attribute ("210mm" -> 1 per mm, "8.5in" -> 25.4, "300" -> px at 96/in).
+double lengthMm(const std::string& s, double& value) {
+ Numbers n{s.data(), s.data() + s.size()};
+ if (!n.number(value)) return 0.0;
+ std::string unit(n.p, n.end);
+ unit.erase(std::remove_if(unit.begin(), unit.end(), [](char c) { return std::isspace(static_cast<unsigned char>(c)); }), unit.end());
+ if (unit == "mm") return 1.0;
+ if (unit == "cm") return 10.0;
+ if (unit == "in") return 25.4;
+ if (unit == "pt") return 25.4 / 72.0;
+ if (unit == "pc") return 25.4 / 6.0;
+ if (unit.empty() || unit == "px") return 25.4 / 96.0;
+ return 0.0; // % or em: no real size
+}
+
+} // namespace
+
+int panelsFromSvg(const std::string& svg, std::vector<Panel>& out, std::string& error) {
+ if (svg.size() > 4u * 1024u * 1024u) {
+ error = "The SVG is larger than 4 MB";
+ return 0;
+ }
+ double mmPerUnit = 25.4 / 96.0;
+ std::vector<Affine> stack{Affine{}};
+ std::vector<Shape> shapes;
+ std::vector<bool> ours; // shapes marked class="sew" (a SculptForge pattern: only those are panels)
+ size_t budget = 200000; // path commands
+ size_t points = 0;
+ bool sawSvg = false;
+ for (size_t i = 0; i < svg.size();) {
+ const size_t lt = svg.find('<', i);
+ if (lt == std::string::npos) break;
+ if (svg.compare(lt, 4, "<!--") == 0) {
+ const size_t e = svg.find("-->", lt + 4);
+ i = e == std::string::npos ? svg.size() : e + 3;
+ continue;
+ }
+ if (svg.compare(lt, 9, "<![CDATA[") == 0) {
+ const size_t e = svg.find("]]>", lt + 9);
+ i = e == std::string::npos ? svg.size() : e + 3;
+ continue;
+ }
+ size_t gt = lt + 1;
+ char quote = 0;
+ while (gt < svg.size() && (quote || svg[gt] != '>')) { // '>' inside a quoted attribute isn't the end
+ if (quote && svg[gt] == quote) quote = 0;
+ else if (!quote && (svg[gt] == '"' || svg[gt] == '\'')) quote = svg[gt];
+ ++gt;
+ }
+ if (gt >= svg.size()) break;
+ const std::string tag = svg.substr(lt + 1, gt - lt - 1);
+ i = gt + 1;
+ if (tag.empty() || tag[0] == '?' || tag[0] == '!') continue; // declarations, DOCTYPE (never expanded)
+ if (tag[0] == '/') {
+ if (tag.compare(1, 1, "g") == 0 && (tag.size() == 2 || std::isspace(static_cast<unsigned char>(tag[2])))) {
+ if (stack.size() > 1) stack.pop_back();
+ }
+ continue;
+ }
+ size_t ne = 0;
+ while (ne < tag.size() && !std::isspace(static_cast<unsigned char>(tag[ne])) && tag[ne] != '/') ++ne;
+ std::string el = tag.substr(0, ne);
+ if (const size_t colon = el.find(':'); colon != std::string::npos) el = el.substr(colon + 1);
+ const bool selfClosing = tag.back() == '/';
+ const Affine m = parseTransform(attr(tag, "transform")).then(stack.back());
+ if (el == "svg" && !sawSvg) {
+ sawSvg = true;
+ double w = 0.0, vb[4] = {0, 0, 0, 0};
+ const double unit = lengthMm(attr(tag, "width"), w);
+ const std::string vbs = attr(tag, "viewBox");
+ Numbers n{vbs.data(), vbs.data() + vbs.size()};
+ int k = 0;
+ while (k < 4 && n.number(vb[k])) ++k;
+ if (unit > 0.0 && w > 0.0 && k == 4 && vb[2] > 0.0) mmPerUnit = w * unit / vb[2];
+ else if (unit > 0.0 && k != 4) mmPerUnit = 25.4 / 96.0; // no viewBox: user units are px
+ continue;
+ }
+ if (el == "g") {
+ if (!selfClosing) stack.push_back(m);
+ if (stack.size() > 64) stack.pop_back();
+ continue;
+ }
+ std::vector<Shape> found;
+ if (el == "path") {
+ found = parsePath(attr(tag, "d"), budget);
+ } else if (el == "polygon" || el == "polyline") {
+ const std::string ps = attr(tag, "points");
+ Numbers n{ps.data(), ps.data() + ps.size()};
+ Shape s;
+ double x, y;
+ while (s.pts.size() < 20000 && n.number(x) && n.number(y)) s.pts.push_back({x, y});
+ if (s.pts.size() >= 2 && glm::length(s.pts.back() - s.pts.front()) < 1e-9) s.pts.pop_back();
+ s.closed = el == "polygon" || s.pts.size() >= 3;
+ s.ctrl.resize(s.pts.size());
+ s.curved.assign(s.pts.size(), false);
+ if (s.pts.size() >= 3) found.push_back(s);
+ } else if (el == "rect") {
+ double x = 0, y = 0, w = 0, h = 0;
+ auto get = [&](const char* a, double& v) {
+ const std::string s = attr(tag, a);
+ Numbers n{s.data(), s.data() + s.size()};
+ return n.number(v);
+ };
+ get("x", x);
+ get("y", y);
+ if (get("width", w) && get("height", h) && w > 0 && h > 0) {
+ Shape s;
+ s.pts = {{x, y}, {x + w, y}, {x + w, y + h}, {x, y + h}};
+ s.ctrl.resize(4);
+ s.curved.assign(4, false);
+ s.closed = true;
+ found.push_back(s);
+ }
+ }
+ const std::string cls = attr(tag, "class");
+ const bool sew = cls == "sew";
+ std::string name = attr(tag, "data-name");
+ if (name.empty()) name = attr(tag, "id");
+ for (Shape& s : found) {
+ if (!s.closed) continue;
+ points += s.pts.size();
+ if (points > 20000 || shapes.size() >= 512) break;
+ for (glm::dvec2& q : s.pts) q = m.apply(q);
+ for (auto& c : s.ctrl)
+ for (glm::dvec2& q : c) q = m.apply(q);
+ s.name = name;
+ shapes.push_back(std::move(s));
+ ours.push_back(sew);
+ }
+ }
+ if (!sawSvg) {
+ error = "Not an SVG file";
+ return 0;
+ }
+ const bool onlyOurs = std::find(ours.begin(), ours.end(), true) != ours.end();
+ int added = 0, rejected = 0;
+ for (size_t k = 0; k < shapes.size(); ++k) {
+ if (onlyOurs && !ours[k]) continue;
+ const Shape& s = shapes[k];
+ Panel p;
+ p.name = s.name.empty() ? "Panel " + std::to_string(out.size() + 1) : s.name.substr(0, 128);
+ auto conv = [&](glm::dvec2 q) { return glm::vec2(float(q.x * mmPerUnit), float(-q.y * mmPerUnit)); };
+ for (size_t e = 0; e < s.pts.size(); ++e) {
+ p.points.push_back(conv(s.pts[e]));
+ p.curves.push_back({bool(s.curved[e]), conv(s.ctrl[e][0]), conv(s.ctrl[e][1])});
+ }
+ // Drop points closer than 1 mm to the one before (exporters repeat points).
+ for (size_t e = p.points.size(); e-- > 1 && p.points.size() > 3;)
+ if (glm::length(p.points[e] - p.points[e - 1]) < 1.0f && !p.curves[e - 1].curved) {
+ p.points.erase(p.points.begin() + long(e));
+ p.curves[e - 1] = p.curves[e];
+ p.curves.erase(p.curves.begin() + long(e));
+ }
+ if (p.points.size() == 2) { // two points joined by a curve and a line (or two curves): split each curve
+ Pattern one;
+ one.panels.push_back(std::move(p));
+ for (uint32_t e = 2; e-- > 0;)
+ if (one.panels[0].curves[e].curved) splitEdge(one, 0, e, 0.5f);
+ p = std::move(one.panels[0]);
+ }
+ normalizePanel(p);
+ std::string why;
+ if (!validPanel(p, why)) {
+ ++rejected;
+ continue;
+ }
+ out.push_back(std::move(p));
+ ++added;
+ }
+ if (!added) error = shapes.empty() ? "No closed shapes in the SVG" : "No usable panels in the SVG (" + std::to_string(rejected) + " shapes skipped)";
+ else if (rejected) error = std::to_string(rejected) + " shapes skipped (open, crossing or too small)";
+ return added;
+}
+
+} // namespace sf::garment
diff --git a/src/core/GarmentMesh.cpp b/src/core/GarmentMesh.cpp
new file mode 100644
index 00000000..f482d6b2
--- /dev/null
+++ b/src/core/GarmentMesh.cpp
@@ -0,0 +1,535 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Even triangulation of pattern panels (core/Garment.h). Per panel:
+// 1. The outline is sampled at the particle distance h, edge by edge, split at every seam end; both sides of a
+// seam get the same number of points, so the seam's particles pair one to one.
+// 2. The inside is filled with a triangular lattice of spacing h along the grain line, keeping points that are
+// at least about h/2 from the outline and outside every outline segment's diametral circle (so the outline
+// segments are Delaunay edges almost always).
+// 3. Bowyer-Watson Delaunay triangulation of all the points; outline segments that are still missing are
+// recovered by edge flips; triangles outside the outline are dropped.
+// 4. Laplacian smoothing of the inside points (never folding a triangle) and constrained Lawson flips back to
+// a Delaunay triangulation.
+#include "core/Garment.h"
+
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <unordered_map>
+
+namespace sf::garment {
+
+namespace {
+
+using dvec2 = glm::dvec2;
+
+double orient(dvec2 a, dvec2 b, dvec2 c) { return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); }
+
+// > 0 when d is inside the circle through counter-clockwise a, b, c.
+double inCircle(dvec2 a, dvec2 b, dvec2 c, dvec2 d) {
+ const double adx = a.x - d.x, ady = a.y - d.y, bdx = b.x - d.x, bdy = b.y - d.y, cdx = c.x - d.x, cdy = c.y - d.y;
+ const double ad = adx * adx + ady * ady, bd = bdx * bdx + bdy * bdy, cd = cdx * cdx + cdy * cdy;
+ return adx * (bdy * cd - bd * cdy) - ady * (bdx * cd - bd * cdx) + ad * (bdx * cdy - bdy * cdx);
+}
+
+bool insidePolygon(const std::vector<dvec2>& poly, dvec2 p) {
+ bool in = false;
+ for (size_t i = 0, j = poly.size() - 1; i < poly.size(); j = i++) {
+ const dvec2 a = poly[i], b = poly[j];
+ if ((a.y > p.y) != (b.y > p.y) && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x) in = !in;
+ }
+ return in;
+}
+
+double segDist2(dvec2 p, dvec2 a, dvec2 b) {
+ const dvec2 d = b - a;
+ const double l = glm::dot(d, d);
+ const double t = l > 0 ? std::clamp(glm::dot(p - a, d) / l, 0.0, 1.0) : 0.0;
+ const dvec2 q = a + d * t - p;
+ return glm::dot(q, q);
+}
+
+uint64_t key(uint32_t a, uint32_t b) { return uint64_t(std::min(a, b)) << 32 | std::max(a, b); }
+
+// --- Bowyer-Watson ---
+
+struct Delaunay {
+ struct Tri {
+ int v[3];
+ int n[3]; // across the edge opposite v[i] (v[i+1] -> v[i+2]); -1 = none
+ bool alive;
+ };
+ std::vector<dvec2> P;
+ std::vector<Tri> T;
+ std::vector<int> stamp;
+ int mark = 0, last = 0;
+
+ void init(dvec2 lo, dvec2 hi) {
+ const dvec2 c = (lo + hi) * 0.5;
+ const double r = std::max(hi.x - lo.x, hi.y - lo.y) * 20.0 + 1.0;
+ P = {c + dvec2(-r, -r), c + dvec2(r, -r), c + dvec2(0, r)};
+ T = {{{0, 1, 2}, {-1, -1, -1}, true}};
+ stamp = {0};
+ }
+
+ int locate(dvec2 p) {
+ int t = (last >= 0 && last < int(T.size()) && T[size_t(last)].alive) ? last : -1;
+ if (t < 0)
+ for (size_t i = 0; i < T.size(); ++i)
+ if (T[i].alive) {
+ t = int(i);
+ break;
+ }
+ for (size_t steps = 0; steps < T.size() + 16; ++steps) {
+ const Tri& tr = T[size_t(t)];
+ int next = -1;
+ for (int i = 0; i < 3; ++i) {
+ const dvec2 a = P[size_t(tr.v[(i + 1) % 3])], b = P[size_t(tr.v[(i + 2) % 3])];
+ if (orient(a, b, p) < 0 && tr.n[i] >= 0) {
+ next = tr.n[i];
+ break;
+ }
+ }
+ if (next < 0) return t;
+ t = next;
+ }
+ for (size_t i = 0; i < T.size(); ++i) { // (a walk that cycles: scan)
+ const Tri& tr = T[i];
+ if (tr.alive && orient(P[size_t(tr.v[0])], P[size_t(tr.v[1])], p) >= 0 &&
+ orient(P[size_t(tr.v[1])], P[size_t(tr.v[2])], p) >= 0 && orient(P[size_t(tr.v[2])], P[size_t(tr.v[0])], p) >= 0)
+ return int(i);
+ }
+ return t;
+ }
+
+ bool bad(int t, dvec2 p) const {
+ const Tri& tr = T[size_t(t)];
+ return inCircle(P[size_t(tr.v[0])], P[size_t(tr.v[1])], P[size_t(tr.v[2])], p) > 0;
+ }
+
+ void insert(dvec2 p) {
+ const int pi = int(P.size());
+ P.push_back(p);
+ const int t0 = locate(p);
+ ++mark;
+ std::vector<int> cavity{t0}, stack{t0};
+ stamp[size_t(t0)] = mark;
+ struct Boundary {
+ int a, b, outside;
+ };
+ std::vector<Boundary> border;
+ while (!stack.empty()) {
+ const int t = stack.back();
+ stack.pop_back();
+ for (int i = 0; i < 3; ++i) {
+ const int nb = T[size_t(t)].n[i];
+ const int a = T[size_t(t)].v[(i + 1) % 3], b = T[size_t(t)].v[(i + 2) % 3];
+ if (nb >= 0 && stamp[size_t(nb)] == mark) continue;
+ if (nb >= 0 && bad(nb, p)) {
+ stamp[size_t(nb)] = mark;
+ cavity.push_back(nb);
+ stack.push_back(nb);
+ } else {
+ border.push_back({a, b, nb});
+ }
+ }
+ }
+ // Edges between two cavity triangles were skipped; border edges whose outside joined the cavity later
+ // are interior after all.
+ border.erase(std::remove_if(border.begin(), border.end(),
+ [&](const Boundary& e) { return e.outside >= 0 && stamp[size_t(e.outside)] == mark; }),
+ border.end());
+ for (int t : cavity) T[size_t(t)].alive = false;
+ std::vector<int> made;
+ made.reserve(border.size());
+ size_t reuse = 0;
+ for (const Boundary& e : border) {
+ int id;
+ if (reuse < cavity.size()) id = cavity[reuse++];
+ else {
+ id = int(T.size());
+ T.push_back({});
+ stamp.push_back(0);
+ }
+ T[size_t(id)] = {{e.a, e.b, pi}, {-1, -1, e.outside}, true};
+ if (e.outside >= 0) {
+ Tri& o = T[size_t(e.outside)];
+ for (int j = 0; j < 3; ++j)
+ if (o.v[(j + 1) % 3] == e.b && o.v[(j + 2) % 3] == e.a) o.n[j] = id;
+ }
+ made.push_back(id);
+ }
+ for (int id : made) {
+ Tri& t = T[size_t(id)];
+ for (int other : made) {
+ if (other == id) continue;
+ const Tri& o = T[size_t(other)];
+ if (o.v[0] == t.v[1]) t.n[0] = other; // edge (b, p) is the other's (p, a') with a' = b
+ if (o.v[1] == t.v[0]) t.n[1] = other; // edge (p, a)
+ }
+ }
+ last = made.empty() ? 0 : made.front();
+ }
+};
+
+// --- Triangle soup with an edge map, for flips ---
+
+struct Soup {
+ std::vector<dvec2>* P = nullptr;
+ std::vector<glm::uvec3> tris;
+ std::unordered_map<uint64_t, std::array<int, 2>> edges;
+
+ void build() {
+ edges.clear();
+ edges.reserve(tris.size() * 2);
+ for (size_t t = 0; t < tris.size(); ++t)
+ for (int k = 0; k < 3; ++k) {
+ auto [it, fresh] = edges.try_emplace(key(tris[t][k], tris[t][(k + 1) % 3]), std::array<int, 2>{-1, -1});
+ (it->second[0] < 0 ? it->second[0] : it->second[1]) = int(t);
+ }
+ }
+ static uint32_t opposite(const glm::uvec3& t, uint32_t u, uint32_t v) {
+ for (int k = 0; k < 3; ++k)
+ if (t[k] != u && t[k] != v) return t[k];
+ return t[0];
+ }
+ void replace(uint64_t e, int from, int to) {
+ auto it = edges.find(e);
+ if (it == edges.end()) return;
+ for (int& x : it->second)
+ if (x == from) {
+ x = to;
+ return;
+ }
+ }
+ // Flips edge (u, v) shared by two triangles when their quad is strictly convex.
+ bool flip(uint32_t u, uint32_t v) {
+ auto it = edges.find(key(u, v));
+ if (it == edges.end() || it->second[0] < 0 || it->second[1] < 0) return false;
+ int t1 = it->second[0], t2 = it->second[1];
+ // t1 holds u -> v in its winding.
+ auto hasDirected = [&](int t, uint32_t a, uint32_t b) {
+ for (int k = 0; k < 3; ++k)
+ if (tris[size_t(t)][k] == a && tris[size_t(t)][(k + 1) % 3] == b) return true;
+ return false;
+ };
+ if (!hasDirected(t1, u, v)) std::swap(t1, t2);
+ if (!hasDirected(t1, u, v)) return false;
+ const uint32_t x = opposite(tris[size_t(t1)], u, v), y = opposite(tris[size_t(t2)], u, v);
+ const std::vector<dvec2>& p = *P;
+ if (!(orient(p[x], p[u], p[y]) > 0 && orient(p[y], p[v], p[x]) > 0)) return false;
+ tris[size_t(t1)] = {x, u, y};
+ tris[size_t(t2)] = {y, v, x};
+ edges.erase(it);
+ edges[key(x, y)] = {t1, t2};
+ replace(key(u, y), t2, t1);
+ replace(key(v, x), t1, t2);
+ return true;
+ }
+ bool has(uint32_t u, uint32_t v) const { return edges.count(key(u, v)) != 0; }
+};
+
+bool properCross(dvec2 a, dvec2 b, dvec2 c, dvec2 d) {
+ const double d1 = orient(a, b, c), d2 = orient(a, b, d), d3 = orient(c, d, a), d4 = orient(c, d, b);
+ return ((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && ((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0));
+}
+
+// Makes segment (a, b) an edge by flipping the edges crossing it (Sloan 1993). False when it can't.
+bool recover(Soup& s, uint32_t a, uint32_t b) {
+ const std::vector<dvec2>& P = *s.P;
+ for (int round = 0; round < 400 && !s.has(a, b); ++round) {
+ bool flipped = false;
+ std::vector<uint64_t> crossing;
+ for (const auto& [k, ts] : s.edges) {
+ const uint32_t u = uint32_t(k >> 32), v = uint32_t(k & 0xffffffffu);
+ if (u == a || u == b || v == a || v == b) continue;
+ if (properCross(P[a], P[b], P[u], P[v])) crossing.push_back(k);
+ }
+ std::sort(crossing.begin(), crossing.end());
+ for (uint64_t k : crossing)
+ if (s.flip(uint32_t(k >> 32), uint32_t(k & 0xffffffffu))) flipped = true;
+ if (!flipped) return false;
+ }
+ return s.has(a, b);
+}
+
+void lawson(Soup& s, const std::unordered_map<uint64_t, bool>& fixed) {
+ const std::vector<dvec2>& P = *s.P;
+ std::vector<uint64_t> queue;
+ queue.reserve(s.edges.size());
+ for (const auto& [k, ts] : s.edges) queue.push_back(k);
+ std::sort(queue.begin(), queue.end());
+ size_t budget = queue.size() * 20 + 100;
+ while (!queue.empty() && budget--) {
+ const uint64_t k = queue.back();
+ queue.pop_back();
+ if (fixed.count(k)) continue;
+ auto it = s.edges.find(k);
+ if (it == s.edges.end() || it->second[0] < 0 || it->second[1] < 0) continue;
+ const uint32_t u = uint32_t(k >> 32), v = uint32_t(k & 0xffffffffu);
+ const glm::uvec3 t1 = s.tris[size_t(it->second[0])], t2 = s.tris[size_t(it->second[1])];
+ const uint32_t y = Soup::opposite(t2, u, v);
+ if (!(inCircle(P[t1.x], P[t1.y], P[t1.z], P[y]) > 1e-9)) continue;
+ const uint32_t x = Soup::opposite(t1, u, v);
+ if (s.flip(u, v)) {
+ for (uint64_t e : {key(x, u), key(u, y), key(y, v), key(v, x)}) queue.push_back(e);
+ }
+ }
+}
+
+// One panel's outline samples.
+struct EdgeSamples {
+ std::vector<float> t; // along the edge, from 0 (its start); its end is the next edge's first sample
+ std::vector<uint32_t> index; // vertex (panel-local)
+};
+
+} // namespace
+
+bool triangulatePattern(const Pattern& pat, GarmentMesh& out, std::string& error) {
+ out = {};
+ const double h = std::clamp(double(pat.particleDistance), 1.0, 500.0);
+ if (pat.panels.empty()) {
+ error = "The pattern has no panels";
+ return false;
+ }
+ for (const Panel& p : pat.panels) {
+ if (!validPanel(p, error)) return false;
+ if (panelArea(p) < 0.0f) {
+ error = p.name + " is drawn clockwise";
+ return false;
+ }
+ }
+ // Points per seam: the longer side at h, both sides the same.
+ std::vector<int> seamCount(pat.seams.size());
+ for (size_t s = 0; s < pat.seams.size(); ++s) {
+ const Seam& sm = pat.seams[s];
+ if (sm.a.panel >= pat.panels.size() || sm.b.panel >= pat.panels.size()) {
+ error = "A seam sews a panel that is gone";
+ return false;
+ }
+ const double l = std::max(seamSideLength(pat, sm.a), seamSideLength(pat, sm.b));
+ seamCount[s] = std::max(1, int(std::lround(l / h)));
+ }
+ // Each seam side's samples (global vertex ids), from t0 to t1.
+ std::vector<std::array<std::vector<uint32_t>, 2>> seamVerts(pat.seams.size());
+ // Vertex count guard: a 20 mm pattern stays well under this; tiny particle distances on big panels don't.
+ double estimate = 0.0;
+ for (const Panel& p : pat.panels) estimate += double(panelArea(p)) / (0.866 * h * h) + double(perimeter(p)) / h;
+ if (estimate > 2.0e6) {
+ error = "The particle distance is too small for panels this big (over 2 million particles)";
+ return false;
+ }
+
+ for (uint32_t pi = 0; pi < pat.panels.size(); ++pi) {
+ const Panel& p = pat.panels[pi];
+ const uint32_t ne = uint32_t(p.points.size());
+ const uint32_t base = uint32_t(out.flat.size());
+ out.panelFirstVertex.push_back(base);
+ out.panelFirstTriangle.push_back(uint32_t(out.triangles.size()));
+ std::vector<dvec2> P; // panel-local vertices (outline first)
+ std::vector<EdgeSamples> samples(ne);
+ // Seam ends on each edge split it into pieces; a piece that is a seam side takes the seam's count.
+ for (uint32_t e = 0; e < ne; ++e) {
+ std::vector<float> cuts{0.0f, 1.0f};
+ for (const Seam& sm : pat.seams)
+ for (const SeamSide* sd : {&sm.a, &sm.b})
+ if (sd->panel == pi && sd->edge == e) {
+ cuts.push_back(sd->t0);
+ cuts.push_back(sd->t1);
+ }
+ std::sort(cuts.begin(), cuts.end());
+ cuts.erase(std::unique(cuts.begin(), cuts.end(), [](float a, float b) { return std::abs(a - b) < 1e-4f; }),
+ cuts.end());
+ const float len = edgeLength(p, e);
+ for (size_t c = 0; c + 1 < cuts.size(); ++c) {
+ const float a = cuts[c], b = cuts[c + 1];
+ int n = std::max(1, int(std::lround(double(len) * double(b - a) / h)));
+ for (size_t s = 0; s < pat.seams.size(); ++s)
+ for (const SeamSide* sd : {&pat.seams[s].a, &pat.seams[s].b})
+ if (sd->panel == pi && sd->edge == e && std::abs(sd->t0 - a) < 1e-4f && std::abs(sd->t1 - b) < 1e-4f)
+ n = seamCount[s];
+ for (int k = 0; k < n; ++k) {
+ const float t = a + (b - a) * float(k) / float(n);
+ samples[e].t.push_back(t);
+ samples[e].index.push_back(uint32_t(P.size()));
+ P.push_back(dvec2(edgePoint(p, e, t)));
+ }
+ }
+ }
+ const uint32_t nb = uint32_t(P.size()); // outline vertices: 0 .. nb-1, in order around the panel
+ std::vector<dvec2> poly(P.begin(), P.end());
+ // Fill: a triangular lattice along the grain.
+ const double g = double(p.grainDegrees) * 3.14159265358979 / 180.0;
+ const dvec2 e1 = h * dvec2(std::cos(g), std::sin(g)), e2 = h * dvec2(std::cos(g + 1.0471975512), std::sin(g + 1.0471975512));
+ dvec2 lo(1e30), hi(-1e30);
+ for (dvec2 q : poly) {
+ lo = glm::min(lo, q);
+ hi = glm::max(hi, q);
+ }
+ // Lattice coordinates (i, j) covering the bounding box: solve q = o + i e1 + j e2 at the corners.
+ const dvec2 o = lo;
+ const double det = e1.x * e2.y - e1.y * e2.x;
+ double imin = 1e30, imax = -1e30, jmin = 1e30, jmax = -1e30;
+ for (dvec2 c : {lo, hi, dvec2(lo.x, hi.y), dvec2(hi.x, lo.y)}) {
+ const dvec2 d = c - o;
+ const double i = (d.x * e2.y - d.y * e2.x) / det, j = (e1.x * d.y - e1.y * d.x) / det;
+ imin = std::min(imin, i);
+ imax = std::max(imax, i);
+ jmin = std::min(jmin, j);
+ jmax = std::max(jmax, j);
+ }
+ // A grid over the outline's segments to find the near ones quickly.
+ const double cell = 2.0 * h;
+ const int gx = std::max(1, int(std::ceil((hi.x - lo.x) / cell)) + 1), gy = std::max(1, int(std::ceil((hi.y - lo.y) / cell)) + 1);
+ std::vector<std::vector<uint32_t>> grid(size_t(gx) * size_t(gy));
+ for (uint32_t s = 0; s < nb; ++s) {
+ const dvec2 a = poly[s], b = poly[(s + 1) % nb];
+ const int x0 = std::clamp(int((std::min(a.x, b.x) - lo.x) / cell), 0, gx - 1), x1 = std::clamp(int((std::max(a.x, b.x) - lo.x) / cell), 0, gx - 1);
+ const int y0 = std::clamp(int((std::min(a.y, b.y) - lo.y) / cell), 0, gy - 1), y1 = std::clamp(int((std::max(a.y, b.y) - lo.y) / cell), 0, gy - 1);
+ for (int y = y0; y <= y1; ++y)
+ for (int x = x0; x <= x1; ++x) grid[size_t(y) * size_t(gx) + size_t(x)].push_back(s);
+ }
+ const double keep2 = 0.55 * 0.55 * h * h;
+ for (long j = long(std::floor(jmin)); j <= long(std::ceil(jmax)); ++j)
+ for (long i = long(std::floor(imin)); i <= long(std::ceil(imax)); ++i) {
+ const dvec2 q = o + double(i) * e1 + double(j) * e2;
+ if (q.x < lo.x || q.x > hi.x || q.y < lo.y || q.y > hi.y || !insidePolygon(poly, q)) continue;
+ const int cx = std::clamp(int((q.x - lo.x) / cell), 0, gx - 1), cy = std::clamp(int((q.y - lo.y) / cell), 0, gy - 1);
+ bool ok = true;
+ for (int y = std::max(0, cy - 1); y <= std::min(gy - 1, cy + 1) && ok; ++y)
+ for (int x = std::max(0, cx - 1); x <= std::min(gx - 1, cx + 1) && ok; ++x)
+ for (uint32_t s : grid[size_t(y) * size_t(gx) + size_t(x)]) {
+ const dvec2 a = poly[s], b = poly[(s + 1) % nb];
+ const dvec2 m = 0.5 * (a + b);
+ const double r2 = 0.25 * glm::dot(b - a, b - a) * 1.1;
+ if (segDist2(q, a, b) < keep2 || glm::dot(q - m, q - m) < r2) {
+ ok = false;
+ break;
+ }
+ }
+ if (ok) P.push_back(q);
+ }
+ // Delaunay, inserting in a snake order over coarse cells (short walks).
+ Delaunay dt;
+ dt.init(lo, hi);
+ std::vector<uint32_t> order(P.size());
+ for (uint32_t k = 0; k < order.size(); ++k) order[k] = k;
+ const double oc = 8.0 * h;
+ std::sort(order.begin(), order.end(), [&](uint32_t a, uint32_t b) {
+ const long ra = long((P[a].y - lo.y) / oc), rb = long((P[b].y - lo.y) / oc);
+ if (ra != rb) return ra < rb;
+ const double xa = (ra & 1) ? -P[a].x : P[a].x, xb = (rb & 1) ? -P[b].x : P[b].x;
+ return xa < xb;
+ });
+ std::vector<int> dtIndex(P.size());
+ for (uint32_t k : order) {
+ dtIndex[k] = int(dt.P.size());
+ dt.insert(P[k]);
+ }
+ std::vector<uint32_t> back(dt.P.size(), ~0u);
+ for (uint32_t k = 0; k < P.size(); ++k) back[size_t(dtIndex[k])] = k;
+ Soup soup;
+ soup.P = &P;
+ for (const auto& t : dt.T) {
+ if (!t.alive || t.v[0] < 3 || t.v[1] < 3 || t.v[2] < 3) continue;
+ soup.tris.push_back({back[size_t(t.v[0])], back[size_t(t.v[1])], back[size_t(t.v[2])]});
+ }
+ soup.build();
+ std::unordered_map<uint64_t, bool> fixedEdges;
+ for (uint32_t s = 0; s < nb; ++s) {
+ const uint32_t a = s, b = (s + 1) % nb;
+ fixedEdges[key(a, b)] = true;
+ if (!soup.has(a, b) && !recover(soup, a, b)) {
+ error = p.name + ": could not triangulate the outline (try a larger particle distance)";
+ return false;
+ }
+ }
+ // Drop what's outside the outline.
+ std::vector<glm::uvec3> inside;
+ for (const glm::uvec3& t : soup.tris)
+ if (insidePolygon(poly, (P[t.x] + P[t.y] + P[t.z]) / 3.0)) inside.push_back(t);
+ soup.tris = std::move(inside);
+ soup.build();
+ lawson(soup, fixedEdges);
+ // Smooth the inside points (never folding a triangle), then flip back to Delaunay.
+ std::vector<std::vector<uint32_t>> vt(P.size());
+ for (uint32_t t = 0; t < soup.tris.size(); ++t)
+ for (int k = 0; k < 3; ++k) vt[soup.tris[t][k]].push_back(t);
+ for (int pass = 0; pass < 4; ++pass) {
+ for (uint32_t v = nb; v < P.size(); ++v) {
+ if (vt[v].empty()) continue;
+ dvec2 sum(0.0);
+ int n = 0;
+ for (uint32_t t : vt[v])
+ for (int k = 0; k < 3; ++k)
+ if (soup.tris[t][k] != v) {
+ sum += P[soup.tris[t][k]];
+ ++n;
+ }
+ const dvec2 old = P[v];
+ P[v] = glm::mix(old, sum / double(n), 0.6);
+ for (uint32_t t : vt[v]) {
+ const glm::uvec3 tr = soup.tris[t];
+ if (orient(P[tr.x], P[tr.y], P[tr.z]) < 0.05 * h * h) {
+ P[v] = old;
+ break;
+ }
+ }
+ }
+ lawson(soup, fixedEdges);
+ for (auto& l : vt) l.clear();
+ for (uint32_t t = 0; t < soup.tris.size(); ++t)
+ for (int k = 0; k < 3; ++k) vt[soup.tris[t][k]].push_back(t);
+ }
+ // Points the triangulation didn't use (none in practice) are kept so indices stay simple.
+ for (uint32_t v = 0; v < P.size(); ++v) {
+ out.flat.push_back(glm::vec2(P[v]));
+ out.panelOf.push_back(pi);
+ out.border.push_back(v < nb ? 1 : 0);
+ }
+ for (const glm::uvec3& t : soup.tris) out.triangles.push_back(t + glm::uvec3(base));
+ // This panel's seam sides.
+ for (size_t s = 0; s < pat.seams.size(); ++s)
+ for (int side = 0; side < 2; ++side) {
+ const SeamSide& sd = side == 0 ? pat.seams[s].a : pat.seams[s].b;
+ if (sd.panel != pi) continue;
+ std::vector<uint32_t>& list = seamVerts[s][size_t(side)];
+ const EdgeSamples& es = samples[sd.edge];
+ for (size_t k = 0; k < es.t.size(); ++k)
+ if (es.t[k] >= sd.t0 - 1e-4f && es.t[k] <= sd.t1 + 1e-4f) list.push_back(base + es.index[k]);
+ if (sd.t1 > 1.0f - 1e-4f) list.push_back(base + samples[(sd.edge + 1) % ne].index.front());
+ }
+ }
+ out.panelFirstVertex.push_back(uint32_t(out.flat.size()));
+ out.panelFirstTriangle.push_back(uint32_t(out.triangles.size()));
+ for (size_t s = 0; s < pat.seams.size(); ++s) {
+ const std::vector<uint32_t>& a = seamVerts[s][0];
+ const std::vector<uint32_t>& b = seamVerts[s][1];
+ if (a.size() != b.size() || a.empty()) {
+ error = "Seam " + std::to_string(s + 1) + " could not be matched";
+ return false;
+ }
+ const size_t n = a.size();
+ for (size_t k = 0; k < n; ++k) out.links.push_back({a[k], pat.seams[s].flipped ? b[k] : b[n - 1 - k]});
+ }
+ return true;
+}
+
+MeshQuality meshQuality(const GarmentMesh& m, float h) {
+ MeshQuality q{1e30f, 0.0f, 180.0f};
+ if (m.triangles.empty()) return {};
+ for (const glm::uvec3& t : m.triangles)
+ for (int k = 0; k < 3; ++k) {
+ const glm::vec2 a = m.flat[t[k]], b = m.flat[t[(k + 1) % 3]], c = m.flat[t[(k + 2) % 3]];
+ const float l = glm::length(b - a) / h;
+ q.minEdge = std::min(q.minEdge, l);
+ q.maxEdge = std::max(q.maxEdge, l);
+ const glm::vec2 u = b - a, v = c - a;
+ const float cosA = glm::dot(u, v) / std::max(1e-12f, glm::length(u) * glm::length(v));
+ q.minAngle = std::min(q.minAngle, std::acos(std::clamp(cosA, -1.0f, 1.0f)) * 57.2957795f);
+ }
+ return q;
+}
+
+} // namespace sf::garment
diff --git a/tests/test_garment.cpp b/tests/test_garment.cpp
new file mode 100644
index 00000000..6258a0c4
--- /dev/null
+++ b/tests/test_garment.cpp
@@ -0,0 +1,443 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Garments (core/Garment.h): pattern panels, even triangulation, seams that weld into one consistently oriented
+// garment (a T-shirt sewn from its template is a single surface with exactly four openings: hem, neck, two
+// sleeves), the arrangement around a body, project and file round trips (SVG, DXF), the SVG reader against
+// hostile input, and the garment_* commands.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/Garment.h"
+#include "core/Primitives.h"
+#include "core/Project.h"
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <fstream>
+#include <map>
+#include <random>
+#include <set>
+#include <sstream>
+
+using namespace sf;
+using namespace sf::garment;
+
+namespace {
+
+float meshArea(const GarmentMesh& m, uint32_t panel) {
+ double a = 0.0;
+ for (uint32_t t = m.panelFirstTriangle[panel]; t < m.panelFirstTriangle[panel + 1]; ++t) {
+ const glm::uvec3 tri = m.triangles[t];
+ const glm::vec2 u = m.flat[tri.y] - m.flat[tri.x], v = m.flat[tri.z] - m.flat[tri.x];
+ a += 0.5 * double(u.x * v.y - u.y * v.x);
+ }
+ return float(a);
+}
+
+// Boundary loops and orientation of a closed-up mesh: every edge used once (border) or twice in opposite
+// directions (consistently oriented); edges used twice the same way or more than twice break it.
+struct Topology {
+ int borderLoops = 0;
+ bool consistent = true;
+ bool manifold = true;
+};
+Topology topology(const Mesh& m) {
+ std::map<std::pair<uint32_t, uint32_t>, int> directed;
+ for (const glm::uvec3& t : m.triangles)
+ for (int k = 0; k < 3; ++k) ++directed[{t[k], t[(k + 1) % 3]}];
+ Topology r;
+ std::map<uint32_t, uint32_t> next; // border: a -> b
+ for (const auto& [e, n] : directed) {
+ if (n > 1) r.consistent = false;
+ const auto back = directed.find({e.second, e.first});
+ const int other = back == directed.end() ? 0 : back->second;
+ if (n + other > 2) r.manifold = false;
+ if (other == 0) {
+ if (next.count(e.first)) r.manifold = false;
+ next[e.first] = e.second;
+ }
+ }
+ std::set<uint32_t> seen;
+ for (const auto& [a, b] : next) {
+ if (seen.count(a)) continue;
+ ++r.borderLoops;
+ uint32_t v = a;
+ for (size_t guard = 0; guard <= next.size() && !seen.count(v); ++guard) {
+ seen.insert(v);
+ const auto it = next.find(v);
+ if (it == next.end()) break;
+ v = it->second;
+ }
+ }
+ return r;
+}
+
+// A w x h x d box centred on the origin (finely divided, so the body analysis has vertices to read).
+Mesh makeBox(float w, float h, float d) {
+ Mesh m = makeCube(12, 2.0f);
+ AABB b;
+ for (const glm::vec3& p : m.positions) b.expand(p);
+ for (glm::vec3& p : m.positions) p = (p - b.center()) / b.extent() * glm::vec3(w, h, d);
+ m.rebuildTopology();
+ return m;
+}
+
+std::string readAll(const std::string& path) {
+ std::ifstream f(path, std::ios::binary);
+ std::stringstream s;
+ s << f.rdbuf();
+ return s.str();
+}
+
+} // namespace
+
+TEST(garment_tshirt_template_is_valid_and_matched) {
+ const Pattern pat = tshirtPattern();
+ CHECK(pat.panels.size() == 4);
+ CHECK(pat.seams.size() == 10);
+ CHECK(patternProblems(pat).empty());
+ for (const Seam& s : pat.seams) {
+ const SeamCheck c = checkSeam(pat, s);
+ CHECK(c.lengthsMatch);
+ CHECK(!c.twisted);
+ }
+ for (const Panel& p : pat.panels) CHECK(panelArea(p) > 0.0f);
+ // Real size: the front is about half the chest plus ease wide and 70 cm long.
+ const glm::vec2 size = panelMax(pat.panels[0]) - panelMin(pat.panels[0]);
+ CHECK(std::abs(size.x - 520.0f) < 1.0f && std::abs(size.y - 700.0f) < 1.0f);
+}
+
+TEST(garment_triangulation_is_even_and_covers_each_panel) {
+ Pattern pat = tshirtPattern();
+ for (float h : {10.0f, 15.0f, 25.0f}) {
+ pat.particleDistance = h;
+ GarmentMesh m;
+ std::string error;
+ CHECK(triangulatePattern(pat, m, error));
+ CHECK(error.empty());
+ // Exactly the outline's area (the outline is sampled as chords: curves lose a sliver).
+ for (uint32_t p = 0; p < pat.panels.size(); ++p) {
+ const float want = panelArea(pat.panels[p]), got = meshArea(m, p);
+ CHECK(std::abs(got - want) < 0.01f * want);
+ }
+ const MeshQuality q = meshQuality(m, h);
+ CHECK(q.minAngle > 20.0f);
+ CHECK(q.minEdge > 0.4f && q.maxEdge < 1.8f);
+ // About one particle per equilateral triangle pair: area / (0.866 h^2).
+ double area = 0.0;
+ for (const Panel& p : pat.panels) area += panelArea(p);
+ const double expect = area / (0.866 * h * h);
+ CHECK(double(m.vertexCount()) > 0.8 * expect && double(m.vertexCount()) < 1.4 * expect);
+ // Every triangle counter-clockwise (faces out once placed).
+ bool ccw = true;
+ for (const glm::uvec3& t : m.triangles) {
+ const glm::vec2 u = m.flat[t.y] - m.flat[t.x], v = m.flat[t.z] - m.flat[t.x];
+ ccw = ccw && u.x * v.y - u.y * v.x > 0.0f;
+ }
+ CHECK(ccw);
+ }
+}
+
+TEST(garment_sewn_tshirt_welds_into_one_oriented_surface) {
+ const Pattern pat = tshirtPattern();
+ GarmentMesh m;
+ std::string error;
+ CHECK(triangulatePattern(pat, m, error));
+ // One link per point along each seam, both sides the same count.
+ CHECK(!m.links.empty());
+ std::vector<glm::vec3> placed, rest;
+ placePattern(pat, m, defaultBody(), placed, rest);
+ const Mesh flat = garmentToMesh(m, placed, 0.0f);
+ CHECK(flat.triangleCount() == m.triangles.size());
+ const Topology t = topology(flat);
+ CHECK(t.manifold);
+ CHECK(t.consistent); // seams sewn the right way round: no panel turned over
+ CHECK(t.borderLoops == 4); // hem, neck, two sleeve hems
+ CHECK(flat.uvs.size() == flat.triangleCount() * 3);
+ bool inUnit = true;
+ for (glm::vec2 uv : flat.uvs) inUnit = inUnit && uv.x >= 0 && uv.x <= 1 && uv.y >= 0 && uv.y <= 1;
+ CHECK(inUnit);
+ std::set<uint32_t> groups(flat.facegroups.begin(), flat.facegroups.end());
+ CHECK(groups == std::set<uint32_t>({1, 2, 3, 4}));
+ // Thickened: closed (no border at all) and still consistently oriented.
+ const Mesh thick = garmentToMesh(m, placed, 2.0f);
+ const Topology tt = topology(thick);
+ CHECK(tt.manifold && tt.consistent && tt.borderLoops == 0);
+ CHECK(thick.vertexCount() == 2 * flat.vertexCount());
+}
+
+TEST(garment_flipped_seam_is_reported_and_twists) {
+ Pattern pat = tshirtPattern();
+ pat.seams[0].flipped = true;
+ CHECK(checkSeam(pat, pat.seams[0]).twisted);
+ CHECK(!patternProblems(pat).empty());
+ GarmentMesh m;
+ std::string error;
+ CHECK(triangulatePattern(pat, m, error));
+ std::vector<glm::vec3> placed, rest;
+ placePattern(pat, m, defaultBody(), placed, rest);
+ CHECK(!topology(garmentToMesh(m, placed, 0.0f)).consistent);
+}
+
+TEST(garment_panels_are_placed_around_the_body_facing_out) {
+ const Pattern pat = tshirtPattern();
+ GarmentMesh m;
+ std::string error;
+ CHECK(triangulatePattern(pat, m, error));
+ // A capsule-ish body: a tall box torso with arms out (T pose), 1.75 m.
+ Mesh body = makeBox(0.34f, 0.6f, 0.22f);
+ for (glm::vec3& p : body.positions) p += glm::vec3(0, 1.1f, 0);
+ Mesh arms = makeBox(1.4f, 0.1f, 0.1f);
+ const size_t base = body.positions.size();
+ for (glm::vec3 p : arms.positions) body.positions.push_back(p + glm::vec3(0, 1.36f, 0));
+ for (glm::uvec3 t : arms.triangles) body.triangles.push_back(t + glm::uvec3(uint32_t(base)));
+ Mesh legs = makeBox(0.3f, 0.8f, 0.2f);
+ const size_t base2 = body.positions.size();
+ for (glm::vec3 p : legs.positions) body.positions.push_back(p + glm::vec3(0, 0.4f, 0));
+ for (glm::uvec3 t : legs.triangles) body.triangles.push_back(t + glm::uvec3(uint32_t(base2)));
+ body.rebuildTopology();
+ const BodyFrame f = analyzeBody(body);
+ CHECK(f.arms);
+ CHECK(std::abs(f.torsoHalfWidth - 0.17f) < 0.03f);
+ CHECK(f.torsoFrontZ > 0.09f && f.torsoBackZ < -0.09f);
+ CHECK(f.leftArmDir.x > 0.9f && f.rightArmDir.x < -0.9f);
+ std::vector<glm::vec3> placed, rest;
+ placePattern(pat, m, f, placed, rest);
+ CHECK(placed.size() == m.vertexCount() && rest.size() == m.vertexCount());
+ // Front in front of the chest, back behind it, sleeves out along the arms.
+ auto mean = [&](uint32_t panel) {
+ glm::dvec3 s(0.0);
+ for (uint32_t v = m.panelFirstVertex[panel]; v < m.panelFirstVertex[panel + 1]; ++v) s += glm::dvec3(placed[v]);
+ return glm::vec3(s / double(m.panelFirstVertex[panel + 1] - m.panelFirstVertex[panel]));
+ };
+ // (wrapped half-way round, so their middles are off the chest and back, their sides beside the torso)
+ auto extremeZ = [&](uint32_t panel, bool front) {
+ float z = front ? -1e9f : 1e9f;
+ for (uint32_t v = m.panelFirstVertex[panel]; v < m.panelFirstVertex[panel + 1]; ++v)
+ z = front ? std::max(z, placed[v].z) : std::min(z, placed[v].z);
+ return z;
+ };
+ CHECK(mean(0).z > f.centerZ && extremeZ(0, true) > f.torsoFrontZ + 0.02f);
+ CHECK(mean(1).z < f.centerZ && extremeZ(1, false) < f.torsoBackZ - 0.02f);
+ CHECK(mean(2).x > f.torsoHalfWidth && mean(3).x < -f.torsoHalfWidth);
+ // Triangles face away from the body: outward from the torso axis or the arm's axis.
+ int out = 0, total = 0;
+ for (uint32_t t = 0; t < m.triangles.size(); ++t) {
+ const glm::uvec3 tri = m.triangles[t];
+ const glm::vec3 a = placed[tri.x], b = placed[tri.y], c = placed[tri.z];
+ const glm::vec3 n = glm::cross(b - a, c - a), ctr = (a + b + c) / 3.0f;
+ const uint32_t panel = m.panelOf[tri.x];
+ glm::vec3 radial;
+ if (panel < 2) radial = glm::vec3(ctr.x - f.centerX, 0, ctr.z - f.centerZ);
+ else {
+ const glm::vec3 s = panel == 2 ? f.leftShoulder : f.rightShoulder;
+ const glm::vec3 d = panel == 2 ? f.leftArmDir : f.rightArmDir;
+ radial = (ctr - s) - glm::dot(ctr - s, d) * d;
+ }
+ out += glm::dot(n, radial) > 0.0f;
+ ++total;
+ }
+ CHECK(out > total * 95 / 100);
+ // The rest shape is the flat pattern, metres.
+ CHECK(std::abs(rest[0].x - m.flat[0].x * 0.001f) < 1e-6f && rest[0].z == 0.0f);
+}
+
+TEST(garment_pattern_round_trips_json_and_project) {
+ Pattern pat = tshirtPattern(1000.0f, 650.0f);
+ pat.particleDistance = 12.0f;
+ pat.fabric = "denim";
+ pat.panels[2].place.offset = {0.01f, -0.02f, 0.005f};
+ pat.seams[3].flipped = true;
+ Pattern back;
+ std::string error;
+ CHECK(patternFromJson(patternToJson(pat), back, error));
+ CHECK(patternToJson(back).dump() == patternToJson(pat).dump());
+ // In a project.
+ Document doc = makeDoc(makeIcosphere(2));
+ setDocumentPattern(doc, pat);
+ const std::string path = tempPath("garment_roundtrip.sfproj");
+ CHECK(saveProject(path, doc, error));
+ Document loaded;
+ CHECK(loadProject(path, loaded, error));
+ Pattern got;
+ CHECK(documentPattern(loaded, got));
+ CHECK(patternToJson(got).dump() == patternToJson(pat).dump());
+ std::remove(path.c_str());
+ // Hostile JSON: wrong types, huge counts, bad seams are refused or dropped, never crash.
+ Json j;
+ CHECK(Json::parse(R"({"panels":[{"name":"x","points":[0,0,1e30,0,0,5]},{"points":"no"},
+ {"name":"ok","points":[0,0,100,0,100,100,0,100],"curves":[[99,0,0,0,0]],"notches":[[-1,2]]}],
+ "seams":[{"a":[0,0,0,1],"b":[5,0,0,1]},{"a":[0,0,0.5,0.2],"b":[0,1,0,1]}]})",
+ j, error));
+ Pattern bad;
+ error.clear();
+ CHECK(patternFromJson(j, bad, error));
+ CHECK(bad.panels.size() == 1 && bad.panels[0].name == "ok" && bad.seams.empty());
+ CHECK(!error.empty());
+}
+
+TEST(garment_svg_round_trips_at_real_size) {
+ const Pattern pat = tshirtPattern();
+ const std::string svg = patternToSvg(pat);
+ CHECK(svg.find("mm\" height=") != std::string::npos);
+ CHECK(svg.find("class=\"cut\"") != std::string::npos && svg.find("class=\"notch\"") != std::string::npos);
+ std::vector<Panel> panels;
+ std::string error;
+ CHECK(panelsFromSvg(svg, panels, error) == 4);
+ CHECK(error.empty());
+ for (size_t i = 0; i < panels.size(); ++i) {
+ CHECK(panels[i].name == pat.panels[i].name);
+ CHECK(std::abs(panelArea(panels[i]) - panelArea(pat.panels[i])) < 0.002f * panelArea(pat.panels[i]));
+ CHECK(std::abs(perimeter(panels[i]) - perimeter(pat.panels[i])) < 1.0f);
+ CHECK(panels[i].points.size() == pat.panels[i].points.size());
+ }
+ const std::string dxf = patternToDxf(pat);
+ CHECK(dxf.find("$INSUNITS") != std::string::npos && dxf.find("POLYLINE") != std::string::npos);
+ CHECK(dxf.find("SEW") != std::string::npos && dxf.find("CUT") != std::string::npos);
+ CHECK(dxf.substr(dxf.size() - 4) == "EOF\n");
+}
+
+TEST(garment_svg_import_reads_units_transforms_and_shapes) {
+ // A 10 x 20 cm rectangle in a cm document, a translated triangle path (relative commands), a polygon in a
+ // scaled group, an open path (ignored) and a quadratic curve.
+ const std::string svg = R"svg(<?xml version="1.0"?>
+<!DOCTYPE svg [ <!ENTITY big "aaaaaaaaaaaaaaaaaaaa"> ]>
+<svg xmlns="http://www.w3.org/2000/svg" width="50cm" height="50cm" viewBox="0 0 50 50">
+ <!-- a comment with <rect x="0" y="0" width="1" height="1"/> inside -->
+ <rect id="Front" x="1" y="1" width="10" height="20"/>
+ <path id="tri" transform="translate(30 5)" d="m0,0 l10,0 l-5-8.66z"/>
+ <g transform="scale(2)"><polygon id="poly" points="1,30 6,30 6,35"/></g>
+ <path d="M0 0 L 5 5"/>
+ <path id="curve" d="M 20 40 Q 25 30 30 40 Z"/>
+</svg>)svg";
+ std::vector<Panel> panels;
+ std::string error;
+ CHECK(panelsFromSvg(svg, panels, error) == 4);
+ if (panels.size() != 4) {
+ std::printf(" svg import: %zu panels (%s)\n", panels.size(), error.c_str());
+ for (const Panel& p : panels) std::printf(" %s %zu points area %.1f\n", p.name.c_str(), p.points.size(), double(panelArea(p)));
+ return;
+ }
+ CHECK(panels[0].name == "Front");
+ CHECK(std::abs(panelArea(panels[0]) - 100.0f * 200.0f) < 1.0f); // mm^2
+ CHECK(std::abs(panelArea(panels[1]) - 0.5f * 100.0f * 86.6f) < 5.0f);
+ CHECK(std::abs(panelArea(panels[2]) - 0.5f * 100.0f * 100.0f) < 5.0f); // scaled 2x: 10 x 10 cm triangle
+ CHECK(std::any_of(panels[3].curves.begin(), panels[3].curves.end(), [](const EdgeCurve& c) { return c.curved; }));
+ for (const Panel& p : panels) CHECK(panelArea(p) > 0.0f); // counter-clockwise after the y flip
+ // px documents (no units): 96 per inch.
+ panels.clear();
+ CHECK(panelsFromSvg(R"(<svg width="200" height="200"><rect width="96" height="96"/></svg>)", panels, error) == 1);
+ CHECK(!panels.empty() && std::abs(panelArea(panels[0]) - 25.4f * 25.4f) < 0.5f);
+}
+
+TEST(garment_svg_reader_survives_hostile_input) {
+ std::vector<Panel> panels;
+ std::string error;
+ CHECK(panelsFromSvg("", panels, error) == 0);
+ CHECK(panelsFromSvg("<svg><path d=\"M 1e999 0 L 0 1e999 L 5 5 Z\"/></svg>", panels, error) == 0);
+ CHECK(panelsFromSvg("<svg><path d=\"M0 0 L" + std::string(100000, '9') + " 0 Z\"/></svg>", panels, error) == 0);
+ CHECK(panelsFromSvg(std::string(5u << 20, '<'), panels, error) == 0); // over 4 MB
+ // Mutations of a real pattern: random bytes changed, inserted, cut. Never a crash or a hang.
+ const std::string base = patternToSvg(tshirtPattern());
+ std::mt19937 rng(7);
+ const auto start = std::chrono::steady_clock::now();
+ for (int i = 0; i < 300; ++i) {
+ std::string s = base;
+ const int edits = 1 + int(rng() % 20);
+ for (int e = 0; e < edits; ++e) {
+ const size_t at = rng() % s.size();
+ switch (rng() % 3) {
+ case 0: s[at] = char(rng() % 256); break;
+ case 1: s.insert(at, 1, "<>\"'=-.eE0zZmMcC/"[rng() % 17]); break;
+ default: s.erase(at, std::min<size_t>(s.size() - at, rng() % 40)); break;
+ }
+ }
+ panels.clear();
+ panelsFromSvg(s, panels, error);
+ for (const Panel& p : panels) CHECK(validPanel(p, error));
+ }
+ CHECK(std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count() < timeLimit(20.0));
+}
+
+TEST(garment_edits_keep_seams_and_shapes) {
+ // Mirror twice: the same panel; area unchanged.
+ Pattern pat = tshirtPattern();
+ mirrorPanel(pat, 2);
+ CHECK(panelArea(pat.panels[2]) > 0.0f);
+ CHECK(patternProblems(pat).empty());
+ mirrorPanel(pat, 2);
+ std::string error;
+ CHECK(std::abs(panelArea(pat.panels[2]) - panelArea(tshirtPattern().panels[2])) < 1.0f);
+ CHECK(pat.seams.size() == 10);
+ // Unfold a half: a 100 x 300 half about its left edge (edge 4, from (0,300) down to (0,0)) doubles.
+ Pattern half;
+ half.panels.push_back(rectanglePanel("Front", 100.0f, 300.0f));
+ CHECK(unfoldPanel(half, 0, 3, error));
+ CHECK(std::abs(panelArea(half.panels[0]) - 2.0f * 100.0f * 300.0f) < 1.0f);
+ CHECK(half.panels[0].points.size() == 6); // the fold's two points stay as corners of the hem and top
+ CHECK(validPanel(half.panels[0], error));
+ // Split an edge under a seam end: the seam moves with its piece; removing a point drops seams on it.
+ Pattern s;
+ s.panels.push_back(rectanglePanel("A", 100.0f, 100.0f));
+ s.panels.push_back(rectanglePanel("B", 100.0f, 100.0f, {200.0f, 0.0f}));
+ CHECK(addSeam(s, {{0, 1, 0.0f, 0.5f}, {1, 3, 0.5f, 1.0f}, false}, error));
+ CHECK(!addSeam(s, {{0, 1, 0.25f, 0.75f}, {1, 1, 0.0f, 1.0f}, false}, error)); // overlaps
+ splitEdge(s, 0, 1, 0.5f);
+ CHECK(s.panels[0].points.size() == 5 && s.seams.size() == 1);
+ CHECK(s.seams[0].a.edge == 1 && std::abs(s.seams[0].a.t1 - 1.0f) < 1e-4f);
+ CHECK(std::abs(seamSideLength(s, s.seams[0].a) - 50.0f) < 0.01f);
+ CHECK(removePoint(s, 0, 2));
+ CHECK(s.seams.empty() && s.panels[0].points.size() == 4);
+ // Mirrored copy: the other arm.
+ Pattern t = tshirtPattern();
+ const uint32_t c = mirroredCopy(t, 2, "Extra");
+ CHECK(t.panels[c].place.slot == Slot::RightArm && t.panels[c].name == "Extra");
+}
+
+TEST(garment_triangulates_quickly) {
+ Pattern pat = tshirtPattern();
+ pat.particleDistance = 10.0f; // about 9,000 particles
+ GarmentMesh m;
+ std::string error;
+ const auto t0 = std::chrono::steady_clock::now();
+ CHECK(triangulatePattern(pat, m, error));
+ const double s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+ std::printf(" garment: %zu particles, %zu triangles in %.0f ms\n", m.vertexCount(), m.triangles.size(), s * 1000.0);
+ CHECK(s < timeLimit(1.0));
+}
+
+TEST(garment_commands_make_sew_and_export) {
+ CommandRegistry reg;
+ Document doc = makeDoc(makeIcosphere(2));
+ CHECK(!reg.execute(doc, "garment_info").ok);
+ CommandResult r = reg.execute(doc, "garment_new", {{"template", std::string("tshirt")}});
+ CHECK(r.ok && r.message.find("4 panels, 10 seams") != std::string::npos);
+ CHECK(reg.execute(doc, "garment_info").message.find("Left sleeve") != std::string::npos);
+ r = reg.execute(doc, "garment_add_panel", {{"name", std::string("Pocket")}, {"width_mm", 120.0}, {"height_mm", 140.0}});
+ CHECK(r.ok);
+ r = reg.execute(doc, "garment_add_panel", {{"name", std::string("Bad")}, {"points", std::string("[0,0,1,1]")}});
+ CHECK(!r.ok);
+ r = reg.execute(doc, "garment_sew", {{"a_panel", std::string("Pocket")}, {"a_edge", 1.0}, {"b_panel", std::string("front")},
+ {"b_edge", 1.0}, {"b_from", 0.1}, {"b_to", 0.3}});
+ CHECK(r.ok); // the front hem is free
+ CHECK(reg.execute(doc, "garment_set", {{"particle_mm", 20.0}, {"fabric", std::string("silk")}}).ok);
+ CHECK(!reg.execute(doc, "garment_set", {{"fabric", std::string("tweed")}}).ok);
+ CHECK(reg.execute(doc, "garment_place", {{"panel", std::string("Pocket")}, {"slot", std::string("front")}, {"z", 0.01}}).ok);
+ const std::string svg = tempPath("garment_cmd.svg"), dxf = tempPath("garment_cmd.dxf");
+ CHECK(reg.execute(doc, "garment_export", {{"path", svg}}).ok);
+ CHECK(reg.execute(doc, "garment_export", {{"path", dxf}}).ok);
+ CHECK(readAll(dxf).find("POLYLINE") != std::string::npos);
+ // Import our own file into a fresh pattern: the five panels come back.
+ CHECK(reg.execute(doc, "garment_new", {{"template", std::string("empty")}}).ok);
+ r = reg.execute(doc, "garment_import", {{"path", svg}});
+ CHECK(r.ok && r.message.find("Imported 5 panels") != std::string::npos);
+ Pattern got;
+ CHECK(documentPattern(doc, got) && got.panels.size() == 5);
+ CHECK(got.panels[1].place.slot == Slot::Back && got.panels[2].place.slot == Slot::LeftArm &&
+ got.panels[3].place.slot == Slot::RightArm);
+ CHECK(reg.execute(doc, "garment_clear").ok && !documentPattern(doc, got));
+ std::remove(svg.c_str());
+ std::remove(dxf.c_str());
+}