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.

Perf moonshots: three flag-gated prototypes and the research note

islandmed4fd988f13e3c
diff --git a/docs/design/perf-moonshots.md b/docs/design/perf-moonshots.md
new file mode 100644
index 00000000..1d197dc0
--- /dev/null
+++ b/docs/design/perf-moonshots.md
@@ -0,0 +1,186 @@
+# Performance moonshots: sculpting that costs pixels, not polygons
+
+Research branch `research/perf-moonshots` (2026-11-01). Goal: the cost of a stroke grows with the pixels on screen
+and the brush footprint, never with the total polygon count. This note surveys recent work, rates eight ideas,
+reports three prototypes measured with `--benchmark standard-33m`, and recommends what to ship.
+
+Starting point (Tony's clean 33M run, M1 Pro, Asahi, Mesa GL 4.6, unified memory): orbit 89 fps; Clay small p99
+38 ms; Clay large p99 119 ms; 240 px brush p99 338 ms; Move 18 fps. The branch is built on `perf/bigbrush-p99`
+(dabs of meshes from 2M vertices go to the solver thread without the preview), which already takes the stroke
+p99s to about 30 ms; what it leaves is the surface trailing the pen (each 240 px dab at 33M still costs
+100-200 ms of CPU) and Move, which never used the solver path.
+
+## 1. What SculptForge already does (so the ideas below are measured against the right thing)
+
+| Piece | Where | State |
+|---|---|---|
+| Solver thread for dabs, two-part upload (pack on the thread, `glBufferSubData` on the GL thread) | `app/AsyncStroke.cpp`, `Renderer::prepareStrokeUpload` | on (bigbrush: from 2M vertices) |
+| GPU preview of the dabs not solved yet ("ghost"), analytic per brush kernel in the vertex shader, normals by forward differentiation | `render/Ghost.h`, `kMeshVS` GHOST | only with Predictive Strokes, which is **off** by default |
+| Pen prediction: alpha-beta-gamma filter, 25 ms ahead | `core/PenPredictor.h` | with the ghost |
+| Draft strokes: positions only, normals at pen lift | `Sculptor::draftStrokes` | off; measured no gain on M1 |
+| Cluster culling + motion proxy | `render/Clusters.h` | on |
+| Micro levels: 16-bit scalar height per point above the top level, evaluated in the vertex shader; stride-sampled brushes | `core/Micro.h`, `render/MicroRenderer.h` | on; 1.02B triangles in 1.7 GB RSS |
+| Kelvinlet brushes (grab, twist, scale, snake) | `core/Kelvinlet.h` | on |
+
+So "GPU preview from a dab list" (idea 1) and "quantized scalar displacement" (idea 6) exist already; the
+question for them is where they are not used yet.
+
+## 2. Research (2022-2026, plus the classics they build on)
+
+**Micro-meshes and displacement micro-maps.** NVIDIA's micro-mesh primitive is a base mesh plus a compressed,
+UV-free displacement per base face (11-bit scalars, four watertight levels), with hardware support on recent GPUs
+for ray tracing [1]. Maggiordomo, Moreton and Tarini, *Micro-Mesh Construction* (SIGGRAPH 2023 / TOG 42(4)) build
+them automatically from dense meshes with a base simplification tuned for tessellation and displacement sampling,
+with an open reference implementation [2]. Our micro levels are the same idea (16-bit heights, barycentric grid
+per base triangle) for editing rather than for ray tracing; [2]'s base-mesh simplification is relevant to
+"Divide to micro" on scanned meshes.
+
+**Cluster LOD / virtual geometry.** Nanite (Karis, Stubbe, Wihlidal, SIGGRAPH 2021 Advances [3]): ~128-triangle
+clusters, a DAG of cluster groups simplified with locked group borders, LOD chosen per group by projected error,
+visibility buffer and a software rasterizer for small triangles, streaming of pages. The 2021 design assumed rigid
+meshes; UE 5.4 added tessellation with programmable displacement and UE 5.5 skinned Nanite meshes (deformed on
+the GPU before culling) [4] (secondary sources; Epic's own notes should be checked before quoting).
+NVIDIA's RTX Mega Geometry (2025) builds cluster acceleration structures, *cluster templates* (topology reused,
+only vertices new), per-frame cluster tessellation of subdivision surfaces at about one triangle per pixel, and a
+continuous cluster-LOD library [5]. The common lesson for an editor: keep topology-derived data (clusters, LOD
+DAG, templates) fixed while vertices change, and rebuild only the cluster groups an edit touched.
+
+**Sculpting engines.** Blender 4.3's sculpt refactor (2024) reports brushes about 8x faster and 30% less memory
+on a 16M-face mesh, from data-oriented attribute arrays, a face (not triangle) BVH, removing per-element call
+layers and writing deformation directly per symmetry pass [6]. That is the "make the CPU kernel lean" path; we
+are already there in structure (flat arrays, parallel kernels); our remaining dab cost is proportional to the
+vertices under the brush, which is the term this note attacks.
+
+**Analytic deformers.** Regularized Kelvinlets (de Goes and James, SIGGRAPH 2017) give closed-form, volume-aware
+grab/twist/scale/pinch brushes from regularized fundamental solutions of linear elasticity [7]; Dynamic
+Kelvinlets (2018) and Sharp Kelvinlets (DigiPro 2019, multi-scale cusps) extend them [7]. Blender's Elastic Deform
+and Unreal's modeling tools ship them. Key property for us: a closed-form displacement of the *start* position
+is exactly what a vertex shader can evaluate; so are our Move and Standard kernels.
+
+**Progressive refinement.** Hoppe's progressive meshes (SIGGRAPH 1996) and their GPU successors (cluster DAGs
+above) refine coarse-to-fine by screen error. For editing, the exact final geometry is the constraint: coarse
+first is useful as a *display* order, not as a different result.
+
+**Zero-copy buffers.** `GL_ARB_buffer_storage` (core in 4.4) allows immutable storage that stays mapped while the
+GPU uses it (`MAP_PERSISTENT`), with writes visible without flushes (`MAP_COHERENT`); it is the core of the
+"Approaching Zero Driver Overhead" techniques (Everitt, McDonald et al., GDC 2014 [8]). It does not remove
+synchronisation: the application must fence what the GPU may still read [8].
+
+**Pen-latency prediction.** Henze et al. (MobileHCI 2016/2017) extrapolate touch with small neural networks;
+predicting 33 ms ahead improved task performance, beyond that it did not [9]. A GRU-CNN stylus predictor
+(Samsung Research, HCII 2020) reports 0.07/0.24/0.47 mm error at ~16/33/50 ms, several times below LSTM
+baselines [10]. TurboTouch (UIST 2018) uses finite-time derivative estimation and predicts 2-3x further with few
+side effects [11]. Our alpha-beta-gamma filter is the classical baseline these improve on.
+
+**What the Asahi driver offers (checked on this machine).** Mesa 26.1.8 reports OpenGL 4.6 core with
+`GL_ARB_buffer_storage`, `GL_ARB_compute_shader`, `GL_ARB_shader_storage_buffer_object`,
+`GL_ARB_multi_draw_indirect`, `GL_ARB_indirect_parameters` and `GL_ARB_shader_draw_parameters` (glxinfo). The
+Asahi drivers are conformant for OpenGL 4.6, OpenGL ES 3.2, OpenCL 3.0 and Vulkan 1.4 (Honeykrisp, in Mesa since
+24.3); the hardware has no geometry or tessellation shaders, which the driver emulates with compute [12]
+(so our texture-painting geometry shader is a compute pass on this GPU). No source says Honeykrisp exposes
+`VK_EXT_mesh_shader`, and `vulkaninfo` is not installed here; treat mesh shaders as unavailable. GPU-driven
+culling therefore means compute + multi-draw-indirect, which the driver has.
+
+## 3. How ZBrush does it (publicly documented approaches only)
+
+From Maxon's documentation and public material only (no binaries inspected):
+(a) **2.5D pixol canvas**: ZBrush has "a 2.5D canvas document", not a 3D scene; a pixol is a pixel with depth,
+orientation and material [13]. The heritage is a CPU renderer whose cost follows pixels.
+(b) **Subdivision levels**: the classic multires stack (ours: subdivision levels).
+(c) **HD Geometry**: DivideHD adds levels beyond the highest SDiv; Sculpt HD (the A hotkey) "selects an area of
+your model around the current mouse position for high-definition sculpting", circular or square [14]; only that
+region is at HD resolution while the rest stays at the regular top level.
+(d) **Per-mesh caps**: Preferences > Mem > MaxPolyPerMesh limits polygons per mesh (in millions), with a separate
+HD preview cap [15]; dense work is split into many objects, hidden ones costing little.
+
+What it implies: their interactivity comes from bounding the *active* point count (cap per object, a local HD
+region) on a CPU renderer. Our equivalents must bound the same thing with our own design: micro levels (bounded
+bytes per triangle), a focus region (idea 8) and GPU drawing whose cost follows the screen.
+
+## 4. Ideas, rated
+
+Gain is for the 33M standard scene unless said; effort in agent-days; fit = how well it suits our engine.
+
+| # | Idea | Expected gain | Risk | Effort | Fit |
+|---|---|---|---|---|---|
+| 1 | GPU stroke preview from the dab list, async commit | surface under the pen within a few px at any brush size (measured below); Move frame cost independent of the region | low: preview only, the solver's mesh is unchanged | 1-2 (exists; extend) | **high** |
+| 2 | Coarse-first progressive dab application | none on the final mesh (same work); as a display order (visible clusters packed first) maybe 30-50% sooner visible surface on big symmetric brushes | medium: order changes must stay bit-identical | 2-3 | low once (1) is on: the preview already shows the result |
+| 3 | Strokes as data (analytic fields, replay, re-tune, cheap undo) | undo of a 240 px stroke at 33M: tens of MB of positions -> ~10 KB of dabs; re-tune strength after the fact | high: Clay, Smooth, Flatten read the surface, so replay is sequential and as costly as the stroke; determinism across versions | 10+ | medium (Sculpt Timeline is the natural home) |
+| 4 | Zero-copy persistent mapped buffers on unified memory | the GL thread's commit (2-10 ms per batch) -> a GPU copy command; measured below | low-medium: fences; not on macOS GL 4.1 (fallback kept) | 1 (prototyped) | medium |
+| 5 | Cluster LOD with a per-cluster pixel budget (Nanite-style DAG on an editable mesh) | orbit cost bounded by screen (as micro levels already are: 3-4M triangles drawn at 299M, 8-9 ms); 33M orbit 89 -> ~110+ fps | high: cracks at group borders, rebuild the edited groups after each stroke | 10-15 | medium (compute + MDI available, no mesh shaders) |
+| 6 | Quantized scalar displacement + GPU normals | memory 90 -> 1.25 B per triangle above the top level (micro levels, measured in docs/performance.md) | low (exists) | 2-3 to make it automatic ("Divide" past ~8M goes to a micro level) | **high** |
+| 7 | Learned pen prediction | at most 1-3 px of the 1-4 px preview lag left; literature: no gain beyond 33 ms ahead [9] | medium: training data, per-device tuning | 3-5 | low |
+| 8 | **Focus Detail** (below) | billion-triangle assets in a few GB of RAM and ~0.3-0.5 GB of GPU, editable locally at the speed of a 30-60M mesh | medium-high: streaming latency, seams between levels | 8-12 (data side started on `research/focus-detail`) | **high** |
+
+### Idea 8: Focus Detail (our design)
+
+The region under and near the brush is promoted to full micro resolution; everything else stays at a coarse
+micro level (or compressed on disk), and the GPU draws each tile at its own level.
+
+- **Data** (`core/FocusDetail`, branch `research/focus-detail`, in progress): micro tiles (one per base
+ triangle) stored zstd-compressed in a tile file; a focus region (brush footprint plus a margin, plus what the
+ view needs at one micro triangle per pixel) is decompressed to full level; tiles outside hold an upsampled coarse
+ grid (level 3) so the MicroRenderer works unchanged today. Promotion and demotion `markDirty(tri)`; budget the
+ promoted tiles by bytes (e.g. 512 MB) and demote least recently used.
+- **GPU** (follow-up here): per-tile resident level. Coarse tiles keep 45 points (level 3) instead of 8385
+ (level 7), drawn with the same vertex-shader evaluation at that level; the data side exposes
+ `FocusDetail::tileLevel(tri)`. Edge stitching between a level-3 and a level-7 tile: snap the fine tile's edge
+ points to the coarse edge (as micro levels already stitch shared edges).
+- **What it enables, estimated** for 1.0B triangles (micro level 7 on 61K base triangles; 8385 points a tile):
+ all tiles at full level are 511M points: 1.0 GB of heights on the CPU, ~3 GB on the GPU (2 B height + 4 B
+ shading per point). With Focus Detail: coarse everywhere 2.7M points (16 MB GPU); a focus of ~2% of the tiles
+ (a 240 px brush plus margin on a full figure) 1.2K tiles x 8385 points = 10M points (60 MB GPU, 20 MB CPU);
+ compressed tile file perhaps 0.4-0.6 GB on disk (16-bit heights of sculpted detail compress 2-3x; to be
+ measured). Dab cost depends on the points under the brush at full level, the same as on a 30-60M mesh today
+ (docs/performance.md: Standard 64 px on 1.02B Micro 5 is 39 ms a step, 300 px 283 ms); drawing stays bounded
+ by the screen. **A billion-triangle asset, editable locally at interactive rates on a 16 GB laptop**, is the
+ claim to test; nothing here is measured yet, so no public claim until it is.
+- **Difference from (c)**: the focus follows the brush automatically (no mode to enter), the coarse remainder is
+ the same surface at a lower micro level (not a separate HD layer), and GPU memory follows focus + screen.
+
+## 5. Prototypes (feature flags, off by default)
+
+All three are environment flags so they cost nothing when off. None changes what a stroke leaves on the mesh
+except Live Move's commit (one grab with the summed move instead of one per frame; tested equal to 1e-6).
+
+1. **Background preview** (`SF_BG_GHOST=1`, idea 1): the ghost (already written for predictive strokes) also
+ draws the dabs of bigbrush's background path, and the frame no longer waits 12.5 ms for a batch. The solver's
+ dabs are unchanged (same dabs, same order), so the final mesh is identical by construction.
+2. **Live Move** (`SF_LIVE_MOVE=1`, ideas 1 and 3): a Move drag is not applied frame by frame. The GPU draws it
+ from the grab's start positions (`GhostKind::Move`: x0 + d w(|x0 - c|), normals by the rank-one inverse
+ transpose), per symmetry mirror, and one `Sculptor::grab` with the whole move is applied when the stroke ends.
+ Falls back to the old path with masks, hidden faces, sculpt layers, micro levels, connected-only or view
+ falloff. Test `live_move_matches_the_grab`: the preview matches the grab to 1e-5, one grab matches the
+ per-frame grabs to 1e-6 (X symmetry, focal shift).
+3. **Persistent upload** (`SF_PERSISTENT_UPLOAD=1`, idea 4): two persistently mapped, coherent staging buffers
+ (48 MB each, `glBufferStorage`); the solver thread packs straight into one, the GL thread issues
+ `glCopyBufferSubData` for each range and a fence; a buffer is reused only after its fence. Batches larger than
+ 4M vertices pack into the old vector as before.
+
+### Measurements
+
+MEASUREMENTS
+
+## 6. Recommendation
+
+RECOMMENDATION
+
+## References
+
+1. NVIDIA Research, *Micro-Mesh Construction* project page and micro-mesh format: https://research.nvidia.com/publication/2023-08_micro-mesh-construction
+2. A. Maggiordomo, H. Moreton, M. Tarini, *Micro-Mesh Construction*, ACM TOG 42(4), SIGGRAPH 2023: https://micromesh.di.unimi.it/
+3. B. Karis, R. Stubbe, G. Wihlidal, *Nanite: A Deep Dive*, SIGGRAPH 2021 Advances: https://advances.realtimerendering.com/s2021/Karis_Nanite_SIGGRAPH_Advances_2021_final.pdf
+4. UE 5.4 Nanite tessellation (Puget Systems): https://www.pugetsystems.com/blog/2024/04/16/exploring-unreal-engine-5-4-whats-new-and-whats-next/ ; UE 5.5 skinned Nanite (secondary): https://wnhub.io/news/engines/item-45659
+5. NVIDIA, *Fast Ray Tracing of Dynamic Scenes Using OptiX 9 and RTX Mega Geometry*: https://developer.nvidia.com/blog/fast-ray-tracing-of-dynamic-scenes-using-nvidia-optix-9-and-nvidia-rtx-mega-geometry ; Vulkan samples: https://developer.nvidia.com/blog/nvidia-rtx-mega-geometry-now-available-with-new-vulkan-samples
+6. Blender developers, *This Summer's Sculpt Mode Refactor* (2024): https://code.blender.org/2024/11/this-summers-sculpt-mode-refactor/
+7. F. de Goes, D. L. James, *Regularized Kelvinlets* (SIGGRAPH 2017): https://graphics.pixar.com/library/Kelvinlets ; *Sharp Kelvinlets* (DigiPro 2019): https://graphics.pixar.com/library/SharpKelvinlets
+8. `ARB_buffer_storage` specification: https://developer.download.nvidia.com/opengl/specs/GL_ARB_buffer_storage.txt ; C. Everitt, J. McDonald, *Beyond Porting* (AZDO): https://www.ozone3d.net/dl/201401/NVIDIA_OpenGL_beyond_porting.pdf ; persistent mapping notes: https://cppstories.com/2015/01/persistent-mapped-buffers-in-opengl
+9. N. Henze, H. V. Le, S. Mayer, V. Schwind, *Improving Software-Reduced Touchscreen Latency*, MobileHCI 2017: https://www.medien.informatik.uni-muenchen.de/pubdb/publications/pub/henze2017improving/henze2017improving.pdf
+10. Samsung Research, *Active Stylus Input Latency Compensation on Touch Screen Mobile Devices* (HCII 2020): https://research.samsung.com/research-papers/Active-Stylus-Input-Latency-Compensation-on-Touch-Screen-Mobile-Devices
+11. TurboTouch predictor (UIST 2018): https://github.com/LokiResearch/TurboTouchPredictor ; https://hal.archives-ouvertes.fr/hal-01893310
+12. A. Rosenzweig, Asahi GPU driver status (OpenGL 4.6, Vulkan 1.4, geometry/tessellation emulation): https://rosenzweig.io/blog/asahi-gpu-part-n.html ; Honeykrisp in Mesa 24.3: https://www.phoronix.com/news/Apple-Vulkan-Driver-Mesa-24.3
+13. Maxon ZBrush docs, *The Canvas Document* and *The Pixol*: https://help.maxon.net/zbr/en-us/Content/html/getting-started/basic-concepts/the-canvas-document/the-canvas-document.html ; https://help.maxon.net/zbr/en-us/Content/html/getting-started/basic-concepts/the-pixol/the-pixol.html
+14. Maxon ZBrush docs, *Geometry HD*: https://help.maxon.net/zbr/en-us/Content/html/reference-guide/tool/polymesh/geometry-hd/geometry-hd.html
+15. Maxon ZBrush docs, *Preferences > Mem*: https://help.maxon.net/zbr/en-us/Content/html/reference-guide/preferences/mem/mem.html
+
+ZBrush is a trademark of Maxon; SculptForge is not affiliated with or endorsed by Maxon.
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 12c487cc..bff37ffa 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -1710,6 +1710,11 @@ void App::beginStroke(float x, float y, const RayHit& hit) {
p.connectedOnly = uiPrefs_.connectedOnly;
p.viewFalloff = uiPrefs_.viewFalloff;
doc_.sculptor.beginGrab(doc_.mesh, doc_.bvh, p, symmetry_);
+ liveMove_ = {};
+ if (liveMoveEnabled() && !p.connectedOnly && !p.viewFalloff && !doc_.mesh.micro && !doc_.mesh.hasMask() &&
+ !doc_.mesh.hasHidden() && doc_.mesh.layers.empty() && !doc_.sculptor.dyntopo.enabled &&
+ &displayedMesh() == &doc_.mesh)
+ liveMove_ = {true, p.center, glm::vec3(0.0f), p.radius, std::clamp(p.strength * 2.0f, 0.0f, 1.0f)};
grabPlanePoint_ = grabLast_ = hit.position;
beginAlongNormal(hit, p.radius);
return;
@@ -1758,7 +1763,8 @@ void App::strokeTo(float x, float y) {
const BrushRecipe* recipe = strokeRecipe();
if (strokeBrush_ == BrushType::Move && !recipe && strokeSculpt_ && strokeAlongNormal_) {
const glm::vec3 p = alongNormalTarget(x, y);
- doc_.sculptor.grab(doc_.mesh, doc_.bvh, p - grabLast_);
+ if (liveMove_.active) liveMove_.delta += p - grabLast_;
+ else doc_.sculptor.grab(doc_.mesh, doc_.bvh, p - grabLast_);
grabLast_ = p;
return;
}
@@ -1770,7 +1776,8 @@ void App::strokeTo(float x, float y) {
if (std::abs(denom) < 1e-6f) return;
float t = glm::dot(grabPlanePoint_ - origin, n) / denom;
glm::vec3 p = origin + dir * t;
- doc_.sculptor.grab(doc_.mesh, doc_.bvh, p - grabLast_);
+ if (liveMove_.active) liveMove_.delta += p - grabLast_;
+ else doc_.sculptor.grab(doc_.mesh, doc_.bvh, p - grabLast_);
grabLast_ = p;
return;
}
diff --git a/src/app/App.h b/src/app/App.h
index 57830487..ece9f7d6 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -312,6 +312,7 @@ private:
bool asyncStroke_ = false; // this stroke's dabs go to the solver thread
bool strokeFinishing_ = false; // released: the solver places the last dabs, the UI carries on
bool predictiveStrokes() const; // the preference (and its environment override)
+ bool previewStrokes() const; // the stroke's dabs draw the predictive preview (predictive, or SF_BG_GHOST)
bool draftStrokes() const; // Draft Strokes (SF_DRAFT_STROKE=0 / 1 overrides)
bool backgroundDabs() const; // a heavy mesh's dabs on the solver thread without the preview (SF_BACKGROUND_DABS)
bool asyncStrokeAllowed() const; // the stroke beginning now may use the solver thread
@@ -348,6 +349,16 @@ private:
BrushType strokeBrush_ = BrushType::Standard;
bool strokeInvert_ = false;
glm::vec3 grabPlanePoint_{0.0f}, grabLast_{0.0f};
+ // Live Move (SF_LIVE_MOVE=1, a research prototype, docs/design/perf-moonshots.md): a Move drag on a plain mesh
+ // isn't applied frame by frame; the GPU draws it (render/Ghost.h, GhostKind::Move) from the grab's start, and
+ // the whole move is applied once when the stroke ends (finishStrokeNow): one grab instead of one a frame.
+ struct LiveMove {
+ bool active = false;
+ glm::vec3 center{0.0f}, delta{0.0f};
+ float radius = 0.0f, scale = 0.0f;
+ } liveMove_;
+ static bool liveMoveEnabled();
+ void commitLiveMove();
// Along the normal (from the discussions): Move, Tendril, Elastic Tendril and KelvinGrab strokes that began with
// the invert key held (Preferences > Input > Along the normal) slide along the average normal under the brush
// at the press instead of the view plane. alongNormalTarget: where the cursor puts the grabbed point.
diff --git a/src/app/AsyncStroke.cpp b/src/app/AsyncStroke.cpp
index 91f7e76b..633e3cc7 100644
--- a/src/app/AsyncStroke.cpp
+++ b/src/app/AsyncStroke.cpp
@@ -152,6 +152,16 @@ bool App::backgroundDabs() const {
return env >= 0 ? env == 1 : doc_.mesh.vertexCount() >= kBackgroundDabVertices;
}
+bool App::previewStrokes() const {
+ // SF_BG_GHOST=1 (a research prototype, docs/design/perf-moonshots.md): background dabs draw the predictive
+ // preview too (it never changes the mesh: the solver's dabs are the same), and the frame doesn't wait for them.
+ static const bool bgGhost = [] {
+ const char* v = std::getenv("SF_BG_GHOST");
+ return v && *v == '1';
+ }();
+ return predictiveStrokes() || (bgGhost && backgroundDabs());
+}
+
bool App::asyncStrokeAllowed() const {
// Sculpt strokes of queued dabs only: Move, Snake Hook and the drag strokes work in strokeTo itself; painting,
// masking and dynamic topology (which changes the layout the renderer packs for) stay in the frame loop.
@@ -295,11 +305,28 @@ void App::pumpStroke() {
s.start();
// Background dabs: a batch is waited for here up to a frame's share of work, so a light one shows in this frame
// as in the frame loop's own path; a heavier one goes on while the frame draws, and the next frame commits it.
- if (!predictiveStrokes() && dabSeconds_ > 0.0 && s.waitFor(kBackgroundBatchSeconds * 1.25) && s.done)
+ if (!previewStrokes() && dabSeconds_ > 0.0 && s.waitFor(kBackgroundBatchSeconds * 1.25) && s.done)
commitSolverBatch();
}
+bool App::liveMoveEnabled() {
+ static const bool on = [] {
+ const char* v = std::getenv("SF_LIVE_MOVE");
+ return v && *v == '1';
+ }();
+ return on;
+}
+
+void App::commitLiveMove() {
+ if (!liveMove_.active) return;
+ liveMove_.active = false;
+ // One grab with the whole move: the weights are the grab's own, so this is the sum of the per-frame grabs.
+ if (glm::dot(liveMove_.delta, liveMove_.delta) > 0.0f) doc_.sculptor.grab(doc_.mesh, doc_.bvh, liveMove_.delta);
+ renderer_.setGhost(0, GhostStroke());
+}
+
void App::finishStrokeNow() {
+ commitLiveMove();
if (solver_) solver_->finalize = false;
doc_.sculptor.flushDraft(doc_.mesh, doc_.bvh); // (a draft stroke ended here rather than on the solver thread)
renderer_.setDraftNormals(0);
@@ -369,7 +396,7 @@ bool App::pickWith(const DabView& view, float x, float y, RayHit& hit) const {
}
glm::vec2 App::predictedPointer() const {
- if (!predictiveStrokes() || drag_ != Drag::Stroke || !asyncStroke_) return glm::vec2(mouseX_, mouseY_);
+ if (!previewStrokes() || drag_ != Drag::Stroke || !asyncStroke_) return glm::vec2(mouseX_, mouseY_);
// To when this frame reaches the screen: about a frame after the newest sample.
const double ahead = std::clamp(frameSeconds_, 0.004, PenPredictor::kMaxAhead);
return penPredictor_.predict(pointerLatestAt_ + ahead, pointerLatest_);
@@ -401,11 +428,30 @@ bool App::ghostSurface(const glm::vec3& origin, const glm::vec3& dir, glm::vec3&
void App::buildGhost() {
ghostHeadValid_ = false;
const uint32_t id = doc_.activeSubtoolInfo().id;
+ if (liveMove_.active) { // Live Move: one "dab" per mirror, the whole move so far
+ GhostStroke g;
+ g.kind = GhostKind::Move;
+ g.focal = focalShift_;
+ std::vector<SymCopy> mirrors = Sculptor::copies(symmetry_);
+ if (mirrors.size() > GhostStroke::kMaxMirrors) mirrors.resize(GhostStroke::kMaxMirrors);
+ for (uint32_t m = 0; m < mirrors.size(); ++m) {
+ GhostDab d;
+ d.center = mirrors[m].point(liveMove_.center);
+ d.radius = liveMove_.radius;
+ d.normal = mirrors[m].m * liveMove_.delta;
+ d.strength = liveMove_.scale;
+ d.areaCenter = d.center;
+ d.mirror = m;
+ g.dabs.push_back(d);
+ }
+ renderer_.setGhost(id, g);
+ return;
+ }
static const bool noGhost = [] { // SF_GHOST=0: the solver thread without the preview (for comparison)
const char* v = std::getenv("SF_GHOST");
return v && *v == '0';
}();
- if (!asyncStroke_ || !solver_ || !predictiveStrokes() || noGhost) {
+ if (!asyncStroke_ || !solver_ || !previewStrokes() || noGhost) {
renderer_.setGhost(id, GhostStroke());
return;
}
diff --git a/src/render/GL.cpp b/src/render/GL.cpp
index 98bf666e..6d1ae4a6 100644
--- a/src/render/GL.cpp
+++ b/src/render/GL.cpp
@@ -6,6 +6,7 @@ namespace gl {
#define SF_GL_DEFINE(ret, name, ...) PFN_##name name = nullptr;
SF_GL_FUNCTIONS(SF_GL_DEFINE)
+SF_GL_OPTIONAL(SF_GL_DEFINE)
#undef SF_GL_DEFINE
const char* load(ProcLoader loader) {
@@ -14,6 +15,9 @@ const char* load(ProcLoader loader) {
if (!name) return "gl" #name;
SF_GL_FUNCTIONS(SF_GL_LOAD)
#undef SF_GL_LOAD
+#define SF_GL_LOAD_OPTIONAL(ret, name, ...) name = reinterpret_cast<PFN_##name>(loader("gl" #name));
+ SF_GL_OPTIONAL(SF_GL_LOAD_OPTIONAL)
+#undef SF_GL_LOAD_OPTIONAL
return nullptr;
}
diff --git a/src/render/GL.h b/src/render/GL.h
index 67218d11..3370ba96 100644
--- a/src/render/GL.h
+++ b/src/render/GL.h
@@ -25,6 +25,8 @@ using GLchar = char;
using GLubyte = unsigned char;
using GLsizeiptr = std::ptrdiff_t;
using GLintptr = std::ptrdiff_t;
+using GLuint64 = uint64_t;
+using GLsync = struct __GLsync*;
constexpr GLenum GL_FALSE = 0;
constexpr GLenum GL_TRUE = 1;
@@ -193,14 +195,31 @@ constexpr GLbitfield GL_COLOR_BUFFER_BIT = 0x4000;
X(void, DrawElementsBaseVertex, GLenum, GLsizei, GLenum, const void*, GLint) \
X(void*, MapBufferRange, GLenum, GLintptr, GLsizeiptr, GLbitfield) \
X(GLboolean, UnmapBuffer, GLenum) \
+ X(void, CopyBufferSubData, GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) \
+ X(GLsync, FenceSync, GLenum, GLbitfield) \
+ X(GLenum, ClientWaitSync, GLsync, GLbitfield, GLuint64) \
+ X(void, DeleteSync, GLsync) \
X(void, MultiDrawElementsBaseVertex, GLenum, const GLsizei*, GLenum, const void* const*, GLsizei, const GLint*)
+// Optional (GL 4.4 / GL_ARB_buffer_storage; macOS stops at 4.1): null when missing.
+#define SF_GL_OPTIONAL(X) X(void, BufferStorage, GLenum, GLsizeiptr, const void*, GLbitfield)
+
+constexpr GLenum GL_COPY_READ_BUFFER = 0x8F36;
+constexpr GLenum GL_COPY_WRITE_BUFFER = 0x8F37;
+constexpr GLenum GL_SYNC_GPU_COMMANDS_COMPLETE = 0x9117;
+constexpr GLbitfield GL_SYNC_FLUSH_COMMANDS_BIT = 0x00000001;
+constexpr GLenum GL_TIMEOUT_EXPIRED = 0x911B;
+constexpr GLenum GL_WAIT_FAILED = 0x911D;
+constexpr GLbitfield GL_MAP_PERSISTENT_BIT = 0x0040;
+constexpr GLbitfield GL_MAP_COHERENT_BIT = 0x0080;
+
namespace gl {
#define SF_GL_DECLARE(ret, name, ...) \
using PFN_##name = ret(SF_GLAPI*)(__VA_ARGS__); \
extern PFN_##name name;
SF_GL_FUNCTIONS(SF_GL_DECLARE)
+SF_GL_OPTIONAL(SF_GL_DECLARE)
#undef SF_GL_DECLARE
using GenericProc = void (*)();
diff --git a/src/render/Ghost.cpp b/src/render/Ghost.cpp
index d7d945bc..2835d79f 100644
--- a/src/render/Ghost.cpp
+++ b/src/render/Ghost.cpp
@@ -37,6 +37,14 @@ glm::vec3 onPlane(const glm::vec3& v, const glm::vec3& n) { return v - n * glm::
// Keep in step with kMeshVS's ghostMove (Renderer.cpp) and the kernels in Sculptor::dabSingle.
glm::vec3 ghostMove(const GhostStroke& g, glm::vec3 x, const glm::vec3& n) {
const float sign = g.invert ? -1.0f : 1.0f;
+ if (g.kind == GhostKind::Move) { // Sculptor::grab: every mirror's weight from the grab's start position
+ const glm::vec3 start = x;
+ for (const GhostDab& d : g.dabs) {
+ const float dist = glm::length(start - d.center);
+ if (dist < d.radius) x += d.normal * (ghostFalloff(dist, d.radius, g.focal) * d.strength);
+ }
+ return x;
+ }
for (const GhostDab& d : g.dabs) {
const glm::vec3 o = x - d.center;
const float dist = glm::length(o);
@@ -77,6 +85,7 @@ glm::vec3 ghostMove(const GhostStroke& g, glm::vec3 x, const glm::vec3& n) {
if (sign * h > 0.0f) x -= an * (h * std::min(1.0f, std::sqrt(f) * (0.5f + s)));
break;
}
+ case GhostKind::Move: break; // (below: measured from the start position, not the moved one)
case GhostKind::None: break;
}
}
diff --git a/src/render/Ghost.h b/src/render/Ghost.h
index c48a37d8..b19f38b7 100644
--- a/src/render/Ghost.h
+++ b/src/render/Ghost.h
@@ -26,7 +26,11 @@ namespace sf {
// The brush kernels the preview can draw (the rest show no ghost: Smooth, Layer, Nudge, Move, Snake Hook,
// VDM, recipes, masking, painting).
-enum class GhostKind : int32_t { None = 0, Standard, Inflate, Clay, ClayBuildup, Flatten, Crease, Pinch, DamStandard, Trim };
+enum class GhostKind : int32_t { None = 0, Standard, Inflate, Clay, ClayBuildup, Flatten, Crease, Pinch, DamStandard, Trim,
+ // Live Move (SF_LIVE_MOVE=1, app/App.cpp): the Move brush's whole drag. Each dab is one mirror's grab: `normal`
+ // holds its world move, `strength` the grab's weight scale (Sculptor::beginGrab), and the falloff is measured
+ // from the position the GPU holds (the grab's start), as the grab's weights are.
+ Move };
struct GhostDab {
glm::vec3 center{0.0f}; // surface point (estimated)
diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cpp
index 7a82b00c..46c59dda 100644
--- a/src/render/Renderer.cpp
+++ b/src/render/Renderer.cpp
@@ -75,6 +75,7 @@ uniform ivec2 uGhostRange[8]; // [first, end) of each run
uniform ivec2 uGhostKind; // kernel (sf::GhostKind), inverted
uniform float uGhostFocal;
uniform float uGhostEdge; // the mesh's edge length under the brush (the cavity term's scale)
+vec3 ghostStart; // the vertex as uploaded (Live Move measures its falloff there)
// The falloff and its first two derivatives in the distance (brushFalloff with Focal Shift).
vec3 ghostFalloff(float d, float r) {
float u = clamp(1.0 - d / r, 0.0, 1.0);
@@ -96,7 +97,7 @@ vec3 ghostMove(vec3 x, vec3 n, int first, int end, inout vec3 g, inout float lap
for (int i = first; i < end; ++i) {
vec3 c = uGhostA[i].xyz;
float r = uGhostA[i].w;
- float dist = length(x - c);
+ float dist = length((kind == 10 ? ghostStart : x) - c);
if (dist >= r) continue;
float w = uGhostC[i].w;
vec3 F = ghostFalloff(dist, r) * w; // f, f', f'' in the distance
@@ -148,6 +149,10 @@ vec3 ghostMove(vec3 x, vec3 n, int first, int end, inout vec3 g, inout float lap
x += an * (a * f3 * f) + onPlane(c - x, an) * (0.3 * s * f);
g += radial * (cn * a * 4.0 * f3 * F.y);
lap += cn * a * (12.0 * f * f * F.y * F.y + 4.0 * f3 * F.z + 4.0 * f3 * F.y * inv);
+ } else if (kind == 10) { // Live Move: x0 + d w(x0) (dist from x0), normals by the inverse transpose
+ vec3 gw = (ghostStart - c) * (s * F.y * inv);
+ x += an * (s * f);
+ g += gw * (cn / max(1.0 + dot(gw, an), 1e-3));
} else if (kind == 9) { // Trim: what sticks out above a plane cut off
float h = dot(x - (ac - an * (sgn * r * 0.02 * s)), an);
if (sgn * h > 0.0) {
@@ -171,8 +176,9 @@ void main() {
#ifdef GHOST
// The moved position, normal and cavity term (one evaluation per vertex, no extra varyings: a tiled GPU
// writes every vertex's outputs to memory and reads them back).
+ ghostStart = world;
for (int k = 0; k < uGhostGroups; ++k) {
- if (distance(world, uGhostBound[k].xyz) >= uGhostBound[k].w) continue;
+ if (distance(uGhostKind.x == 10 ? ghostStart : world, uGhostBound[k].xyz) >= uGhostBound[k].w) continue;
vec3 g = vec3(0.0);
float lap = 0.0;
world = ghostMove(world, normal, uGhostRange[k].x, uGhostRange[k].y, g, lap);
@@ -1085,6 +1091,11 @@ size_t Renderer::gpuBytes() const {
void Renderer::shutdown() {
for (auto& s : slots_) freeSlot(s);
+ for (Staging& st : persist_) {
+ if (st.fence) gl::DeleteSync(st.fence);
+ if (st.buffer) gl::DeleteBuffers(1, &st.buffer); // (unmaps it)
+ st = Staging();
+ }
slots_.clear();
drawList_.clear();
if (!matcapTextures_.empty()) gl::DeleteTextures(GLsizei(matcapTextures_.size()), matcapTextures_.data());
@@ -3115,6 +3126,8 @@ bool Renderer::prepareStrokeUpload(uint32_t id, Mesh& mesh, StrokeUpload& out, c
out.id = id;
out.ready = false;
out.data.clear();
+ out.packed = 0;
+ out.staged = false;
out.ranges.clear();
out.movedClusters.clear();
out.bounds.clear();
@@ -3162,7 +3175,9 @@ bool Renderer::prepareStrokeUpload(uint32_t id, Mesh& mesh, StrokeUpload& out, c
pieces.push_back({c, ce, total});
total += ce - c;
}
- out.data.resize(total);
+ out.staged = out.stagingPtr && total <= out.stagingCap;
+ out.packed = total;
+ out.data.resize(out.staged ? 0 : total);
};
cut();
std::atomic<bool> outside{false};
@@ -3175,7 +3190,7 @@ bool Renderer::prepareStrokeUpload(uint32_t id, Mesh& mesh, StrokeUpload& out, c
poolFor(pieces.size(), [&](size_t i0, size_t i1) {
for (size_t pi = i0; pi < i1; ++pi) {
const Piece& pc = pieces[pi];
- PackedVertex* dst = out.data.data() + pc.offset;
+ PackedVertex* dst = out.dst() + pc.offset;
bool inside = true;
uint64_t hp = 0, hn = 0;
AABB box;
@@ -3279,7 +3294,18 @@ void Renderer::commitStrokeUpload(StrokeUpload& up) {
if (!found) return;
MeshSlot& s = *found;
if (up.regrid) s.grid = up.grid; // (with every vertex, packed on it)
- if (!up.ranges.empty()) {
+ if (!up.ranges.empty() && up.staged && up.stagingIndex >= 0) { // (packed into a staging buffer: the GPU copies)
+ Staging& st = persist_[up.stagingIndex];
+ gl::BindBuffer(GL_COPY_READ_BUFFER, st.buffer);
+ gl::BindBuffer(GL_COPY_WRITE_BUFFER, s.vertexBuffer);
+ for (const StrokeUpload::Range& r : up.ranges)
+ gl::CopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GLintptr(r.offset * sizeof(PackedVertex)),
+ GLintptr(size_t(r.begin) * sizeof(PackedVertex)),
+ GLsizeiptr(size_t(r.end - r.begin) * sizeof(PackedVertex)));
+ gl::BindBuffer(GL_COPY_READ_BUFFER, 0);
+ gl::BindBuffer(GL_COPY_WRITE_BUFFER, 0);
+ st.fence = gl::FenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); // (bindStrokeUpload waits before it's reused)
+ } else if (!up.ranges.empty()) {
gl::BindBuffer(GL_ARRAY_BUFFER, s.vertexBuffer);
for (const StrokeUpload::Range& r : up.ranges)
gl::BufferSubData(GL_ARRAY_BUFFER, GLintptr(size_t(r.begin) * sizeof(PackedVertex)),
@@ -3319,10 +3345,47 @@ void Renderer::commitStrokeUpload(StrokeUpload& up) {
void Renderer::setDraftNormals(uint32_t id) { draftId_ = id; }
+bool Renderer::persistentUpload() {
+ static const bool on = [] {
+ const char* v = std::getenv("SF_PERSISTENT_UPLOAD");
+ return v && *v == '1' && gl::BufferStorage != nullptr;
+ }();
+ return on;
+}
+
void Renderer::bindStrokeUpload(uint32_t id, StrokeUpload& up) {
up.slot = nullptr;
for (MeshSlot& s : slots_)
if (s.id == id) up.slot = &s;
+ up.stagingPtr = nullptr;
+ up.stagingCap = 0;
+ up.stagingIndex = -1;
+ up.staged = false;
+ if (!persistentUpload()) return;
+ // Two buffers in turn: the one lent now was last copied from two commits ago (its fence has nearly always
+ // passed). 4M vertices (48 MB) each; a bigger batch packs into `data` as before.
+ constexpr size_t kCap = size_t(4) << 20;
+ const int k = stagingNext_;
+ stagingNext_ ^= 1;
+ Staging& st = persist_[k];
+ if (st.fence) {
+ gl::ClientWaitSync(st.fence, GL_SYNC_FLUSH_COMMANDS_BIT, 1'000'000'000ull);
+ gl::DeleteSync(st.fence);
+ st.fence = nullptr;
+ }
+ if (!st.buffer) {
+ gl::GenBuffers(1, &st.buffer);
+ gl::BindBuffer(GL_COPY_READ_BUFFER, st.buffer);
+ const GLbitfield flags = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT;
+ gl::BufferStorage(GL_COPY_READ_BUFFER, GLsizeiptr(kCap * sizeof(PackedVertex)), nullptr, flags);
+ st.ptr = gl::MapBufferRange(GL_COPY_READ_BUFFER, 0, GLsizeiptr(kCap * sizeof(PackedVertex)), flags);
+ gl::BindBuffer(GL_COPY_READ_BUFFER, 0);
+ st.cap = st.ptr ? kCap : 0;
+ }
+ if (!st.ptr) return;
+ up.stagingPtr = static_cast<PackedVertex*>(st.ptr);
+ up.stagingCap = st.cap;
+ up.stagingIndex = k;
}
void Renderer::refineStrokeBoundsInto(uint32_t id, const Mesh& mesh, StrokeUpload& up) {
diff --git a/src/render/Renderer.h b/src/render/Renderer.h
index 50a1e27c..422bce0c 100644
--- a/src/render/Renderer.h
+++ b/src/render/Renderer.h
@@ -184,7 +184,16 @@ public:
bool exact = false; // refineStrokeBoundsInto: exact bounds to set
std::vector<uint32_t> exactClusters;
std::vector<ClusterBounds> exactBounds;
- size_t bytes() const { return data.size() * sizeof(PackedVertex); }
+ size_t bytes() const { return packed * sizeof(PackedVertex); }
+ size_t packed = 0; // vertices packed (in data, or the staging buffer)
+ // Persistent upload (SF_PERSISTENT_UPLOAD=1, a research prototype): bindStrokeUpload lends a persistently
+ // mapped staging buffer; prepare packs straight into it when the batch fits (`staged`), and commit has
+ // the GPU copy the ranges into the vertex buffer (no glBufferSubData of the packed data on the GL thread).
+ PackedVertex* stagingPtr = nullptr;
+ size_t stagingCap = 0; // vertices
+ int stagingIndex = -1;
+ bool staged = false;
+ PackedVertex* dst() { return staged ? stagingPtr : data.data(); }
};
// `curvature` (optional, by vertex): the cavity term of every vertex the mesh marked dirty, already worked
// out (Sculptor::strokeCurvature).
@@ -247,6 +256,14 @@ private:
GLuint viewFbo_ = 0, viewResolveFbo_ = 0, viewRb_[3] = {};
int viewW_ = 0, viewH_ = 0, viewSamples_ = 0, viewFailed_ = 0;
bool directView_ = false;
+ struct Staging { // the persistent upload's buffers (StrokeUpload::stagingPtr), used in turn
+ GLuint buffer = 0;
+ void* ptr = nullptr;
+ size_t cap = 0; // vertices
+ GLsync fence = nullptr;
+ } persist_[2];
+ int stagingNext_ = 0;
+ static bool persistentUpload();
int captureW_ = 0, captureH_ = 0;
GLuint emptyVao_ = 0;
bool thumbnailPass_ = false; // draw(): transparent background, no gradient (renderMeshThumbnail)
diff --git a/tests/test_ghost.cpp b/tests/test_ghost.cpp
index d9f6ff66..3f4dc459 100644
--- a/tests/test_ghost.cpp
+++ b/tests/test_ghost.cpp
@@ -210,3 +210,54 @@ TEST(pen_predictor_tracks_a_circle_better_than_holding_still) {
}
CHECK(predicted / n < held / n * 0.25);
}
+
+TEST(live_move_matches_the_grab) {
+ // Live Move (SF_LIVE_MOVE, research prototype): the preview of a whole Move drag (GhostKind::Move, from the
+ // grab's start positions) is where the grab puts every vertex, and one grab with the whole move lands where a
+ // grab per frame does (up to float rounding), with X symmetry.
+ Mesh sphere = makeIcosphere(6);
+ DabParams p;
+ p.center = glm::normalize(glm::vec3(0.3f, 0.2f, 1.0f));
+ p.radius = 0.45f;
+ p.strength = 0.4f;
+ p.focal = 0.3f;
+ p.viewDir = -p.center;
+ const Symmetry sym{true, false, false};
+ const std::vector<glm::vec3> steps = {{0.01f, 0.02f, 0.0f}, {0.03f, -0.01f, 0.02f}, {0.02f, 0.02f, 0.01f}};
+ glm::vec3 total(0.0f);
+ for (const glm::vec3& s : steps) total += s;
+
+ Document framed = makeDoc(sphere), once = makeDoc(sphere);
+ const std::vector<glm::vec3> before = framed.mesh.positions, normals = framed.mesh.normals;
+ framed.sculptor.beginStroke(framed.mesh, "test");
+ framed.sculptor.beginGrab(framed.mesh, framed.bvh, p, sym);
+ for (const glm::vec3& s : steps) framed.sculptor.grab(framed.mesh, framed.bvh, s);
+ framed.sculptor.endStroke();
+ once.sculptor.beginStroke(once.mesh, "test");
+ once.sculptor.beginGrab(once.mesh, once.bvh, p, sym);
+ once.sculptor.grab(once.mesh, once.bvh, total);
+ once.sculptor.endStroke();
+
+ GhostStroke g;
+ g.kind = GhostKind::Move;
+ g.focal = p.focal;
+ const std::vector<SymCopy> copies = Sculptor::copies(sym);
+ for (uint32_t m = 0; m < copies.size(); ++m) {
+ GhostDab d;
+ d.center = copies[m].point(p.center);
+ d.radius = p.radius;
+ d.normal = copies[m].m * total;
+ d.strength = std::clamp(p.strength * 2.0f, 0.0f, 1.0f);
+ d.mirror = m;
+ g.dabs.push_back(d);
+ }
+ float moved = 0.0f, single = 0.0f, ghost = 0.0f;
+ for (size_t v = 0; v < before.size(); ++v) {
+ moved = std::max(moved, glm::distance(before[v], framed.mesh.positions[v]));
+ single = std::max(single, glm::distance(once.mesh.positions[v], framed.mesh.positions[v]));
+ ghost = std::max(ghost, glm::distance(ghostMove(g, before[v], normals[v]), framed.mesh.positions[v]));
+ }
+ CHECK(moved > 0.02f);
+ CHECK(single < 1e-6f);
+ CHECK(ghost < 1e-5f);
+}