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
Kelvinlet brushes and Alpha / VDM from viewport in the core
islandmed2d4723f09f2d
diff --git a/CMakeLists.txt b/CMakeLists.txtindex ff6dc1f0..631affde 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -83,6 +83,8 @@ add_library(sculptforge_core STATICsrc/core/Tangents.cppthird_party/mikktspace/mikktspace.csrc/core/Vdm.cpp+ src/core/Kelvinlet.cpp+ src/core/ViewCapture.cppthird_party/tinyexr/tinyexr_impl.cppsrc/core/Matcap.cppsrc/core/Trash.cppdiff --git a/src/core/Benchmark.cpp b/src/core/Benchmark.cppindex 393722e5..db2217b9 100644--- a/src/core/Benchmark.cpp+++ b/src/core/Benchmark.cpp@@ -99,6 +99,16 @@ void registerPerformanceCommands(CommandRegistry& registry) {", undo " + mb(u.undo) + "), GPU buffers about " + mb(u.gpu);return {true, msg};}});+ registry.add({"new_bench_sphere",+ "Replace the scene with the benchmark's sphere of about `millions` million triangles (a cube made "+ "round, then divided: subdivision levels like a real sculpt), for measuring brushes on heavy meshes.",+ {{"millions", ParamSpec::Type::Number, "Triangles in millions (0.01-200, default 5).", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ const double m = std::clamp(argNumber(a, "millions", 5.0), 0.01, 200.0);+ doc.setMesh(makeBenchSphere(size_t(m * 1e6)), "Sphere");+ doc.path.clear();+ return {true, "Created benchmark sphere with " + std::to_string(doc.mesh.triangleCount()) + " triangles"};+ }});registry.add({"set_multithreading","Run brushes, normal and BVH updates, project saving and other per-dab work on every core (on, the ""default) or on one thread (off: slower, for comparing or troubleshooting). Results are the same.",diff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex 5af26762..39a9b59a 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -1,6 +1,7 @@// SculptForge - open source digital sculpting// SPDX-License-Identifier: GPL-3.0-or-later#include "core/Commands.h"+#include "core/ViewCapture.h"#include "core/Bake.h"#include "core/Benchmark.h"@@ -580,6 +581,7 @@ CommandRegistry::CommandRegistry() {registerBrushLibraryCommands(*this); // brush_install, brush_code, brush_delete, ... (BrushLibrary.cpp)registerBrushCommands(*this); // brush_set_alpha (BrushAlpha.cpp)registerVdmCommands(*this); // vdm_set, vdm_capture, vdm_stamp, ... (Vdm.cpp)+ registerCaptureCommands(*this); // capture_alpha, capture_vdm: alpha / VDM from the viewport (ViewCapture.cpp)registerRetopoCommands(*this); // qremesh, project_all (RetopoCommands.cpp)registerQRemeshGuideCommands(*this); // qremesh_guide, ... (QRemeshGuides.cpp)registerZSphereCommands(*this); // zsphere_new, ... (ZSpheres.cpp)diff --git a/src/core/Kelvinlet.cpp b/src/core/Kelvinlet.cppnew file mode 100644index 00000000..2e4af721--- /dev/null+++ b/src/core/Kelvinlet.cpp@@ -0,0 +1,438 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Kelvinlet brushes (see Kelvinlet.h for the math) and the Detail Clone brush (VDM stamps along a stroke).+#include "core/Kelvinlet.h"++#include "core/Sculpt.h"+#include "core/ThreadPool.h"+#include "core/Vdm.h"++#include <algorithm>+#include <cmath>+#include <vector>++namespace sf {++float KelvinletSettings::poisson() const { return 0.49f * std::clamp(squash, 0.0f, 1.0f); }++// ---------------------------------------------------------------------------+// Kernels+// ---------------------------------------------------------------------------++void KelvinletKernel::grabTerms(float r2, float& A, float& B) const {+ A = B = 0.0f;+ for (int i = 0; i < scales; ++i) {+ const float e2 = eps[i] * eps[i];+ const float re2 = r2 + e2;+ const float inv = 1.0f / std::sqrt(re2);+ const float inv3 = inv * inv * inv;+ A += w[i] * ((1.0f - beta) * inv + 0.5f * e2 * inv3);+ B += w[i] * (beta * inv3);+ }+ A *= norm;+ B *= norm;+}++float KelvinletKernel::profile(float r2) const {+ float t = 0.0f;+ for (int i = 0; i < scales; ++i) {+ const float e2 = eps[i] * eps[i];+ const float re2 = r2 + e2;+ const float inv = 1.0f / std::sqrt(re2);+ const float inv3 = inv * inv * inv;+ t += w[i] * (inv3 + 1.5f * e2 * inv3 * inv * inv);+ }+ return t * norm;+}++float KelvinletKernel::envelope(float r) const {+ const float r2 = r * r;+ if (kind == KelvinletKind::Grab) {+ float A, B;+ grabTerms(r2, A, B);+ return std::max(std::abs(A), std::abs(A + B * r2));+ }+ return std::abs(profile(r2)) * r; // displacement per radian (or per unit log scale) at distance r+}++float KelvinletKernel::cutoff(float amount, float epsilon, float maxDist) const {+ if (!(amount > 0.0f) || !(maxDist > 0.0f)) return 0.0f;+ // Walk in from the far end: the first sample whose displacement reaches epsilon (the field is not+ // monotonic: multi-scale kernels dip slightly below zero before they fade).+ constexpr int kSteps = 96;+ for (int i = kSteps; i > 0; --i) {+ const float r = maxDist * float(i) / float(kSteps);+ if (envelope(r) * amount >= epsilon) return std::min(maxDist, r + maxDist / float(kSteps));+ }+ return maxDist / float(kSteps);+}++KelvinletKernel makeKelvinletKernel(KelvinletKind kind, float radius, const KelvinletSettings& settings, bool tight) {+ KelvinletKernel k;+ k.kind = kind;+ const float nu = settings.poisson();+ k.beta = 1.0f / (4.0f * (1.0f - nu));+ const float sharp = std::clamp(settings.sharpness, 0.0f, 1.0f);+ radius = std::max(radius, 1e-6f);+ if (kind == KelvinletKind::Grab && !tight) {+ // Tri-scale (1/r^5 far field). The weights cancel the 1/r and 1/r^3 terms of the far field.+ const float e1 = 0.6f * radius;+ k.scales = 3;+ k.eps[0] = e1;+ k.eps[1] = 1.5f * e1;+ k.eps[2] = 2.25f * e1;+ } else {+ // Bi-scale: Snake's narrower pull (1/r^3 far field), and Twist / Scale (whose single-scale field already+ // falls off as 1/r^3, so the pair falls off as 1/r^5).+ const float e1 = (kind == KelvinletKind::Grab ? 0.6f : 0.8f) * radius;+ k.scales = 2;+ k.eps[0] = e1;+ k.eps[1] = 1.5f * e1;+ }+ // Sharpness: a smaller inner scale gives the cusped, localized peak of the sharp Kelvinlets while the outer+ // scales keep the far field (the weights are recomputed, so the far-field terms still cancel).+ k.eps[0] *= 1.0f - 0.6f * sharp;+ if (k.scales == 3) {+ const float a = k.eps[0] * k.eps[0], b = k.eps[1] * k.eps[1], c = k.eps[2] * k.eps[2];+ k.w[0] = 1.0f;+ k.w[1] = -(c - a) / (c - b);+ k.w[2] = (b - a) / (c - b);+ } else {+ k.w[0] = 1.0f;+ k.w[1] = -1.0f;+ k.w[2] = 0.0f;+ }+ // Normalize: K(0) = I for Grab, t(0) = 1 for Twist and Scale.+ float at0 = 0.0f;+ for (int i = 0; i < k.scales; ++i)+ at0 += k.w[i] * (kind == KelvinletKind::Grab ? (1.5f - k.beta) / k.eps[i] : 2.5f / (k.eps[i] * k.eps[i] * k.eps[i]));+ k.norm = std::abs(at0) > 1e-30f ? 1.0f / at0 : 0.0f;+ return k;+}++glm::vec3 kelvinletGrab(const KelvinletKernel& k, const glm::vec3& r, const glm::vec3& delta) {+ float A, B;+ k.grabTerms(glm::dot(r, r), A, B);+ return A * delta + B * glm::dot(r, delta) * r;+}++glm::vec3 kelvinletTwist(const KelvinletKernel& k, const glm::vec3& r, const glm::vec3& axis, float angle) {+ const float theta = angle * k.profile(glm::dot(r, r));+ // Rodrigues: an exact rotation of this shell about the axis through the centre.+ const float c = std::cos(theta), s = std::sin(theta);+ const glm::vec3 rotated = r * c + glm::cross(axis, r) * s + axis * (glm::dot(axis, r) * (1.0f - c));+ return rotated - r;+}++glm::vec3 kelvinletScale(const KelvinletKernel& k, const glm::vec3& r, float logScale) {+ // Integrates the radial flow dr/dt = s t(r) r (midpoint steps): a pinch never folds a vertex past the centre.+ const float len0 = glm::length(r);+ if (len0 < 1e-12f) return glm::vec3(0.0f);+ const int steps = std::clamp(int(std::ceil(std::abs(logScale) / 0.2f)), 1, 8); // midpoint steps: plenty+ const float h = logScale / float(steps);+ float len = len0;+ for (int i = 0; i < steps; ++i) {+ const float mid = len * std::exp(0.5f * h * k.profile(len * len));+ len *= std::exp(h * k.profile(mid * mid));+ }+ return r * (len / len0 - 1.0f);+}++// ---------------------------------------------------------------------------+// The brushes+// ---------------------------------------------------------------------------++namespace {++KelvinletKind kindOf(BrushType type) {+ switch (type) {+ case BrushType::KelvinTwist: return KelvinletKind::Twist;+ case BrushType::KelvinScale: return KelvinletKind::Scale;+ default: return KelvinletKind::Grab;+ }+}++float window(float r, float cut) {+ // 1 inside 70% of the cutoff, then a smoothstep to 0 at the cutoff.+ const float t = std::clamp((r - 0.7f * cut) / (0.3f * cut), 0.0f, 1.0f);+ return 1.0f - t * t * (3.0f - 2.0f * t);+}++} // namespace++namespace {++// The kernel's radial terms tabulated over u = r^2 / cut^2 (they depend on |r| only), the window folded in: a+// lookup and a lerp per vertex instead of three square roots and divisions per scale.+struct RadialTable {+ static constexpr int kSize = 2048;+ float scale = 0.0f; // kSize / cut^2+ std::vector<float> a, b; // Grab: window * A, window * B; Twist / Scale: profile, window+ void build(const KelvinletKernel& k, float cut) {+ a.resize(kSize + 2);+ b.resize(kSize + 2);+ scale = float(kSize) / (cut * cut);+ for (int i = 0; i <= kSize + 1; ++i) {+ const float r2 = float(std::min(i, kSize)) / scale;+ const float w = window(std::sqrt(r2), cut);+ if (k.kind == KelvinletKind::Grab) {+ float A, B;+ k.grabTerms(r2, A, B);+ a[size_t(i)] = A * w;+ b[size_t(i)] = B * w;+ } else {+ a[size_t(i)] = k.profile(r2);+ b[size_t(i)] = w;+ }+ }+ }+ // r2 < cut^2.+ void at(float r2, float& outA, float& outB) const {+ const float x = r2 * scale;+ const int i = std::min(int(x), kSize);+ const float t = x - float(i);+ outA = a[size_t(i)] + (a[size_t(i) + 1] - a[size_t(i)]) * t;+ outB = b[size_t(i)] + (b[size_t(i) + 1] - b[size_t(i)]) * t;+ }+};++} // namespace++void Sculptor::kelvinletSingle(Mesh& mesh, BVH& bvh, const KelvinletKernel& k, const KelvinletStep& s) {+ auto clock = std::chrono::steady_clock::now();+ float amount = 0.0f, moveScale = 0.0f; // the step's size, and about how far it moves the centre (world)+ switch (k.kind) {+ case KelvinletKind::Grab: amount = moveScale = glm::length(s.delta); break;+ case KelvinletKind::Twist: amount = std::abs(s.angle), moveScale = amount * s.radius; break;+ case KelvinletKind::Scale: amount = std::abs(s.logScale), moveScale = amount * s.radius; break;+ }+ if (!(amount > 0.0f)) return;+ // Adaptive cutoff: where this step moves the surface less than a small fraction of the brush radius (and of+ // the step: a long jump between frames doesn't drag the whole mesh into the pass; the window hides the rest).+ const float epsilon = 0.006f * s.radius + 0.02f * moveScale;+ const float cut = k.cutoff(amount, epsilon, 3.0f * s.radius);+ if (!(cut > 0.0f)) return;+ // Grab: the load point travels from `center` to `center + travel` in `substeps` pieces, each a linear Kelvinlet+ // applied to where the vertex is by then (forward Euler on the flow), all in one pass: one query, one move,+ // one normal and BVH update however far the cursor jumped since the last frame.+ const bool grab = k.kind == KelvinletKind::Grab;+ const glm::vec3 travel = grab ? (glm::length(s.travel) > 0.0f ? s.travel : s.delta) : glm::vec3(0.0f);+ const int n = grab ? std::clamp(s.substeps, 1, 64) : 1;+ const glm::vec3 mid = s.center + 0.5f * travel;+ brushVertices(mesh, bvh, mid, cut + 0.5f * glm::length(travel), verts_);+ if (verts_.empty()) return;+ const auto& pos = mesh.positions;+ if (s.frontFacesOnly) {+ const auto& nrm = mesh.normals;+ std::erase_if(verts_, [&](uint32_t v) { return glm::dot(nrm[v], s.viewDir) > 0.0f; });+ if (verts_.empty()) return;+ }+ RadialTable table;+ table.build(k, cut);+ const float cut2 = cut * cut;+ const glm::vec3 dStep = s.delta / float(n), cStep = travel / float(n);+ scratch_.resize(verts_.size());+ poolFor(verts_.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) {+ const glm::vec3 x0 = pos[verts_[i]];+ glm::vec3 x = x0;+ switch (k.kind) {+ case KelvinletKind::Grab: {+ glm::vec3 c = s.center;+ for (int j = 0; j < n; ++j, c += cStep) {+ const glm::vec3 r = x - c;+ const float r2 = glm::dot(r, r);+ if (r2 >= cut2) continue;+ float A, B;+ table.at(r2, A, B);+ x += A * dStep + B * glm::dot(r, dStep) * r;+ }+ break;+ }+ case KelvinletKind::Twist: {+ const glm::vec3 r = x - s.center;+ const float r2 = glm::dot(r, r);+ if (r2 >= cut2) break;+ float t, w;+ table.at(r2, t, w);+ const float theta = s.angle * t, co = std::cos(theta), si = std::sin(theta);+ const glm::vec3 rot = r * co + glm::cross(s.axis, r) * si + s.axis * (glm::dot(s.axis, r) * (1.0f - co));+ x += (rot - r) * w;+ break;+ }+ case KelvinletKind::Scale: {+ const glm::vec3 r = x - s.center;+ const float r2 = glm::dot(r, r);+ if (r2 >= cut2 || r2 < 1e-24f) break;+ // The radial flow dr/dt = s t(r) r in midpoint steps, t from the table (clamped at the cutoff).+ const int steps = std::clamp(int(std::ceil(amount / 0.2f)), 1, 8);+ const float h = s.logScale / float(steps);+ const float len0 = std::sqrt(r2), lim = cut2 * 0.999f;+ float len = len0, t, w;+ for (int j = 0; j < steps; ++j) {+ table.at(std::min(len * len, lim), t, w);+ const float midLen = len * std::exp(0.5f * h * t);+ table.at(std::min(midLen * midLen, lim), t, w);+ len *= std::exp(h * t);+ }+ table.at(r2, t, w);+ x += r * ((len / len0 - 1.0f) * w);+ break;+ }+ }+ scratch_[i] = x - x0;+ }+ }, 2048);+ // Only what moves noticeably this step goes on (undo, normals, the BVH): the far part of the region moves+ // less than 0.2% of the step, which adds up to less than 0.2% of the whole drag.+ const float keep = 2e-3f * moveScale, keep2 = keep * keep;+ const size_t total = verts_.size();+ size_t kept = 0;+ for (size_t i = 0; i < total; ++i)+ if (glm::dot(scratch_[i], scratch_[i]) > keep2) {+ verts_[kept] = verts_[i];+ scratch_[kept++] = scratch_[i];+ }+ verts_.resize(kept);+ scratch_.resize(kept);+ if (verts_.empty()) return;+ displaceAll(mesh, verts_, scratch_);+ if (kept * 4 > total) {+ finishDab(mesh, bvh, clock); // much of the region moved: refit and renormal the queried leaves+ return;+ }+ timings.kernelMs += lapMs(clock);+ bvh.refit(mesh, verts_);+ timings.bvhMs += lapMs(clock);+ ++timings.dabs;+ timings.vertices += verts_.size();+ dabVerts_.insert(dabVerts_.end(), verts_.begin(), verts_.end());+ kelvinRingNormals_ = true; // updateDabNormals: the moved vertices' rings, not every queried leaf+}++void Sculptor::kelvinletStep(Mesh& mesh, BVH& bvh, BrushType type, const KelvinletStep& step, Symmetry sym) {+ if (!active_ || !isKelvinletBrush(type) || type == BrushType::DetailClone) return;+ const KelvinletKernel k = makeKelvinletKernel(kindOf(type), step.radius, kelvinlet, type == BrushType::KelvinSnake);+ dabVerts_.clear();+ dabLeaves_.clear();+ for (const glm::vec3& m : mirrors(sym)) {+ KelvinletStep ms = step;+ ms.center *= m;+ ms.delta *= m;+ ms.travel *= m;+ ms.viewDir *= m;+ // The rotation axis is a pseudovector: a mirror flips it once more (det = -1 for an odd mirror count).+ ms.axis = step.axis * m * (m.x * m.y * m.z);+ kelvinletSingle(mesh, bvh, k, ms);+ }+ if (kelvinRingNormals_) dabLeaves_.clear(); // (a mirror that moved little: rings for every mirror's vertices)+ kelvinRingNormals_ = false;+ updateDabNormals(mesh, bvh);+}++// A plain dab of a Kelvinlet brush (strokes along a path, the Dots stroke, scripts): Grab and Snake follow the+// stroke (a click without motion pulls the surface toward the viewer), Twist turns and Scale pinches by an amount+// set by Z Intensity per dab (Alt reverses).+void Sculptor::dabKelvinlet(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p, Symmetry sym) {+ if (type == BrushType::DetailClone) {+ dabDetailClone(mesh, bvh, p, sym);+ return;+ }+ const float s = std::clamp(p.strength, 0.0f, 1.0f) * std::clamp(p.pressure, 0.0f, 1.0f);+ const float sign = p.invert ? -1.0f : 1.0f;+ KelvinletStep step;+ step.center = p.center;+ step.radius = p.radius;+ step.viewDir = p.viewDir;+ step.frontFacesOnly = p.frontFacesOnly;+ step.axis = glm::length(p.viewDir) > 1e-6f ? -glm::normalize(p.viewDir) : glm::vec3(0.0f, 0.0f, 1.0f);+ switch (type) {+ case BrushType::KelvinGrab:+ case BrushType::KelvinSnake: {+ if (type == BrushType::KelvinSnake) {+ // The multi-scale Snake: the pull narrows as it travels, so drawn-out shapes taper to a tip.+ if (snakeStroke_ != strokeId_) {+ snakeStroke_ = strokeId_;+ snakeTravel_ = 0.0f;+ }+ snakeTravel_ += glm::length(p.strokeDelta);+ step.radius = p.radius * std::max(0.4f, 1.0f / (1.0f + snakeTravel_ / (4.0f * p.radius)));+ }+ glm::vec3 delta = p.strokeDelta * std::min(1.0f, 2.0f * s);+ if (glm::length(p.strokeDelta) < 1e-9f) delta = step.axis * (sign * 0.05f * s * p.radius);+ // Small pieces: each one is a linear Kelvinlet, so large moves integrate the flow instead of shearing.+ step.delta = delta;+ step.travel = glm::length(p.strokeDelta) < 1e-9f ? delta : p.strokeDelta;+ step.substeps = std::clamp(int(std::ceil(glm::length(step.travel) / (0.4f * step.radius))), 1, 16);+ kelvinletStep(mesh, bvh, type, step, sym);+ return;+ }+ case BrushType::KelvinTwist: step.angle = sign * s * 0.15f; break;+ case BrushType::KelvinScale: step.logScale = -sign * s * 0.06f; break; // pinches; Alt swells+ default: return;+ }+ kelvinletStep(mesh, bvh, type, step, sym);+}++// ---------------------------------------------------------------------------+// Detail Clone: the VDM brush's map stamped along the stroke, each stamp turned to follow the stroke+// ---------------------------------------------------------------------------++void Sculptor::cloneStamp(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym) {+ dabVerts_.clear();+ dabLeaves_.clear();+ for (const glm::vec3& m : mirrors(sym)) {+ DabParams mp = p;+ mp.center *= m;+ mp.viewDir *= m;+ mp.strokeDelta *= m;+ mp.alphaUp *= m;+ dabVdmSingle(mesh, bvh, mp, m.x * m.y * m.z);+ }+ updateDabNormals(mesh, bvh);+}++void Sculptor::dabDetailClone(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym) {+ if (!active_) return;+ if (clone_.stroke != strokeId_) {+ clone_ = CloneState{};+ clone_.stroke = strokeId_;+ }+ const float r = p.radius;+ const float spacing = 2.0f * r * std::clamp(kelvinlet.cloneSpacing, 0.25f, 3.0f);+ auto stampAt = [&](DabParams q, const glm::vec3& dir) {+ if (kelvinlet.cloneFollowStroke && glm::length(dir) > 1e-9f) q.alphaUp = glm::normalize(dir);+ cloneStamp(mesh, bvh, q, sym);+ clone_.last = q.center;+ clone_.stamped = true;+ };+ if (!clone_.stamped) {+ if (!clone_.pending) { // the first stamp waits for the stroke's direction+ clone_.pending = true;+ clone_.first = p;+ return;+ }+ const glm::vec3 dir = p.center - clone_.first.center;+ if (glm::length(dir) < 0.02f * r) { // dabs in place (scripts, a Dots click held still): stamp as turned+ stampAt(clone_.first, glm::vec3(0.0f));+ clone_.pending = false;+ return;+ }+ if (glm::length(dir) < 0.25f * r) return; // not far enough yet to say which way the stroke goes+ stampAt(clone_.first, dir);+ clone_.pending = false;+ }+ const glm::vec3 d = p.center - clone_.last;+ if (glm::length(d) >= spacing) stampAt(p, d);+}++void Sculptor::flushDetailClone(Mesh& mesh, BVH& bvh, Symmetry sym) {+ if (!active_ || clone_.stroke != strokeId_ || !clone_.pending || clone_.stamped) return;+ DabParams q = clone_.first;+ cloneStamp(mesh, bvh, q, sym);+ clone_.pending = false;+ clone_.stamped = true;+}++} // namespace sfdiff --git a/src/core/Kelvinlet.h b/src/core/Kelvinlet.hnew file mode 100644index 00000000..16dfaf48--- /dev/null+++ b/src/core/Kelvinlet.h@@ -0,0 +1,92 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Kelvinlet brushes: physically based elastic deformation (de Goes & James, "Regularized Kelvinlets: Sculpting+// Brushes based on Fundamental Solutions of Elasticity", SIGGRAPH 2017; the localized falloff idea of "Sharp+// Kelvinlets", 2019). A brush is the closed-form displacement an infinite elastic solid makes when a regularized+// point load (a force, a twist or a uniform scale) acts on it, so the surface moves like clay pushed with a thumb:+// no falloff edge, and the material bulges out around the grab when it is incompressible.+//+// The regularized Kelvinlet for a force f at the origin, with a = 1/(4 pi mu), b = a / (4 (1 - nu)), r_e =+// sqrt(|r|^2 + e^2):+// u(r) = [ ((a - b) / r_e + a e^2 / (2 r_e^3)) I + (b / r_e^3) r r^T ] f+// Its value at r = 0 is (3a - 2b) / (2e) f, so a "grab" that moves the brush centre by D uses f = 2e D / (3a - 2b);+// the result then depends only on Poisson's ratio nu (the Squash slider), not on the stiffness mu. A single+// Kelvinlet falls off as 1/r and reaches everywhere; the paper's multi-scale extrapolation combines several scales+// e_i with weights that cancel the far field (sum w_i = 0 cancels 1/r, sum w_i e_i^2 = 0 cancels 1/r^3), so the+// tri-scale brush falls off as 1/r^5 and can be cut off where it moves less than an epsilon.+//+// Twist (a torque) and Scale (a uniform pinch / expand) are the paper's affine loads:+// u_twist(r) = -a (1/r_e^3 + 3 e^2 / (2 r_e^5)) (q x r), u_scale(r) = (2b - a)(1/r_e^3 + 3 e^2 / (2 r_e^5)) s r+// We use the radial profile t(r) = (1/r_e^3 + 3e^2/(2 r_e^5)) normalized to 1 at the centre (bi-scale, so it falls+// off as 1/r^5): Twist turns every spherical shell around the centre by angle * t(r) (an exact rotation, which keeps+// volume, as twisting does in the paper), Scale integrates the radial flow dr/dt = s t(r) r.+//+// Each brush step evaluates only the vertices inside an adaptive cutoff radius: the distance past which this+// step's displacement is below epsilon, found from the kernel's envelope; a smooth window takes the last part of+// the field to zero, so there is never an edge.+#pragma once++#include <glm/glm.hpp>++#include <cstddef>++namespace sf {++// Brush > Kelvinlet (saved with the project's brush settings by the app).+struct KelvinletSettings {+ float squash = 0.5f; // 0..1: Poisson's ratio nu = 0.49 * squash. 0 = rubbery (no bulge), 1 = incompressible clay+ float sharpness = 0.0f; // 0..1: blends toward a tighter, cusped kernel (smaller inner scale): pointed pulls+ float cloneSpacing = 1.0f; // Detail Clone: stamp spacing along the stroke, in stamp widths (0.25..3)+ bool cloneFollowStroke = true; // Detail Clone: the stamp's top turns with the stroke (else it keeps screen up)++ float poisson() const;+};++enum class KelvinletKind { Grab, Twist, Scale };++// The normalized kernel of one brush: scales e_i and weights w_i (multi-scale extrapolation).+struct KelvinletKernel {+ KelvinletKind kind = KelvinletKind::Grab;+ int scales = 3;+ float eps[3]{1.0f, 1.5f, 2.25f};+ float w[3]{1.0f, 0.0f, 0.0f};+ float beta = 0.25f; // b / a = 1 / (4 (1 - nu))+ float norm = 1.0f; // 1 / (unnormalized value at r = 0)++ // Grab: the 3x3 response at offset r is A(r) I + B(r) r r^T (A, B already normalized; K(0) = I).+ void grabTerms(float r2, float& A, float& B) const;+ // Twist / Scale: the radial profile t(r), 1 at the centre.+ float profile(float r2) const;+ // Largest response at distance r (the envelope used for the cutoff): |A| + |B| r^2 for Grab, t for the others.+ float envelope(float r) const;+ // The smallest distance past which envelope() * amount stays below `epsilon` (searched up to `maxDist`).+ float cutoff(float amount, float epsilon, float maxDist) const;+};++// The kernel for a brush of world radius `radius`: Grab is tri-scale (1/r^5 falloff), Twist and Scale bi-scale.+// The scales are chosen so the visible footprint is close to a Move brush of the same radius (a third to a half+// of the displacement at half the radius, about a tenth at the radius) with a soft tail out to ~2 radii. `tight` (the Snake) is the bi-scale grab: a+// narrower pull that tapers.+KelvinletKernel makeKelvinletKernel(KelvinletKind kind, float radius, const KelvinletSettings& settings, bool tight = false);++// Displacement of a point at offset `r` from the brush centre (pure functions, for tests and the brush).+glm::vec3 kelvinletGrab(const KelvinletKernel& k, const glm::vec3& r, const glm::vec3& delta);+glm::vec3 kelvinletTwist(const KelvinletKernel& k, const glm::vec3& r, const glm::vec3& axis, float angle);+glm::vec3 kelvinletScale(const KelvinletKernel& k, const glm::vec3& r, float logScale);++// One step of a Kelvinlet brush (Sculptor::kelvinlet): what moves this step.+struct KelvinletStep {+ glm::vec3 center{0.0f}; // where the load acts (the grabbed point; the twist / scale centre)+ float radius = 0.1f; // world units: the brush's footprint+ glm::vec3 delta{0.0f}; // Grab / Snake: how far the surface at the centre moves this step+ glm::vec3 travel{0.0f}; // Grab / Snake: how far the load point itself moves (0: as far as delta)+ int substeps = 1; // Grab / Snake: the move integrated in this many pieces, in one pass over the vertices+ glm::vec3 axis{0.0f, 0.0f, 1.0f}; // Twist: the rotation axis (unit)+ float angle = 0.0f; // Twist: radians this step at the centre+ float logScale = 0.0f; // Scale: ln(size factor) this step at the centre (< 0 pinches)+ glm::vec3 viewDir{0.0f, 0.0f, -1.0f};+ bool frontFacesOnly = false;+};++} // namespace sfdiff --git a/src/core/PathStroke.cpp b/src/core/PathStroke.cppindex de03b760..6ccdc640 100644--- a/src/core/PathStroke.cpp+++ b/src/core/PathStroke.cpp@@ -152,6 +152,45 @@ int strokePath(Document& doc, const BrushRecipe* recipe, BrushType type, const Pfor (size_t i = 1; i < samples.size(); ++i) doc.sculptor.grab(mesh, doc.bvh, samples[i] - samples[i - 1]);dabs = int(samples.size());}+ } else if ((type == BrushType::KelvinGrab || type == BrushType::KelvinSnake) && !recipe) {+ // Elastic grab and Snake: the grabbed point follows the path (in the view plane, as the cursor drags it;+ // a ray would hit the surface behind a pulled shape), in small steps.+ RayHit hit;+ if (project(samples.front(), hit)) {+ DabParams p = base;+ glm::vec3 tip = hit.position;+ const glm::vec3 offset = hit.position - samples.front();+ for (size_t i = 1; i < samples.size(); ++i) {+ p.center = tip;+ p.strokeDelta = samples[i] + offset - tip;+ doc.sculptor.dab(mesh, doc.bvh, type, p, stroke.symmetry);+ tip += p.strokeDelta;+ }+ if (samples.size() == 1) {+ p.center = tip;+ doc.sculptor.dab(mesh, doc.bvh, type, p, stroke.symmetry);+ }+ dabs = int(samples.size());+ }+ } else if ((type == BrushType::KelvinTwist || type == BrushType::KelvinScale) && !recipe && samples.size() > 1) {+ // Twist and Scale act at the first point; moving right along the screen turns clockwise / swells (as a+ // drag in the viewport does), by the distance in brush radii.+ RayHit hit;+ if (project(samples.front(), hit)) {+ KelvinletStep step;+ step.center = hit.position;+ step.radius = radius;+ step.viewDir = view;+ step.axis = -view;+ const float amount = std::min(1.0f, 2.0f * base.strength) * base.pressure * (stroke.invert ? -1.0f : 1.0f);+ for (size_t i = 1; i < samples.size(); ++i) {+ const float dx = glm::dot(samples[i] - samples[i - 1], right) / radius * amount;+ if (type == BrushType::KelvinTwist) step.angle = -dx * 1.5707963f;+ else step.logScale = dx * 0.6f;+ doc.sculptor.kelvinletStep(mesh, doc.bvh, type, step, stroke.symmetry);+ }+ dabs = int(samples.size());+ }} else {glm::vec3 last{0.0f};bool haveLast = false;@@ -169,6 +208,7 @@ int strokePath(Document& doc, const BrushRecipe* recipe, BrushType type, const P++dabs;}}+ doc.sculptor.flushDetailClone(mesh, doc.bvh, stroke.symmetry); // a click with Detail CloneUndoRecord record = doc.sculptor.endStroke();if (!record.empty()) doc.undo.push(std::move(record));return dabs;diff --git a/src/core/Sculpt.cpp b/src/core/Sculpt.cppindex 389b0545..0237d348 100644--- a/src/core/Sculpt.cpp+++ b/src/core/Sculpt.cpp@@ -29,6 +29,11 @@ const char* brushName(BrushType type) {case BrushType::Layer: return "Layer";case BrushType::Nudge: return "Nudge";case BrushType::Vdm: return "VDM";+ case BrushType::KelvinGrab: return "KelvinGrab";+ case BrushType::KelvinTwist: return "KelvinTwist";+ case BrushType::KelvinScale: return "KelvinScale";+ case BrushType::KelvinSnake: return "KelvinSnake";+ case BrushType::DetailClone: return "DetailClone";default: return "?";}}@@ -453,6 +458,10 @@ UndoRecord Sculptor::endStroke() {void Sculptor::dab(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p, Symmetry sym) {if (!active_) return;+ if (isKelvinletBrush(type)) { // Kelvinlet.cpp (no remeshing: they move the surface, as Move does)+ dabKelvinlet(mesh, bvh, type, p, sym);+ return;+ }if (type != BrushType::Move) {const bool useAlpha = p.alpha && !p.alpha->empty(); // (the reach dabSingle gives the brush)const float reach = useAlpha ? 1.4143f : type == BrushType::ClayBuildup ? 1.3f : 1.0f;diff --git a/src/core/Sculpt.h b/src/core/Sculpt.hindex 674e5c8a..0a1ae3ad 100644--- a/src/core/Sculpt.h+++ b/src/core/Sculpt.h@@ -5,6 +5,7 @@#include "core/BVH.h"#include "core/BrushRecipe.h"#include "core/Dyntopo.h"+#include "core/Kelvinlet.h"#include "core/Mesh.h"#include "core/Undo.h"@@ -26,9 +27,21 @@ enum class BrushType {Layer, // raises to one fixed height per stroke (overlaps never stack)Nudge, // slides the surface sideways along the strokeVdm, // vector displacement: stamps DabParams::vdm (a horn, an ear...) with overhangs (core/Vdm.h)+ // Kelvinlet brushes (core/Kelvinlet.h): physically based elastic deformation.+ KelvinGrab, // elastic move: drags the surface like clay, bulging with Squash (Poisson's ratio)+ KelvinTwist, // turns the surface around the view axis, fading smoothly+ KelvinScale, // pinches (or swells) the surface toward the centre+ KelvinSnake, // multi-scale elastic SnakeHook: pulls tapering horns out along the stroke+ DetailClone, // stamps the VDM brush's map along the stroke, each stamp turned to follow it (Kelvinlet.cpp)Count};+// The brushes Kelvinlet.cpp implements (Sculptor::dab hands them over).+inline bool isKelvinletBrush(BrushType t) {+ return t == BrushType::KelvinGrab || t == BrushType::KelvinTwist || t == BrushType::KelvinScale ||+ t == BrushType::KelvinSnake || t == BrushType::DetailClone;+}+const char* brushName(BrushType type);struct DabParams {@@ -118,6 +131,15 @@ public:// DragDot; restoreStroke) put positions back, not topology. restoreStroke holds it too.void holdTopology() { topologyHeld_ = true; }+ // Kelvinlet brushes (core/Kelvinlet.h, defined in Kelvinlet.cpp): one step of KelvinGrab / KelvinSnake+ // (step.delta), KelvinTwist (step.angle) or KelvinScale (step.logScale), mirrored by `sym`. dab() turns a plain+ // dab into steps. The settings are Brush > Kelvinlet's.+ KelvinletSettings kelvinlet;+ void kelvinletStep(Mesh& mesh, BVH& bvh, BrushType type, const KelvinletStep& step, Symmetry sym);+ // Detail Clone: a stroke that never moved has its one stamp waiting (for a direction): this presses it.+ // Call before endStroke() (harmless for every other brush).+ void flushDetailClone(Mesh& mesh, BVH& bvh, Symmetry sym);+// Mirror sign vectors for the enabled symmetry axes (always starts with (1,1,1)).static std::vector<glm::vec3> mirrors(Symmetry sym);@@ -130,6 +152,20 @@ private:void dabRecipeSingle(Mesh& mesh, BVH& bvh, const BrushRecipe& r, const DabParams& p);// The Vdm brush (defined in Vdm.cpp); `handedness` -1 for a mirrored pass, so the stamp mirrors exactly.void dabVdmSingle(Mesh& mesh, BVH& bvh, const DabParams& p, float handedness);+ // Kelvinlet.cpp: the Kelvinlet brushes and Detail Clone.+ void dabKelvinlet(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p, Symmetry sym);+ void kelvinletSingle(Mesh& mesh, BVH& bvh, const KelvinletKernel& k, const KelvinletStep& s);+ void dabDetailClone(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym);+ void cloneStamp(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym);+ struct CloneState {+ uint64_t stroke = 0;+ bool pending = false, stamped = false;+ DabParams first;+ glm::vec3 last{0.0f};+ } clone_;+ bool kelvinRingNormals_ = false; // a Kelvinlet pass moved only part of what it queried+ uint64_t snakeStroke_ = 0;+ float snakeTravel_ = 0.0f;void finishDab(Mesh& mesh, BVH& bvh, std::chrono::steady_clock::time_point clock);void updateDabNormals(Mesh& mesh, const BVH& bvh);void touch(Mesh& mesh, uint32_t v);diff --git a/src/core/ViewCapture.cpp b/src/core/ViewCapture.cppnew file mode 100644index 00000000..c9fd3538--- /dev/null+++ b/src/core/ViewCapture.cpp@@ -0,0 +1,688 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/ViewCapture.h"++#include "core/BVH.h"+#include "core/BrushLibrary.h"+#include "core/Commands.h"+#include "core/Document.h"+#include "core/Mesh.h"+#include "core/PathStroke.h"+#include "core/ThreadPool.h"++#include <algorithm>+#include <chrono>+#include <cmath>+#include <deque>+#include <filesystem>+#include <limits>++namespace sf {++namespace {++constexpr float kInf = std::numeric_limits<float>::infinity();++float smooth01(float t) {+ t = std::clamp(t, 0.0f, 1.0f);+ return t * t * (3.0f - 2.0f * t);+}++// 1 inside, fading to 0 over the last `fade` of the square (or circle) at u, v in -1..1.+float borderFade(float u, float v, bool circle, float fade) {+ const float d = circle ? std::sqrt(u * u + v * v) : std::max(std::abs(u), std::abs(v));+ if (d >= 1.0f) return 0.0f;+ if (fade <= 1e-4f) return 1.0f;+ return smooth01((1.0f - d) / fade);+}++// A triangle in texel coordinates (x right, y down; pixel centres at integers) with a depth (smaller = in front)+// and a vector attribute per corner.+struct RasterTri {+ glm::vec2 q[3];+ float z[3];+ glm::vec3 a[3];+};++// Front-most rasterization of `tris` into res x res: depth (kInf where nothing) and, when given, the attribute.+// Rows are split into bands rasterized in parallel, so no texel is written by two threads.+void rasterize(int res, const std::vector<RasterTri>& tris, std::vector<float>& depth, std::vector<glm::vec3>* attr) {+ depth.assign(size_t(res) * size_t(res), kInf);+ if (attr) attr->assign(depth.size(), glm::vec3(0.0f));+ const size_t bands = size_t(std::min(res, 64));+ std::vector<std::vector<uint32_t>> inBand(bands);+ for (uint32_t t = 0; t < tris.size(); ++t) {+ const RasterTri& r = tris[t];+ const float lo = std::min({r.q[0].y, r.q[1].y, r.q[2].y}), hi = std::max({r.q[0].y, r.q[1].y, r.q[2].y});+ const int r0 = std::max(0, int(std::ceil(lo - 1e-4f))), r1 = std::min(res - 1, int(std::floor(hi + 1e-4f)));+ if (r0 > r1) continue;+ const size_t b0 = size_t(r0) * bands / size_t(res), b1 = size_t(r1) * bands / size_t(res);+ for (size_t b = b0; b <= b1; ++b) inBand[b].push_back(t);+ }+ poolFor(bands, [&](size_t bb, size_t be) {+ for (size_t band = bb; band < be; ++band) {+ const int rowLo = int(band * size_t(res) / bands), rowHi = int((band + 1) * size_t(res) / bands) - 1;+ for (uint32_t t : inBand[band]) {+ const RasterTri& r = tris[t];+ const glm::vec2* q = r.q;+ const float area = (q[1].x - q[0].x) * (q[2].y - q[0].y) - (q[2].x - q[0].x) * (q[1].y - q[0].y);+ if (std::abs(area) < 1e-12f) continue;+ const int x0 = std::max(0, int(std::ceil(std::min({q[0].x, q[1].x, q[2].x}) - 1e-4f)));+ const int x1 = std::min(res - 1, int(std::floor(std::max({q[0].x, q[1].x, q[2].x}) + 1e-4f)));+ const int y0 = std::max(rowLo, int(std::ceil(std::min({q[0].y, q[1].y, q[2].y}) - 1e-4f)));+ const int y1 = std::min(rowHi, int(std::floor(std::max({q[0].y, q[1].y, q[2].y}) + 1e-4f)));+ for (int y = y0; y <= y1; ++y)+ for (int x = x0; x <= x1; ++x) {+ const glm::vec2 c{float(x), float(y)};+ auto edge = [&](int a, int b) {+ return ((q[b].x - q[a].x) * (c.y - q[a].y) - (c.x - q[a].x) * (q[b].y - q[a].y)) / area;+ };+ const float w0 = edge(1, 2), w1 = edge(2, 0), w2 = edge(0, 1);+ if (w0 < -1e-4f || w1 < -1e-4f || w2 < -1e-4f) continue;+ const float z = r.z[0] * w0 + r.z[1] * w1 + r.z[2] * w2;+ const size_t i = size_t(y) * size_t(res) + size_t(x);+ if (z >= depth[i]) continue;+ depth[i] = z;+ if (attr) (*attr)[i] = r.a[0] * w0 + r.a[1] * w1 + r.a[2] * w2;+ }+ }+ }+ }, 1, 1);+}++glm::vec2 texel(float u, float v, int res) {+ return glm::vec2((u * 0.5f + 0.5f) * float(res) - 0.5f, (0.5f - v * 0.5f) * float(res) - 0.5f);+}++// The front-most depth along the view (dot(x - centre, forward)) over the square, from the triangles near it.+void viewDepth(const Mesh& mesh, const BVH& bvh, const CaptureFrame& f, int res, std::vector<float>& depth) {+ std::vector<uint32_t> tris;+ bvh.queryTriangles(mesh, f.center, f.halfSize * 2.6f, tris);+ std::vector<RasterTri> raster;+ raster.reserve(tris.size());+ const float inv = 1.0f / f.halfSize;+ for (uint32_t t : tris) {+ if (mesh.hasHidden() && mesh.triangleHidden(t)) continue;+ RasterTri r;+ float umin = kInf, umax = -kInf, vmin = kInf, vmax = -kInf;+ for (int k = 0; k < 3; ++k) {+ const glm::vec3 o = mesh.positions[mesh.triangles[t][k]] - f.center;+ const float u = glm::dot(o, f.right) * inv, v = glm::dot(o, f.up) * inv;+ umin = std::min(umin, u), umax = std::max(umax, u), vmin = std::min(vmin, v), vmax = std::max(vmax, v);+ r.q[k] = texel(u, v, res);+ r.z[k] = glm::dot(o, f.forward);+ r.a[k] = glm::vec3(0.0f);+ }+ if (umax < -1.0f || umin > 1.0f || vmax < -1.0f || vmin > 1.0f) continue;+ raster.push_back(r);+ }+ rasterize(res, raster, depth, nullptr);+}++// A wide blur of `h` weighted by `m` (normalized convolution: uncovered texels don't pull it down): three box+// blurs of running sums, which approximate a Gaussian of `sigma` in time independent of its width.+std::vector<float> maskedBlur(const std::vector<float>& h, const std::vector<float>& m, int res, float sigma) {+ const int rad = std::max(1, int(std::lround(std::sqrt(sigma * sigma + 1.0f) * 0.8660254f))); // 3 boxes ~ sigma+ const size_t n = size_t(res) * size_t(res);+ std::vector<float> hm(n), mm(m), tmp(n);+ for (size_t i = 0; i < n; ++i) hm[i] = h[i] * m[i];+ auto box = [&](std::vector<float>& img, bool horizontal) {+ poolFor(size_t(res), [&](size_t b, size_t e) {+ std::vector<double> line(size_t(res) + 1);+ for (size_t row = b; row < e; ++row) {+ auto at = [&](int c) -> float& {+ return horizontal ? img[row * size_t(res) + size_t(c)] : img[size_t(c) * size_t(res) + row];+ };+ line[0] = 0.0;+ for (int c = 0; c < res; ++c) line[size_t(c) + 1] = line[size_t(c)] + double(at(c));+ for (int c = 0; c < res; ++c) {+ const int lo = std::max(0, c - rad), hi = std::min(res - 1, c + rad);+ at(c) = float((line[size_t(hi) + 1] - line[size_t(lo)]) / double(2 * rad + 1));+ }+ }+ }, 8);+ };+ for (int pass = 0; pass < 3; ++pass)+ for (bool horizontal : {true, false}) {+ box(hm, horizontal);+ box(mm, horizontal);+ }+ std::vector<float> out(n, 0.0f);+ for (size_t i = 0; i < n; ++i) out[i] = mm[i] > 1e-6f ? hm[i] / mm[i] : 0.0f;+ return out;+}++} // namespace++CaptureFrame makeCaptureFrame(const glm::vec3& center, const glm::vec3& forward, const glm::vec3& up, float halfSize,+ bool circle) {+ CaptureFrame f;+ f.center = center;+ f.forward = glm::length(forward) > 1e-12f ? glm::normalize(forward) : glm::vec3(0.0f, 0.0f, -1.0f);+ glm::vec3 u = up - f.forward * glm::dot(up, f.forward);+ if (glm::length(u) < 1e-6f) {+ const glm::vec3 helper = std::abs(f.forward.y) > 0.9f ? glm::vec3(0.0f, 0.0f, -1.0f) : glm::vec3(0.0f, 1.0f, 0.0f);+ u = helper - f.forward * glm::dot(helper, f.forward);+ }+ f.up = glm::normalize(u);+ f.right = glm::cross(f.forward, f.up); // forward x up = right for a camera looking along forward+ f.halfSize = std::max(halfSize, 1e-6f);+ f.circle = circle;+ return f;+}++// ---------------------------------------------------------------------------+// Height alpha+// ---------------------------------------------------------------------------++bool captureHeightAlpha(const Mesh& mesh, const BVH& bvh, const CaptureFrame& f, const CaptureOptions& opt,+ BrushAlpha& out, std::string& error, CaptureInfo* info) {+ const int res = std::clamp(opt.resolution, 32, 1024);+ if (mesh.triangleCount() == 0) {+ error = "The active SubTool is empty";+ return false;+ }+ std::vector<float> depth;+ viewDepth(mesh, bvh, f, res, depth);+ const size_t n = depth.size();+ std::vector<float> h(n, 0.0f), m(n, 0.0f);+ int covered = 0;+ for (size_t i = 0; i < n; ++i)+ if (depth[i] < kInf) {+ h[i] = -depth[i]; // toward the viewer+ m[i] = 1.0f;+ ++covered;+ }+ if (covered < 16) {+ error = "Nothing to capture there: drag over the model";+ return false;+ }+ auto uvOf = [&](size_t i) {+ const int x = int(i % size_t(res)), y = int(i / size_t(res));+ return glm::vec2((float(x) + 0.5f) / float(res) * 2.0f - 1.0f, 1.0f - (float(y) + 0.5f) / float(res) * 2.0f);+ };+ if (opt.fitPlane) {+ // Least squares h = a u + b v + c over the covered texels: the tilt of the surface goes.+ double s[3][3] = {}, r[3] = {};+ for (size_t i = 0; i < n; ++i) {+ if (m[i] == 0.0f) continue;+ const glm::vec2 uv = uvOf(i);+ const double x[3] = {uv.x, uv.y, 1.0};+ for (int a = 0; a < 3; ++a) {+ r[a] += x[a] * h[i];+ for (int b = 0; b < 3; ++b) s[a][b] += x[a] * x[b];+ }+ }+ // Cramer's rule on the 3x3 normal equations.+ auto det3 = [](double A[3][3]) {+ return A[0][0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) - A[0][1] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) ++ A[0][2] * (A[1][0] * A[2][1] - A[1][1] * A[2][0]);+ };+ const double d = det3(s);+ if (std::abs(d) > 1e-12) {+ double coef[3];+ for (int c = 0; c < 3; ++c) {+ double A[3][3];+ for (int a = 0; a < 3; ++a)+ for (int b = 0; b < 3; ++b) A[a][b] = b == c ? r[a] : s[a][b];+ coef[c] = det3(A) / d;+ }+ for (size_t i = 0; i < n; ++i) {+ if (m[i] == 0.0f) continue;+ const glm::vec2 uv = uvOf(i);+ h[i] -= float(coef[0] * uv.x + coef[1] * uv.y + coef[2]);+ }+ }+ }+ if (opt.smoothing > 0.0f) {+ // Detail only: the smooth form (a wide blur) is taken away, so a curved surface gives a flat stamp.+ const float sigma = std::max(1.0f, (1.05f - std::clamp(opt.smoothing, 0.0f, 1.0f)) * float(res) * 0.25f);+ const std::vector<float> base = maskedBlur(h, m, res, sigma);+ for (size_t i = 0; i < n; ++i)+ if (m[i] > 0.0f) h[i] -= base[i];+ }+ // Normalize: the 2nd percentile is 0, the top is 1.+ std::vector<float> vals;+ vals.reserve(size_t(covered));+ for (size_t i = 0; i < n; ++i)+ if (m[i] > 0.0f) vals.push_back(h[i]);+ std::sort(vals.begin(), vals.end());+ const float lo = vals[vals.size() / 50], hi = vals.back();+ const float range = std::max(hi - lo, 1e-9f);+ out = BrushAlpha{};+ out.name = "Captured";+ out.width = out.height = res;+ out.values.assign(n, 0.0f);+ const float fade = std::clamp(opt.edgeFade, 0.0f, 0.9f);+ for (size_t i = 0; i < n; ++i) {+ if (m[i] == 0.0f) continue;+ float v = std::clamp((h[i] - lo) / range, 0.0f, 1.0f);+ if (opt.invert) v = 1.0f - v;+ const glm::vec2 uv = uvOf(i);+ out.values[i] = v * borderFade(uv.x, uv.y, f.circle, fade);+ }+ if (info) {+ info->depthRange = hi - lo;+ info->coverage = covered;+ }+ return true;+}++// ---------------------------------------------------------------------------+// VDM+// ---------------------------------------------------------------------------++bool captureVdmFromView(const Mesh& mesh, const BVH& bvh, const CaptureFrame& f, const CaptureOptions& opt,+ VectorDisplacement& out, std::string& error, CaptureInfo* info) {+ const int res = std::clamp(opt.resolution, 32, 1024);+ if (mesh.triangleCount() == 0) {+ error = "The active SubTool is empty";+ return false;+ }+ const float half = f.halfSize, inv = 1.0f / half;+ // 1. The front surface in the square: candidates near the centre whose projection is inside (a little+ // margin, so the base reaches the border) and that are not much behind the front-most surface there (the+ // undersides of overhangs stay, the far side of the model doesn't).+ constexpr int kVisRes = 128;+ std::vector<float> front;+ viewDepth(mesh, bvh, f, kVisRes, front);+ std::vector<uint32_t> cand;+ bvh.queryVertices(mesh, f.center, half * 2.6f, cand); // sorted+ const float tol = 0.75f * half;+ std::vector<uint8_t> ok(cand.size(), 0);+ poolFor(cand.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) {+ const uint32_t v = cand[i];+ if (mesh.hasHidden() && mesh.vertexHidden(v)) continue;+ const glm::vec3 o = mesh.positions[v] - f.center;+ const float u = glm::dot(o, f.right) * inv, w = glm::dot(o, f.up) * inv;+ if (std::abs(u) > 1.08f || std::abs(w) > 1.08f) continue;+ const glm::vec2 q = texel(std::clamp(u, -1.0f, 1.0f), std::clamp(w, -1.0f, 1.0f), kVisRes);+ const int x = std::clamp(int(std::lround(q.x)), 0, kVisRes - 1), y = std::clamp(int(std::lround(q.y)), 0, kVisRes - 1);+ float zf = kInf; // the nearest front depth around (holes in the coarse map at silhouettes)+ for (int dy = -1; dy <= 1; ++dy)+ for (int dx = -1; dx <= 1; ++dx) {+ const int xx = std::clamp(x + dx, 0, kVisRes - 1), yy = std::clamp(y + dy, 0, kVisRes - 1);+ zf = std::min(zf, front[size_t(yy) * kVisRes + size_t(xx)]);+ }+ if (zf < kInf && glm::dot(o, f.forward) <= zf + tol) ok[i] = 1;+ }+ });+ auto candIndex = [&](uint32_t v) -> int64_t {+ const auto it = std::lower_bound(cand.begin(), cand.end(), v);+ return it != cand.end() && *it == v ? int64_t(it - cand.begin()) : -1;+ };+ // 2. Connected to the surface under the centre (flood fill over the candidates).+ int64_t seed = -1;+ float best = kInf;+ for (size_t i = 0; i < cand.size(); ++i)+ if (ok[i]) {+ const float d = glm::distance(mesh.positions[cand[i]], f.center);+ if (d < best) best = d, seed = int64_t(i);+ }+ if (seed < 0) {+ error = "Nothing to capture there: drag over the model";+ return false;+ }+ std::vector<uint8_t> inRegion(cand.size(), 0);+ std::deque<uint32_t> queue{uint32_t(seed)};+ inRegion[size_t(seed)] = 1;+ while (!queue.empty()) {+ const uint32_t i = queue.front();+ queue.pop_front();+ for (uint32_t nb : mesh.neighbors(cand[i])) {+ const int64_t j = candIndex(nb);+ if (j < 0 || !ok[size_t(j)] || inRegion[size_t(j)]) continue;+ inRegion[size_t(j)] = 1;+ queue.push_back(uint32_t(j));+ }+ }+ std::vector<uint32_t> region; // sorted (cand is)+ for (size_t i = 0; i < cand.size(); ++i)+ if (inRegion[i]) region.push_back(cand[i]);+ const size_t n = region.size();+ if (n < 16) {+ error = "Too few points in the square: drag a larger square, or divide the mesh";+ return false;+ }+ auto local = [&](uint32_t v) -> int64_t {+ const auto it = std::lower_bound(region.begin(), region.end(), v);+ return it != region.end() && *it == v ? int64_t(it - region.begin()) : -1;+ };+ // Adjacency inside the region (CSR) and the rim (vertices with a neighbour outside it).+ std::vector<uint32_t> start(n + 1, 0), adj;+ std::vector<uint8_t> rim(n, 0);+ double edgeSum = 0.0;+ size_t edgeCount = 0;+ for (size_t i = 0; i < n; ++i) {+ start[i] = uint32_t(adj.size());+ for (uint32_t nb : mesh.neighbors(region[i])) {+ const int64_t j = local(nb);+ if (j < 0) {+ rim[i] = 1;+ continue;+ }+ adj.push_back(uint32_t(j));+ edgeSum += glm::distance(mesh.positions[region[i]], mesh.positions[nb]);+ ++edgeCount;+ }+ }+ start[n] = uint32_t(adj.size());+ const float meanEdge = edgeCount ? float(edgeSum / double(edgeCount)) : half * 0.01f;+ std::vector<glm::vec3> X(n);+ for (size_t i = 0; i < n; ++i) X[i] = mesh.positions[region[i]];+ // The region's triangles (each once: from its lowest-numbered vertex).+ std::vector<glm::uvec3> tris;+ for (size_t i = 0; i < n; ++i)+ for (uint32_t t : mesh.vertexTriangles(region[i])) {+ const glm::uvec3 tri = mesh.triangles[t];+ if (std::min({tri.x, tri.y, tri.z}) != region[i]) continue;+ if (mesh.hasHidden() && mesh.triangleHidden(t)) continue;+ const int64_t a = local(tri.x), b = local(tri.y), c = local(tri.z);+ if (a < 0 || b < 0 || c < 0) continue;+ tris.emplace_back(uint32_t(a), uint32_t(b), uint32_t(c));+ }+ if (tris.empty()) {+ error = "Too few points in the square";+ return false;+ }+ auto areaNormal = [&](const std::vector<glm::vec3>& P) {+ glm::vec3 nsum(0.0f);+ for (const glm::uvec3& t : tris) nsum += glm::cross(P[t.y] - P[t.x], P[t.z] - P[t.x]);+ if (glm::dot(nsum, -f.forward) < 0.0f) nsum = -nsum; // toward the viewer+ return glm::length(nsum) > 1e-20f ? glm::normalize(nsum) : -f.forward;+ };+ // 3. The base surface.+ std::vector<glm::vec3> base(n);+ int iterations = 0;+ const float smoothing = std::clamp(opt.smoothing, 0.0f, 1.0f);+ glm::vec3 np = areaNormal(X);+ if (smoothing <= 0.0f) {+ for (size_t i = 0; i < n; ++i) base[i] = X[i] - np * glm::dot(X[i] - f.center, np);+ } else {+ // Implicit fairing with the rim held: (1 + l deg_i) x_i - l sum_{j inner} x_j = X_i + l sum_{j rim} X_j,+ // solved for the inner vertices by Jacobi-preconditioned conjugate gradients (three right-hand sides).+ const float sigma = half * (0.2f + 1.6f * smoothing); // the size of form the base keeps+ const float lambda = (sigma / std::max(meanEdge, 1e-9f)) * (sigma / std::max(meanEdge, 1e-9f));+ std::vector<glm::vec3> b(n), x(X), r(n), z(n), p(n), Ap(n);+ std::vector<float> diag(n);+ for (size_t i = 0; i < n; ++i) {+ diag[i] = 1.0f + lambda * float(start[i + 1] - start[i]);+ glm::vec3 rhs = X[i];+ for (uint32_t k = start[i]; k < start[i + 1]; ++k)+ if (rim[adj[k]]) rhs += lambda * X[adj[k]];+ b[i] = rim[i] ? glm::vec3(0.0f) : rhs;+ }+ auto apply = [&](const std::vector<glm::vec3>& v, std::vector<glm::vec3>& o) {+ poolFor(n, [&](size_t lo, size_t hi) {+ for (size_t i = lo; i < hi; ++i) {+ if (rim[i]) {+ o[i] = glm::vec3(0.0f);+ continue;+ }+ glm::vec3 s(0.0f);+ for (uint32_t k = start[i]; k < start[i + 1]; ++k)+ if (!rim[adj[k]]) s += v[adj[k]];+ o[i] = diag[i] * v[i] - lambda * s;+ }+ });+ };+ auto dot3 = [&](const std::vector<glm::vec3>& a, const std::vector<glm::vec3>& c) {+ constexpr size_t kBlock = 4096;+ std::vector<glm::dvec3> parts((n + kBlock - 1) / kBlock, glm::dvec3(0.0));+ poolFor(n, [&](size_t lo, size_t hi) {+ glm::dvec3 acc(0.0);+ for (size_t i = lo; i < hi; ++i) acc += glm::dvec3(a[i] * c[i]);+ parts[lo / kBlock] = acc;+ }, kBlock);+ glm::dvec3 s(0.0);+ for (const glm::dvec3& q : parts) s += q;+ return s;+ };+ apply(x, Ap);+ for (size_t i = 0; i < n; ++i) {+ r[i] = rim[i] ? glm::vec3(0.0f) : b[i] - Ap[i];+ z[i] = r[i] / diag[i];+ p[i] = z[i];+ }+ glm::dvec3 rz = dot3(r, z);+ const glm::dvec3 bb = dot3(b, b);+ const double tol2 = 1e-8 * std::max({bb.x, bb.y, bb.z, 1e-30}); // 1e-4 relative residual+ const int maxIter = 800;+ for (iterations = 0; iterations < maxIter; ++iterations) {+ const glm::dvec3 rr = dot3(r, r);+ if (rr.x + rr.y + rr.z <= tol2) break;+ apply(p, Ap);+ const glm::dvec3 pAp = dot3(p, Ap);+ const glm::vec3 alpha(pAp.x > 0 ? rz.x / pAp.x : 0.0, pAp.y > 0 ? rz.y / pAp.y : 0.0, pAp.z > 0 ? rz.z / pAp.z : 0.0);+ poolFor(n, [&](size_t lo, size_t hi) {+ for (size_t i = lo; i < hi; ++i) {+ x[i] += alpha * p[i];+ r[i] -= alpha * Ap[i];+ z[i] = r[i] / diag[i];+ }+ });+ const glm::dvec3 rzNew = dot3(r, z);+ const glm::vec3 beta(rz.x > 0 ? rzNew.x / rz.x : 0.0, rz.y > 0 ? rzNew.y / rz.y : 0.0, rz.z > 0 ? rzNew.z / rz.z : 0.0);+ rz = rzNew;+ poolFor(n, [&](size_t lo, size_t hi) {+ for (size_t i = lo; i < hi; ++i) p[i] = z[i] + beta * p[i];+ });+ }+ for (size_t i = 0; i < n; ++i) base[i] = rim[i] ? X[i] : x[i];+ np = areaNormal(base);+ }+ // 4. The base's normals and the stamp's frame (the screen's right and up laid on the base plane).+ std::vector<glm::vec3> bn(n, glm::vec3(0.0f));+ for (const glm::uvec3& t : tris) {+ const glm::vec3 c = glm::cross(base[t.y] - base[t.x], base[t.z] - base[t.x]);+ bn[t.x] += c, bn[t.y] += c, bn[t.z] += c;+ }+ glm::vec3 right = f.right - np * glm::dot(f.right, np);+ right = glm::length(right) > 1e-6f ? glm::normalize(right) : f.right;+ const glm::vec3 up = glm::cross(np, right);+ std::vector<glm::vec3> offset(n), uvz(n);+ float maxOffset = 0.0f;+ for (size_t i = 0; i < n; ++i) {+ glm::vec3 ni = bn[i];+ if (glm::dot(ni, np) < 0.0f) ni = -ni;+ ni = glm::length(ni) > 1e-20f ? glm::normalize(ni) : np;+ if (smoothing <= 0.0f) ni = np;+ glm::vec3 t = right - ni * glm::dot(right, ni);+ t = glm::length(t) > 1e-6f ? glm::normalize(t) : right;+ const glm::vec3 bt = glm::cross(ni, t);+ const glm::vec3 d = X[i] - base[i];+ offset[i] = glm::vec3(glm::dot(d, t), glm::dot(d, bt), glm::dot(d, ni)) * inv;+ const glm::vec3 o = base[i] - f.center;+ uvz[i] = glm::vec3(glm::dot(o, right) * inv, glm::dot(o, up) * inv, -glm::dot(o, np));+ }+ // 5. Rasterize the offsets through the base's position on the plane (the front-most base wins a texel).+ std::vector<RasterTri> raster;+ raster.reserve(tris.size());+ for (const glm::uvec3& t : tris) {+ RasterTri r;+ for (int k = 0; k < 3; ++k) {+ const uint32_t i = t[k];+ r.q[k] = texel(uvz[i].x, uvz[i].y, res);+ r.z[k] = uvz[i].z;+ r.a[k] = offset[i];+ }+ raster.push_back(r);+ }+ std::vector<float> depth;+ std::vector<glm::vec3> vectors;+ rasterize(res, raster, depth, &vectors);+ const float fade = std::clamp(opt.edgeFade, 0.0f, 0.9f);+ int covered = 0;+ for (int y = 0; y < res; ++y)+ for (int x = 0; x < res; ++x) {+ const size_t i = size_t(y) * size_t(res) + size_t(x);+ if (depth[i] == kInf) continue;+ ++covered;+ const float u = (float(x) + 0.5f) / float(res) * 2.0f - 1.0f, v = 1.0f - (float(y) + 0.5f) / float(res) * 2.0f;+ vectors[i] *= borderFade(u, v, f.circle, fade);+ maxOffset = std::max(maxOffset, glm::length(vectors[i]));+ }+ out = VectorDisplacement{};+ out.name = "Captured VDM";+ out.width = out.height = res;+ out.vectors = std::move(vectors);+ if (info) {+ info->vertices = n;+ info->maxOffset = maxOffset;+ info->coverage = covered;+ info->iterations = iterations;+ }+ return true;+}++Image alphaToImage(const BrushAlpha& alpha) {+ Image img;+ img.width = alpha.width;+ img.height = alpha.height;+ img.rgba.resize(size_t(img.width) * size_t(img.height) * 4);+ for (size_t i = 0; i < alpha.values.size(); ++i) {+ const uint8_t g = uint8_t(std::lround(std::clamp(alpha.values[i], 0.0f, 1.0f) * 255.0f));+ img.rgba[i * 4 + 0] = img.rgba[i * 4 + 1] = img.rgba[i * 4 + 2] = g;+ img.rgba[i * 4 + 3] = 255;+ }+ return img;+}++// ---------------------------------------------------------------------------+// Commands+// ---------------------------------------------------------------------------++namespace {++std::string utf8(const std::filesystem::path& p) {+ const std::u8string s = p.u8string();+ return std::string(s.begin(), s.end());+}+std::filesystem::path fsPath(const std::string& s) { return std::filesystem::path(std::u8string(s.begin(), s.end())); }++// The frame from a script's point / view / up / size, or an error.+bool frameFromArgs(Document& doc, const Args& a, CaptureFrame& f, std::string& error) {+ glm::vec3 point, view(0.0f, 0.0f, -1.0f), up(0.0f, 1.0f, 0.0f);+ if (!parseVec3(argString(a, "point"), point)) return error = "Bad point (expected x,y,z)", false;+ if (a.count("view") && !parseVec3(argString(a, "view"), view)) return error = "Bad view (expected x,y,z)", false;+ if (a.count("up") && !parseVec3(argString(a, "up"), up)) return error = "Bad up (expected x,y,z)", false;+ if (glm::length(view) < 1e-6f) return error = "The view direction must not be zero", false;+ view = glm::normalize(view);+ if (doc.mesh.triangleCount() == 0) return error = "The active SubTool is empty", false;+ doc.syncBvh();+ const AABB box = doc.mesh.bounds();+ const float diag = std::max(glm::length(box.extent()), 1e-4f);+ RayHit hit;+ const glm::vec3 origin = point - view * (glm::dot(point - box.center(), view) + diag);+ if (!doc.bvh.raycast(doc.mesh, origin, view, hit)) return error = "The ray misses the surface", false;+ float size = float(argNumber(a, "size", 0.0));+ if (!(size > 0.0f)) size = diag * 0.05f;+ f = makeCaptureFrame(hit.position, view, up, size, argBool(a, "circle", false));+ return true;+}++CaptureOptions optionsFromArgs(const Args& a) {+ CaptureOptions o;+ o.resolution = std::clamp(int(argNumber(a, "resolution", 256)), 32, 1024);+ o.smoothing = float(std::clamp(argNumber(a, "smoothing", 0.5), 0.0, 1.0));+ o.edgeFade = float(std::clamp(argNumber(a, "edge_fade", 0.12), 0.0, 0.9));+ o.fitPlane = argBool(a, "fit_plane", true);+ o.invert = argBool(a, "invert", false);+ return o;+}++} // namespace++void registerCaptureCommands(CommandRegistry& registry) {+ using T = ParamSpec::Type;+ const std::vector<ParamSpec> common = {+ {"point", T::String, "x,y,z the view ray goes through; where it meets the surface is the capture's centre.", true},+ {"view", T::String, "x,y,z view direction into the scene (default 0,0,-1).", false},+ {"up", T::String, "x,y,z screen up (default 0,1,0).", false},+ {"size", T::Number, "Half the square's side in world units (default 5% of the model's size).", false},+ {"circle", T::Bool, "Capture the circle inside the square only.", false},+ {"resolution", T::Number, "Pixels a side (32-1024, default 256).", false},+ {"smoothing", T::Number, "0-1: how much of the smooth form the base takes away (0 = flat plane; default 0.5).", false},+ {"edge_fade", T::Number, "0-0.9: border fade, as a fraction of the half size (default 0.12).", false},+ };+ std::vector<ParamSpec> alphaParams = common;+ alphaParams.push_back({"fit_plane", T::Bool, "Height over a plane fitted to the surface (default true) instead of the view plane.", false});+ alphaParams.push_back({"invert", T::Bool, "White = deepest.", false});+ alphaParams.push_back({"path", T::String, "Also save it as a PNG here (e.g. your library's Alphas folder).", false});+ alphaParams.push_back({"name", T::String, "Name of the alpha (default Captured).", false});+ registry.add({"capture_alpha",+ "Capture the surface in a square seen along `view` as a grayscale height alpha and make it the brush "+ "alpha (Alpha from viewport): its height toward the viewer, normalized to 0..1.",+ alphaParams,+ [](Document& doc, const Args& a) -> CommandResult {+ CaptureFrame f;+ std::string err;+ if (!frameFromArgs(doc, a, f, err)) return {false, err};+ const auto t0 = std::chrono::steady_clock::now();+ BrushAlpha alpha;+ CaptureInfo info;+ if (!captureHeightAlpha(doc.mesh, doc.bvh, f, optionsFromArgs(a), alpha, err, &info)) return {false, err};+ alpha.name = argString(a, "name", "Captured");+ if (alpha.name.empty()) alpha.name = "Captured";+ std::string note;+ if (const std::string path = argString(a, "path"); !path.empty()) {+ std::error_code ec;+ std::filesystem::create_directories(fsPath(path).parent_path(), ec);+ if (!alphaToImage(alpha).savePng(path, err)) return {false, err};+ note = ", saved " + path;+ }+ doc.brushAlpha = std::move(alpha);+ char buf[96];+ std::snprintf(buf, sizeof buf, " (%d px, height range %.4g, %.0f ms)", doc.brushAlpha.width, info.depthRange,+ std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count());+ return {true, "Captured alpha '" + doc.brushAlpha.name + "'" + buf + note};+ }});+ std::vector<ParamSpec> vdmParams = common;+ vdmParams.push_back({"name", T::String, "Name of the new VDM (default 'Captured VDM').", false});+ vdmParams.push_back({"save", T::Bool, "Keep it in the brush library (default true).", false});+ vdmParams.push_back({"exr", T::String, "Also write it as a 32-bit OpenEXR here.", false});+ registry.add({"capture_vdm",+ "Capture the surface in a square seen along `view` as a vector displacement brush (VDM from "+ "viewport): every point's 3D offset from a smoothed base surface, overhangs included. It becomes the "+ "VDM brush's (and Detail Clone's) map.",+ vdmParams,+ [](Document& doc, const Args& a) -> CommandResult {+ CaptureFrame f;+ std::string err;+ if (!frameFromArgs(doc, a, f, err)) return {false, err};+ const auto t0 = std::chrono::steady_clock::now();+ VectorDisplacement v;+ CaptureInfo info;+ if (!captureVdmFromView(doc.mesh, doc.bvh, f, optionsFromArgs(a), v, err, &info)) return {false, err};+ v.name = argString(a, "name", "Captured VDM");+ if (v.name.empty()) v.name = "Captured VDM";+ if (builtinVdm(v.name)) v.name += " (mine)";+ std::string note;+ if (argBool(a, "save", true)) {+ const std::string dir = brushLibraryPaths().userDir;+ if (dir.empty()) {+ note = " (not saved: no brush library)";+ } else {+ std::error_code ec;+ std::filesystem::create_directories(fsPath(dir), ec);+ const std::string file = utf8(fsPath(dir) / fsPath(vdmFileName(v.name)));+ if (writeVdmFile(file, v, err)) v.path = file;+ else note = " (not saved: " + err + ")";+ }+ }+ if (const std::string exr = argString(a, "exr"); !exr.empty()) {+ if (!writeVdmExr(exr, v, err)) return {false, err};+ note += ", EXR " + exr;+ }+ char buf[160];+ std::snprintf(buf, sizeof buf, " (%d px, %zu points, reach %.2f radii, %d smoothing iterations, %.0f ms)",+ v.width, info.vertices, info.maxOffset, info.iterations,+ std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count());+ const std::string msg = "Captured VDM '" + v.name + "'" + buf + note;+ addVdm(doc, std::move(v));+ return {true, msg};+ }});+}++} // namespace sfdiff --git a/src/core/ViewCapture.h b/src/core/ViewCapture.hnew file mode 100644index 00000000..999a0b6e--- /dev/null+++ b/src/core/ViewCapture.h@@ -0,0 +1,73 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Alpha and VDM from the viewport: drag a square (or circle) over any sculpted detail and capture it as+// (a) a grayscale height alpha: the surface's height toward the viewer over the view-aligned (or fitted) plane,+// normalized to 0..1, optionally only the fine detail (the smooth form subtracted);+// (b) a vector displacement map (core/Vdm.h): the true 3D offset of every point from a smooth base surface,+// in the base's own tangent frame, so overhangs and sideways leans come along. The base is the region+// smoothed by implicit fairing (Desbrun et al. 1999: (I + lambda L) x = x0, its rim held), or the fitted+// plane when Base Smoothing is 0.+// Either becomes a brush at once: the alpha shapes any brush, the VDM is stamped by the VDM brush or along a+// stroke by Detail Clone.+#pragma once++#include "core/BrushAlpha.h"+#include "core/Vdm.h"++#include <glm/glm.hpp>++#include <string>++namespace sf {++class BVH;+class CommandRegistry;+class Mesh;+struct Document;++// The captured square: centred on `center` (a point on the surface), seen along `forward`, with the screen's+// `right` and `up`; `halfSize` world units from the centre to an edge. Captures project along `forward`+// (orthographically), so the frame is the same in a perspective or orthographic view.+struct CaptureFrame {+ glm::vec3 center{0.0f};+ glm::vec3 forward{0.0f, 0.0f, -1.0f};+ glm::vec3 right{1.0f, 0.0f, 0.0f};+ glm::vec3 up{0.0f, 1.0f, 0.0f};+ float halfSize = 0.1f;+ bool circle = false; // capture the inscribed circle only (the rest fades to nothing)+};++struct CaptureOptions {+ int resolution = 256; // pixels a side (32..1024)+ float edgeFade = 0.12f; // fraction of the half size over which the capture fades to 0 at its border+ float smoothing = 0.5f; // 0..1: how much smooth form the base takes away (0: plain plane; VDM and alpha)+ bool fitPlane = true; // height alpha: relative to a plane fitted to the surface (removes tilt)+ bool invert = false; // height alpha: white = deepest+};++// What a capture found (for the status line and tests).+struct CaptureInfo {+ size_t vertices = 0; // region vertices (VDM)+ float depthRange = 0.0f; // world height range the alpha's 0..1 spans+ float maxOffset = 0.0f; // largest VDM vector, in brush radii+ int coverage = 0; // texels the surface covered+ int iterations = 0; // smoothing solver iterations+};++// A frame for the square around the surface point `center` seen along `forward` with the camera's `up`.+CaptureFrame makeCaptureFrame(const glm::vec3& center, const glm::vec3& forward, const glm::vec3& up, float halfSize,+ bool circle = false);++bool captureHeightAlpha(const Mesh& mesh, const BVH& bvh, const CaptureFrame& frame, const CaptureOptions& opt,+ BrushAlpha& out, std::string& error, CaptureInfo* info = nullptr);+bool captureVdmFromView(const Mesh& mesh, const BVH& bvh, const CaptureFrame& frame, const CaptureOptions& opt,+ VectorDisplacement& out, std::string& error, CaptureInfo* info = nullptr);++// The alpha as an 8-bit grayscale PNG (what the Alphas folder keeps).+Image alphaToImage(const BrushAlpha& alpha);++// capture_alpha, capture_vdm: the same from a script (point + view + size).+void registerCaptureCommands(CommandRegistry& registry);++} // namespace sfdiff --git a/tests/test_kelvinlet.cpp b/tests/test_kelvinlet.cppnew file mode 100644index 00000000..955f41dc--- /dev/null+++ b/tests/test_kelvinlet.cpp@@ -0,0 +1,454 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Kelvinlet brushes (core/Kelvinlet.h): the kernels (normalization, multi-scale far-field cancellation,+// incompressibility, exact twist, pinch without folding), the brushes on meshes (symmetry, mask, undo, sculpt+// layers, adaptive cutoff, bulge with Squash), Detail Clone, and Alpha / VDM from the viewport+// (core/ViewCapture.h) with its commands. Timing checks run with SF_BENCH_LIMITS=1.+#include "TestHarness.h"++#include "core/Commands.h"+#include "core/Kelvinlet.h"+#include "core/PathStroke.h"+#include "core/Primitives.h"+#include "core/Sculpt.h"+#include "core/ThreadPool.h"+#include "core/Vdm.h"+#include "core/ViewCapture.h"++#include <algorithm>+#include <chrono>+#include <cmath>+#include <cstdlib>+#include <filesystem>++using namespace sf;++namespace {++bool run(Document& d, const std::string& name, const Args& args = {}) {+ static CommandRegistry registry;+ const CommandResult r = registry.execute(d, name, args);+ if (!r.ok) std::printf(" %s: %s\n", name.c_str(), r.message.c_str());+ return r.ok;+}++uint32_t nearest(const Mesh& m, const glm::vec3& p) {+ uint32_t best = 0;+ for (uint32_t v = 1; v < m.vertexCount(); ++v)+ if (glm::distance(m.positions[v], p) < glm::distance(m.positions[best], p)) best = v;+ return best;+}++KelvinletSettings squash(float s, float sharp = 0.0f) {+ KelvinletSettings k;+ k.squash = s;+ k.sharpness = sharp;+ return k;+}++// Numerical divergence of the grab field at r.+float divergence(const KelvinletKernel& k, const glm::vec3& r, const glm::vec3& f) {+ const float h = 1e-3f;+ float div = 0.0f;+ for (int a = 0; a < 3; ++a) {+ glm::vec3 e(0.0f);+ e[a] = h;+ div += (kelvinletGrab(k, r + e, f)[a] - kelvinletGrab(k, r - e, f)[a]) / (2.0f * h);+ }+ return div;+}++PathStroke pathAlongX(float x0, float x1, float radius, float y = 0.0f) {+ PathStroke st;+ st.points = {glm::vec3(x0, y, 2.0f), glm::vec3(x1, y, 2.0f)};+ st.view = glm::vec3(0.0f, 0.0f, -1.0f);+ st.radius = radius;+ st.strength = 0.5f;+ st.curve = false;+ return st;+}++} // namespace++TEST(kelvinlet_kernels_are_normalized_and_localized) {+ for (float sq : {0.0f, 0.5f, 1.0f})+ for (float sharp : {0.0f, 1.0f}) {+ const KelvinletSettings s = squash(sq, sharp);+ for (bool tight : {false, true}) {+ const KelvinletKernel k = makeKelvinletKernel(KelvinletKind::Grab, 0.2f, s, tight);+ // The grabbed point moves exactly with the cursor.+ const glm::vec3 d(0.03f, -0.01f, 0.02f);+ CHECK(glm::length(kelvinletGrab(k, glm::vec3(0.0f), d) - d) < 1e-5f);+ // The far-field terms cancel: sum w = 0 (1/r) and, for three scales, sum w e^2 = 0 (1/r^3).+ float sw = 0.0f, swe = 0.0f;+ for (int i = 0; i < k.scales; ++i) sw += k.w[i], swe += k.w[i] * k.eps[i] * k.eps[i];+ CHECK(std::abs(sw) < 1e-5f);+ if (k.scales == 3) CHECK(std::abs(swe) < 1e-5f * k.eps[2] * k.eps[2]);+ // About half way at half the radius (the Move brush's footprint), almost nothing at 3 radii.+ const float half = glm::length(kelvinletGrab(k, glm::vec3(0.1f, 0.0f, 0.0f), glm::vec3(0, 0, 1)));+ if (sharp == 0.0f && !tight) CHECK(half > 0.15f && half < 0.8f);+ CHECK(k.envelope(0.6f) < 0.03f);+ // The cutoff grows with the step and stays inside the search range.+ const float small = k.cutoff(0.001f, 0.0006f, 0.8f), big = k.cutoff(0.05f, 0.0006f, 0.8f);+ CHECK(small > 0.0f && small < big && big <= 0.8f);+ }+ for (KelvinletKind kind : {KelvinletKind::Twist, KelvinletKind::Scale}) {+ const KelvinletKernel k = makeKelvinletKernel(kind, 0.2f, s);+ CHECK(std::abs(k.profile(0.0f) - 1.0f) < 1e-5f);+ CHECK(k.profile(0.6f * 0.6f) < 0.01f);+ }+ }+ // Sharpness gives a tighter peak with the same far field.+ const KelvinletKernel soft = makeKelvinletKernel(KelvinletKind::Grab, 0.2f, squash(0.5f, 0.0f));+ const KelvinletKernel sharp = makeKelvinletKernel(KelvinletKind::Grab, 0.2f, squash(0.5f, 1.0f));+ CHECK(sharp.envelope(0.08f) < soft.envelope(0.08f));+}++TEST(kelvinlet_squash_is_poissons_ratio) {+ // Incompressible clay (Squash 1, nu = 0.49) is nearly divergence free; rubber (Squash 0) is not.+ const KelvinletKernel clay = makeKelvinletKernel(KelvinletKind::Grab, 0.2f, squash(1.0f));+ const KelvinletKernel rubber = makeKelvinletKernel(KelvinletKind::Grab, 0.2f, squash(0.0f));+ const glm::vec3 f(0.0f, 0.0f, 0.05f);+ float dc = 0.0f, dr = 0.0f;+ for (const glm::vec3 r : {glm::vec3(0.05f, 0.0f, 0.05f), glm::vec3(0.1f, 0.05f, -0.08f), glm::vec3(0.0f, 0.12f, 0.1f)}) {+ dc += std::abs(divergence(clay, r, f));+ dr += std::abs(divergence(rubber, r, f));+ }+ CHECK(dc < 0.1f * dr);+ // Pressing a flat sheet in: incompressible clay bulges up around the dent, more than rubber does.+ auto bulge = [](float sq) {+ Document d = makeDoc(makePlane(160, 2.0f));+ d.sculptor.kelvinlet.squash = sq;+ CHECK(d.sculptor.beginStroke(d.mesh, "KelvinGrab"));+ DabParams p;+ p.center = glm::vec3(0.0f);+ p.viewDir = glm::vec3(0.0f, -1.0f, 0.0f);+ p.radius = 0.25f;+ p.strength = 0.5f;+ p.strokeDelta = glm::vec3(0.0f, -0.15f, 0.0f);+ d.sculptor.dab(d.mesh, d.bvh, BrushType::KelvinGrab, p, Symmetry{false, false, false});+ d.undo.push(d.sculptor.endStroke());+ float up = 0.0f;+ for (const glm::vec3& q : d.mesh.positions) up = std::max(up, q.y);+ const float centre = d.mesh.positions[nearest(d.mesh, glm::vec3(0.0f, -0.15f, 0.0f))].y;+ CHECK(centre < -0.12f); // the thumb pushed the centre down with it+ return up;+ };+ const float clayUp = bulge(1.0f), rubberUp = bulge(0.0f);+ CHECK(clayUp > 0.0f);+ CHECK(clayUp > rubberUp * 1.3f);+}++TEST(kelvinlet_twist_is_a_rotation_and_scale_never_folds) {+ const KelvinletKernel tw = makeKelvinletKernel(KelvinletKind::Twist, 0.2f, KelvinletSettings{});+ const glm::vec3 axis(0.0f, 0.0f, 1.0f);+ for (const glm::vec3 r : {glm::vec3(0.05f, 0.0f, 0.0f), glm::vec3(0.1f, 0.1f, 0.03f), glm::vec3(0.3f, -0.2f, 0.1f)}) {+ const glm::vec3 moved = r + kelvinletTwist(tw, r, axis, 2.5f);+ CHECK(std::abs(glm::length(moved) - glm::length(r)) < 1e-5f); // stays on its shell+ CHECK(std::abs(moved.z - r.z) < 1e-6f); // and its height along the axis+ }+ // The centre turns by the full angle.+ const glm::vec3 nearCentre(1e-4f, 0.0f, 0.0f);+ const glm::vec3 m = nearCentre + kelvinletTwist(tw, nearCentre, axis, 0.5f);+ CHECK(std::abs(std::atan2(m.y, m.x) - 0.5f) < 1e-3f);+ // A hard pinch keeps the order of points along a ray (no folding through the centre).+ const KelvinletKernel sc = makeKelvinletKernel(KelvinletKind::Scale, 0.2f, KelvinletSettings{});+ float last = 0.0f;+ for (int i = 1; i <= 100; ++i) {+ const glm::vec3 r(0.006f * float(i), 0.0f, 0.0f);+ const float len = glm::length(r + kelvinletScale(sc, r, -4.0f));+ CHECK(len > last);+ last = len;+ }+ const glm::vec3 r(0.01f, 0.0f, 0.0f);+ CHECK(glm::length(r + kelvinletScale(sc, r, std::log(2.0f))) > 0.019f); // doubles at the centre+}++TEST(kelvinlet_grab_on_a_sphere_symmetry_mask_undo) {+ Document d = makeDoc(makeIcosphere(5, 1.0f));+ const auto start = d.mesh.positions;+ // Mask the -Y half.+ auto& mask = d.mesh.ensureMask(0.0f);+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v)+ if (d.mesh.positions[v].y < -0.05f) mask[v] = 1.0f;+ PathStroke st = pathAlongX(0.4f, 0.75f, 0.25f, 0.3f);+ st.symmetry = Symmetry{true, false, false};+ std::string err;+ CHECK(strokePath(d, nullptr, BrushType::KelvinGrab, st, err) > 0);+ size_t moved = 0;+ float worstMirror = 0.0f, maskedMove = 0.0f, rimMove = 0.0f, maxMove = 0.0f;+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) {+ const glm::vec3 dv = d.mesh.positions[v] - start[v];+ maxMove = std::max(maxMove, glm::length(dv));+ if (glm::length(dv) > 1e-6f) ++moved;+ if (mask[v] == 1.0f) maskedMove = std::max(maskedMove, glm::length(dv));+ // At the edge of what moved (a moved vertex next to one that didn't), it moved next to nothing.+ if (mask[v] == 0.0f && glm::length(dv) > 0.0f)+ for (uint32_t n : d.mesh.neighbors(v))+ if (mask[n] == 0.0f && d.mesh.positions[n] == start[n]) rimMove = std::max(rimMove, glm::length(dv));+ }+ CHECK(moved > 200);+ CHECK(moved < d.mesh.vertexCount()); // the cutoff left the far side alone+ CHECK(maskedMove == 0.0f);+ CHECK(maxMove > 0.1f);+ // No hard falloff edge: the field fades to nothing before the cutoff.+ CHECK(rimMove < 0.01f * maxMove);+ // Symmetry: compare each vertex of the +X half with its start-mirror.+ {+ Mesh ref = makeIcosphere(5, 1.0f);+ BVH bvh;+ bvh.build(ref);+ int checked = 0;+ for (uint32_t v = 0; v < ref.vertexCount() && checked < 400; v += 7) {+ const glm::vec3 p = ref.positions[v];+ if (p.x < 0.2f) continue;+ std::vector<uint32_t> near;+ bvh.queryVertices(ref, glm::vec3(-p.x, p.y, p.z), 1e-4f, near);+ if (near.size() != 1) continue;+ const glm::vec3 a = d.mesh.positions[v] - p, b = d.mesh.positions[near[0]] - ref.positions[near[0]];+ worstMirror = std::max(worstMirror, glm::length(a - glm::vec3(-b.x, b.y, b.z)));+ ++checked;+ }+ CHECK(checked > 50);+ CHECK(worstMirror < 1e-4f);+ }+ CHECK(d.undo.canUndo());+ d.undo.undo(d.mesh, d.bvh);+ float back = 0.0f;+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) back = std::max(back, glm::distance(d.mesh.positions[v], start[v]));+ CHECK(back < 1e-6f);+}++TEST(kelvinlet_brushes_write_into_sculpt_layers) {+ Document d = makeDoc(makeIcosphere(4, 1.0f));+ CHECK(run(d, "layer_add", {{"name", std::string("Elastic")}}));+ const auto start = d.mesh.positions;+ for (BrushType type : {BrushType::KelvinGrab, BrushType::KelvinTwist, BrushType::KelvinScale, BrushType::KelvinSnake}) {+ std::string err;+ CHECK(strokePath(d, nullptr, type, pathAlongX(0.0f, 0.3f, 0.3f), err) > 0);+ }+ float layerSum = 0.0f;+ for (const glm::vec3& o : d.mesh.layers.back().delta) layerSum += glm::length(o);+ CHECK(layerSum > 0.1f);+ // Turning the layer off puts the base back.+ CHECK(run(d, "layer_set_weight", {{"index", 0.0}, {"weight", 0.0}}));+ float worst = 0.0f;+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) worst = std::max(worst, glm::distance(d.mesh.positions[v], start[v]));+ CHECK(worst < 1e-4f);+}++TEST(kelvinlet_twist_and_snake_strokes) {+ // Twist turns the surface around the view axis (clockwise for a drag to the right).+ Document d = makeDoc(makePlane(120, 2.0f));+ const auto start = d.mesh.positions;+ PathStroke st;+ st.points = {glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.2f, 1.0f, 0.0f)};+ st.view = glm::vec3(0.0f, -1.0f, 0.0f);+ st.radius = 0.4f;+ st.strength = 0.5f;+ st.curve = false;+ std::string err;+ CHECK(strokePath(d, nullptr, BrushType::KelvinTwist, st, err) > 0);+ const uint32_t v = nearest(d.mesh, glm::vec3(0.1f, 0.0f, 0.0f));+ const glm::vec3 a = start[v], b = d.mesh.positions[v];+ CHECK(std::abs(glm::length(b) - glm::length(a)) < 1e-3f); // a rotation in the sheet+ CHECK(std::abs(b.y) < 1e-6f);+ CHECK(glm::length(b - a) > 0.02f);+ // Snake pulls a tapering horn straight out of a sphere.+ Document s = makeDoc(makeIcosphere(6, 1.0f));+ PathStroke pull;+ pull.points = {glm::vec3(0.0f, 0.0f, 2.0f), glm::vec3(0.0f, 0.0f, 2.0f)};+ // (headless Snake follows the path in the view plane: pull out to the right of a side view)+ pull.points = {glm::vec3(0.0f, 0.9f, 2.0f), glm::vec3(0.0f, 1.6f, 2.0f)};+ pull.view = glm::vec3(0.0f, 0.0f, -1.0f);+ pull.radius = 0.2f;+ pull.strength = 0.5f;+ pull.curve = false;+ CHECK(strokePath(s, nullptr, BrushType::KelvinSnake, pull, err) > 0);+ float top = 0.0f;+ for (const glm::vec3& p : s.mesh.positions) top = std::max(top, p.y);+ std::printf(" snake: tip at %.3f\n", top);+ CHECK(top > 1.3f); // pulled well out of the unit sphere+}++// A round dome (Z only), so each stamp is one peak.+std::shared_ptr<const VectorDisplacement> domeVdm() {+ VectorDisplacement v;+ v.name = "Dome";+ v.width = v.height = 64;+ v.vectors.resize(64 * 64);+ for (int y = 0; y < 64; ++y)+ for (int x = 0; x < 64; ++x) {+ const float u = (float(x) + 0.5f) / 32.0f - 1.0f, w = (float(y) + 0.5f) / 32.0f - 1.0f;+ const float d2 = u * u + w * w;+ v.vectors[size_t(y) * 64 + size_t(x)] = glm::vec3(0.0f, 0.0f, d2 < 0.5f ? 0.3f * (1.0f - d2 / 0.5f) : 0.0f);+ }+ return std::make_shared<const VectorDisplacement>(std::move(v));+}++TEST(detail_clone_stamps_along_the_stroke) {+ Document d = makeDoc(makePlane(200, 2.0f));+ d.brushVdm = domeVdm();+ d.sculptor.kelvinlet.cloneSpacing = 1.0f;+ PathStroke st;+ st.points = {glm::vec3(-0.6f, 1.0f, 0.0f), glm::vec3(0.6f, 1.0f, 0.0f)};+ st.view = glm::vec3(0.0f, -1.0f, 0.0f);+ st.radius = 0.1f;+ st.strength = 0.5f;+ st.curve = false;+ std::string err;+ CHECK(strokePath(d, nullptr, BrushType::DetailClone, st, err) > 0);+ // Count the separate stamps: height peaks along x.+ constexpr int kBins = 120;+ float height[kBins] = {};+ for (const glm::vec3& p : d.mesh.positions) {+ const int b = std::clamp(int((p.x + 1.0f) / 2.0f * kBins), 0, kBins - 1);+ height[b] = std::max(height[b], p.y);+ }+ float top = 0.0f;+ for (float h : height) top = std::max(top, h);+ int peaks = 0;+ for (int i = 1; i + 1 < kBins; ++i)+ if (height[i] > 0.4f * top && height[i] >= height[i - 1] && height[i] > height[i + 1]) ++peaks;+ std::printf(" detail clone: %d stamps, top %.3f\n", peaks, top);+ CHECK(top > 0.02f);+ CHECK(peaks >= 5 && peaks <= 8); // 1.2 long, a stamp every 0.2+ // A click stamps once.+ Document c = makeDoc(makePlane(120, 2.0f));+ c.brushVdm = builtinVdm("horn");+ PathStroke click = st;+ click.points = {glm::vec3(0.0f, 1.0f, 0.0f)};+ click.radius = 0.3f;+ CHECK(strokePath(c, nullptr, BrushType::DetailClone, click, err) == 1);+ float h = 0.0f;+ for (const glm::vec3& p : c.mesh.positions) h = std::max(h, p.y);+ CHECK(h > 0.05f);+}++TEST(capture_height_alpha_from_view) {+ Document d = makeDoc(makePlane(160, 2.0f));+ // A bump in the middle.+ PathStroke st;+ st.points = {glm::vec3(0.0f, 1.0f, 0.0f)};+ st.view = glm::vec3(0.0f, -1.0f, 0.0f);+ st.radius = 0.3f;+ st.strength = 1.0f;+ std::string err;+ for (int i = 0; i < 4; ++i) CHECK(strokePath(d, nullptr, BrushType::Standard, st, err) == 1);+ d.syncBvh();+ const CaptureFrame f = makeCaptureFrame(glm::vec3(0.0f), glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f), 0.5f);+ CaptureOptions opt;+ opt.resolution = 128;+ opt.smoothing = 0.0f;+ BrushAlpha a;+ CaptureInfo info;+ CHECK(captureHeightAlpha(d.mesh, d.bvh, f, opt, a, err, &info));+ CHECK(a.width == 128 && a.height == 128);+ CHECK(a.sample(0.0f, 0.0f) > 0.9f);+ CHECK(a.sample(0.95f, 0.95f) < 0.05f);+ CHECK(info.depthRange > 0.01f);+ opt.invert = true;+ CHECK(captureHeightAlpha(d.mesh, d.bvh, f, opt, a, err));+ CHECK(a.sample(0.0f, 0.0f) < 0.1f);+ // Nothing under the square: an error.+ const CaptureFrame off = makeCaptureFrame(glm::vec3(5.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f), 0.2f);+ CHECK(!captureHeightAlpha(d.mesh, d.bvh, off, opt, a, err) && !err.empty());+ // The command makes it the brush alpha and saves the PNG.+ const std::string png = tempPath("sf_capture_alpha.png");+ std::filesystem::remove(png);+ CHECK(run(d, "capture_alpha", {{"point", std::string("0,1,0")}, {"view", std::string("0,-1,0")}, {"size", 0.5},+ {"path", png}, {"name", std::string("Bump")}}));+ CHECK(d.brushAlpha.name == "Bump" && !d.brushAlpha.empty());+ CHECK(std::filesystem::exists(png));+ Image img;+ CHECK(Image::load(png, img, err) && img.width == 256);+}++TEST(capture_vdm_from_view_round_trips_a_stamp) {+ // Stamp an asymmetric, leaning VDM on a grid, capture it from the top, stamp the capture on a fresh grid:+ // the same shape comes back, sideways lean included (fairing a grid with its rim held finds its start).+ auto source = builtinVdm("ear curl");+ Document a = makeDoc(makePlane(200, 2.0f));+ a.brushVdm = source;+ const Args stamp = {{"point", std::string("0,1,0")}, {"view", std::string("0,-1,0")}, {"radius", 0.5}};+ CHECK(run(a, "vdm_stamp", stamp));+ a.syncBvh();+ const CaptureFrame f = makeCaptureFrame(glm::vec3(0.0f), glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f), 0.5f);+ CaptureOptions opt;+ opt.resolution = 256;+ opt.smoothing = 1.0f;+ opt.edgeFade = 0.03f;+ VectorDisplacement captured;+ CaptureInfo info;+ std::string err;+ CHECK(captureVdmFromView(a.mesh, a.bvh, f, opt, captured, err, &info));+ CHECK(info.vertices > 1000);+ CHECK(info.maxOffset > 0.1f);+ Document b = makeDoc(makePlane(200, 2.0f));+ b.brushVdm = std::make_shared<const VectorDisplacement>(captured);+ CHECK(run(b, "vdm_stamp", stamp));+ double err2 = 0.0, ref2 = 0.0, lateral = 0.0;+ const Mesh flat = makePlane(200, 2.0f);+ for (uint32_t v = 0; v < flat.vertexCount(); ++v) {+ const glm::vec3 da = a.mesh.positions[v] - flat.positions[v], db = b.mesh.positions[v] - flat.positions[v];+ err2 += double(glm::dot(da - db, da - db));+ ref2 += double(glm::dot(da, da));+ lateral += double(da.x * da.x + da.z * da.z);+ }+ CHECK(lateral > 0.05 * ref2); // the source really leans sideways+ const double rel = std::sqrt(err2 / std::max(ref2, 1e-12));+ std::printf(" capture_vdm round trip: relative RMS error %.3f, %zu points, %d CG iterations\n", rel, info.vertices,+ info.iterations);+ CHECK(rel < 0.2);+ // The command adds it to the VDMs and makes it the brush's.+ const size_t before = a.vdms.size();+ CHECK(run(a, "capture_vdm", {{"point", std::string("0,1,0")}, {"view", std::string("0,-1,0")}, {"size", 0.5},+ {"name", std::string("Ear Copy")}, {"save", false}, {"resolution", 64.0}}));+ CHECK(a.vdms.size() == before + 1 && a.brushVdm && a.brushVdm->name == "Ear Copy");+}++TEST(kelvinlet_is_deterministic_with_threads) {+ std::vector<glm::vec3> result[2];+ for (int pass = 0; pass < 2; ++pass) {+ ThreadPool::shared().setSerial(pass == 0);+ Document d = makeDoc(makeIcosphere(6, 1.0f));+ std::string err;+ for (BrushType t : {BrushType::KelvinGrab, BrushType::KelvinTwist, BrushType::KelvinScale, BrushType::KelvinSnake}) {+ PathStroke st = pathAlongX(-0.2f, 0.3f, 0.5f, 0.1f);+ st.symmetry = Symmetry{true, false, false};+ CHECK(strokePath(d, nullptr, t, st, err) > 0);+ }+ result[pass] = d.mesh.positions;+ }+ ThreadPool::shared().setSerial(false);+ CHECK(result[0] == result[1]);+}++TEST(kelvinlet_grab_dense_mesh_timing) {+ // ~2.6M triangles: one drag step of a large elastic grab. Limits only with SF_BENCH_LIMITS=1.+ Document d = makeDoc(makeIcosphere(8, 1.0f));+ d.syncBvh();+ CHECK(d.sculptor.beginStroke(d.mesh, "KelvinGrab"));+ KelvinletStep step;+ step.center = glm::vec3(0.0f, 0.0f, 1.0f);+ step.radius = 0.3f;+ step.delta = glm::vec3(0.01f, 0.005f, 0.0f);+ step.viewDir = glm::vec3(0.0f, 0.0f, -1.0f);+ double worst = 0.0, total = 0.0;+ for (int i = 0; i < 10; ++i) {+ const auto t0 = std::chrono::steady_clock::now();+ d.sculptor.kelvinletStep(d.mesh, d.bvh, BrushType::KelvinGrab, step, Symmetry{false, false, false});+ const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();+ worst = std::max(worst, ms);+ total += ms;+ step.center += step.delta;+ }+ const SculptTimings tm = d.sculptor.timings;+ std::printf(" (kernel %.1f, normals %.1f, BVH %.1f ms in all)\n", tm.kernelMs, tm.normalsMs, tm.bvhMs);+ d.undo.push(d.sculptor.endStroke());+ std::printf(" KelvinGrab r=0.3 on %u triangles: %.1f ms per step (worst %.1f), %llu vertices a step\n",+ d.mesh.triangleCount(), total / 10.0, worst,+ (unsigned long long)(d.sculptor.timings.vertices / std::max<uint64_t>(1, d.sculptor.timings.dabs)));+ if (std::getenv("SF_BENCH_LIMITS")) CHECK(total / 10.0 < 60.0);+}