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.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
QRemesh Guides: pin lattice corners evenly round closed guides, only the loop's own vertices snap to a guide; qremesh guides / curves_strength options; projects keep guides per SubTool; tests
islandmed7974f9105b4e
diff --git a/src/core/Project.cpp b/src/core/Project.cppindex f369c476..8841fa17 100644--- a/src/core/Project.cpp+++ b/src/core/Project.cpp@@ -714,6 +714,7 @@ bool readSubdiv(Reader& r, const Json& sj, Mesh& m, std::string& error, bool wor// A SubTool read from a project, before it joins the document.struct LoadedSubtool {std::string name, gozName;+ std::vector<QRemeshGuide> qremeshGuides;bool visible = true;int activeLayer = -1;Mesh mesh;@@ -772,6 +773,8 @@ bool saveProject(const std::string& path, const Document& doc, std::string& errost.set("subdiv", writeSubdiv(w, "subtools/" + std::to_string(i) + "/", doc.subtoolMesh(i)));const std::string& gozName = active ? doc.gozName : s.gozName;if (!gozName.empty()) st.set("goz_name", gozName);+ const std::vector<QRemeshGuide>& guides = active ? doc.qremeshGuides : s.qremeshGuides;+ if (!guides.empty()) st.set("qremesh_guides", qremeshGuidesToJson(guides)); // (no format change: optional)subtools.push(std::move(st));}manifest.set("subtools", std::move(subtools));@@ -878,6 +881,7 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {if (s.name.empty()) s.name = "SubTool";s.visible = sj["visible"].asBool(true);s.gozName = sj["goz_name"].asString();+ s.qremeshGuides = qremeshGuidesFromJson(sj["qremesh_guides"]);if (!readMesh(r, sj["mesh"], sj["layers"], s.mesh, error, false, false)) return false;// The BVH builds (on the pool) while the levels and topology load (off it), then the normals.s.startBvh();@@ -927,6 +931,7 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {doc.setMesh(std::move(subtools[0].mesh), subtools[0].name, built);doc.activeLayer = validLayer(subtools[0].activeLayer, doc.mesh);doc.gozName = subtools[0].gozName;+ doc.qremeshGuides = std::move(subtools[0].qremeshGuides);doc.subtools[0].visible = subtools[0].visible;for (size_t i = 1; i < subtools.size(); ++i) {BVH* builtI = subtools[i].finishBvh();@@ -935,6 +940,7 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {s.visible = subtools[i].visible;s.activeLayer = validLayer(subtools[i].activeLayer, s.mesh);s.gozName = subtools[i].gozName;+ s.qremeshGuides = std::move(subtools[i].qremeshGuides);}doc.selectSubtool(activeSubtool);doc.splats = std::move(splats);diff --git a/src/core/QRemesh.cpp b/src/core/QRemesh.cppindex 13f9916b..76a4f5ab 100644--- a/src/core/QRemesh.cpp+++ b/src/core/QRemesh.cpp@@ -286,6 +286,11 @@ struct Level {// without guides).std::vector<float> gw;std::vector<vec3> gdir;+ // Line constraints on a closed guide (empty without closed guides): which (-1: none), where along it, and+ // whether cpos is pinned as a lattice corner (pinClosedGuides).+ std::vector<int32_t> gid;+ std::vector<float> garc;+ std::vector<uint8_t> cfix;// Fields.std::vector<vec3> Q, O;std::vector<float> S;@@ -485,19 +490,38 @@ Level buildFinest(const WorkMesh& m, bool keepGroups, float sharpCos, std::vectoreturn 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.+// --- QRemesh Guides --------------------------------------------------------------------------------------++// A closed guide: its points (in order), the arc length at each, and how many lattice steps go round it.struct ClosedGuide {- SegmentBVH bvh;+ std::vector<vec3> points;+ std::vector<float> arc; // arc[i]: length from points[0] to points[i]float length = 0.0f;+ SegmentBVH bvh;+ float steps = 0.0f; // set by closedGuideSize++ vec3 at(float s) const { // the point at arc length s (wrapping round)+ s = std::fmod(s, length);+ if (s < 0.0f) s += length;+ const size_t i = size_t(std::upper_bound(arc.begin(), arc.end(), s) - arc.begin()) - 1;+ const size_t j = (i + 1) % points.size();+ const float len = (j ? arc[j] : length) - arc[i];+ return glm::mix(points[i], points[j], len > 0.0f ? (s - arc[i]) / len : 0.0f);+ }};+// 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+// `guideSegs`, so relaxation keeps the loop's vertices on the curve. Line vertices on a closed guide remember+// which (Level::gid) and where along it (Level::garc), for pinClosedGuides.void applyGuides(Level& l, const std::vector<QRemeshGuide>& guides, float radius,- std::vector<std::pair<vec3, vec3>>& borderSegs, std::vector<ClosedGuide>& closed) {+ std::vector<std::pair<vec3, vec3>>& guideSegs, std::vector<ClosedGuide>& closed) {std::vector<vec3> a, b, ta, tb; // segments and the curve's tangent at each end+ std::vector<int32_t> segClosed; // per segment: its closed guide, or -1+ std::vector<float> segArc; // arc length at the segment's start (closed guides)+ closed.clear();for (const QRemeshGuide& g : guides) {const size_t n = g.points.size();if (n < 2) continue;@@ -505,36 +529,39 @@ void applyGuides(Level& l, const std::vector<QRemeshGuide>& guides, float radiusconst 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;+ const bool loop = g.closed && n > 2;+ ClosedGuide c;+ const size_t segs = loop ? 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]});+ guideSegs.push_back({g.points[i], g.points[j]});+ segClosed.push_back(loop ? int32_t(closed.size()) : -1);+ segArc.push_back(c.length);+ if (loop) {+ c.points.push_back(g.points[i]);+ c.arc.push_back(c.length);+ c.length += glm::length(g.points[j] - g.points[i]);+ }+ }+ if (loop) {+ c.bvh.build(std::vector<vec3>(a.end() - long(segs), a.end()), std::vector<vec3>(b.end() - long(segs), b.end()));+ closed.push_back(std::move(c));}}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));+ if (!closed.empty()) {+ l.gid.assign(nv, -1);+ l.garc.assign(nv, 0.0f);+ }parallelFor(nv, [&](size_t b0, size_t e0) {for (size_t v = b0; v < e0; ++v) {SurfaceHit hit;@@ -556,16 +583,20 @@ void applyGuides(Level& l, const std::vector<QRemeshGuide>& guides, float radiusl.ctype[v] = kLine;l.cdir[v] = t;l.cpos[v] = hit.position;+ if (const int32_t c = segClosed[hit.prim]; c >= 0) {+ l.gid[v] = c;+ l.garc[v] = segArc[hit.prim] + hit.bary.y * glm::length(b[hit.prim] - a[hit.prim]);+ }}}});}// 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) {+// field slips somewhere along it (a kink in the edge loop). Picks that number for each closed guide from the+// mean size on it, and scales the size field to fit, blended out over `reach`.+void closedGuideSize(const Level& L, std::vector<float>& S, std::vector<ClosedGuide>& closed, float reach) {+ for (ClosedGuide& c : closed) {double sum = 0.0;size_t cnt = 0;std::vector<std::pair<uint32_t, float>> near; // (vertex, distance)@@ -575,10 +606,11 @@ void closedGuideSize(const Level& L, std::vector<float>& S, const std::vector<Clnear.push_back({v, hit.distance});if (hit.distance < 0.25f * reach) sum += S[v], ++cnt;}+ c.steps = 0.0f;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);+ c.steps = std::max(4.0f, std::round(c.length / s));+ const float f = c.length / (c.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;@@ -586,6 +618,21 @@ void closedGuideSize(const Level& L, std::vector<float>& S, const std::vector<Cl}}+// Puts lattice corners at `steps` even places round each closed guide: every line vertex on it is pinned to the+// one nearest along the curve, so the corners round the loop agree with each other and it closes up cleanly.+void pinClosedGuides(Level& l, const std::vector<ClosedGuide>& closed) {+ if (l.gid.empty()) return;+ l.cfix.assign(l.size(), 0);+ for (uint32_t v = 0; v < l.size(); ++v) {+ if (l.gid[v] < 0 || l.ctype[v] != kLine) continue;+ const ClosedGuide& c = closed[size_t(l.gid[v])];+ if (c.steps <= 0.0f) continue;+ const float step = c.length / c.steps;+ l.cpos[v] = c.at(std::round(l.garc[v] / step) * step);+ l.cfix[v] = 1;+ }+}+// 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();@@ -619,6 +666,7 @@ bool downsample(Level& f, Level& c) {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]);+ if (!f.gid.empty()) c.gid.push_back(f.gid[i]), c.garc.push_back(f.garc[i]);};for (const Entry& e : entries) {if (up[e.i] != kNone || up[e.j] != kNone) continue;@@ -635,6 +683,7 @@ bool downsample(Level& f, Level& c) {c.ctype[v] = f.ctype[e.j];c.cdir[v] = f.cdir[e.j];c.cpos[v] = f.cpos[e.j];+ if (!f.gid.empty()) c.gid[v] = f.gid[e.j], c.garc[v] = f.garc[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@@ -737,6 +786,8 @@ void smoothOrientations(Level& l, int iterations) {void applyPositionConstraint(const Level& l, uint32_t i, const vec3& q, vec3& o) {if (l.ctype[i] == kPoint) {o = l.cpos[i] - l.N[i] * glm::dot(l.N[i], l.cpos[i] - l.V[i]);+ } else if (l.ctype[i] == kLine && !l.cfix.empty() && l.cfix[i]) { // a pinned corner on a closed guide+ o = l.cpos[i] - l.N[i] * glm::dot(l.N[i], l.cpos[i] - l.V[i]);} else if (l.ctype[i] == kLine) {const vec3 perp = glm::cross(l.N[i], l.cdir[i]); // across the line, in the tangent planeo -= perp * glm::dot(o - l.cpos[i], perp);@@ -1199,6 +1250,7 @@ struct Snapper {const SegmentBVH* borders = nullptr; // polygroup borders (Keep Groups) and hard edgesconst SegmentBVH* corners = nullptr; // where several of those meet (as zero-length segments)float reach = 1.0f;+ const SegmentBVH* guides = nullptr; // QRemesh Guides: only the loops' own vertices snap to them};// Tangential relaxation on the source surface; vertices on open edges stay on the source's open edges, those@@ -1231,9 +1283,14 @@ void relax(QuadMesh& q, const Snapper& snap, int iterations, float edge, const Qnormal = vec3(0.0f);return hit.position;}- if (open[v] == 1 && snap.borders && snap.borders->closestPoint(p, snap.reach, hit)) {- normal = vec3(0.0f);- return hit.position;+ if (open[v] == 1) {+ SurfaceHit g;+ const bool onBorder = snap.borders && snap.borders->closestPoint(p, snap.reach, hit);+ const bool onGuide = snap.guides && snap.guides->closestPoint(p, onBorder ? hit.distance : snap.reach, g);+ if (onBorder || onGuide) {+ normal = vec3(0.0f);+ return onGuide ? g.position : hit.position;+ }}if (snap.surface->closestPoint(p, snap.reach, hit)) {normal = snap.surface->faceNormal(hit.prim);@@ -1247,10 +1304,12 @@ void relax(QuadMesh& q, const Snapper& snap, int iterations, float edge, const Qfor (size_t v = b; v < e; ++v) q.P[v] = project(uint32_t(v), q.P[v], normal[v]);});// Polygroup-border vertices: within a fifth of an edge of a border.- if (snap.borders && !snap.borders->empty())+ // Vertices on a guide's loop are the ones extracted on it (features): a vertex merely near a guide stays free.+ if (snap.borders || snap.guides)for (uint32_t v = 0; v < nv; ++v) {SurfaceHit hit;- if (open[v] == 0 && (q.feature[v] || snap.borders->closestPoint(q.P[v], 0.2f * edge, hit))) open[v] = 1;+ if (open[v] == 0 && (q.feature[v] || (snap.borders && snap.borders->closestPoint(q.P[v], 0.2f * edge, hit))))+ open[v] = 1;}// Corners of the source (a box's, a thin slab's) each pin their nearest quad vertex, so they stay sharp.std::vector<uint8_t> pinned(nv, 0);@@ -1418,7 +1477,7 @@ bool remeshPiece(WorkMesh work, int axis, double wantQuads, const QRemeshOptionsmark("surface bvh");if (!report(0.05f)) return false;- std::vector<std::pair<vec3, vec3>> boundarySegs, borderSegs;+ std::vector<std::pair<vec3, vec3>> boundarySegs, borderSegs, guideSegs;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;@@ -1430,7 +1489,7 @@ bool remeshPiece(WorkMesh work, int axis, double wantQuads, const QRemeshOptions// 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);+ applyGuides(levels[0], guides, spacing * (0.25f + 2.75f * strength), guideSegs, closedGuides);mark("guides");}mark("finest level");@@ -1547,7 +1606,10 @@ bool remeshPiece(WorkMesh work, int axis, double wantQuads, const QRemeshOptionsconst 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);+ if (!closedGuides.empty()) {+ closedGuideSize(L, L.S, closedGuides, 2.0f * c);+ for (size_t li = base; li < levels.size(); ++li) pinClosedGuides(levels[li], closedGuides);+ }for (size_t li = base + 1; li < levels.size(); ++li) {const Level& f = levels[li - 1];Level& cl = levels[li];@@ -1602,7 +1664,7 @@ bool remeshPiece(WorkMesh work, int axis, double wantQuads, const QRemeshOptionsif (!report(0.85f)) return false;// Snap to the sculpt and relax.- SegmentBVH boundaryBvh, borderBvh, cornerBvh;+ SegmentBVH boundaryBvh, borderBvh, cornerBvh, guideBvh;{std::vector<vec3> c;for (uint32_t i = 0; i < levels[0].size(); ++i)@@ -1614,9 +1676,12 @@ bool remeshPiece(WorkMesh work, int axis, double wantQuads, const QRemeshOptionsa.clear(), b.clear();for (auto& s : borderSegs) a.push_back(s.first), b.push_back(s.second);borderBvh.build(std::move(a), std::move(b));+ a.clear(), b.clear();+ for (auto& s : guideSegs) a.push_back(s.first), b.push_back(s.second);+ guideBvh.build(std::move(a), std::move(b));}Snapper snap{&surface, boundaryBvh.empty() ? nullptr : &boundaryBvh, borderBvh.empty() ? nullptr : &borderBvh,- cornerBvh.empty() ? nullptr : &cornerBvh, spacing * 4.0f + 1e-3f * diag};+ cornerBvh.empty() ? nullptr : &cornerBvh, spacing * 4.0f + 1e-3f * diag, guideBvh.empty() ? nullptr : &guideBvh};bool cancelled = false;relax(qm, snap, std::max(opt.smoothIterations, 0), sp * 0.5f, progress, 0.85f, 0.95f, cancelled);if (cancelled) return false;@@ -1736,24 +1801,41 @@ 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.+ // A guide mostly off the surface (the SubTool was moved after it was drawn) is left out.std::vector<QRemeshGuide> guides;- for (const QRemeshGuide& g : opt.guides)- if (g.points.size() >= 2) guides.push_back(g);+ if (!opt.guides.empty()) buildFull();+ for (const QRemeshGuide& g : opt.guides) {+ QRemeshGuide s = g;+ size_t on = 0;+ for (vec3& p : s.points) {+ SurfaceHit hit;+ if (full.closestPoint(p, 0.05f * diag, hit)) p = hit.position, ++on;+ if (axis >= 0) p[axis] -= center;+ }+ if (s.points.size() >= 2 && on * 2 > s.points.size()) guides.push_back(std::move(s));+ else ++st.guidesSkipped;+ }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) {+ // A curve that is its own mirror image (a loop round the mouth, across the middle) isn't doubled:+ // the two copies would pin different corners on the same loop.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));+ std::vector<vec3> a, b;+ for (size_t k = 0; k + 1 < guides[i].points.size(); ++k)+ a.push_back(guides[i].points[k]), b.push_back(guides[i].points[k + 1]);+ if (guides[i].closed) a.push_back(guides[i].points.back()), b.push_back(guides[i].points.front());+ SegmentBVH self;+ self.build(std::move(a), std::move(b));+ double off = 0.0;+ for (const vec3& p : m.points) {+ SurfaceHit hit;+ off += self.closestPoint(p, 0.05f * diag, hit) ? hit.distance : 0.05f * diag;+ }+ if (off / double(m.points.size()) > 0.004 * diag) guides.push_back(std::move(m));}}}diff --git a/src/core/QRemesh.h b/src/core/QRemesh.hindex 048bc192..3b1966e3 100644--- a/src/core/QRemesh.h+++ b/src/core/QRemesh.h@@ -70,6 +70,7 @@ struct QRemeshStats {float asymmetry = 0.0f; // the model's mirror mismatch about that plane, in mean quad edgessize_t pieces = 0; // separate pieces of the source (small ones are remeshed on their own)size_t guides = 0; // QRemesh Guides used+ size_t guidesSkipped = 0; // guides left out: mostly off the surface (the SubTool moved since)double seconds = 0;};diff --git a/src/core/RetopoCommands.cpp b/src/core/RetopoCommands.cppindex b0d4d204..66ba982e 100644--- a/src/core/RetopoCommands.cpp+++ b/src/core/RetopoCommands.cpp@@ -34,6 +34,7 @@ std::string applyQRemesh(Document& doc, Mesh result, bool keepOriginal, const QRconst int at = doc.activeSubtool + 1;doc.addSubtool(doc.mesh, active.name + " Original", false, at);doc.subtools[size_t(at)].visible = false;+ doc.subtools[size_t(at)].qremeshGuides = doc.qremeshGuides; // to remesh it again with them}doc.replaceMeshUndoable(std::move(result), "QRemesh");const size_t faces = st.quads + st.triangles;@@ -49,6 +50,10 @@ std::string applyQRemesh(Document& doc, Mesh result, bool keepOriginal, const QRstd::snprintf(s, sizeof s, "; mirrored across %c", axis);sym = s;}+ if (st.guides) sym += "; followed " + std::to_string(st.guides) + (st.guides == 1 ? " guide" : " guides");+ if (st.guidesSkipped)+ sym += "; " + std::to_string(st.guidesSkipped) + (st.guidesSkipped == 1 ? " guide is" : " guides are") ++ " off the surface and were ignored (draw them again after moving the SubTool)";char buf[512];std::snprintf(buf, sizeof buf, "QRemesh: %zu quads%s from %zu triangles (%.0f%% quads%s) in %.1f s%s%s", st.quads,st.triangles ? (" + " + std::to_string(st.triangles) + " triangles").c_str() : "", before,@@ -81,7 +86,12 @@ void registerRetopoCommands(CommandRegistry& reg) {{"smooth", T::Number, "Relaxation passes on the surface (0-30). Default 6.", false},{"seed", T::Number, "Random start of the direction field (results are repeatable per seed).", false},{"keep_texture", T::Bool, "Keep a painted texture: Auto UV the result and project the texture onto it. "- "Default true.", false}},+ "Default true.", false},+ {"guides", T::Bool, "Follow the SubTool's QRemesh Guides (curves drawn with qremesh_guide): an edge loop "+ "runs along each. Default true.", false},+ {"curves_strength", T::Number, "Curves Strength 0-100: how far around each guide the edge flow follows "+ "it (0 = just the loop on the curve, 100 = about six quads to each side). "+ "Default 50.", false}},[](Document& doc, const Args& a) -> CommandResult {if (doc.mesh.triangleCount() == 0) return {false, "QRemesh: the SubTool is empty"};QRemeshOptions o;@@ -97,6 +107,8 @@ void registerRetopoCommands(CommandRegistry& reg) {}o.smoothIterations = int(std::clamp(argNumber(a, "smooth", 6), 0.0, 30.0));o.seed = uint32_t(std::max(0.0, argNumber(a, "seed", 1)));+ if (argBool(a, "guides", true)) o.guides = doc.qremeshGuides;+ o.guideStrength = float(std::clamp(argNumber(a, "curves_strength", 50.0), 0.0, 100.0) / 100.0);Mesh out;std::string err;QRemeshStats st;diff --git a/tests/test_qremesh_guides.cpp b/tests/test_qremesh_guides.cppindex cc330849..6ccff79e 100644--- a/tests/test_qremesh_guides.cpp+++ b/tests/test_qremesh_guides.cpp@@ -53,6 +53,15 @@ std::vector<std::pair<uint32_t, uint32_t>> faceEdges(const Mesh& m) {return {edges.begin(), edges.end()};}+// Vertices with 7 or more edges (fans, stars): a defect in a quad mesh.+size_t highValence(const Mesh& m) {+ std::map<uint32_t, int> deg;+ for (auto [a, b] : faceEdges(m)) ++deg[a], ++deg[b];+ size_t n = 0;+ for (auto [v, d] : deg) n += d >= 7;+ return n;+}+struct GuideFit {float meanAngle = 90.0f; // degrees, edges near the curve against its tangent (0 = along or across it)size_t nearEdges = 0;@@ -129,6 +138,26 @@ GuideFit measureFit(const Mesh& m, glm::vec3 c, float angle) {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 (comp.size() > 10)+ for (uint32_t x : comp) {+ if (loop[x].size() == 2) continue;+ glm::vec3 t;+ float phi;+ const float d = onCircle(m.positions[x], t, phi);+ std::printf(" v%u deg %zu at %.0f deg, %.2f edges off; all edges:", x, loop[x].size(), phi * 180.0f / kPi, d / edge);+ for (auto [a, b] : edges) {+ if (a != x && b != x) continue;+ const uint32_t y = a == x ? b : a;+ glm::vec3 ty;+ float py;+ const float dy = onCircle(m.positions[y], ty, py);+ const glm::vec3 dd = glm::normalize(m.positions[y] - m.positions[x]);+ std::printf(" [v%u %.2f off, %.0f deg to tangent, len %.2f]", y, dy / edge,+ std::acos(std::clamp(std::abs(glm::dot(dd, t)), 0.0f, 1.0f)) * 180.0f / kPi,+ glm::length(m.positions[y] - m.positions[x]) / edge);+ }+ std::printf("\n");+ }}if (gap < fit.loopGap) fit.loopGap = gap;if (cycle && gap < 30.0f) fit.closedLoop = true;@@ -136,6 +165,37 @@ GuideFit measureFit(const Mesh& m, glm::vec3 c, float angle) {return fit;}+// SF_GUIDE_DEBUG=dir: saves `m` as dir/name.obj with the faces just outside each circle that have an edge on it+// in polygroup 1 (a clean band when the loop is clean), for renders with --polygroups --wireframe.+void debugDump(const char* name, const Mesh& m, std::vector<glm::vec3> eyes, float angle) {+ const char* dir = std::getenv("SF_GUIDE_DEBUG");+ if (!dir) return;+ Mesh copy = m;+ copy.ensurePolygroups();+ const float edge = std::sqrt(4.0f * kPi / float(std::max<size_t>(m.quadCount(), 1)));+ for (uint32_t t = 0; t < copy.triangleCount(); ++t) {+ glm::uvec4 f;+ const uint32_t u = copy.quadPartnerAt(t);+ const int n = copy.exportFace(u == Mesh::kNoQuad ? t : std::min(t, u), f);+ copy.polygroups[t] = 0;+ for (const glm::vec3& eye : eyes) {+ const glm::vec3 c = glm::normalize(eye);+ int on = 0;+ glm::vec3 centre(0.0f);+ for (int k = 0; k < n; ++k) {+ const glm::vec3 p = glm::normalize(copy.positions[f[k]]);+ centre += p;+ // distance from the circle along the sphere, roughly+ on += std::abs(std::acos(std::clamp(glm::dot(p, c), -1.0f, 1.0f)) - angle) < 0.2f * edge;+ }+ const bool outside = std::acos(std::clamp(glm::dot(glm::normalize(centre), c), -1.0f, 1.0f)) > angle;+ if (on >= 2 && outside) copy.polygroups[t] = 1;+ }+ }+ std::string err;+ saveObj(std::string(dir) + "/" + name + ".obj", copy, err);+}+QRemeshGuide guideFrom(const std::vector<glm::vec3>& points, bool closed) {QRemeshGuide g;g.points = points;@@ -148,51 +208,250 @@ QRemeshGuide guideFrom(const std::vector<glm::vec3>& points, bool closed) {} // namespaceTEST(qremesh_guide_loop_round_an_eye) {+ // Six eyes of different sizes and places (off every axis, so the plain field has no reason to circle them).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);+ struct Eye {+ glm::vec3 at;+ float angle; // angular radius, radians+ int target;+ };+ const Eye eyes[] = {{{0.35f, 0.3f, 0.88f}, 0.42f, 3000}, {{-0.5f, 0.2f, 0.7f}, 0.3f, 4000},+ {{0.1f, -0.6f, 0.6f}, 0.55f, 2000}, {{0.7f, 0.5f, -0.3f}, 0.35f, 5000},+ {{-0.2f, 0.9f, 0.3f}, 0.6f, 1500}, {{0.4f, -0.3f, -0.85f}, 0.25f, 3500}};+ int loops = 0;+ for (const Eye& e : eyes) {+ QRemeshOptions o;+ o.targetQuads = e.target;+ o.adaptive = 0.0f;+ Mesh plain, guided;+ std::string err;+ CHECK(qremesh(sphere, o, plain, err));+ o.guides = {guideFrom(circleOnSphere(e.at, e.angle, 240), 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(std::abs(double(st.quads) / e.target - 1.0) < 0.1);+ const GuideFit a = measureFit(plain, e.at, e.angle), b = measureFit(guided, e.at, e.angle);+ std::printf(" eye %.2f rad, %d quads: without guide %.1f deg (%zu edges, loop %d), with %.1f deg (%zu edges, loop %d)\n",+ double(e.angle), e.target, a.meanAngle, a.nearEdges, int(a.closedLoop), b.meanAngle, b.nearEdges,+ int(b.closedLoop));+ CHECK(b.meanAngle < 0.5f * a.meanAngle);+ CHECK(b.meanAngle < 8.0f);+ CHECK(!a.closedLoop);+ loops += b.closedLoop;+ CHECK(highValence(guided) == 0);+ debugDump(("guide_eye" + std::to_string(&e - eyes)).c_str(), guided, {e.at}, e.angle);+ if (&e == &eyes[0]) {+ debugDump("guide_plain", plain, {e.at}, e.angle);+ debugDump("guide_guided", guided, {e.at}, e.angle);+ // Deterministic.+ Mesh again;+ CHECK(qremesh(sphere, o, again, err));+ CHECK(again.positions == guided.positions && again.triangles == guided.triangles);+ }+ }+ std::printf(" %d of 6 loops closed\n", loops);+ CHECK(loops == 6);+}++TEST(qremesh_guide_open_curve_turns_the_flow) {+ // An open arc (a third of a tilted circle): the edges along it follow it.+ const Mesh sphere = makeIcosphere(6);+ const glm::vec3 axis(0.6f, 0.7f, -0.3f);+ const float angle = 1.2f;+ std::vector<glm::vec3> arc = circleOnSphere(axis, angle, 300);+ arc.resize(100);QRemeshOptions o;- o.targetQuads = 3000;+ o.targetQuads = 2500;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);+ o.guides = {guideFrom(arc, false)};+ CHECK(qremesh(sphere, o, guided, err));+ CHECK(topologyReport(guided).manifold());+ // Measure on the arc's part of the circle only: the rest of the circle isn't guided.+ auto fitOnArc = [&](const Mesh& m) {+ Mesh part = m;+ const glm::vec3 c = glm::normalize(axis);+ const glm::vec3 u = glm::normalize(glm::cross(c, glm::vec3(0, 1, 0))), v = glm::cross(c, u);+ for (uint32_t t = 0; t < part.triangleCount(); ++t) {+ const glm::vec3 p = glm::normalize(part.positions[part.triangles[t].x]);+ float phi = std::atan2(glm::dot(p, v), glm::dot(p, u));+ if (phi < 0.0f) phi += 2.0f * kPi;+ if (phi < 0.25f || phi > 2.0f * kPi / 3.0f - 0.25f) part.triangles[t] = {0, 0, 0}; // off the arc}+ return measureFit(part, axis, angle);+ };+ const GuideFit a = fitOnArc(plain), b = fitOnArc(guided);+ std::printf(" arc: without %.1f deg (%zu edges), with %.1f deg (%zu edges)\n", a.meanAngle, a.nearEdges, b.meanAngle,+ b.nearEdges);+ CHECK(b.meanAngle < 0.6f * a.meanAngle);+ CHECK(b.meanAngle < 10.0f);+}++TEST(qremesh_guide_with_symmetry_loops_both_sides) {+ // One loop drawn on the +X side; QRemesh with X symmetry puts a loop round both "eyes".+ const Mesh sphere = makeIcosphere(6);+ const glm::vec3 eye(0.45f, 0.25f, 0.86f), mirrored(-0.45f, 0.25f, 0.86f);+ const float angle = 0.36f;+ QRemeshOptions o;+ o.targetQuads = 3000;+ o.adaptive = 0.0f;+ o.symmetryAxis = 0;+ o.guides = {guideFrom(circleOnSphere(eye, angle, 240), true)};+ Mesh out;+ std::string err;+ QRemeshStats st;+ CHECK(qremesh(sphere, o, out, err, {}, &st));+ CHECK(st.symmetryUsed && st.guides == 1);+ const TopologyReport topo = topologyReport(out);+ CHECK(topo.manifold() && topo.boundaryEdges == 0);+ debugDump("guide_symmetric", out, {eye, mirrored}, angle);+ const GuideFit right = measureFit(out, eye, angle), left = measureFit(out, mirrored, angle);+ std::printf(" symmetric: right %.1f deg loop %d, left %.1f deg loop %d\n", right.meanAngle, int(right.closedLoop),+ left.meanAngle, int(left.closedLoop));+ CHECK(right.closedLoop && left.closedLoop);+ CHECK(right.meanAngle < 8.0f && left.meanAngle < 8.0f);+}++TEST(qremesh_guide_drawing_and_commands) {+ CommandRegistry reg;+ Document doc;+ reg.execute(doc, "new_sphere", {{"subdivisions", 5.0}});+ // A loop seen from the front, mirrored across X: two guides, one stroke.+ std::string pts;+ for (int i = 0; i <= 24; ++i) {+ const float a = 2.0f * kPi * float(i) / 24.0f;+ char buf[64];+ std::snprintf(buf, sizeof buf, "%s%.4f,%.4f,2", i ? " " : "", 0.45 + 0.2 * std::cos(a), 0.2 + 0.2 * std::sin(a));+ pts += buf;+ }+ CommandResult r = reg.execute(doc, "qremesh_guide", {{"points", pts}, {"view", std::string("0,0,-1")},+ {"symmetry", std::string("x")}});+ CHECK(r.ok);+ std::printf(" %s\n", r.message.c_str());+ CHECK(doc.qremeshGuides.size() == 2);+ CHECK(doc.qremeshGuides[0].closed && doc.qremeshGuides[1].closed);+ CHECK(doc.qremeshGuides[0].stroke == doc.qremeshGuides[1].stroke);+ for (const glm::vec3& p : doc.qremeshGuides[0].points) CHECK(std::abs(glm::length(p) - 1.0f) < 0.01f); // on the sphere+ CHECK(doc.qremeshGuides[0].points[0].x > 0.0f && doc.qremeshGuides[1].points[0].x < 0.0f);+ CHECK(doc.modified);+ // An open curve, not mirrored; a loop across the middle mirrored onto itself is kept once.+ CHECK(reg.execute(doc, "qremesh_guide", {{"points", std::string("-0.5,-0.4,2 0,-0.5,2 0.5,-0.4,2")},+ {"view", std::string("0,0,-1")}}).ok);+ CHECK(doc.qremeshGuides.size() == 3 && !doc.qremeshGuides[2].closed);+ CHECK(reg.execute(doc, "qremesh_guide", {{"points", std::string("-0.3,0.6,2 0,0.65,2 0.3,0.6,2")},+ {"view", std::string("0,0,-1")}, {"symmetry", std::string("x")}}).ok);+ CHECK(doc.qremeshGuides.size() == 4);+ CHECK(reg.execute(doc, "qremesh_guides_info").message.find("4 QRemesh guides (2 loops)") != std::string::npos);+ // Too short, or off the model.+ CHECK(!reg.execute(doc, "qremesh_guide", {{"points", std::string("0,0,2 0.001,0,2")}, {"view", std::string("0,0,-1")}}).ok);+ CHECK(!reg.execute(doc, "qremesh_guide", {{"points", std::string("5,5,2 6,5,2")}, {"view", std::string("0,0,-1")}}).ok);+ CHECK(!reg.execute(doc, "qremesh_guide", {{"points", std::string("0,0,2 0.5,0,2")}, {"symmetry", std::string("w")}}).ok);+ // Delete Last takes a stroke (with its mirror), Clear the rest.+ CHECK(reg.execute(doc, "qremesh_guide_delete_last").ok);+ CHECK(doc.qremeshGuides.size() == 3);+ CHECK(reg.execute(doc, "qremesh_guide_delete_last").ok);+ CHECK(doc.qremeshGuides.size() == 2);+ CHECK(reg.execute(doc, "qremesh_guides_clear").ok);+ CHECK(doc.qremeshGuides.empty());+ CHECK(!reg.execute(doc, "qremesh_guide_delete_last").ok);+ CHECK(!reg.execute(doc, "qremesh_guides_clear").ok);+}++TEST(qremesh_guide_command_subtools_and_projects) {+ CommandRegistry reg;+ Document doc;+ reg.execute(doc, "new_sphere", {{"subdivisions", 5.0}});+ CHECK(reg.execute(doc, "qremesh_guide", {{"points", std::string("0.2,0,2 0.4,0.2,2 0.6,0,2 0.4,-0.2,2 0.2,0,2")},+ {"view", std::string("0,0,-1")}}).ok);+ const std::vector<QRemeshGuide> drawn = doc.qremeshGuides;+ // Per SubTool: a new SubTool has none, going back brings them back.+ CHECK(reg.execute(doc, "subtool_append", {{"type", std::string("cube")}}).ok);+ CHECK(doc.subtoolCount() == 2 && doc.activeSubtool == 1);+ CHECK(doc.qremeshGuides.empty());+ doc.selectSubtool(0);+ CHECK(doc.qremeshGuides.size() == drawn.size() && doc.qremeshGuides[0].points == drawn[0].points);++ // Projects keep them, per SubTool, exactly.+ const std::string path = (std::filesystem::temp_directory_path() / "sf_test_guides.sfproj").string();+ std::string err;+ doc.selectSubtool(1);+ CHECK(saveProject(path, doc, err)); // the guided SubTool inactive while saving+ Document loaded;+ CHECK(loadProject(path, loaded, err));+ std::filesystem::remove(path);+ CHECK(loaded.activeSubtool == 1 && loaded.qremeshGuides.empty());+ loaded.selectSubtool(0);+ CHECK(loaded.qremeshGuides.size() == 1);+ CHECK(loaded.qremeshGuides[0].closed == drawn[0].closed && loaded.qremeshGuides[0].stroke == drawn[0].stroke);+ CHECK(loaded.qremeshGuides[0].points.size() == drawn[0].points.size());+ float worst = 0.0f;+ for (size_t i = 0; i < drawn[0].points.size(); ++i)+ worst = std::max(worst, glm::length(loaded.qremeshGuides[0].points[i] - drawn[0].points[i]));+ CHECK(worst < 1e-5f);+ // Bad JSON entries are skipped.+ Json bad;+ CHECK(Json::parse("[{\"points\":[1,2]},{\"points\":\"x\"},{\"closed\":true,\"points\":[0,0,1,0,1,0,1,0,0]}]", bad, err));+ const auto parsed = qremeshGuidesFromJson(bad);+ CHECK(parsed.size() == 1 && parsed[0].closed && parsed[0].points.size() == 3);++ // The qremesh command follows them, keeps them for the original, and can ignore them.+ doc.selectSubtool(0);+ CommandResult r = reg.execute(doc, "qremesh", {{"target", 1500.0}, {"keep_original", true}});+ CHECK(r.ok);+ std::printf(" %s\n", r.message.c_str());+ CHECK(r.message.find("followed 1 guide") != std::string::npos);+ CHECK(doc.qremeshGuides.size() == 1);+ CHECK(doc.subtools[size_t(doc.activeSubtool + 1)].qremeshGuides.size() == 1);+ r = reg.execute(doc, "qremesh", {{"target", 1500.0}, {"guides", false}});+ CHECK(r.ok && r.message.find("guide") == std::string::npos);+ // Guides left behind by a move are ignored, with a note.+ for (glm::vec3& p : doc.qremeshGuides[0].points) p += glm::vec3(5.0f, 0.0f, 0.0f);+ r = reg.execute(doc, "qremesh", {{"target", 1500.0}});+ CHECK(r.ok && r.message.find("off the surface") != std::string::npos);+}++// SF_GUIDE_SWEEP=1: closed-loop rate, mean angle and fans over many eyes, sizes and targets, with and without+// symmetry (for tuning).+TEST(qremesh_guide_sweep) {+ if (!std::getenv("SF_GUIDE_SWEEP")) return;+ const Mesh sphere = makeIcosphere(6);+ int loops = 0, runs = 0;+ size_t fans = 0, fansPlain = 0;+ double angleSum = 0.0;+ uint32_t seed = 7;+ auto rnd = [&] {+ seed = seed * 1664525u + 1013904223u;+ return float(seed >> 8) / float(1u << 24);+ };+ for (int i = 0; i < 32; ++i) {+ const bool sym = i >= 16;+ glm::vec3 eye = glm::normalize(glm::vec3(rnd() - 0.5f, rnd() - 0.5f, rnd() - 0.5f));+ const float angle = 0.25f + 0.4f * rnd();+ if (sym) eye = glm::normalize(glm::vec3(std::sin(angle) + 0.05f + 0.4f * rnd(), 0.6f * (rnd() - 0.5f), 0.8f));+ QRemeshOptions o;+ o.targetQuads = 1000 + int(4000 * rnd());+ o.adaptive = 0.0f;+ o.symmetryAxis = sym ? 0 : -1;+ Mesh plain, out;+ std::string err;+ if (!qremesh(sphere, o, plain, err)) continue;+ o.guides = {guideFrom(circleOnSphere(eye, angle, 240), true)};+ if (!qremesh(sphere, o, out, err)) continue;+ const GuideFit f = measureFit(out, eye, angle);+ const GuideFit g = sym ? measureFit(out, eye * glm::vec3(-1, 1, 1), angle) : f;+ ++runs;+ loops += f.closedLoop && g.closedLoop;+ angleSum += f.meanAngle;+ const size_t hv = highValence(out), hp = highValence(plain);+ fans += hv, fansPlain += hp;+ std::printf(" %2d%s: target %d, angle %.2f: %.1f deg, loop %d%d, fans %zu (plain %zu)\n", i, sym ? " sym" : " ",+ o.targetQuads, angle, f.meanAngle, int(f.closedLoop), int(g.closedLoop), hv, hp);}- 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);+ std::printf(" sweep: %d / %d closed loops, mean %.1f deg, %zu fans (plain %zu)\n", loops, runs,+ angleSum / std::max(runs, 1), fans, fansPlain);}