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.

QRemesh Guides: curves that QRemesh's edge loops follow (field constraint, loop on the curve, closed loops fitted to whole lattice steps); per-SubTool storage and commands

islandmede6ef096f4415
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 3b2e654a..e42b584a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -68,6 +68,7 @@ add_library(sculptforge_core STATIC
src/core/TextureTransfer.cpp
src/core/SurfaceQuery.cpp
src/core/QRemesh.cpp
+ src/core/QRemeshGuides.cpp
src/core/Projection.cpp
src/core/RetopoCommands.cpp
third_party/xatlas/xatlas.cpp
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index 473263de..a2f10b65 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -562,6 +562,7 @@ CommandRegistry::CommandRegistry() {
registerBrushLibraryCommands(*this); // brush_install, brush_code, brush_delete, ... (BrushLibrary.cpp)
registerBrushCommands(*this); // brush_set_alpha (BrushAlpha.cpp)
registerRetopoCommands(*this); // qremesh, project_all (RetopoCommands.cpp)
+ registerQRemeshGuideCommands(*this); // qremesh_guide, ... (QRemeshGuides.cpp)
add({"stroke",
"Apply a brush along a path on the active SubTool, like dragging the cursor in the viewport (one undo "
diff --git a/src/core/Document.cpp b/src/core/Document.cpp
index 182f51e7..eb25c4dc 100644
--- a/src/core/Document.cpp
+++ b/src/core/Document.cpp
@@ -24,6 +24,7 @@ void Document::setMesh(Mesh m, std::string name, BVH* built) {
activeLayer = -1;
bvhDirty = false;
gozName.clear();
+ qremeshGuides.clear();
subtools.clear();
subtools.emplace_back();
subtools.back().id = nextSubtoolId_++;
@@ -57,6 +58,7 @@ void Document::selectSubtool(int i) {
std::swap(undo, s.undo);
std::swap(activeLayer, s.activeLayer);
std::swap(gozName, s.gozName);
+ std::swap(qremeshGuides, s.qremeshGuides);
std::swap(bvhDirty, s.bvhDirty);
std::swap(cleanRevision_, s.cleanRevision);
};
diff --git a/src/core/Document.h b/src/core/Document.h
index cb98db3d..a3774623 100644
--- a/src/core/Document.h
+++ b/src/core/Document.h
@@ -7,6 +7,7 @@
#include "core/BrushRecipe.h"
#include "core/Json.h"
#include "core/Mesh.h"
+#include "core/QRemeshGuides.h"
#include "core/Sculpt.h"
#include "core/Splats.h"
#include "core/Undo.h"
@@ -33,6 +34,7 @@ struct SubTool {
std::string gozName;
bool bvhDirty = false;
uint64_t cleanRevision = 0;
+ std::vector<QRemeshGuide> qremeshGuides; // QRemesh Guides (core/QRemeshGuides.h)
};
// Everything that makes up the open scene: the mesh, its acceleration
@@ -64,6 +66,9 @@ struct Document {
bool bvhDirty = false; // set after whole-mesh deformations (e.g. layer weights)
// SubTool name of a mesh that came from ZBrush (GoZ), so sending it back updates that SubTool.
std::string gozName;
+ // QRemesh Guides of the active SubTool: curves QRemesh's edge loops follow (core/QRemeshGuides.h). Not part
+ // of undo (Delete Last / Clear remove them); editing them sets `modified`.
+ std::vector<QRemeshGuide> qremeshGuides;
void syncBvh() {
if (bvhDirty) bvh.build(mesh);
diff --git a/src/core/QRemesh.cpp b/src/core/QRemesh.cpp
index 80fc4aef..13f9916b 100644
--- a/src/core/QRemesh.cpp
+++ b/src/core/QRemesh.cpp
@@ -282,6 +282,10 @@ struct Level {
std::vector<vec3> cdir, cpos;
std::vector<uint8_t> boundary; // on an open edge of the mesh
std::vector<vec3> color; // polypaint (usePolypaint only)
+ // QRemesh Guides: how strongly (0..1) the orientation turns to the nearest curve's direction gdir (empty
+ // without guides).
+ std::vector<float> gw;
+ std::vector<vec3> gdir;
// Fields.
std::vector<vec3> Q, O;
std::vector<float> S;
@@ -481,6 +485,107 @@ Level buildFinest(const WorkMesh& m, bool keepGroups, float sharpCos, std::vecto
return l;
}
+// QRemesh Guides on the finest level: vertices on a curve (within about half an edge of it) get a line
+// constraint along it, so the lattice puts a line, and the result an edge loop, there; vertices within `radius`
+// turn their orientation towards the curve's direction with a weight falling off from 1 on the curve. Vertices
+// with a constraint already (open edges, borders, hard edges) keep theirs. The curves' segments are added to
+// `borderSegs`, so relaxation keeps the loop's vertices on the curve.
+struct ClosedGuide {
+ SegmentBVH bvh;
+ float length = 0.0f;
+};
+
+void applyGuides(Level& l, const std::vector<QRemeshGuide>& guides, float radius,
+ std::vector<std::pair<vec3, vec3>>& borderSegs, std::vector<ClosedGuide>& closed) {
+ std::vector<vec3> a, b, ta, tb; // segments and the curve's tangent at each end
+ for (const QRemeshGuide& g : guides) {
+ const size_t n = g.points.size();
+ if (n < 2) continue;
+ auto tangent = [&](size_t i) {
+ const size_t prev = i > 0 ? i - 1 : g.closed ? n - 1 : 0, next = i + 1 < n ? i + 1 : g.closed ? 0 : n - 1;
+ return safeNormalize(g.points[next] - g.points[prev], vec3(0.0f));
+ };
+ const size_t segs = g.closed && n > 2 ? n : n - 1;
+ for (size_t i = 0; i < segs; ++i) {
+ const size_t j = (i + 1) % n;
+ a.push_back(g.points[i]);
+ b.push_back(g.points[j]);
+ ta.push_back(tangent(i));
+ tb.push_back(tangent(j));
+ borderSegs.push_back({g.points[i], g.points[j]});
+ }
+ }
+ if (a.empty()) return;
+ SegmentBVH bvh;
+ bvh.build(a, b);
+ // Closed curves for the scale field (closedGuideSize).
+ closed.clear();
+ for (const QRemeshGuide& g : guides) {
+ if (!g.closed || g.points.size() < 3) continue;
+ ClosedGuide c;
+ std::vector<vec3> ca, cb;
+ for (size_t i = 0; i < g.points.size(); ++i) {
+ ca.push_back(g.points[i]);
+ cb.push_back(g.points[(i + 1) % g.points.size()]);
+ c.length += glm::length(cb.back() - ca.back());
+ }
+ c.bvh.build(std::move(ca), std::move(cb));
+ closed.push_back(std::move(c));
+ }
+ const size_t nv = l.size();
+ l.gw.assign(nv, 0.0f);
+ l.gdir.assign(nv, vec3(0.0f));
+ parallelFor(nv, [&](size_t b0, size_t e0) {
+ for (size_t v = b0; v < e0; ++v) {
+ SurfaceHit hit;
+ if (!bvh.closestPoint(l.V[v], radius, hit)) continue;
+ vec3 t = ta[hit.prim] * hit.bary.x + tb[hit.prim] * hit.bary.y;
+ if (glm::dot(t, ta[hit.prim]) < 0.0f) t = ta[hit.prim];
+ const vec3 n = l.N[v];
+ t -= n * glm::dot(n, t);
+ if (glm::length(t) < 1e-6f) continue;
+ t = glm::normalize(t);
+ const float f = 1.0f - hit.distance / radius;
+ l.gw[v] = f * f;
+ l.gdir[v] = t;
+ if (l.ctype[v] != kFree) continue;
+ float edge = 0.0f;
+ for (uint32_t k = l.off[v]; k < l.off[v + 1]; ++k) edge += glm::length(l.V[l.adj[k]] - l.V[v]);
+ const uint32_t deg = l.off[v + 1] - l.off[v];
+ if (deg && hit.distance < 0.6f * edge / float(deg)) {
+ l.ctype[v] = kLine;
+ l.cdir[v] = t;
+ l.cpos[v] = hit.position;
+ }
+ }
+ });
+}
+
+// A loop's lattice closes up only when its length is a whole number of lattice steps; otherwise the position
+// field slips somewhere along it (a kink in the edge loop). Scales the size field near each closed guide so it
+// is: the mean size on the curve, rounded to fit, blended out over `reach`.
+void closedGuideSize(const Level& L, std::vector<float>& S, const std::vector<ClosedGuide>& closed, float reach) {
+ for (const ClosedGuide& c : closed) {
+ double sum = 0.0;
+ size_t cnt = 0;
+ std::vector<std::pair<uint32_t, float>> near; // (vertex, distance)
+ for (uint32_t v = 0; v < L.size(); ++v) {
+ SurfaceHit hit;
+ if (!c.bvh.closestPoint(L.V[v], reach, hit)) continue;
+ near.push_back({v, hit.distance});
+ if (hit.distance < 0.25f * reach) sum += S[v], ++cnt;
+ }
+ if (!cnt) continue;
+ const float s = float(sum / double(cnt));
+ const float steps = std::max(4.0f, std::round(c.length / s));
+ const float f = c.length / (steps * s);
+ for (auto [v, d] : near) {
+ const float w = d < 0.25f * reach ? 1.0f : 1.0f - (d - 0.25f * reach) / (0.75f * reach);
+ S[v] *= 1.0f + (f - 1.0f) * w;
+ }
+ }
+}
+
// The next coarser level: greedy matching of neighbours with similar normals (Instant Meshes' ordering).
bool downsample(Level& f, Level& c) {
const size_t n = f.size();
@@ -502,6 +607,7 @@ bool downsample(Level& f, Level& c) {
std::vector<uint32_t>& up = f.up;
up.assign(n, kNone);
const bool colors = !f.color.empty();
+ const bool guided = !f.gw.empty();
auto addVertex = [&](uint32_t i) {
up[i] = uint32_t(c.V.size());
c.V.push_back(f.V[i]);
@@ -512,6 +618,7 @@ bool downsample(Level& f, Level& c) {
c.cpos.push_back(f.cpos[i]);
c.boundary.push_back(f.boundary[i]);
if (colors) c.color.push_back(f.color[i]);
+ if (guided) c.gw.push_back(f.gw[i]), c.gdir.push_back(f.gdir[i]);
};
for (const Entry& e : entries) {
if (up[e.i] != kNone || up[e.j] != kNone) continue;
@@ -530,6 +637,7 @@ bool downsample(Level& f, Level& c) {
c.cpos[v] = f.cpos[e.j];
}
c.boundary[v] |= f.boundary[e.j];
+ if (guided && f.gw[e.j] > c.gw[v]) c.gw[v] = f.gw[e.j], c.gdir[v] = f.gdir[e.j]; // the stronger pull
}
for (uint32_t i = 0; i < n; ++i)
if (up[i] == kNone) addVertex(i);
@@ -612,6 +720,14 @@ void smoothOrientations(Level& l, int iterations) {
if (len > 1e-20f) sum /= len;
}
if (glm::length(sum) < 0.5f) sum = l.Q[i];
+ if (!l.gw.empty() && l.gw[i] > 0.0f) { // turn towards the guide's direction
+ const vec3 g = l.gdir[i] - n * glm::dot(n, l.gdir[i]);
+ if (glm::length(g) > 1e-6f) {
+ const vec3 a = alignTo(sum, n, glm::normalize(g), n);
+ const vec3 m = glm::mix(sum, a, l.gw[i]);
+ sum = safeNormalize(m - n * glm::dot(n, m), sum);
+ }
+ }
applyOrientationConstraint(l, i, sum);
l.Q[i] = sum;
}
@@ -1283,8 +1399,8 @@ struct PieceResult {
// The field-aligned remesh of one connected piece to about `wantQuads` quads. False on cancel.
bool remeshPiece(WorkMesh work, int axis, double wantQuads, const QRemeshOptions& opt, float diag,
- const std::function<bool(float)>& report, const std::function<void(const char*)>& mark,
- PieceResult& res) {
+ const std::vector<QRemeshGuide>& guides, const std::function<bool(float)>& report,
+ const std::function<void(const char*)>& mark, PieceResult& res) {
static const bool timing = std::getenv("SF_QREMESH_TIMING") != nullptr;
const QRemeshProgress progress = [&](float f) { return report(f); };
double area = 0.0;
@@ -1306,9 +1422,17 @@ bool remeshPiece(WorkMesh work, int axis, double wantQuads, const QRemeshOptions
std::vector<uint8_t> boundaryIsCut;
work = refineLongEdges(std::move(work), 1.5f * wantEdge, std::max<size_t>(4'000'000, work.T.size()));
std::vector<Level> levels;
+ std::vector<ClosedGuide> closedGuides;
const float sharpCos = opt.detectEdges ? std::cos(glm::radians(50.0f)) : 2.0f;
mark("refine");
levels.push_back(buildFinest(work, opt.keepGroups, sharpCos, boundarySegs, boundaryIsCut, borderSegs, axis));
+ if (!guides.empty()) {
+ // The flow follows a curve over 0.5 (Curves Strength 0) to 6 quads (1) to each side; a quad is half the
+ // lattice spacing (each extracted face splits into four).
+ const float strength = std::clamp(opt.guideStrength, 0.0f, 1.0f);
+ applyGuides(levels[0], guides, spacing * (0.25f + 2.75f * strength), borderSegs, closedGuides);
+ mark("guides");
+ }
mark("finest level");
if (!report(0.10f)) return false;
// Hierarchy down to a few vertices; fields are solved from the top to the finest level dense enough.
@@ -1423,6 +1547,7 @@ bool remeshPiece(WorkMesh work, int axis, double wantQuads, const QRemeshOptions
const float c = float(std::sqrt(want / faces)) * (sp / spacing);
L.S.resize(L.size());
for (uint32_t i = 0; i < L.size(); ++i) L.S[i] = c * rel[i];
+ if (!closedGuides.empty()) closedGuideSize(L, L.S, closedGuides, 2.0f * c);
for (size_t li = base + 1; li < levels.size(); ++li) {
const Level& f = levels[li - 1];
Level& cl = levels[li];
@@ -1609,6 +1734,30 @@ bool qremesh(const Mesh& source, const QRemeshOptions& opt, Mesh& out, std::stri
}
}
+ // QRemesh Guides in the working frame: snapped onto the sculpt as it is now (it may have changed since they
+ // were drawn) and, with symmetry, mirrored, so a curve drawn on either side guides both.
+ std::vector<QRemeshGuide> guides;
+ for (const QRemeshGuide& g : opt.guides)
+ if (g.points.size() >= 2) guides.push_back(g);
+ st.guides = guides.size();
+ if (!guides.empty()) {
+ buildFull();
+ for (QRemeshGuide& g : guides)
+ for (vec3& p : g.points) {
+ SurfaceHit hit;
+ if (full.closestPoint(p, 0.05f * diag, hit)) p = hit.position;
+ if (axis >= 0) p[axis] -= center;
+ }
+ if (axis >= 0) {
+ const size_t n = guides.size();
+ for (size_t i = 0; i < n; ++i) {
+ QRemeshGuide m = guides[i];
+ for (vec3& p : m.points) p[axis] = -p[axis];
+ guides.push_back(std::move(m));
+ }
+ }
+ }
+
// Small separate pieces (eyes, teeth, rivets: fewer than ~100 quads by their area) are remeshed on their
// own with a few dozen quads at least, so they don't vanish between the lattice corners of the big ones;
// the rest share one field (and the target, by curvature, as before).
@@ -1689,7 +1838,7 @@ bool qremesh(const Mesh& source, const QRemeshOptions& opt, Mesh& out, std::stri
// A piece the lattice misses is tried again finer, then kept as it is (its own triangles).
for (int attempt = 0; attempt < 3 && r.mesh.quads.empty(); ++attempt) {
r = PieceResult{};
- if (!remeshPiece(parts[i], axis, budget[i] * std::pow(2.5, attempt), opt, diag, pieceReport, mark, r)) {
+ if (!remeshPiece(parts[i], axis, budget[i] * std::pow(2.5, attempt), opt, diag, guides, pieceReport, mark, r)) {
error = "QRemesh cancelled";
return false;
}
diff --git a/src/core/QRemesh.h b/src/core/QRemesh.h
index 67c8db24..048bc192 100644
--- a/src/core/QRemesh.h
+++ b/src/core/QRemesh.h
@@ -17,6 +17,8 @@
// 5. The quads are relaxed and snapped back onto the sculpt; the target count is met by adjusting the
// lattice size and extracting again.
//
+// QRemesh Guides (curves drawn on the surface) constrain the fields the same way: a lattice line along each
+// curve, and the orientation turned towards it over a falloff (core/QRemeshGuides.h).
// Keep Groups constrains the fields to the polygroup borders, so edge loops run along them (and the result
// keeps the groups). Symmetry remeshes one half (cut at the plane) and mirrors it, welded on the seam; the plane
// is the model's own (found from it, so a model away from the origin works), and a model that isn't
@@ -26,6 +28,7 @@
#pragma once
#include "core/Mesh.h"
+#include "core/QRemeshGuides.h"
#include <functional>
#include <string>
@@ -49,6 +52,11 @@ struct QRemeshOptions {
float symmetryCenter = 0.0f;
int smoothIterations = 6;
uint32_t seed = 1; // the field's random start (the result is deterministic for a seed)
+ // QRemesh Guides (core/QRemeshGuides.h), in the source's space: an edge loop runs along each curve and the
+ // edge flow turns to follow it. guideStrength (ZBrush's Curves Strength, 0..1): how far around a curve the
+ // flow follows it (0 = only the loop on the curve itself, 1 = about six quads to each side).
+ std::vector<QRemeshGuide> guides;
+ float guideStrength = 0.5f;
};
struct QRemeshStats {
@@ -61,6 +69,7 @@ struct QRemeshStats {
float symmetryCenter = 0.0f; // the plane used (with symmetryUsed)
float asymmetry = 0.0f; // the model's mirror mismatch about that plane, in mean quad edges
size_t pieces = 0; // separate pieces of the source (small ones are remeshed on their own)
+ size_t guides = 0; // QRemesh Guides used
double seconds = 0;
};
diff --git a/src/core/QRemeshGuides.cpp b/src/core/QRemeshGuides.cpp
new file mode 100644
index 00000000..ca65c4a4
--- /dev/null
+++ b/src/core/QRemeshGuides.cpp
@@ -0,0 +1,253 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// QRemesh Guides: drawing, storing and scripting the curves QRemesh follows (core/QRemeshGuides.h). The field
+// side is in core/QRemesh.cpp.
+#include "core/QRemeshGuides.h"
+
+#include "core/Commands.h"
+#include "core/PathStroke.h"
+#include "core/SurfaceQuery.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <limits>
+
+namespace sf {
+
+namespace {
+
+using glm::vec3;
+
+float polylineLength(const std::vector<vec3>& p, bool closed) {
+ float len = 0.0f;
+ for (size_t i = 1; i < p.size(); ++i) len += glm::length(p[i] - p[i - 1]);
+ if (closed && p.size() > 2) len += glm::length(p.front() - p.back());
+ return len;
+}
+
+// Points every `step` along the polyline (the last one at its end, or before the start of a closed one).
+std::vector<vec3> resample(const std::vector<vec3>& p, bool closed, float step) {
+ std::vector<vec3> line = p;
+ if (closed) line.push_back(p.front());
+ std::vector<vec3> out;
+ if (line.empty()) return out;
+ out.push_back(line.front());
+ float carry = 0.0f; // distance walked since the last point placed
+ for (size_t i = 1; i < line.size(); ++i) {
+ const vec3 a = line[i - 1], b = line[i];
+ const float len = glm::length(b - a);
+ if (len <= 0.0f) continue;
+ float at = step - carry;
+ while (at <= len) {
+ out.push_back(a + (b - a) * (at / len));
+ at += step;
+ }
+ carry = len - (at - step);
+ }
+ if (closed) {
+ if (out.size() > 1 && glm::length(out.back() - out.front()) < 0.5f * step) out.pop_back();
+ } else if (glm::length(out.back() - line.back()) > 0.25f * step) {
+ out.push_back(line.back());
+ }
+ return out;
+}
+
+// The closest point of the mesh within `reach` of p (p itself when there is none).
+vec3 snapToSurface(const Mesh& mesh, const BVH& bvh, const vec3& p, float reach, std::vector<uint32_t>& scratch) {
+ bvh.queryTriangles(mesh, p, reach, scratch);
+ float best = std::numeric_limits<float>::max();
+ vec3 at = p;
+ for (uint32_t t : scratch) {
+ const glm::uvec3 tri = mesh.triangles[t];
+ glm::vec3 bary;
+ const vec3 q = closestPointOnTriangle(p, mesh.positions[tri.x], mesh.positions[tri.y], mesh.positions[tri.z], bary);
+ const float d = glm::dot(q - p, q - p);
+ if (d < best) best = d, at = q;
+ }
+ return at;
+}
+
+// Mean distance from the points of `a` to the polyline `b`.
+float meanDistance(const std::vector<vec3>& a, const std::vector<vec3>& b, bool closedB) {
+ if (a.empty() || b.size() < 2) return std::numeric_limits<float>::max();
+ double sum = 0.0;
+ const size_t segs = closedB ? b.size() : b.size() - 1;
+ for (const vec3& p : a) {
+ float best = std::numeric_limits<float>::max();
+ for (size_t s = 0; s < segs; ++s) {
+ const vec3 u = b[s], v = b[(s + 1) % b.size()], d = v - u;
+ const float l2 = glm::dot(d, d);
+ const float t = l2 > 0.0f ? std::clamp(glm::dot(p - u, d) / l2, 0.0f, 1.0f) : 0.0f;
+ best = std::min(best, glm::length(u + d * t - p));
+ }
+ sum += best;
+ }
+ return float(sum / double(a.size()));
+}
+
+} // namespace
+
+int addQRemeshGuide(std::vector<QRemeshGuide>& guides, const Mesh& mesh, const BVH& bvh, const std::vector<vec3>& path,
+ const Symmetry& symmetry, float step) {
+ if (path.size() < 2 || mesh.triangleCount() == 0) return 0;
+ const float diag = glm::length(mesh.bounds().extent());
+ if (!(diag > 0.0f)) return 0;
+ if (step <= 0.0f) step = 0.005f * diag;
+ const float length = polylineLength(path, false);
+ if (length < 4.0f * step) return 0;
+ // Ends close together (within a tenth of the curve's length and a few steps): a loop.
+ const bool closed = length > 12.0f * step && glm::length(path.back() - path.front()) < std::max(0.1f * length, 3.0f * step);
+ QRemeshGuide g;
+ g.closed = closed;
+ std::vector<uint32_t> scratch;
+ // Two passes of resample + snap: the chord between hits cuts under a curved surface.
+ g.points = path;
+ for (int pass = 0; pass < 2; ++pass) {
+ g.points = resample(g.points, closed && pass > 0, step);
+ for (vec3& p : g.points) p = snapToSurface(mesh, bvh, p, 4.0f * step, scratch);
+ }
+ if (g.points.size() < 3) return 0;
+ uint32_t stroke = 1;
+ for (const QRemeshGuide& o : guides) stroke = std::max(stroke, o.stroke + 1);
+ g.stroke = stroke;
+
+ std::vector<QRemeshGuide> added{g};
+ for (const vec3& m : Sculptor::mirrors(symmetry)) {
+ if (m == vec3(1.0f)) continue;
+ QRemeshGuide copy = g;
+ for (vec3& p : copy.points) p = snapToSurface(mesh, bvh, p * m, 4.0f * step, scratch);
+ // A curve that is its own mirror image (a loop round the mouth, across the middle) is kept once.
+ bool same = false;
+ for (const QRemeshGuide& a : added) same |= meanDistance(copy.points, a.points, a.closed) < 2.0f * step;
+ if (!same) added.push_back(std::move(copy));
+ }
+ guides.insert(guides.end(), added.begin(), added.end());
+ return int(added.size());
+}
+
+bool deleteLastQRemeshGuide(std::vector<QRemeshGuide>& guides) {
+ if (guides.empty()) return false;
+ const uint32_t last = guides.back().stroke;
+ guides.erase(std::remove_if(guides.begin(), guides.end(), [&](const QRemeshGuide& g) { return g.stroke == last; }),
+ guides.end());
+ return true;
+}
+
+float qremeshGuideLength(const std::vector<QRemeshGuide>& guides) {
+ float len = 0.0f;
+ for (const QRemeshGuide& g : guides) len += polylineLength(g.points, g.closed);
+ return len;
+}
+
+Json qremeshGuidesToJson(const std::vector<QRemeshGuide>& guides) {
+ Json out = Json::array();
+ for (const QRemeshGuide& g : guides) {
+ Json j = Json::object();
+ j.set("closed", g.closed);
+ j.set("stroke", double(g.stroke));
+ Json pts = Json::array();
+ for (const vec3& p : g.points)
+ for (int k = 0; k < 3; ++k) pts.push(double(p[k]));
+ j.set("points", std::move(pts));
+ out.push(std::move(j));
+ }
+ return out;
+}
+
+std::vector<QRemeshGuide> qremeshGuidesFromJson(const Json& json) {
+ std::vector<QRemeshGuide> out;
+ if (!json.isArray()) return out;
+ for (const Json& j : json.items()) {
+ const Json& pts = j["points"];
+ if (!pts.isArray() || pts.size() < 6 || pts.size() % 3 != 0) continue;
+ QRemeshGuide g;
+ g.closed = j["closed"].asBool(false);
+ g.stroke = uint32_t(std::max(0.0, j["stroke"].asNumber(double(out.size() + 1))));
+ bool ok = true;
+ for (size_t i = 0; i < pts.size() && ok; i += 3) {
+ const vec3 p(float(pts[i].asNumber(NAN)), float(pts[i + 1].asNumber(NAN)), float(pts[i + 2].asNumber(NAN)));
+ ok = std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.z);
+ g.points.push_back(p);
+ }
+ if (ok) out.push_back(std::move(g));
+ }
+ return out;
+}
+
+void registerQRemeshGuideCommands(CommandRegistry& reg) {
+ using T = ParamSpec::Type;
+ reg.add({"qremesh_guide",
+ "QRemesh Guides (ZBrush's ZRemesher Guides brush): draw a curve on the active SubTool for QRemesh to "
+ "follow; an edge loop runs along it and the edge flow around it turns with it. A curve that ends where it "
+ "started becomes a loop (around an eye or the mouth). The guides are kept with the SubTool and saved in "
+ "projects.",
+ {{"points", T::String, "The curve: \"x,y,z x,y,z ...\" (2+ points), on or near the surface.", true},
+ {"view", T::String, "Project the points onto the surface along this direction \"x,y,z\" (as a stroke "
+ "seen from the camera). Default: each point goes to the closest surface point.", false},
+ {"symmetry", T::String, "Mirror the curve across these planes through the centre, e.g. \"x\" or \"xz\". "
+ "Default: none.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ if (doc.mesh.triangleCount() == 0) return {false, "QRemesh Guides: the SubTool is empty"};
+ std::vector<vec3> pts;
+ std::string err;
+ if (!parsePathPoints(argString(a, "points"), pts, err)) return {false, err};
+ doc.syncBvh();
+ if (a.contains("view")) {
+ vec3 view;
+ if (!parseVec3(argString(a, "view"), view) || !(glm::length(view) > 1e-6f))
+ return {false, "view must be a direction \"x,y,z\""};
+ view = glm::normalize(view);
+ const AABB box = doc.mesh.bounds();
+ const float diag = glm::length(box.extent());
+ // Through the dense samples of the path, so the curve hugs the surface between the points.
+ std::vector<vec3> hits;
+ for (const vec3& p : samplePath(pts, false, 0.005f * diag)) {
+ RayHit hit;
+ const vec3 origin = p - view * (glm::dot(p - box.center(), view) + diag);
+ if (doc.bvh.raycast(doc.mesh, origin, view, hit)) hits.push_back(hit.position);
+ }
+ pts = std::move(hits);
+ }
+ const std::string sym = argString(a, "symmetry");
+ Symmetry s{false, false, false};
+ for (char c : sym) {
+ if (c == 'x' || c == 'X') s.x = true;
+ else if (c == 'y' || c == 'Y') s.y = true;
+ else if (c == 'z' || c == 'Z') s.z = true;
+ else return {false, "symmetry takes the letters x, y and z"};
+ }
+ const int added = addQRemeshGuide(doc.qremeshGuides, doc.mesh, doc.bvh, pts, s);
+ if (added == 0) return {false, "QRemesh Guides: the curve is too short or misses the SubTool"};
+ doc.modified = true;
+ const QRemeshGuide& g = doc.qremeshGuides[doc.qremeshGuides.size() - size_t(added)];
+ return {true, std::string("QRemesh guide added (") + (g.closed ? "a loop" : "a curve") +
+ (added > 1 ? ", mirrored" : "") + "); " + std::to_string(doc.qremeshGuides.size()) +
+ " guides on the SubTool"};
+ }});
+ reg.add({"qremesh_guide_delete_last", "QRemesh Guides: delete the last curve drawn (with its mirror copies).", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ if (!deleteLastQRemeshGuide(doc.qremeshGuides)) return {false, "No QRemesh guides to delete"};
+ doc.modified = true;
+ return {true, std::to_string(doc.qremeshGuides.size()) + " QRemesh guides left"};
+ }});
+ reg.add({"qremesh_guides_clear", "QRemesh Guides: delete every guide curve of the active SubTool.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ if (doc.qremeshGuides.empty()) return {false, "No QRemesh guides to delete"};
+ doc.qremeshGuides.clear();
+ doc.modified = true;
+ return {true, "QRemesh guides cleared"};
+ }});
+ reg.add({"qremesh_guides_info", "QRemesh Guides: how many guide curves the active SubTool has, and their length.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ size_t loops = 0;
+ for (const QRemeshGuide& g : doc.qremeshGuides) loops += g.closed;
+ char buf[160];
+ std::snprintf(buf, sizeof buf, "%zu QRemesh guides (%zu loops), total length %.4g", doc.qremeshGuides.size(),
+ loops, double(qremeshGuideLength(doc.qremeshGuides)));
+ return {true, buf};
+ }});
+}
+
+} // namespace sf
diff --git a/src/core/QRemeshGuides.h b/src/core/QRemeshGuides.h
new file mode 100644
index 00000000..2d6e3de7
--- /dev/null
+++ b/src/core/QRemeshGuides.h
@@ -0,0 +1,54 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// QRemesh Guides (ZBrush's ZRemesher Guides brush): curves drawn on the surface that QRemesh's edge loops
+// follow, around the eyes, the mouth, a joint. Each SubTool keeps its own (Document::qremeshGuides while it is
+// active, SubTool::qremeshGuides otherwise) and projects save them ("qremesh_guides" in a SubTool's manifest
+// entry, so older versions ignore them and older projects open without any).
+//
+// QRemesh (core/QRemesh.cpp) uses them twice: the cross field turns to follow every curve, with a falloff
+// over a few quads that Curves Strength widens, and the quad lattice gets a line along each curve, so one edge
+// loop runs right on it.
+#pragma once
+
+#include "core/Json.h"
+
+#include <glm/glm.hpp>
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+class BVH;
+class CommandRegistry;
+class Mesh;
+struct Document;
+struct Symmetry;
+
+struct QRemeshGuide {
+ std::vector<glm::vec3> points; // on the surface, in the SubTool's space, evenly spaced
+ bool closed = false; // a loop: the last point joins the first
+ uint32_t stroke = 0; // guides drawn together (a curve and its mirror) share a stroke number
+};
+
+// Turns a drawn path (points on or near the surface) into guides: the path is resampled every `step` (<= 0:
+// 0.5% of the SubTool's size), snapped onto the surface, closed when it ends near where it started, and copied
+// across each mirror plane of `symmetry` (planes through the world's centre, as the brushes mirror). Appends to
+// `guides` with a new stroke number; returns how many guides were added (0: the path was too short).
+int addQRemeshGuide(std::vector<QRemeshGuide>& guides, const Mesh& mesh, const BVH& bvh,
+ const std::vector<glm::vec3>& path, const Symmetry& symmetry, float step = 0.0f);
+// Removes the guides of the last stroke; false when there are none.
+bool deleteLastQRemeshGuide(std::vector<QRemeshGuide>& guides);
+// Total length of the guides (for the status line).
+float qremeshGuideLength(const std::vector<QRemeshGuide>& guides);
+
+// Projects: [{"closed": bool, "stroke": n, "points": [x, y, z, x, y, z, ...]}, ...]. Bad entries are skipped.
+Json qremeshGuidesToJson(const std::vector<QRemeshGuide>& guides);
+std::vector<QRemeshGuide> qremeshGuidesFromJson(const Json& json);
+
+// qremesh_guide, qremesh_guide_delete_last, qremesh_guides_clear, qremesh_guides_info.
+void registerQRemeshGuideCommands(CommandRegistry& registry);
+
+} // namespace sf
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index 2dfac195..d9e34139 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -1,15 +1,20 @@
// SculptForge - open source digital sculpting
// SPDX-License-Identifier: GPL-3.0-or-later
//
-// Runs every TEST registered by the tests/test_*.cpp files.
+// Runs every TEST registered by the tests/test_*.cpp files (with arguments: only the tests whose names contain
+// one of them, e.g. `sculptforge_tests qremesh_guide`).
#include "TestHarness.h"
#include <cstdio>
+#include <cstring>
#include <exception>
-int main() {
+int main(int argc, char** argv) {
using namespace sf::test;
for (const auto& t : registry()) {
+ bool wanted = argc < 2;
+ for (int i = 1; i < argc && !wanted; ++i) wanted = std::strstr(t.name, argv[i]) != nullptr;
+ if (!wanted) continue;
std::printf("[ RUN] %s\n", t.name);
std::fflush(stdout); // so a crash still shows which test was running
int before = g_failures;
diff --git a/tests/test_qremesh_guides.cpp b/tests/test_qremesh_guides.cpp
new file mode 100644
index 00000000..cc330849
--- /dev/null
+++ b/tests/test_qremesh_guides.cpp
@@ -0,0 +1,198 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// QRemesh Guides (ZBrush's ZRemesher Guides): a curve drawn round an "eye" on a sphere gets a closed edge loop
+// along it, and the edges near the curve line up with its tangent much better than without the guide; drawing
+// (snapping, closing, mirroring), Delete Last / Clear, commands, SubTool swaps and project round trips.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/Primitives.h"
+#include "core/Project.h"
+#include "core/QRemesh.h"
+#include "core/QRemeshGuides.h"
+#include "io/ObjIO.h"
+
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <filesystem>
+#include <map>
+#include <set>
+
+using namespace sf;
+
+namespace {
+
+constexpr float kPi = 3.14159265f;
+
+// A circle of angular radius `angle` on the unit sphere around direction `c`.
+std::vector<glm::vec3> circleOnSphere(glm::vec3 c, float angle, int n, float radius = 1.0f) {
+ c = glm::normalize(c);
+ const glm::vec3 u = glm::normalize(glm::cross(c, std::abs(c.y) < 0.9f ? glm::vec3(0, 1, 0) : glm::vec3(1, 0, 0)));
+ const glm::vec3 v = glm::cross(c, u);
+ std::vector<glm::vec3> out;
+ for (int i = 0; i <= n; ++i) { // the last point repeats the first: a drawn loop
+ const float phi = 2.0f * kPi * float(i % n) / float(n);
+ out.push_back(radius * (std::cos(angle) * c + std::sin(angle) * (std::cos(phi) * u + std::sin(phi) * v)));
+ }
+ return out;
+}
+
+// Unique edges of the result as exported (quads once).
+std::vector<std::pair<uint32_t, uint32_t>> faceEdges(const Mesh& m) {
+ std::set<std::pair<uint32_t, uint32_t>> edges;
+ for (uint32_t t = 0; t < m.triangleCount(); ++t) {
+ glm::uvec4 f;
+ const int n = m.exportFace(t, f);
+ for (int k = 0; k < n; ++k) {
+ const uint32_t a = f[k], b = f[(k + 1) % n];
+ edges.insert({std::min(a, b), std::max(a, b)});
+ }
+ }
+ return {edges.begin(), edges.end()};
+}
+
+struct GuideFit {
+ float meanAngle = 90.0f; // degrees, edges near the curve against its tangent (0 = along or across it)
+ size_t nearEdges = 0;
+ bool closedLoop = false; // a cycle of edges runs all the way round on the curve
+ float loopGap = 360.0f; // the largest gap (degrees round the circle) in that cycle's coverage
+};
+
+// How well the edges of `m` near the circle (around `c` at `angle`, on the unit sphere) follow it.
+GuideFit measureFit(const Mesh& m, glm::vec3 c, float angle) {
+ c = glm::normalize(c);
+ const glm::vec3 u = glm::normalize(glm::cross(c, std::abs(c.y) < 0.9f ? glm::vec3(0, 1, 0) : glm::vec3(1, 0, 0)));
+ const glm::vec3 v = glm::cross(c, u);
+ const auto edges = faceEdges(m);
+ double len = 0.0;
+ for (auto [a, b] : edges) len += glm::length(m.positions[a] - m.positions[b]);
+ const float edge = float(len / double(edges.size()));
+ // Distance of a point from the circle, and the circle's tangent nearest it.
+ auto onCircle = [&](glm::vec3 p, glm::vec3& tangent, float& phi) {
+ const glm::vec3 d = glm::normalize(p);
+ phi = std::atan2(glm::dot(d, v), glm::dot(d, u));
+ const glm::vec3 radial = std::cos(phi) * u + std::sin(phi) * v;
+ tangent = -std::sin(phi) * u + std::cos(phi) * v;
+ const glm::vec3 q = std::cos(angle) * c + std::sin(angle) * radial;
+ return glm::length(p - q);
+ };
+ GuideFit fit;
+ double sum = 0.0;
+ std::map<uint32_t, std::vector<uint32_t>> loop; // edges on the curve, along it
+ for (auto [a, b] : edges) {
+ const glm::vec3 pa = m.positions[a], pb = m.positions[b];
+ glm::vec3 t;
+ float phi;
+ if (onCircle(0.5f * (pa + pb), t, phi) > 0.5f * edge) continue;
+ const glm::vec3 d = glm::normalize(pb - pa);
+ float deg = std::acos(std::clamp(std::abs(glm::dot(d, t)), 0.0f, 1.0f)) * 180.0f / kPi; // 0..90
+ deg = std::min(deg, 90.0f - deg); // a cross field: across the curve is as good as along it
+ sum += deg;
+ ++fit.nearEdges;
+ glm::vec3 ta, tb;
+ float fa, fb;
+ if (deg < 20.0f && std::acos(std::clamp(std::abs(glm::dot(d, t)), 0.0f, 1.0f)) < 0.5f &&
+ onCircle(pa, ta, fa) < 0.3f * edge && onCircle(pb, tb, fb) < 0.3f * edge) {
+ loop[a].push_back(b);
+ loop[b].push_back(a);
+ }
+ }
+ fit.meanAngle = fit.nearEdges ? float(sum / double(fit.nearEdges)) : 90.0f;
+ // The biggest connected set of loop edges: a cycle (every vertex twice) going all the way round.
+ std::set<uint32_t> seen;
+ for (auto& [start, nb] : loop) {
+ if (seen.count(start)) continue;
+ std::vector<uint32_t> stack{start}, comp;
+ seen.insert(start);
+ while (!stack.empty()) {
+ const uint32_t x = stack.back();
+ stack.pop_back();
+ comp.push_back(x);
+ for (uint32_t y : loop[x])
+ if (seen.insert(y).second) stack.push_back(y);
+ }
+ bool cycle = comp.size() >= 6;
+ std::vector<float> phis;
+ for (uint32_t x : comp) {
+ cycle &= loop[x].size() == 2;
+ glm::vec3 t;
+ float phi;
+ onCircle(m.positions[x], t, phi);
+ phis.push_back(phi * 180.0f / kPi);
+ }
+ std::sort(phis.begin(), phis.end());
+ float gap = 360.0f - (phis.back() - phis.front());
+ for (size_t i = 1; i < phis.size(); ++i) gap = std::max(gap, phis[i] - phis[i - 1]);
+ if (std::getenv("SF_GUIDE_DEBUG")) {
+ size_t d1 = 0, d2 = 0, d3 = 0;
+ for (uint32_t x : comp) (loop[x].size() == 1 ? d1 : loop[x].size() == 2 ? d2 : d3)++;
+ std::printf(" component %zu vertices: degree 1 %zu, 2 %zu, 3+ %zu, gap %.0f\n", comp.size(), d1, d2, d3, gap);
+ }
+ if (gap < fit.loopGap) fit.loopGap = gap;
+ if (cycle && gap < 30.0f) fit.closedLoop = true;
+ }
+ return fit;
+}
+
+QRemeshGuide guideFrom(const std::vector<glm::vec3>& points, bool closed) {
+ QRemeshGuide g;
+ g.points = points;
+ if (closed) g.points.pop_back();
+ g.closed = closed;
+ g.stroke = 1;
+ return g;
+}
+
+} // namespace
+
+TEST(qremesh_guide_loop_round_an_eye) {
+ const Mesh sphere = makeIcosphere(6);
+ const glm::vec3 eye(0.35f, 0.3f, 0.88f); // off every axis, so the plain field has no reason to circle it
+ const float angle = 0.42f; // about 24 degrees
+ const std::vector<glm::vec3> circle = circleOnSphere(eye, angle, 240);
+ QRemeshOptions o;
+ o.targetQuads = 3000;
+ o.adaptive = 0.0f;
+ Mesh plain, guided;
+ std::string err;
+ CHECK(qremesh(sphere, o, plain, err));
+ o.guides = {guideFrom(circle, true)};
+ QRemeshStats st;
+ CHECK(qremesh(sphere, o, guided, err, {}, &st));
+ CHECK(st.guides == 1);
+ const TopologyReport topo = topologyReport(guided);
+ CHECK(topo.manifold() && topo.boundaryEdges == 0 && topo.quadFraction() >= 0.95f);
+ CHECK(st.quads > 2500 && st.quads < 3500);
+ if (const char* dir = std::getenv("SF_GUIDE_DEBUG")) {
+ // Faces the circle passes through in their own polygroup, for --polygroups renders.
+ for (Mesh* m : {&plain, &guided}) {
+ Mesh copy = *m;
+ copy.ensurePolygroups();
+ for (uint32_t t = 0; t < copy.triangleCount(); ++t) {
+ const glm::uvec3 tri = copy.triangles[t];
+ float lo = 1e9f, hi = -1e9f;
+ for (int k = 0; k < 3; ++k) {
+ const float d = glm::dot(glm::normalize(copy.positions[tri[k]]), glm::normalize(eye)) - std::cos(angle);
+ lo = std::min(lo, d), hi = std::max(hi, d);
+ }
+ copy.polygroups[t] = lo <= 0.0f && hi >= 0.0f ? 1u : 0u;
+ }
+ saveObj(std::string(dir) + (m == &plain ? "/guide_plain.obj" : "/guide_guided.obj"), copy, err);
+ }
+ }
+ const GuideFit a = measureFit(plain, eye, angle), b = measureFit(guided, eye, angle);
+ std::printf(" without guide: %.1f deg mean over %zu edges, loop %d (gap %.0f deg)\n", a.meanAngle, a.nearEdges,
+ int(a.closedLoop), a.loopGap);
+ std::printf(" with guide: %.1f deg mean over %zu edges, loop %d (gap %.0f deg), %zu quads\n", b.meanAngle,
+ b.nearEdges, int(b.closedLoop), b.loopGap, st.quads);
+ CHECK(b.meanAngle < 0.5f * a.meanAngle);
+ CHECK(b.meanAngle < 8.0f);
+ CHECK(b.closedLoop);
+ CHECK(!a.closedLoop);
+ // Deterministic.
+ Mesh again;
+ CHECK(qremesh(sphere, o, again, err));
+ CHECK(again.positions == guided.positions && again.triangles == guided.triangles);
+}