Skip to content

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

Kelvinlets on dense meshes: bounded moves per frame, lattice far field, adaptive cutoff; threaded VDM capture

islandmedd5dd7b7a31dd
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 3e6c482b..9dcb6c81 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -755,6 +755,7 @@ int App::run() {
}
}
drainStrokeDabs(kStrokeBudgetSeconds); // the stroke's queued dabs, for a limited time: then look at the pointer again
+ kelvinCatchUp(); // a long Kelvinlet move, a bounded part per frame (PanelKelvinlet.cpp)
Uint64 now = SDL_GetTicksNS();
float dt = float(double(now - lastTicks) * 1e-9);
lastTicks = now;
@@ -1387,6 +1388,7 @@ void App::dabAt(float x, float y, float pressure) {
void App::endStroke() {
drainStrokeDabs(0.0); // the dabs still waiting belong to this stroke
doc_.sculptor.flushDetailClone(doc_.mesh, doc_.bvh, symmetry_); // a Detail Clone click
+ kelvinFinish(); // the rest of a Kelvinlet move (PanelKelvinlet.cpp)
strokeMask_ = false;
maskClickPending_ = false; // (a command can end a Ctrl+click before its release)
firstDabPending_ = false;
diff --git a/src/app/App.h b/src/app/App.h
index 9f56bcfb..1d0a65e8 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -423,6 +423,9 @@ private:
bool kelvinStrokeBrush() const; // KelvinGrab / Twist / Scale: the drag drives the brush, not dabs
void kelvinBegin(const RayHit& hit);
void kelvinTo(float x, float y);
+ void kelvinAdvance(); // applies a bounded part of the move the cursor asked for
+ void kelvinCatchUp(); // every frame: the rest of a long move, a frame at a time
+ void kelvinFinish(); // the stroke ends: all of it
void drawKelvinletSection();
void registerKelvinletActions();
bool captureMouseDown(float x, float y); // true while Capture from view is armed (it takes the drag)
@@ -445,6 +448,9 @@ private:
} capture_;
glm::vec3 kelvinCenter_{0.0f};
float kelvinRadius_ = 0.0f, kelvinLastX_ = 0.0f;
+ glm::vec3 kelvinTarget_{0.0f}; // KelvinGrab: where the cursor wants the grabbed point
+ float kelvinPending_ = 0.0f; // Twist / Scale: the turn or scale still to apply
+ float kelvinAmount_ = 1.0f;
static void SDLCALL onVdmChosen(void* userdata, const char* const* files, int filter);
static void SDLCALL onVdmExportChosen(void* userdata, const char* const* files, int filter);
friend void drawVdmGrid(App&, GridMode);
diff --git a/src/app/PanelKelvinlet.cpp b/src/app/PanelKelvinlet.cpp
index 1e9621b3..ba631f1a 100644
--- a/src/app/PanelKelvinlet.cpp
+++ b/src/app/PanelKelvinlet.cpp
@@ -54,7 +54,8 @@ void App::kelvinBegin(const RayHit& hit) {
const float pressure = pressureSize_ ? std::max(strokePressure(), 0.05f) : 1.0f;
kelvinCenter_ = hit.position;
kelvinRadius_ = radiusPx_ * pressure * camera_.worldPerPixel(hit.position, canvasHeight());
- grabPlanePoint_ = grabLast_ = hit.position;
+ grabPlanePoint_ = grabLast_ = kelvinTarget_ = hit.position;
+ kelvinPending_ = 0.0f;
kelvinLastX_ = lastX_;
lastDabScreen_ = glm::vec2(lastX_, lastY_);
}
@@ -62,12 +63,7 @@ void App::kelvinBegin(const RayHit& hit) {
void App::kelvinTo(float x, float y) {
if (strokeProbe_) strokeProbe_->emplace_back(x, y); // --measure-stroke counts each drag step as a dab
const float pressure = pressureStrength_ ? strokePressure() : 1.0f;
- const float amount = std::min(1.0f, 2.0f * strength_) * pressure;
- KelvinletStep step;
- step.radius = kelvinRadius_;
- step.viewDir = camera_.forward();
- step.axis = -camera_.forward();
- step.frontFacesOnly = frontFacesOnly_;
+ kelvinAmount_ = std::min(1.0f, 2.0f * strength_) * pressure;
if (strokeBrush_ == BrushType::KelvinGrab) {
// The grabbed point follows the cursor in the plane through it facing the camera (as Move).
glm::vec3 origin, dir;
@@ -75,36 +71,81 @@ void App::kelvinTo(float x, float y) {
const glm::vec3 n = camera_.forward();
const float denom = glm::dot(dir, n);
if (std::abs(denom) < 1e-6f) return;
- const glm::vec3 target = origin + dir * (glm::dot(grabPlanePoint_ - origin, n) / denom);
- const glm::vec3 delta = target - grabLast_;
- // One pass integrates the drag in pieces (the elastic flow, not one big shear).
+ kelvinTarget_ = origin + dir * (glm::dot(grabPlanePoint_ - origin, n) / denom);
+ } else {
+ // Twist / Scale: the drag's sideways distance in brush radii (Alt reverses).
+ const float dx = (x - kelvinLastX_) / std::max(radiusPx_, 1.0f) * kelvinAmount_ * (strokeInvert_ ? -1.0f : 1.0f);
+ kelvinPending_ += strokeBrush_ == BrushType::KelvinTwist ? -dx * 0.5f * kPi : dx * 0.6f;
+ }
+ kelvinLastX_ = x;
+ lastDabScreen_ = glm::vec2(x, y);
+ kelvinAdvance();
+}
+
+// Applies what the cursor asked for since the last move, at most a bounded amount per frame (about one brush radius
+// of travel, a 0.3 rad turn or a 0.2 log-scale step): a fast drag over a dense mesh then costs a bounded frame and
+// the rest comes in the next frames (kelvinCatchUp runs every frame, also when the pointer stopped).
+void App::kelvinAdvance() {
+ if (drag_ != Drag::Stroke || !kelvinStrokeBrush()) return;
+ KelvinletStep step;
+ step.radius = kelvinRadius_;
+ step.viewDir = camera_.forward();
+ step.axis = -camera_.forward();
+ step.frontFacesOnly = frontFacesOnly_;
+ static const bool log = std::getenv("SF_KELVIN_LOG") != nullptr;
+ const SculptTimings before = doc_.sculptor.timings;
+ // Over budget last time (the vertices a move touched): smaller pieces per frame.
+ const float share = doc_.sculptor.kelvinletOverBudget() ? 0.5f : 1.0f;
+ if (strokeBrush_ == BrushType::KelvinGrab) {
+ glm::vec3 delta = kelvinTarget_ - grabLast_;
+ const float len = glm::length(delta), most = share * kelvinRadius_;
+ if (len < 1e-7f * kelvinRadius_) return;
+ if (len > most) delta *= most / len;
+ // One pass integrates the move in pieces (the elastic flow, not one big shear).
step.center = grabLast_;
- step.delta = delta * amount;
+ step.delta = delta * kelvinAmount_;
step.travel = delta;
- step.substeps = std::clamp(int(std::ceil(glm::length(delta) / (0.4f * kelvinRadius_))), 1, 8);
- static const bool log = std::getenv("SF_KELVIN_LOG") != nullptr;
- const SculptTimings before = doc_.sculptor.timings;
+ step.substeps = std::clamp(int(std::ceil(glm::length(delta) / (0.4f * kelvinRadius_))), 1, 3);
doc_.sculptor.kelvinletStep(doc_.mesh, doc_.bvh, strokeBrush_, step, symmetry_);
- if (log) {
- const SculptTimings& t = doc_.sculptor.timings;
- SDL_Log("kelvin: %d pieces, %llu vertices, kernel %.1f normals %.1f bvh %.1f ms (renderer sync so far %.0f ms in %llu frames)", step.substeps,
- (unsigned long long)(t.vertices - before.vertices), t.kernelMs - before.kernelMs,
- t.normalsMs - before.normalsMs, t.bvhMs - before.bvhMs, perf_.strokeSyncMs, (unsigned long long)perf_.strokeFrames);
- }
- grabLast_ = target;
+ grabLast_ += delta;
} else {
- // Twist / Scale: the drag's sideways distance in brush radii (Alt reverses).
- const float dx = (x - kelvinLastX_) / std::max(radiusPx_, 1.0f) * amount * (strokeInvert_ ? -1.0f : 1.0f);
- if (dx == 0.0f) return;
+ const float most = share * (strokeBrush_ == BrushType::KelvinTwist ? 0.3f : 0.2f);
+ if (std::abs(kelvinPending_) < 1e-6f) return;
+ const float now = std::clamp(kelvinPending_, -most, most);
+ kelvinPending_ -= now;
step.center = kelvinCenter_;
- const float total = strokeBrush_ == BrushType::KelvinTwist ? -dx * 0.5f * kPi : dx * 0.6f;
// (Rotations about one axis compose exactly, and Scale integrates its own flow: one pass.)
- if (strokeBrush_ == BrushType::KelvinTwist) step.angle = total;
- else step.logScale = total;
+ if (strokeBrush_ == BrushType::KelvinTwist) step.angle = now;
+ else step.logScale = now;
doc_.sculptor.kelvinletStep(doc_.mesh, doc_.bvh, strokeBrush_, step, symmetry_);
}
- kelvinLastX_ = x;
- lastDabScreen_ = glm::vec2(x, y);
+ if (log) {
+ const SculptTimings& t = doc_.sculptor.timings;
+ SDL_Log("kelvin: %llu vertices, kernel %.1f normals %.1f bvh %.1f ms (renderer sync so far %.0f ms in %llu frames)",
+ (unsigned long long)(t.vertices - before.vertices), t.kernelMs - before.kernelMs,
+ t.normalsMs - before.normalsMs, t.bvhMs - before.bvhMs, perf_.strokeSyncMs,
+ (unsigned long long)perf_.strokeFrames);
+ }
+}
+
+void App::kelvinCatchUp() {
+ if (drag_ != Drag::Stroke || !kelvinStrokeBrush()) return;
+ const float left = strokeBrush_ == BrushType::KelvinGrab ? glm::length(kelvinTarget_ - grabLast_) / std::max(kelvinRadius_, 1e-9f)
+ : std::abs(kelvinPending_);
+ if (left > 1e-6f) kelvinAdvance();
+ else if (doc_.sculptor.kelvinletFarPending()) doc_.sculptor.flushKelvinletFar(doc_.mesh, doc_.bvh, false); // resting: the far field catches up
+ else return;
+ redrawIn(0.0); // more to do: the next frame comes even if the pointer rests
+}
+
+void App::kelvinFinish() {
+ if (drag_ != Drag::Stroke || !kelvinStrokeBrush()) return;
+ for (int i = 0; i < 64; ++i) { // the rest of the move before the stroke ends
+ const float left = strokeBrush_ == BrushType::KelvinGrab ? glm::length(kelvinTarget_ - grabLast_) / std::max(kelvinRadius_, 1e-9f)
+ : std::abs(kelvinPending_);
+ if (left < 1e-6f) break;
+ kelvinAdvance();
+ }
}
// ---------------------------------------------------------------------------
diff --git a/src/core/Kelvinlet.cpp b/src/core/Kelvinlet.cpp
index 6babdb15..529bb31e 100644
--- a/src/core/Kelvinlet.cpp
+++ b/src/core/Kelvinlet.cpp
@@ -10,7 +10,10 @@
#include "core/Vdm.h"
#include <algorithm>
+#include <array>
#include <cmath>
+#include <functional>
+#include <unordered_map>
#include <vector>
namespace sf {
@@ -200,6 +203,194 @@ struct RadialTable {
} // namespace
+// ---------------------------------------------------------------------------
+// The deferred far field (dense meshes)
+// ---------------------------------------------------------------------------
+//
+// Over a large region, most vertices are in the far field, where the move is a small fraction of the step and
+// smooth. There the field (times 1 - the near weight) is added to a coarse lattice in world space, kept once per
+// group of vertices (vertex index mod kGroups); each frame one group's vertices take what their lattice gathered
+// since their last turn and that lattice starts over. Every vertex gets the near part of every move at once and
+// the far part within kGroups frames (all of it when the stroke ends or the pointer rests: flushKelvinletFar).
+
+struct KelvinFarField {
+ static constexpr int kGroups = 6;
+ uint64_t stroke = 0;
+ float h = 0.0f; // lattice spacing (world)
+ int turn = 0; // the group whose turn is next
+ std::unordered_map<uint64_t, uint32_t> index; // lattice point -> slot
+ std::vector<glm::ivec3> point; // slot -> lattice point
+ std::vector<std::array<glm::vec3, kGroups>> acc;
+ glm::vec3 lo[kGroups], hi[kGroups]; // per group: the bounds of what it gathered since its turn
+ bool any[kGroups] = {};
+ static uint64_t key(const glm::ivec3& p) {
+ return (uint64_t(uint32_t(p.x + (1 << 20)) & 0x1fffff) << 42) | (uint64_t(uint32_t(p.y + (1 << 20)) & 0x1fffff) << 21) |
+ uint64_t(uint32_t(p.z + (1 << 20)) & 0x1fffff);
+ }
+ bool pending() const {
+ for (bool a : any)
+ if (a) return true;
+ return false;
+ }
+};
+
+namespace {
+
+// 1 within 0.6 of the radius of the load's path, a smoothstep to 0 at 1.2 radii: the near field.
+float nearWeight(float d, float radius) {
+ const float t = std::clamp((d - 0.6f * radius) / (0.6f * radius), 0.0f, 1.0f);
+ return 1.0f - t * t * (3.0f - 2.0f * t);
+}
+
+} // namespace
+
+void Sculptor::gatherKelvinletFar(const std::function<glm::vec3(const glm::vec3&)>& displacement, const glm::vec3& a,
+ const glm::vec3& ab, float radius, const glm::vec3& mid, float reach) {
+ KelvinFarField& f = *kelvinFar_;
+ const float h = f.h;
+ const glm::ivec3 i0 = glm::ivec3(glm::floor((mid - glm::vec3(reach)) / h));
+ const glm::ivec3 i1 = glm::ivec3(glm::ceil((mid + glm::vec3(reach)) / h));
+ const glm::ivec3 dim = i1 - i0 + glm::ivec3(1);
+ const size_t count = size_t(dim.x) * size_t(dim.y) * size_t(dim.z);
+ const float ab2 = glm::dot(ab, ab), reach2 = (reach + 1.8f * h) * (reach + 1.8f * h);
+ std::vector<glm::vec3> value(count, glm::vec3(0.0f));
+ std::vector<uint8_t> used(count, 0);
+ poolFor(count, [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ const glm::ivec3 q = i0 + glm::ivec3(int(i % size_t(dim.x)), int((i / size_t(dim.x)) % size_t(dim.y)),
+ int(i / (size_t(dim.x) * size_t(dim.y))));
+ const glm::vec3 p = glm::vec3(q) * h;
+ if (glm::dot(p - mid, p - mid) > reach2) continue;
+ const float t = ab2 > 0.0f ? std::clamp(glm::dot(p - a, ab) / ab2, 0.0f, 1.0f) : 0.0f;
+ const float w = 1.0f - nearWeight(glm::distance(p, a + ab * t), radius);
+ if (w <= 0.0f) continue;
+ value[i] = displacement(p) * w;
+ used[i] = 1;
+ }
+ }, 1024);
+ for (size_t i = 0; i < count; ++i) {
+ if (!used[i]) continue;
+ const glm::ivec3 q = i0 + glm::ivec3(int(i % size_t(dim.x)), int((i / size_t(dim.x)) % size_t(dim.y)),
+ int(i / (size_t(dim.x) * size_t(dim.y))));
+ auto [it, fresh] = f.index.try_emplace(KelvinFarField::key(q), uint32_t(f.point.size()));
+ if (fresh) {
+ f.point.push_back(q);
+ f.acc.emplace_back();
+ f.acc.back().fill(glm::vec3(0.0f));
+ }
+ for (glm::vec3& slot : f.acc[it->second]) slot += value[i];
+ }
+ const glm::vec3 lo = glm::vec3(i0) * h, hi = glm::vec3(i1) * h;
+ for (int g = 0; g < KelvinFarField::kGroups; ++g) {
+ f.lo[g] = f.any[g] ? glm::min(f.lo[g], lo) : lo;
+ f.hi[g] = f.any[g] ? glm::max(f.hi[g], hi) : hi;
+ f.any[g] = true;
+ }
+}
+
+// One group's turn: its vertices in the bounds its lattice gathered take the interpolated field.
+void Sculptor::applyKelvinletFarGroup(Mesh& mesh, BVH& bvh, int g) {
+ KelvinFarField& f = *kelvinFar_;
+ if (!f.any[g]) return;
+ auto clock = std::chrono::steady_clock::now();
+ const float h = f.h;
+ const glm::ivec3 i0 = glm::ivec3(glm::floor(f.lo[g] / h)), i1 = glm::ivec3(glm::ceil(f.hi[g] / h));
+ const glm::ivec3 dim = i1 - i0 + glm::ivec3(2);
+ std::vector<glm::vec3> dense(size_t(dim.x) * size_t(dim.y) * size_t(dim.z), glm::vec3(0.0f));
+ for (size_t s = 0; s < f.point.size(); ++s) {
+ const glm::ivec3 q = f.point[s] - i0;
+ glm::vec3& v = f.acc[s][size_t(g)];
+ if (q.x < 0 || q.y < 0 || q.z < 0 || q.x >= dim.x || q.y >= dim.y || q.z >= dim.z) {
+ v = glm::vec3(0.0f); // (outside every bound gathered since the turn: nothing there)
+ continue;
+ }
+ dense[(size_t(q.z) * size_t(dim.y) + size_t(q.y)) * size_t(dim.x) + size_t(q.x)] = v;
+ v = glm::vec3(0.0f);
+ }
+ f.any[g] = false;
+ const auto& pos = mesh.positions;
+ const glm::vec3 c = 0.5f * (f.lo[g] + f.hi[g]), ext = f.hi[g] - f.lo[g], meshExt = mesh.bounds().extent();
+ const double volume = double(ext.x) * double(ext.y) * double(ext.z);
+ const double meshVolume = std::max(1e-30, double(meshExt.x) * double(meshExt.y) * double(meshExt.z));
+ if (volume > 0.05 * meshVolume) {
+ // A box over much of the model: this group's vertices directly (every kGroups-th index), not a BVH query
+ // that would list all the others too.
+ const size_t nv = mesh.vertexCount(), mine = (nv + KelvinFarField::kGroups - 1 - size_t(g)) / KelvinFarField::kGroups;
+ constexpr size_t kBlock = 1 << 16;
+ std::vector<std::vector<uint32_t>> parts((mine + kBlock - 1) / kBlock);
+ const glm::vec3 lo = f.lo[g], hi = f.hi[g];
+ poolFor(mine, [&](size_t b, size_t e) {
+ auto& out = parts[b / kBlock];
+ for (size_t k = b; k < e; ++k) {
+ const uint32_t v = uint32_t(k * KelvinFarField::kGroups + size_t(g));
+ const glm::vec3 p = pos[v];
+ if (p.x < lo.x || p.y < lo.y || p.z < lo.z || p.x > hi.x || p.y > hi.y || p.z > hi.z) continue;
+ if (mesh.hasHidden() && mesh.vertexHidden(v)) continue;
+ out.push_back(v);
+ }
+ }, kBlock);
+ verts_.clear();
+ for (const auto& part : parts) verts_.insert(verts_.end(), part.begin(), part.end());
+ } else {
+ brushVertices(mesh, bvh, c, 0.5f * glm::length(ext), verts_);
+ std::erase_if(verts_, [&](uint32_t v) { return int(v % uint32_t(KelvinFarField::kGroups)) != g; });
+ }
+ scratch_.resize(verts_.size());
+ poolFor(verts_.size(), [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ const glm::vec3 gp = pos[verts_[i]] / h - glm::vec3(i0);
+ const int x = int(std::floor(gp.x)), y = int(std::floor(gp.y)), z = int(std::floor(gp.z));
+ if (x < 0 || y < 0 || z < 0 || x >= dim.x - 1 || y >= dim.y - 1 || z >= dim.z - 1) {
+ scratch_[i] = glm::vec3(0.0f);
+ continue;
+ }
+ const glm::vec3 fr = gp - glm::vec3(float(x), float(y), float(z));
+ auto at = [&](int dx, int dy, int dz) {
+ return dense[(size_t(z + dz) * size_t(dim.y) + size_t(y + dy)) * size_t(dim.x) + size_t(x + dx)];
+ };
+ const glm::vec3 c00 = glm::mix(at(0, 0, 0), at(1, 0, 0), fr.x), c10 = glm::mix(at(0, 1, 0), at(1, 1, 0), fr.x);
+ const glm::vec3 c01 = glm::mix(at(0, 0, 1), at(1, 0, 1), fr.x), c11 = glm::mix(at(0, 1, 1), at(1, 1, 1), fr.x);
+ scratch_[i] = glm::mix(glm::mix(c00, c10, fr.y), glm::mix(c01, c11, fr.y), fr.z);
+ }
+ }, 4096);
+ size_t kept = 0;
+ const float keep2 = (1e-4f * h) * (1e-4f * h);
+ for (size_t i = 0; i < verts_.size(); ++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_);
+ timings.kernelMs += lapMs(clock);
+ bvh.refit(mesh, verts_);
+ timings.bvhMs += lapMs(clock);
+ timings.vertices += verts_.size();
+ dabVerts_.insert(dabVerts_.end(), verts_.begin(), verts_.end());
+ kelvinRingNormals_ = true;
+}
+
+bool Sculptor::kelvinletFarPending() const {
+ return active_ && kelvinFar_ && kelvinFar_->stroke == strokeId_ && kelvinFar_->pending();
+}
+
+void Sculptor::flushKelvinletFar(Mesh& mesh, BVH& bvh, bool all) {
+ if (!kelvinletFarPending()) return;
+ dabVerts_.clear();
+ dabLeaves_.clear();
+ KelvinFarField& f = *kelvinFar_;
+ for (int i = 0; i < KelvinFarField::kGroups; ++i) {
+ applyKelvinletFarGroup(mesh, bvh, f.turn);
+ f.turn = (f.turn + 1) % KelvinFarField::kGroups;
+ if (!all) break;
+ }
+ dabLeaves_.clear();
+ kelvinRingNormals_ = false;
+ updateDabNormals(mesh, bvh);
+}
+
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)
@@ -209,85 +400,177 @@ void Sculptor::kelvinletSingle(Mesh& mesh, BVH& bvh, const KelvinletKernel& k, c
case KelvinletKind::Scale: amount = std::abs(s.logScale), moveScale = amount * s.radius; break;
}
if (!(amount > 0.0f)) return;
+ if (kelvinStroke_ != strokeId_) { // per stroke: the region size the last move found
+ kelvinStroke_ = strokeId_;
+ kelvinLastVerts_ = 0;
+ kelvinLastCut_ = 0.0f;
+ }
// Adaptive cutoff: where this step's displacement falls below epsilon = 4% of its largest (the window takes the
// rest smoothly to 0), so a slow drag of tiny steps still moves the surface and a fast one doesn't drag the whole
- // mesh into the pass.
+ // mesh into the pass. Over the vertex budget (the last move's density says how many the cutoff will find) the
+ // fraction rises toward 10%: a tighter region on very dense meshes.
float peak = 0.0f;
for (int i = 0; i <= 32; ++i) peak = std::max(peak, k.envelope(1.5f * s.radius * float(i) / 32.0f));
- const float epsilon = std::max(0.04f * amount * peak, 1e-7f * s.radius);
- const float cut = k.cutoff(amount, epsilon, 3.0f * s.radius);
+ const glm::vec3 travel0 = k.kind == KelvinletKind::Grab ? (glm::length(s.travel) > 0.0f ? s.travel : s.delta) : glm::vec3(0.0f);
+ const float maxDist = 3.0f * s.radius;
+ float fraction = 0.04f;
+ float cut = k.cutoff(amount, std::max(fraction * amount * peak, 1e-7f * s.radius), maxDist);
+ const size_t budget = std::max<size_t>(kelvinlet.vertexBudget, 1000);
+ if (kelvinLastVerts_ > 0 && kelvinLastCut_ > 0.0f) {
+ const float reach = cut + 0.5f * glm::length(travel0), lastReach = kelvinLastCut_;
+ const double predicted = double(kelvinLastVerts_) * double(reach * reach) / double(lastReach * lastReach);
+ if (predicted > double(budget)) {
+ fraction = std::min(0.10f, float(0.04 * predicted / double(budget)));
+ cut = k.cutoff(amount, std::max(fraction * amount * peak, 1e-7f * s.radius), maxDist);
+ }
+ }
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 glm::vec3 travel = travel0;
const int n = grab ? std::clamp(s.substeps, 1, 64) : 1;
+ RadialTable table;
+ table.build(k, cut);
+ const float cut2 = cut * cut;
+ const glm::vec3 dStep = s.delta / float(n), cStep = travel / float(n);
+ // The displacement of a point that starts at x0 (exact: the kernel through the table).
+ auto displacement = [&](const glm::vec3& x0) {
+ 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;
+ }
+ }
+ return x - x0;
+ };
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 float reach = cut + 0.5f * glm::length(travel);
const auto& pos = mesh.positions;
+ // A region bigger than kelvinlet.deferMinVertices (from the last move's density): the far field goes to the
+ // lattice (gatherKelvinletFar), only the near field's vertices are moved now.
+ const float nearReach = 1.2f * s.radius + 0.5f * glm::length(travel);
+ const bool defer = kelvinLastVerts_ > 0 && kelvinLastCut_ > 0.0f && reach > nearReach &&
+ double(kelvinLastVerts_) * double(reach * reach) / double(kelvinLastCut_ * kelvinLastCut_) >
+ double(kelvinlet.deferMinVertices);
+ if (defer) {
+ if (!kelvinFar_) kelvinFar_ = std::make_shared<KelvinFarField>();
+ if (kelvinFar_->stroke != strokeId_) {
+ *kelvinFar_ = KelvinFarField{};
+ kelvinFar_->stroke = strokeId_;
+ kelvinFar_->h = 0.1f * s.radius;
+ }
+ gatherKelvinletFar(displacement, s.center, travel, s.radius, mid, reach);
+ brushVertices(mesh, bvh, mid, nearReach, verts_);
+ kelvinLastVerts_ = size_t(double(verts_.size()) * double(reach * reach) / double(nearReach * nearReach));
+ } else {
+ brushVertices(mesh, bvh, mid, reach, verts_);
+ kelvinLastVerts_ = verts_.size();
+ }
+ kelvinLastCut_ = reach;
+ kelvinOverBudget_ = kelvinOverBudget_ || kelvinLastVerts_ > budget;
+ if (verts_.empty()) return;
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;
+ if (defer) {
+ const glm::vec3 a = s.center, ab = travel;
+ const float ab2 = glm::dot(ab, ab);
+ poolFor(verts_.size(), [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ const glm::vec3 x0 = pos[verts_[i]];
+ const float t = ab2 > 0.0f ? std::clamp(glm::dot(x0 - a, ab) / ab2, 0.0f, 1.0f) : 0.0f;
+ const float w = nearWeight(glm::distance(x0, a + ab * t), s.radius);
+ scratch_[i] = w > 0.0f ? displacement(x0) * w : glm::vec3(0.0f);
}
- 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;
+ }, 2048);
+ } else
+ // Many vertices: the smooth part of the field (beyond half the radius from the load's path) is evaluated on a
+ // coarse lattice of points around the region and interpolated (trilinear); the near field stays exact. The
+ // lattice spacing is a fortieth of the region, a tenth of the radius at most: the interpolation error is about
+ // (h / e)^2 / 8 of the move (well under 1% of it, a fraction of a pixel; tests/test_kelvinlet.cpp checks it).
+ if (verts_.size() > kelvinlet.proxyMinVertices) {
+ const float h = std::min(0.06f * s.radius, 2.0f * reach / 48.0f);
+ const glm::vec3 lo = mid - glm::vec3(reach + h);
+ const int dim = std::min(128, int(std::ceil(2.0f * (reach + h) / h)) + 2);
+ const float cell = 2.0f * (reach + h) / float(dim - 1);
+ std::vector<glm::vec3> lattice(size_t(dim) * size_t(dim) * size_t(dim));
+ poolFor(lattice.size(), [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ const size_t ix = i % size_t(dim), iy = (i / size_t(dim)) % size_t(dim), iz = i / (size_t(dim) * size_t(dim));
+ lattice[i] = displacement(lo + glm::vec3(float(ix), float(iy), float(iz)) * cell);
}
- 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);
+ }, 1024);
+ const float near = (k.kind == KelvinletKind::Scale ? 0.75f : 0.5f) * s.radius + cell;
+ const glm::vec3 a = s.center, ab = travel;
+ const float ab2 = glm::dot(ab, ab);
+ poolFor(verts_.size(), [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ const glm::vec3 x0 = pos[verts_[i]];
+ const float t = ab2 > 0.0f ? std::clamp(glm::dot(x0 - a, ab) / ab2, 0.0f, 1.0f) : 0.0f;
+ if (glm::distance(x0, a + ab * t) < near) {
+ scratch_[i] = displacement(x0);
+ continue;
}
- table.at(r2, t, w);
- x += r * ((len / len0 - 1.0f) * w);
- break;
+ const glm::vec3 g = (x0 - lo) / cell;
+ const int x = std::clamp(int(g.x), 0, dim - 2), y = std::clamp(int(g.y), 0, dim - 2), z = std::clamp(int(g.z), 0, dim - 2);
+ const glm::vec3 f = glm::clamp(g - glm::vec3(float(x), float(y), float(z)), 0.0f, 1.0f);
+ auto at = [&](int dx, int dy, int dz) {
+ return lattice[(size_t(z + dz) * size_t(dim) + size_t(y + dy)) * size_t(dim) + size_t(x + dx)];
+ };
+ const glm::vec3 c00 = glm::mix(at(0, 0, 0), at(1, 0, 0), f.x), c10 = glm::mix(at(0, 1, 0), at(1, 1, 0), f.x);
+ const glm::vec3 c01 = glm::mix(at(0, 0, 1), at(1, 0, 1), f.x), c11 = glm::mix(at(0, 1, 1), at(1, 1, 1), f.x);
+ scratch_[i] = glm::mix(glm::mix(c00, c10, f.y), glm::mix(c01, c11, f.y), f.z);
}
- }
- scratch_[i] = x - x0;
- }
- }, 2048);
+ }, 4096);
+ } else {
+ poolFor(verts_.size(), [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) scratch_[i] = displacement(pos[verts_[i]]);
+ }, 2048);
+ }
// Only what moves noticeably this step goes on (undo, normals, the BVH): the far part of the region moves
// less than 0.5% of the step, which adds up to less than 0.5% of the whole drag.
const float keep = 5e-3f * moveScale, keep2 = keep * keep;
@@ -318,6 +601,7 @@ void Sculptor::kelvinletSingle(Mesh& mesh, BVH& bvh, const KelvinletKernel& k, c
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);
+ kelvinOverBudget_ = false;
dabVerts_.clear();
dabLeaves_.clear();
for (const glm::vec3& m : mirrors(sym)) {
@@ -330,6 +614,10 @@ void Sculptor::kelvinletStep(Mesh& mesh, BVH& bvh, BrushType type, const Kelvinl
ms.axis = step.axis * m * (m.x * m.y * m.z);
kelvinletSingle(mesh, bvh, k, ms);
}
+ if (kelvinletFarPending()) { // one group of the far field's vertices catches up (see KelvinFarField)
+ applyKelvinletFarGroup(mesh, bvh, kelvinFar_->turn);
+ kelvinFar_->turn = (kelvinFar_->turn + 1) % KelvinFarField::kGroups;
+ }
if (kelvinRingNormals_) dabLeaves_.clear(); // (a mirror that moved little: rings for every mirror's vertices)
kelvinRingNormals_ = false;
updateDabNormals(mesh, bvh);
@@ -432,6 +720,7 @@ void Sculptor::dabDetailClone(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry
}
void Sculptor::flushDetailClone(Mesh& mesh, BVH& bvh, Symmetry sym) {
+ flushKelvinletFar(mesh, bvh, true); // (and the deferred far field of a Kelvinlet stroke)
if (!active_ || clone_.stroke != strokeId_ || !clone_.pending || clone_.stamped) return;
DabParams q = clone_.first;
cloneStamp(mesh, bvh, q, sym);
diff --git a/src/core/Kelvinlet.h b/src/core/Kelvinlet.h
index 52a3bf42..2c1ab8cc 100644
--- a/src/core/Kelvinlet.h
+++ b/src/core/Kelvinlet.h
@@ -41,6 +41,14 @@ struct KelvinletSettings {
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)
+ // Dense meshes: a move whose region holds more vertices than this tightens its cutoff (4% -> up to 10% of the
+ // peak) and the app gives it a smaller part of the move per frame. (A constant until the hardware profile sets it.)
+ size_t vertexBudget = 1500000;
+ // Regions above this many vertices evaluate the far field on a coarse lattice and interpolate it.
+ size_t proxyMinVertices = 150000;
+ // Regions above this many vertices move only their near field (within the radius) at once and gather the far
+ // field on a lattice that a sixth of the vertices take each frame (all of them when the stroke ends).
+ size_t deferMinVertices = 400000;
float poisson() const;
};
diff --git a/src/core/Sculpt.h b/src/core/Sculpt.h
index 0a1ae3ad..a1c9f7ff 100644
--- a/src/core/Sculpt.h
+++ b/src/core/Sculpt.h
@@ -10,6 +10,8 @@
#include "core/Undo.h"
#include <chrono>
+#include <functional>
+#include <memory>
#include <string>
#include <vector>
@@ -139,6 +141,12 @@ public:
// 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);
+ // A dense Kelvinlet stroke defers part of its far field (Kelvinlet.cpp, KelvinFarField): whether some is still
+ // waiting, and applying it (one group of vertices, or all; flushDetailClone applies all at a stroke's end).
+ bool kelvinletFarPending() const;
+ void flushKelvinletFar(Mesh& mesh, BVH& bvh, bool all);
+ // The last kelvinletStep found more vertices than kelvinlet.vertexBudget (the app then moves less per frame).
+ bool kelvinletOverBudget() const { return kelvinOverBudget_; }
// Mirror sign vectors for the enabled symmetry axes (always starts with (1,1,1)).
static std::vector<glm::vec3> mirrors(Symmetry sym);
@@ -164,6 +172,14 @@ private:
glm::vec3 last{0.0f};
} clone_;
bool kelvinRingNormals_ = false; // a Kelvinlet pass moved only part of what it queried
+ std::shared_ptr<struct KelvinFarField> kelvinFar_;
+ void gatherKelvinletFar(const std::function<glm::vec3(const glm::vec3&)>& displacement, const glm::vec3& a,
+ const glm::vec3& ab, float radius, const glm::vec3& mid, float reach);
+ void applyKelvinletFarGroup(Mesh& mesh, BVH& bvh, int group);
+ bool kelvinOverBudget_ = false; // the last kelvinletStep's region held more than kelvinlet.vertexBudget vertices
+ uint64_t kelvinStroke_ = 0;
+ size_t kelvinLastVerts_ = 0; // the last move's region: its vertex count and reach (the next one's prediction)
+ float kelvinLastCut_ = 0.0f;
uint64_t snakeStroke_ = 0;
float snakeTravel_ = 0.0f;
void finishDab(Mesh& mesh, BVH& bvh, std::chrono::steady_clock::time_point clock);
diff --git a/src/core/ViewCapture.cpp b/src/core/ViewCapture.cpp
index 5d54b88e..2c911ebc 100644
--- a/src/core/ViewCapture.cpp
+++ b/src/core/ViewCapture.cpp
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "core/ViewCapture.h"
+#include "core/AtomicRef.h"
#include "core/BVH.h"
#include "core/BrushLibrary.h"
#include "core/Commands.h"
@@ -312,7 +313,8 @@ bool captureVdmFromView(const Mesh& mesh, const BVH& bvh, const CaptureFrame& f,
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).
+ // 2. Connected to the surface under the centre: a flood fill over the candidates, a ring at a time, each ring
+ // in parallel (a vertex joins once: an atomic flag).
int64_t seed = -1;
float best = kInf;
for (size_t i = 0; i < cand.size(); ++i)
@@ -324,18 +326,25 @@ bool captureVdmFromView(const Mesh& mesh, const BVH& bvh, const CaptureFrame& f,
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)};
+ std::vector<uint32_t> inRegion(cand.size(), 0);
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> frontier{uint32_t(seed)};
+ while (!frontier.empty()) {
+ constexpr size_t kBlock = 1024;
+ std::vector<std::vector<uint32_t>> next((frontier.size() + kBlock - 1) / kBlock);
+ poolFor(frontier.size(), [&](size_t b, size_t e) {
+ std::vector<uint32_t>& out = next[b / kBlock];
+ for (size_t q = b; q < e; ++q)
+ for (uint32_t nb : mesh.neighbors(cand[frontier[q]])) {
+ const int64_t j = candIndex(nb);
+ if (j < 0 || !ok[size_t(j)]) continue;
+ AtomicRef<uint32_t> flag(inRegion[size_t(j)]);
+ if (flag.load(std::memory_order_relaxed) || flag.exchange(1, std::memory_order_relaxed)) continue;
+ out.push_back(uint32_t(j));
+ }
+ }, kBlock);
+ frontier.clear();
+ for (const auto& part : next) frontier.insert(frontier.end(), part.begin(), part.end());
}
std::vector<uint32_t> region; // sorted (cand is)
for (size_t i = 0; i < cand.size(); ++i)
@@ -349,39 +358,59 @@ bool captureVdmFromView(const Mesh& mesh, const BVH& bvh, const CaptureFrame& f,
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).
+ // Adjacency inside the region (CSR, counted then filled in parallel) 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;
+ constexpr size_t kAdjBlock = 4096;
+ std::vector<double> edgeParts((n + kAdjBlock - 1) / kAdjBlock, 0.0);
+ poolFor(n, [&](size_t b, size_t e) {
+ double sum = 0.0;
+ for (size_t i = b; i < e; ++i) {
+ uint32_t count = 0;
+ for (uint32_t nb : mesh.neighbors(region[i])) {
+ if (local(nb) < 0) {
+ rim[i] = 1;
+ continue;
+ }
+ ++count;
+ sum += glm::distance(mesh.positions[region[i]], mesh.positions[nb]);
}
- adj.push_back(uint32_t(j));
- edgeSum += glm::distance(mesh.positions[region[i]], mesh.positions[nb]);
- ++edgeCount;
+ start[i + 1] = count;
}
- }
- start[n] = uint32_t(adj.size());
+ edgeParts[b / kAdjBlock] = sum;
+ }, kAdjBlock);
+ for (size_t i = 0; i < n; ++i) start[i + 1] += start[i];
+ adj.resize(start[n]);
+ poolFor(n, [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ uint32_t k = start[i];
+ for (uint32_t nb : mesh.neighbors(region[i]))
+ if (const int64_t j = local(nb); j >= 0) adj[k++] = uint32_t(j);
+ }
+ }, kAdjBlock);
+ double edgeSum = 0.0;
+ for (double part : edgeParts) edgeSum += part;
+ const size_t edgeCount = 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).
+ // The region's triangles (each once: from its lowest-numbered vertex), gathered per block in parallel.
+ std::vector<std::vector<glm::uvec3>> triParts((n + kAdjBlock - 1) / kAdjBlock);
+ poolFor(n, [&](size_t b, size_t e) {
+ std::vector<glm::uvec3>& out = triParts[b / kAdjBlock];
+ for (size_t i = b; i < e; ++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), bb = local(tri.y), c = local(tri.z);
+ if (a < 0 || bb < 0 || c < 0) continue;
+ out.emplace_back(uint32_t(a), uint32_t(bb), uint32_t(c));
+ }
+ }, kAdjBlock);
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));
- }
+ for (const auto& part : triParts) tris.insert(tris.end(), part.begin(), part.end());
if (tris.empty()) {
error = "Too few points in the square";
return false;
diff --git a/tests/test_kelvinlet.cpp b/tests/test_kelvinlet.cpp
index 09a457df..613ff820 100644
--- a/tests/test_kelvinlet.cpp
+++ b/tests/test_kelvinlet.cpp
@@ -445,6 +445,131 @@ TEST(capture_vdm_on_a_curved_surface_keeps_only_the_detail) {
CHECK(band < 0.15f * centre); // (what is left: the sphere is not quite a quadric over so wide a square)
}
+TEST(kelvinlet_lattice_proxy_matches_the_exact_field) {
+ // The far field interpolated from the lattice against the exact kernel everywhere: the error metric is the largest
+ // difference over all vertices as a fraction of the largest displacement (and of the brush radius).
+ for (BrushType type : {BrushType::KelvinGrab, BrushType::KelvinTwist, BrushType::KelvinScale}) {
+ std::vector<glm::vec3> result[2], start;
+ for (int pass = 0; pass < 2; ++pass) {
+ Document d = makeDoc(makeIcosphere(7, 1.0f));
+ start = d.mesh.positions;
+ d.sculptor.kelvinlet.proxyMinVertices = pass == 0 ? size_t(1) << 40 : 0;
+ d.syncBvh();
+ CHECK(d.sculptor.beginStroke(d.mesh, "proxy"));
+ KelvinletStep step;
+ step.center = glm::normalize(glm::vec3(0.5f, 0.0f, 0.86f)); // (off the mirror plane: a twist there cancels)
+ step.radius = 0.4f;
+ step.delta = step.travel = glm::vec3(0.12f, 0.05f, 0.0f);
+ step.substeps = 3;
+ step.axis = glm::vec3(0.0f, 0.0f, 1.0f);
+ step.angle = 0.4f;
+ step.logScale = -0.3f;
+ d.sculptor.kelvinletStep(d.mesh, d.bvh, type, step, Symmetry{true, false, false});
+ d.undo.push(d.sculptor.endStroke());
+ result[pass] = d.mesh.positions;
+ }
+ float worst = 0.0f, biggest = 0.0f;
+ for (size_t v = 0; v < start.size(); ++v) {
+ worst = std::max(worst, glm::distance(result[0][v], result[1][v]));
+ biggest = std::max(biggest, glm::distance(result[0][v], start[v]));
+ }
+ std::printf(" %s lattice proxy: worst error %.2e = %.3f%% of the largest move, %.3f%% of the radius\n",
+ brushName(type), worst, 100.0f * worst / biggest, 100.0f * worst / 0.4f);
+ // The step's own size: how far it moves the centre (the 0.5% floor below which a vertex's move is skipped is
+ // part of both runs' difference, so the bound is against it).
+ const float stepSize = type == BrushType::KelvinGrab ? glm::length(glm::vec3(0.12f, 0.05f, 0.0f))
+ : type == BrushType::KelvinTwist ? 0.4f * 0.4f
+ : 0.3f * 0.4f;
+ std::printf(" = %.3f%% of the step\n", 100.0f * worst / stepSize);
+ CHECK(biggest > 0.01f);
+ CHECK(worst < 0.01f * stepSize); // under 1% of the step
+ }
+}
+
+TEST(kelvinlet_tightens_its_cutoff_over_the_vertex_budget) {
+ auto touched = [](size_t budget) {
+ Document d = makeDoc(makeIcosphere(7, 1.0f));
+ d.sculptor.kelvinlet.vertexBudget = budget;
+ d.syncBvh();
+ CHECK(d.sculptor.beginStroke(d.mesh, "budget"));
+ KelvinletStep step;
+ step.center = glm::vec3(0.0f, 0.0f, 1.0f);
+ step.radius = 0.5f;
+ step.delta = glm::vec3(0.01f, 0.0f, 0.0f);
+ uint64_t last = 0;
+ for (int i = 0; i < 3; ++i) { // (the first move measures the density, the next ones predict from it)
+ const uint64_t before = d.sculptor.timings.vertices;
+ d.sculptor.kelvinletStep(d.mesh, d.bvh, BrushType::KelvinGrab, step, Symmetry{false, false, false});
+ last = d.sculptor.timings.vertices - before;
+ }
+ const bool over = d.sculptor.kelvinletOverBudget();
+ d.undo.push(d.sculptor.endStroke());
+ return std::make_pair(last, over);
+ };
+ const auto [free, freeOver] = touched(size_t(1) << 40);
+ const auto [tight, tightOver] = touched(10000);
+ std::printf(" vertices a move: %llu without a budget, %llu with a 10k budget\n", (unsigned long long)free,
+ (unsigned long long)tight);
+ CHECK(!freeOver && tightOver);
+ CHECK(tight < free);
+}
+
+TEST(kelvinlet_deferred_far_field_matches_the_immediate_one) {
+ // A drag of ten moves with the far field deferred to the lattice (every move) against all of it at once: after
+ // the stroke's end the two surfaces agree within a small fraction of the drag. Undo puts everything back.
+ for (BrushType type : {BrushType::KelvinGrab, BrushType::KelvinTwist}) {
+ std::vector<glm::vec3> result[2], start;
+ size_t deferredTouched = 0, immediateTouched = 0;
+ for (int pass = 0; pass < 2; ++pass) {
+ Document d = makeDoc(makeIcosphere(7, 1.0f));
+ start = d.mesh.positions;
+ d.sculptor.kelvinlet.deferMinVertices = pass == 0 ? size_t(1) << 40 : 2000;
+ d.syncBvh();
+ CHECK(d.sculptor.beginStroke(d.mesh, "far"));
+ KelvinletStep step;
+ step.center = glm::normalize(glm::vec3(0.4f, 0.1f, 0.9f));
+ step.radius = 0.35f;
+ step.delta = glm::vec3(0.03f, 0.01f, 0.0f);
+ step.axis = glm::vec3(0.0f, 0.0f, 1.0f);
+ step.angle = 0.08f;
+ for (int i = 0; i < 10; ++i) {
+ const uint64_t before = d.sculptor.timings.vertices;
+ d.sculptor.kelvinletStep(d.mesh, d.bvh, type, step, Symmetry{true, false, false});
+ (pass == 0 ? immediateTouched : deferredTouched) += d.sculptor.timings.vertices - before;
+ if (type == BrushType::KelvinGrab) step.center += step.delta;
+ }
+ CHECK(pass == 0 || d.sculptor.kelvinletFarPending());
+ d.sculptor.flushDetailClone(d.mesh, d.bvh, Symmetry{true, false, false}); // the stroke's end
+ CHECK(!d.sculptor.kelvinletFarPending());
+ d.undo.push(d.sculptor.endStroke());
+ result[pass] = d.mesh.positions;
+ if (pass == 1) {
+ d.undo.undo(d.mesh, d.bvh);
+ float back = 0.0f;
+ for (size_t v = 0; v < start.size(); ++v) back = std::max(back, glm::distance(d.mesh.positions[v], start[v]));
+ CHECK(back < 1e-6f);
+ }
+ }
+ float worst = 0.0f, biggest = 0.0f;
+ size_t at = 0;
+ for (size_t v = 0; v < start.size(); ++v) {
+ const float e = glm::distance(result[0][v], result[1][v]);
+ if (e > worst) worst = e, at = v;
+ biggest = std::max(biggest, glm::distance(result[0][v], start[v]));
+ }
+ std::printf(" (worst at %.3f from the first centre, moved %.4f / %.4f)\n",
+ glm::distance(start[at], glm::normalize(glm::vec3(0.4f, 0.1f, 0.9f))),
+ glm::distance(result[0][at], start[at]), glm::distance(result[1][at], start[at]));
+ std::printf(" %s deferred far field: worst %.2e = %.2f%% of the largest move (%.3f%% of the radius); "
+ "vertex moves %zu deferred vs %zu at once\n",
+ brushName(type), worst, 100.0f * worst / biggest, 100.0f * worst / 0.35f, deferredTouched, immediateTouched);
+ // (Part of it is the reference's own floor: it skips vertices that move under 0.5% of a step.) Smooth, and
+ // under 1.5% of the radius: under a pixel for brushes up to about 70 px.
+ CHECK(worst < 0.015f * 0.35f);
+ CHECK(deferredTouched < immediateTouched);
+ }
+}
+
TEST(kelvinlet_is_deterministic_with_threads) {
std::vector<glm::vec3> result[2];
for (int pass = 0; pass < 2; ++pass) {