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
Kelvinlets: far-field groups are triangle blocks (spatial patches, few dirty clusters), near field within one radius; on the predictive-stroke solver thread when it is on (kelvinPump: one bounded move a batch, the stroke's end after the last)
islandmed407a4ba6ef14
diff --git a/src/app/App.h b/src/app/App.hindex 340ff155..d21a72f1 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -517,6 +517,8 @@ private:void kelvinBegin(const RayHit& hit);void kelvinTo(float x, float y);void kelvinAdvance(); // applies a bounded part of the move the cursor asked for+ bool kelvinNextStep(KelvinletStep& step); // that part, as a step (false: nothing left)+ bool kelvinPump(); // predictive strokes: hands the next step to the solver threadvoid kelvinCatchUp(); // every frame: the rest of a long move, a frame at a timevoid kelvinFinish(); // the stroke ends: all of itvoid drawKelvinletSection();diff --git a/src/app/AsyncStroke.cpp b/src/app/AsyncStroke.cppindex 9a1c5535..ebd4d693 100644--- a/src/app/AsyncStroke.cpp+++ b/src/app/AsyncStroke.cpp@@ -78,6 +78,15 @@ void App::StrokeSolver::loop() {spent += std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();}app.dabView_ = nullptr;+ if (!kelvinSteps.empty() || kelvinFar) { // a Kelvinlet stroke's moves (PanelKelvinlet.cpp)+ const auto t0 = std::chrono::steady_clock::now();+ for (const KelvinletStep& step : kelvinSteps)+ app.doc_.sculptor.kelvinletStep(app.doc_.mesh, app.doc_.bvh, kelvinBrush, step, kelvinSymmetry);+ if (kelvinSteps.empty() && kelvinFar) app.doc_.sculptor.flushKelvinletFar(app.doc_.mesh, app.doc_.bvh, false);+ spent += std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();+ kelvinSteps.clear();+ kelvinFar = false;+ }dabSeconds = batch.empty() ? 0.0 : spent / double(batch.size());const auto prepStart = std::chrono::steady_clock::now();uploadReady = prepare && app.renderer_.prepareStrokeUpload(uploadId, app.doc_.mesh, upload, app.doc_.sculptor.strokeCurvature());@@ -216,6 +225,7 @@ void App::commitSolverBatch() {void App::pumpStroke() {if (!asyncStroke_) return;+ if (kelvinStrokeBrush()) return; // (Kelvinlet strokes hand their moves over in kelvinCatchUp)if (!solver_) solver_ = std::make_unique<StrokeSolver>(*this);if (solver_->busy()) return;if (solver_->done) commitSolverBatch();diff --git a/src/app/AsyncStroke.h b/src/app/AsyncStroke.hindex 6a05764f..83eef932 100644--- a/src/app/AsyncStroke.h+++ b/src/app/AsyncStroke.h@@ -36,6 +36,12 @@ struct App::StrokeSolver {uint32_t uploadId = 0; // the active SubTool's renderer slotbool prepare = true; // pack the upload on the threadbool finalize = false; // before the batch: Sculptor::flushDraft (a draft stroke's end)+ // Kelvinlet strokes (PanelKelvinlet.cpp): after the batch's dabs, these moves (taken on the main thread, by+ // value) and, when kelvinFar, one group of the deferred far field.+ std::vector<KelvinletStep> kelvinSteps;+ BrushType kelvinBrush = BrushType::KelvinGrab;+ Symmetry kelvinSymmetry;+ bool kelvinFar = false;Renderer::StrokeUpload upload;bool uploadReady = false; // packed (else the main thread's syncScene sends the change)bool done = false; // a finished batch waits for its commitdiff --git a/src/app/PanelKelvinlet.cpp b/src/app/PanelKelvinlet.cppindex 8b1e26af..2f0eb683 100644--- a/src/app/PanelKelvinlet.cpp+++ b/src/app/PanelKelvinlet.cpp@@ -9,6 +9,7 @@// - Capture from view (Ctrl+Alt+C): drag a square (or circle) over the model; a window shows the captured// height alpha and VDM, their options, and Use / Save to library buttons.#include "app/App.h"+#include "app/AsyncStroke.h"#include "app/Ui.h"#include "core/BrushLibrary.h"@@ -85,8 +86,72 @@ void App::kelvinTo(float x, float y) {// 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).+bool App::kelvinNextStep(KelvinletStep& step) {+ step = KelvinletStep{};+ step.radius = kelvinRadius_;+ step.viewDir = camera_.forward();+ step.axis = -camera_.forward();+ step.frontFacesOnly = frontFacesOnly_;+ 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 false;+ if (len > most) delta *= most / len;+ step.center = grabLast_;+ step.delta = delta * kelvinAmount_;+ step.travel = delta;+ step.substeps = std::clamp(int(std::ceil(glm::length(delta) / (0.4f * kelvinRadius_))), 1, 3);+ grabLast_ += delta;+ return true;+ }+ const float most = share * (strokeBrush_ == BrushType::KelvinTwist ? 0.3f : 0.2f);+ if (std::abs(kelvinPending_) < 1e-6f) return false;+ const float now = std::clamp(kelvinPending_, -most, most);+ kelvinPending_ -= now;+ step.center = kelvinCenter_;+ if (strokeBrush_ == BrushType::KelvinTwist) step.angle = now;+ else step.logScale = now;+ return true;+}++// Predictive strokes (AsyncStroke.cpp): the next bounded move goes to the solver thread when it is free; the frame+// draws meanwhile. The finished batch's upload is committed first. False when there was nothing to hand over.+bool App::kelvinPump() {+ if (!solver_) solver_ = std::make_unique<StrokeSolver>(*this);+ if (solver_->busy()) return true;+ if (solver_->done) commitSolverBatch();+ StrokeSolver& s = *solver_;+ KelvinletStep step;+ const bool move = kelvinNextStep(step);+ const bool far = !move && doc_.sculptor.kelvinletFarPending();+ if (!move && !far) return false;+ s.batch.clear();+ s.kelvinSteps.clear();+ if (move) s.kelvinSteps.push_back(step);+ s.kelvinFar = far;+ s.kelvinBrush = strokeBrush_;+ s.kelvinSymmetry = symmetry_;+ s.finalize = false;+ s.view.camera = camera_;+ s.view.canvas = canvasRect();+ s.view.probe = nullptr;+ s.view.radiusProbe = nullptr;+ s.view.settings = dabSettings();+ s.uploadId = doc_.activeSubtoolInfo().id;+ renderer_.bindStrokeUpload(s.uploadId, s.upload);+ s.prepare = &displayedMesh() == &doc_.mesh;+ renderer_.setDraftNormals(doc_.sculptor.draftActive() ? s.uploadId : 0);+ s.start();+ return true;+}+void App::kelvinAdvance() {if (drag_ != Drag::Stroke || !kelvinStrokeBrush()) return;+ if (asyncStroke_) { // the solver thread does the moves (kelvinCatchUp hands them over each frame)+ kelvinPump();+ return;+ }KelvinletStep step;step.radius = kelvinRadius_;step.viewDir = camera_.forward();@@ -130,6 +195,17 @@ void App::kelvinAdvance() {}void App::kelvinCatchUp() {+ if (asyncStroke_ && kelvinStrokeBrush() && (drag_ == Drag::Stroke || strokeFinishing_)) {+ if (kelvinPump()) {+ redrawIn(0.0);+ return;+ }+ if (strokeFinishing_) { // released and everything applied: the stroke's end (a draft's normals too)+ solverWait();+ finishStrokeNow();+ }+ return;+ }if (drag_ != Drag::Stroke || !kelvinStrokeBrush()) return;if (kelvinMovedThisFrame_) { // the pointer already moved it this frame: one bounded move a framekelvinMovedThisFrame_ = false;@@ -145,13 +221,17 @@ void App::kelvinCatchUp() {}void App::kelvinFinish() {- if (drag_ != Drag::Stroke || !kelvinStrokeBrush()) return;+ if (!kelvinStrokeBrush() || (drag_ != Drag::Stroke && !strokeFinishing_)) return;+ if (asyncStroke_) solverWait(); // (then the rest on this thread)for (int i = 0; i < 64; ++i) { // the rest of the move before the stroke endsconst float left = strokeBrush_ == BrushType::KelvinGrab ? glm::length(kelvinTarget_ - grabLast_) / std::max(kelvinRadius_, 1e-9f): std::abs(kelvinPending_);if (left < 1e-6f) break;- kelvinAdvance();+ KelvinletStep step;+ if (!kelvinNextStep(step)) break;+ doc_.sculptor.kelvinletStep(doc_.mesh, doc_.bvh, strokeBrush_, step, symmetry_);}+ doc_.sculptor.flushKelvinletFar(doc_.mesh, doc_.bvh, true);}// ---------------------------------------------------------------------------diff --git a/src/core/Kelvinlet.cpp b/src/core/Kelvinlet.cppindex 17629cfe..52a33b62 100644--- a/src/core/Kelvinlet.cpp+++ b/src/core/Kelvinlet.cpp@@ -225,6 +225,35 @@ struct KelvinFarField {uint64_t stroke = 0;float h = 0.0f; // lattice spacing (world)double meshVolume = 1.0; // the model's bounding box volume at the stroke's start+ // Spatial groups: blocks of kBlockTriangles consecutive triangles (a compact patch: the renderer's chunks and+ // clusters are made of runs of consecutive triangles too), block b in group b % kGroups; a vertex belongs to+ // the block of its first triangle (fixed for the stroke: Kelvinlets don't change the topology). So a group's+ // turn moves whole patches and dirties few render clusters.+ static constexpr uint32_t kBlockShift = 12; // 4096 triangles+ std::vector<uint32_t> firstTriangle; // per vertex (its block is its group's)+ std::vector<AABB> blockBox; // per block, at the stroke's start, grown by the radius+ void prepare(const Mesh& mesh, float margin) {+ const size_t nv = mesh.vertexCount(), nt = mesh.triangleCount(), blocks = (nt + (1u << kBlockShift) - 1) >> kBlockShift;+ firstTriangle.assign(nv, ~0u);+ poolFor(nv, [&](size_t b, size_t e) {+ for (size_t v = b; v < e; ++v) {+ const IndexRing tris = mesh.vertexTriangles(uint32_t(v));+ if (tris.begin() != tris.end()) firstTriangle[v] = *tris.begin();+ }+ }, 1 << 14);+ blockBox.assign(blocks, AABB{});+ poolFor(blocks, [&](size_t b, size_t e) {+ for (size_t k = b; k < e; ++k) {+ AABB box;+ const size_t t1 = std::min(nt, (k + 1) << kBlockShift);+ for (size_t t = k << kBlockShift; t < t1; ++t)+ for (int c = 0; c < 3; ++c) box.expand(mesh.positions[mesh.triangles[t][c]]);+ box.min -= glm::vec3(margin);+ box.max += glm::vec3(margin);+ blockBox[k] = box;+ }+ }, 16);+ }int turn = 0; // the group whose turn is nextstd::unordered_map<uint64_t, uint32_t> index; // lattice point -> slotstd::vector<glm::ivec3> point; // slot -> lattice point@@ -246,9 +275,9 @@ struct KelvinFarField {namespace {-// 1 within 0.6 of the radius of the load's path, a smoothstep to 0 at 1.2 radii: the near field.+// 1 within half the radius of the load's path, a smoothstep to 0 at the radius: 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);+ const float t = std::clamp((d - 0.5f * radius) / (0.5f * radius), 0.0f, 1.0f);return 1.0f - t * t * (3.0f - 2.0f * t);}@@ -335,33 +364,33 @@ void Sculptor::applyKelvinletFarGroup(Mesh& mesh, BVH& bvh, int g) {const glm::vec3 c = 0.5f * (f.lo[g] + f.hi[g]), ext = f.hi[g] - f.lo[g];const double volume = double(ext.x) * double(ext.y) * double(ext.z);const double meshVolume = f.meshVolume; // (measured once per stroke: bounds() reads every vertex)- // Groups are runs of 4096 consecutive vertices (every kGroups-th run): a group is read as contiguous memory.- constexpr uint32_t kRun = 4096;- auto inGroup = [&](uint32_t v) { return int((v / kRun) % uint32_t(KelvinFarField::kGroups)) == g; };- if (volume > 0.05 * meshVolume) {- // A box over much of the model: this group's runs directly, not a BVH query that would list the others too.- const size_t nv = mesh.vertexCount(), runs = (nv + kRun - 1) / kRun;- std::vector<std::vector<uint32_t>> parts(runs);- const glm::vec3 lo = f.lo[g], hi = f.hi[g];- poolFor(runs, [&](size_t b, size_t e) {- for (size_t r = b; r < e; ++r) {- if (int(r % size_t(KelvinFarField::kGroups)) != g) continue;- auto& out = parts[r];- const uint32_t v0 = uint32_t(r * kRun), v1 = uint32_t(std::min(nv, (r + 1) * size_t(kRun)));- for (uint32_t v = v0; v < v1; ++v) {- 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);+ (void)c;+ (void)volume;+ (void)meshVolume;+ const double denseMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - clock).count();+ // This group's blocks that meet the bounds it gathered: their triangles' corners that belong to the group.+ const size_t nt = mesh.triangleCount(), blocks = f.blockBox.size();+ const glm::vec3 lo = f.lo[g], hi = f.hi[g];+ std::vector<std::vector<uint32_t>> parts(blocks);+ poolFor(blocks, [&](size_t b, size_t e) {+ for (size_t k = b; k < e; ++k) {+ if (int(k % size_t(KelvinFarField::kGroups)) != g) continue;+ const AABB& box = f.blockBox[k];+ if (box.max.x < lo.x || box.max.y < lo.y || box.max.z < lo.z || box.min.x > hi.x || box.min.y > hi.y || box.min.z > hi.z)+ continue;+ auto& out = parts[k];+ const size_t t1 = std::min(nt, (k + 1) << KelvinFarField::kBlockShift);+ for (size_t t = k << KelvinFarField::kBlockShift; t < t1; ++t)+ for (int corner = 0; corner < 3; ++corner) {+ const uint32_t v = mesh.triangles[t][corner];+ // (each vertex once: from its first triangle, which is in a block of its group)+ if (f.firstTriangle[v] == uint32_t(t) && !(mesh.hasHidden() && mesh.vertexHidden(v))) out.push_back(v);}- }- }, 1);- 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 !inGroup(v); });- }+ }+ }, 1);+ verts_.clear();+ for (const auto& part : parts) verts_.insert(verts_.end(), part.begin(), part.end());+ const double selectMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - clock).count();scratch_.resize(verts_.size());poolFor(verts_.size(), [&](size_t b, size_t e) {for (size_t i = b; i < e; ++i) {@@ -390,9 +419,8 @@ void Sculptor::applyKelvinletFarGroup(Mesh& mesh, BVH& bvh, int g) {verts_.resize(kept);scratch_.resize(kept);if (std::getenv("SF_KELVIN_LOG"))- std::fprintf(stderr, "kelvin far: group %d, %zu vertices, %s, %.1f ms\n", g, kept,- volume > 0.05 * meshVolume ? "stride" : "query",- std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - clock).count());+ std::fprintf(stderr, "kelvin far: group %d, %zu vertices, lattice %.1f, select %.1f, total %.1f ms\n", g, kept, denseMs,+ selectMs, std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - clock).count());if (verts_.empty()) return;displaceAll(mesh, verts_, scratch_);timings.kernelMs += lapMs(clock);@@ -520,7 +548,7 @@ void Sculptor::kelvinletSingle(Mesh& mesh, BVH& bvh, const KelvinletKernel& k, cconst 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 float nearReach = 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);@@ -532,6 +560,7 @@ void Sculptor::kelvinletSingle(Mesh& mesh, BVH& bvh, const KelvinletKernel& k, ckelvinFar_->h = 0.1f * s.radius;const glm::vec3 e = mesh.bounds().extent();kelvinFar_->meshVolume = std::max(1e-30, double(e.x) * double(e.y) * double(e.z));+ kelvinFar_->prepare(mesh, s.radius);}gatherKelvinletFar(displacement, s.center, travel, s.radius, mid, reach);brushVertices(mesh, bvh, mid, nearReach, verts_);@@ -542,6 +571,9 @@ void Sculptor::kelvinletSingle(Mesh& mesh, BVH& bvh, const KelvinletKernel& k, c}kelvinLastCut_ = reach;kelvinOverBudget_ = kelvinOverBudget_ || kelvinLastVerts_ > budget;+ if (std::getenv("SF_KELVIN_LOG"))+ std::fprintf(stderr, "kelvin move: %s, %zu vertices queried, reach %.3f (radius %.3f, travel %.3f), cut %.2f%%\n",+ defer ? "near field now" : "all now", verts_.size(), reach, s.radius, glm::length(travel), fraction * 100.0f);if (verts_.empty()) return;if (s.frontFacesOnly) {const auto& nrm = mesh.normals;