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.

Merge origin/integration/next (micromesh, hw-profile, pbr, timeline-proof, surface-cursor) into feat/zero-latency

islandmed5028c188873f
diff --cc CHANGELOG.md
index e2e90067,ff0c777d..6e12166a
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -7,40 -7,104 +7,138 @@@ All notable changes to SculptForge are
## [Unreleased]
### Added
+ - **Micro levels: hundreds of millions of sculptable polygons** (**Tool > Geometry > Micro**, `micro_*`
+ commands). Above the highest subdivision level a SubTool can carry a micro level: per triangle a regular grid of
+ 16-bit heights along the interpolated normal of the smooth (Phong-tessellated) base, instead of a mesh.
+ 300 million micro triangles take 374 MB (1.25 bytes each; the whole app about 0.8 GB), where a mesh of that size
+ would need about 27 GB. Unlike ZBrush's HD Geometry the whole model is sculptable at once.
+ - Brushes: Standard, Clay, Clay Buildup, Smooth, Inflate, Flatten, Trim, Layer, Pinch / Crease / Dam Standard
+ (as height sharpening), Mask; symmetry, Focal Shift, pressure and the mask apply. Big brushes are evaluated on
+ a coarser grid and interpolated (scale-adaptive). Move reshapes the base below the micro level and the detail
+ rides along (dual scale); "Move along normals" moves the micro surface itself.
+ - Viewport: the micro surface is evaluated on the GPU per frame, with a level of detail per cluster and a
+ triangle budget (2M on a laptop profile, 8M on a workstation, `RenderSettings::renderTriangleBudget`), crack
+ free; the shading keeps every micro detail. 300M micro triangles orbit at 70+ fps with 4x antialiasing (M1 Pro).
+ - Bake Micro (to a mesh), Export Displacement (32-bit EXR or 16-bit PNG, scalar or vector, over the base UVs).
+ - Undo: a packed journal per stroke (tiles in Morton order, each tile's change predicted and packed).
+ - Very large levels stay out of core in a sparse memory-mapped file (only what you touch is in memory).
+ - Projects: format 7 when a SubTool has a micro level (others stay format 6 for older versions).
+ - `sculptforge --bench-micro --bench-sizes 33,100,300` measures it. Guide chapter "Micro levels".
+ - Automatic hardware detection and calibration. On first launch, and again when the graphics card, its driver or
+ the version changes, SculptForge spends about a second or two (under a small overlay; Esc skips) measuring
+ triangle throughput, upload bandwidth, brush speed and memory bandwidth, and probes the GPU (OpenGL strings,
+ video memory through GL_NVX_gpu_memory_info, GL_ATI_meminfo, GLX_MESA_query_renderer, amdgpu sysfs, DXGI or
+ CGL), RAM, threads, SIMD and OS. The result picks a profile: **Laptop / Budget**, **Workstation** (64 GB+ RAM
+ with a 16 GB+ discrete GPU, or Apple Silicon Max / Ultra and big APUs, that measure fast) or a **Software** safe
+ mode for llvmpipe, with a render triangle budget, motion proxy
+ threshold, GPU memory and upload budgets, texture, subdivision and micro-triangle limits and the thread count.
+ Cached in the settings folder; no network use. A one-line status bar message says what was found.
+ - Preferences > Performance shows what was detected and measured ("Detected <GPU>, <memory> -> Workstation"),
+ the settings in effect, **Re-calibrate** and manual overrides (kept across re-calibrations).
+ - An adaptive frame governor holds the view at 60 fps (120 / 144 on a fast display) while it moves, by switching
+ big scenes to their motion proxy sooner or later, with hysteresis; it changes only what is drawn, never the
+ model. Fast Navigation's 10 million triangle threshold now comes from the profile.
+ - On battery (laptops), brushes switch to draft mode, uploads per frame halve and the target is 60 Hz.
+ - `sculptforge --calibrate` prints the profile as JSON (schema sculptforge.calibration/1); commands
+ `performance_profile`, `calibrate` and `set_performance_override` for the console, scripts and MCP.
+ - For developers: `core/TierConfig.h` (resident cache cap, active-triangle budget, upload budget, draft brush
+ mode, zero-copy UMA, target Hz) and `renderTriangleBudget()` for the renderer and micro-displacement
+ (docs/performance.md, "Hardware profile").
+ - Material painting (PBR): a painted texture can carry Roughness, Metallic, Normal, Height (16-bit), Ambient
+ Occlusion, Emissive and Opacity besides its colour, all painted in the same strokes. Turn channels on in
+ **Tool > Texture Map > Material Channels** (`texture_channels`); a channel costs no memory until it is painted
+ (64x64 copy-on-write tiles; untouched tiles aren't stored). **Color > Material** sets what the brush lays on
+ each channel (material swatches, per-channel value swatches and sliders; `paint_material`), and **C** picks the
+ whole material under the cursor. Paint layers hold every channel: channel chips on each layer row turn a
+ channel on or off for that layer, and give it its own blend mode and opacity, including **Normal Combine** for
+ normals (`texture_layer_channel`). Height also yields a normal combined onto the Normal channel. One undo step
+ per stroke, kept per layer and channel. Auto UV, Voxel Remesh, QRemesh and merging SubTools carry every channel.
+ See the guide's Material painting page.
+ - Solo channel view: **Tool > Texture Map** shows one channel on the model (roughness and the other scalars in
+ grey, the normal as colours, emission in colour), live while painting (`channel_view`).
+ - Export Maps with presets (`export_maps`): Unreal (`T_*_BC`, `T_*_N` in DirectX, `T_*_ORM`), Unity URP and HDRP
+ (mask map), glTF, Godot, Blender (one file per channel) and USD, plus your own JSON presets (the guide's Export
+ presets page). Height maps are 16-bit PNG.
+ - Model exports wire the channels into their materials: glTF metal-rough slots (packed occlusion / roughness /
+ metallic, normal, emissive, alpha from opacity), UsdPreviewSurface inputs, the MTL PBR keys and FBX material
+ maps. Send to Unreal imports `T_<Name>_BC / _N / _ORM` and builds an `M_<Name>` material from them.
+ - Preferences > Performance and `perf_info` show the memory of textures and their material channels.
+
+ ### Changed
+ - Texture painting on dense meshes costs the texels a dab reaches instead of the triangles under it: the brush
+ finds the texture tiles under it from the BVH and paints each texel from a cached triangle-and-barycentrics
+ map, tiles in parallel. A 0.35-radius dab with X symmetry on a 21M-triangle sphere: 4K 150-360 ms -> 24-39 ms,
+ 8K 240-350 ms -> 39-55 ms (M1 Pro, ranges over a busy and a quiet machine); results match the old dab within
+ 1/255. Lighter meshes keep the per-triangle dab. No first-dab stutter: the UV bins are shared by every texture on
+ the same UVs (undo steps, copies) and built in parallel when painting starts (about 45 ms at 21M), the area under
+ the hovering brush is readied before it lands, and a stroke into a fresh area stays under 20 ms at 4K.
+ Preferences > Performance counts these caches.
+ - Project format 7 stores material channels. It is written only when a texture has them: other projects are
+ still saved as format 6, and every older project opens as before.
+ - **Sculpt Timeline**: every stroke and operation is a tick on a strip along the bottom of the canvas. Drag the
+ scrubber to see the model at any point of the session, click a step to go there. Sculpting from an earlier
+ point no longer throws the later steps away: they stay as a branch (a lane above the track) you can switch
+ back to, with undo / redo working on the active branch as before. Right-click a stroke to re-tune its strength
+ (0 removes it, 2 doubles it) without redoing the strokes after it; where later strokes overlap it they keep
+ their own displacement on top (they aren't sculpted again; see the guide's Sculpt Timeline chapter). Seeking
+ reuses undo's per-stroke deltas, swaps runs of strokes at once with one normal / BVH / GPU update, and jumps
+ from full checkpoints every 16 steps (within 1 GB; fewer on huge meshes) for long seeks. Each SubTool keeps
+ its own timeline. Commands `timeline_info`, `timeline_seek`, `timeline_select`, `timeline_retune`,
+ `timeline_save`, `timeline_load`; UI test timeline.
+ - **Save with project** (in the timeline's header) also writes the history beside the project as
+ `<name>.sfhist` (strokes, masks, polypaint, visibility, polygroups, branches, re-tuned strengths; a topology
+ change cuts it). Opening the project brings it back when the mesh matches. The project format is unchanged.
+ - **Export timelapse**: the history rendered as a turntable video, the model building up stroke by stroke while
+ the camera goes once around it (1080p or 4K MP4, no captions; needs ffmpeg). Also
+ `sculptforge project.sfproj --timelapse out.mp4 [--size 3840x2160] [--timelapse-seconds 20]`.
+ - **Proof mode** (**Help > Benchmark**, `sculptforge --benchmark`): a scripted 240 Hz pen stroke through the
+ same input handlers a real pen uses, with a 60 px and a 240 px brush and a turn of the view, on 5, 20 and 33
+ million triangle meshes (100 million when free memory allows). A live HUD shows fps, frame time p50 / p95 /
+ p99, how far the stroke trails the pointer (ms and px) and memory; the run is recorded to an MP4 with the HUD in
+ it and written as a JSON result with the processor, graphics card, memory, OS, version and commit.
+ `docs/benchmark.md` describes the format, `tools/benchmark/submit.py` checks results and adds them to
+ `website/benchmarks/results.json`, which the new benchmarks page lists.
+ - The brush cursor follows the surface (#25), as in SculptGL: over the model the Draw Size and Focal Shift rings
+ lie on the surface under the pointer, turned to its (smoothed) direction and pressed onto its shape, at the
+ brush's real size there, with a short normal line; with symmetry on, a fainter mirrored ring shows too. Every
+ brush (sculpt, paint, mask, dynamic topology). A few dozen BVH ray casts per drawn frame, no pass over the mesh
+ (0.09 ms on 5M triangles), and the idle view still draws nothing. **Preferences > Input > Cursor follows
+ surface** (on by default) brings back the flat screen rings.
+
+- **Predictive Strokes** (Preferences > Performance, on by default): a sculpt stroke's brush is worked out on its
+ own thread while the view keeps drawing at the display's rate. The dabs not finished yet are drawn as a GPU
+ preview on the surface (each brush's kernel in the vertex shader, with its shading and cavities), and the brush
+ cursor and the stroke's head are drawn where the pen will be a frame later. When a dab's result reaches the GPU
+ it replaces its preview in the same frame. Lifting the pen never waits. The finished sculpt is the same, bit for
+ bit, as with it off (`--measure-stroke` with `SF_MEASURE_VERIFY=1` replays the stroke and checks undo).
+ Painting, masking, dynamic topology, Move, Snake Hook and the drag strokes work as before.
+- **Draft Strokes** (Preferences > Performance, off by default; meant for laptops and battery): with Predictive
+ Strokes, the brush only moves the surface during the stroke; normals, cavities and culling bounds are worked out
+ once when the pen lifts.
+- `tools/bench_strokes.sh`: the big-brush stroke benchmark on 5M, 21M and 33M triangles, one build or two
+ interleaved (docs/performance.md). `new_sphere triangles=N` makes a sphere of about N triangles.
+ `--measure-stroke` reports frame p95 / p99, the preview's lag, and when the first and last dab reach the screen.
+
- ### Changed
++### Changed (predictive strokes)
+- Big brushes on dense meshes no longer slow the view. `tools/bench_strokes.sh`, 200 px brush, M1 Pro shared
+ with other builds (load 9-45, so both columns are slower than on an idle machine; A/B interleaved):
+
+ | | 0.9.7 frame mean / p99 | Now | Brush on screen behind the pointer, 0.9.7 / now | Press | Release |
+ |---|---|---|---|---|---|
+ | 5.2M | 47 / 134 ms | 8.4 / 14 ms | 95 / 1 px | 98 -> 24 ms | 31 -> 0 ms |
+ | 21M | 71 / 651 ms | 8.8 / 18 ms | 37 / 1.5 px | 623 -> 14 ms | 1 -> 0 ms |
+ | 33.6M | 169 / 323 ms | 12.2 / 27 ms | 245 / 4 px | 315 -> 13 ms | 374 -> 0 ms |
+
+ With 60 and 240 px brushes at 21M and 33.6M the p99 frame is 11-31 ms (0.9.7: 26-636 ms). The solved surface
+ itself still trails as before; the preview covers it (docs/performance.md, "Predictive strokes").
+- Packing a stroke's vertices for the GPU no longer walks every vertex's neighbours again: the cavity term comes
+ from the normals pass. Clusters a stroke moved get quick culling bounds, made exact when it ends.
+- `Mesh::recomputeAllNormals` (new meshes, undo of big changes, timeline seeks) runs in parallel.
+
- ### Fixed
++### Fixed (predictive strokes)
+- A big brush that raised the surface past the GPU's position grid stalled the view for seconds on dense meshes
+ (the whole mesh was re-packed inside a frame); it is re-packed on the brush thread now.
+
## [0.9.7] - 2026-10-31
Speed first: big brushes on dense meshes take a third less time per frame, trail the pen by half as far and no
diff --cc CMakeLists.txt
index fa602e94,d64cd5cd..ae41bccb
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@@ -205,9 -219,10 +219,11 @@@ if(SCULPTFORGE_BUILD_APP
${CMAKE_CURRENT_BINARY_DIR}/EmbeddedGuide.cpp
src/app/main.cpp
src/app/Bench.cpp
+ src/app/Calibration.cpp
+ src/app/PanelPerformanceProfile.cpp
src/app/CrashLog.cpp
src/app/App.cpp
+ src/app/AsyncStroke.cpp
src/app/Demo.cpp
src/app/UiTest.cpp
src/app/Actions.cpp
@@@ -257,8 -275,8 +276,9 @@@
src/render/GL.cpp
src/render/Camera.cpp
src/render/Clusters.cpp
+ src/render/Ghost.cpp
src/render/Renderer.cpp
+ src/render/MicroRenderer.cpp
)
target_link_libraries(sculptforge PRIVATE sculptforge_core sculptforge_ai sculptforge_phone imgui SDL3::SDL3)
target_include_directories(sculptforge PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/lucide)
diff --cc docs/guide/performance.md
index ab42e0bd,df7cc9bc..25d1b4db
--- a/docs/guide/performance.md
+++ b/docs/guide/performance.md
@@@ -37,9 -37,7 +37,9 @@@ Open **Preferences** and click **Perfor
| Control | What it does |
|---|---|
| **Antialiasing** (Off, 2x, 4x, 8x) | How many samples per pixel the 3D view uses to smooth edges. 4x is the default. More samples look smoother and cost more on huge meshes. If the graphics card can't make room for them, the view quietly uses fewer and the panel says so |
- | **Fast Navigation** | While you rotate, pan or zoom a scene of 10 million triangles or more, draw it without antialiasing and draw big meshes as a lighter version with about a fifth of their triangles, so the view keeps up. The full mesh, smooth again, is back as soon as the view stops. On by default |
+ | **Fast Navigation** | While you rotate, pan or zoom a scene bigger than the hardware profile's motion proxy threshold (see below), draw it without antialiasing and draw big meshes as a lighter version with about a fifth of their triangles, so the view keeps up. The full mesh, smooth again, is back as soon as the view stops. On by default |
+| **Predictive Strokes** | The brush is worked out on its own thread while the view keeps drawing at full speed. The dabs it hasn't finished show at once as a preview on the surface, and the brush cursor and the stroke's head are drawn where the pen is about to be, so on a heavy mesh the surface moves under the pen straight away and lifting the pen never waits. The finished sculpt is exactly the same as with it off. On by default (painting, masking, dynamic topology, Move, Snake Hook and the drag strokes work as before) |
+| **Draft Strokes** | With Predictive Strokes: while you sculpt, the brush only moves the surface, the moved part is shaded from its facets, and the smooth shading, the cavities and the rest are worked out once when you lift the pen. Lighter on laptops and on battery. Inflate and the plane brushes use the surface's direction from the stroke's start, so the result can differ slightly from a full stroke. Off by default |
| **Multithreading** | Run brushes, normal and picking updates and project saving on every core (the number of threads is shown beside it). The results are exactly the same with it off; turn it off only to compare speeds or rule it out when something goes wrong |
| **Last stroke** | What your last stroke cost per dab: **Brush** (finding and moving the vertices), **Normals** (shading), **BVH** (the structure that finds the surface under the cursor), and the **GPU upload** per frame |
| **Memory** | What the scene holds: the meshes, the BVHs, the subdivision levels kept for stepping between them, the undo history (up to 1 GB; the oldest steps are dropped beyond that) and, roughly, the graphics card's buffers |
diff --cc docs/performance.md
index 32bca515,ec4e4100..3d2d1a93
--- a/docs/performance.md
+++ b/docs/performance.md
@@@ -12,144 -12,210 +12,347 @@@ sculptforge-cli --bench ..
Machine for all figures: Apple M1 Pro (8 performance + 2 efficiency cores, 32 GB unified memory, 30 GB usable
under Asahi Linux), integrated GPU, Mesa 26.1 (OpenGL 4.6). How the benchmark works is described under v0.5 below.
+## Next version: predictive strokes (feat/zero-latency)
+
+A stroke on a heavy mesh used to run in the frame loop: each frame placed a dab (45-50 ms at 21M with a 200 px
+brush), re-packed what it moved for the GPU (about 28 ms) and only then drew. Now the brush runs on its own
+thread and the frame loop only commits what it finished, so the view draws at the display's rate whatever a dab
+costs; what the brush hasn't finished is drawn ahead of it by the GPU.
+
+```
+tools/bench_strokes.sh [-s 5,21,33] [-n RUNS] [-r RADIUS_PX] BINARY [BINARY_B] # A/B runs interleaved
+```
+
+It runs `sculptforge --run SCENE --measure-stroke 3,R` (a fast two-turn circle, X symmetry) on 5.2M
+(`new_sphere subdivisions=8; subdiv_divide`), 21.0M (two Divides) and 33.6M triangles
+(`new_sphere triangles=2100000; subdiv_divide; subdiv_divide`) and averages SculptForge's own figures.
+
+**How to read the figures below.** They were taken on the M1 Pro while other agents were building and testing on
+the same machine (load average 9 to 45 on 10 cores during the runs), so absolute times are two to four times
+those of an idle machine and vary from run to run (0.9.7 measured 65 ms frames at 21M on an idle machine; here
+71-180 ms). A and B were interleaved run by run, two runs each, so they saw the same load. "A" is main (0.9.7)
+with only the measurement additions, "B" this branch with Predictive Strokes on (the default).
+
+- Frame: the interval between frames on screen, mean / p95 / p99 (120 Hz display, vsync).
+- Surface lag: how far round the circle the last dab whose result is on the GPU is behind the pointer.
+- Preview lag: the same for the preview's head (B; for A it is the surface).
+- Press: from the press to the first frame on screen that shows it (B: the preview of the first dab); first
+ surface: until the first dab's own result is on screen.
+- Release: how long letting go holds up the UI; until done: until the last dab's result is on screen.
+
+200 px brush:
+
+| Mesh | | Frame mean / p95 / p99 | Surface lag | Preview lag | Press | First surface | Release | Until done |
+|---|---|---:|---:|---:|---:|---:|---:|---:|
+| 5.2M | A | 47.0 / 98.5 / 134 ms | 95 px | 95 px | 98 ms | 98 ms | 31 ms | 44 ms |
+| | B | **8.4 / 11.3 / 14.3 ms** | 72 px | **1.0 px** | **24 ms** | 68 ms | **0 ms** | 64 ms |
+| 21.0M | A | 71.0 / 245 / 651 ms | 37 px | 37 px | 623 ms | 623 ms | 1.4 ms | 8 ms |
+| | B | **8.8 / 14.1 / 17.6 ms** | 198 px | **1.5 px** | **14 ms** | 144 ms | **0 ms** | 224 ms |
+| 33.6M | A | 169 / 311 / 323 ms | 245 px | 245 px | 315 ms | 315 ms | 374 ms | 493 ms |
+| | B | **12.2 / 22.8 / 27.0 ms** | 307 px | **4.1 px** | **13 ms** | 264 ms | **0 ms** | 500 ms |
+
+60 and 240 px brushes (the sizes proof mode reported stalls with):
+
+| Mesh, brush | | Frame mean / p95 / p99 | Surface lag | Preview lag | Press | Release | Until done |
+|---|---|---:|---:|---:|---:|---:|---:|
+| 21.0M, 60 px | A | 14.8 / 22.1 / 26.2 ms | 16 px | 16 px | 26 ms | 5 ms | 10 ms |
+| | B | **8.4 / 9.9 / 11.4 ms** | 31 px | **0.7 px** | **8 ms** | 0 ms | 33 ms |
+| 33.6M, 60 px | A | 24.9 / 31.6 / 34.8 ms | 48 px | 48 px | 34 ms | 31 ms | 42 ms |
+| | B | **8.9 / 14.3 / 17.2 ms** | 63 px | **1.9 px** | **13 ms** | 0 ms | 82 ms |
+| 21.0M, 240 px | A | 215 / 433 / 433 ms | 283 px | 283 px | 582 ms | 544 ms | 675 ms |
+| | B | **10.2 / 18.5 / 23.8 ms** | 465 px | **3.1 px** | **21 ms** | 0 ms | 1132 ms |
+| 33.6M, 240 px | A | 292 / 636 / 636 ms | 226 px | 226 px | 779 ms | 826 ms | 1362 ms |
+| | B | **12.8 / 27.2 / 31.1 ms** | 337 px | 117 px* | **11 ms** | 0 ms | 1689 ms |
+
+\* One of the two runs had a preview lag of 230 px, the other 4 px; repeated runs with the head logged gave
+4 px and couldn't reproduce it (a tiling window manager resizing the window mid-stroke, which other agents'
+windows did during these runs, also moves the canvas under the scripted circle).
+
+What the figures say:
+
+- **Frames no longer depend on the brush.** B's frames are 8-13 ms on average at every size, p99 11-31 ms,
+ where A's worst frames were 0.3 to 1.2 s (the solver and the upload ran inside the frame). The long stalls proof
+ mode saw are gone: the biggest was a vertex leaving the GPU's position grid (a big brush raising the surface),
+ which re-packed the whole mesh inside a frame (seconds at 33M); it is re-packed on the brush thread now, and
+ the stroke's end work (exact culling bounds of everything it moved) runs there too, so release is 0 ms.
+- **The brush trails the pointer by a few pixels on screen**, where it trailed by 40-280 px: the preview shows
+ every dab not yet solved, and the pen's next position. The surface itself (the solver's result) still trails
+ by as much as before, or more on a loaded machine (B batches dabs so that packing stays under half the work,
+ so the real surface updates less often); when it lands it replaces the preview without a visible jump: with
+ `SF_MEASURE_POP=1` the view changes by 0.055 (mean, 0-255) when a batch replaces its preview, against 0.36 if
+ there were no preview (5M, 200 px).
+- **Press** is the first frame (8-24 ms, the preview of the first dab); the first dab's own result follows when
+ the solver has it.
+- **Until done** is longer for B with big brushes: B places every queued dab after the pen lifts (the preview
+ already shows them) and A's frame loop thinned more. It doesn't hold anything up: the UI keeps going, and a new
+ stroke or command first finishes the old one.
+- The targets set for this work were 33M with a 200 px brush at 60 fps (frames under 16.7 ms), the brush under
+ 20 px behind the pointer, press and release under 50 ms. Met on this loaded machine: press (13 ms), release
+ (0 ms), the brush on screen behind the pointer (4 px), the mean frame at 21M (8.8 ms). Not met: 33M frames are
+ 12.2 ms mean but 22.8 / 27.0 ms at p95 / p99. Those frames wait on the GPU (`SF_FRAME_LOG=16`: the time is
+ in the swap, drawing 33M triangles; the preview costs about 1-2 ms of it), not on the CPU.
+
+### Where a batch's time goes (21M, 200 px, `SF_STROKE_LOG=1`, loaded)
+
+The solver thread: the dab 160-300 ms (kernel 50-115, normals 65-150, BVH 25-50), then packing the upload
+110-180 ms before this work, 25-45 ms after it (vertices 25-40, bounds under 1.5). On an idle machine divide by
+about four. The main thread's commit (glBufferSubData of 30-55 MB): 2-3 ms, occasionally 10.
+
+What changed, in order:
+
+1. **Predictive strokes** (app/AsyncStroke.cpp). The queued dabs go to a solver thread in batches; each frame
+ the finished batch is committed and the next one starts. The mesh, its BVH and the sculptor belong to the
+ solver while it runs (syncScene and the pollers wait; every path that edits the document ends the stroke
+ first). The dabs, their order and parameters are the frame loop's (each batch sees the view as it was when it
+ began), so the result is the same bit for bit: `SF_MEASURE_VERIFY=1` replays the measured stroke without the
+ thread and checks undo.
+2. **The preview** (render/Ghost.h, the GHOST shader variant). The dabs not yet on the GPU (in flight, queued, and
+ the stroke's head where the pen will be a frame later, core/PenPredictor.h) move the uploaded vertices as each
+ brush kernel would; the kernels are differentiated forward (height gradient and Laplacian over the tangent
+ plane) for the bent normal and the cavity term, with no extra varyings (a tiled GPU writes every vertex's
+ outputs to memory). Each dab's surface point comes from a sphere fitted to the last two placed dabs (their
+ normals turn by an angle over the distance between them): centre within 0.003-0.07 r, normal within 1-5
+ degrees (measured with a debug log since removed). Only the clusters a ghost dab reaches use it. The brush cursor is drawn at the
+ predicted pen position too.
+3. **Two-part upload** (Renderer::prepareStrokeUpload / commitStrokeUpload). The solver thread packs the dirty
+ vertices and the culling bounds; the GL thread only calls glBufferSubData. The cavity term comes from the
+ normals pass (Mesh::curvatureAt from each vertex's triangles, the ring average on a manifold) instead of a
+ second walk of every vertex's ring (packing 110 -> 30 ms a batch at 21M, loaded). Clusters a stroke moved get
+ bounds round their vertices' boxes (found while packing) without a normal cone; exact ones at the end.
+4. **No stalls**: the position grid re-pack and the end-of-stroke bounds on the solver thread (above); batches
+ sized so packing stays under half the work, and after release every dab left in one batch with the end
+ work (21M, 240 px: until done 2.9 -> 0.6 s).
+5. **Mesh::recomputeAllNormals** sums each vertex's own triangles in parallel when the topology is known (same
+ order, same bits, no face array): it summed on one thread, which dominated full-history timeline seeks.
+
+Not done: persistent-mapped upload buffers (the commit is 2-3 ms, not worth the complexity on GL 3.3 / macOS
+4.1); per-vertex dirty bitsets per cluster beyond what UploadOrder already does; normals in the shader (they
+are already 2 x 11-bit octahedral in 12-byte vertices since v0.6). The CPU dab itself (kernel, normals, BVH) is
+unchanged: it bounds how soon the real surface catches up, not the frame rate.
+
+### Draft strokes (33.6M, measured both ways)
+
+`SF_DRAFT_STROKE=1` (Preferences > Performance > Draft Strokes): dabs only move vertices and refit the BVH;
+the moved clusters draw with per-pixel face normals; normals, cavities and exact bounds are worked out once at
+pen lift, on the solver thread. Interleaved, two runs each, A = draft off, B = draft on:
+
+| Brush | | Frame mean / p95 / p99 | Surface lag | Press | First surface | Until done |
+|---|---|---:|---:|---:|---:|---:|
+| 200 px | off | 12.4 / 24.6 / 28.6 ms | 438 px | 14 ms | 476 ms | 1182 ms |
+| | draft | 13.6 / 27.0 / 30.6 ms | 445 px | 38 ms | 523 ms | 2985 ms |
+| 240 px | off | 12.8 / 26.6 / 30.9 ms | 281 px | 18 ms | 757 ms | 1988 ms |
+| | draft | 13.8 / 29.0 / 32.1 ms | 427 px | 22 ms | 719 ms | 3070 ms |
+
+On this machine draft strokes don't pay: the frames were never CPU-bound (the solver is on its own thread), the
+dab saves its normals pass but the stroke's end then recomputes the normals of everything the stroke touched,
+so the last result arrives later. (The draft runs coincided with the heaviest load of the session, 18-45.)
+It should help where the solver's cores are the bottleneck and energy matters (a laptop on battery, fewer
+cores): off by default, for the hardware tiers to turn on.
+
+ ## Micro-displacement levels: 300M-1B sculptable triangles (feat/micromesh)
+
+ ```
+ sculptforge --bench-micro --bench-sizes 33,100,300 [--bench-micro-level 5] [--bench-brushes TEXT]
+ sculptforge-cli --bench-micro ... # without the GPU: memory, brush and shading times
+ ```
+
+ A micro level (core/Micro.h) stores the surface above the highest subdivision level as one 16-bit height per
+ point of a regular grid on each base triangle, along the interpolated normal of the Phong-tessellated base.
+ Micro triangles are never stored: brushes evaluate them on the CPU, the renderer in its vertex shader
+ (render/MicroRenderer.h). The benchmark divides a bench sphere to the size, sculpts strokes of 30 dabs with X
+ symmetry (two dabs a step) and orbits. M1 Pro, Release; the machine was shared with other jobs during these runs
+ (load average 10-20), so treat single rows as +/-30%.
+
+ Memory and frames:
+
+ | | 33M (Micro 4) | 104M (Micro 4) | 299M (Micro 4) | 299M (Micro 5) | **1.02B (Micro 5)** |
+ |---|---:|---:|---:|---:|---:|
+ | Base triangles | 130k | 406k | 1.2M | 292k | 995k |
+ | Micro level in memory | 42 MB | 130 MB | 374 MB | 332 MB | 1131 MB |
+ | per micro triangle / micro vertex | 1.25 / 2.50 B | 1.25 / 2.50 B | 1.25 / 2.50 B | 1.11 / 2.22 B | 1.11 / 2.22 B |
+ | Process RSS, everything | 263 MB | 432 MB | 801 MB | 710 MB | **1713 MB** |
+ | GPU buffers | 125 MB | 392 MB | 1128 MB | 997 MB | 3398 MB |
+ | Divide to micro | 5 ms | 32 ms | 60 ms | 29 ms | 93 ms |
+ | First shading + upload | 0.1 s | 0.7 s | 1.2 s | 1.7 s | 5.1 s |
+ | Orbit, 4x AA | 8.3 ms | 9.7 ms | 14.0 ms | 8.9 ms | 13.4 ms |
+ | Orbit, no AA / moving | 5.0 / 2.9 ms | 6.6 / 4.7 ms | 10.4 / 4.5 ms | 6.2 / 4.1 ms | 11.3 / 5.0 ms |
+ | Triangles drawn (still / moving) | 4.3M / 1.1M | 3.9M / 1.0M | 3.4M / 0.9M | 3.4M / 0.9M | 3.0M / 0.8M |
+ | Save / open project | 31 / 61 ms | 71 / 100 ms | 217 / 285 ms | 187 / 264 ms | 649 / 489 ms |
+
+ The same 300M as a plain mesh would need about 27 GB (90 B per triangle, see 33M below). The frame time follows
+ the triangle budget and the number of base triangles on screen, not the micro triangle count: 33M at Micro 4
+ and 299M at Micro 5 (130k and 292k base triangles) both draw in 8-9 ms. Patches of one or four triangles are
+ drawn unrolled (gl_VertexID), not instanced: instancing them cost 21 ms a moving frame at 299M, unrolled 4.4 ms.
+
+ Brushes, per dab step (both mirrors), GPU upload included:
+
+ | | 33M | 104M | 299M (Micro 4) | 299M (Micro 5) | 1.02B (Micro 5) |
+ |---|---:|---:|---:|---:|---:|
+ | Standard (r 0.12, ~64 px) | 2.4 ms | 11 ms | 13 ms | 17 ms | 39 ms |
+ | Standard, 300 px (r 0.56) | 13.5 ms | 56 ms | 115 ms | 48 ms | 283 ms |
+ | Smooth (large, r 0.4) | 9.4 ms | 21 ms | 50 ms | 44 ms | 54 ms |
+ | Move, 300 px (base cage) | 13 ms | 19 ms | 58 ms (45 after the pick fix) | 22 ms | 55 ms |
+ | Undo step, Standard stroke (30 dabs) | 0.6 MB | 1.7 MB | 4.7 MB | 3.4 MB | 11.2 MB |
+
+ Scale-adaptive brushes: a dab is evaluated on grid points `stride` apart (about 48 across its radius) and
+ interpolated in between, so the evaluation (the "kernel" column of the report) stays bounded; writing the
+ interpolated values, stitching and the GPU upload still grow with the points under the brush. The 300 px grab
+ (Move) deforms the base cage and doesn't touch the micro level at all: 20 ms at 31M against 45 ms at 299M (Micro 4,
+ ten times the base triangles) in one run; at Micro 5 (2.4x the base) 22 ms. Picking at 299M went from 37 to 11 ms
+ once the candidates were filtered by their own displacement range along the ray.
+
+ Undo journal: tiles in Morton order, each the stroke's change predicted from its neighbour and packed (minimum +
+ bit width): about a third of whole tiles. A short stroke stays under the 500 KB target (10 dabs of r 0.15 at
+ 5M: 31 KB); the benchmark's 30-dab strokes over 300M are 2-5 MB, limited by the rounding noise each dab leaves
+ (2-4 bits per point). A whole-surface edit (micro_noise) keeps whole tiles.
+
+ What a frame still costs: the CPU shading (normals, curvature) of what a dab changed, about 20 ns per grid point,
+ within a budget per frame (TierConfig::shadeBudgetPoints, 3M: the rest of a big dab's normals follow over the next
+ frames); the first full shading of a level (1-5 s). Candidates: shading on the GPU from the displacement texture
+ (needs the edge neighbours in the fragment shader), and storing the coarse part of big strokes on a coarse grid
+ (multires-style) so a 300 px dab writes thousands of points instead of millions.
+ ## Hardware profile, calibration and the frame governor (feat/hw-profile)
+
+ SculptForge measures the computer it runs on and sets its budgets from what it measured. Code:
+ `src/core/HardwareProfile.*` (probe types, mapping, cache, JSON, commands), `src/core/TierConfig.*` (the knobs other
+ modules read), `src/core/FrameGovernor.*` (run-time adaptation), `src/app/Calibration.*` (OpenGL probe and GPU
+ benchmarks, `--calibrate`), `src/app/PanelPerformanceProfile.cpp` (first-launch flow, Preferences > Performance).
+ Nothing in it uses the network.
+
+ ### When it runs
+
+ On first launch, and again when `GL_VENDOR`, `GL_RENDERER` or `GL_VERSION` (which carries the driver version)
+ or the app version changes, or when the cache holds only a CPU calibration from `sculptforge-cli`. The result
+ is cached in `<settings folder>/hardware_profile.json` (Linux `~/.local/share/SculptForge/SculptForge/`, macOS
+ `~/Library/Application Support/SculptForge/SculptForge/`, Windows `%APPDATA%\SculptForge\SculptForge\`). In the
+ app it runs over the first frames, one step per frame under a small overlay (Esc or Skip skips it; the profile
+ then comes from the probe alone). UI tests, renders, recordings, demos and the `--measure-*` runs never
+ calibrate and keep the fixed defaults (Fast Navigation at 10 million triangles), so their results don't depend
+ on the machine. `SF_NO_CALIBRATION=1` skips it too.
+
+ ```
+ sculptforge --calibrate [--calibrate-quick] [--calibrate-no-save] # prints JSON (schema sculptforge.calibration/1)
+ sculptforge-cli -c 'calibrate' # CPU half only (no OpenGL); GPU numbers from the cache
+ sculptforge-cli -c 'performance_profile' # the cached profile as JSON
+ sculptforge-cli -c 'set_performance_override name=render_triangle_budget value=12000000' # value=auto clears
+ ```
+
+ The same three commands are in the command registry, so the console, scripts and MCP clients have them; in the
+ app `calibrate` measures the GPU too.
+
+ ### What it probes
+
+ | | How |
+ |---|---|
+ | GPU | `GL_VENDOR`, `GL_RENDERER`, `GL_VERSION`, `GL_MAX_TEXTURE_SIZE`, timer queries (`GL_TIME_ELAPSED`) |
+ | Memory type | Software (llvmpipe, softpipe, SwiftShader, GDI Generic, Microsoft Basic Render), unified (Apple GPUs on macOS and Asahi), integrated or discrete, from the renderer string, refined by `GLX_RENDERER_UNIFIED_MEMORY_ARCHITECTURE_MESA` / `..._ACCELERATED_MESA` where available. Only the memory type comes from names; tiers come from measurements and memory sizes |
+ | Video memory | the first that answers: `GL_NVX_gpu_memory_info` (NVIDIA; Mesa's radeonsi and asahi too), `GL_ATI_meminfo` (free memory only), `GLX_MESA_query_renderer` (Mesa on X11), amdgpu's `mem_info_vram_total` in sysfs (Linux, also on Wayland), DXGI (Windows), CGL (macOS). Unified memory counts at most two thirds of the RAM (Metal's working set), whatever the driver reports |
+ | Machine | RAM, hardware threads, SIMD (SSE4.2 / AVX2 / AVX-512 on x86, NEON / SVE on ARM) and what the build uses, OS, CPU brand (x86 cpuid, macOS sysctl, the device tree on ARM Linux) |
+
+ ### What it measures (about 0.5-1.5 s of work; medians of 5 runs, 3 quick)
+
+ | Measurement | Work |
+ |---|---|
+ | Triangle throughput | a 512 x 256 quad grid (262k triangles, about 4 pixels each, like a whole sculpt on screen) drawn instanced into a 1024 x 1024 offscreen target, every instance in front of the last; the instance count is chosen for about 25 ms a run; GL timer queries, else glFinish around the CPU clock |
+ | Upload bandwidth | `glBufferSubData` of a 32 MB buffer, waited for (glFinish) |
+ | Brush dab | 20 Standard dabs (X symmetry, radius 0.12) on a generated 1M-triangle sphere, undone between runs |
+ | Memory bandwidth | `memcpy` of 64 MB |
+
+ ### Profiles
+
+ Two main tiers and a safe mode:
+
+ - **Workstation**: 64 GB or more of RAM (60 GB reported) and either a discrete GPU with 16 GB or more (15 GB
+ reported) or a GPU sharing the system memory (Apple Silicon Max / Ultra, big APUs), whose pool counts as two
+ thirds of the RAM; and in both cases at least 1000M triangles/s, dabs under 3 ms, memory over 4 GB/s.
+ - **Laptop / Budget**: everything else (8-32 GB RAM, 2-8 GB GPUs, Apple Silicon with less than 64 GB, thermal and
+ battery limits).
+ - **Software** (safe mode): a software renderer, or under 60M triangles/s.
+
+ A re-calibration of the same GPU keeps the previous tier while the new triangle throughput is within 15% of the
+ boundary, so a busy machine doesn't flip between tiers. Settings, before overrides:
+
+ | Setting | How |
+ |---|---|
+ | `render_triangle_budget` | half a 60 Hz frame of the measured throughput, clamped per tier (Software 0.25-4M, Laptop 2-40M, Workstation 8-600M) |
+ | `motion_proxy_threshold` | the budget (at least 262k): scenes over it draw the motion proxy while the view moves |
+ | `vram_budget_mb` | 80% of dedicated memory; unified: two thirds of RAM; integrated: half of RAM; software: a quarter |
+ | `upload_budget_mb_per_frame` | a quarter of a 60 Hz frame at the measured upload bandwidth (4-1024 MB) |
+ | `max_texture_size` | the GL limit, at most 4096 / 8192 / 16384 by tier, 8192 under 2 GB of GPU memory |
+ | `max_subdivision_triangles` | the smaller of half the RAM at 100 bytes per triangle and the GPU budget at 16 bytes per triangle, capped by tier |
+ | `micro_triangle_limit` | a quarter of the GPU budget at 8 bytes per micro-triangle, capped by tier |
+ | `threads` | hardware threads (at most 16, the pool's limit); half in safe mode, where llvmpipe draws on the same cores. Applies at the next start |
+ | `target_fps` | 60, 120 or 144 from the display (`TierConfig::targetHz`) |
+
+ Every setting can be overridden by hand (Preferences > Performance > Manual overrides, or `set_performance_override`),
+ and overrides survive re-calibration.
+
+ ### TierConfig (core/TierConfig.h)
+
+ What feat/micromesh and feat/zero-latency read, through `currentTierConfig()` (thread-safe; `tierConfigRevision()`
+ changes when it does):
+
+ | Field | Software | Laptop / Budget | Workstation |
+ |---|---|---|---|
+ | `residentCacheCapMB` | RAM / 8, at most 1 GB | RAM / 4, at most 4 GB | RAM x 2/5, at most 64 GB |
+ | `activeTriangleBudget` | 0.5M | 2M | 8M+ (half the render budget, at most 64M) |
+ | `uploadBudgetMBPerFrame` | the profile's | the profile's | the profile's |
+ | `draftBrushMode` (normals and cavity at pen release) | on | on | off (continuous) |
+ | `zeroCopyUMA` | the GPU shares system memory: unified or integrated, in any tier (a 64 GB+ Apple Silicon Workstation too) | | |
+ | `targetHz` | 60 | 60 / 120 / 144 from the display | 60 / 120 / 144 from the display |
+
+ The app reads the power source with `SDL_GetPowerInfo` at start and every 5 seconds. On battery, whatever the tier
+ (an Apple Silicon Workstation is a laptop too): draft brushes,
+ half the upload budget and 60 Hz (unless set by hand), and the status bar says so. The `draft_brush` override
+ (on / off) wins over both. `draftBrushMode` is a flag for the brush engine; the brushes don't read it yet.
+
+ ### Render triangle budget and the frame governor
+
+ `renderTriangleBudget()` (core/HardwareProfile.h) is the number of triangles the 3D view may draw per frame to
+ hold the target frame rate; `motionProxyThreshold()` is where Fast Navigation switches big scenes to their
+ motion proxy. The frame governor (core/FrameGovernor.h) adjusts both from real frames:
+
+ - Inputs per drawn frame: CPU time from input to swap (without the vsync wait), GPU time from a `GL_TIME_ELAPSED`
+ query read up to 4 frames later (never waiting), triangles drawn, the scene's full triangle count, whether
+ the view is moving and whether the proxy was used. Only moving frames count: still frames draw everything in
+ full and the governor can't change them. Frames over 250 ms (dialogs, loading) are ignored.
+ - Every 20 counted frames it takes the medians. Above the target frame time it lowers the budget (aiming at 80%
+ of the frame, at most halving it); under 60% it raises it (at most 1.25x) when the budget is what limits the
+ view. In between it holds (the dead band). After a change, 5 frames are ignored.
+ - Raising the budget past the scene's size would switch the proxy off; it only does when the predicted full
+ frame stays under 90% of the target, so the view never flips between proxy and full detail.
+ - Bounds: an eighth to four times the profile's budget. It changes only how much is drawn, never the mesh.
+
+ Today's renderer uses the governed threshold for the motion proxy (Preferences > Performance > Fast Navigation;
+ `SF_FAST_NAVIGATION_TRIANGLES` still overrides it for tests).
+
+ **How micromesh consumes it:** read `renderTriangleBudget()` once per frame (an atomic load) and amplify
+ micro-displacement only until the frame's drawn triangles reach it, finest where the screen-space error is
+ largest; keep the generated micro-triangles under `currentPerformanceSettings().microTriangleLimit` and their
+ pages under `currentTierConfig().residentCacheCapMB`. Report the triangles actually drawn through
+ `Renderer::lastDrawnTriangles()` so the governor sees them; it then raises or lowers the budget continuously
+ (continuous level of detail converges without the proxy's step, see the `governor_converges_*` tests).
+
+ ### This machine
+
+ Apple M1 Pro under Asahi Linux, on battery, with about 35 other processes compiling (load average 35 on 10
+ cores), so the CPU numbers here are low (memory bandwidth measured 23 GB/s on a quieter run, dabs 0.07 ms on a
+ 0.2M sphere):
+
+ ```
+ "gl_renderer": "Apple M1 Pro (G13S C0)", "gl_version": "4.6 (Core Profile) Mesa 26.1.8", "gpu_kind": "unified",
+ "vram_mb": 31667 (GL_NVX_gpu_memory_info: all of the RAM), "timer_query": true, "cpu_threads": 10, "simd": ["neon"]
+ measurements: 1358M triangles/s (GPU timer), upload 12.8 GB/s, dab 0.37 ms (2.5k vertices), memory 5.9 GB/s, 607 ms
+ profile: Laptop (32 GB of RAM is under the 64 GB Workstation needs; this run predates the unified-memory rule, so its
+ reason read "no discrete GPU"; it now reads "30.9 GB RAM")
+ settings: render budget 11.3M, motion proxy from 11.3M, GPU memory 20.6 GB, uploads 50 MB/frame, textures 8192,
+ subdivision 120M, micro-triangles 256M, 10 threads, 60 fps
+ tier_config: cache 4 GB, active 2M, uploads 25 MB/frame (battery), draft brushes, zero-copy UMA, 60 Hz, on battery
+ ```
+
+ Across runs on the busy machine the triangle throughput ranged 913-1410M/s and upload 4.3-21 GB/s.
+
-## Next version: big brushes on dense meshes (feat/perf-pass)
+## 0.9.7: big brushes on dense meshes (feat/perf-pass)
What a user feels on a heavy model is a large brush: how far it trails the pointer, how long a frame takes, and
what happens on press and release. Measured with the stroke the app draws itself (pointer read once per pass of
diff --cc src/app/App.cpp
index 2ad71a7a,70042348..ec4c0e48
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@@ -1,7 -1,7 +1,8 @@@
// SculptForge - open source digital sculpting
// SPDX-License-Identifier: GPL-3.0-or-later
#include "app/App.h"
+#include "app/AsyncStroke.h"
+ #include "app/Calibration.h"
#include "app/CrashLog.h"
#include "ai/AiCommands.h"
@@@ -893,55 -812,23 +906,61 @@@ int App::run()
keepImGuiOnPen();
ImGui::NewFrame();
drawUi();
+ drawHardwareProfileOverlay();
ImGui::Render();
+ mark();
- prewarmTexturePaint(); // dense textured meshes: ready the area under the hovering Paint brush (PanelPbr.cpp)
+ buildGhost(); // the dabs not on the GPU yet, drawn as a preview (predictive strokes)
++ // dense textured meshes: ready the area under the hovering Paint brush (PanelPbr.cpp); not while the solver
++ // thread owns the mesh
++ if (!solverBusy()) prewarmTexturePaint();
const auto syncStart = std::chrono::steady_clock::now();
syncScene();
+ mark();
notePerformanceFrame(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - syncStart).count());
const int samples = viewSamples();
renderSettings_.motionProxy = perf_.proxyNow; // big meshes draw their lighter proxy while the view moves
perf_.samplesUsed = renderer_.drawView(camera_, fbW, fbH, renderSettings_, canvasViewport(fbW, fbH), samples);
+ if (snapshotEnv && *snapshotEnv && (sm.moving || sm.releasing)) {
+ // Three points of the stroke, and the end (the frame the last dab reached the screen).
+ const double u = sm.moving ? (seconds() - sm.start) / double(options_.measureStroke) : 2.0;
+ const bool last = sm.releasing && !doc_.sculptor.strokeActive();
+ if ((sm.snapshots < 3 && u >= 0.3 * (sm.snapshots + 1)) || (last && sm.snapshots < 4)) {
+ sm.snapshots = last ? 4 : sm.snapshots + 1;
+ const Renderer::Viewport v = canvasViewport(fbW, fbH);
+ Image img;
+ img.width = v.w > 0 ? v.w : fbW;
+ img.height = v.h > 0 ? v.h : fbH;
+ img.rgba.resize(size_t(img.width) * size_t(img.height) * 4);
+ gl::ReadPixels(v.w > 0 ? v.x : 0, v.w > 0 ? v.y : 0, img.width, img.height, GL_RGBA, GL_UNSIGNED_BYTE, img.rgba.data());
+ for (int y = 0; y < img.height / 2; ++y) // (GL rows are bottom-up)
+ std::swap_ranges(img.rgba.begin() + std::ptrdiff_t(size_t(y) * img.width * 4),
+ img.rgba.begin() + std::ptrdiff_t(size_t(y + 1) * img.width * 4),
+ img.rgba.begin() + std::ptrdiff_t(size_t(img.height - 1 - y) * img.width * 4));
+ std::string error;
+ img.savePng(std::string(snapshotEnv) + "-" + std::to_string(sm.snapshots) + ".png", error);
+ }
+ }
renderSettings_.motionProxy = false; // (other renders, e.g. project thumbnails, draw in full)
+ mark();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
+ hardwareProfileFrameEnd();
+ if (proof_) proofBeforeSwap(fbW, fbH); // Help > Benchmark: timing, video capture, the scripted pointer
SDL_GL_SwapWindow(window_);
+ mark();
+ if (phases == 7 && phase[6] - phase[0] > frameLogMs)
+ SDL_Log("frame %.1f ms: events %.1f, dabs %.1f, UI %.1f, ghost + sync %.1f, draw %.1f, UI draw + swap %.1f",
+ phase[6] - phase[0], phase[1] - phase[0], phase[2] - phase[1], phase[3] - phase[2], phase[4] - phase[3],
+ phase[5] - phase[4], phase[6] - phase[5]);
++framesDrawn;
- if (sm.started && !sm.moving) { // the press is on screen: start moving round the circle
+ {
+ const double frameNow = seconds();
+ static double lastSwap = 0.0;
+ if (lastSwap > 0.0) frameSeconds_ = frameSeconds_ * 0.9 + std::min(0.1, frameNow - lastSwap) * 0.1;
+ lastSwap = frameNow;
+ }
+ if (sm.started && sm.firstSurfaceMs == 0.0 && !sm.dabs.empty()) sm.firstSurfaceMs = (seconds() - sm.pressAt) * 1000.0;
+ if (sm.started && !sm.moving && !sm.releasing && sm.pressMs == 0.0) { // the press is on screen: start moving round the circle
sm.moving = true;
sm.pressMs = (seconds() - sm.start) * 1000.0;
sm.start = sm.lastFrame = seconds();
diff --cc src/app/AsyncStroke.cpp
index b5646dd0,00000000..9a1c5535
mode 100644,000000..100644
--- a/src/app/AsyncStroke.cpp
+++ b/src/app/AsyncStroke.cpp
@@@ -1,487 -1,0 +1,492 @@@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Strokes on heavy meshes (App.h): the solver thread, the per-frame hand-over, the ghost and the pen prediction.
+//
+// One frame of a stroke on the main thread: events queue dabs (strokeTo); pumpStroke commits the batch the
+// solver finished (its packed vertices go up with glBufferSubData, its dabs leave the ghost) and hands it the
+// dabs waiting; buildGhost gives the renderer every dab not on the GPU yet; the frame draws and swaps while the
+// solver works. The mesh, its BVH and the sculptor belong to the solver while it is busy: nothing on the main
+// thread reads or writes them then (syncScene and the pollers wait, and every path that edits the document
+// ends the stroke first, which waits for the solver).
+#include "app/AsyncStroke.h"
+
++#include "core/Micro.h"
+#include "core/Sculpt.h"
++#include "core/TierConfig.h"
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <cstdlib>
+
+namespace sf {
+
+namespace {
+
+constexpr double kBatchSeconds = 0.033; // a batch's dabs: about this much work (the surface updates this often)
+
+} // namespace
+
+App::StrokeSolver::StrokeSolver(App& a) : app(a) { thread_ = std::thread([this] { loop(); }); }
+
+App::StrokeSolver::~StrokeSolver() {
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ quit_ = true;
+ }
+ wake_.notify_all();
+ if (thread_.joinable()) thread_.join();
+}
+
+void App::StrokeSolver::start() {
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ pending_ = true;
+ done = false;
+ busy_.store(true, std::memory_order_release);
+ }
+ wake_.notify_one();
+}
+
+void App::StrokeSolver::wait() {
+ std::unique_lock<std::mutex> lock(mutex_);
+ idle_.wait(lock, [this] { return !busy_.load(std::memory_order_acquire); });
+}
+
+void App::StrokeSolver::loop() {
+ for (;;) {
+ {
+ std::unique_lock<std::mutex> lock(mutex_);
+ wake_.wait(lock, [this] { return pending_ || quit_; });
+ if (quit_) return;
+ pending_ = false;
+ }
+ probe.clear();
+ radiusProbe.clear();
+ double spent = 0.0;
+ const SculptTimings before = app.doc_.sculptor.timings;
+ app.dabView_ = &view;
+ if (finalize) { // a draft stroke's end: every normal and cavity term it touched
+ const auto t0 = std::chrono::steady_clock::now();
+ app.doc_.sculptor.flushDraft(app.doc_.mesh, app.doc_.bvh);
+ spent += std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+ }
+ for (const PathDab& d : batch) {
+ const auto t0 = std::chrono::steady_clock::now();
+ app.dabAt(d.x, d.y, d.pressure);
+ spent += std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+ }
+ app.dabView_ = nullptr;
+ 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());
+ if (finalize && uploadReady) app.renderer_.refineStrokeBoundsInto(uploadId, app.doc_.mesh, upload);
+ prepSeconds = finalize ? 0.0 : std::chrono::duration<double>(std::chrono::steady_clock::now() - prepStart).count();
+ static const bool log = std::getenv("SF_STROKE_LOG") != nullptr;
+ if (log) {
+ const SculptTimings& t = app.doc_.sculptor.timings;
+ SDL_Log("solver: %zu dabs %.1f ms (kernel %.1f, normals %.1f, BVH %.1f), upload packed in %.1f ms (vertices %.1f, "
+ "bounds %.1f), %.1f MB",
+ batch.size(), spent * 1000.0, t.kernelMs - before.kernelMs, t.normalsMs - before.normalsMs,
+ t.bvhMs - before.bvhMs,
+ std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - prepStart).count(),
+ upload.packMs, upload.boundsMs, double(upload.bytes()) / 1e6);
+ }
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ done = true;
+ busy_.store(false, std::memory_order_release);
+ }
+ idle_.notify_all();
+ wakeMainLoop();
+ }
+}
+
+// ---------------------------------------------------------------------------
+
+bool App::predictiveStrokes() const {
+ static const int env = [] {
+ const char* v = std::getenv("SF_PREDICTIVE_STROKE");
+ return v && *v ? (*v == '0' ? 0 : 1) : -1;
+ }();
+ return env >= 0 ? env == 1 : uiPrefs_.predictiveStrokes;
+}
+
+bool App::draftStrokes() const {
+ static const int env = [] {
+ const char* v = std::getenv("SF_DRAFT_STROKE");
+ return v && *v ? (*v == '0' ? 0 : 1) : -1;
+ }();
- return predictiveStrokes() && (env >= 0 ? env == 1 : uiPrefs_.draftStrokes);
++ // The hardware profile's tier decides (draft on laptops and on battery, core/TierConfig.h); the preference
++ // turns it on whatever the tier.
++ return predictiveStrokes() && (env >= 0 ? env == 1 : uiPrefs_.draftStrokes || currentTierConfig().draftBrushMode);
+}
+
+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.
+ const bool recipe = strokeRecipe() != nullptr;
+ return interactiveStrokes_ && predictiveStrokes() && strokeSculpt_ && !strokePaint_ && !strokeMask_ &&
+ !doc_.sculptor.dyntopo.enabled && previewLod_ < 0 && !faceTakePlaying_ &&
++ !doc_.mesh.micro && // (a micro level is sculpted and drawn by core/MicroSculpt and the MicroRenderer)
+ (recipe || (strokeBrush_ != BrushType::Move && strokeBrush_ != BrushType::SnakeHook)) &&
+ strokeType_ != StrokeType::DragRect && strokeType_ != StrokeType::DragDot;
+}
+
+bool App::solverBusy() const { return solver_ && solver_->busy(); }
+
+void App::solverWait() {
+ if (!solver_) return;
+ solver_->wait();
+ if (solver_->done) commitSolverBatch();
+}
+
+void App::commitSolverBatch() {
+ StrokeSolver& s = *solver_;
+ s.done = false;
+ ++commits_;
+ // SF_MEASURE_POP: the view before the commit, with and without the batch's preview.
+ std::vector<uint8_t> withPreview, withoutPreview, after;
+ const CanvasRect canvas = canvasRect();
+ const float scale = std::min(1.0f, 640.0f / std::max(canvas.w, canvas.h));
+ const int pw = std::max(1, int(canvas.w * scale)), ph = std::max(1, int(canvas.h * scale));
+ auto render = [&](std::vector<uint8_t>& out) {
+ std::string error;
+ Camera cam = camera_;
+ cam.aspect = float(pw) / float(ph);
+ renderer_.renderToImage(cam, pw, ph, renderSettings_, out, error);
+ };
+ const bool probe = popProbe_ && !s.batch.empty();
+ if (probe) {
+ buildGhost();
+ render(withPreview);
+ std::vector<PathDab> batch;
+ batch.swap(s.batch);
+ buildGhost();
+ render(withoutPreview);
+ batch.swap(s.batch);
+ }
+ if (s.uploadReady) {
+ const auto t0 = std::chrono::steady_clock::now();
+ renderer_.commitStrokeUpload(s.upload);
+ s.uploadReady = false;
+ static const bool log = std::getenv("SF_STROKE_LOG") != nullptr;
+ if (log) SDL_Log("commit: %.1f ms", std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count());
+ } else {
+ syncScene(); // (the regular sync: a new grid, or a mesh the two-part upload doesn't handle)
+ }
+ if (strokeProbe_) strokeProbe_->insert(strokeProbe_->end(), s.probe.begin(), s.probe.end());
+ if (strokeRadiusProbe_) strokeRadiusProbe_->insert(strokeRadiusProbe_->end(), s.radiusProbe.begin(), s.radiusProbe.end());
+ if (s.prepSeconds > 0.0) prepSeconds_ = prepSeconds_ > 0.0 ? prepSeconds_ * 0.7 + s.prepSeconds * 0.3 : s.prepSeconds;
+ if (!s.batch.empty()) {
+ lastDabScreen_ = glm::vec2(s.batch.back().x, s.batch.back().y);
+ if (s.dabSeconds > 0.0) dabSeconds_ = dabSeconds_ > 0.0 ? dabSeconds_ * 0.8 + s.dabSeconds * 0.2 : s.dabSeconds;
+ }
+ if (doc_.sculptor.lastFrame.valid) {
+ // The surface's curvature along the stroke (signed, 1 / radius; > 0 convex), from how the area normal
+ // turned since the last frame, smoothed over the batches; small turns count as flat.
+ const Sculptor::DabFrame& f = doc_.sculptor.lastFrame;
+ const glm::vec3 d = f.center - ghostFrame_.center;
+ const float dist = glm::length(d);
+ const float angle = std::acos(std::clamp(glm::dot(glm::normalize(f.normal), glm::normalize(ghostFrame_.normal)), -1.0f, 1.0f));
+ if (dist > 1e-6f) {
+ float k = angle > glm::radians(0.5f) ? angle / dist : 0.0f;
+ if (glm::dot(d, f.normal - ghostFrame_.normal) < 0.0f) k = -k; // normals converging: concave
+ ghostCurvature_ = ghostCurvature_ == 0.0f ? k : ghostCurvature_ * 0.5f + k * 0.5f;
+ }
+ ghostFrame_ = f;
+ }
+ s.batch.clear();
+ if (probe) {
+ buildGhost();
+ render(after);
+ auto diff = [&](const std::vector<uint8_t>& a) {
+ uint64_t sum = 0;
+ for (size_t i = 1; i < a.size() && i < after.size(); i += 4) sum += uint64_t(std::abs(int(a[i]) - int(after[i])));
+ return double(sum) / double(std::max<size_t>(1, after.size() / 4));
+ };
+ const double with = diff(withPreview);
+ popWith_ += with;
+ popWithout_ += diff(withoutPreview);
+ popWorst_ = std::max(popWorst_, with);
+ ++popCommits_;
+ }
+}
+
+void App::pumpStroke() {
+ if (!asyncStroke_) return;
+ if (!solver_) solver_ = std::make_unique<StrokeSolver>(*this);
+ if (solver_->busy()) return;
+ if (solver_->done) commitSolverBatch();
+ if (dabQueue_.empty() && strokeFinishing_ && !solver_->finalize) {
+ // Released: the stroke's end work on the solver thread too (a draft's normals and cavities, the exact
+ // culling bounds of what it moved), then the end.
+ StrokeSolver& s = *solver_;
+ s.batch.clear();
+ s.finalize = true;
+ 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);
+ renderer_.bindStrokeUpload(s.uploadId, s.upload); // (the slot, found here: the thread doesn't walk the renderer's list)
+ s.prepare = &displayedMesh() == &doc_.mesh;
+ s.start();
+ return;
+ }
+ if (dabQueue_.empty()) {
+ if (strokeFinishing_) finishStrokeNow(); // released, and every dab is on the GPU
+ return;
+ }
+ // The next batch, oldest first: about kBatchSeconds of work, or as much as packing its upload costs (so the
+ // packing, per batch, stays at most about half the work), at least one dab; once the pen has lifted, every
+ // dab left (the preview shows them all: only the end result is waited for), with the stroke's end work.
+ StrokeSolver& s = *solver_;
+ const double target = std::max(kBatchSeconds, prepSeconds_);
+ size_t n = dabSeconds_ > 0.0 ? size_t(std::clamp(target / dabSeconds_, 1.0, 64.0)) : 1;
+ if (strokeFinishing_) n = 64;
+ s.batch.clear();
+ while (!dabQueue_.empty() && s.batch.size() < n) s.batch.push_back(dabQueue_.pop());
+ s.finalize = strokeFinishing_ && dabQueue_.empty();
+ s.view.camera = camera_;
+ s.view.canvas = canvasRect();
+ s.view.probe = strokeProbe_ ? &s.probe : nullptr;
+ s.view.radiusProbe = strokeProbe_ ? &s.radiusProbe : nullptr;
+ s.view.settings = dabSettings();
+ s.uploadId = doc_.activeSubtoolInfo().id;
+ renderer_.bindStrokeUpload(s.uploadId, s.upload); // (the slot, found here: the thread doesn't walk the renderer's list)
+ s.prepare = &displayedMesh() == &doc_.mesh; // (a previewed LOD shows instead: nothing to pack)
+ renderer_.setDraftNormals(doc_.sculptor.draftActive() ? s.uploadId : 0);
+ s.start();
+}
+
+void App::finishStrokeNow() {
+ 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);
+ if (asyncStroke_) renderer_.refineStrokeBounds(doc_.activeSubtoolInfo().id, displayedMesh()); // (the quick ones)
+ strokeFinishing_ = false;
+ asyncStroke_ = false;
+ renderer_.setGhost(0, GhostStroke());
+ ghostHeadValid_ = false;
+ strokeMask_ = false;
+ maskClickPending_ = false;
+ firstDabPending_ = false;
+ // Preferences > Performance shows what the stroke cost.
+ if (doc_.sculptor.timings.dabs > 0) {
+ perf_.lastStroke = doc_.sculptor.timings;
+ perf_.lastStrokeSyncMs = perf_.strokeSyncMs;
+ perf_.lastStrokeFrames = perf_.strokeFrames;
+ }
+ doc_.sculptor.timings = {};
+ perf_.strokeSyncMs = 0.0;
+ perf_.strokeFrames = 0;
+ UndoRecord r = doc_.sculptor.endStroke();
+ finishPaintStroke(r);
+ if (r.topology && !r.topology->uvs.empty())
+ status_ = "Dynamic topology removed the UVs of the remeshed SubTool (Undo brings them back)";
+ if (!r.empty()) {
+ doc_.undo.push(std::move(r));
+ doc_.modified = true;
+ updateTitle();
+ }
+}
+
+App::DabSettings App::dabSettings() const {
+ DabSettings st;
+ st.radiusPx = radiusPx_;
+ st.strength = strength_;
+ st.smoothStrength = smoothStrength_;
+ st.focal = focalShift_;
+ st.maskStrength = maskStrength_;
+ st.sprayScatter = sprayScatter_;
+ st.pressureSize = pressureSize_;
+ st.pressureStrength = pressureStrength_;
+ st.invert = strokeInvert_;
+ st.frontFacesOnly = frontFacesOnly_;
+ st.mask = strokeMask_;
+ st.paint = strokePaint_;
+ st.sculpt = strokeSculpt_;
+ st.visible = doc_.activeSubtoolInfo().visible;
+ st.brush = strokeBrush_;
+ st.strokeType = strokeType_;
+ st.symmetry = symmetry_;
+ // A predictive stroke works from its own copies of the recipe and alpha (made when it began).
+ st.recipe = asyncStroke_ ? strokeRecipe_.get() : strokeRecipe();
+ st.alpha = asyncStroke_ ? strokeAlpha_.get() : &doc_.brushAlpha; // (null: round)
+ st.vdmOwner = doc_.brushVdm;
+ st.vdm = st.vdmOwner.get();
+ return st;
+}
+
+bool App::pickWith(const DabView& view, float x, float y, RayHit& hit) const {
+ if (!view.settings.visible) return false;
+ glm::vec3 origin, dir;
+ view.camera.screenRay(x - view.canvas.x, y - view.canvas.y, view.canvas.w, view.canvas.h, origin, dir);
- return doc_.bvh.raycast(doc_.mesh, origin, dir, hit);
++ return surfaceRaycast(doc_.mesh, doc_.bvh, origin, dir, hit);
+}
+
+glm::vec2 App::predictedPointer() const {
+ if (!predictiveStrokes() || 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_);
+}
+
+bool App::ghostSurface(const glm::vec3& origin, const glm::vec3& dir, glm::vec3& at, glm::vec3& normal) const {
+ const glm::vec3 n0 = glm::normalize(ghostFrame_.normal);
+ const float denom = glm::dot(dir, n0);
+ if (std::abs(denom) < 1e-4f) return false;
+ const float tp = glm::dot(ghostFrame_.center - origin, n0) / denom; // the tangent plane
+ if (tp <= 0.0f) return false;
+ at = origin + dir * tp;
+ normal = n0;
+ if (ghostCurvature_ == 0.0f) return true;
+ // The sphere: centre one radius behind (convex) or in front of (concave) the last dab, along its normal.
+ const float R = 1.0f / std::abs(ghostCurvature_), side = ghostCurvature_ > 0.0f ? 1.0f : -1.0f;
+ const glm::vec3 C = ghostFrame_.center - n0 * (side * R);
+ const glm::vec3 oc = origin - C;
+ const float b = glm::dot(oc, dir), cc = glm::dot(oc, oc) - R * R, disc = b * b - cc;
+ if (disc < 0.0f) return true; // (the ray misses it: the plane)
+ const float sq = std::sqrt(disc);
+ const float t = std::abs(-b - sq - tp) < std::abs(-b + sq - tp) ? -b - sq : -b + sq; // the root nearer the plane's
+ if (t <= 0.0f) return true;
+ at = origin + dir * t;
+ normal = glm::normalize(at - C) * side;
+ return true;
+}
+
+void App::buildGhost() {
+ ghostHeadValid_ = false;
+ const uint32_t id = doc_.activeSubtoolInfo().id;
+ 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) {
+ renderer_.setGhost(id, GhostStroke());
+ return;
+ }
+ GhostStroke g;
+ g.kind = strokeRecipe() ? GhostKind::None : ghostKindForBrush(int(strokeBrush_));
+ g.invert = strokeInvert_;
+ g.focal = focalShift_;
+ g.edge = ghostEdge_;
+ // Where the dabs not on the GPU yet are on screen: those in flight, those waiting, and the head.
+ struct Screen {
+ float x, y, pressure, weight;
+ };
+ std::vector<Screen> pending;
+ for (const PathDab& d : solver_->batch) pending.push_back({d.x, d.y, d.pressure, 1.0f});
+ for (const PathDab& d : dabQueue_.items()) pending.push_back({d.x, d.y, d.pressure, 1.0f});
+ // The head: from the last dab to where the pen will be when this frame shows (not for strokes that move the
+ // pointer's path: Lazy Mouse, a Shift line, jitter or spray), in part, as the dabs the pen is about to lay.
+ const float spacing = std::max(1.0f, radiusPx_ * (strokeRecipe() ? strokeRecipe()->spacing : 0.15f));
+ if (drag_ == Drag::Stroke && strokeType_ != StrokeType::LazyMouse && strokeType_ != StrokeType::Spray && !straight_.active &&
+ !(strokeRecipe() && strokeRecipe()->jitter > 0.0f)) {
+ const glm::vec2 head = predictedPointer();
+ const glm::vec2 from = !pending.empty() ? glm::vec2(pending.back().x, pending.back().y) : lastDabScreen_;
+ const float gap = glm::distance(head, from);
+ const bool moving = glm::length(penPredictor_.velocity()) > 20.0f; // px / s
+ if (moving && gap > 0.2f * spacing)
+ pending.push_back({head.x, head.y, lastStrokePressure_, std::min(1.0f, gap / spacing)});
+ }
+ if (!pending.empty()) {
+ ghostHead_ = glm::vec2(pending.back().x, pending.back().y);
+ ghostHeadValid_ = true;
+ }
+ if (g.kind == GhostKind::None || pending.empty() || !ghostFrame_.valid) {
+ renderer_.setGhost(id, GhostStroke());
+ return;
+ }
+ // Each dab's surface point and normal: where its ray meets the surface as the last dabs placed describe it, a
+ // sphere through the last one with the curvature the last two show (their normals turn by an angle over the
+ // distance between them), or its tangent plane where they don't turn. The solver's result replaces the
+ // estimate when it arrives.
+ const CanvasRect c = canvasRect();
+ const glm::vec3 n0 = glm::normalize(ghostFrame_.normal);
+ const float depth = glm::dot(ghostFrame_.center - ghostFrame_.areaCenter, n0); // area centre below the surface
+ const std::vector<glm::vec3> mirrors = Sculptor::mirrors(symmetry_);
+ const size_t perMirror = GhostStroke::kMaxDabs / std::max<size_t>(1, mirrors.size());
+ std::vector<GhostDab> base;
+ for (const Screen& sd : pending) {
+ if (base.size() >= perMirror) break;
+ glm::vec3 origin, dir, n;
+ camera_.screenRay(sd.x - c.x, sd.y - c.y, c.w, c.h, origin, dir);
+ GhostDab d;
+ if (!ghostSurface(origin, dir, d.center, n)) continue;
+ d.radius = radiusPx_ * (pressureSize_ ? std::max(sd.pressure, 0.05f) : 1.0f) * camera_.worldPerPixel(d.center, c.h);
+ d.normal = n;
+ d.strength = std::clamp((strokeBrush_ == BrushType::Smooth ? smoothStrength_ : strength_), 0.0f, 1.0f) *
+ std::clamp(pressureStrength_ ? sd.pressure : 1.0f, 0.0f, 1.0f);
+ d.areaCenter = d.center - n * depth;
+ d.weight = sd.weight;
+ base.push_back(d);
+ }
+ for (uint32_t m = 0; m < mirrors.size(); ++m)
+ for (const GhostDab& b : base) {
+ GhostDab d = b;
+ d.center *= mirrors[m];
+ d.normal *= mirrors[m];
+ d.areaCenter *= mirrors[m];
+ d.mirror = m;
+ g.dabs.push_back(d);
+ }
+ renderer_.setGhost(id, g);
+}
+
+// --measure-stroke with SF_MEASURE_VERIFY=1: the stroke just drawn must come out of the frame loop's own path the
+// same, bit for bit, and its undo must give back the mesh it started from. Undoes it, checks the mesh, places the
+// same dabs (the probe's screen points, the mouse's pressure) with the solver thread off, and compares.
+uint64_t App::meshStateHash(const Mesh& mesh) {
+ uint64_t h = 1469598103934665603ull;
+ auto add = [&](const void* data, size_t bytes) {
+ const auto* p = static_cast<const uint8_t*>(data);
+ for (size_t i = 0; i < bytes; ++i) h = (h ^ p[i]) * 1099511628211ull;
+ };
+ add(mesh.positions.data(), mesh.positions.size() * sizeof(glm::vec3));
+ add(mesh.normals.data(), mesh.normals.size() * sizeof(glm::vec3));
+ return h;
+}
+
+bool App::verifyStroke(uint64_t before, const std::vector<glm::vec2>& dabs, const std::vector<float>& radii) {
+ const uint64_t after = meshStateHash(doc_.mesh);
+ runCommand("undo", {});
+ const uint64_t undone = meshStateHash(doc_.mesh);
+ const bool undoOk = undone == before;
+ // The same dabs, placed here (as with predictive strokes off).
+ const bool wasAsync = asyncStroke_;
+ asyncStroke_ = false;
+ haveLastDab_ = false;
+ const auto place = [&] {
+ doc_.syncBvh();
+ haveLastDab_ = false;
+ doc_.sculptor.draftStrokes = draftStrokes(); // (the measured stroke is one the solver thread takes)
+ doc_.sculptor.beginStroke(doc_.mesh, brushName(strokeBrush_), doc_.activeLayer);
+ const float radius = radiusPx_;
+ for (size_t i = 0; i < dabs.size(); ++i) {
+ if (i < radii.size()) radiusPx_ = radii[i]; // (the size each dab had: it may change mid-stroke)
+ dabAt(dabs[i].x, dabs[i].y, 1.0f);
+ }
+ radiusPx_ = radius;
+ doc_.sculptor.flushDraft(doc_.mesh, doc_.bvh);
+ doc_.undo.push(doc_.sculptor.endStroke());
+ return meshStateHash(doc_.mesh);
+ };
+ const uint64_t replay = place();
+ // And once more: the frame-loop path against itself (anything here that isn't deterministic shows).
+ runCommand("undo", {});
+ const uint64_t again = place();
+ asyncStroke_ = wasAsync;
+ const bool same = replay == after;
+ std::printf("verify: undo %s; %zu dabs replayed without the solver thread: %s (replayed twice: %s)\n",
+ undoOk ? "restores the mesh" : "DIFFERS", dabs.size(), same ? "identical" : "DIFFERENT",
+ again == replay ? "identical" : "DIFFERENT");
+ std::fflush(stdout);
+ return undoOk && same;
+}
+
+} // namespace sf
diff --cc src/app/PanelPerformance.cpp
index d44d80ab,f02ee015..3b281950
--- a/src/app/PanelPerformance.cpp
+++ b/src/app/PanelPerformance.cpp
@@@ -84,26 -88,7 +88,28 @@@ void App::registerPerformanceUiActions(
[] { return !ThreadPool::shared().serial(); },
"Run brushes, normal and BVH updates and project saving on every core. Turn it off only to compare speeds "
"or rule it out when troubleshooting: the results are the same either way.");
+ add("perf.predictive_strokes", "Predictive Strokes",
+ [this] {
+ uiPrefs_.predictiveStrokes = !uiPrefs_.predictiveStrokes;
+ status_ = uiPrefs_.predictiveStrokes ? "Predictive strokes on" : "Predictive strokes off";
+ },
+ [this] { return uiPrefs_.predictiveStrokes; },
+ "Sculpt strokes work out the brush on their own thread while the view keeps drawing at full speed, and show "
+ "the dabs still being worked out as a preview on the surface, with the cursor and the stroke's head drawn "
+ "where the pen is about to be. On a heavy mesh the surface moves under the pen at once and lifting the pen "
+ "is instant. The finished sculpt is exactly the same either way.");
+ add("perf.draft_strokes", "Draft Strokes",
+ [this] {
+ uiPrefs_.draftStrokes = !uiPrefs_.draftStrokes;
+ status_ = uiPrefs_.draftStrokes ? "Draft strokes on" : "Draft strokes off";
+ },
+ [this] { return uiPrefs_.draftStrokes; },
+ "With Predictive Strokes: while you sculpt, the brush only moves the surface and shades the moved part from "
+ "its facets; the smooth shading, the cavities and the rest are worked out once when you lift the pen. "
- "Lighter on laptops and on battery. Brushes that follow the surface's direction (Inflate, the plane brushes) "
- "use its direction from the stroke's start, so the result can differ slightly from a full stroke.");
++ "Lighter on laptops and on battery: the hardware profile turns it on there by itself (its Draft brushes "
++ "setting); this turns it on everywhere. Brushes that follow the surface's direction (Inflate, the plane "
++ "brushes) use its direction from the stroke's start, so the result can differ slightly from a full stroke.");
+ registerPerformanceProfileUiActions(); // Re-calibrate, the frame governor (PanelPerformanceProfile.cpp)
}
void App::applyPerformancePrefs() { ThreadPool::shared().setSerial(!uiPrefs_.multithreading); }
diff --cc src/app/ProofMode.cpp
index 00000000,af564e67..6dba974f
mode 000000,100644..100644
--- a/src/app/ProofMode.cpp
+++ b/src/app/ProofMode.cpp
@@@ -1,0 -1,871 +1,896 @@@
+ // SculptForge - open source digital sculpting
+ // SPDX-License-Identifier: GPL-3.0-or-later
+ //
+ // Proof mode (Help > Benchmark, sculptforge --benchmark; docs/benchmark.md).
+ //
+ // For each mesh size it builds a sphere with subdivision levels the way a sculptor gets one, then, in the
+ // app's own interactive loop, plays a scripted pen stroke into the same handlers mouse and pen events call
+ // (App::onMouseDown / onMouseMove / onMouseUp: the dab queue, the time budget, the renderer, all as when you
+ // sculpt), at 240 pointer samples a second, with a normal and a large brush, and turns the view. Every frame it
+ // records the frame time and how far the stroke on screen trails the pointer: in pixels along the path, and
+ // in milliseconds from the pointer sample the newest drawn dab belongs to until the frame showing it is handed
+ // to the display (SwapWindow; the display's own scan-out and the compositor come on top). A HUD shows the
+ // numbers live; the frames go, HUD included, to an MP4 (read back through pixel buffers, encoded by ffmpeg on
+ // its own thread), and a JSON result with the hardware and version is written at the end.
+ #include "app/ProofMode.h"
+
+ #include "app/App.h"
+ #include "app/Theme.h"
+
+ #include "core/Benchmark.h"
+ #include "core/Primitives.h"
+ #include "core/Timeline.h"
+
+ #include "render/GL.h"
+
+ #include <algorithm>
+ #include <chrono>
+ #include <cmath>
+ #include <condition_variable>
+ #include <cstdio>
+ #include <cstring>
+ #include <ctime>
+ #include <deque>
+ #include <filesystem>
+ #include <fstream>
+ #include <mutex>
+ #include <sstream>
+ #include <thread>
+
+ #if defined(_WIN32)
+ #include <windows.h>
+ #elif defined(__APPLE__)
+ #include <sys/sysctl.h>
+ #include <sys/utsname.h>
+ #include <mach/mach.h>
+ #else
+ #include <sys/utsname.h>
+ #include <unistd.h>
+ #endif
+
+ #ifndef SF_GIT_COMMIT
+ #define SF_GIT_COMMIT "unknown"
+ #endif
+
+ namespace sf {
+
+ // ---------------------------------------------------------------------------------------------------------------
+ // Sizes and hardware
+
+ std::vector<ProofMeshSize>& proofExtraSizes() {
+ static std::vector<ProofMeshSize> extra;
+ return extra;
+ }
+
+ std::vector<ProofMeshSize> proofDefaultSizes(size_t available) {
+ std::vector<ProofMeshSize> sizes{{5, "5M", nullptr, 150}, {20, "20M", nullptr, 150}, {33, "33M", nullptr, 150}};
+ auto fits = [&](const ProofMeshSize& s) {
+ return available > 0 && s.millions * 1e6 * s.bytesPerTriangle * 1.25 < double(available);
+ };
+ if (ProofMeshSize big{100, "100M", nullptr, 150}; fits(big)) sizes.push_back(big);
+ for (const ProofMeshSize& s : proofExtraSizes())
+ if (fits(s)) sizes.push_back(s);
+ return sizes;
+ }
+
+ size_t availableMemoryBytes() {
+ #if defined(_WIN32)
+ MEMORYSTATUSEX m{};
+ m.dwLength = sizeof m;
+ return GlobalMemoryStatusEx(&m) ? size_t(m.ullAvailPhys) : 0;
+ #elif defined(__APPLE__)
+ vm_statistics64_data_t vm{};
+ mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
+ if (host_statistics64(mach_host_self(), HOST_VM_INFO64, reinterpret_cast<host_info64_t>(&vm), &count) != KERN_SUCCESS) return 0;
+ return size_t(vm.free_count + vm.inactive_count + vm.purgeable_count) * size_t(vm_page_size);
+ #else
+ std::ifstream f("/proc/meminfo");
+ std::string key;
+ size_t kb = 0;
+ std::string unit;
+ while (f >> key >> kb >> unit)
+ if (key == "MemAvailable:") return kb * 1024;
+ return 0;
+ #endif
+ }
+
+ size_t totalMemoryBytes() {
+ #if defined(_WIN32)
+ MEMORYSTATUSEX m{};
+ m.dwLength = sizeof m;
+ return GlobalMemoryStatusEx(&m) ? size_t(m.ullTotalPhys) : 0;
+ #elif defined(__APPLE__)
+ uint64_t bytes = 0;
+ size_t len = sizeof bytes;
+ return sysctlbyname("hw.memsize", &bytes, &len, nullptr, 0) == 0 ? size_t(bytes) : 0;
+ #else
+ const long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGE_SIZE);
+ return pages > 0 && page > 0 ? size_t(pages) * size_t(page) : 0;
+ #endif
+ }
+
+ namespace {
+
+ std::string trim(std::string s) {
+ while (!s.empty() && (s.back() == '\n' || s.back() == ' ' || s.back() == '\0' || s.back() == '\r')) s.pop_back();
+ size_t i = 0;
+ while (i < s.size() && (s[i] == ' ' || s[i] == '\t')) ++i;
+ return s.substr(i);
+ }
+
+ std::string cpuModel() {
+ #if defined(_WIN32)
+ char buf[256] = {};
+ DWORD size = sizeof buf;
+ if (RegGetValueA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", "ProcessorNameString",
+ RRF_RT_REG_SZ, nullptr, buf, &size) == ERROR_SUCCESS)
+ return trim(buf);
+ return "unknown";
+ #elif defined(__APPLE__)
+ char buf[256] = {};
+ size_t len = sizeof buf;
+ if (sysctlbyname("machdep.cpu.brand_string", buf, &len, nullptr, 0) == 0) return trim(buf);
+ return "unknown";
+ #else
+ std::ifstream f("/proc/cpuinfo");
+ for (std::string line; std::getline(f, line);) {
+ if (line.rfind("model name", 0) == 0 || line.rfind("Hardware", 0) == 0) {
+ const size_t colon = line.find(':');
+ if (colon != std::string::npos) return trim(line.substr(colon + 1));
+ }
+ }
+ // ARM boards (Apple silicon under Asahi, Raspberry Pi...): the device tree names the machine.
+ std::ifstream dt("/proc/device-tree/model");
+ std::string model((std::istreambuf_iterator<char>(dt)), std::istreambuf_iterator<char>());
+ return model.empty() ? "unknown" : trim(model);
+ #endif
+ }
+
+ std::string osName() {
+ #if defined(_WIN32)
+ return "Windows";
+ #else
+ utsname u{};
+ if (uname(&u) != 0) return "unknown";
+ std::string s = std::string(u.sysname) + " " + u.release + " " + u.machine;
+ #if !defined(__APPLE__)
+ std::ifstream f("/etc/os-release");
+ for (std::string line; std::getline(f, line);)
+ if (line.rfind("PRETTY_NAME=", 0) == 0) {
+ std::string v = line.substr(12);
+ v.erase(std::remove(v.begin(), v.end(), '"'), v.end());
+ s = v + " (" + s + ")";
+ }
+ #endif
+ return s;
+ #endif
+ }
+
+ } // namespace
+
+ Json describeHardware() {
+ Json h = Json::object();
+ h.set("cpu", cpuModel());
+ h.set("logical_cores", int(std::thread::hardware_concurrency()));
+ h.set("ram_gb", std::round(double(totalMemoryBytes()) / double(1u << 30) * 10.0) / 10.0);
+ h.set("os", osName());
+ return h;
+ }
+
+ // ---------------------------------------------------------------------------------------------------------------
+ // The run
+
+ namespace {
+
+ using Clock = std::chrono::steady_clock;
+ double nowSeconds() { return std::chrono::duration<double>(Clock::now().time_since_epoch()).count(); }
+
+ constexpr GLenum kPixelPackBuffer = 0x88EB, kStreamRead = 0x88E1, kMapReadBit = 0x0001;
+ constexpr double kPointerHz = 240.0;
+ constexpr int kVideoFps = 30;
+
+ struct Percentiles {
+ double p50 = 0, p95 = 0, p99 = 0, max = 0, mean = 0;
+ };
+ Percentiles percentiles(std::vector<double> v) {
+ Percentiles p;
+ if (v.empty()) return p;
+ std::sort(v.begin(), v.end());
+ auto at = [&](double q) { return v[std::min(v.size() - 1, size_t(q * double(v.size())))]; };
+ p.p50 = at(0.5), p.p95 = at(0.95), p.p99 = at(0.99), p.max = v.back();
+ for (double x : v) p.mean += x;
+ p.mean /= double(v.size());
+ return p;
+ }
+ Json percentilesJson(const Percentiles& p) {
+ Json j = Json::object();
+ auto r = [](double x) { return std::round(x * 100.0) / 100.0; };
+ j.set("p50", r(p.p50));
+ j.set("p95", r(p.p95));
+ j.set("p99", r(p.p99));
+ j.set("max", r(p.max));
+ j.set("mean", r(p.mean));
+ return j;
+ }
+
+ // Frames to ffmpeg on a thread of its own, at a constant rate (frames repeat while the app is slower).
+ class VideoWriter {
+ public:
+ bool start(const std::string& path, int w, int h) {
+ w_ = w, h_ = h;
+ // Bottom-up rows from glReadPixels: flipped; scaled to at most 1920 wide to keep the encoder light.
+ const std::string cmd = "ffmpeg -loglevel error -y -f rawvideo -pix_fmt rgba -s " + std::to_string(w) + "x" +
+ std::to_string(h) + " -r " + std::to_string(kVideoFps) +
+ " -i - -vf \"vflip,scale='min(1920,iw)':-2\" -c:v libx264 -preset veryfast -crf 20 "
+ "-pix_fmt yuv420p -movflags +faststart \"" + path + "\"";
+ #if defined(_WIN32)
+ ff_ = _popen(cmd.c_str(), "wb");
+ #else
+ ff_ = popen(cmd.c_str(), "w");
+ #endif
+ if (!ff_) return false;
+ thread_ = std::thread([this] { loop(); });
+ return true;
+ }
+ // Takes the frame shown at `t` (seconds); drops it when the encoder is behind.
+ void push(double t, std::vector<uint8_t>&& rgba) {
+ std::lock_guard<std::mutex> lock(m_);
+ if (queue_.size() >= 4) return;
+ queue_.push_back({t, std::move(rgba)});
+ cv_.notify_one();
+ }
+ bool finish() {
+ if (!ff_) return false;
+ {
+ std::lock_guard<std::mutex> lock(m_);
+ stop_ = true;
+ cv_.notify_one();
+ }
+ thread_.join();
+ #if defined(_WIN32)
+ const int status = _pclose(ff_);
+ #else
+ const int status = pclose(ff_);
+ #endif
+ ff_ = nullptr;
+ return status == 0 && written_ > 0;
+ }
+ int width() const { return w_; }
+ int height() const { return h_; }
+ bool running() const { return ff_ != nullptr; }
+ ~VideoWriter() {
+ if (ff_) finish();
+ }
+
+ private:
+ void loop() {
+ std::vector<uint8_t> last;
+ double next = -1.0;
+ for (;;) {
+ std::pair<double, std::vector<uint8_t>> f;
+ {
+ std::unique_lock<std::mutex> lock(m_);
+ cv_.wait(lock, [&] { return stop_ || !queue_.empty(); });
+ if (queue_.empty()) break;
+ f = std::move(queue_.front());
+ queue_.pop_front();
+ }
+ if (next < 0) next = f.first;
+ // Slots up to this frame's time show the previous frame; then this one.
+ while (!last.empty() && next + 1.0 / kVideoFps <= f.first) {
+ std::fwrite(last.data(), 1, last.size(), ff_);
+ ++written_;
+ next += 1.0 / kVideoFps;
+ }
+ if (next <= f.first + 1e-9 || last.empty()) {
+ std::fwrite(f.second.data(), 1, f.second.size(), ff_);
+ ++written_;
+ next += 1.0 / kVideoFps;
+ }
+ last = std::move(f.second);
+ }
+ }
+ FILE* ff_ = nullptr;
+ int w_ = 0, h_ = 0;
+ std::thread thread_;
+ std::mutex m_;
+ std::condition_variable cv_;
+ std::deque<std::pair<double, std::vector<uint8_t>>> queue_;
+ bool stop_ = false;
+ long written_ = 0;
+ };
+
+ struct PhaseSpec {
+ const char* name;
+ float radiusPx; // 0 = an orbit, no stroke
+ double seconds;
+ };
+
+ struct PhaseResult {
+ std::string name;
+ float radiusPx = 0;
+ double seconds = 0, pathPx = 0, releaseMs = 0; // releaseMs: lifting the pen (the dabs still queued, the undo step)
++ double releaseDoneMs = 0; // until the stroke has ended (predictive strokes: the solver thread's last dabs on screen)
+ size_t dabs = 0, samples = 0;
+ std::vector<double> frameMs, lagMs, lagPx;
++ std::vector<double> previewLagPx; // the predictive preview's head behind the pointer (the surface's without it)
+ };
+
+ struct SizeResult {
+ std::string label;
+ size_t triangles = 0, vertices = 0;
+ double buildSeconds = 0;
+ size_t ramBytes = 0, peakRamBytes = 0;
+ std::vector<PhaseResult> phases;
+ };
+
+ } // namespace
+
+ struct ProofState {
+ enum class Stage { Intro, Announce, Build, Settle, Phase, Finish, Results };
+ Stage stage = Stage::Intro;
+ bool cli = false, video = true, vsync = false;
+ double strokeSeconds = 6.0;
+ std::string jsonPath, videoPath;
+ std::vector<ProofMeshSize> sizes;
+ size_t sizeIndex = 0, phaseIndex = 0;
+ std::vector<PhaseSpec> phases;
+ std::vector<SizeResult> results;
+ double stageStart = 0, lastFrame = 0, lastSample = 0;
+ // The stroke
+ float cx = 0, cy = 0, R = 0;
+ struct Sample {
+ double t;
+ glm::vec2 p;
+ double s; // path length so far
+ };
+ std::vector<Sample> samples;
+ std::vector<glm::vec2> dabs;
+ size_t sent = 1; // samples handed to onMouseMove (the first went to onMouseDown)
+ bool pressed = false;
++ bool releasing = false; // let go: the phase ends with the stroke (predictive strokes finish after the release)
++ double releaseAt = 0;
+ // Live HUD values
+ std::string hudTitle, hudLine2, hudLine3;
+ std::string error;
+ // Video
+ VideoWriter writer;
+ GLuint pbo[3] = {0, 0, 0};
+ double pboTime[3] = {0, 0, 0};
+ int pboW = 0, pboH = 0, pboNext = 0, pboFilled = 0;
+ Json hardware;
+ std::string gpu;
+ bool written = false;
+ // The scene before, restored by the results window's Close.
+ float radiusBefore = 60, strengthBefore = 0.5f;
+ BrushType brushBefore = BrushType::Standard;
+ };
+
+ namespace {
+
+ glm::vec2 strokePoint(const ProofState& p, double u) {
+ // A figure eight across the front of the model, three times round.
+ const double phi = 2.0 * 3.14159265358979 * 3.0 * u;
+ return {p.cx + p.R * 1.25f * float(std::sin(phi)), p.cy + p.R * 0.75f * float(std::sin(2.0 * phi))};
+ }
+
+ std::string isoDate() {
+ const std::time_t t = std::time(nullptr);
+ char buf[32];
+ std::strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%SZ", std::gmtime(&t));
+ return buf;
+ }
+
+ std::string fileStamp() {
+ const std::time_t t = std::time(nullptr);
+ char buf[32];
+ std::strftime(buf, sizeof buf, "%Y%m%d-%H%M%S", std::localtime(&t));
+ return buf;
+ }
+
+ std::vector<ProofMeshSize> parseSizes(const std::string& list) {
+ std::vector<ProofMeshSize> out;
+ std::stringstream ss(list);
+ for (std::string item; std::getline(ss, item, ',');) {
+ const double m = std::atof(item.c_str());
+ if (m <= 0) continue;
+ char label[32];
+ std::snprintf(label, sizeof label, "%gM", m);
+ out.push_back({m, label, nullptr, 150});
+ }
+ return out;
+ }
+
+ } // namespace
+
+ void App::startProofMode() {
+ if (proof_ && proof_->stage != ProofState::Stage::Results && proof_->stage != ProofState::Stage::Intro) return;
+ auto p = std::make_shared<ProofState>();
+ p->cli = options_.benchmark;
+ p->video = !options_.benchmarkNoVideo;
+ p->vsync = options_.benchmarkVsync;
+ p->strokeSeconds = std::max(1.0f, options_.benchmarkStrokeSeconds);
+ p->sizes = options_.benchmarkSizes.empty() ? proofDefaultSizes(availableMemoryBytes()) : parseSizes(options_.benchmarkSizes);
+ if (p->sizes.empty()) p->sizes = proofDefaultSizes(availableMemoryBytes());
+ const std::string stamp = fileStamp();
+ std::filesystem::path dir = std::filesystem::current_path();
+ if (!p->cli && !configDir_.empty()) dir = std::filesystem::path(std::u8string(configDir_.begin(), configDir_.end())) / "benchmarks";
+ std::error_code ec;
+ std::filesystem::create_directories(dir, ec);
+ auto u8 = [](const std::filesystem::path& x) {
+ const auto s = x.u8string();
+ return std::string(s.begin(), s.end());
+ };
+ p->jsonPath = !options_.benchmarkOut.empty() ? options_.benchmarkOut : u8(dir / ("sculptforge-benchmark-" + stamp + ".json"));
+ p->videoPath = !options_.benchmarkVideo.empty() ? options_.benchmarkVideo : u8(dir / ("sculptforge-benchmark-" + stamp + ".mp4"));
+ p->phases = {{"stroke", 60.0f, p->strokeSeconds}, {"large brush stroke", 240.0f, p->strokeSeconds}, {"orbit", 0.0f, 3.0}};
+ p->stage = p->cli ? ProofState::Stage::Announce : ProofState::Stage::Intro;
+ p->radiusBefore = radiusPx_;
+ p->strengthBefore = strength_;
+ p->brushBefore = brush_;
+ proof_ = p;
+ }
+
+ void App::drawProofUi() {
+ ProofState& p = *proof_;
+ const float sc = uiScale_;
+ if (p.stage == ProofState::Stage::Intro) {
+ ImGui::OpenPopup("Benchmark (proof mode)");
+ if (ImGui::BeginPopupModal("Benchmark (proof mode)", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
+ ImGui::PushTextWrapPos(520 * sc);
+ ImGui::TextWrapped("Proof mode measures how responsive sculpting is on this computer. For each mesh size it "
+ "builds a sphere with subdivision levels, then plays a scripted pen stroke through the "
+ "same code your pen goes through (240 samples a second), with a normal and a large brush, "
+ "and turns the view.");
+ ImGui::Spacing();
+ std::string sizes;
+ for (const auto& s : p.sizes) sizes += (sizes.empty() ? "" : ", ") + s.label;
+ ImGui::Text("Meshes: %s triangles", sizes.c_str());
+ ImGui::TextDisabled("(100M runs when free memory allows: %.1f GB free now)", double(availableMemoryBytes()) / double(1u << 30));
+ ImGui::Spacing();
+ ImGui::TextWrapped("A live display shows the frame rate, frame times (median, 95th, 99th percentile), how far "
+ "the stroke trails the pointer, and memory. The result is saved as JSON beside a video "
+ "of the run:");
+ ImGui::TextDisabled("%s", p.jsonPath.c_str());
+ ImGui::Checkbox("Record a video of the run (needs ffmpeg)", &p.video);
+ ImGui::Checkbox("Keep vertical sync on (frame rate capped at the display's)", &p.vsync);
+ ImGui::Spacing();
+ ImGui::TextColored(theme::accent, "The current scene is replaced. Save your work first.");
+ ImGui::TextDisabled("Press Esc to stop the run.");
+ ImGui::PopTextWrapPos();
+ if (ImGui::Button("Start")) {
+ p.stage = ProofState::Stage::Announce;
+ ImGui::CloseCurrentPopup();
+ }
+ ImGui::SameLine();
+ if (ImGui::Button("Cancel")) {
+ ImGui::CloseCurrentPopup();
+ proof_.reset();
+ }
+ ImGui::EndPopup();
+ }
+ return;
+ }
+ if (p.stage == ProofState::Stage::Results) {
+ ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
+ bool open = true;
+ if (ImGui::Begin("Benchmark results", &open, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse)) {
+ if (!p.error.empty()) ImGui::TextColored(theme::danger, "%s", p.error.c_str());
+ if (ImGui::BeginTable("##proof", 7, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg)) {
+ for (const char* h : {"Mesh", "Phase", "fps", "frame p50", "frame p95", "frame p99", "trails pointer p50 / p95"})
+ ImGui::TableSetupColumn(h);
+ ImGui::TableHeadersRow();
+ for (const SizeResult& r : p.results)
+ for (const PhaseResult& ph : r.phases) {
+ const Percentiles f = percentiles(ph.frameMs), l = percentiles(ph.lagMs), lp = percentiles(ph.lagPx);
+ ImGui::TableNextRow();
+ ImGui::TableNextColumn();
+ ImGui::Text("%s", r.label.c_str());
+ ImGui::TableNextColumn();
+ ImGui::Text("%s", ph.name.c_str());
+ ImGui::TableNextColumn();
+ ImGui::Text("%.0f", ph.seconds > 0 ? double(ph.frameMs.size()) / ph.seconds : 0.0);
+ ImGui::TableNextColumn();
+ ImGui::Text("%.1f ms", f.p50);
+ ImGui::TableNextColumn();
+ ImGui::Text("%.1f ms", f.p95);
+ ImGui::TableNextColumn();
+ ImGui::Text("%.1f ms", f.p99);
+ ImGui::TableNextColumn();
+ if (ph.lagMs.empty()) ImGui::TextDisabled("-");
+ else ImGui::Text("%.0f / %.0f ms, %.0f / %.0f px", l.p50, l.p95, lp.p50, lp.p95);
+ }
+ ImGui::EndTable();
+ }
+ ImGui::TextDisabled("Result: %s", p.jsonPath.c_str());
+ if (p.video) ImGui::TextDisabled("Video: %s", p.videoPath.c_str());
+ if (ImGui::Button("Open folder")) {
+ const std::string dir = std::filesystem::path(p.jsonPath).parent_path().string();
+ SDL_OpenURL(("file://" + dir).c_str());
+ }
+ ImGui::SameLine();
+ if (ImGui::Button("How to share results")) SDL_OpenURL("https://sculptforge.app/benchmarks/");
+ ImGui::SameLine();
+ if (ImGui::Button("Close")) open = false;
+ }
+ ImGui::End();
+ if (!open) {
+ radiusPx_ = p.radiusBefore;
+ strength_ = p.strengthBefore;
+ brush_ = p.brushBefore;
+ proof_.reset();
+ }
+ return;
+ }
+ // The HUD, top left of the canvas (burned into the video: it is part of the frame).
+ const CanvasRect c = canvasRect();
+ ImDrawList* dl = ImGui::GetForegroundDrawList();
+ ImFont* font = ImGui::GetFont();
+ const float big = ImGui::GetFontSize() * 1.35f, small = ImGui::GetFontSize() * 1.05f;
+ const ImVec2 at(c.x + 14 * sc, c.y + 14 * sc);
+ const std::string brand = std::string("SculptForge ") + SCULPTFORGE_VERSION + " (" + SF_GIT_COMMIT + ") - proof mode";
+ const char* lines[] = {brand.c_str(), p.hudTitle.c_str(), p.hudLine2.c_str(), p.hudLine3.c_str()};
+ float w = 0, h = 0;
+ for (int i = 0; i < 4; ++i) {
+ const ImVec2 s = font->CalcTextSizeA(i == 1 ? big : small, 1e9f, 0.0f, lines[i]);
+ w = std::max(w, s.x);
+ h += s.y + 3 * sc;
+ }
+ dl->AddRectFilled(ImVec2(at.x - 10 * sc, at.y - 8 * sc), ImVec2(at.x + w + 10 * sc, at.y + h + 6 * sc), IM_COL32(12, 12, 14, 215), 6 * sc);
+ float y = at.y;
+ for (int i = 0; i < 4; ++i) {
+ const float size = i == 1 ? big : small;
+ dl->AddText(font, size, ImVec2(at.x, y), i == 0 ? theme::u32(theme::textDim) : i == 1 ? theme::u32(theme::textBright) : theme::u32(theme::text), lines[i]);
+ y += font->CalcTextSizeA(size, 1e9f, 0.0f, lines[i]).y + 3 * sc;
+ }
+ if (p.pressed && !p.samples.empty()) { // where the pointer is: a small cross the stroke follows
+ const glm::vec2 q = p.samples.back().p;
+ dl->AddLine(ImVec2(q.x - 7 * sc, q.y), ImVec2(q.x + 7 * sc, q.y), theme::u32(theme::accent), 2 * sc);
+ dl->AddLine(ImVec2(q.x, q.y - 7 * sc), ImVec2(q.x, q.y + 7 * sc), theme::u32(theme::accent), 2 * sc);
+ }
+ }
+
+ void App::proofBeforeSwap(int fbW, int fbH) {
+ ProofState& p = *proof_;
+ using Stage = ProofState::Stage;
+ if (p.stage == Stage::Intro || p.stage == Stage::Results) return;
+ const double now = nowSeconds();
+ activeUntil_ = std::max(activeUntil_, double(SDL_GetTicksNS()) * 1e-9 + 0.5); // keep the loop drawing
+ // Esc stops the run (the real pointer is kept out of the scripted stroke, the keyboard is not).
+ if (const bool* keys = SDL_GetKeyboardState(nullptr); keys && keys[SDL_SCANCODE_ESCAPE] && p.stage != Stage::Finish) {
+ p.error = "Stopped with Esc: the results are partial";
+ if (p.pressed) onMouseUp();
+ p.pressed = false;
+ strokeProbe_ = nullptr;
+ p.stage = Stage::Finish;
+ }
+
+ // The frame about to be shown: into the video (asynchronously, through a ring of pixel buffers).
+ if (p.video && p.stage != Stage::Announce && p.stage != Stage::Build) {
+ const int w = fbW & ~1, h = fbH & ~1;
+ if (!p.writer.running() && p.error.find("video") == std::string::npos) {
+ if (p.writer.start(p.videoPath, w, h)) {
+ p.pboW = w, p.pboH = h;
+ gl::GenBuffers(3, p.pbo);
+ for (GLuint b : p.pbo) {
+ gl::BindBuffer(kPixelPackBuffer, b);
+ gl::BufferData(kPixelPackBuffer, GLsizeiptr(size_t(w) * size_t(h) * 4), nullptr, kStreamRead);
+ }
+ gl::BindBuffer(kPixelPackBuffer, 0);
+ } else {
+ p.error = "The video couldn't be recorded (ffmpeg missing?)";
+ p.video = false;
+ }
+ }
+ if (p.writer.running() && w == p.pboW && h == p.pboH) {
+ const int slot = p.pboNext;
+ if (p.pboFilled >= 3) { // the oldest read is done by now: hand it to the encoder
+ gl::BindBuffer(kPixelPackBuffer, p.pbo[slot]);
+ if (const void* data = gl::MapBufferRange(kPixelPackBuffer, 0, GLsizeiptr(size_t(w) * size_t(h) * 4), kMapReadBit)) {
+ std::vector<uint8_t> rgba(size_t(w) * size_t(h) * 4);
+ std::memcpy(rgba.data(), data, rgba.size());
+ gl::UnmapBuffer(kPixelPackBuffer);
+ p.writer.push(p.pboTime[slot], std::move(rgba));
+ }
+ }
+ gl::BindFramebuffer(GL_READ_FRAMEBUFFER, 0);
+ gl::BindBuffer(kPixelPackBuffer, p.pbo[slot]);
+ gl::PixelStorei(GL_PACK_ALIGNMENT, 1);
+ gl::ReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
+ gl::BindBuffer(kPixelPackBuffer, 0);
+ p.pboTime[slot] = now;
+ p.pboNext = (slot + 1) % 3;
+ p.pboFilled = std::min(p.pboFilled + 1, 3);
+ }
+ }
+
+ const double frameMs = (now - p.lastFrame) * 1000.0;
+ p.lastFrame = now;
+ const CanvasRect c = canvasRect();
+ auto beginPhase = [&] {
+ const PhaseSpec& spec = p.phases[p.phaseIndex];
+ SizeResult& r = p.results.back();
+ r.phases.push_back({});
+ r.phases.back().name = spec.name;
+ r.phases.back().radiusPx = spec.radiusPx;
+ p.stageStart = p.lastFrame = nowSeconds(); // (not counting what the last phase's release cost)
+ p.samples.clear();
+ p.dabs.clear();
+ p.sent = 1;
+ if (spec.radiusPx > 0) {
+ brush_ = BrushType::Standard;
+ doc_.activeBrush = -1;
+ paintMode_ = false;
+ radiusPx_ = spec.radiusPx;
+ strength_ = 0.35f;
+ p.cx = c.x + c.w * 0.5f;
+ p.cy = c.y + c.h * 0.5f;
+ p.R = 0.26f * std::min(c.w, c.h);
+ const glm::vec2 q = strokePoint(p, 0.0);
+ p.samples.push_back({now, q, 0.0});
+ p.lastSample = now;
+ strokeProbe_ = &p.dabs;
+ onMouseDown(q.x, q.y, SDL_BUTTON_LEFT);
+ p.pressed = drag_ == Drag::Stroke;
+ if (!p.pressed) {
+ strokeProbe_ = nullptr;
+ p.error = "No stroke began on the " + r.label + " mesh (nothing under the pointer)";
+ }
+ }
+ p.stage = Stage::Phase;
+ };
+ auto nextPhase = [&] {
+ SizeResult& r = p.results.back();
- r.phases.back().seconds = now - p.stageStart;
++ if (r.phases.back().seconds == 0) r.phases.back().seconds = now - p.stageStart; // (a stroke set it at its release)
+ ++p.phaseIndex;
+ if (p.phaseIndex < p.phases.size()) {
+ beginPhase();
+ return;
+ }
+ r.ramBytes = residentBytes();
+ r.peakRamBytes = peakResidentBytes();
+ ++p.sizeIndex;
+ p.stage = p.sizeIndex < p.sizes.size() ? Stage::Announce : Stage::Finish;
+ };
+
+ switch (p.stage) {
+ case Stage::Announce: { // show "Building ..." for one frame, then build
+ if (p.sizeIndex == 0 && p.results.empty()) {
+ if (lightbox_.open()) lightbox_.toggle(); // the canvas clear (it opens at start-up)
+ if (!p.vsync) SDL_GL_SetSwapInterval(0);
+ p.gpu = std::string(reinterpret_cast<const char*>(gl::GetString(GL_RENDERER))) + ", OpenGL " +
+ reinterpret_cast<const char*>(gl::GetString(GL_VERSION));
+ p.hardware = describeHardware();
+ p.hardware.set("gpu", p.gpu);
+ int ww = 0, wh = 0;
+ SDL_GetWindowSize(window_, &ww, &wh);
+ Json win = Json::array();
+ win.push(fbW);
+ win.push(fbH);
+ p.hardware.set("framebuffer", win);
+ p.hardware.set("ui_scale", double(uiScale_));
+ }
+ const ProofMeshSize& s = p.sizes[p.sizeIndex];
+ p.hudTitle = "Building a " + s.label + " triangle mesh...";
+ p.hudLine2 = "mesh " + std::to_string(p.sizeIndex + 1) + " of " + std::to_string(p.sizes.size());
+ p.hudLine3 = p.gpu.empty() ? std::string() : p.gpu;
+ p.stage = Stage::Build;
+ break;
+ }
+ case Stage::Build: {
+ const ProofMeshSize& s = p.sizes[p.sizeIndex];
+ doc_.setMesh(makeIcosphere(1)); // free the last mesh (and its history) first
+ resetPeakResidentBytes();
+ const double t0 = nowSeconds();
+ const size_t tris = size_t(s.millions * 1e6);
+ Mesh m = s.build ? s.build(tris) : makeBenchSphere(tris);
+ SizeResult r;
+ r.label = s.label;
+ r.triangles = m.triangleCount();
+ r.vertices = m.vertexCount();
+ doc_.setMesh(std::move(m), "Benchmark");
+ r.buildSeconds = nowSeconds() - t0;
+ p.results.push_back(r);
+ camera_.frame(sceneBounds());
+ camera_.yaw = 0.0f;
+ camera_.pitch = 0.0f;
+ p.stageStart = nowSeconds();
+ p.phaseIndex = 0;
+ p.stage = Stage::Settle;
+ char buf[160];
+ std::snprintf(buf, sizeof buf, "%s triangles (%.1fM vertices), built in %.1f s", r.label.c_str(), double(r.vertices) / 1e6, r.buildSeconds);
+ p.hudTitle = buf;
+ p.hudLine2 = "settling (the first upload to the GPU)";
+ break;
+ }
+ case Stage::Settle:
+ if (now - p.stageStart > 1.0 && !backgroundBusy()) beginPhase();
+ break;
+ case Stage::Phase: {
+ const PhaseSpec& spec = p.phases[p.phaseIndex];
+ PhaseResult& ph = p.results.back().phases.back();
++ if (p.releasing) { // (frames while the last dabs land aren't the stroke's)
++ if (doc_.sculptor.strokeActive()) break;
++ p.releasing = false;
++ ph.releaseDoneMs = (nowSeconds() - p.releaseAt) * 1000.0;
++ strokeProbe_ = nullptr;
++ ph.dabs = p.dabs.size();
++ nextPhase();
++ break;
++ }
+ if (ph.frameMs.size() < 1000000 && now - p.stageStart > 0.0) ph.frameMs.push_back(frameMs);
+ const double u = std::min(1.0, (now - p.stageStart) / spec.seconds);
+ if (spec.radiusPx <= 0) { // orbit: the view turns, as a drag would
+ camera_.yaw = float(6.2831853 * u);
+ perf_.framesStill = 0;
+ } else if (p.pressed) {
+ // The pointer samples since the last frame (240 a second), in the order a tablet sends them.
+ while (p.lastSample + 1.0 / kPointerHz <= now) {
+ p.lastSample += 1.0 / kPointerHz;
+ const double su = std::min(1.0, (p.lastSample - p.stageStart) / spec.seconds);
+ const glm::vec2 q = strokePoint(p, su);
+ p.samples.push_back({p.lastSample, q, p.samples.back().s + double(glm::length(q - p.samples.back().p))});
+ ++ph.samples;
+ }
+ // How far the stroke on screen (the newest dab in this frame) trails the pointer (the newest sample).
+ if (!p.dabs.empty()) {
+ const glm::vec2 d = p.dabs.back();
+ size_t best = p.samples.size() - 1;
+ float bestDist = 1e30f;
+ for (size_t i = p.samples.size(); i-- > 0 && p.samples.size() - i < 2000;) {
+ const float dist = glm::length(p.samples[i].p - d);
+ if (dist < bestDist) bestDist = dist, best = i;
+ }
+ ph.lagMs.push_back((now - p.samples[best].t) * 1000.0);
+ ph.lagPx.push_back(p.samples.back().s - p.samples[best].s);
++ // The same for what is on screen ahead of the solved surface: the predictive preview's head.
++ const glm::vec2 h = ghostHeadValid_ ? ghostHead_ : d;
++ size_t near = p.samples.size() - 1;
++ float nearDist = 1e30f;
++ for (size_t i = p.samples.size(); i-- > 0 && p.samples.size() - i < 2000;) {
++ const float dist = glm::length(p.samples[i].p - h);
++ if (dist < nearDist) nearDist = dist, near = i;
++ }
++ ph.previewLagPx.push_back(p.samples.back().s - p.samples[near].s);
+ }
+ // ... then the new samples go to the input handler, as the next frame's events would.
+ for (; p.sent < p.samples.size(); ++p.sent)
+ onMouseMove(p.samples[p.sent].p.x, p.samples[p.sent].p.y, 0.0f, 0.0f, false);
+ if (u >= 1.0) {
+ const double up = nowSeconds();
+ onMouseUp(); // places the dabs still waiting, ends the stroke (undo step, timeline)
+ ph.releaseMs = (nowSeconds() - up) * 1000.0;
+ p.pressed = false;
- strokeProbe_ = nullptr;
- ph.dabs = p.dabs.size();
+ ph.pathPx = p.samples.back().s;
- nextPhase();
++ ph.seconds = now - p.stageStart;
++ p.releasing = true; // (the phase ends when the stroke has: see the top of this stage)
++ p.releaseAt = up;
+ break;
+ }
+ } else {
+ nextPhase(); // a stroke that couldn't begin
+ break;
+ }
+ if (u >= 1.0 && spec.radiusPx <= 0) {
+ nextPhase();
+ break;
+ }
+ // Live numbers over the last second.
+ std::vector<double> recentF, recentL, recentP;
+ double span = 0;
+ for (size_t i = ph.frameMs.size(); i-- > 0 && span < 1000.0;) {
+ span += ph.frameMs[i];
+ recentF.push_back(ph.frameMs[i]);
+ }
+ for (size_t i = ph.lagMs.size(); i-- > 0 && recentL.size() < recentF.size();) {
+ recentL.push_back(ph.lagMs[i]);
+ recentP.push_back(ph.lagPx[i]);
+ }
+ const Percentiles f = percentiles(recentF), l = percentiles(recentL), lp = percentiles(recentP);
+ const SizeResult& r = p.results.back();
+ char buf[256];
+ std::snprintf(buf, sizeof buf, "%s triangles - %s%s", r.label.c_str(), spec.name,
+ spec.radiusPx > 0 ? (" (" + std::to_string(int(spec.radiusPx)) + " px brush)").c_str() : "");
+ p.hudTitle = buf;
+ std::snprintf(buf, sizeof buf, "%.0f fps frame %.1f / %.1f / %.1f ms (p50 / p95 / p99)", span > 0 ? 1000.0 * double(recentF.size()) / span : 0.0,
+ f.p50, f.p95, f.p99);
+ p.hudLine2 = buf;
+ if (spec.radiusPx > 0)
+ std::snprintf(buf, sizeof buf, "stroke trails pointer %.0f ms / %.0f px (p95 %.0f ms) RAM %.1f GB %s", l.p50, lp.p50, l.p95,
+ double(residentBytes()) / double(1u << 30), p.vsync ? "vsync on" : "vsync off");
+ else
+ std::snprintf(buf, sizeof buf, "orbiting RAM %.1f GB %s", double(residentBytes()) / double(1u << 30), p.vsync ? "vsync on" : "vsync off");
+ p.hudLine3 = buf;
+ break;
+ }
+ case Stage::Finish: {
+ if (!p.vsync) SDL_GL_SetSwapInterval(1);
+ if (p.writer.running()) {
+ if (!p.writer.finish()) p.error += (p.error.empty() ? "" : "; ") + std::string("the video couldn't be written");
+ gl::DeleteBuffers(3, p.pbo);
+ }
+ Json root = Json::object();
+ root.set("schema", "sculptforge-benchmark/1");
+ Json app = Json::object();
+ app.set("version", SCULPTFORGE_VERSION);
+ app.set("commit", SF_GIT_COMMIT);
+ root.set("sculptforge", app);
+ root.set("date", isoDate());
+ root.set("hardware", p.hardware);
+ Json settings = Json::object();
+ settings.set("vsync", p.vsync);
+ settings.set("video", p.video);
+ settings.set("pointer_hz", kPointerHz);
+ settings.set("stroke_seconds", p.strokeSeconds);
+ settings.set("input", "scripted pointer samples into App::onMouseMove (the mouse / pen handler)");
+ settings.set("lag", "pointer sample time to SwapWindow of the frame showing its dab (display scan-out not included)");
+ root.set("settings", settings);
+ Json runs = Json::array();
+ for (const SizeResult& r : p.results) {
+ Json run = Json::object();
+ run.set("label", r.label);
+ run.set("triangles", double(r.triangles));
+ run.set("vertices", double(r.vertices));
+ run.set("build_seconds", std::round(r.buildSeconds * 100) / 100);
+ run.set("ram_mb", double(r.ramBytes >> 20));
+ run.set("peak_ram_mb", double(r.peakRamBytes >> 20));
+ Json phases = Json::array();
+ for (const PhaseResult& ph : r.phases) {
+ Json j = Json::object();
+ j.set("name", ph.name);
+ if (ph.radiusPx > 0) j.set("brush_radius_px", double(ph.radiusPx));
+ j.set("seconds", std::round(ph.seconds * 100) / 100);
+ j.set("frames", double(ph.frameMs.size()));
+ j.set("fps", ph.seconds > 0 ? std::round(double(ph.frameMs.size()) / ph.seconds * 10) / 10 : 0.0);
+ j.set("frame_ms", percentilesJson(percentiles(ph.frameMs)));
+ if (ph.radiusPx > 0) {
+ j.set("lag_ms", percentilesJson(percentiles(ph.lagMs)));
+ j.set("lag_px", percentilesJson(percentiles(ph.lagPx)));
+ j.set("dabs", double(ph.dabs));
+ j.set("pointer_samples", double(ph.samples));
+ j.set("path_px", std::round(ph.pathPx));
+ j.set("release_ms", std::round(ph.releaseMs * 10) / 10);
++ j.set("release_done_ms", std::round(ph.releaseDoneMs * 10) / 10);
++ j.set("preview_lag_px", percentilesJson(percentiles(ph.previewLagPx)));
+ j.set("pointer_speed_px_s", ph.seconds > 0 ? std::round(ph.pathPx / ph.seconds) : 0.0);
+ }
+ phases.push(j);
+ }
+ run.set("phases", phases);
+ runs.push(run);
+ }
+ root.set("runs", runs);
+ if (p.video) root.set("video", std::filesystem::path(p.videoPath).filename().string());
+ if (!p.error.empty()) root.set("notes", p.error);
+ {
+ std::ofstream f(std::filesystem::path(std::u8string(p.jsonPath.begin(), p.jsonPath.end())));
+ f << root.dump(true) << "\n";
+ if (!f) p.error += (p.error.empty() ? "" : "; ") + ("couldn't write " + p.jsonPath);
+ }
+ // A summary on the terminal too.
+ std::printf("SculptForge %s (%s) proof mode on %s | %s\n", SCULPTFORGE_VERSION, SF_GIT_COMMIT,
+ root["hardware"]["cpu"].asString().c_str(), p.gpu.c_str());
+ for (const SizeResult& r : p.results)
+ for (const PhaseResult& ph : r.phases) {
+ const Percentiles f = percentiles(ph.frameMs), l = percentiles(ph.lagMs), lp = percentiles(ph.lagPx);
+ std::printf(" %-5s %-19s %6.1f fps frame p50 %5.1f p95 %5.1f p99 %5.1f ms", r.label.c_str(), ph.name.c_str(),
+ ph.seconds > 0 ? double(ph.frameMs.size()) / ph.seconds : 0.0, f.p50, f.p95, f.p99);
+ if (ph.radiusPx > 0)
- std::printf(" trails %4.0f ms / %4.0f px (p95 %4.0f ms / %4.0f px), release %.0f ms", l.p50, lp.p50, l.p95, lp.p95, ph.releaseMs);
++ std::printf(" trails %4.0f ms / %4.0f px (p95 %4.0f ms / %4.0f px), preview %4.0f px, release %.0f ms (done %.0f ms)",
++ l.p50, lp.p50, l.p95, lp.p95, percentiles(ph.previewLagPx).p50, ph.releaseMs, ph.releaseDoneMs);
+ std::printf("\n");
+ }
+ std::printf("Result: %s%s%s\n", p.jsonPath.c_str(), p.video ? "\nVideo: " : "", p.video ? p.videoPath.c_str() : "");
+ if (!p.error.empty()) std::printf("Note: %s\n", p.error.c_str());
+ std::fflush(stdout);
+ p.stage = Stage::Results;
+ if (p.cli) running_ = false;
+ status_ = "Benchmark finished: " + p.jsonPath;
+ break;
+ }
+ default:
+ break;
+ }
+ }
+
+ } // namespace sf
diff --cc src/core/Sculpt.h
index f4fe0d17,cd8bceed..fbfef624
--- a/src/core/Sculpt.h
+++ b/src/core/Sculpt.h
@@@ -125,21 -118,12 +125,27 @@@ public
// DragDot; restoreStroke) put positions back, not topology. restoreStroke holds it too.
void holdTopology() { topologyHeld_ = true; }
+ // The cavity term (Mesh::curvatureAt) of every vertex whose normal this stroke's dabs updated, by vertex,
+ // worked out with the normals (the renderer packs it instead of walking the rings again); null outside a
+ // stroke. Entries of other vertices are stale.
+ const float* strokeCurvature() const { return active_ && !curvature_.empty() ? curvature_.data() : nullptr; }
+
+ // Draft strokes (Preferences > Performance > Draft Strokes): when set before beginStroke (it asks once), dabs move the vertices
+ // and refit the BVH but leave the normals and the cavity term as they were (the brushes that read normals see
+ // the stroke-start ones, so the result differs slightly from a full stroke); the vertices are only marked
+ // for the GPU. flushDraft works out every normal and cavity term the stroke touched, once (the app calls
+ // it before endStroke). Not with dynamic topology.
+ bool draftStrokes = false;
+ bool draftActive() const { return draft_; }
+ bool draftPending() const { return draft_ && !draftLeaves_.empty(); }
+ void flushDraft(Mesh& mesh, const BVH& bvh);
+
+ // Micro level timings (findMs, kernelMs, stitchMs, points) of the current stroke (core/Micro.h).
+ const MicroStroke& microStroke() const { return micro_; }
+ // Move on a micro level: false (default) deforms the base cage and the detail rides along; true moves the
+ // micro displacement along its normals instead.
+ bool microMoveAlongNormals = false;
+ MicroStroke& microStroke() { return micro_; }
// Mirror sign vectors for the enabled symmetry axes (always starts with (1,1,1)).
static std::vector<glm::vec3> mirrors(Symmetry sym);
diff --cc src/render/GL.h
index 7d523c6a,2e1b9b42..e82cd41f
--- a/src/render/GL.h
+++ b/src/render/GL.h
@@@ -174,10 -178,9 +178,11 @@@ constexpr GLbitfield GL_COLOR_BUFFER_BI
X(void, ActiveTexture, GLenum) \
X(void, GetIntegerv, GLenum, GLint*) \
X(void, Uniform1i, GLint, GLint) \
+ X(void, Uniform1iv, GLint, GLsizei, const GLint*) \
X(void, Uniform1f, GLint, GLfloat) \
X(void, Uniform2f, GLint, GLfloat, GLfloat) \
+ X(void, Uniform2i, GLint, GLint, GLint) \
+ X(void, Uniform2iv, GLint, GLsizei, const GLint*) \
X(void, DisableVertexAttribArray, GLuint) \
X(void, VertexAttrib1f, GLuint, GLfloat) \
X(void, VertexAttrib3f, GLuint, GLfloat, GLfloat, GLfloat) \
diff --cc src/render/Renderer.cpp
index 771ce273,198b0db3..69bfe305
--- a/src/render/Renderer.cpp
+++ b/src/render/Renderer.cpp
@@@ -633,16 -574,18 +688,20 @@@ bool Renderer::init(std::string& error
const Renderer::MeshProgram* Renderer::meshProgram(int features) {
if (features & (kTextured | kNormalMap)) features |= kTextured | kPrim;
- if (features & kMicro) features &= kMicro | kFlat; // (micro levels: no per-vertex paint or per-triangle data)
-- MeshProgram& p = programs_[features & 63];
++ // (micro levels: no per-vertex paint, per-triangle data or predictive preview)
++ if (features & kMicro) features &= kMicro | kFlat;
++ MeshProgram& p = programs_[features & 127];
if (p.id) return &p;
std::string prefix = "#version 330 core\n";
+ if (features & kMicro) prefix += "#define MICRO\n";
if (features & kPaint) prefix += "#define PAINT\n";
if (features & kPrim) prefix += "#define PRIM\n";
if (features & kTextured) prefix += "#define TEXTURED\n";
if (features & kNormalMap) prefix += "#define NORMALMAP\n";
if (features & kFlat) prefix += "#define FLAT\n";
+ if (features & kGhost) prefix += "#define GHOST\n";
- const std::string vs = prefix + kMeshVS, fs = prefix + kMeshFS, gs = prefix + kMeshGS;
+ const std::string vs = prefix + ((features & kMicro) ? microVertexShaderSource() : kMeshVS), fs = prefix + kMeshFS,
+ gs = prefix + kMeshGS;
p.id = link(vs.c_str(), fs.c_str(), programError_, nullptr, (features & kTextured) ? gs.c_str() : nullptr);
if (!p.id) return nullptr;
auto at = [&](const char* name) { return gl::GetUniformLocation(p.id, name); };
@@@ -2471,326 -2416,6 +2575,326 @@@ void Renderer::drawSlot(const MeshSlot
gl::Disable(GL_CULL_FACE);
}
+// ---------------------------------------------------------------------------
+// Strokes on heavy meshes: the ghost and the two-part upload (app/AsyncStroke.cpp)
+// ---------------------------------------------------------------------------
+
+void Renderer::setGhost(uint32_t id, const GhostStroke& ghost) {
+ ghostId_ = id;
+ ghost_.kind = ghost.kind;
+ ghost_.invert = ghost.invert;
+ ghost_.focal = ghost.focal;
+ ghost_.edge = ghost.edge;
+ ghost_.dabs.assign(ghost.dabs.begin(), ghost.dabs.begin() + std::ptrdiff_t(std::min(ghost.dabs.size(), GhostStroke::kMaxDabs)));
+}
+
+void Renderer::setGhostUniforms(const MeshProgram& p) {
+ glm::vec4 a[GhostStroke::kMaxDabs], b[GhostStroke::kMaxDabs], c[GhostStroke::kMaxDabs];
+ glm::vec4 bound[GhostStroke::kMaxMirrors];
+ GLint range[GhostStroke::kMaxMirrors * 2];
+ int groups = 0;
+ const size_t n = ghost_.dabs.size();
+ for (size_t i = 0; i < n; ++i) {
+ const GhostDab& d = ghost_.dabs[i];
+ a[i] = glm::vec4(d.center, d.radius);
+ b[i] = glm::vec4(d.normal, d.strength);
+ c[i] = glm::vec4(d.areaCenter, d.weight);
+ const bool next = i == 0 || d.mirror != ghost_.dabs[i - 1].mirror;
+ if (next) {
+ if (groups == int(GhostStroke::kMaxMirrors)) break;
+ range[groups * 2] = range[groups * 2 + 1] = GLint(i);
+ ++groups;
+ }
+ range[groups * 2 - 1] = GLint(i + 1);
+ }
+ // Each run's bounding sphere (around its dabs' spheres, a little wider: the moves reach out a little).
+ for (int g = 0; g < groups; ++g) {
+ AABB box;
+ for (GLint i = range[g * 2]; i < range[g * 2 + 1]; ++i) {
+ box.expand(glm::vec3(a[i]) - glm::vec3(a[i].w));
+ box.expand(glm::vec3(a[i]) + glm::vec3(a[i].w));
+ }
+ bound[g] = glm::vec4(box.center(), glm::length(box.max - box.min) * 0.5f * 1.1f);
+ }
+ gl::Uniform1i(p.ghostGroups, groups);
+ gl::Uniform4fv(p.ghostBound, groups, glm::value_ptr(bound[0]));
+ gl::Uniform2iv(p.ghostRange, groups, range);
+ gl::Uniform4fv(p.ghostA, GLsizei(n), glm::value_ptr(a[0]));
+ gl::Uniform4fv(p.ghostB, GLsizei(n), glm::value_ptr(b[0]));
+ gl::Uniform4fv(p.ghostC, GLsizei(n), glm::value_ptr(c[0]));
+ gl::Uniform2i(p.ghostKind, GLint(ghost_.kind), ghost_.invert ? 1 : 0);
+ gl::Uniform1f(p.ghostFocal, ghost_.focal);
+ gl::Uniform1f(p.ghostEdge, ghost_.edge);
+}
+
+bool Renderer::prepareStrokeUpload(uint32_t id, Mesh& mesh, StrokeUpload& out, const float* curvature) {
+ out.id = id;
+ out.ready = false;
+ out.data.clear();
+ out.ranges.clear();
+ out.movedClusters.clear();
+ out.bounds.clear();
+ out.exactClusters.clear();
+ out.exactBounds.clear();
+ out.regrid = false;
+ out.packMs = out.boundsMs = 0.0;
+ const auto clock = std::chrono::steady_clock::now();
+ MeshSlot* found = static_cast<MeshSlot*>(out.slot); // (bindStrokeUpload: never the list from this thread)
+ if (!found || found->id != id) return false;
+ MeshSlot& s = *found;
+ const size_t nv = mesh.vertexCount();
+ // What only the regular sync handles: a new layout, faces, attributes appearing, dynamic topology, textures.
- if (s.fresh || s.outOfMemory || s.regrid || mesh.topologyDirty || mesh.facesDirty || nv != s.vertexCapacity ||
++ if (s.micro || s.fresh || s.outOfMemory || s.regrid || mesh.topologyDirty || mesh.facesDirty || nv != s.vertexCapacity ||
+ !mesh.changedTriangles.empty() || !s.patches.empty() || mesh.normals.size() != nv || s.hasUvs ||
+ s.hasColors != (nv > 0 && mesh.colors.size() == nv) || s.hasMask != (nv > 0 && mesh.mask.size() == nv))
+ return false;
+ std::vector<std::pair<uint32_t, uint32_t>> runs;
+ s.order.dirtyRuns(mesh, runs);
+ if (runs.empty()) {
+ out.ready = true;
+ return true;
+ }
+ // The colours and mask of the dirty runs would go up too (a sculpt stroke doesn't change them; a stroke that
+ // does takes the regular sync).
+ const size_t ns = s.order.size();
+ const size_t nb = (ns + UploadOrder::kBlock - 1) / UploadOrder::kBlock;
+ const std::span<const uint32_t> order = s.order.fromGpu();
+ s.blockHash.resize(nb * 2, 0);
+ out.blockChanged.assign(nb, 0);
+ out.blockMoved.assign(nb, 0);
+ // Pieces of a few thousand slots packed in parallel, each at its offset in `data`.
+ constexpr uint32_t kPiece = 2048;
+ struct Piece {
+ uint32_t begin, end;
+ size_t offset;
+ };
+ std::vector<Piece> pieces;
+ const auto cut = [&] {
+ pieces.clear();
+ size_t total = 0;
+ for (const auto& [b, e] : runs)
+ for (uint32_t c = b; c < e; c += kPiece) {
+ const uint32_t ce = std::min(e, c + kPiece);
+ pieces.push_back({c, ce, total});
+ total += ce - c;
+ }
+ out.data.resize(total);
+ };
+ cut();
+ std::atomic<bool> outside{false};
+ std::vector<uint64_t> hashes(nb * 2, 0); // (written per block, then compared: a failed prepare keeps the old)
+ std::vector<AABB> boxes(nb);
+ s.blockBox.resize(nb);
+ PositionGrid grid = s.grid;
+ bool everything = false;
+ const auto pack = [&] {
+ 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;
+ bool inside = true;
+ uint64_t hp = 0, hn = 0;
+ AABB box;
+ for (uint32_t i = pc.begin; i < pc.end; ++i) {
+ const uint32_t v = order[i];
+ PackedVertex pv{};
+ if (v < nv) {
+ inside &= packVertex(grid, mesh.positions[v], mesh.normals[v], curvature ? curvature[v] : curvatureAt(mesh, v), pv);
+ box.expand(mesh.positions[v]);
+ }
+ dst[i - pc.begin] = pv;
+ hp = (hp ^ (uint64_t(pv.pos[0]) | uint64_t(pv.pos[1]) << 32)) * 0x100000001B3ull + i;
+ hn = (hn ^ pv.normal) * 0x100000001B3ull + i;
+ if ((i + 1) % UploadOrder::kBlock == 0 || i + 1 == pc.end) {
+ const size_t g = i >> UploadOrder::kBlockShift;
+ hashes[g * 2] = hp;
+ hashes[g * 2 + 1] = hn;
+ out.blockMoved[g] = everything || s.blockHash[g * 2] != hp;
+ out.blockChanged[g] = out.blockMoved[g] || s.blockHash[g * 2 + 1] != hn;
+ boxes[g] = box;
+ hp = hn = 0;
+ box = AABB();
+ }
+ }
+ if (!inside) outside.store(true, std::memory_order_relaxed);
+ }
+ }, 1, 2);
+ };
+ pack();
+ if (outside.load()) {
+ // A vertex left the position grid: a new one round the mesh, and every vertex packed again, here on this
+ // thread (the GL thread keeps drawing with the old grid and data until the commit swaps both; the
+ // regular sync did this in the frame, a stall of seconds at 33M triangles).
+ grid = PositionGrid::around(meshBounds(mesh));
+ runs.assign(1, {0u, uint32_t(ns)});
+ cut();
+ everything = true;
+ outside = false;
+ pack();
+ if (outside.load()) return false; // (can't happen: the grid holds the mesh)
+ out.regrid = true;
+ out.grid = grid;
+ }
+ out.packMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - clock).count();
+ // The changed blocks' GPU ranges and where they are in `data`.
+ for (const Piece& pc : pieces)
+ for (uint32_t b = pc.begin; b < pc.end;) {
+ const uint32_t e = std::min(pc.end, (b & ~(UploadOrder::kBlock - 1)) + UploadOrder::kBlock);
+ const size_t g = b >> UploadOrder::kBlockShift;
+ s.blockBox[g] = boxes[g];
+ if (out.blockChanged[g]) {
+ s.blockHash[g * 2] = hashes[g * 2];
+ s.blockHash[g * 2 + 1] = hashes[g * 2 + 1];
+ const size_t offset = pc.offset + (b - pc.begin);
+ if (!out.ranges.empty() && out.ranges.back().end == b && out.ranges.back().offset +
+ (out.ranges.back().end - out.ranges.back().begin) == offset)
+ out.ranges.back().end = e;
+ else out.ranges.push_back({b, e, offset});
+ }
+ b = e;
+ }
+ // The clusters with a block that moved, and their culling bounds.
+ for (const auto& [b, e] : runs)
+ for (uint32_t g = b >> UploadOrder::kBlockShift; g < (e + UploadOrder::kBlock - 1) >> UploadOrder::kBlockShift; ++g) {
+ if (!out.blockMoved[g]) continue;
+ const uint32_t c = s.order.clusterOfSlot(g << UploadOrder::kBlockShift);
+ if (out.movedClusters.empty() || c > out.movedClusters.back()) out.movedClusters.push_back(c);
+ }
+ // Their quick bounds: a sphere round their blocks' boxes, no normal cone (never culled as facing away), the
+ // volume as it was (a stroke doesn't turn the mesh inside out); refineStrokeBounds makes them exact.
+ out.bounds.resize(out.movedClusters.size());
+ const auto layout = s.order.clusters();
+ for (size_t i = 0; i < out.movedClusters.size(); ++i) {
+ const uint32_t c = out.movedClusters[i];
+ AABB box;
+ for (uint32_t g = layout[c].firstVertex >> UploadOrder::kBlockShift,
+ ge = (layout[c].firstVertex + layout[c].vertexCount + UploadOrder::kBlock - 1) >> UploadOrder::kBlockShift;
+ g < ge && g < nb; ++g)
+ if (s.blockBox[g].valid()) box.expand(s.blockBox[g]);
+ ClusterBounds& cb = out.bounds[i];
+ cb = ClusterBounds();
+ if (box.valid()) {
+ cb.center = box.center();
+ cb.radius = glm::length(box.max - box.min) * 0.5f;
+ }
+ cb.coneAngle = -1.0f;
+ cb.volume = c < s.bounds.size() ? s.bounds[c].volume : 0.0;
+ }
+ mesh.clearDirty();
+ out.boundsMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - clock).count() - out.packMs;
+ out.ready = true;
+ return true;
+}
+
+void Renderer::commitStrokeUpload(StrokeUpload& up) {
+ if (!up.ready) return;
+ up.ready = false;
+ MeshSlot* found = nullptr;
+ for (MeshSlot& s : slots_)
+ if (s.id == up.id) found = &s;
+ if (!found) return;
+ MeshSlot& s = *found;
+ if (up.regrid) s.grid = up.grid; // (with every vertex, packed on it)
+ 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)),
+ GLsizeiptr(size_t(r.end - r.begin) * sizeof(PackedVertex)), up.data.data() + r.offset);
+ gl::BindBuffer(GL_ARRAY_BUFFER, 0);
+ }
+ if (!up.movedClusters.empty()) {
+ s.bounds.resize(s.order.clusters().size());
+ s.proxyStale.resize(s.bounds.size(), 1);
+ for (size_t i = 0; i < up.movedClusters.size(); ++i) {
+ s.bounds[up.movedClusters[i]] = up.bounds[i];
+ s.proxyStale[up.movedClusters[i]] = 1;
+ }
+ s.looseClusters.insert(s.looseClusters.end(), up.movedClusters.begin(), up.movedClusters.end());
+ s.looseMark.resize(s.bounds.size(), 0);
+ for (uint32_t c : up.movedClusters) s.looseMark[c] = 1;
+ }
+ if (up.exact) { // the stroke's end (refineStrokeBoundsInto): exact bounds for every cluster it moved
+ s.bounds.resize(s.order.clusters().size());
+ for (size_t i = 0; i < up.exactClusters.size(); ++i)
+ if (up.exactClusters[i] < s.bounds.size()) s.bounds[up.exactClusters[i]] = up.exactBounds[i];
+ s.looseClusters.clear();
+ std::fill(s.looseMark.begin(), s.looseMark.end(), 0);
+ }
+ if (!up.movedClusters.empty() || up.exact) {
+ s.box = AABB();
+ s.volume = 0.0;
+ for (const ClusterBounds& b : s.bounds) {
+ s.volume += b.volume;
+ if (b.radius >= 0.0f) {
+ s.box.expand(b.center - glm::vec3(b.radius));
+ s.box.expand(b.center + glm::vec3(b.radius));
+ }
+ }
+ }
+}
+
+void Renderer::setDraftNormals(uint32_t id) { draftId_ = id; }
+
+void Renderer::bindStrokeUpload(uint32_t id, StrokeUpload& up) {
+ up.slot = nullptr;
+ for (MeshSlot& s : slots_)
+ if (s.id == id) up.slot = &s;
+}
+
+void Renderer::refineStrokeBoundsInto(uint32_t id, const Mesh& mesh, StrokeUpload& up) {
+ up.exact = false;
+ up.exactClusters.clear();
+ up.exactBounds.clear();
+ MeshSlot* found = static_cast<MeshSlot*>(up.slot);
+ if (!found || found->id != id) return;
+ MeshSlot& s = *found;
+ const size_t nc = s.order.clusters().size();
+ if (s.fresh || mesh.topologyDirty || s.bounds.size() != nc) return;
+ // Those moved before and those this upload moves (the main thread doesn't touch the list while we run).
+ up.exactClusters = s.looseClusters;
+ up.exactClusters.insert(up.exactClusters.end(), up.movedClusters.begin(), up.movedClusters.end());
+ std::sort(up.exactClusters.begin(), up.exactClusters.end());
+ up.exactClusters.erase(std::unique(up.exactClusters.begin(), up.exactClusters.end()), up.exactClusters.end());
+ while (!up.exactClusters.empty() && up.exactClusters.back() >= nc) up.exactClusters.pop_back();
+ up.exactBounds.resize(up.exactClusters.size());
+ poolFor(up.exactClusters.size(), [&](size_t i0, size_t i1) {
+ for (size_t i = i0; i < i1; ++i) up.exactBounds[i] = clusterBounds(mesh, s.order, up.exactClusters[i]);
+ }, 1, 2);
+ up.exact = true;
+ up.ready = true;
+}
+
+void Renderer::refineStrokeBounds(uint32_t id, const Mesh& mesh) {
+ MeshSlot* found = nullptr;
+ for (MeshSlot& s : slots_)
+ if (s.id == id) found = &s;
+ if (!found) return;
+ std::fill(found->looseMark.begin(), found->looseMark.end(), 0);
+ if (found->looseClusters.empty()) return;
+ MeshSlot& s = *found;
+ std::sort(s.looseClusters.begin(), s.looseClusters.end());
+ s.looseClusters.erase(std::unique(s.looseClusters.begin(), s.looseClusters.end()), s.looseClusters.end());
+ const size_t nc = s.order.clusters().size();
+ if (s.fresh || mesh.topologyDirty || s.bounds.size() != nc) { // (a full upload since makes them anyway)
+ s.looseClusters.clear();
+ return;
+ }
+ poolFor(s.looseClusters.size(), [&](size_t i0, size_t i1) {
+ for (size_t i = i0; i < i1; ++i)
+ if (s.looseClusters[i] < nc) s.bounds[s.looseClusters[i]] = clusterBounds(mesh, s.order, s.looseClusters[i]);
+ }, 1, 2);
+ s.looseClusters.clear();
+ s.volume = 0.0;
+ s.box = AABB();
+ for (const ClusterBounds& b : s.bounds) {
+ s.volume += b.volume;
+ if (b.radius >= 0.0f) {
+ s.box.expand(b.center - glm::vec3(b.radius));
+ s.box.expand(b.center + glm::vec3(b.radius));
+ }
+ }
+}
+
// ---------------------------------------------------------------------------
// Thumbnails (LightBox / pickers)
// ---------------------------------------------------------------------------
diff --cc src/render/Renderer.h
index bcf8b786,a58aed17..7ec35cbb
--- a/src/render/Renderer.h
+++ b/src/render/Renderer.h
@@@ -9,10 -9,9 +9,11 @@@
#include "render/Camera.h"
#include "render/Clusters.h"
#include "render/GL.h"
+#include "render/Ghost.h"
#include <cstdint>
+#include <list>
+ #include <memory>
#include <string>
#include <vector>
@@@ -325,10 -272,10 +335,11 @@@ private
GLint view = -1, proj = -1, gridOrigin = -1, gridStep = -1, viewport = -1, projScale = -1, baseColor = -1, paint = -1,
showMask = -1, groups = -1, matcap = -1, matcapCavity = -1, dim = -1, primBase = -1, hasPaint = -1,
normalFlipY = -1, twoSided = -1;
+ GLint ghostGroups = -1, ghostRange = -1, ghostEdge = -1, ghostA = -1, ghostB = -1, ghostC = -1, ghostBound = -1, ghostKind = -1, ghostFocal = -1;
};
- static constexpr int kPaint = 1, kPrim = 2, kTextured = 4, kNormalMap = 8, kFlat = 16, kGhost = 32;
- static constexpr int kPaint = 1, kPrim = 2, kTextured = 4, kNormalMap = 8, kFlat = 16, kMicro = 32;
-- MeshProgram programs_[64];
++ static constexpr int kPaint = 1, kPrim = 2, kTextured = 4, kNormalMap = 8, kFlat = 16, kMicro = 32, kGhost = 64;
++ MeshProgram programs_[128];
+ void drawMicro(const MeshSlot& s, bool active, bool flat, const RenderSettings& settings);
std::string programError_;
const MeshProgram* meshProgram(int features);
bool vertexIdHasBase_ = true; // gl_VertexID includes the base vertex (checked at init; else per-cluster draws)