Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Merge origin/feat/hw-profile: its TierConfig is canonical
islandmedc64d2392276c
diff --cc CHANGELOG.mdindex 91f2ef2f,d3664a49..e9c329cb--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -7,23 -7,26 +7,43 @@@ 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").## [0.9.7] - 2026-10-31diff --cc CMakeLists.txtindex 26fd4bdf,6f455ce2..17c2f6e3--- a/CMakeLists.txt+++ b/CMakeLists.txt@@@ -68,11 -71,6 +71,10 @@@ add_library(sculptforge_core STATIsrc/core/Texture.cppsrc/core/TextureCommands.cppsrc/core/Multires.cpp+ src/core/Micro.cpp+ src/core/MicroSculpt.cpp+ src/core/MicroCommands.cpp+ src/core/MicroStore.cpp- src/core/TierConfig.cppsrc/core/MultiresCommands.cppsrc/core/AutoUv.cppsrc/core/TextureTransfer.cppdiff --cc docs/performance.mdindex 65c73410,6f88bf75..ec4e4100--- a/docs/performance.md+++ b/docs/performance.md@@@ -12,68 -12,146 +12,208 @@@ sculptforge-cli --bench ..Machine for all figures: Apple M1 Pro (8 performance + 2 efficiency cores, 32 GB unified memory, 30 GB usableunder Asahi Linux), integrated GPU, Mesa 26.1 (OpenGL 4.6). How the benchmark works is described under v0.5 below.+## 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)diff --cc src/app/main.cppindex 9bc93e37,6f291b31..2a201740--- a/src/app/main.cpp+++ b/src/app/main.cpp@@@ -51,9 -52,9 +52,11 @@@ void usage()" --bench-no-project Skip the project save / open (it needs twice the memory)\n"" --bench-view Benchmark only what the viewport costs (uploads, orbit)\n"" --bench-dyntopo Benchmark dynamic topology strokes (e.g. --bench-sizes 0.25,1,4)\n"+ " --bench-micro Benchmark micro-displacement levels (sizes = micro triangles, e.g. 33,100,300)\n"+ " --bench-micro-level N Micro level for --bench-micro (default 4: 256 per base triangle)\n"" --bench-out FILE Write the benchmark report (Markdown) to FILE\n"+ " --calibrate Measure this computer (GPU, CPU, memory; about 2-3 s), print the hardware\n"+ " profile as JSON and save it (add --calibrate-quick, --calibrate-no-save)\n"" --log-dir DIR Write sculptforge.log to DIR instead of the user data folder\n"" --crash-test KIND Crash on purpose (segv, abort or throw) to test the crash note in the log");}diff --cc src/core/Micro.cppindex 3531a773,00000000..6d472529mode 100644,000000..100644--- a/src/core/Micro.cpp+++ b/src/core/Micro.cpp@@@ -1,1242 -1,0 +1,1242 @@@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Micro-displacement levels (core/Micro.h): the data, evaluation, Divide / Delete, picking, the renderer's+// shading, baking down and displacement maps. The brushes are in MicroSculpt.cpp, the commands in+// MicroCommands.cpp.+#include "core/Micro.h"++#include "core/BakeImage.h"+#include "core/BVH.h"+#include "core/Multires.h"+#include "core/ThreadPool.h"+#include "core/TierConfig.h"++#include <algorithm>+#include <atomic>+#include <cmath>+#include <cstdlib>+#include <cstring>+#include <limits>+#include <mutex>++#if defined(_WIN32)+#define NOMINMAX+#include <windows.h>+#else+#include <unistd.h>+#endif++namespace sf {++// ---------------------------------------------------------------------------+// MicroMesh+// ---------------------------------------------------------------------------++uint64_t MicroMesh::newSerial() {+ static std::atomic<uint64_t> next{1};+ return next++;+}++size_t MicroMesh::microVertices() const {+ size_t edges = size_t(baseTriangles) * 3 / 2;+ if (edgeNeighbor.size() == size_t(baseTriangles) * 3) {+ size_t boundary = 0;+ for (uint32_t e : edgeNeighbor) boundary += e == kNone;+ edges = (size_t(baseTriangles) * 3 + boundary) / 2;+ }+ const size_t interior = n >= 2 ? size_t(n - 1) * (n - 2) / 2 : 0;+ return size_t(baseVertices) + edges * (n - 1) + size_t(baseTriangles) * interior;+}++size_t MicroMesh::bytes() const {+ return disp.capacity() * sizeof(int16_t) + mask.capacity() + triRange.capacity() * sizeof(uint16_t) ++ edgeNeighbor.capacity() * sizeof(uint32_t) + dirtyBits.capacity() * sizeof(uint64_t);+}++void MicroMesh::clearDirty() {+ std::fill(dirtyBits.begin(), dirtyBits.end(), 0);+ allDirty = false;+ maskDirty = false;+ rescaled = false;+}++int MicroMesh::widen(float need) {+ if (!(need > rangeWorld())) return 1;+ int doublings = 2;+ while (need > 32767.0f * step * float(1 << doublings) && doublings < 12) ++doublings;+ const int div = 1 << doublings;+ poolFor(disp.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) disp[i] = int16_t(int(disp[i]) / div);+ }, 1 << 16);+ for (uint16_t& v : triRange) v = uint16_t(std::min(int(v) / div + 1, 32767));+ rangeMax = uint16_t(std::min(int(rangeMax) / div + 1, 32767));+ step *= float(div);+ rescaled = true;+ ++revision;+ return div;+}++void MicroMesh::ensureTopology(const Mesh& base) {+ const size_t nt = base.triangleCount();+ if (edgeNeighbor.size() == nt * 3 && nt == baseTriangles) return;+ edgeNeighbor.assign(nt * 3, kNone);+ poolFor(nt, [&](size_t b, size_t e) {+ for (size_t t = b; t < e; ++t) {+ const glm::uvec3 tri = base.triangles[t];+ for (int k = 0; k < 3; ++k) {+ const uint32_t a = tri[k], c = tri[(k + 1) % 3];+ for (uint32_t u : base.vertexTriangles(a)) {+ if (u == t) continue;+ const glm::uvec3 o = base.triangles[u];+ int f = -1;+ for (int q = 0; q < 3 && f < 0; ++q)+ if ((o[q] == a && o[(q + 1) % 3] == c) || (o[q] == c && o[(q + 1) % 3] == a)) f = q;+ if (f >= 0) {+ edgeNeighbor[t * 3 + size_t(k)] = (u << 2) | uint32_t(f);+ break;+ }+ }+ }+ }+ }, 1 << 12);+}++// ---------------------------------------------------------------------------+// Evaluation+// ---------------------------------------------------------------------------++void MicroTriangle::set(const Mesh& base, uint32_t tri, uint32_t segments) {+ const glm::uvec3 t = base.triangles[tri];+ uint8_t o[3] = {0, 1, 2};+ if (t[o[0]] > t[o[1]]) std::swap(o[0], o[1]);+ if (t[o[1]] > t[o[2]]) std::swap(o[1], o[2]);+ if (t[o[0]] > t[o[1]]) std::swap(o[0], o[1]);+ for (int k = 0; k < 3; ++k) {+ slot[k] = o[k];+ p[k] = base.positions[t[o[k]]];+ nrm[k] = base.normals[t[o[k]]];+ }+ n = segments;+ invN = 1.0f / float(segments);+}++// The same operations, in the same order, as the renderer's vertex shader (render/MicroRenderer.cpp): corners in+// ascending vertex order, so a point on a shared edge (whose third weight is exactly 0) comes out bit-identical+// from both triangles.+void MicroTriangle::evalWeights(const float wc[3], glm::vec3& surface, glm::vec3& normal) const {+ const float w0 = wc[slot[0]], w1 = wc[slot[1]], w2 = wc[slot[2]];+ glm::vec3 f = p[0] * w0;+ f += p[1] * w1;+ f += p[2] * w2;+ glm::vec3 nn = nrm[0] * w0;+ nn += nrm[1] * w1;+ nn += nrm[2] * w2;+ // Phong tessellation: the flat point pulled towards each corner's tangent plane.+ glm::vec3 pull = nrm[0] * (w0 * glm::dot(f - p[0], nrm[0]));+ pull += nrm[1] * (w1 * glm::dot(f - p[1], nrm[1]));+ pull += nrm[2] * (w2 * glm::dot(f - p[2], nrm[2]));+ surface = f - pull * MicroMesh::kPhong;+ const float len = glm::length(nn);+ normal = len > 1e-20f ? nn / len : glm::vec3(0.0f, 0.0f, 1.0f);+}++void MicroTriangle::eval(uint32_t i, uint32_t j, glm::vec3& surface, glm::vec3& normal) const {+ const float w[3] = {float(n - i - j) * invN, float(i) * invN, float(j) * invN};+ evalWeights(w, surface, normal);+}++glm::vec3 MicroTriangle::flat(uint32_t i, uint32_t j) const {+ const float wc[3] = {float(n - i - j) * invN, float(i) * invN, float(j) * invN};+ glm::vec3 f = p[0] * wc[slot[0]];+ f += p[1] * wc[slot[1]];+ f += p[2] * wc[slot[2]];+ return f;+}++MicroPatch microPatch(Mesh& m, uint32_t id) {+ MicroMesh& mm = mutableMicro(m);+ MicroPatch p;+ p.id = id;+ p.n = mm.n;+ p.heights = mm.disp.data() + size_t(id) * mm.samples;+ p.mask = mm.hasMask() ? mm.mask.data() + size_t(id) * mm.samples : nullptr;+ return p;+}++bool PatchPageTable::resident(uint32_t patch) const {+ if (!mm_.disp.mapped()) return true;+ return mm_.disp.rangeResident(size_t(patch) * mm_.samples, mm_.samples);+}++size_t PatchPageTable::residentPatches() const {+ if (!mm_.disp.mapped()) return mm_.baseTriangles;+ size_t count = 0;+ for (uint32_t t = 0; t < mm_.baseTriangles; ++t) count += resident(t);+ return count;+}++int microLevel(const Mesh& m) { return m.micro ? m.micro->level : 0; }+size_t microTriangleCount(const Mesh& m) { return m.micro ? m.micro->microTriangles() : 0; }+size_t microBytes(const Mesh& m) { return m.micro ? m.micro->bytes() : 0; }++std::string microText(const Mesh& m) {+ if (!m.micro) return {};+ char buf[64];+ std::snprintf(buf, sizeof buf, "Micro %d (%.1fM)", m.micro->level, double(m.micro->microTriangles()) / 1e6);+ return buf;+}++bool microMatches(const Mesh& m) {+ return m.micro && m.micro->baseTriangles == m.triangleCount() && m.micro->baseVertices == m.vertexCount();+}++MicroMesh& mutableMicro(Mesh& m) {+ if (m.micro.use_count() > 1) m.micro = std::make_shared<MicroMesh>(*m.micro);+ return *m.micro;+}++size_t microMaxTriangles() {+ size_t memory = 0;+#if defined(_WIN32)+ MEMORYSTATUSEX status{};+ status.dwLength = sizeof status;+ if (GlobalMemoryStatusEx(&status)) memory = size_t(status.ullTotalPhys);+#elif defined(_SC_PHYS_PAGES)+ const long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGESIZE);+ if (pages > 0 && page > 0) memory = size_t(pages) * size_t(page);+#endif+ // Per micro triangle about 0.6 grid points (level 4) x (2 bytes + 1 of mask + 6 on the GPU) + undo: ~6 bytes.+ return std::clamp<size_t>(memory / 10 * 5 / 6, 100'000'000, size_t(8'000'000'000));+}++int microLevelFor(const Mesh& m, size_t target) {+ const double nt = double(std::max<size_t>(m.triangleCount(), 1));+ int best = 1;+ double bestErr = 1e300;+ for (int l = 1; l <= MicroMesh::kMaxLevel; ++l) {+ const double err = std::abs(std::log(nt * std::pow(4.0, l) / double(std::max<size_t>(target, 1))));+ if (err < bestErr) bestErr = err, best = l;+ }+ return best;+}++glm::vec3 microPoint(const Mesh& m, uint32_t tri, uint32_t i, uint32_t j) {+ const MicroMesh& mm = *m.micro;+ MicroTriangle T;+ T.set(m, tri, mm.n);+ glm::vec3 s, nn;+ T.eval(i, j, s, nn);+ return s + nn * (float(mm.disp[size_t(tri) * mm.samples + MicroMesh::index(i, j, mm.n)]) * mm.step);+}++namespace {++// The micro triangle holding barycentric point w of a base triangle: its three grid points (i, j) and weights.+struct Cell {+ uint32_t i[3], j[3];+ float w[3];+};+Cell cellAt(const float wc[3], uint32_t n) {+ const float fi = std::clamp(wc[1], 0.0f, 1.0f) * float(n), fj = std::clamp(wc[2], 0.0f, 1.0f) * float(n);+ uint32_t i0 = std::min(uint32_t(fi), n - 1), j0 = std::min(uint32_t(fj), n - 1);+ if (i0 + j0 > n - 1) { // outside the last full cell along the hypotenuse+ if (fi >= fj) i0 = n - 1 - j0;+ else j0 = n - 1 - i0;+ }+ const float a = fi - float(i0), b = fj - float(j0);+ Cell c;+ if (a + b <= 1.0f || i0 + j0 + 2 > n) {+ c.i[0] = i0, c.j[0] = j0, c.i[1] = i0 + 1, c.j[1] = j0, c.i[2] = i0, c.j[2] = j0 + 1;+ c.w[0] = 1.0f - a - b, c.w[1] = a, c.w[2] = b;+ } else {+ c.i[0] = i0 + 1, c.j[0] = j0, c.i[1] = i0 + 1, c.j[1] = j0 + 1, c.i[2] = i0, c.j[2] = j0 + 1;+ c.w[0] = 1.0f - b, c.w[1] = a + b - 1.0f, c.w[2] = 1.0f - a;+ }+ return c;+}++} // namespace++glm::vec3 microPointAt(const Mesh& m, uint32_t tri, const float wc[3], glm::vec3* normal) {+ const MicroMesh& mm = *m.micro;+ MicroTriangle T;+ T.set(m, tri, mm.n);+ const Cell c = cellAt(wc, mm.n);+ glm::vec3 q[3];+ for (int k = 0; k < 3; ++k) {+ glm::vec3 s, nn;+ T.eval(c.i[k], c.j[k], s, nn);+ q[k] = s + nn * (float(mm.disp[size_t(tri) * mm.samples + MicroMesh::index(c.i[k], c.j[k], mm.n)]) * mm.step);+ }+ if (normal) {+ const glm::vec3 g = glm::cross(q[1] - q[0], q[2] - q[0]);+ const float len = glm::length(g);+ *normal = len > 0.0f ? g / len : glm::vec3(0.0f, 0.0f, 1.0f);+ }+ return q[0] * c.w[0] + q[1] * c.w[1] + q[2] * c.w[2];+}++// ---------------------------------------------------------------------------+// Divide / Delete+// ---------------------------------------------------------------------------++namespace {++// The most a base triangle's Phong surface leaves its plane (an upper bound).+float triangleBulge(const MicroTriangle& T) {+ float e = 0.0f;+ for (int k = 0; k < 3; ++k)+ for (int q = 0; q < 3; ++q) e = std::max(e, std::abs(glm::dot(T.p[q] - T.p[k], T.nrm[k])));+ return e * MicroMesh::kPhong;+}++} // namespace++bool microWantsOutOfCore(size_t points) {+ if (const char* e = std::getenv("SF_MICRO_OUT_OF_CORE"); e && *e) return std::string(e) == "1";- if (const size_t limit = tierConfig().outOfCorePoints) return points > limit;++ if (const size_t limit = currentTierConfig().outOfCorePoints) return points > limit;+ size_t memory = 0;+#if defined(_SC_PHYS_PAGES)+ const long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGESIZE);+ if (pages > 0 && page > 0) memory = size_t(pages) * size_t(page);+#endif+ return memory && points * 2 > memory / 4;+}++bool microDivide(Mesh& m, int level, std::string& error, int outOfCore) {+ if (level < 1 || level > MicroMesh::kMaxLevel) {+ error = "Micro level must be 1 to " + std::to_string(MicroMesh::kMaxLevel);+ return false;+ }+ const size_t nt = m.triangleCount();+ if (nt == 0) {+ error = "Nothing to divide";+ return false;+ }+ if (m.micro) {+ error = "This SubTool already has a micro level (Delete micro or Bake it first)";+ return false;+ }+ if (subdivLevelCount(m) > 0 && subdivCurrentLevel(m) != subdivLevelCount(m) - 1) {+ error = "Go to the highest subdivision level first: the micro level goes on top of it";+ return false;+ }+ if (!m.zspheres.empty()) {+ error = "ZSphere SubTools can't have a micro level (make an adaptive skin first)";+ return false;+ }+ if (!m.layers.empty()) {+ error = "Sculpt layers can't carry a micro level yet: bake or delete the layers first";+ return false;+ }+ if (nt > (size_t(1) << 30)) {+ error = "Too many base triangles for a micro level";+ return false;+ }+ const size_t micro = nt << (2 * level);+ if (micro > microMaxTriangles()) {+ char buf[200];+ std::snprintf(buf, sizeof buf, "%.0fM micro triangles is more than this computer allows (%.0fM): pick a lower micro level",+ double(micro) / 1e6, double(microMaxTriangles()) / 1e6);+ error = buf;+ return false;+ }+ if (m.normals.size() != m.vertexCount()) m.recomputeAllNormals();+ auto mm = std::make_shared<MicroMesh>();+ mm->level = level;+ mm->n = 1u << level;+ mm->samples = (mm->n + 1) * (mm->n + 2) / 2;+ mm->baseTriangles = uint32_t(nt);+ mm->baseVertices = uint32_t(m.vertexCount());+ if (outOfCore < 0 ? microWantsOutOfCore(nt * mm->samples) : outOfCore == 1) {+ std::string why;+ mm->disp.assignMapped(nt * mm->samples, why); // (falls back to memory)+ } else {+ mm->disp.assign(nt * mm->samples, 0);+ }+ mm->triRange.assign(nt, 0);+ mm->dirtyBits.assign((nt + 63) / 64, 0);+ mm->ensureTopology(m);+ // Edge length and bulge, in parallel blocks (combined in order: deterministic).+ const size_t block = 1 << 14, blocks = (nt + block - 1) / block;+ std::vector<double> edgeSum(blocks, 0.0);+ std::vector<float> bulge(blocks, 0.0f);+ poolFor(nt, [&](size_t b, size_t e) {+ double s = 0.0;+ float g = 0.0f;+ MicroTriangle T;+ for (size_t t = b; t < e; ++t) {+ T.set(m, uint32_t(t), mm->n);+ s += double(glm::distance(T.p[0], T.p[1]) + glm::distance(T.p[1], T.p[2]) + glm::distance(T.p[2], T.p[0]));+ g = std::max(g, triangleBulge(T));+ }+ edgeSum[b / block] = s;+ bulge[b / block] = g;+ }, block);+ double total = 0.0;+ for (size_t i = 0; i < blocks; ++i) {+ total += edgeSum[i];+ mm->bulgeMax = std::max(mm->bulgeMax, bulge[i]);+ }+ const float avgEdge = float(total / double(nt * 3));+ mm->baseEdge = avgEdge;+ // 1/4096 of a base edge per unit: +/-8 base edges of range, steps far below a micro edge (1/256 of one at+ // level 4). Brushes widen the range when they need more (MicroStroke).+ mm->step = std::max(avgEdge / 4096.0f, 1e-12f);+ mm->serial = MicroMesh::newSerial();+ mm->allDirty = true;+ m.micro = std::move(mm);+ m.topologyDirty = true; // the renderer draws it differently+ return true;+}++bool microAttach(Mesh& m, int level, float step, MicroStore disp, std::vector<uint8_t> mask, std::string& error) {+ if (level < 1 || level > MicroMesh::kMaxLevel || !(step > 0.0f) || !std::isfinite(step)) {+ error = "Project micro level is invalid";+ return false;+ }+ const size_t nt = m.triangleCount();+ const uint32_t n = 1u << level, S = (n + 1) * (n + 2) / 2;+ if (disp.size() != nt * S || (!mask.empty() && mask.size() != disp.size())) {+ error = "Project micro level doesn't fit its mesh";+ return false;+ }+ if (m.normals.size() != m.vertexCount()) m.recomputeAllNormals();+ auto mm = std::make_shared<MicroMesh>();+ mm->level = level;+ mm->n = n;+ mm->samples = S;+ mm->step = step;+ mm->baseTriangles = uint32_t(nt);+ mm->baseVertices = uint32_t(m.vertexCount());+ mm->disp = std::move(disp);+ mm->mask = std::move(mask);+ mm->triRange.assign(nt, 0);+ mm->dirtyBits.assign((nt + 63) / 64, 0);+ const size_t block = 1 << 12, blocks = (nt + block - 1) / block;+ std::vector<float> bulge(blocks, 0.0f);+ poolFor(nt, [&](size_t b, size_t e) {+ MicroTriangle T;+ float g = 0.0f;+ for (size_t t = b; t < e; ++t) {+ const int16_t* d = mm->disp.data() + t * S;+ int r = 0;+ for (uint32_t k = 0; k < S; ++k) r = std::max(r, std::abs(int(d[k])));+ mm->triRange[t] = uint16_t(std::min(r, 32767));+ T.set(m, uint32_t(t), n);+ g = std::max(g, triangleBulge(T));+ }+ bulge[b / block] = g;+ }, block);+ for (float g : bulge) mm->bulgeMax = std::max(mm->bulgeMax, g);+ {+ double e = 0.0;+ for (size_t t = 0; t < nt; ++t) {+ const glm::uvec3 tr = m.triangles[t];+ e += double(glm::distance(m.positions[tr.x], m.positions[tr.y]) + glm::distance(m.positions[tr.y], m.positions[tr.z]) ++ glm::distance(m.positions[tr.z], m.positions[tr.x]));+ }+ mm->baseEdge = float(e / double(std::max<size_t>(nt * 3, 1)));+ }+ for (uint16_t r : mm->triRange) mm->rangeMax = std::max(mm->rangeMax, r);+ mm->ensureTopology(m);+ mm->serial = MicroMesh::newSerial();+ mm->allDirty = true;+ m.micro = std::move(mm);+ m.topologyDirty = true;+ return true;+}++void microDelete(Mesh& m) {+ if (!m.micro) return;+ m.micro.reset();+ m.topologyDirty = true;+}++// ---------------------------------------------------------------------------+// Picking+// ---------------------------------------------------------------------------++namespace {++bool rayTriangle(const glm::vec3& o, const glm::vec3& d, const glm::vec3& a, const glm::vec3& b, const glm::vec3& c, float& t) {+ const glm::vec3 e1 = b - a, e2 = c - a, pv = glm::cross(d, e2);+ const float det = glm::dot(e1, pv);+ if (std::abs(det) < 1e-30f) return false;+ const float inv = 1.0f / det;+ const glm::vec3 tv = o - a;+ const float u = glm::dot(tv, pv) * inv;+ if (u < 0.0f || u > 1.0f) return false;+ const glm::vec3 qv = glm::cross(tv, e1);+ const float v = glm::dot(d, qv) * inv;+ if (v < 0.0f || u + v > 1.0f) return false;+ t = glm::dot(e2, qv) * inv;+ return t > 0.0f;+}++} // namespace++bool microRaycast(const Mesh& m, const BVH& bvh, const glm::vec3& origin, const glm::vec3& dir, RayHit& hit) {+ if (!microMatches(m)) return bvh.raycast(m, origin, dir, hit);+ const MicroMesh& mm = *m.micro;+ RayHit base;+ if (!bvh.raycast(m, origin, dir, base)) return false;+ const float reach = mm.bulgeMax + float(mm.rangeMax) * mm.step;+ std::vector<uint32_t> cand;+ bvh.queryTriangles(m, base.position, 2.0f * reach + 1e-7f, cand);+ // Only the triangles whose own reach (their bulge and displacement range) the ray passes through.+ const glm::vec3 inv(1.0f / (std::abs(dir.x) > 1e-20f ? dir.x : 1e-20f), 1.0f / (std::abs(dir.y) > 1e-20f ? dir.y : 1e-20f),+ 1.0f / (std::abs(dir.z) > 1e-20f ? dir.z : 1e-20f));+ std::erase_if(cand, [&](uint32_t t) {+ if (t == base.triangle) return false;+ MicroTriangle T;+ T.set(m, t, mm.n);+ const float grow = triangleBulge(T) + float(mm.triRange[t]) * mm.step;+ const glm::vec3 lo = glm::min(T.p[0], glm::min(T.p[1], T.p[2])) - grow, hi = glm::max(T.p[0], glm::max(T.p[1], T.p[2])) + grow;+ const glm::vec3 t0 = (lo - origin) * inv, t1 = (hi - origin) * inv;+ const glm::vec3 tn = glm::min(t0, t1), tf = glm::max(t0, t1);+ const float enter = std::max({tn.x, tn.y, tn.z, 0.0f}), leave = std::min({tf.x, tf.y, tf.z});+ return enter > leave;+ });+ if (std::find(cand.begin(), cand.end(), base.triangle) == cand.end()) cand.push_back(base.triangle);+ constexpr size_t kMaxCandidates = 4096;+ if (cand.size() > kMaxCandidates) { // a huge displacement range: rank by distance and keep the nearest+ std::nth_element(cand.begin(), cand.begin() + kMaxCandidates, cand.end(), [&](uint32_t a, uint32_t b) {+ auto c = [&](uint32_t t) {+ const glm::uvec3 tr = m.triangles[t];+ return glm::distance(base.position, (m.positions[tr.x] + m.positions[tr.y] + m.positions[tr.z]) / 3.0f);+ };+ return c(a) < c(b);+ });+ cand.resize(kMaxCandidates);+ }+ const uint32_t n = mm.n, S = mm.samples;+ struct Best {+ float t = std::numeric_limits<float>::max();+ uint32_t tri = 0;+ glm::vec3 a{0.0f}, b{0.0f}, c{0.0f};+ };+ const size_t block = 4;+ std::vector<Best> best((cand.size() + block - 1) / block);+ poolFor(cand.size(), [&](size_t b0, size_t e0) {+ thread_local std::vector<glm::vec3> P;+ P.resize(S);+ Best bb;+ MicroTriangle T;+ for (size_t ci = b0; ci < e0; ++ci) {+ const uint32_t tri = cand[ci];+ if (m.triangleHidden(tri)) continue;+ T.set(m, tri, n);+ const int16_t* g = mm.disp.data() + size_t(tri) * S;+ uint32_t idx = 0;+ for (uint32_t j = 0; j <= n; ++j)+ for (uint32_t i = 0; i + j <= n; ++i, ++idx) {+ glm::vec3 s, nn;+ T.eval(i, j, s, nn);+ P[idx] = s + nn * (float(g[idx]) * mm.step);+ }+ for (uint32_t j = 0; j < n; ++j) {+ const uint32_t row = MicroMesh::index(0, j, n), next = MicroMesh::index(0, j + 1, n);+ for (uint32_t i = 0; i + j < n; ++i) {+ float t;+ const glm::vec3 &a = P[row + i], &b = P[row + i + 1], &c = P[next + i];+ if (rayTriangle(origin, dir, a, b, c, t) && t < bb.t) bb = {t, tri, a, b, c};+ if (i + j + 1 < n) {+ const glm::vec3 &d = P[next + i + 1];+ if (rayTriangle(origin, dir, b, d, c, t) && t < bb.t) bb = {t, tri, b, d, c};+ }+ }+ }+ }+ best[b0 / block] = bb;+ }, block, 2);+ Best win;+ for (const Best& b : best)+ if (b.t < win.t) win = b;+ if (win.t == std::numeric_limits<float>::max()) {+ // Missed every micro triangle near the base hit (a grazing ray): the micro point under the base hit.+ const glm::uvec3 tr = m.triangles[base.triangle];+ const glm::vec3 a = m.positions[tr.x], b = m.positions[tr.y], c = m.positions[tr.z];+ const glm::vec3 v0 = b - a, v1 = c - a, v2 = base.position - a;+ const float d00 = glm::dot(v0, v0), d01 = glm::dot(v0, v1), d11 = glm::dot(v1, v1), d20 = glm::dot(v2, v0),+ d21 = glm::dot(v2, v1), den = d00 * d11 - d01 * d01;+ float w[3] = {1.0f, 0.0f, 0.0f};+ if (std::abs(den) > 0.0f) {+ w[1] = (d11 * d20 - d01 * d21) / den;+ w[2] = (d00 * d21 - d01 * d20) / den;+ w[0] = 1.0f - w[1] - w[2];+ }+ hit = base;+ hit.position = microPointAt(m, base.triangle, w, &hit.normal);+ hit.t = glm::dot(hit.position - origin, dir);+ return true;+ }+ hit.t = win.t;+ hit.triangle = win.tri;+ hit.position = origin + dir * win.t;+ const glm::vec3 g = glm::cross(win.b - win.a, win.c - win.a);+ const float len = glm::length(g);+ hit.normal = len > 0.0f ? g / len : base.normal;+ return true;+}++bool surfaceRaycast(const Mesh& m, const BVH& bvh, const glm::vec3& origin, const glm::vec3& dir, RayHit& hit) {+ if (m.micro && microMatches(m)) return microRaycast(m, bvh, origin, dir, hit);+ return bvh.raycast(m, origin, dir, hit);+}++// ---------------------------------------------------------------------------+// Shading for the renderer+// ---------------------------------------------------------------------------++namespace {++constexpr int kPartialFloats = 5; // normal sum (3), neighbour displacement sum, neighbour count++uint32_t encodeShade(glm::vec3 nrm, float curvature, uint8_t mask) {+ const float l1 = std::abs(nrm.x) + std::abs(nrm.y) + std::abs(nrm.z);+ glm::vec2 e(0.0f);+ if (l1 > 0.0f) {+ nrm /= l1;+ e = glm::vec2(nrm.x, nrm.y);+ if (nrm.z < 0.0f)+ e = glm::vec2((1.0f - std::abs(nrm.y)) * (nrm.x >= 0.0f ? 1.0f : -1.0f),+ (1.0f - std::abs(nrm.x)) * (nrm.y >= 0.0f ? 1.0f : -1.0f));+ }+ auto q = [](float v) { return uint32_t(std::clamp(std::lround((v * 0.5f + 0.5f) * 255.0f), 0L, 255L)); };+ const float c = std::clamp(curvature, -1.0f, 1.0f);+ const float s = (c >= 0.0f ? 1.0f : -1.0f) * std::sqrt(std::abs(c));+ const uint32_t cq = uint32_t(std::clamp(std::lround(s * 127.0f) + 128L, 1L, 255L));+ return q(e.x) | q(e.y) << 8 | cq << 16 | uint32_t(mask) << 24;+}++// The grid of one base triangle: positions, then per point the sum of the face normals of its micro triangles+// (area weighted) and of its neighbours' displacements, within this triangle.+struct GridWork {+ std::vector<glm::vec3> pos, nsum;+ std::vector<float> dsum, cnt;+ void compute(const Mesh& m, const MicroMesh& mm, uint32_t tri) {+ const uint32_t n = mm.n, S = mm.samples;+ pos.resize(S);+ nsum.assign(S, glm::vec3(0.0f));+ dsum.assign(S, 0.0f);+ cnt.assign(S, 0.0f);+ MicroTriangle T;+ T.set(m, tri, n);+ const int16_t* g = mm.disp.data() + size_t(tri) * S;+ uint32_t idx = 0;+ for (uint32_t j = 0; j <= n; ++j)+ for (uint32_t i = 0; i + j <= n; ++i, ++idx) {+ glm::vec3 s, nn;+ T.eval(i, j, s, nn);+ pos[idx] = s + nn * (float(g[idx]) * mm.step);+ }+ for (uint32_t j = 0; j < n; ++j) {+ const uint32_t row = MicroMesh::index(0, j, n), next = MicroMesh::index(0, j + 1, n);+ for (uint32_t i = 0; i + j < n; ++i) {+ const uint32_t a = row + i, b = row + i + 1, c = next + i;+ const glm::vec3 f = glm::cross(pos[b] - pos[a], pos[c] - pos[a]);+ nsum[a] += f, nsum[b] += f, nsum[c] += f;+ // the lattice edges a-b, a-c, b-c (each once: every edge belongs to one upward triangle)+ const float da = g[a], db = g[b], dc = g[c];+ dsum[a] += db + dc, dsum[b] += da + dc, dsum[c] += da + db;+ cnt[a] += 2.0f, cnt[b] += 2.0f, cnt[c] += 2.0f;+ if (i + j + 1 < n) {+ const uint32_t d = next + i + 1;+ const glm::vec3 f2 = glm::cross(pos[d] - pos[b], pos[c] - pos[b]);+ nsum[b] += f2, nsum[d] += f2, nsum[c] += f2;+ }+ }+ }+ }+};++} // namespace++void MicroShader::shade(const Mesh& m, std::span<const uint32_t> dirty, bool all, std::vector<uint32_t>& written,+ const std::function<uint32_t*(uint32_t tri)>& out, const Prepare& prepare) {+ written.clear();+ if (!m.micro) return;+ if (!all) {+ shadeSet(m, dirty, true, written, out, prepare);+ return;+ }+ // Everything: in runs of triangles (neighbours by index on levels made by Divide), each with the ring its+ // shared points need, so the edge sums stay a few MB instead of 20 bytes per edge point of the whole mesh.+ const uint32_t nt = m.micro->baseTriangles;+ constexpr uint32_t kRun = 1u << 16;+ std::vector<uint32_t> run;+ for (uint32_t b = 0; b < nt; b += kRun) {+ run.resize(std::min(kRun, nt - b));+ for (uint32_t i = 0; i < run.size(); ++i) run[i] = b + i;+ shadeSet(m, run, false, written, out, prepare);+ }+}++void MicroShader::shadeSet(const Mesh& m, std::span<const uint32_t> dirty, bool grow, std::vector<uint32_t>& written,+ const std::function<uint32_t*(uint32_t tri)>& out, const Prepare& prepare) {+ const MicroMesh& mm = *m.micro;+ const uint32_t n = mm.n, S = mm.samples, nt = mm.baseTriangles;+ if (mm.edgeNeighbor.size() != size_t(nt) * 3) return; // (ensureTopology first)+ if (stamp_.size() != nt) {+ stamp_.assign(nt, 0);+ slot_.assign(nt, 0);+ epoch_ = 0;+ }+ if (vstamp_.size() != m.vertexCount()) vstamp_.assign(m.vertexCount(), 0);+ if (epoch_ > 0xFFFFFF00u) {+ std::fill(stamp_.begin(), stamp_.end(), 0);+ std::fill(vstamp_.begin(), vstamp_.end(), 0);+ epoch_ = 0;+ }+ // R = the triangles to write: dirty ones and those sharing a vertex; R2 = R and those sharing a vertex with+ // R (whose edge sums the shared points need). stamp_: epoch + 1 = in R, epoch + 2 = only in R2.+ const uint32_t inR = ++epoch_;+ const uint32_t inR2 = ++epoch_;+ auto vertexRing = [&](const std::vector<uint32_t>& from, std::vector<uint32_t>& into, uint32_t mark, uint32_t vmark) {+ for (uint32_t t : from) {+ const glm::uvec3 tri = m.triangles[t];+ for (int k = 0; k < 3; ++k) {+ if (vstamp_[tri[k]] == vmark) continue;+ vstamp_[tri[k]] = vmark;+ for (uint32_t u : m.vertexTriangles(tri[k]))+ if (stamp_[u] != inR && stamp_[u] != mark) {+ stamp_[u] = mark;+ into.push_back(u);+ }+ }+ }+ };+ ring_.clear();+ ring2_.clear();+ for (uint32_t t : dirty)+ if (t < nt && stamp_[t] != inR) stamp_[t] = inR, ring_.push_back(t);+ if (grow) {+ seed_.assign(ring_.begin(), ring_.end());+ grown_.clear();+ const uint32_t v1 = ++epoch_;+ vertexRing(seed_, grown_, inR, v1); // (marks them inR directly: they're written too)+ ring_.insert(ring_.end(), grown_.begin(), grown_.end());+ }+ const uint32_t v2 = ++epoch_;+ vertexRing(ring_, ring2_, inR2, v2);+ for (size_t i = 0; i < ring_.size(); ++i) slot_[ring_[i]] = uint32_t(i);+ for (size_t i = 0; i < ring2_.size(); ++i) slot_[ring2_[i]] = uint32_t(ring_.size() + i);+ if (prepare) prepare(ring_);+ const size_t slots = ring_.size() + ring2_.size();+ const size_t edgePoints = size_t(3) * n;+ partial_.resize(slots * edgePoints * kPartialFloats);+ auto tileOf = [&](size_t i) { return i < ring_.size() ? ring_[i] : ring2_[i - ring_.size()]; };+ auto microEdge = [&](uint32_t tri) {+ const glm::uvec3 t = m.triangles[tri];+ const float e = glm::distance(m.positions[t.x], m.positions[t.y]) + glm::distance(m.positions[t.y], m.positions[t.z]) ++ glm::distance(m.positions[t.z], m.positions[t.x]);+ return std::max(e / (3.0f * float(n)), 1e-20f);+ };+ auto finish = [&](const glm::vec3& ns, float ds, float c, float d, float h, uint8_t mk) {+ const float len = glm::length(ns);+ const glm::vec3 nn = len > 0.0f ? ns / len : glm::vec3(0.0f, 0.0f, 1.0f);+ const float curv = c > 0.0f ? (ds / c - d) * mm.step / h : 0.0f;+ return encodeShade(nn, curv, mk);+ };+ // Phase 1: every R2 triangle's edge partials; R triangles' interior points written.+ poolFor(slots, [&](size_t b, size_t e) {+ thread_local GridWork w;+ for (size_t s = b; s < e; ++s) {+ const uint32_t tri = tileOf(s);+ w.compute(m, mm, tri);+ float* part = partial_.data() + s * edgePoints * kPartialFloats;+ for (int ed = 0; ed < 3; ++ed)+ for (uint32_t k = 0; k < n; ++k) {+ uint32_t i, j;+ MicroMesh::edgePoint(ed, k, n, i, j);+ const uint32_t idx = MicroMesh::index(i, j, n);+ float* p = part + (size_t(ed) * n + k) * kPartialFloats;+ p[0] = w.nsum[idx].x, p[1] = w.nsum[idx].y, p[2] = w.nsum[idx].z, p[3] = w.dsum[idx], p[4] = w.cnt[idx];+ }+ if (s >= ring_.size()) continue;+ uint32_t* dst = out(tri);+ const int16_t* g = mm.disp.data() + size_t(tri) * S;+ const uint8_t* mk = mm.hasMask() ? mm.mask.data() + size_t(tri) * S : nullptr;+ const float h = microEdge(tri);+ for (uint32_t j = 1; j + 1 < n; ++j)+ for (uint32_t i = 1; i + j < n; ++i) {+ const uint32_t idx = MicroMesh::index(i, j, n);+ dst[idx] = finish(w.nsum[idx], w.dsum[idx], w.cnt[idx], float(g[idx]), h, mk ? mk[idx] : 0);+ }+ }+ }, 16);+ // Phase 2: R triangles' edge and corner points, summed with the other triangles holding them.+ poolFor(ring_.size(), [&](size_t b, size_t e) {+ for (size_t s = b; s < e; ++s) {+ const uint32_t tri = ring_[s];+ uint32_t* dst = out(tri);+ const int16_t* g = mm.disp.data() + size_t(tri) * S;+ const uint8_t* mk = mm.hasMask() ? mm.mask.data() + size_t(tri) * S : nullptr;+ const float h = microEdge(tri);+ const float* own = partial_.data() + s * edgePoints * kPartialFloats;+ const glm::uvec3 ttri = m.triangles[tri];+ for (int ed = 0; ed < 3; ++ed) {+ const uint32_t nb = mm.edgeNeighbor[size_t(tri) * 3 + size_t(ed)];+ const float* other = nullptr;+ bool reversed = true;+ int f = 0;+ if (nb != MicroMesh::kNone && (stamp_[nb >> 2] == inR || stamp_[nb >> 2] == inR2)) {+ const uint32_t u = nb >> 2;+ f = int(nb & 3);+ other = partial_.data() + size_t(slot_[u]) * edgePoints * kPartialFloats;+ reversed = m.triangles[u][f] != ttri[ed]; // usual: the neighbour runs the edge the other way+ }+ for (uint32_t k = 1; k < n; ++k) {+ const float* p = own + (size_t(ed) * n + k) * kPartialFloats;+ glm::vec3 ns(p[0], p[1], p[2]);+ float ds = p[3], c = p[4];+ if (other) {+ const float* q = other + (size_t(f) * n + (reversed ? n - k : k)) * kPartialFloats;+ ns += glm::vec3(q[0], q[1], q[2]);+ ds += q[3];+ c += q[4];+ }+ uint32_t i, j;+ MicroMesh::edgePoint(ed, k, n, i, j);+ const uint32_t idx = MicroMesh::index(i, j, n);+ dst[idx] = finish(ns, ds, c, float(g[idx]), h, mk ? mk[idx] : 0);+ }+ // The corner at the start of this edge: every triangle around the vertex.+ const uint32_t v = ttri[ed];+ glm::vec3 ns(0.0f);+ float ds = 0.0f, c = 0.0f;+ for (uint32_t u : m.vertexTriangles(v)) {+ if (stamp_[u] != inR && stamp_[u] != inR2) continue;+ const glm::uvec3 ut = m.triangles[u];+ const int corner = ut.x == v ? 0 : ut.y == v ? 1 : 2;+ const float* q = partial_.data() + (size_t(slot_[u]) * edgePoints + size_t(corner) * n) * kPartialFloats;+ ns += glm::vec3(q[0], q[1], q[2]);+ ds += q[3];+ c += q[4];+ }+ uint32_t i, j;+ MicroMesh::edgePoint(ed, 0, n, i, j);+ const uint32_t idx = MicroMesh::index(i, j, n);+ dst[idx] = finish(ns, ds, c, float(g[idx]), h, mk ? mk[idx] : 0);+ }+ }+ }, 16);+ written.insert(written.end(), ring_.begin(), ring_.end());+}++// ---------------------------------------------------------------------------+// Undo+// ---------------------------------------------------------------------------++void MicroUndo::swapWith(Mesh& m) {+ if (swapWhole) {+ std::swap(m.micro, whole);+ if (m.micro) {+ m.micro->allDirty = true;+ m.micro->ensureTopology(m);+ if (m.micro->dirtyBits.size() != (size_t(m.micro->baseTriangles) + 63) / 64)+ m.micro->dirtyBits.assign((size_t(m.micro->baseTriangles) + 63) / 64, 0);+ }+ m.topologyDirty = true;+ return;+ }+ if (!m.micro || !microMatches(m) || m.micro->samples != samples) return;+ MicroMesh& mm = mutableMicro(m);+ const size_t S = samples;+ // Values kept in another step size (the range grew since): convert to the current one.+ if (!journal && step != mm.step && step > 0.0f) {+ const float r = step / mm.step;+ for (int16_t& v : disp) v = int16_t(std::clamp(std::lround(float(v) * r), -32767L, 32767L));+ step = mm.step;+ }+ if (maskAdded) {+ if (mm.hasMask()) {+ poolFor(tris.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i)+ std::swap_ranges(mask.begin() + std::ptrdiff_t(i * S), mask.begin() + std::ptrdiff_t((i + 1) * S),+ mm.mask.begin() + std::ptrdiff_t(size_t(tris[i]) * S));+ }, 64);+ std::vector<uint8_t>().swap(mm.mask);+ } else {+ mm.mask.assign(mm.disp.size(), 0);+ poolFor(tris.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i)+ std::swap_ranges(mask.begin() + std::ptrdiff_t(i * S), mask.begin() + std::ptrdiff_t((i + 1) * S),+ mm.mask.begin() + std::ptrdiff_t(size_t(tris[i]) * S));+ }, 64);+ }+ mm.maskDirty = true;+ } else if (!mask.empty() && mm.hasMask()) {+ poolFor(tris.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i)+ std::swap_ranges(mask.begin() + std::ptrdiff_t(i * S), mask.begin() + std::ptrdiff_t((i + 1) * S),+ mm.mask.begin() + std::ptrdiff_t(size_t(tris[i]) * S));+ }, 64);+ }+ if (journal) { // the stroke's change: subtract it (undo) or add it back (redo)+ std::vector<int16_t> change(tris.size() * S, 0);+ if (!microUnpackTiles(packed.data(), packed.size(), tris.size(), samples, change.data())) return;+ poolFor(tris.size(), [&](size_t b, size_t e) { // (stored as differences to the point before, see MicroUndo)+ const uint32_t n = mm.n;+ for (size_t t = b; t < e; ++t) {+ int16_t* c = change.data() + t * S;+ uint32_t p = 0;+ for (uint32_t j = 0; j <= n; ++j)+ for (uint32_t i = 0; i + j <= n; ++i, ++p) {+ int v;+ if (p == 0) v = firsts[t];+ else if (i > 0) v = int(c[p - 1]) + int(c[p]);+ else v = int(c[MicroMesh::index(0, j - 1, n)]) + int(c[p]);+ c[p] = int16_t(std::clamp(v, -32767, 32767));+ }+ }+ }, 256);+ const float ratio = step / mm.step; // (the range grew since: the change in today's units)+ const int sgn = applied ? -1 : 1;+ poolFor(tris.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) {+ int16_t* g = mm.disp.data() + size_t(tris[i]) * S;+ int r = 0;+ for (size_t k = 0; k < S; ++k) {+ const float c = ratio == 1.0f ? float(change[i * S + k]) : float(change[i * S + k]) * ratio;+ const int v = std::clamp(int(g[k]) + sgn * int(std::lround(c)), -32767, 32767);+ g[k] = int16_t(v);+ r = std::max(r, std::abs(v));+ }+ mm.triRange[tris[i]] = uint16_t(std::max<int>(r, mm.triRange[tris[i]]));+ }+ }, 64);+ applied = !applied;+ for (uint32_t t : tris) mm.rangeMax = std::max(mm.rangeMax, mm.triRange[t]);+ }+ if (!disp.empty()) {+ poolFor(tris.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) {+ int16_t* g = mm.disp.data() + size_t(tris[i]) * S;+ std::swap_ranges(disp.begin() + std::ptrdiff_t(i * S), disp.begin() + std::ptrdiff_t((i + 1) * S), g);+ int r = 0;+ for (size_t k = 0; k < S; ++k) r = std::max(r, std::abs(int(g[k])));+ mm.triRange[tris[i]] = uint16_t(r);+ }+ }, 64);+ for (uint32_t t : tris) mm.rangeMax = std::max(mm.rangeMax, mm.triRange[t]);+ }+ for (uint32_t t : tris) mm.markDirty(t);+ ++mm.revision;+}++size_t MicroUndo::bytes() const {+ return tris.size() * sizeof(uint32_t) + keys.size() * sizeof(uint64_t) + packed.size() + firsts.size() * sizeof(int16_t) + disp.size() * sizeof(int16_t) ++ mask.size() + (swapWhole && whole ? whole->bytes() : 0);+}++// ---------------------------------------------------------------------------+// Bake down+// ---------------------------------------------------------------------------++bool microBakeMesh(const Mesh& m, int level, Mesh& out, std::string& error, size_t maxTriangles) {+ if (!m.micro || !microMatches(m)) {+ error = "This SubTool has no micro level";+ return false;+ }+ const MicroMesh& mm = *m.micro;+ if (level < 0 || level > mm.level) level = mm.level;+ if (mm.edgeNeighbor.size() != size_t(mm.baseTriangles) * 3) {+ error = "Micro level topology missing";+ return false;+ }+ if (maxTriangles == 0) maxTriangles = subdivMaxTriangles();+ const uint32_t q = 1u << level, step = mm.n / q, nt = mm.baseTriangles, nv = mm.baseVertices;+ const size_t tris = size_t(nt) * q * q;+ if (tris > maxTriangles || tris >= (size_t(1) << 32)) {+ char buf[200];+ std::snprintf(buf, sizeof buf, "Baking micro level %d makes %.0fM triangles, more than this computer allows (%.0fM): pick a lower level",+ level, double(tris) / 1e6, double(maxTriangles) / 1e6);+ error = buf;+ return false;+ }+ // Vertex numbering: base vertices, then each base edge's q - 1 inner points (numbered by the triangle that+ // owns the edge: the lower index of the two), then each triangle's inner points.+ std::vector<uint32_t> edgeStart(size_t(nt) * 3, 0);+ uint32_t next = nv;+ for (uint32_t t = 0; t < nt; ++t)+ for (int e = 0; e < 3; ++e) {+ const uint32_t nb = mm.edgeNeighbor[size_t(t) * 3 + size_t(e)];+ if (nb == MicroMesh::kNone || (nb >> 2) > t) {+ edgeStart[size_t(t) * 3 + size_t(e)] = next;+ next += q - 1;+ }+ }+ for (uint32_t t = 0; t < nt; ++t)+ for (int e = 0; e < 3; ++e) {+ const uint32_t nb = mm.edgeNeighbor[size_t(t) * 3 + size_t(e)];+ if (nb != MicroMesh::kNone && (nb >> 2) < t) edgeStart[size_t(t) * 3 + size_t(e)] = edgeStart[size_t(nb >> 2) * 3 + (nb & 3)];+ }+ const uint32_t inner = q >= 2 ? (q - 1) * (q - 2) / 2 : 0;+ const size_t verts = size_t(next) + size_t(nt) * inner;+ if (verts >= (size_t(1) << 32)) {+ error = "Too many vertices";+ return false;+ }+ out = Mesh();+ out.positions.resize(verts);+ out.triangles.resize(tris);+ const bool uvs = m.hasUvs(), groups = m.hasPolygroups(), hidden = m.hasHidden(), masked = mm.hasMask();+ if (uvs) out.uvs.resize(tris * 3);+ if (groups) out.polygroups.resize(tris);+ if (hidden) out.hidden.resize(tris);+ if (masked) out.mask.assign(verts, 0.0f);+ // The vertex of grid point (a, b) (bake level) of triangle t.+ auto vertexOf = [&](uint32_t t, uint32_t a, uint32_t b) -> uint32_t {+ const glm::uvec3 tr = m.triangles[t];+ if (a == 0 && b == 0) return tr.x;+ if (a == q && b == 0) return tr.y;+ if (a == 0 && b == q) return tr.z;+ int e = -1;+ uint32_t k = 0;+ if (b == 0) e = 0, k = a;+ else if (a + b == q) e = 1, k = b;+ else if (a == 0) e = 2, k = q - b;+ if (e >= 0) {+ const uint32_t nb = mm.edgeNeighbor[size_t(t) * 3 + size_t(e)];+ const bool owner = nb == MicroMesh::kNone || (nb >> 2) > t;+ if (!owner) { // numbered from the owner's start corner+ const uint32_t u = nb >> 2;+ const bool reversed = m.triangles[u][nb & 3] != tr[e];+ if (reversed) k = q - k;+ }+ return edgeStart[size_t(t) * 3 + size_t(e)] + k - 1;+ }+ // inner point: rows b = 1..q-2, a = 1..q-1-b+ const uint32_t r = b - 1;+ const uint32_t before = r * (q - 2) - r * (r - 1) / 2; // points in rows 1..b-1: sum (q - 1 - b')+ return next + t * inner + before + (a - 1);+ };+ poolFor(nt, [&](size_t b0, size_t e0) {+ MicroTriangle T;+ for (size_t tt = b0; tt < e0; ++tt) {+ const uint32_t t = uint32_t(tt);+ T.set(m, t, mm.n);+ const int16_t* g = mm.disp.data() + size_t(t) * mm.samples;+ const uint8_t* mk = masked ? mm.mask.data() + size_t(t) * mm.samples : nullptr;+ for (uint32_t b = 0; b <= q; ++b)+ for (uint32_t a = 0; a + b <= q; ++a) {+ const uint32_t v = vertexOf(t, a, b);+ // Each shared point is written by every triangle holding it, with the same value (stitched).+ const uint32_t i = a * step, j = b * step, idx = MicroMesh::index(i, j, mm.n);+ glm::vec3 s, nn;+ T.eval(i, j, s, nn);+ out.positions[v] = s + nn * (float(g[idx]) * mm.step);+ if (mk) out.mask[v] = float(mk[idx]) / 255.0f;+ }+ const size_t first = size_t(t) * q * q;+ size_t o = first;+ glm::vec2 uv[3];+ if (uvs) uv[0] = m.uvs[size_t(t) * 3], uv[1] = m.uvs[size_t(t) * 3 + 1], uv[2] = m.uvs[size_t(t) * 3 + 2];+ auto uvAt = [&](uint32_t a, uint32_t b) {+ const float fa = float(a) / float(q), fb = float(b) / float(q);+ return uv[0] * (1.0f - fa - fb) + uv[1] * fa + uv[2] * fb;+ };+ for (uint32_t b = 0; b < q; ++b)+ for (uint32_t a = 0; a + b < q; ++a) {+ out.triangles[o] = {vertexOf(t, a, b), vertexOf(t, a + 1, b), vertexOf(t, a, b + 1)};+ if (uvs) out.uvs[o * 3] = uvAt(a, b), out.uvs[o * 3 + 1] = uvAt(a + 1, b), out.uvs[o * 3 + 2] = uvAt(a, b + 1);+ ++o;+ if (a + b + 1 < q) {+ out.triangles[o] = {vertexOf(t, a + 1, b), vertexOf(t, a + 1, b + 1), vertexOf(t, a, b + 1)};+ if (uvs)+ out.uvs[o * 3] = uvAt(a + 1, b), out.uvs[o * 3 + 1] = uvAt(a + 1, b + 1), out.uvs[o * 3 + 2] = uvAt(a, b + 1);+ ++o;+ }+ }+ for (size_t k = first; k < o; ++k) {+ if (groups) out.polygroups[k] = m.polygroups[t];+ if (hidden) out.hidden[k] = m.hidden[t];+ }+ }+ }, 256);+ out.texture = m.texture;+ out.paintToTexture = m.paintToTexture;+ out.rebuildTopology();+ out.recomputeAllNormals();+ return true;+}++// ---------------------------------------------------------------------------+// Displacement maps+// ---------------------------------------------------------------------------++bool microExportDisplacement(const Mesh& m, const std::string& path, int size, bool vector, const std::string& format,+ float& scaleOut, std::string& error) {+ if (!m.micro || !microMatches(m)) {+ error = "This SubTool has no micro level";+ return false;+ }+ if (!m.hasUvs()) {+ error = "Displacement maps need UVs on the base (Tool > UV Map, at the lowest level)";+ return false;+ }+ if (size < 16 || size > 16384) {+ error = "Map size must be 16 to 16384";+ return false;+ }+ if (format != "exr" && format != "png") {+ error = "Format must be exr or png";+ return false;+ }+ const MicroMesh& mm = *m.micro;+ const int W = size, H = size, C = vector ? 3 : 1;+ std::vector<float> px(size_t(W) * H * C, 0.0f);+ std::vector<uint8_t> covered(size_t(W) * H, 0);+ const uint32_t n = mm.n, S = mm.samples;+ poolFor(mm.baseTriangles, [&](size_t b0, size_t e0) {+ MicroTriangle T;+ thread_local std::vector<glm::vec3> P, F, N;+ P.resize(S), F.resize(S), N.resize(S);+ for (size_t tt = b0; tt < e0; ++tt) {+ const uint32_t t = uint32_t(tt);+ if (m.triangleHidden(t)) continue;+ const glm::vec2 a = m.uvs[size_t(t) * 3], b = m.uvs[size_t(t) * 3 + 1], c = m.uvs[size_t(t) * 3 + 2];+ // texel space, top-down+ const glm::vec2 A(a.x * W, (1.0f - a.y) * H), B(b.x * W, (1.0f - b.y) * H), Cc(c.x * W, (1.0f - c.y) * H);+ const float area = (B.x - A.x) * (Cc.y - A.y) - (Cc.x - A.x) * (B.y - A.y);+ if (std::abs(area) < 1e-12f) continue;+ T.set(m, t, n);+ const int16_t* g = mm.disp.data() + size_t(t) * S;+ uint32_t idx = 0;+ for (uint32_t j = 0; j <= n; ++j)+ for (uint32_t i = 0; i + j <= n; ++i, ++idx) {+ glm::vec3 s, nn;+ T.eval(i, j, s, nn);+ P[idx] = s + nn * (float(g[idx]) * mm.step);+ F[idx] = T.flat(i, j);+ N[idx] = nn;+ }+ const int x0 = std::max(0, int(std::floor(std::min({A.x, B.x, Cc.x})))),+ x1 = std::min(W - 1, int(std::ceil(std::max({A.x, B.x, Cc.x})))),+ y0 = std::max(0, int(std::floor(std::min({A.y, B.y, Cc.y})))),+ y1 = std::min(H - 1, int(std::ceil(std::max({A.y, B.y, Cc.y}))));+ for (int y = y0; y <= y1; ++y)+ for (int x = x0; x <= x1; ++x) {+ const glm::vec2 p(float(x) + 0.5f, float(y) + 0.5f);+ const float w1 = ((p.x - A.x) * (Cc.y - A.y) - (Cc.x - A.x) * (p.y - A.y)) / area;+ const float w2 = ((B.x - A.x) * (p.y - A.y) - (p.x - A.x) * (B.y - A.y)) / area;+ const float w0 = 1.0f - w1 - w2;+ if (w0 < -1e-5f || w1 < -1e-5f || w2 < -1e-5f) continue;+ const float w[3] = {w0, w1, w2};+ const Cell cl = cellAt(w, n);+ glm::vec3 pm(0.0f), pf(0.0f), pn(0.0f);+ for (int k = 0; k < 3; ++k) {+ const uint32_t id = MicroMesh::index(cl.i[k], cl.j[k], n);+ pm += P[id] * cl.w[k], pf += F[id] * cl.w[k], pn += N[id] * cl.w[k];+ }+ const size_t o = size_t(y) * W + size_t(x);+ const glm::vec3 off = pm - pf;+ if (vector) px[o * 3] = off.x, px[o * 3 + 1] = off.y, px[o * 3 + 2] = off.z;+ else px[o] = glm::dot(off, glm::normalize(pn));+ covered[o] = 1;+ }+ }+ }, 256);+ // Padding: 8 rings of texels around the islands take their neighbours' values (mip and filter seams).+ for (int pass = 0; pass < 8; ++pass) {+ std::vector<uint8_t> grow = covered;+ for (int y = 0; y < H; ++y)+ for (int x = 0; x < W; ++x) {+ const size_t o = size_t(y) * W + size_t(x);+ if (covered[o]) continue;+ float sum[3] = {0, 0, 0};+ int cnt = 0;+ for (int dy = -1; dy <= 1; ++dy)+ for (int dx = -1; dx <= 1; ++dx) {+ const int xx = x + dx, yy = y + dy;+ if (xx < 0 || yy < 0 || xx >= W || yy >= H) continue;+ const size_t q = size_t(yy) * W + size_t(xx);+ if (!covered[q]) continue;+ for (int k = 0; k < C; ++k) sum[k] += px[q * C + size_t(k)];+ ++cnt;+ }+ if (!cnt) continue;+ for (int k = 0; k < C; ++k) px[o * C + size_t(k)] = sum[k] / float(cnt);+ grow[o] = 1;+ }+ covered.swap(grow);+ }+ float maxAbs = 0.0f;+ for (float v : px) maxAbs = std::max(maxAbs, std::abs(v));+ scaleOut = maxAbs;+ if (format == "exr") return saveExr(path, W, H, C, px, error);+ std::vector<uint16_t> q(px.size());+ const float s = maxAbs > 0.0f ? 32767.0f / maxAbs : 0.0f;+ for (size_t i = 0; i < px.size(); ++i) q[i] = uint16_t(std::clamp(std::lround(px[i] * s) + 32768L, 0L, 65535L));+ return savePng16(path, W, H, C, q, error);+}++// ---------------------------------------------------------------------------+// Procedural detail+// ---------------------------------------------------------------------------++namespace {++float hashFloat(int x, int y, int z, uint32_t seed) {+ uint32_t h = uint32_t(x) * 0x8da6b343u ^ uint32_t(y) * 0xd8163841u ^ uint32_t(z) * 0xcb1ab31fu ^ seed * 0x9E3779B9u;+ h ^= h >> 13;+ h *= 0x85EBCA6Bu;+ h ^= h >> 16;+ return float(h & 0xFFFFFF) / float(0xFFFFFF) * 2.0f - 1.0f;+}++float valueNoise(const glm::vec3& p, uint32_t seed) {+ const glm::vec3 f = glm::floor(p);+ const glm::vec3 t = p - f;+ const glm::vec3 u = t * t * (3.0f - 2.0f * t);+ const int x = int(f.x), y = int(f.y), z = int(f.z);+ auto h = [&](int dx, int dy, int dz) { return hashFloat(x + dx, y + dy, z + dz, seed); };+ const float a = glm::mix(glm::mix(h(0, 0, 0), h(1, 0, 0), u.x), glm::mix(h(0, 1, 0), h(1, 1, 0), u.x), u.y);+ const float b = glm::mix(glm::mix(h(0, 0, 1), h(1, 0, 1), u.x), glm::mix(h(0, 1, 1), h(1, 1, 1), u.x), u.y);+ return glm::mix(a, b, u.z);+}++} // namespace++void microNoise(Mesh& m, float amplitude, float frequency, uint32_t seed) {+ if (!m.micro) return;+ MicroMesh& mm = mutableMicro(m);+ mm.ensureTopology(m);+ mm.widen(float(mm.rangeMax) * mm.step + std::abs(amplitude) * 1.5f);+ const uint32_t n = mm.n, S = mm.samples;+ poolFor(mm.baseTriangles, [&](size_t b0, size_t e0) {+ MicroTriangle T;+ for (size_t tt = b0; tt < e0; ++tt) {+ const uint32_t t = uint32_t(tt);+ if (m.triangleHidden(t)) continue;+ T.set(m, t, n);+ int16_t* g = mm.disp.data() + size_t(t) * S;+ const uint8_t* mk = mm.hasMask() ? mm.mask.data() + size_t(t) * S : nullptr;+ uint32_t idx = 0;+ int r = mm.triRange[t];+ for (uint32_t j = 0; j <= n; ++j)+ for (uint32_t i = 0; i + j <= n; ++i, ++idx) {+ glm::vec3 s, nn;+ T.eval(i, j, s, nn);+ const glm::vec3 p = s * frequency;+ // three octaves, ridged a little so it reads as skin-like pores and wrinkles+ float v = valueNoise(p, seed) * 0.6f + valueNoise(p * 2.03f, seed + 1) * 0.28f ++ valueNoise(p * 4.11f, seed + 2) * 0.12f;+ v = 1.0f - std::abs(v) * 2.0f;+ float d = float(g[idx]) * mm.step + amplitude * v * (mk ? 1.0f - float(mk[idx]) / 255.0f : 1.0f);+ const long q = std::clamp(std::lround(d / mm.step), -32767L, 32767L);+ g[idx] = int16_t(q);+ r = std::max(r, int(std::abs(q)));+ }+ mm.triRange[t] = uint16_t(r);+ }+ }, 256);+ for (uint16_t r : mm.triRange) mm.rangeMax = std::max(mm.rangeMax, r);+ mm.allDirty = true;+ ++mm.revision;+}++} // namespace sfdiff --cc src/core/Micro.hindex 7a9f3feb,00000000..41c4ed5fmode 100644,000000..100644--- a/src/core/Micro.h+++ b/src/core/Micro.h@@@ -1,328 -1,0 +1,328 @@@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Micro-displacement levels: hundreds of millions of sculptable triangles without a mesh that size.+//+// Above the top subdivision level a SubTool can carry a micro level (Mesh::micro). The surface is then+//+// micro point = S(t, i, j) + d(t, i, j) * N(t, i, j)+//+// for every base triangle t (the mesh itself: its current, highest subdivision level) and every point (i, j) of+// a regular grid of n = 2^level segments per base edge on it (n^2 micro triangles per base triangle):+// - S is the base triangle's Phong-tessellated surface (Boubekeur & Alexa 2008, shape factor 3/4): the flat+// point pulled towards the tangent planes of the three corners, which is smooth across base edges and needs+// nothing but the base positions and normals;+// - N is the interpolated base vertex normal (normalised);+// - d is ONE scalar per grid point, stored as a 16-bit integer times `step` (world units).+// Micro triangles are never stored: positions are generated on the fly (brushes on the CPU, the renderer in its+// vertex shader). Memory is 2 bytes per grid point (+1 with a mask): 300 million micro triangles at level 4 on+// 1.2 million base triangles are about 360 MB, against roughly 30 GB as a plain mesh.+//+// Each base triangle keeps its whole grid, so the points on a base edge exist once per triangle beside it (and a+// corner once per triangle around it): about 20% extra at level 4 for grids that are contiguous per triangle (a+// brush, an undo tile and a GPU upload are one memcpy-able run each). After every edit the copies are made equal+// again ("stitching"), so the surface stays watertight. Positions on shared edges are computed from the base+// corners in ascending vertex-index order on the CPU and GPU alike, so both sides of an edge get bit-identical+// points even where the compiler fuses multiply-adds.+//+// Grid layout per triangle (corners c0, c1, c2 = triangle.x, .y, .z): point (i, j) with i, j >= 0, i + j <= n+// has barycentric weights ((n - i - j) / n, i / n, j / n); row j holds n + 1 - j points, so its index is+// j * (n + 1) - j * (j - 1) / 2 + i. Corner c0 = (0, 0), c1 = (n, 0), c2 = (0, n). Edge e runs from corner e to+// corner e + 1: e0 = (k, 0), e1 = (n - k, k), e2 = (0, n - k), k = 0..n.+//+// What a scalar displacement can't do: move points sideways. Brushes that slide the surface (Move's sideways+// part, Snake Hook, Nudge, VDM stamps with overhangs) work on real subdivision levels; on a micro level Pinch+// sharpens the height profile instead (see microBrushSupport).+#pragma once++#include "core/Mesh.h"+#include "core/MicroStore.h"++#include <cstdint>+#include <functional>+#include <memory>+#include <span>+#include <string>+#include <vector>++namespace sf {++class BVH;+class CommandRegistry;+struct Document;+struct RayHit;+enum class BrushType;++struct MicroMesh {+ static constexpr int kMaxLevel = 7; // 128 x 128 segments per base triangle (8,385 points)+ static constexpr float kPhong = 0.75f; // Phong tessellation shape factor+ static constexpr uint32_t kNone = ~0u;++ int level = 0; // n = 2^level segments per base edge+ uint32_t n = 1;+ uint32_t samples = 3; // grid points per base triangle: (n + 1)(n + 2) / 2+ float step = 1e-6f; // world units per integer unit of `disp`+ uint32_t baseTriangles = 0, baseVertices = 0;+ MicroStore disp; // baseTriangles * samples (in memory or out of core: core/MicroStore.h)+ std::vector<uint8_t> mask; // empty, or one per grid point (0 = free, 255 = masked)+ std::vector<uint16_t> triRange; // per base triangle: the largest |disp| (an upper bound; brushes find triangles with it)+ uint16_t rangeMax = 0; // the largest triRange (an upper bound)+ float bulgeMax = 0.0f; // the most S leaves a base triangle's plane (world units, an upper bound)+ float baseEdge = 0.0f; // the base's average edge length++ // Base topology this level needs (derived, not saved; rebuilt when the base changes): per triangle edge the+ // neighbouring triangle (tri << 2 | its edge), or kNone on a boundary.+ std::vector<uint32_t> edgeNeighbor;++ // What changed since the renderer last looked: per base triangle a bit, or everything.+ std::vector<uint64_t> dirtyBits;+ bool allDirty = true;+ bool maskDirty = false; // the mask was added or removed (the renderer's shading changes everywhere)+ bool stroking = false; // a stroke is running (TierConfig draft normals: the renderer shades less meanwhile)+ bool rescaled = false; // `step` grew and every value was rescaled (same surface: the renderer re-sends the values only)+ uint64_t revision = 0; // bumped by every edit+ // Which level this is (new on Divide / load; kept by copies, which hold the same values): the renderer keeps+ // its GPU copy while the serial stays.+ uint64_t serial = 0;+ static uint64_t newSerial();++ size_t microTriangles() const { return size_t(baseTriangles) * n * n; }+ size_t microVertices() const; // unique grid points (shared edges and corners counted once)+ size_t bytes() const;+ bool hasMask() const { return !mask.empty(); }+ float rangeWorld() const { return 32767.0f * step; } // the largest |d| `step` can hold++ static uint32_t index(uint32_t i, uint32_t j, uint32_t n) { return j * (n + 1) - j * (j - 1) / 2 + i; }+ // The grid point of edge e at k (from corner e towards corner e + 1).+ static void edgePoint(int e, uint32_t k, uint32_t n, uint32_t& i, uint32_t& j) {+ if (e == 0) i = k, j = 0;+ else if (e == 1) i = n - k, j = k;+ else i = 0, j = n - k;+ }+ void markDirty(uint32_t tri) { dirtyBits[tri >> 6] |= uint64_t(1) << (tri & 63); }+ // Grows `step` (by powers of two, at least 4x) until +/-`need` world units fit, rescaling every value (each+ // loses its lowest bits). Returns the divisor applied (1 = it fitted already).+ int widen(float need);+ void markAllDirty() { allDirty = true; }+ void clearDirty();+ // Builds edgeNeighbor for `base` (if it doesn't fit already).+ void ensureTopology(const Mesh& base);+};++// --- The two-tier engine's vocabulary ---+// BaseCage: the coarse surface the brushes for big forms (Move, transforms) deform: the SubTool's mesh, its highest+// subdivision level. Its polygons are triangles (a quad of the cage is a triangle pair, one patch each).+using BaseCage = Mesh;+// MicroPatch: one base triangle's regular grid of scalar heights (n + 1)(n + 2) / 2, implicit topology (no index+// buffer anywhere), heights 16-bit in memory and packed to their range (0-16 bits) on disk and in undo steps.+struct MicroPatch {+ uint32_t id = 0; // the base triangle+ uint32_t n = 0; // segments per edge+ int16_t* heights = nullptr;+ uint8_t* mask = nullptr; // null without a mask+ size_t points() const { return size_t(n + 1) * (n + 2) / 2; }+};+MicroPatch microPatch(Mesh& m, uint32_t id);+// PatchPageTable: which patches are resident. In memory every patch is; out of core (MicroStore::mapped) a patch+// is resident when its pages are, cold ones live in the sparse file (untouched = a hole) and come back on touch;- // the operating system's page cache keeps the LRU order and trim() enforces TierConfig::residentPatchCacheMB.++// the operating system's page cache keeps the LRU order and trim() enforces TierConfig::residentCacheCapMB.+class PatchPageTable {+public:+ explicit PatchPageTable(MicroMesh& mm) : mm_(mm) {}+ bool resident(uint32_t patch) const;+ size_t residentPatches() const;+ size_t residentBytes() const { return mm_.disp.residentBytes(); }+ size_t trim(size_t maxBytes) { return mm_.disp.trim(maxBytes); }++private:+ MicroMesh& mm_;+};++// The base triangle's corners and normals, sorted by vertex index, for evaluating its grid points.+struct MicroTriangle {+ glm::vec3 p[3], nrm[3]; // in vertex-index order+ uint8_t slot[3]; // which corner (0..2 of the triangle) each is+ float invN = 1.0f;+ uint32_t n = 1;+ void set(const Mesh& base, uint32_t tri, uint32_t n);+ // The reference surface S and direction N at grid point (i, j).+ void eval(uint32_t i, uint32_t j, glm::vec3& surface, glm::vec3& normal) const;+ // ... and at barycentric weights of corners 0..2 (sum 1).+ void evalWeights(const float w[3], glm::vec3& surface, glm::vec3& normal) const;+ // The flat point (no Phong) at grid point (i, j): what displacement maps are measured from.+ glm::vec3 flat(uint32_t i, uint32_t j) const;+};++// --- Queries ---+inline bool hasMicro(const Mesh& m) { return m.micro != nullptr; }+int microLevel(const Mesh& m); // 0 = none+size_t microTriangleCount(const Mesh& m);+size_t microBytes(const Mesh& m);+// "Micro 4 (300.0M)" or "".+std::string microText(const Mesh& m);+// True when the micro level still fits the mesh (base triangle and vertex counts).+bool microMatches(const Mesh& m);+// The micro level to change in place: copied first when another Mesh (an undo snapshot, a copy) shares it.+MicroMesh& mutableMicro(Mesh& m);+// The most micro triangles this computer is allowed to make (RAM: about 4 bytes a grid point with the GPU's share).+size_t microMaxTriangles();+// The level that brings the mesh closest to `targetTriangles` micro triangles (1..kMaxLevel).+int microLevelFor(const Mesh& m, size_t targetTriangles);++// The micro surface point at grid point (i, j) of base triangle t (reads the stored displacement).+glm::vec3 microPoint(const Mesh& m, uint32_t tri, uint32_t i, uint32_t j);+// The micro surface at barycentric weights of base triangle t (displacement interpolated on the micro triangle+// holding the point), with its geometric normal.+glm::vec3 microPointAt(const Mesh& m, uint32_t tri, const float w[3], glm::vec3* normal = nullptr);++// --- Operations (no undo; see the commands) ---+// Adds a micro level of `level` (1..kMaxLevel) to the mesh: its current level must be the highest (or it has no+// subdivision levels). The surface starts as S (smooth, d = 0).+// `outOfCore`: 1 = keep the displacements in a memory-mapped file (core/MicroStore.h), 0 = in memory, -1 = decide+// (out of core when they'd take more than a quarter of this computer's memory, or SF_MICRO_OUT_OF_CORE=1).+bool microDivide(Mesh& m, int level, std::string& error, int outOfCore = -1);+// The -1 rule of microDivide for `points` grid points.+bool microWantsOutOfCore(size_t points);+// Removes the micro level.+void microDelete(Mesh& m);+// Gives a loaded mesh (with normals) a micro level from saved data: `disp` holds baseTriangles * samples values+// (`mask` that many or none). Works out the derived data (ranges, bulge, edge neighbours).+bool microAttach(Mesh& m, int level, float step, MicroStore disp, std::vector<uint8_t> mask, std::string& error);+// A regular mesh of the micro surface at micro level `level` (<= the micro level): shared points welded, the base+// triangles' UVs, polygroups and hidden flags carried to their micro triangles, mask from the micro mask. Fails+// when it would exceed `maxTriangles` (0 = what subdivision Divide allows on this computer).+bool microBakeMesh(const Mesh& m, int level, Mesh& out, std::string& error, size_t maxTriangles = 0);+// Displacement maps over the base UVs (needs UVs): `vector` = object-space offset of the micro surface from the+// flat base triangles (RGB), else the height along the interpolated normal from the flat base triangles.+// `format` "exr" (32-bit float, world units) or "png" (16-bit; scalar: 32768 = 0 and +/-`scaleOut` at white /+// black; vector: each channel likewise). Writes `path`.+bool microExportDisplacement(const Mesh& m, const std::string& path, int size, bool vector, const std::string& format,+ float& scaleOut, std::string& error);+// Adds procedural detail (value noise of `frequency` cycles per unit, `amplitude` world units) over the whole+// micro surface, for demos and benchmarks.+void microNoise(Mesh& m, float amplitude, float frequency, uint32_t seed = 1);++// Ray against the micro surface: the base triangle hit (BVH) and its neighbourhood within the displacement range,+// at full micro resolution. hit.triangle is the base triangle; hit.position / normal are on the micro surface.+bool microRaycast(const Mesh& m, const BVH& bvh, const glm::vec3& origin, const glm::vec3& dir, RayHit& hit);+// bvh.raycast, or microRaycast on a mesh with a micro level: what brushes and the cursor pick.+bool surfaceRaycast(const Mesh& m, const BVH& bvh, const glm::vec3& origin, const glm::vec3& dir, RayHit& hit);++// --- Shading for the renderer: per grid point an octahedral normal (2 x 8 bits), curvature (8 bits,+// sign(c) sqrt|c| like the mesh shader's) and mask (8 bits), packed little-endian in a uint32. ---+class MicroShader {+public:+ // Recomputes what changes when base triangles `dirty` changed (all of them when `all`): the shading of those+ // and of every base triangle sharing a vertex with one (whose shared edges and corners average with them).+ // out(tri) gives where that triangle's `samples` values go (each written whole). `written` lists them.+ // `prepare`, if given, sees the triangles about to be written (before any out() call), once per batch.+ using Prepare = std::function<void(std::span<const uint32_t> tris)>;+ void shade(const Mesh& m, std::span<const uint32_t> dirty, bool all, std::vector<uint32_t>& written,+ const std::function<uint32_t*(uint32_t tri)>& out, const Prepare& prepare = {});++private:+ // shade() for the triangles `seeds` (grown by the triangles sharing a vertex when `grow`); appends to `written`.+ void shadeSet(const Mesh& m, std::span<const uint32_t> seeds, bool grow, std::vector<uint32_t>& written,+ const std::function<uint32_t*(uint32_t tri)>& out, const Prepare& prepare);+ std::vector<uint32_t> seed_, grown_;+ std::vector<uint32_t> stamp_, slot_; // per base triangle: in a set of this call (stamp), its partials (slot)+ std::vector<uint32_t> vstamp_; // per base vertex+ uint32_t epoch_ = 0;+ std::vector<uint32_t> ring_, ring2_;+ std::vector<float> partial_; // per slot: 3n edge points x 6 floats+};++// --- Brushes (driven by Sculptor, which calls these when the mesh has a micro level) ---++// Whether a brush works on micro levels: 2 = as on a mesh, 1 = approximated (Pinch, Crease and Dam Standard+// sharpen instead of pulling sideways; Move moves along the normal), 0 = not at all.+int microBrushSupport(BrushType type);++struct MicroUndo;+class MicroStroke {+public:+ void begin(Mesh& m);+ // One dab (one mirror) of a displacement brush, or the mask brush (`maskBrush`: raises the mask to 1, or+ // lowers it with invert).+ void dab(Mesh& m, const BVH& bvh, BrushType type, const glm::vec3& center, const glm::vec3& viewDir, float radius,+ float strength, bool invert, float focal, const glm::vec3& alphaUp, bool maskBrush, float maskStrength);+ // Move: captures the points within the dab (with each mirror's signs), then moves them along their normals.+ void beginGrab(Mesh& m, const BVH& bvh, const glm::vec3& center, float radius, float focal, const glm::vec3& mirror);+ void grab(Mesh& m, const glm::vec3& delta);+ // Puts every grid point the stroke changed back (the stroke stays open).+ void restore(Mesh& m);+ // The stroke's undo step (null when nothing changed).+ std::unique_ptr<MicroUndo> end(Mesh& m);+ bool active() const { return active_; }+ // Scale-adaptive brushing: a dab is evaluated on grid points about radius / kBrushSamples apart (a power-of-two+ // stride of the micro grid) and interpolated in between, so its evaluation cost doesn't grow with the micro+ // level. Off: every grid point (tests compare).+ static constexpr int kBrushSamples = 48;+ bool adaptive = true;+ uint32_t lastStride = 1; // the stride the last dab used+ // Timings of the last dabs (ms): finding the triangles + saving undo tiles, the kernel, stitching.+ double findMs = 0, kernelMs = 0, stitchMs = 0;+ uint64_t points = 0; // grid points visited++private:+ void touch(MicroMesh& mm, std::span<const uint32_t> tris);+ void widen(MicroMesh& mm, float need); // MicroMesh::widen, keeping this stroke's saved tiles in step+ void stitch(const Mesh& m, MicroMesh& mm, std::span<const uint32_t> tris);+ bool active_ = false;+ float strokeStep_ = 0.0f;+ std::vector<uint32_t> tileOf_; // per base triangle: its undo tile + 1 (0 = not yet touched)+ std::vector<uint32_t> tiles_; // the touched base triangles, in order+ std::vector<int16_t> oldDisp_; // tiles_.size() * samples+ std::vector<uint8_t> oldMask_; // likewise, while the mask exists+ bool maskAdded_ = false; // the stroke allocated the mask+ std::vector<uint32_t> cand_; // this dab's base triangles+ std::vector<uint32_t> dabStamp_; // per base triangle: == dabEpoch_ when in cand_+ uint32_t dabEpoch_ = 0;+ std::vector<uint32_t> vertStamp_;+ std::vector<uint32_t> corners_;+ float baseEdge_ = 0.0f; // the base's average edge length+ // Move: per mirror its triangles and, per triangle, weight and direction of its coarse grid points.+ struct GrabMirror {+ glm::vec3 mirror{1.0f};+ uint32_t stride = 1, firstTri = 0, tris = 0;+ };+ std::vector<GrabMirror> grabMirrors_;+ std::vector<uint32_t> grabTris_;+ std::vector<float> grabWeight_;+ std::vector<glm::vec3> grabNormal_;+};++// One micro step: the old grid points of the base triangles a stroke touched (in units of `step`), or a whole+// micro level swapped in or out (Divide to micro, Delete micro: `whole`, with `swapWhole`).+//+// Strokes keep a journal (`journal`): the touched tiles sorted by a Morton code of their centre (`keys`, so the+// journal of a region is contiguous and can be looked up), each as the stroke's change (new - old, stored as the+// difference to the point before it in its row, or below it for a row's first) packed with the tile codec (core/MicroStore.h): untouched points cost nothing, a smooth change a few bits+// per point, so a typical stroke's step is tens of KB instead of 2 bytes per point. `applied`: the change is in+// the mesh (undo subtracts it, redo adds it back).+struct MicroUndo {+ float step = 0.0f;+ uint32_t samples = 0;+ std::vector<uint32_t> tris;+ std::vector<int16_t> disp; // whole-tile old values (no journal)+ bool journal = false;+ bool applied = true;+ std::vector<uint64_t> keys; // journal: Morton code of each tile's centre, ascending+ std::vector<uint8_t> packed; // journal: the tiles' changes (each point less its predecessor), packed+ std::vector<int16_t> firsts; // journal: each tile's first change+ std::vector<uint8_t> mask;+ bool maskAdded = false; // the step allocated the mask: undo frees it again (redo brings it back)+ bool swapWhole = false;+ std::shared_ptr<MicroMesh> whole;+ void swapWith(Mesh& m);+ size_t bytes() const;+};++// --- Undoable document operations ---+bool microDivideUndoable(Document& doc, int level, std::string& message);+bool microDeleteUndoable(Document& doc, std::string& message);++// micro_divide, micro_delete, micro_info, micro_bake, micro_export_displacement, micro_noise.+void registerMicroCommands(CommandRegistry& registry);++} // namespace sfdiff --cc src/core/MicroSculpt.cppindex feb4de97,00000000..6601fcf6mode 100644,000000..100644--- a/src/core/MicroSculpt.cpp+++ b/src/core/MicroSculpt.cpp@@@ -1,744 -1,0 +1,744 @@@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Brushes on micro-displacement levels (core/Micro.h). A dab:+// 1. finds the base triangles it can reach: the BVH over the base, with the radius grown by how far the micro+// surface can leave the base (the Phong bulge plus the largest displacement), then each triangle's own box;+// 2. saves the grids of triangles the stroke touches for the first time (the undo step: whole tiles);+// 3. finds the brush plane (area normal and centre) from every second grid point under the brush;+// 4. runs the kernel over the triangles in parallel: each grid point inside the brush gets a new scalar;+// 5. stitches: copies of a point on a shared edge or corner are averaged (they differ only where a brush read+// neighbours, like Smooth), so the surface stays closed.+#include "core/Micro.h"++#include "core/BVH.h"+#include "core/Sculpt.h"+#include "core/ThreadPool.h"+#include "core/TierConfig.h"++#include <algorithm>+#include <atomic>+#include <cmath>++namespace sf {++int microBrushSupport(BrushType type) {+ switch (type) {+ case BrushType::Standard:+ case BrushType::Clay:+ case BrushType::ClayBuildup:+ case BrushType::Smooth:+ case BrushType::Inflate:+ case BrushType::Flatten:+ case BrushType::Trim:+ case BrushType::Layer: return 2;+ case BrushType::Pinch:+ case BrushType::Crease:+ case BrushType::DamStandard:+ case BrushType::Move: return 1;+ default: return 0;+ }+}++namespace {++glm::vec3 projectOnPlane(const glm::vec3& v, const glm::vec3& n) { return v - n * glm::dot(v, n); }++// A base triangle's box grown by its Phong bulge and displacement range.+bool triangleNear(const Mesh& m, const MicroMesh& mm, uint32_t t, const glm::vec3& c, float r) {+ const glm::uvec3 tr = m.triangles[t];+ const glm::vec3 a = m.positions[tr.x], b = m.positions[tr.y], d = m.positions[tr.z];+ const glm::vec3 na = m.normals[tr.x], nb = m.normals[tr.y], nd = m.normals[tr.z];+ float bulge = 0.0f;+ bulge = std::max({bulge, std::abs(glm::dot(b - a, na)), std::abs(glm::dot(d - a, na)), std::abs(glm::dot(a - b, nb)),+ std::abs(glm::dot(d - b, nb)), std::abs(glm::dot(a - d, nd)), std::abs(glm::dot(b - d, nd))});+ const float grow = bulge * MicroMesh::kPhong + float(mm.triRange[t]) * mm.step;+ const glm::vec3 lo = glm::min(a, glm::min(b, d)) - grow, hi = glm::max(a, glm::max(b, d)) + grow;+ const glm::vec3 q = glm::clamp(c, lo, hi);+ return glm::dot(q - c, q - c) <= r * r;+}++// Writes the change at every grid point of an n-grid from `coarse` changes on the points `stride` apart (a grid of+// n / stride): each point gets the coarse micro triangle's values interpolated (exactly the coarse value on coarse+// points). apply(index, change) is called for the points whose change isn't 0.+template <class F>+void interpolateCoarse(const float* coarse, uint32_t n, uint32_t stride, F&& apply) {+ const uint32_t cm = n / stride;+ const float inv = 1.0f / float(stride);+ uint32_t idx = 0;+ for (uint32_t j = 0; j <= n; ++j) {+ const uint32_t cj = j / stride, rj = j % stride;+ const float fj = float(rj) * inv;+ for (uint32_t i = 0; i + j <= n; ++i, ++idx) {+ const uint32_t ci = i / stride, ri = i % stride;+ const float fi = float(ri) * inv;+ float d;+ if (ri == 0 && rj == 0) d = coarse[MicroMesh::index(ci, cj, cm)];+ else if (fi + fj <= 1.0f)+ d = coarse[MicroMesh::index(ci, cj, cm)] * (1.0f - fi - fj) + coarse[MicroMesh::index(ci + 1, cj, cm)] * fi ++ coarse[MicroMesh::index(ci, cj + 1, cm)] * fj;+ else+ d = coarse[MicroMesh::index(ci + 1, cj, cm)] * (1.0f - fj) + coarse[MicroMesh::index(ci + 1, cj + 1, cm)] * (fi + fj - 1.0f) ++ coarse[MicroMesh::index(ci, cj + 1, cm)] * (1.0f - fi);+ if (d != 0.0f) apply(idx, d);+ }+ }+}++// Rounds `units` (a displacement over its step) to the nearest storable value (no libm call: brushes write+// millions of these).+inline int16_t quantizeUnits(float units) {+ units = std::clamp(units, -32767.0f, 32767.0f);+ return int16_t(units >= 0.0f ? int(units + 0.5f) : -int(0.5f - units));+}++// The six lattice neighbours of (i, j) inside the triangle.+template <class F>+void forNeighbors(uint32_t i, uint32_t j, uint32_t n, F&& f) {+ if (i > 0) f(i - 1, j);+ if (i + j < n) f(i + 1, j);+ if (j > 0) f(i, j - 1);+ if (i + j < n) f(i, j + 1);+ if (j > 0) f(i + 1, j - 1);+ if (i > 0) f(i - 1, j + 1);+}++} // namespace++void MicroStroke::begin(Mesh& m) {+ MicroMesh& mm = mutableMicro(m);+ mm.ensureTopology(m);+ if (mm.dirtyBits.size() != (size_t(mm.baseTriangles) + 63) / 64) mm.dirtyBits.assign((size_t(mm.baseTriangles) + 63) / 64, 0);+ tileOf_.assign(mm.baseTriangles, 0);+ tiles_.clear();+ oldDisp_.clear();+ oldMask_.clear();+ maskAdded_ = false;+ if (dabStamp_.size() != mm.baseTriangles) {+ dabStamp_.assign(mm.baseTriangles, 0);+ dabEpoch_ = 0;+ }+ if (vertStamp_.size() != m.vertexCount()) vertStamp_.assign(m.vertexCount(), 0);+ strokeStep_ = mm.step;+ grabMirrors_.clear();+ grabTris_.clear();+ grabWeight_.clear();+ grabNormal_.clear();+ baseEdge_ = mm.baseEdge;+ mm.stroking = true;+ active_ = true;+}++// Saves the grids of the triangles in `tris` that this stroke hasn't touched yet.+void MicroStroke::touch(MicroMesh& mm, std::span<const uint32_t> tris) {+ const size_t S = mm.samples, before = tiles_.size();+ for (uint32_t t : tris)+ if (!tileOf_[t]) {+ tiles_.push_back(t);+ tileOf_[t] = uint32_t(tiles_.size());+ }+ if (tiles_.size() == before) return;+ oldDisp_.resize(tiles_.size() * S);+ if (mm.hasMask()) oldMask_.resize(tiles_.size() * S);+ poolFor(tiles_.size() - before, [&](size_t b, size_t e) {+ for (size_t i = before + b; i < before + e; ++i) {+ const size_t t = tiles_[i];+ std::copy_n(mm.disp.data() + t * S, S, oldDisp_.data() + i * S);+ if (mm.hasMask()) std::copy_n(mm.mask.data() + t * S, S, oldMask_.data() + i * S);+ }+ }, 64);+}++// Makes the copies of every shared point of triangles `tris` equal again (see the file comment).+void MicroStroke::stitch(const Mesh& m, MicroMesh& mm, std::span<const uint32_t> tris) {+ const uint32_t n = mm.n, S = mm.samples;+ const uint32_t epoch = dabEpoch_;+ auto inDab = [&](uint32_t t) { return dabStamp_[t] == epoch; };+ // Edges: each shared edge once, by the lower triangle of the two (both in this dab), or copied from a hidden+ // neighbour (which brushes leave alone).+ poolFor(tris.size(), [&](size_t b, size_t e) {+ for (size_t s = b; s < e; ++s) {+ const uint32_t t = tris[s];+ const glm::uvec3 tt = m.triangles[t];+ int16_t* g = mm.disp.data() + size_t(t) * S;+ uint8_t* mk = mm.hasMask() ? mm.mask.data() + size_t(t) * S : nullptr;+ for (int ed = 0; ed < 3; ++ed) {+ const uint32_t nb = mm.edgeNeighbor[size_t(t) * 3 + size_t(ed)];+ if (nb == MicroMesh::kNone) continue;+ const uint32_t u = nb >> 2;+ const int f = int(nb & 3);+ const bool hiddenU = m.triangleHidden(u);+ if (!(inDab(u) && t < u) && !(hiddenU && !inDab(u))) continue;+ int16_t* h = mm.disp.data() + size_t(u) * S;+ uint8_t* hk = mk ? mm.mask.data() + size_t(u) * S : nullptr;+ const bool reversed = m.triangles[u][f] != tt[ed];+ for (uint32_t k = 1; k < n; ++k) {+ uint32_t i, j, i2, j2;+ MicroMesh::edgePoint(ed, k, n, i, j);+ MicroMesh::edgePoint(f, reversed ? n - k : k, n, i2, j2);+ const uint32_t a = MicroMesh::index(i, j, n), c = MicroMesh::index(i2, j2, n);+ if (hiddenU) {+ g[a] = h[c];+ if (mk) mk[a] = hk[c];+ } else {+ const int16_t v = int16_t((int(g[a]) + int(h[c]) + (int(g[a]) + int(h[c]) >= 0 ? 1 : 0)) / 2);+ g[a] = h[c] = v;+ if (mk) mk[a] = hk[c] = uint8_t((int(mk[a]) + int(hk[c]) + 1) / 2);+ }+ }+ }+ }+ }, 64);+ // Corners: every base vertex of these triangles once, averaged over the triangles around it in this dab (or+ // taken from a hidden one).+ corners_.clear();+ const uint32_t vmark = epoch;+ for (uint32_t t : tris) {+ const glm::uvec3 tt = m.triangles[t];+ for (int k = 0; k < 3; ++k)+ if (vertStamp_[tt[k]] != vmark) {+ vertStamp_[tt[k]] = vmark;+ corners_.push_back(tt[k]);+ }+ }+ poolFor(corners_.size(), [&](size_t b, size_t e) {+ for (size_t s = b; s < e; ++s) {+ const uint32_t v = corners_[s];+ const IndexRing ring = m.vertexTriangles(v);+ auto cornerIndex = [&](uint32_t u) {+ const glm::uvec3 ut = m.triangles[u];+ const int c = ut.x == v ? 0 : ut.y == v ? 1 : 2;+ return size_t(u) * S + (c == 0 ? 0 : c == 1 ? MicroMesh::index(n, 0, n) : MicroMesh::index(0, n, n));+ };+ long sum = 0, msum = 0;+ int count = 0;+ int hiddenValue = 0, hiddenMask = 0;+ bool fromHidden = false;+ for (uint32_t u : ring) {+ const size_t ci = cornerIndex(u);+ if (!inDab(u)) {+ if (m.triangleHidden(u) && !fromHidden) {+ fromHidden = true;+ hiddenValue = mm.disp[ci];+ hiddenMask = mm.hasMask() ? mm.mask[ci] : 0;+ }+ continue;+ }+ sum += mm.disp[ci];+ if (mm.hasMask()) msum += mm.mask[ci];+ ++count;+ }+ if (!count) continue;+ const int16_t value = fromHidden ? int16_t(hiddenValue)+ : int16_t((sum + (sum >= 0 ? count / 2 : -(count / 2))) / count);+ const uint8_t mval = fromHidden ? uint8_t(hiddenMask) : uint8_t((msum + count / 2) / count);+ for (uint32_t u : ring) {+ if (!inDab(u)) continue;+ const size_t ci = cornerIndex(u);+ mm.disp[ci] = value;+ if (mm.hasMask()) mm.mask[ci] = mval;+ }+ }+ }, 256);+ // Ranges (the kernel grew them for what it wrote): stitching averaged shared points with the neighbours, so+ // a triangle's edges may now hold its neighbour's larger value.+ poolFor(tris.size(), [&](size_t b, size_t e) {+ for (size_t s = b; s < e; ++s) {+ const uint32_t t = tris[s];+ const int16_t* g = mm.disp.data() + size_t(t) * S;+ int r = mm.triRange[t];+ for (int ed = 0; ed < 3; ++ed)+ for (uint32_t k = 0; k < n; ++k) {+ uint32_t i, j;+ MicroMesh::edgePoint(ed, k, n, i, j);+ r = std::max(r, std::abs(int(g[MicroMesh::index(i, j, n)])));+ }+ mm.triRange[t] = uint16_t(std::min(r, 32767));+ }+ }, 64);+ for (uint32_t t : tris) {+ mm.rangeMax = std::max(mm.rangeMax, mm.triRange[t]);+ mm.markDirty(t);+ }+ ++mm.revision;+}++void MicroStroke::dab(Mesh& m, const BVH& bvh, BrushType type, const glm::vec3& center, const glm::vec3& viewDir, float radius,+ float strength, bool invert, float focal, const glm::vec3& alphaUp, bool maskBrush, float maskStrength) {+ if (!active_ || !m.micro || radius <= 0.0f) return;+ if (!maskBrush && microBrushSupport(type) == 0) return;+ auto clock = std::chrono::steady_clock::now();+ MicroMesh& mm = *m.micro; // (made unique by begin)+ const uint32_t n = mm.n, S = mm.samples;+ const float r = radius, r2 = r * r;+ const float s = std::clamp(strength, 0.0f, 1.0f);+ const float sign = invert ? -1.0f : 1.0f;+ const float reach = type == BrushType::ClayBuildup && !maskBrush ? 1.3f : 1.0f;++ // The displacement range this dab may need: widened first (it costs precision) when what a dab adds could+ // pass it; a dab that still clips (planes far off) widens it for the next one.+ if (!maskBrush) widen(mm, float(mm.rangeMax) * mm.step + 0.12f * r * s);++ // 1. The base triangles within reach.+ if (++dabEpoch_ == 0) {+ std::fill(dabStamp_.begin(), dabStamp_.end(), 0);+ std::fill(vertStamp_.begin(), vertStamp_.end(), 0);+ dabEpoch_ = 1;+ }+ bvh.queryTriangles(m, center, r * reach + mm.bulgeMax + float(mm.rangeMax) * mm.step, cand_);+ std::erase_if(cand_, [&](uint32_t t) { return m.triangleHidden(t) || !triangleNear(m, mm, t, center, r * reach); });+ if (cand_.empty()) return;+ for (uint32_t t : cand_) dabStamp_[t] = dabEpoch_;+ if (maskBrush && !mm.hasMask()) {+ mm.mask.assign(mm.disp.size(), 0);+ oldMask_.assign(tiles_.size() * S, 0); // (the tiles saved so far had no mask: zeros)+ maskAdded_ = true;+ mm.maskDirty = true;+ }+ touch(mm, cand_);+ findMs += lapMs(clock);++ // 2. The brush plane: weighted area normal and centre over every second grid point under the brush.+ glm::vec3 areaNormal(0.0f), areaCenter(0.0f);+ const bool needPlane = !maskBrush && type != BrushType::Smooth && type != BrushType::Inflate && type != BrushType::Pinch;+ if (needPlane) {+ const uint32_t stride = n >= 4 ? 2 : 1;+ struct Sum {+ glm::dvec3 nrm{0.0}, ctr{0.0};+ double w = 0.0;+ };+ const size_t block = 8;+ std::vector<Sum> sums((cand_.size() + block - 1) / block);+ poolFor(cand_.size(), [&](size_t b, size_t e) {+ Sum acc;+ MicroTriangle T;+ for (size_t ci = b; ci < e; ++ci) {+ const uint32_t t = cand_[ci];+ T.set(m, t, n);+ const int16_t* g = mm.disp.data() + size_t(t) * S;+ for (uint32_t j = 0; j <= n; j += stride)+ for (uint32_t i = 0; i + j <= n; i += stride) {+ glm::vec3 sp, nn;+ T.eval(i, j, sp, nn);+ const glm::vec3 p = sp + nn * (float(g[MicroMesh::index(i, j, n)]) * mm.step);+ const float d2 = glm::dot(p - center, p - center);+ if (d2 >= r2) continue;+ const float w = brushFalloff(std::sqrt(d2), r, focal);+ acc.nrm += glm::dvec3(nn * w);+ acc.ctr += glm::dvec3(p * w);+ acc.w += w;+ }+ }+ sums[b / block] = acc;+ }, block, 2);+ Sum total;+ for (const Sum& x : sums) total.nrm += x.nrm, total.ctr += x.ctr, total.w += x.w;+ if (total.w <= 0.0) {+ // nothing under the brush (it only grazed the boxes): the stitch below still runs for the saved tiles+ areaNormal = -viewDir;+ areaCenter = center;+ } else {+ areaCenter = glm::vec3(total.ctr / total.w);+ const double len = glm::length(total.nrm);+ areaNormal = len > 1e-12 ? glm::vec3(total.nrm / len) : -viewDir;+ }+ }+ glm::vec3 up = projectOnPlane(alphaUp, areaNormal);+ if (glm::length(up) < 1e-6f)+ up = projectOnPlane(std::abs(areaNormal.x) < 0.9f ? glm::vec3(1, 0, 0) : glm::vec3(0, 1, 0), areaNormal);+ up = glm::normalize(up);+ const glm::vec3 right = glm::cross(up, areaNormal);+ const float layerHeight = r * 0.08f * s;+ const bool readsNeighbours = type == BrushType::Smooth || type == BrushType::Pinch || type == BrushType::Crease ||+ type == BrushType::DamStandard;++ // 3. The kernel, in parallel over the triangles (each writes only its own grid). Scale-adaptive: the brush is+ // evaluated on the grid points `stride` apart, about kBrushSamples across its radius, and the points in between+ // get the change interpolated over the coarse micro triangle holding them (a big brush moves big forms; the+ // finer displacement rides on top unchanged). Brush evaluation then costs the same at any micro level; what+ // grows with the level is only writing the interpolated values.+ const float microEdge = baseEdge_ / float(n);+ uint32_t stride = 1;+ if (adaptive && microEdge > 0.0f)+ while (stride < n && microEdge * float(stride * 2) <= r / float(kBrushSamples)) stride *= 2;+ lastStride = stride;+ const uint32_t cm = n / stride;+ std::vector<uint64_t> visited((cand_.size() + 7) / 8, 0);+ std::vector<float> clipped((cand_.size() + 7) / 8, 0.0f); // per block: the largest |d| that didn't fit+ const float invStep = 1.0f / mm.step;+ poolFor(cand_.size(), [&](size_t b, size_t e) {+ thread_local std::vector<int16_t> before;+ thread_local std::vector<float> coarse;+ MicroTriangle T;+ uint64_t count = 0;+ float over = 0.0f;+ for (size_t ci = b; ci < e; ++ci) {+ const uint32_t t = cand_[ci];+ T.set(m, t, n);+ int16_t* g = mm.disp.data() + size_t(t) * S;+ uint8_t* mk = mm.hasMask() ? mm.mask.data() + size_t(t) * S : nullptr;+ if (readsNeighbours && !maskBrush) before.assign(g, g + S); // Jacobi: neighbours as they were+ const int16_t* old = !maskBrush && type == BrushType::Layer ? oldDisp_.data() + size_t(tileOf_[t] - 1) * S : nullptr;+ coarse.assign(size_t(cm + 1) * (cm + 2) / 2, 0.0f);+ bool any = false;+ uint32_t cidx = 0;+ for (uint32_t cj = 0; cj <= cm; ++cj)+ for (uint32_t cii = 0; cii + cj <= cm; ++cii, ++cidx) {+ const uint32_t i = cii * stride, j = cj * stride, idx = MicroMesh::index(i, j, n);+ glm::vec3 sp, nn;+ T.eval(i, j, sp, nn);+ const float d = float(g[idx]) * mm.step;+ const glm::vec3 p = sp + nn * d;+ const glm::vec3 o = p - center;+ const float dist2 = glm::dot(o, o);+ if (dist2 >= r2 * reach * reach) continue;+ ++count;+ if (maskBrush) {+ if (dist2 >= r2) continue;+ coarse[cidx] = std::clamp(maskStrength, 0.0f, 1.0f) * brushFalloff(std::sqrt(dist2), r, focal);+ any = true;+ continue;+ }+ float f = brushFalloff(std::sqrt(dist2), r, focal);+ if (type == BrushType::ClayBuildup) { // square tip, rounded corners (as Sculpt.cpp)+ const float cheb = std::max(std::abs(glm::dot(o, right)), std::abs(glm::dot(o, up))) / r;+ const float corner = std::clamp((1.3f - std::sqrt(dist2) / r) / 0.3f, 0.0f, 1.0f);+ const float edge = std::clamp((1.0f - cheb) / 0.35f, 0.0f, 1.0f);+ f = edge * edge * (3.0f - 2.0f * edge) * corner;+ }+ if (mk && stride == 1) f *= 1.0f - float(mk[idx]) / 255.0f; // (coarse: the fine points' mask, below)+ if (f <= 0.0f) continue;+ const float facing = std::max(glm::dot(nn, areaNormal), 0.3f); // moving along nn reaches a plane this much slower+ float delta = 0.0f;+ auto neighbourAverage = [&](float& lo, float& hi) {+ float sum = 0.0f;+ int c = 0;+ lo = 1e30f, hi = -1e30f;+ forNeighbors(cii, cj, cm, [&](uint32_t a2, uint32_t b2) {+ const float v = float(before[MicroMesh::index(a2 * stride, b2 * stride, n)]);+ sum += v, ++c;+ lo = std::min(lo, v), hi = std::max(hi, v);+ });+ return c ? sum / float(c) : float(before[idx]);+ };+ auto sharpen = [&](float k) { // pinch, on a height field: away from the neighbour average, kept within them+ float lo, hi;+ const float avg = neighbourAverage(lo, hi);+ const float cur = float(before[idx]);+ const float target = std::clamp(cur + (cur - avg) * k, lo, hi);+ return (target - cur) * mm.step;+ };+ switch (type) {+ case BrushType::Standard: delta = sign * s * r * 0.06f * f * glm::dot(areaNormal, nn); break;+ case BrushType::Inflate: delta = sign * s * r * 0.05f * f; break;+ case BrushType::Smooth: {+ float lo, hi;+ const float avg = neighbourAverage(lo, hi);+ delta = (avg - float(before[idx])) * mm.step * std::min(1.0f, s * f);+ break;+ }+ case BrushType::Flatten: {+ const float h = glm::dot(p - areaCenter, areaNormal);+ delta = -h * s * f * (invert ? -0.5f : 1.0f) / facing;+ break;+ }+ case BrushType::Clay: {+ const glm::vec3 pp = areaCenter + areaNormal * (sign * r * 0.05f * s);+ const float h = glm::dot(p - pp, areaNormal);+ if (sign * h < 0.0f) delta = -h * f / facing;+ break;+ }+ case BrushType::ClayBuildup: {+ const glm::vec3 pp = areaCenter + areaNormal * (sign * r * 0.08f * s);+ const float h = glm::dot(p - pp, areaNormal);+ if (sign * h < 0.0f) delta = -h * f / facing;+ break;+ }+ case BrushType::Trim: {+ const glm::vec3 pp = areaCenter - areaNormal * (sign * r * 0.02f * s);+ const float h = glm::dot(p - pp, areaNormal);+ if (sign * h > 0.0f) delta = -h * std::min(1.0f, std::sqrt(f) * (0.5f + s)) / facing;+ break;+ }+ case BrushType::Layer: {+ // Up to one height per stroke above where the point started (overlaps never stack).+ const float start = float(old[idx]) * mm.step;+ const float target = start + sign * layerHeight * f;+ delta = sign > 0.0f ? std::max(0.0f, target - d) : std::min(0.0f, target - d);+ break;+ }+ case BrushType::Pinch: delta = sign * sharpen(0.6f * s * f); break;+ case BrushType::Crease:+ delta = -sign * s * r * 0.05f * f * f + sharpen(0.5f * s * f);+ break;+ case BrushType::DamStandard:+ delta = -sign * s * r * 0.08f * f * f * f * f + sharpen(0.7f * s * f);+ break;+ default: break;+ }+ coarse[cidx] = delta;+ any = any || delta != 0.0f;+ }+ if (!any) continue;+ // Write: every grid point gets the change interpolated from the coarse points around it (stride 1: its own).+ int triMax = mm.triRange[t];+ auto apply = [&](uint32_t idx, float delta) {+ if (maskBrush) {+ const float a = std::clamp(delta, 0.0f, 1.0f);+ const float cur = float(mk[idx]) * (1.0f / 255.0f);+ const float nv = invert ? cur * (1.0f - a) : cur + (1.0f - cur) * a;+ mk[idx] = uint8_t(std::clamp(int(nv * 255.0f + 0.5f), 0, 255));+ return;+ }+ if (stride > 1 && mk) delta *= 1.0f - float(mk[idx]) * (1.0f / 255.0f);+ const float nd = float(g[idx]) + delta * invStep; // (in units of the step)+ if (std::abs(nd) > 32767.0f) over = std::max(over, std::abs(nd) * mm.step);+ const int16_t q = quantizeUnits(nd);+ g[idx] = q;+ triMax = std::max(triMax, q >= 0 ? int(q) : -int(q));+ };+ if (stride == 1) {+ for (uint32_t k = 0; k < S; ++k)+ if (coarse[k] != 0.0f) apply(k, coarse[k]);+ } else {+ interpolateCoarse(coarse.data(), n, stride, apply);+ count += S;+ }+ mm.triRange[t] = uint16_t(std::min(triMax, 32767));+ }+ visited[b / 8] = count;+ clipped[b / 8] = over;+ }, 8, 2);+ for (uint64_t c : visited) points += c;+ kernelMs += lapMs(clock);+ float over = 0.0f;+ for (float c : clipped) over = std::max(over, c);++ // 4. Stitch the shared points.+ stitch(m, mm, cand_);+ if (over > 0.0f) widen(mm, over * 1.5f);+ stitchMs += lapMs(clock);+}++void MicroStroke::widen(MicroMesh& mm, float need) {+ const int div = mm.widen(need);+ if (div == 1) return;+ for (int16_t& v : oldDisp_) v = int16_t(int(v) / div);+ strokeStep_ = mm.step;+}++void MicroStroke::beginGrab(Mesh& m, const BVH& bvh, const glm::vec3& center, float radius, float focal, const glm::vec3& mirror) {+ if (!active_ || !m.micro) return;+ MicroMesh& mm = *m.micro;+ const uint32_t n = mm.n;+ widen(mm, float(mm.rangeMax) * mm.step + radius); // room to move a radius either way+ // Scale-adaptive like dab(): the weights on grid points `stride` apart, interpolated in between when moving.+ uint32_t stride = 1;+ const float microEdge = baseEdge_ / float(n);+ if (adaptive && microEdge > 0.0f)+ while (stride < n && microEdge * float(stride * 2) <= radius / float(kBrushSamples)) stride *= 2;+ lastStride = stride;+ const uint32_t cm = n / stride, cs = (cm + 1) * (cm + 2) / 2;+ std::vector<uint32_t> cand;+ bvh.queryTriangles(m, center, radius + mm.bulgeMax + float(mm.rangeMax) * mm.step, cand);+ std::erase_if(cand, [&](uint32_t t) { return m.triangleHidden(t) || !triangleNear(m, mm, t, center, radius); });+ touch(mm, cand);+ GrabMirror gm;+ gm.mirror = mirror;+ gm.stride = stride;+ gm.firstTri = uint32_t(grabTris_.size());+ const size_t base = grabWeight_.size();+ grabTris_.insert(grabTris_.end(), cand.begin(), cand.end());+ grabWeight_.resize(base + cand.size() * cs, 0.0f);+ grabNormal_.resize(base + cand.size() * cs, glm::vec3(0.0f));+ std::vector<uint8_t> used(cand.size(), 0);+ poolFor(cand.size(), [&](size_t b, size_t e) {+ MicroTriangle T;+ for (size_t k = b; k < e; ++k) {+ const uint32_t t = cand[k];+ T.set(m, t, n);+ const int16_t* g = mm.disp.data() + size_t(t) * mm.samples;+ float* w = grabWeight_.data() + base + k * cs;+ glm::vec3* nrm = grabNormal_.data() + base + k * cs;+ uint32_t c = 0;+ for (uint32_t cj = 0; cj <= cm; ++cj)+ for (uint32_t ci = 0; ci + cj <= cm; ++ci, ++c) {+ const uint32_t i = ci * stride, j = cj * stride;+ glm::vec3 sp, nn;+ T.eval(i, j, sp, nn);+ const glm::vec3 p = sp + nn * (float(g[MicroMesh::index(i, j, n)]) * mm.step);+ const float d = glm::distance(p, center);+ if (d >= radius) continue;+ w[c] = brushFalloff(d, radius, focal);+ nrm[c] = nn;+ used[k] = 1;+ }+ }+ }, 16);+ gm.tris = uint32_t(cand.size());+ grabMirrors_.push_back(gm);+ for (uint8_t u : used) points += u ? (size_t(cm + 1) * (cm + 2) / 2) : 0;+}++void MicroStroke::grab(Mesh& m, const glm::vec3& delta) {+ if (!active_ || !m.micro || grabMirrors_.empty()) return;+ auto clock = std::chrono::steady_clock::now();+ MicroMesh& mm = *m.micro;+ const uint32_t n = mm.n, S = mm.samples;+ const float invStep = 1.0f / mm.step;+ // One mirror after another (a point may be in two), each in parallel over its triangles.+ size_t weightBase = 0;+ for (const GrabMirror& gm : grabMirrors_) {+ const uint32_t cm = n / gm.stride, cs = (cm + 1) * (cm + 2) / 2;+ const glm::vec3 dm = delta * gm.mirror;+ poolFor(gm.tris, [&](size_t b, size_t e) {+ thread_local std::vector<float> coarse;+ coarse.resize(cs);+ for (size_t k = b; k < e; ++k) {+ const uint32_t t = grabTris_[gm.firstTri + k];+ const float* w = grabWeight_.data() + weightBase + k * cs;+ const glm::vec3* nrm = grabNormal_.data() + weightBase + k * cs;+ bool any = false;+ for (uint32_t c = 0; c < cs; ++c) {+ coarse[c] = w[c] > 0.0f ? glm::dot(dm, nrm[c]) * w[c] : 0.0f;+ any = any || coarse[c] != 0.0f;+ }+ if (!any) continue;+ int16_t* g = mm.disp.data() + size_t(t) * S;+ const uint8_t* mk = mm.hasMask() ? mm.mask.data() + size_t(t) * S : nullptr;+ int triMax = mm.triRange[t];+ interpolateCoarse(coarse.data(), n, gm.stride, [&](uint32_t idx, float dd) {+ if (mk) dd *= 1.0f - float(mk[idx]) * (1.0f / 255.0f);+ const int16_t q = quantizeUnits(float(g[idx]) + dd * invStep);+ g[idx] = q;+ triMax = std::max(triMax, q >= 0 ? int(q) : -int(q));+ });+ mm.triRange[t] = uint16_t(std::min(triMax, 32767));+ }+ }, 8);+ weightBase += size_t(gm.tris) * cs;+ }+ kernelMs += lapMs(clock);+ cand_.clear();+ if (++dabEpoch_ == 0) dabEpoch_ = 1;+ for (uint32_t t : grabTris_)+ if (dabStamp_[t] != dabEpoch_) {+ dabStamp_[t] = dabEpoch_;+ cand_.push_back(t);+ }+ stitch(m, mm, cand_);+ stitchMs += lapMs(clock);+}++void MicroStroke::restore(Mesh& m) {+ if (!active_ || !m.micro || tiles_.empty()) return;+ MicroMesh& mm = *m.micro;+ const size_t S = mm.samples;+ poolFor(tiles_.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) {+ const size_t t = tiles_[i];+ std::copy_n(oldDisp_.data() + i * S, S, mm.disp.data() + t * S);+ if (mm.hasMask() && oldMask_.size() == tiles_.size() * S) std::copy_n(oldMask_.data() + i * S, S, mm.mask.data() + t * S);+ }+ }, 64);+ for (uint32_t t : tiles_) mm.markDirty(t);+ ++mm.revision;+}++std::unique_ptr<MicroUndo> MicroStroke::end(Mesh& m) {+ active_ = false;+ if (m.micro) {+ m.micro->stroking = false;- if (const size_t cap = tierConfig().residentPatchCacheMB) m.micro->disp.trim(cap << 20);++ if (const uint64_t cap = currentTierConfig().residentCacheCapMB) m.micro->disp.trim(size_t(cap) << 20);+ }+ grabMirrors_.clear();+ grabTris_.clear();+ grabWeight_.clear();+ grabNormal_.clear();+ if (tiles_.empty() || !m.micro) {+ tiles_.clear();+ return nullptr;+ }+ auto u = std::make_unique<MicroUndo>();+ const MicroMesh& mm = *m.micro;+ const size_t S = mm.samples, count = tiles_.size();+ u->step = strokeStep_;+ u->samples = mm.samples;+ for (uint32_t t : tiles_) tileOf_[t] = 0;+ // The journal: tiles in Morton order of their centres, each the stroke's change, packed.+ AABB box;+ for (uint32_t t : tiles_) {+ const glm::uvec3 tr = m.triangles[t];+ box.expand(m.positions[tr.x]);+ }+ const glm::vec3 lo = box.min, ext = glm::max(box.extent(), glm::vec3(1e-20f));+ auto spread = [](uint32_t x) {+ uint64_t v = x & 0x1FFFFF;+ v = (v | v << 32) & 0x1F00000000FFFFull;+ v = (v | v << 16) & 0x1F0000FF0000FFull;+ v = (v | v << 8) & 0x100F00F00F00F00Full;+ v = (v | v << 4) & 0x10C30C30C30C30C3ull;+ v = (v | v << 2) & 0x1249249249249249ull;+ return v;+ };+ std::vector<std::pair<uint64_t, uint32_t>> order(count);+ for (size_t i = 0; i < count; ++i) {+ const glm::uvec3 tr = m.triangles[tiles_[i]];+ const glm::vec3 c = ((m.positions[tr.x] + m.positions[tr.y] + m.positions[tr.z]) / 3.0f - lo) / ext;+ const glm::uvec3 q(glm::clamp(c, 0.0f, 1.0f) * 2097151.0f);+ order[i] = {spread(q.x) | spread(q.y) << 1 | spread(q.z) << 2, uint32_t(i)};+ }+ std::sort(order.begin(), order.end());+ std::vector<int16_t> change(count * S), firsts(count);+ std::atomic<bool> fits{true};+ poolFor(count, [&](size_t b, size_t e) {+ for (size_t k = b; k < e; ++k) {+ const size_t i = order[k].second;+ const int16_t* now = mm.disp.data() + size_t(tiles_[i]) * S;+ const int16_t* was = oldDisp_.data() + i * S;+ // The change, predicted from the point before it in its row (a row's first point: from the row below;+ // the very first is kept apart), so a smooth change needs few bits.+ const uint32_t n = mm.n;+ uint32_t p = 0;+ for (uint32_t j = 0; j <= n; ++j)+ for (uint32_t i = 0; i + j <= n; ++i, ++p) {+ const int d = int(now[p]) - int(was[p]);+ int pred = 0;+ if (i > 0) pred = int(now[p - 1]) - int(was[p - 1]);+ else if (j > 0) {+ const uint32_t q = MicroMesh::index(0, j - 1, n);+ pred = int(now[q]) - int(was[q]);+ }+ const int r = d - pred;+ if (r < -32767 || r > 32767) fits = false;+ if (p == 0) firsts[k] = int16_t(std::clamp(d, -32767, 32767)), fits = fits && d >= -32767 && d <= 32767;+ change[k * S + p] = p == 0 ? int16_t(0) : int16_t(r);+ }+ }+ }, 256);+ const bool masked = mm.hasMask() && oldMask_.size() == count * S;+ if (fits) {+ u->journal = true;+ u->tris.resize(count);+ u->keys.resize(count);+ for (size_t k = 0; k < count; ++k) u->tris[k] = tiles_[order[k].second], u->keys[k] = order[k].first;+ microPackTiles(change.data(), count, mm.samples, u->packed);+ u->firsts = std::move(firsts);+ if (masked) {+ u->mask.resize(count * S);+ for (size_t k = 0; k < count; ++k)+ std::copy_n(oldMask_.data() + size_t(order[k].second) * S, S, u->mask.data() + k * S);+ }+ } else { // (a change wider than 16 bits: whole old tiles)+ u->tris = tiles_;+ u->disp = std::move(oldDisp_);+ if (masked) u->mask = std::move(oldMask_);+ }+ u->maskAdded = maskAdded_;+ tiles_.clear();+ oldDisp_.clear();+ oldMask_.clear();+ return u;+}++} // namespace sfdiff --cc src/core/MicroStore.hindex c8f47c16,00000000..6f88bbe6mode 100644,000000..100644--- a/src/core/MicroStore.h+++ b/src/core/MicroStore.h@@@ -1,83 -1,0 +1,83 @@@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Storage for a micro level's displacements (core/Micro.h): in memory, or out of core.+//+// Out of core, the array is a memory-mapped sparse file in the user's cache folder (not /tmp, which is often RAM):+// - untouched tiles are holes in the file: they take neither disk nor memory (a fresh micro level is all holes);+// - the operating system's page cache is the LRU: tiles a brush or the renderer touched stay resident while there+// is memory to spare and are written back and dropped when there isn't, so a level larger than RAM works (1B+// grid points = 2 GB of tiles, mostly cold);+// - the file is deleted as soon as it is open (it disappears with the process, crash or not).+// Saved projects use the tile codec below (delta + per-tile range), so untouched tiles cost 3 bytes on disk.+//+// The interface is the part of std::vector<int16_t> the micro code uses, so the brushes, renderer and undo don't+// care where the values live.+#pragma once++#include <cstddef>+#include <cstdint>+#include <string>+#include <vector>++namespace sf {++class MicroStore {+public:+ MicroStore() = default;+ MicroStore(std::vector<int16_t>&& v) : heap_(std::move(v)) {}+ MicroStore(const MicroStore& o);+ MicroStore(MicroStore&& o) noexcept;+ MicroStore& operator=(const MicroStore& o);+ MicroStore& operator=(MicroStore&& o) noexcept;+ MicroStore& operator=(std::vector<int16_t>&& v);+ ~MicroStore();++ // In memory: n copies of v.+ void assign(size_t n, int16_t v);+ // Out of core: n zeros in a sparse mapped file (falls back to memory, returning false with `error`, where+ // mapping isn't available).+ bool assignMapped(size_t n, std::string& error);+ bool mapped() const { return map_ != nullptr; }++ int16_t* data() { return map_ ? map_ : heap_.data(); }+ const int16_t* data() const { return map_ ? map_ : heap_.data(); }+ size_t size() const { return map_ ? mapCount_ : heap_.size(); }+ bool empty() const { return size() == 0; }+ int16_t& operator[](size_t i) { return data()[i]; }+ int16_t operator[](size_t i) const { return data()[i]; }+ int16_t* begin() { return data(); }+ int16_t* end() { return data() + size(); }+ const int16_t* begin() const { return data(); }+ const int16_t* end() const { return data() + size(); }+ // Bytes of memory it takes: the array in memory; mapped, what is resident now (mincore).+ size_t capacity() const; // (in elements, like std::vector: residentBytes() / 2 when mapped)+ size_t residentBytes() const;+ // Out of core: when more than `maxBytes` are resident, writes the dirty tiles back and lets the system drop- // them (they page in again when touched). TierConfig::residentPatchCacheMB. Returns the bytes resident after.++ // them (they page in again when touched). TierConfig::residentCacheCapMB. Returns the bytes resident after.+ size_t trim(size_t maxBytes);+ // True when every page holding elements [first, first + count) is in memory (always, in memory).+ bool rangeResident(size_t first, size_t count) const;+ std::vector<int16_t> toVector() const { return std::vector<int16_t>(begin(), end()); }+ operator std::vector<int16_t>() const { return toVector(); }+ bool operator==(const std::vector<int16_t>& v) const;+ bool operator!=(const std::vector<int16_t>& v) const { return !(*this == v); }+ bool operator==(const MicroStore& o) const;++ // Where out-of-core files go: $SF_MICRO_SWAP_DIR, else the user cache folder (~/.cache/sculptforge).+ static std::string swapFolder();++private:+ void release();+ std::vector<int16_t> heap_;+ int16_t* map_ = nullptr;+ size_t mapCount_ = 0;+};++// `out` must hold zeros (untouched tiles aren't written).+// Tile codec (projects): each tile of `samples` values as its minimum (int16), a bit width b (0-16) and the+// values minus the minimum in b bits each. An untouched tile (all zero) is 3 bytes.+void microPackTiles(const int16_t* values, size_t tiles, uint32_t samples, std::vector<uint8_t>& out);+bool microUnpackTiles(const uint8_t* data, size_t size, size_t tiles, uint32_t samples, int16_t* out);++} // namespace sfdiff --cc src/core/TierConfig.cppindex 3b0bc8c1,71fe324f..e38d2112--- a/src/core/TierConfig.cpp+++ b/src/core/TierConfig.cpp@@@ -7,44 -8,90 +8,96 @@@namespace sf {- TierConfig TierConfig::laptop() {- TierConfig c;- c.name = "Laptop";- c.residentPatchCacheMB = 1024;- c.activeTriangleBudget = size_t(2) << 20;- c.continuousNormals = false;- c.shadeBudgetPoints = size_t(1) << 20;- c.outOfCorePoints = size_t(256) << 20; // 512 MB of tiles- return c;+ const char* powerSourceName(PowerSource power) {+ switch (power) {+ case PowerSource::AC: return "ac";+ case PowerSource::Battery: return "battery";+ case PowerSource::Unknown: break;+ }+ return "unknown";}- TierConfig TierConfig::workstation() { return TierConfig(); }-- namespace {-- std::mutex& tierMutex() {- static std::mutex m;- return m;+ int targetHzForDisplay(int hz) {+ if (hz >= 143) return 144;+ if (hz >= 119) return 120;+ return 60;}- TierConfig& current() {- static TierConfig c = [] {- const char* e = std::getenv("SF_TIER");- return e && std::string(e) == "laptop" ? TierConfig::laptop() : TierConfig::workstation();- }();+ TierConfig tierConfigFor(const HardwareProfile& p, PowerSource power, int displayHz) {+ TierConfig c;+ c.tier = p.tier;+ c.power = power;+ const uint64_t ram = p.hardware.ramMB ? p.hardware.ramMB : 8192;+ const PerformanceSettings& s = p.settings;+ switch (p.tier) {+ case ProfileTier::Software:+ c.residentCacheCapMB = std::clamp<uint64_t>(ram / 8, 256, 1024);+ c.activeTriangleBudget = 500'000;+ break;+ case ProfileTier::Laptop:+ c.residentCacheCapMB = std::clamp<uint64_t>(ram / 4, 512, 4096);+ c.activeTriangleBudget = 2'000'000;+ break;+ case ProfileTier::Workstation:+ c.residentCacheCapMB = std::clamp<uint64_t>(ram * 2 / 5, 4096, 65536);+ c.activeTriangleBudget = std::clamp<uint64_t>(s.renderTriangleBudget / 2, 8'000'000, 64'000'000);+ break;+ }+ c.uploadBudgetMBPerFrame = std::max<uint64_t>(s.uploadBudgetMBPerFrame, 4);+ c.zeroCopyUMA = p.hardware.gpuKind == GpuKind::Unified || p.hardware.gpuKind == GpuKind::Integrated;+ c.draftBrushMode = p.tier != ProfileTier::Workstation;+ c.targetHz = p.overrides.targetFps ? p.overrides.targetFps : targetHzForDisplay(displayHz);+ if (p.tier == ProfileTier::Software) c.targetHz = std::min(c.targetHz, 60);+ if (c.onBattery()) {+ // On battery: less heat and power. Draft brushes, half the uploads, 60 Hz (unless set by hand).+ c.draftBrushMode = true;+ c.uploadBudgetMBPerFrame = std::max<uint64_t>(c.uploadBudgetMBPerFrame / 2, 4);+ if (!p.overrides.targetFps) c.targetHz = 60;+ }++ // Micro levels: shading per frame by tier; out of core once a level's tiles (2 bytes a point) would pass the++ // resident cache.++ c.shadeBudgetPoints = p.tier == ProfileTier::Workstation ? (3u << 20) : p.tier == ProfileTier::Laptop ? (1u << 20) : (1u << 19);++ c.outOfCorePoints = (c.residentCacheCapMB << 20) / 2;+ if (p.overrides.draftBrush == 1) c.draftBrushMode = true;+ else if (p.overrides.draftBrush == 2) c.draftBrushMode = false;return c;}+ Json tierConfigJson(const TierConfig& c) {+ Json j = Json::object();+ j.set("tier", tierName(c.tier));+ j.set("resident_cache_cap_mb", double(c.residentCacheCapMB));+ j.set("active_triangle_budget", double(c.activeTriangleBudget));++ j.set("shade_budget_points", double(c.shadeBudgetPoints));++ j.set("out_of_core_points", double(c.outOfCorePoints));+ j.set("upload_budget_mb_per_frame", double(c.uploadBudgetMBPerFrame));+ j.set("draft_brush_mode", c.draftBrushMode);+ j.set("zero_copy_uma", c.zeroCopyUMA);+ j.set("target_hz", c.targetHz);+ j.set("power", powerSourceName(c.power));+ j.set("on_battery", c.onBattery());+ return j;+ }++ namespace {+ std::mutex g_mutex;+ TierConfig g_config;+ std::atomic<uint64_t> g_revision{0};} // namespace- const TierConfig& tierConfig() {- std::lock_guard<std::mutex> lock(tierMutex());- return current();+ TierConfig currentTierConfig() {+ std::lock_guard<std::mutex> lock(g_mutex);+ return g_config;}- void setTierConfig(const TierConfig& config) {- std::lock_guard<std::mutex> lock(tierMutex());- current() = config;+ void setCurrentTierConfig(const TierConfig& config) {+ {+ std::lock_guard<std::mutex> lock(g_mutex);+ g_config = config;+ }+ g_revision.fetch_add(1, std::memory_order_relaxed);}+ uint64_t tierConfigRevision() { return g_revision.load(std::memory_order_relaxed); }+} // namespace sfdiff --cc src/core/TierConfig.hindex 278fcf25,d058f701..a26b92b0--- a/src/core/TierConfig.h+++ b/src/core/TierConfig.h@@@ -11,24 -23,33 +23,38 @@@namespace sf {+ enum class PowerSource { Unknown, AC, Battery };+ const char* powerSourceName(PowerSource power); // "unknown", "ac", "battery"+struct TierConfig {- std::string name = "Workstation";- // Resident patch cache: the most memory out-of-core micro tiles may keep resident (MicroStore::trim). 0 = no cap.- size_t residentPatchCacheMB = 0;- // Active-triangle budget: the most triangles a frame draws for micro levels (render/MicroRenderer.h).- size_t activeTriangleBudget = size_t(8) << 20;- // Normal updates while sculpting: continuous (every frame, up to shadeBudgetPoints) or draft (a quarter of- // that while the stroke runs; the rest when it ends).- bool continuousNormals = true;- size_t shadeBudgetPoints = size_t(3) << 20;- // Micro levels larger than this many grid points go out of core (MicroStore; 0 = a quarter of RAM).- size_t outOfCorePoints = 0;-- static TierConfig laptop();- static TierConfig workstation();+ ProfileTier tier = ProfileTier::Laptop;+ uint64_t residentCacheCapMB = 2048; // most memory resident caches (micromesh pages, streamed levels) may hold+ uint64_t activeTriangleBudget = 2'000'000; // triangles a brush / micro-displacement may keep "active" (full+ // detail, updated live) at once; the rest waits or uses coarser levels+ uint64_t uploadBudgetMBPerFrame = 64; // vertex data to send to the GPU per frame before deferring the rest+ bool draftBrushMode = true; // defer normal and cavity recomputation to pen release (Laptop, battery);+ // false: continuous, every dab (Workstation)+ bool zeroCopyUMA = false; // the GPU shares system memory: uploads may write in place (persistent+ // mapped buffers) instead of staging copies+ int targetHz = 60; // 60, 120 or 144: what the display shows (60 on battery, Software)+ PowerSource power = PowerSource::Unknown;++ // Micro-displacement levels (core/Micro.h): grid points of shading (normals, cavity) the renderer recomputes per++ // frame at most (a quarter of it while a stroke runs in draft mode; the rest follows), and the size in grid++ // points above which a level is kept out of core (MicroStore; 0 = when it would take a quarter of RAM).++ uint64_t shadeBudgetPoints = 3u << 20;++ uint64_t outOfCorePoints = 0;+ bool onBattery() const { return power == PowerSource::Battery; }};- const TierConfig& tierConfig();- void setTierConfig(const TierConfig& config);+ // 144 for displays of 143 Hz and up, 120 from 119 Hz, else 60 (also when unknown: 0).+ int targetHzForDisplay(int displayHz);+ // The knobs for `profile` on this power source and display (displayHz 0 = unknown). Deterministic.+ TierConfig tierConfigFor(const HardwareProfile& profile, PowerSource power, int displayHz);+ Json tierConfigJson(const TierConfig& config);++ // The configuration in effect (the app sets it from the profile, the power source and the display).+ TierConfig currentTierConfig();+ void setCurrentTierConfig(const TierConfig& config);+ uint64_t tierConfigRevision();} // namespace sfdiff --cc src/render/MicroRenderer.cppindex d0a730d5,00000000..b1e8eda7mode 100644,000000..100644--- a/src/render/MicroRenderer.cpp+++ b/src/render/MicroRenderer.cpp@@@ -1,679 -1,0 +1,679 @@@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "render/MicroRenderer.h"++#include "core/ThreadPool.h"+#include "core/TierConfig.h"++#include <glm/gtc/type_ptr.hpp>++#include <algorithm>+#include <bit>+#include <cmath>+#include <cstring>++namespace sf {++namespace {++constexpr GLenum kUnitTris = 0x84C8, kUnitBase = 0x84C9, kUnitDisp = 0x84CA, kUnitLevels = 0x84CB, kUnitShade = 0x84CC;+constexpr uint32_t kChunkTexels = 1u << 26;+constexpr uint32_t kNoCluster = 0xFFFFFFFFu;++// Evaluates the micro surface exactly as MicroTriangle::evalWeights (corners in ascending vertex order), so+// both triangles of a shared edge compute bit-identical points there.+const char* kMicroVS = R"(+layout(location = 0) in uvec2 aIJ; // the patch's grid point at uLevel+uniform mat4 uView;+uniform mat4 uProj;+uniform usamplerBuffer uTris; // per slot: (corner vertices, -), (cluster across each edge, -)+uniform samplerBuffer uBase; // per base vertex: position, normal+uniform isamplerBuffer uDisp; // this chunk's displacement grids+uniform usamplerBuffer uLevels; // per cluster: the level it draws+uniform int uSlotBase, uChunkSlot, uLevel, uN, uSamples;+// > 0: a plain (not instanced) draw with this many corners per base triangle, each corner's grid point packed+// i | j << 16 in uCorners (small patches: instancing a few triangles at a time costs more than it saves)+uniform int uUnrolled;+uniform int uCorners[48];+uniform float uStep;+flat out int vSlot;+out vec2 vIJ;+#ifdef FLAT+out vec3 vViewPos;+#endif+vec3 P[3];+vec3 Nn[3];+int ord[3];+int localSlot;+int sampleIndex(int i, int j) { return j * (uN + 1) - (j * (j - 1)) / 2 + i; }+vec3 microPos(int I, int J) {+ float inv = 1.0 / float(uN);+ float wc[3] = float[3](float(uN - I - J) * inv, float(I) * inv, float(J) * inv);+ float w0 = wc[ord[0]], w1 = wc[ord[1]], w2 = wc[ord[2]];+ vec3 f = P[0] * w0;+ f += P[1] * w1;+ f += P[2] * w2;+ vec3 nn = Nn[0] * w0;+ nn += Nn[1] * w1;+ nn += Nn[2] * w2;+ vec3 pull = Nn[0] * (w0 * dot(f - P[0], Nn[0]));+ pull += Nn[1] * (w1 * dot(f - P[1], Nn[1]));+ pull += Nn[2] * (w2 * dot(f - P[2], Nn[2]));+ vec3 s = f - pull * 0.75;+ float len = length(nn);+ vec3 n = len > 1e-20 ? nn / len : vec3(0.0, 0.0, 1.0);+ float d = float(texelFetch(uDisp, localSlot * uSamples + sampleIndex(I, J)).r) * uStep;+ return s + n * d;+}+ivec2 edgePoint(int e, int k, int m) {+ if (e == 0) return ivec2(k, 0);+ if (e == 1) return ivec2(m - k, k);+ return ivec2(0, m - k);+}+void main() {+ int instance = gl_InstanceID;+ uvec2 ij = aIJ;+ if (uUnrolled > 0) {+ instance = gl_VertexID / uUnrolled;+ int c = uCorners[gl_VertexID - instance * uUnrolled];+ ij = uvec2(uint(c & 0xFFFF), uint(c >> 16));+ }+ int slot = uSlotBase + instance;+ localSlot = slot - uChunkSlot;+ vSlot = localSlot;+ uvec4 tv = texelFetch(uTris, slot * 2);+ uvec4 nb = texelFetch(uTris, slot * 2 + 1);+ uint v[3] = uint[3](tv.x, tv.y, tv.z);+ ord[0] = 0; ord[1] = 1; ord[2] = 2;+ if (v[ord[0]] > v[ord[1]]) { int t = ord[0]; ord[0] = ord[1]; ord[1] = t; }+ if (v[ord[1]] > v[ord[2]]) { int t = ord[1]; ord[1] = ord[2]; ord[2] = t; }+ if (v[ord[0]] > v[ord[1]]) { int t = ord[0]; ord[0] = ord[1]; ord[1] = t; }+ for (int k = 0; k < 3; ++k) {+ int vi = int(v[ord[k]]);+ P[k] = texelFetch(uBase, vi * 2).xyz;+ Nn[k] = texelFetch(uBase, vi * 2 + 1).xyz;+ }+ int m = 1 << uLevel, sc = uN >> uLevel;+ int i = int(ij.x), j = int(ij.y);+ int edge = -1, k = 0;+ if (j == 0 && i > 0 && i < m) { edge = 0; k = i; }+ else if (i + j == m && j > 0 && j < m) { edge = 1; k = j; }+ else if (i == 0 && j > 0 && j < m) { edge = 2; k = m - j; }+ vec3 pos;+ int elevel = uLevel;+ if (edge >= 0) {+ uint c = edge == 0 ? nb.x : edge == 1 ? nb.y : nb.z;+ if (c != 0xFFFFFFFFu) elevel = min(uLevel, int(texelFetch(uLevels, int(c)).r));+ }+ int stepE = 1 << (uLevel - elevel);+ int r = k % stepE;+ if (edge >= 0 && r != 0) {+ ivec2 a = edgePoint(edge, k - r, m) * sc, b = edgePoint(edge, k - r + stepE, m) * sc;+ pos = mix(microPos(a.x, a.y), microPos(b.x, b.y), float(r) / float(stepE));+ } else {+ pos = microPos(i * sc, j * sc);+ }+ vIJ = vec2(float(i * sc), float(j * sc));+ vec4 p = uView * vec4(pos, 1.0);+#ifdef FLAT+ vViewPos = p.xyz;+#endif+ gl_Position = uProj * p;+}+)";++uint32_t spread10(uint32_t x) {+ x &= 0x3FF;+ x = (x | (x << 16)) & 0x030000FF;+ x = (x | (x << 8)) & 0x0300F00F;+ x = (x | (x << 4)) & 0x030C30C3;+ x = (x | (x << 2)) & 0x09249249;+ return x;+}++} // namespace++const char* microVertexShaderSource() { return kMicroVS; }++MicroRenderer::~MicroRenderer() { release(); }++void MicroRenderer::release() {+ for (Chunk& c : chunks_) {+ gl::DeleteBuffers(1, &c.disp);+ gl::DeleteBuffers(1, &c.shade);+ gl::DeleteTextures(1, &c.dispTex);+ gl::DeleteTextures(1, &c.shadeTex);+ }+ chunks_.clear();+ for (GLuint* b : {&triData_, &baseData_, &levelData_})+ if (*b) gl::DeleteBuffers(1, b), *b = 0;+ for (GLuint* t : {&triTex_, &baseTex_, &levelTex_})+ if (*t) gl::DeleteTextures(1, t), *t = 0;+ for (Patch& p : patches_) {+ if (p.vao) gl::DeleteVertexArrays(1, &p.vao);+ if (p.vbo) gl::DeleteBuffers(1, &p.vbo);+ if (p.ibo) gl::DeleteBuffers(1, &p.ibo);+ }+ patches_.clear();+ if (emptyVao_) gl::DeleteVertexArrays(1, &emptyVao_), emptyVao_ = 0;+ serial_ = 0;+ bytes_ = 0;+}++size_t MicroRenderer::gpuBytes() const { return bytes_; }++void MicroRenderer::ensurePatches(int maxLevel) {+ while (int(patches_.size()) <= maxLevel) {+ const int l = int(patches_.size());+ const uint32_t m = 1u << l;+ std::vector<uint16_t> verts, idx;+ for (uint32_t j = 0; j <= m; ++j)+ for (uint32_t i = 0; i + j <= m; ++i) verts.push_back(uint16_t(i)), verts.push_back(uint16_t(j));+ for (uint32_t j = 0; j < m; ++j) {+ const uint32_t row = MicroMesh::index(0, j, m), next = MicroMesh::index(0, j + 1, m);+ for (uint32_t i = 0; i + j < m; ++i) {+ idx.insert(idx.end(), {uint16_t(row + i), uint16_t(row + i + 1), uint16_t(next + i)});+ if (i + j + 1 < m) idx.insert(idx.end(), {uint16_t(row + i + 1), uint16_t(next + i + 1), uint16_t(next + i)});+ }+ }+ Patch p;+ gl::GenVertexArrays(1, &p.vao);+ gl::GenBuffers(1, &p.vbo);+ gl::GenBuffers(1, &p.ibo);+ gl::BindVertexArray(p.vao);+ gl::BindBuffer(GL_ARRAY_BUFFER, p.vbo);+ gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(verts.size() * 2), verts.data(), GL_STATIC_DRAW);+ gl::EnableVertexAttribArray(0);+ gl::VertexAttribIPointer(0, 2, GL_UNSIGNED_SHORT, 4, nullptr);+ gl::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, p.ibo);+ gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr(idx.size() * 2), idx.data(), GL_STATIC_DRAW);+ gl::BindVertexArray(0);+ gl::BindBuffer(GL_ARRAY_BUFFER, 0);+ p.indices = GLsizei(idx.size());+ if (l <= kUnrolledLevels)+ for (uint16_t k : idx) p.corners.push_back(GLint(verts[size_t(k) * 2]) | GLint(verts[size_t(k) * 2 + 1]) << 16);+ patches_.push_back(p);+ }+}++void MicroRenderer::buildLayout(const Mesh& mesh) {+ const MicroMesh& mm = *mesh.micro;+ const uint32_t nt = mm.baseTriangles;+ // Slots in Morton order of the triangle centres: clusters of consecutive slots are compact.+ box_ = AABB();+ for (const glm::vec3& p : mesh.positions) box_.expand(p);+ const glm::vec3 lo = box_.min, ext = glm::max(box_.extent(), glm::vec3(1e-20f));+ std::vector<uint64_t> keys(nt);+ poolFor(nt, [&](size_t b, size_t e) {+ for (size_t t = b; t < e; ++t) {+ const glm::uvec3 tr = mesh.triangles[t];+ const glm::vec3 c = ((mesh.positions[tr.x] + mesh.positions[tr.y] + mesh.positions[tr.z]) / 3.0f - lo) / ext;+ const glm::uvec3 q = glm::uvec3(glm::clamp(c, 0.0f, 1.0f) * 1023.0f);+ keys[t] = uint64_t(spread10(q.x) | spread10(q.y) << 1 | spread10(q.z) << 2) << 32 | t;+ }+ }, 1 << 14);+ std::sort(keys.begin(), keys.end());+ order_.resize(nt);+ slotOf_.resize(nt);+ for (uint32_t s = 0; s < nt; ++s) {+ order_[s] = uint32_t(keys[s]);+ slotOf_[order_[s]] = s;+ }+ std::vector<uint64_t>().swap(keys);+ const uint32_t clusterSize = std::clamp(65536u >> (2 * mm.level), 16u, 1024u);+ clusterShift_ = uint32_t(std::countr_zero(clusterSize));+ chunkSlots_ = std::max(clusterSize, (kChunkTexels / mm.samples) & ~(clusterSize - 1));+ const uint32_t clusters = (nt + clusterSize - 1) >> clusterShift_;+ // Corners and the clusters across the edges, per slot.+ std::vector<uint32_t> tri(size_t(nt) * 8);+ poolFor(nt, [&](size_t b, size_t e) {+ for (size_t s = b; s < e; ++s) {+ const uint32_t t = order_[s];+ const glm::uvec3 tr = mesh.triangles[t];+ uint32_t* o = tri.data() + s * 8;+ o[0] = tr.x, o[1] = tr.y, o[2] = tr.z, o[3] = 0;+ for (int k = 0; k < 3; ++k) {+ const uint32_t nb = mm.edgeNeighbor[size_t(t) * 3 + size_t(k)];+ o[4 + k] = nb == MicroMesh::kNone ? kNoCluster : slotOf_[nb >> 2] >> clusterShift_;+ }+ o[7] = 0;+ }+ }, 1 << 14);+ auto makeTex = [&](GLuint& buffer, GLuint& tex, GLenum format, const void* data, size_t bytes) {+ if (!buffer) gl::GenBuffers(1, &buffer);+ if (!tex) gl::GenTextures(1, &tex);+ gl::BindBuffer(GL_TEXTURE_BUFFER, buffer);+ gl::BufferData(GL_TEXTURE_BUFFER, GLsizeiptr(bytes), data, GL_STATIC_DRAW);+ gl::BindTexture(GL_TEXTURE_BUFFER, tex);+ gl::TexBuffer(GL_TEXTURE_BUFFER, format, buffer);+ bytes_ += bytes;+ };+ bytes_ = 0;+ makeTex(triData_, triTex_, GL_RGBA32UI, tri.data(), tri.size() * 4);+ levels_.assign(clusters, 0);+ makeTex(levelData_, levelTex_, GL_R32UI, levels_.data(), levels_.size() * 4);+ // Grid chunks.+ for (Chunk& c : chunks_) {+ gl::DeleteBuffers(1, &c.disp);+ gl::DeleteBuffers(1, &c.shade);+ gl::DeleteTextures(1, &c.dispTex);+ gl::DeleteTextures(1, &c.shadeTex);+ }+ chunks_.clear();+ for (uint32_t first = 0; first < nt; first += chunkSlots_) {+ Chunk c;+ c.firstSlot = first;+ c.slots = std::min(chunkSlots_, nt - first);+ const size_t points = size_t(c.slots) * mm.samples;+ makeTex(c.disp, c.dispTex, GL_R16I, nullptr, points * 2);+ makeTex(c.shade, c.shadeTex, GL_RGBA8, nullptr, points * 4);+ chunks_.push_back(c);+ }+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);+ gl::BindTexture(GL_TEXTURE_BUFFER, 0);+ closed_ = closedOriented(mesh);+ bounds_.assign(clusters, ClusterBounds());+ clusterEdge_.assign(clusters, 0.0f);+ std::vector<uint32_t> all(clusters);+ for (uint32_t c = 0; c < clusters; ++c) all[c] = c;+ updateClusterBounds(mesh, all);+ pending_.assign((size_t(nt) + 63) / 64, 0);+ pendingCount_ = 0;+ ensurePatches(mm.level);+}++void MicroRenderer::uploadBase(const Mesh& mesh) {+ std::vector<glm::vec4> data(mesh.vertexCount() * 2);+ poolFor(mesh.vertexCount(), [&](size_t b, size_t e) {+ for (size_t v = b; v < e; ++v) {+ data[v * 2] = glm::vec4(mesh.positions[v], 1.0f);+ data[v * 2 + 1] = glm::vec4(mesh.normals[v], 0.0f);+ }+ }, 1 << 14);+ if (!baseData_) gl::GenBuffers(1, &baseData_);+ if (!baseTex_) gl::GenTextures(1, &baseTex_);+ gl::BindBuffer(GL_TEXTURE_BUFFER, baseData_);+ gl::BufferData(GL_TEXTURE_BUFFER, GLsizeiptr(data.size() * sizeof(glm::vec4)), data.data(), GL_STATIC_DRAW);+ gl::BindTexture(GL_TEXTURE_BUFFER, baseTex_);+ gl::TexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, baseData_);+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);+ gl::BindTexture(GL_TEXTURE_BUFFER, 0);+ bytes_ += data.size() * sizeof(glm::vec4);+}++void MicroRenderer::updateClusterBounds(const Mesh& mesh, const std::vector<uint32_t>& clusters) {+ const MicroMesh& mm = *mesh.micro;+ const uint32_t nt = mm.baseTriangles, size = 1u << clusterShift_;+ poolFor(clusters.size(), [&](size_t b, size_t e) {+ for (size_t ci = b; ci < e; ++ci) {+ const uint32_t c = clusters[ci];+ const uint32_t s0 = c << clusterShift_, s1 = std::min(nt, s0 + size);+ AABB box;+ glm::vec3 axis(0.0f);+ float edge = 0.0f;+ uint16_t range = 0;+ for (uint32_t s = s0; s < s1; ++s) {+ const uint32_t t = order_[s];+ const glm::uvec3 tr = mesh.triangles[t];+ for (int k = 0; k < 3; ++k) {+ box.expand(mesh.positions[tr[k]]);+ axis += mesh.normals[tr[k]];+ }+ edge += glm::distance(mesh.positions[tr.x], mesh.positions[tr.y]) + glm::distance(mesh.positions[tr.y], mesh.positions[tr.z]) ++ glm::distance(mesh.positions[tr.z], mesh.positions[tr.x]);+ range = std::max(range, mm.triRange[t]);+ }+ ClusterBounds cb;+ cb.center = box.center();+ float radius = 0.0f, cosMin = 1.0f;+ const float al = glm::length(axis);+ axis = al > 0.0f ? axis / al : glm::vec3(0, 0, 1);+ for (uint32_t s = s0; s < s1; ++s) {+ const glm::uvec3 tr = mesh.triangles[order_[s]];+ for (int k = 0; k < 3; ++k) {+ radius = std::max(radius, glm::distance(mesh.positions[tr[k]], cb.center));+ cosMin = std::min(cosMin, glm::dot(mesh.normals[tr[k]], axis));+ }+ }+ cb.radius = radius + mm.bulgeMax + float(range) * mm.step;+ cb.axis = axis;+ // Micro detail tilts the surface off the base normals: half a radian of margin, and none when the+ // displacement is large next to the cluster (its faces could point anywhere).+ const float angle = std::acos(std::clamp(cosMin, -1.0f, 1.0f)) + 0.5f;+ cb.coneAngle = angle < 1.45f && float(range) * mm.step < radius * 0.5f ? angle : -1.0f;+ bounds_[c] = cb;+ clusterEdge_[c] = edge / float(3 * (s1 - s0)) / float(mm.n) * float(mm.n); // (base edge)+ }+ }, 16);+}++void MicroRenderer::uploadDispTiles(const Mesh& mesh, std::vector<uint32_t>& slots, bool all) {+ const MicroMesh& mm = *mesh.micro;+ const size_t S = mm.samples;+ if (all) {+ for (Chunk& c : chunks_) {+ gl::BindBuffer(GL_TEXTURE_BUFFER, c.disp);+ auto* dst = static_cast<int16_t*>(gl::MapBufferRange(GL_TEXTURE_BUFFER, 0, GLsizeiptr(size_t(c.slots) * S * 2),+ GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT));+ if (!dst) continue;+ poolFor(c.slots, [&](size_t b, size_t e) {+ for (size_t s = b; s < e; ++s) std::memcpy(dst + s * S, mm.disp.data() + size_t(order_[c.firstSlot + s]) * S, S * 2);+ }, 1024);+ gl::UnmapBuffer(GL_TEXTURE_BUFFER);+ }+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);+ return;+ }+ if (slots.empty()) return;+ std::sort(slots.begin(), slots.end());+ staging_.resize(slots.size() * S * 2);+ auto* st = reinterpret_cast<int16_t*>(staging_.data());+ poolFor(slots.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) std::memcpy(st + i * S, mm.disp.data() + size_t(order_[slots[i]]) * S, S * 2);+ }, 256);+ for (size_t i = 0; i < slots.size();) {+ const uint32_t chunk = slots[i] / chunkSlots_;+ size_t j = i + 1;+ while (j < slots.size() && slots[j] == slots[j - 1] + 1 && slots[j] / chunkSlots_ == chunk) ++j;+ const Chunk& c = chunks_[chunk];+ gl::BindBuffer(GL_TEXTURE_BUFFER, c.disp);+ gl::BufferSubData(GL_TEXTURE_BUFFER, GLintptr(size_t(slots[i] - c.firstSlot) * S * 2), GLsizeiptr((j - i) * S * 2),+ st + i * S);+ i = j;+ }+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);+}++// Shading for the base triangles marked pending: all of it (`all`), or up to shadeBudget grid points of it.+void MicroRenderer::shadePending(const Mesh& mesh, bool all) {+ const MicroMesh& mm = *mesh.micro;+ const size_t S = mm.samples;+ if (all) {+ std::vector<uint32_t*> mapped(chunks_.size(), nullptr);+ for (size_t i = 0; i < chunks_.size(); ++i) {+ gl::BindBuffer(GL_TEXTURE_BUFFER, chunks_[i].shade);+ mapped[i] = static_cast<uint32_t*>(gl::MapBufferRange(GL_TEXTURE_BUFFER, 0, GLsizeiptr(size_t(chunks_[i].slots) * S * 4),+ GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT));+ }+ thread_local std::vector<uint32_t> sink;+ shader_.shade(mesh, {}, true, written_, [&](uint32_t t) -> uint32_t* {+ const uint32_t s = slotOf_[t], c = s / chunkSlots_;+ if (!mapped[c]) {+ sink.resize(S);+ return sink.data();+ }+ return mapped[c] + size_t(s - chunks_[c].firstSlot) * S;+ });+ for (size_t i = 0; i < chunks_.size(); ++i) {+ gl::BindBuffer(GL_TEXTURE_BUFFER, chunks_[i].shade);+ if (mapped[i]) gl::UnmapBuffer(GL_TEXTURE_BUFFER);+ }+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);+ std::fill(pending_.begin(), pending_.end(), 0);+ pendingCount_ = 0;+ return;+ }+ // The pending triangles, newest first (scratch_ holds this sync's dirty ones, already marked).+ std::vector<uint32_t>& seeds = scratch_;+ const size_t limit = shadeBudget ? std::max<size_t>(1, shadeBudget / (S * 3)) : SIZE_MAX; // (the ring triples it)+ if (seeds.size() < limit)+ for (size_t w = 0; w < pending_.size() && seeds.size() < limit; ++w)+ for (uint64_t bits = pending_[w]; bits && seeds.size() < limit; bits &= bits - 1) {+ const uint32_t t = uint32_t(w * 64 + size_t(std::countr_zero(bits)));+ seeds.push_back(t);+ }+ std::sort(seeds.begin(), seeds.end());+ seeds.erase(std::unique(seeds.begin(), seeds.end()), seeds.end());+ if (seeds.size() > limit) seeds.resize(limit);+ if (seeds.empty()) return;+ std::vector<uint32_t> sorted;+ if (stageIndex_.size() != mm.baseTriangles) stageIndex_.assign(mm.baseTriangles, 0);+ shader_.shade(mesh, seeds, false, written_, [&](uint32_t t) -> uint32_t* {+ return reinterpret_cast<uint32_t*>(staging_.data()) + size_t(stageIndex_[t]) * S;+ }, [&](std::span<const uint32_t> tris) {+ sorted.assign(tris.begin(), tris.end());+ std::sort(sorted.begin(), sorted.end(), [&](uint32_t a, uint32_t b) { return slotOf_[a] < slotOf_[b]; });+ for (size_t i = 0; i < sorted.size(); ++i) stageIndex_[sorted[i]] = uint32_t(i);+ staging_.resize(sorted.size() * S * 4);+ });+ const auto* st = reinterpret_cast<const uint32_t*>(staging_.data());+ for (size_t i = 0; i < sorted.size();) {+ const uint32_t s0 = slotOf_[sorted[i]], chunk = s0 / chunkSlots_;+ size_t j = i + 1;+ while (j < sorted.size() && slotOf_[sorted[j]] == slotOf_[sorted[j - 1]] + 1 && slotOf_[sorted[j]] / chunkSlots_ == chunk) ++j;+ const Chunk& c = chunks_[chunk];+ gl::BindBuffer(GL_TEXTURE_BUFFER, c.shade);+ gl::BufferSubData(GL_TEXTURE_BUFFER, GLintptr(size_t(s0 - c.firstSlot) * S * 4), GLsizeiptr((j - i) * S * 4), st + i * S);+ i = j;+ }+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);+ for (uint32_t t : written_) {+ uint64_t& w = pending_[t >> 6];+ const uint64_t bit = uint64_t(1) << (t & 63);+ if (w & bit) w &= ~bit, --pendingCount_;+ }+}++bool MicroRenderer::sync(Mesh& mesh) {+ MicroMesh& mm = *mesh.micro;+ mm.ensureTopology(mesh);+ if (mm.dirtyBits.size() != (size_t(mm.baseTriangles) + 63) / 64) mm.dirtyBits.assign((size_t(mm.baseTriangles) + 63) / 64, 0);+ const bool baseMoved = mesh.dirtyBegin < mesh.dirtyEnd;+ const bool full = serial_ != mm.serial || baseTriangles_ != mm.baseTriangles || baseVertices_ != mm.baseVertices ||+ level_ != mm.level || mesh.topologyDirty;+ for (int i = 0; i < 16 && gl::GetError() != GL_NO_ERROR; ++i) {+ }+ if (full) {+ serial_ = mm.serial;+ baseTriangles_ = mm.baseTriangles;+ baseVertices_ = mm.baseVertices;+ level_ = mm.level;+ n_ = mm.n;+ samples_ = mm.samples;+ buildLayout(mesh);+ uploadBase(mesh);+ uploadDispTiles(mesh, scratch_, true);+ shadePending(mesh, true);+ } else {+ // The base cage moved (dual-scale Move, a transform, undo of either): the detail rides along on the GPU (it+ // is relative to the base); what changes is the base, the bounds and the shading around moved vertices.+ bool baseEverywhere = false;+ std::vector<uint32_t> baseTris;+ if (baseMoved) {+ size_t moved = 0;+ const uint32_t b0 = mesh.dirtyBegin, b1 = std::min<uint32_t>(mesh.dirtyEnd, uint32_t(mesh.vertexCount()));+ for (uint32_t v = b0; v < b1; ++v)+ if (mesh.vertexDirty(v)) ++moved;+ baseEverywhere = moved * 4 > mesh.vertexCount();+ if (baseEverywhere) {+ uploadBase(mesh);+ bytes_ -= mesh.vertexCount() * 2 * sizeof(glm::vec4);+ std::vector<uint32_t> all(bounds_.size());+ for (uint32_t c = 0; c < all.size(); ++c) all[c] = c;+ updateClusterBounds(mesh, all);+ } else {+ std::vector<glm::vec4> part(size_t(b1 - b0) * 2);+ for (uint32_t v = b0; v < b1; ++v) {+ part[size_t(v - b0) * 2] = glm::vec4(mesh.positions[v], 1.0f);+ part[size_t(v - b0) * 2 + 1] = glm::vec4(mesh.normals[v], 0.0f);+ if (mesh.vertexDirty(v))+ for (uint32_t t : mesh.vertexTriangles(v)) baseTris.push_back(t);+ }+ gl::BindBuffer(GL_TEXTURE_BUFFER, baseData_);+ gl::BufferSubData(GL_TEXTURE_BUFFER, GLintptr(size_t(b0) * 2 * sizeof(glm::vec4)), GLsizeiptr(part.size() * sizeof(glm::vec4)),+ part.data());+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);+ }+ }+ // This sync's dirty triangles.+ scratch_.clear();+ for (size_t w = 0; w < mm.dirtyBits.size(); ++w)+ for (uint64_t bits = mm.dirtyBits[w]; bits; bits &= bits - 1) scratch_.push_back(uint32_t(w * 64 + size_t(std::countr_zero(bits))));+ if (!baseTris.empty()) {+ scratch_.insert(scratch_.end(), baseTris.begin(), baseTris.end());+ std::sort(scratch_.begin(), scratch_.end());+ scratch_.erase(std::unique(scratch_.begin(), scratch_.end()), scratch_.end());+ }+ if (mm.allDirty || mm.rescaled) {+ uploadDispTiles(mesh, scratch_, true);+ } else if (!scratch_.empty()) {+ std::vector<uint32_t> slots(scratch_.size());+ for (size_t i = 0; i < scratch_.size(); ++i) slots[i] = slotOf_[scratch_[i]];+ uploadDispTiles(mesh, slots, false);+ }+ if (!scratch_.empty()) { // their clusters may reach further now+ std::vector<uint32_t> cl;+ for (uint32_t t : scratch_) cl.push_back(slotOf_[t] >> clusterShift_);+ std::sort(cl.begin(), cl.end());+ cl.erase(std::unique(cl.begin(), cl.end()), cl.end());+ updateClusterBounds(mesh, cl);+ }+ if (mm.allDirty || baseEverywhere) {+ shadePending(mesh, true);+ } else {+ for (uint32_t t : scratch_) {+ uint64_t& w = pending_[t >> 6];+ const uint64_t bit = uint64_t(1) << (t & 63);+ if (!(w & bit)) w |= bit, ++pendingCount_;+ }+ // TierConfig: continuous normals shade up to the budget every sync; draft ones a quarter of it while a+ // stroke runs (the rest follows when it ends).- const TierConfig& tier = tierConfig();- shadeBudget = tier.shadeBudgetPoints / (mm.stroking && !tier.continuousNormals ? 4 : 1);++ const TierConfig tier = currentTierConfig();++ shadeBudget = size_t(tier.shadeBudgetPoints) / (mm.stroking && tier.draftBrushMode ? 4 : 1);+ if (pendingCount_) shadePending(mesh, false);+ }+ }+ step_ = mm.step;+ mm.clearDirty();+ mesh.clearDirty();+ mesh.topologyDirty = false;+ mesh.facesDirty = false;+ bool oom = false;+ for (int i = 0; i < 16; ++i) {+ const GLenum e = gl::GetError();+ if (e == GL_NO_ERROR) break;+ oom = oom || e == GL_OUT_OF_MEMORY;+ }+ return !oom;+}++size_t MicroRenderer::draw(GLuint program, const CullView& cullIn, const glm::mat4& proj, const glm::vec4& viewport, size_t budget,+ float targetPx) {+ if (chunks_.empty() || bounds_.empty()) return 0;+ const uint32_t clusters = uint32_t(bounds_.size()), size = 1u << clusterShift_;+ CullView cull = cullIn;+ // Clusters facing away can go when the mesh is closed and the eye is outside it.+ const glm::vec3 grow(box_.extent() * 0.1f);+ const bool eyeInside = glm::all(glm::greaterThanEqual(cull.eye, box_.min - grow)) && glm::all(glm::lessThanEqual(cull.eye, box_.max + grow));+ cull.backfaces = closed_ && !eyeInside && !cull.ortho;+ want_.resize(clusters);+ std::vector<uint8_t> visible(clusters);+ const float h = std::max(viewport.w, 1.0f);+ const bool ortho = proj[3][3] == 1.0f;+ const float scale = h * proj[1][1] * 0.5f;+ std::vector<float> pxEdge(clusters);+ for (uint32_t c = 0; c < clusters; ++c) {+ const ClusterBounds& b = bounds_[c];+ visible[c] = insideFrustum(cull, b) && !facingAway(cull, b);+ const float dist = ortho ? 1.0f : std::max(glm::distance(cull.eye, b.center) - b.radius, std::max(cull.nearDistance, 1e-6f));+ pxEdge[c] = clusterEdge_[c] * scale / dist; // a base edge in pixels+ }+ auto choose = [&](float target) {+ size_t total = 0;+ for (uint32_t c = 0; c < clusters; ++c) {+ const float ratio = pxEdge[c] / target;+ int l = ratio <= 1.0f ? 0 : int(std::ceil(std::log2(ratio)));+ l = std::clamp(l, 0, level_);+ want_[c] = int8_t(l);+ if (visible[c]) total += size_t(std::min(size, baseTriangles_ - (c << clusterShift_))) << (2 * l);+ }+ return total;+ };+ float target = std::max(targetPx, 0.25f);+ size_t total = choose(target);+ for (int it = 0; it < 24 && budget && total > budget; ++it) total = choose(target *= 1.4142f);+ lastTargetPx = target;+ for (uint32_t c = 0; c < clusters; ++c) levels_[c] = uint32_t(want_[c]);+ gl::BindBuffer(GL_TEXTURE_BUFFER, levelData_);+ gl::BufferSubData(GL_TEXTURE_BUFFER, 0, GLsizeiptr(levels_.size() * 4), levels_.data());+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);++ if (u_.program != program) {+ u_.program = program;+ auto at = [&](const char* name) { return gl::GetUniformLocation(program, name); };+ u_.slotBase = at("uSlotBase");+ u_.chunkSlot = at("uChunkSlot");+ u_.level = at("uLevel");+ u_.n = at("uN");+ u_.samples = at("uSamples");+ u_.step = at("uStep");+ u_.unrolled = at("uUnrolled");+ u_.corners = at("uCorners");+ gl::Uniform1i(at("uTris"), 8);+ gl::Uniform1i(at("uBase"), 9);+ gl::Uniform1i(at("uDisp"), 10);+ gl::Uniform1i(at("uLevels"), 11);+ gl::Uniform1i(at("uShade"), 12);+ }+ gl::Uniform1i(u_.n, int(n_));+ gl::Uniform1i(u_.samples, int(samples_));+ gl::Uniform1f(u_.step, step_);+ gl::ActiveTexture(kUnitTris);+ gl::BindTexture(GL_TEXTURE_BUFFER, triTex_);+ gl::ActiveTexture(kUnitBase);+ gl::BindTexture(GL_TEXTURE_BUFFER, baseTex_);+ gl::ActiveTexture(kUnitLevels);+ gl::BindTexture(GL_TEXTURE_BUFFER, levelTex_);+ if (closed_) gl::Enable(GL_CULL_FACE);+ size_t drawn = 0;+ int boundChunk = -1;+ int unrolledLevel = -2; // the patch uCorners holds (-1: instanced draws)+ for (uint32_t c = 0; c < clusters;) {+ if (!visible[c]) {+ ++c;+ continue;+ }+ const int l = want_[c];+ const uint32_t chunk = (c << clusterShift_) / chunkSlots_;+ uint32_t e = c + 1;+ while (e < clusters && visible[e] && want_[e] == l && (e << clusterShift_) / chunkSlots_ == chunk) ++e;+ const uint32_t s0 = c << clusterShift_, s1 = std::min(baseTriangles_, e << clusterShift_);+ if (int(chunk) != boundChunk) {+ boundChunk = int(chunk);+ gl::ActiveTexture(kUnitDisp);+ gl::BindTexture(GL_TEXTURE_BUFFER, chunks_[chunk].dispTex);+ gl::ActiveTexture(kUnitShade);+ gl::BindTexture(GL_TEXTURE_BUFFER, chunks_[chunk].shadeTex);+ gl::Uniform1i(u_.chunkSlot, int(chunks_[chunk].firstSlot));+ }+ gl::Uniform1i(u_.level, l);+ gl::Uniform1i(u_.slotBase, int(s0));+ const Patch& p = patches_[size_t(l)];+ if (l <= kUnrolledLevels) {+ if (!emptyVao_) gl::GenVertexArrays(1, &emptyVao_);+ if (l != unrolledLevel) {+ gl::Uniform1i(u_.unrolled, GLsizei(p.corners.size()));+ gl::Uniform1iv(u_.corners, GLsizei(p.corners.size()), p.corners.data());+ unrolledLevel = l;+ }+ gl::BindVertexArray(emptyVao_);+ gl::DrawArrays(GL_TRIANGLES, 0, GLsizei(size_t(s1 - s0) * p.corners.size()));+ } else {+ if (unrolledLevel != -1) gl::Uniform1i(u_.unrolled, 0), unrolledLevel = -1;+ gl::BindVertexArray(p.vao);+ gl::DrawElementsInstanced(GL_TRIANGLES, p.indices, GL_UNSIGNED_SHORT, nullptr, GLsizei(s1 - s0));+ }+ drawn += size_t(s1 - s0) << (2 * l);+ c = e;+ }+ gl::Disable(GL_CULL_FACE);+ gl::BindVertexArray(0);+ for (GLenum unit : {kUnitTris, kUnitBase, kUnitDisp, kUnitLevels, kUnitShade}) {+ gl::ActiveTexture(unit);+ gl::BindTexture(GL_TEXTURE_BUFFER, 0);+ }+ gl::ActiveTexture(GL_TEXTURE0);+ return drawn;+}++} // namespace sfdiff --cc src/render/Renderer.cppindex 88022340,a19b422e..e7b8289d--- a/src/render/Renderer.cpp+++ b/src/render/Renderer.cpp@@@ -2302,39 -2231,7 +2302,39 @@@ void Renderer::drawClusters(const MeshS}// One mesh. Mask and polygroup colours are for the SubTool being edited; polypaint shows on all of them.+void Renderer::drawMicro(const MeshSlot& s, bool active, bool flat, const RenderSettings& settings) {+ const MeshProgram* p = meshProgram(kMicro | (flat ? kFlat : 0));+ if (!p) return;+ gl::UseProgram(p->id);+ gl::UniformMatrix4fv(p->view, 1, GL_FALSE, glm::value_ptr(frameView_));+ gl::UniformMatrix4fv(p->proj, 1, GL_FALSE, glm::value_ptr(frameProj_));+ gl::Uniform4fv(p->viewport, 1, glm::value_ptr(frameViewport_));+ const bool orthographic = frameProj_[3][3] == 1.0f;+ gl::Uniform2f(p->projScale, orthographic ? 1e20f : frameProj_[0][0], orthographic ? 1e20f : frameProj_[1][1]);+ gl::Uniform3fv(p->baseColor, 1, glm::value_ptr(settings.baseColor));+ gl::Uniform1i(p->matcap, matcapTexture(settings.matcap) ? 1 : 0);+ const MatcapCavity cavity = matcapCavity(settings.matcap);+ gl::Uniform2f(p->matcapCavity, cavity.crease, cavity.ridge);+ gl::Uniform1i(p->paint, 0);+ gl::Uniform1i(p->showMask, active && settings.showMask ? 1 : 0);+ gl::Uniform1i(p->groups, active && settings.showPolygroups ? 2 : 0);+ gl::Uniform1i(p->dim, !active && settings.dimInactive ? 1 : 0);+ gl::Uniform1i(p->twoSided, 1);+ // Moving (Fast Navigation): a coarser target and half the budget, so orbiting stays smooth.+ const bool moving = settings.motionProxy;- const size_t full = settings.renderTriangleBudget ? settings.renderTriangleBudget : tierConfig().activeTriangleBudget;++ const size_t full = settings.renderTriangleBudget ? settings.renderTriangleBudget : size_t(currentTierConfig().activeTriangleBudget);+ const size_t budget = moving ? full / 2 : full;+ const float target = settings.microTargetPx * (moving ? 2.0f : 1.0f);+ // (the budget is shared by the micro SubTools on screen: each gets it whole; one is the usual case)+ const_cast<MeshSlot&>(s).microDrawn = s.micro->draw(p->id, frameCull_, frameProj_, frameViewport_, budget, target);+ lastDrawn_ += s.microDrawn;+}+void Renderer::drawSlot(const MeshSlot& s, bool active, bool flat, const RenderSettings& settings) {+ if (s.micro) {+ drawMicro(s, active, flat, settings);+ return;+ }// A painted texture shows through the textured program (polypaint still multiplies it).const bool textured = s.hasUvs && s.paintTexture && settings.showPolypaint && settings.showTexture;// A baked normal map preview bends the shading normal (core/Bake.h).diff --cc tests/test_micro.cppindex a2b076e3,00000000..40f6e4e5mode 100644,000000..100644--- a/tests/test_micro.cpp+++ b/tests/test_micro.cpp@@@ -1,569 -1,0 +1,572 @@@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Micro-displacement levels (core/Micro.h): divide, brushes, stitching, undo, picking, shading, bake, maps,+// projects and the commands.+#include "TestHarness.h"++#include "core/Benchmark.h"+#include "core/Commands.h"+#include "core/Micro.h"+#include "core/Multires.h"+#include "core/Primitives.h"+#include "core/Project.h"+#include "core/TierConfig.h"+#include "io/Zip.h"++#include <chrono>+#include <cmath>+#include <cstdlib>+#include <cstring>+#include <filesystem>+#include <algorithm>+#include <map>++using namespace sf;++namespace {++Document microDoc(int level, size_t baseTriangles = 20000) {+ Document doc = makeDoc(makeBenchSphere(baseTriangles));+ std::string err;+ CHECK(microDivide(doc.mesh, level, err));+ return doc;+}++// Every point shared by two base triangles (edges) or more (corners) has the same displacement in each copy, and+// the micro positions there are bit-identical.+bool watertight(const Mesh& m) {+ const MicroMesh& mm = *m.micro;+ const uint32_t n = mm.n, S = mm.samples;+ for (uint32_t t = 0; t < mm.baseTriangles; ++t)+ for (int e = 0; e < 3; ++e) {+ const uint32_t nb = mm.edgeNeighbor[size_t(t) * 3 + size_t(e)];+ if (nb == MicroMesh::kNone) continue;+ const uint32_t u = nb >> 2;+ const int f = int(nb & 3);+ const bool reversed = m.triangles[u][f] != m.triangles[t][e];+ for (uint32_t k = 0; k <= n; ++k) {+ uint32_t i, j, i2, j2;+ MicroMesh::edgePoint(e, k, n, i, j);+ MicroMesh::edgePoint(f, reversed ? n - k : k, n, i2, j2);+ if (mm.disp[size_t(t) * S + MicroMesh::index(i, j, n)] != mm.disp[size_t(u) * S + MicroMesh::index(i2, j2, n)])+ return false;+ const glm::vec3 a = microPoint(m, t, i, j), b = microPoint(m, u, i2, j2);+ if (std::memcmp(&a, &b, sizeof a) != 0) return false;+ }+ }+ return true;+}++DabParams dabAt(const glm::vec3& c, float r, float strength = 0.5f) {+ DabParams p;+ p.center = c;+ p.radius = r;+ p.strength = strength;+ p.viewDir = glm::vec3(0, 0, -1);+ return p;+}++// The micro surface's distance from the origin under the point (0, 0, 1) (the sphere's front).+float frontHeight(const Document& doc) {+ RayHit hit;+ CHECK(microRaycast(doc.mesh, doc.bvh, glm::vec3(0.001f, 0.002f, 5.0f), glm::vec3(0, 0, -1), hit));+ return glm::length(hit.position);+}++} // namespace++TEST(micro_divide_counts_and_memory) {+ Document doc = microDoc(3);+ const MicroMesh& mm = *doc.mesh.micro;+ CHECK(mm.n == 8);+ CHECK(mm.samples == 45);+ CHECK(microTriangleCount(doc.mesh) == doc.mesh.triangleCount() * 64);+ CHECK(mm.disp.size() == doc.mesh.triangleCount() * 45);+ // 2 bytes a point, about 1.4 points per unique micro vertex at level 3: well under 4 bytes per micro vertex.+ CHECK(double(mm.disp.size() * 2) / double(mm.microVertices()) < 3.0);+ CHECK(microText(doc.mesh).rfind("Micro 3", 0) == 0);+ // Every base edge has a neighbour on a closed sphere.+ for (uint32_t e : mm.edgeNeighbor) CHECK(e != MicroMesh::kNone);+ // d = 0 everywhere: the surface is the smooth Phong surface, close to the unit sphere.+ // (The bench sphere is a subdivided cube: compare with the radius of each base triangle's corners. The flat+ // triangles sag inwards by up to e^2 / 8; Phong tessellation takes most of that back.)+ float worstMicro = 0.0f, worstFlat = 0.0f;+ for (uint32_t t = 0; t < mm.baseTriangles; t += 97) {+ const glm::uvec3 tr = doc.mesh.triangles[t];+ const float r = (glm::length(doc.mesh.positions[tr.x]) + glm::length(doc.mesh.positions[tr.y]) + glm::length(doc.mesh.positions[tr.z])) / 3.0f;+ MicroTriangle T;+ T.set(doc.mesh, t, mm.n);+ for (uint32_t j = 0; j <= mm.n; ++j)+ for (uint32_t i = 0; i + j <= mm.n; ++i) {+ worstMicro = std::max(worstMicro, std::abs(glm::length(microPoint(doc.mesh, t, i, j)) - r));+ worstFlat = std::max(worstFlat, std::abs(glm::length(T.flat(i, j)) - r));+ }+ }+ CHECK(worstMicro < worstFlat * 0.5f);+ CHECK(watertight(doc.mesh));+ std::string err;+ CHECK(!microDivide(doc.mesh, 2, err)); // one micro level per SubTool+}++TEST(micro_divide_needs_top_level) {+ Document doc = makeDoc(makeBenchSphere(20000));+ std::string err;+ CHECK(subdivSetLevel(doc.mesh, 0, err, &doc.bvh));+ CHECK(!microDivide(doc.mesh, 2, err));+ CHECK(err.find("highest") != std::string::npos);+ CHECK(subdivSetLevel(doc.mesh, subdivLevelCount(doc.mesh) - 1, err, &doc.bvh));+ CHECK(microDivide(doc.mesh, 2, err));+ // ... and blocks subdivision changes while it exists.+ CHECK(!subdivSetLevel(doc.mesh, 0, err, &doc.bvh));+ CHECK(err.find("micro") != std::string::npos);+ CHECK(!subdivDivide(doc.mesh, true, err));+}++TEST(micro_standard_brush_raises_and_undoes) {+ Document doc = microDoc(4);+ const std::vector<int16_t> before = doc.mesh.micro->disp;+ const float h0 = frontHeight(doc);+ Symmetry sym;+ CHECK(doc.sculptor.beginStroke(doc.mesh, "Standard"));+ for (int i = 0; i < 10; ++i) doc.sculptor.dab(doc.mesh, doc.bvh, BrushType::Standard, dabAt(glm::vec3(0, 0, 1), 0.3f), sym);+ UndoRecord r = doc.sculptor.endStroke();+ CHECK(r.micro != nullptr);+ CHECK(!r.empty());+ CHECK(r.micro->tris.size() > 0 && r.micro->tris.size() < doc.mesh.triangleCount());+ doc.undo.push(std::move(r));+ const float h1 = frontHeight(doc);+ CHECK(h1 > h0 + 0.01f);+ CHECK(watertight(doc.mesh));+ // X symmetry: the mirrored side moved too, the back didn't.+ CHECK(doc.mesh.micro->rangeMax > 0);+ const std::vector<int16_t> after = doc.mesh.micro->disp;+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));+ CHECK(doc.mesh.micro->disp == before);+ CHECK(doc.undo.redo(doc.mesh, doc.bvh));+ CHECK(doc.mesh.micro->disp == after);+}++TEST(micro_brushes_each_change_the_surface_and_stay_closed) {+ struct Case {+ BrushType type;+ bool invert;+ };+ for (const Case c : {Case{BrushType::Clay, false}, Case{BrushType::ClayBuildup, false}, Case{BrushType::Inflate, false},+ Case{BrushType::Flatten, false}, Case{BrushType::Crease, false}, Case{BrushType::Pinch, false},+ Case{BrushType::DamStandard, false}, Case{BrushType::Layer, false}, Case{BrushType::Trim, false},+ Case{BrushType::Standard, true}}) {+ Document doc = microDoc(3);+ microNoise(doc.mesh, 0.01f, 12.0f); // something to flatten, trim and pinch+ const std::vector<int16_t> before = doc.mesh.micro->disp;+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, brushName(c.type));+ for (int i = 0; i < 6; ++i) {+ DabParams p = dabAt(glm::normalize(glm::vec3(0.1f * float(i), 0.2f, 1.0f)), 0.25f, 0.8f);+ p.invert = c.invert;+ doc.sculptor.dab(doc.mesh, doc.bvh, c.type, p, sym);+ }+ UndoRecord r = doc.sculptor.endStroke();+ CHECK(doc.mesh.micro->disp != before);+ CHECK(watertight(doc.mesh));+ doc.undo.push(std::move(r));+ doc.undo.undo(doc.mesh, doc.bvh);+ CHECK(doc.mesh.micro->disp == before);+ }+}++TEST(micro_smooth_flattens_noise) {+ Document doc = microDoc(3);+ microNoise(doc.mesh, 0.01f, 30.0f);+ auto roughness = [&] { // spread of the displacement in the triangles near the front+ double sum = 0, sq = 0;+ size_t count = 0;+ const MicroMesh& mm = *doc.mesh.micro;+ for (uint32_t t = 0; t < mm.baseTriangles; ++t) {+ const glm::uvec3 tr = doc.mesh.triangles[t];+ if (doc.mesh.positions[tr.x].z < 0.97f) continue;+ for (uint32_t k = 0; k < mm.samples; ++k) {+ const double v = mm.disp[size_t(t) * mm.samples + k];+ sum += v, sq += v * v, ++count;+ }+ }+ const double mean = sum / double(count);+ return sq / double(count) - mean * mean;+ };+ const double r0 = roughness();+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, "Smooth");+ for (int i = 0; i < 8; ++i) doc.sculptor.dab(doc.mesh, doc.bvh, BrushType::Smooth, dabAt(glm::vec3(0, 0, 1), 0.4f, 1.0f), sym);+ doc.undo.push(doc.sculptor.endStroke());+ CHECK(roughness() < r0 * 0.5);+ CHECK(watertight(doc.mesh));+}++TEST(micro_mask_brush_protects) {+ Document doc = microDoc(3);+ Symmetry sym;+ sym.x = false;+ // Mask the front.+ CHECK(doc.sculptor.beginStroke(doc.mesh, "Mask"));+ DabParams mp = dabAt(glm::vec3(0, 0, 1), 0.5f, 1.0f);+ for (int i = 0; i < 8; ++i) doc.sculptor.dabMask(doc.mesh, doc.bvh, mp, sym);+ UndoRecord mr = doc.sculptor.endStroke();+ CHECK(doc.mesh.micro->hasMask());+ CHECK(mr.micro && mr.micro->maskAdded);+ doc.undo.push(std::move(mr));+ const float h0 = frontHeight(doc);+ doc.sculptor.beginStroke(doc.mesh, "Standard");+ for (int i = 0; i < 5; ++i) doc.sculptor.dab(doc.mesh, doc.bvh, BrushType::Standard, dabAt(glm::vec3(0, 0, 1), 0.3f), sym);+ doc.undo.push(doc.sculptor.endStroke());+ CHECK(std::abs(frontHeight(doc) - h0) < 1e-4f); // fully masked at the centre+ // Undo both: the mask goes away again (it didn't exist before).+ doc.undo.undo(doc.mesh, doc.bvh);+ doc.undo.undo(doc.mesh, doc.bvh);+ CHECK(!doc.mesh.micro->hasMask());+ doc.undo.redo(doc.mesh, doc.bvh);+ CHECK(doc.mesh.micro->hasMask());+}++TEST(micro_move_deforms_the_base_cage) {+ // Dual scale: Move reshapes the base below the micro level; the detail (displacements) rides along unchanged.+ Document doc = microDoc(3);+ microNoise(doc.mesh, 0.005f, 20.0f);+ const std::vector<int16_t> detail = doc.mesh.micro->disp;+ const float h0 = frontHeight(doc);+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, "Move");+ doc.sculptor.beginGrab(doc.mesh, doc.bvh, dabAt(glm::vec3(0, 0, 1), 0.4f, 1.0f), sym);+ for (int i = 0; i < 5; ++i) doc.sculptor.grab(doc.mesh, doc.bvh, glm::vec3(0.03f, 0, 0.02f));+ UndoRecord r = doc.sculptor.endStroke();+ CHECK(!r.positions.empty() && !r.micro);+ doc.undo.push(std::move(r));+ CHECK(doc.mesh.micro->disp == detail);+ CHECK(frontHeight(doc) > h0 + 0.05f);+ CHECK(watertight(doc.mesh));+ doc.undo.undo(doc.mesh, doc.bvh);+ CHECK(std::abs(frontHeight(doc) - h0) < 1e-4f);+}++TEST(micro_move_brush_moves_along_normals) {+ Document doc = microDoc(3);+ doc.sculptor.microMoveAlongNormals = true;+ const float h0 = frontHeight(doc);+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, "Move");+ doc.sculptor.beginGrab(doc.mesh, doc.bvh, dabAt(glm::vec3(0, 0, 1), 0.3f, 1.0f), sym);+ for (int i = 0; i < 5; ++i) doc.sculptor.grab(doc.mesh, doc.bvh, glm::vec3(0, 0, 0.02f));+ doc.undo.push(doc.sculptor.endStroke());+ CHECK(frontHeight(doc) > h0 + 0.05f);+ CHECK(watertight(doc.mesh));+}++TEST(micro_range_widens_for_big_strokes) {+ Document doc = microDoc(2);+ const float step0 = doc.mesh.micro->step;+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, "Standard");+ for (int i = 0; i < 60; ++i) doc.sculptor.dab(doc.mesh, doc.bvh, BrushType::Standard, dabAt(glm::vec3(0, 0, 1), 0.8f, 1.0f), sym);+ UndoRecord r = doc.sculptor.endStroke();+ CHECK(doc.mesh.micro->step > step0);+ CHECK(frontHeight(doc) > 1.5f); // nothing clipped at the old range (+/- 8 base edges)+ doc.undo.push(std::move(r));+ doc.undo.undo(doc.mesh, doc.bvh);+ CHECK(std::abs(frontHeight(doc) - 1.0f) < 0.01f);+}++TEST(micro_raycast_hits_the_micro_surface) {+ Document doc = microDoc(4);+ RayHit base, micro;+ CHECK(doc.bvh.raycast(doc.mesh, glm::vec3(0.01f, 0.01f, 5), glm::vec3(0, 0, -1), base));+ CHECK(microRaycast(doc.mesh, doc.bvh, glm::vec3(0.01f, 0.01f, 5), glm::vec3(0, 0, -1), micro));+ CHECK(std::abs(micro.position.z - base.position.z) < 1e-3f); // flat: the Phong surface is near the base+ microNoise(doc.mesh, 0.02f, 8.0f);+ CHECK(surfaceRaycast(doc.mesh, doc.bvh, glm::vec3(0.01f, 0.01f, 5), glm::vec3(0, 0, -1), micro));+ // The hit lies on the micro surface: its point at the hit's base triangle and weights matches.+ const float h = glm::length(micro.position);+ CHECK(std::abs(h - 1.0f) < 0.03f);+ CHECK(std::abs(micro.t - (5.0f - micro.position.z)) < 1e-4f);+}++TEST(micro_shading_partial_matches_full) {+ Document doc = microDoc(3, 5000);+ microNoise(doc.mesh, 0.01f, 10.0f);+ const MicroMesh& mm = *doc.mesh.micro;+ std::vector<uint32_t> full(size_t(mm.baseTriangles) * mm.samples, 0), part(full.size(), 0);+ MicroShader shader;+ std::vector<uint32_t> written;+ shader.shade(doc.mesh, {}, true, written, [&](uint32_t t) { return full.data() + size_t(t) * mm.samples; });+ CHECK(written.size() == mm.baseTriangles);+ // A brush changes a few triangles; shading just what changed must agree with shading everything.+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, "Standard");+ doc.sculptor.dab(doc.mesh, doc.bvh, BrushType::Standard, dabAt(glm::vec3(0, 0, 1), 0.2f, 1.0f), sym);+ UndoRecord r = doc.sculptor.endStroke();+ std::vector<uint32_t> dirty = r.micro->tris;+ part = full;+ shader.shade(doc.mesh, dirty, false, written, [&](uint32_t t) { return part.data() + size_t(t) * mm.samples; });+ CHECK(written.size() > dirty.size());+ shader.shade(doc.mesh, {}, true, written, [&](uint32_t t) { return full.data() + size_t(t) * mm.samples; });+ CHECK(part == full);+ // Normals point outwards on the sphere.+ int outward = 0, total = 0;+ for (uint32_t t = 0; t < mm.baseTriangles; t += 53) {+ const uint32_t v = full[size_t(t) * mm.samples];+ const float ex = float(v & 255) / 255.0f * 2.0f - 1.0f, ey = float((v >> 8) & 255) / 255.0f * 2.0f - 1.0f;+ glm::vec3 nn(ex, ey, 1.0f - std::abs(ex) - std::abs(ey));+ const float tt = std::max(-nn.z, 0.0f);+ nn.x += nn.x >= 0.0f ? -tt : tt;+ nn.y += nn.y >= 0.0f ? -tt : tt;+ outward += glm::dot(glm::normalize(nn), doc.mesh.positions[doc.mesh.triangles[t].x]) > 0.8f;+ ++total;+ }+ CHECK(outward >= total * 9 / 10);+}++TEST(micro_bake_mesh_is_closed_and_matches) {+ Document doc = microDoc(3, 3000);+ microNoise(doc.mesh, 0.01f, 10.0f);+ Mesh baked;+ std::string err;+ CHECK(microBakeMesh(doc.mesh, 3, baked, err));+ CHECK(baked.triangleCount() == microTriangleCount(doc.mesh));+ CHECK(baked.vertexCount() == doc.mesh.micro->microVertices());+ // Closed: Euler characteristic 2 (V - E + F with E = 3F/2).+ CHECK(long(baked.vertexCount()) - long(baked.triangleCount()) * 3 / 2 + long(baked.triangleCount()) == 2);+ // The base corners are the micro points there.+ const glm::vec3 c = microPoint(doc.mesh, 0, 0, 0);+ CHECK(glm::distance(baked.positions[doc.mesh.triangles[0].x], c) < 1e-6f);+ // Half the level: a quarter of the triangles.+ Mesh half;+ CHECK(microBakeMesh(doc.mesh, 2, half, err));+ CHECK(half.triangleCount() * 4 == baked.triangleCount());+ CHECK(!microBakeMesh(doc.mesh, 3, baked, err, 1000)); // the size limit+}++TEST(micro_displacement_maps) {+ Mesh plane = makePlane(16, 2.0f);+ plane.uvs.resize(plane.triangleCount() * 3);+ for (size_t t = 0; t < plane.triangleCount(); ++t)+ for (int k = 0; k < 3; ++k) {+ const glm::vec3 p = plane.positions[plane.triangles[t][k]];+ plane.uvs[t * 3 + size_t(k)] = glm::vec2(p.x * 0.5f + 0.5f, p.z * 0.5f + 0.5f);+ }+ Document doc = makeDoc(std::move(plane));+ std::string err;+ CHECK(microDivide(doc.mesh, 3, err));+ microNoise(doc.mesh, 0.02f, 6.0f);+ float scale = 0.0f;+ const std::string exr = tempPath("sf_micro_disp.exr"), png = tempPath("sf_micro_disp.png");+ CHECK(microExportDisplacement(doc.mesh, exr, 128, false, "exr", scale, err));+ CHECK(scale > 0.001f && scale < 0.1f);+ CHECK(std::filesystem::file_size(exr) > 128 * 128 * 4);+ CHECK(microExportDisplacement(doc.mesh, png, 64, true, "png", scale, err));+ CHECK(std::filesystem::exists(png));+ std::filesystem::remove(exr);+ std::filesystem::remove(png);+ Document sphere = microDoc(2, 3000);+ CHECK(!microExportDisplacement(sphere.mesh, exr, 64, false, "exr", scale, err)); // no UVs+ CHECK(err.find("UV") != std::string::npos);+}++TEST(micro_project_round_trip) {+ Document doc = microDoc(3, 5000);+ microNoise(doc.mesh, 0.01f, 10.0f);+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, "Mask");+ doc.sculptor.dabMask(doc.mesh, doc.bvh, dabAt(glm::vec3(0, 0, 1), 0.3f, 1.0f), sym);+ doc.undo.push(doc.sculptor.endStroke());+ const std::string path = tempPath("sf_micro_round_trip.sfproj");+ std::string err;+ CHECK(saveProject(path, doc, err));+ auto version = [&] {+ std::vector<ZipEntry> entries;+ Json manifest;+ std::string e;+ if (!readStoredZip(path, entries, e) || entries.empty() ||+ !Json::parse(std::string(entries[0].data.begin(), entries[0].data.end()), manifest, e))+ return -1;+ return int(manifest["version"].asNumber());+ };+ CHECK(version() == 7);+ Document loaded;+ CHECK(loadProject(path, loaded, err));+ CHECK(loaded.mesh.micro != nullptr);+ if (loaded.mesh.micro) {+ CHECK(loaded.mesh.micro->level == 3);+ CHECK(loaded.mesh.micro->step == doc.mesh.micro->step);+ CHECK(loaded.mesh.micro->disp == doc.mesh.micro->disp);+ CHECK(loaded.mesh.micro->mask == doc.mesh.micro->mask);+ CHECK(loaded.mesh.micro->rangeMax == doc.mesh.micro->rangeMax);+ }+ std::filesystem::remove(path);+ // Without a micro level a project stays format 6 (0.9.7 and older open it).+ Document plain = makeDoc(makeIcosphere(2));+ CHECK(saveProject(path, plain, err));+ CHECK(version() == 6);+ Document again;+ CHECK(loadProject(path, again, err));+ CHECK(again.projectSettings.isObject());+ std::filesystem::remove(path);+}++TEST(micro_commands) {+ CommandRegistry reg;+ Document doc = makeDoc(makeBenchSphere(20000));+ CHECK(reg.execute(doc, "micro_info").ok);+ CommandResult r = reg.execute(doc, "micro_divide", {{"triangles", 1.0}});+ CHECK(r.ok);+ CHECK(doc.mesh.micro != nullptr);+ CHECK(microLevel(doc.mesh) == microLevelFor(doc.mesh, 1000000));+ CHECK(reg.execute(doc, "micro_noise", {{"amplitude", 0.002}}).ok);+ CHECK(reg.execute(doc, "micro_info").message.find("Micro level") != std::string::npos);+ CHECK(reg.execute(doc, "micro_bake", {{"level", 1.0}}).ok);+ CHECK(doc.subtoolCount() == 2);+ CHECK(reg.execute(doc, "micro_delete").ok);+ CHECK(doc.mesh.micro == nullptr);+ CHECK(reg.execute(doc, "undo").ok);+ CHECK(doc.mesh.micro != nullptr);+ CHECK(reg.execute(doc, "undo").ok); // the noise+ CHECK(reg.execute(doc, "undo").ok); // the divide+ CHECK(doc.mesh.micro == nullptr);+}++// The point of micro levels: memory and dab time on a dense surface. 5M micro triangles here (fast enough for+// every ctest run); --bench-micro measures 33M - 300M. Timing limits only with SF_BENCH_LIMITS=1.+TEST(micro_memory_and_dab_time) {+ Document doc = makeDoc(makeBenchSphere(80000));+ std::string err;+ const size_t rss0 = residentBytes();+ CHECK(microDivide(doc.mesh, 3, err));+ const MicroMesh& mm = *doc.mesh.micro;+ CHECK(mm.microTriangles() > 4'000'000);+ const double bytesPerMicroTriangle = double(mm.bytes()) / double(mm.microTriangles());+ CHECK(bytesPerMicroTriangle < 2.0);+ (void)rss0;+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, "Standard");+ const auto t0 = std::chrono::steady_clock::now();+ for (int i = 0; i < 20; ++i)+ doc.sculptor.dab(doc.mesh, doc.bvh, BrushType::Standard, dabAt(glm::normalize(glm::vec3(0.02f * float(i), 0.1f, 1)), 0.12f), sym);+ const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count() / 20.0;+ doc.undo.push(doc.sculptor.endStroke());+ std::printf(" micro dab at %.1fM micro triangles: %.2f ms, %.2f bytes/micro triangle\n", double(mm.microTriangles()) / 1e6,+ ms, bytesPerMicroTriangle);+ if (std::getenv("SF_BENCH_LIMITS")) CHECK(ms < 10.0);+}++TEST(micro_tile_codec_round_trip) {+ const uint32_t S = 45;+ std::vector<int16_t> v(S * 5, 0);+ for (uint32_t k = 0; k < S; ++k) v[S + k] = int16_t(int(k) * 7 - 100); // a spread tile+ for (uint32_t k = 0; k < S; ++k) v[3 * S + k] = int16_t(12345); // constant, not zero+ v[4 * S] = -32767, v[4 * S + 1] = 32767; // the full range+ std::vector<uint8_t> packed;+ microPackTiles(v.data(), 5, S, packed);+ CHECK(packed.size() < v.size() * 2);+ std::vector<int16_t> back(v.size(), 0);+ CHECK(microUnpackTiles(packed.data(), packed.size(), 5, S, back.data()));+ CHECK(back == v);+ CHECK(!microUnpackTiles(packed.data(), packed.size() - 1, 5, S, back.data())); // damaged+}++TEST(micro_out_of_core_store) {+ MicroStore s;+ std::string err;+ const size_t n = size_t(64) << 20; // 128 MB of address space, untouched+ const bool mapped = s.assignMapped(n, err);+ CHECK(s.size() == n);+ if (mapped) {+ CHECK(s.mapped());+ CHECK(s.residentBytes() < (size_t(8) << 20)); // holes take no memory+ s[12345] = 77;+ s[n - 1] = -5;+ MicroStore copy = s;+ CHECK(copy.mapped() && copy[12345] == 77 && copy[n - 1] == -5 && copy[0] == 0);+ }+ // A micro level kept out of core sculpts, undoes and saves like one in memory.+ Document doc = makeDoc(makeBenchSphere(20000));+ CHECK(microDivide(doc.mesh, 3, err, 1));+ CHECK(doc.mesh.micro->disp.mapped() == mapped);+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, "Standard");+ doc.sculptor.dab(doc.mesh, doc.bvh, BrushType::Standard, dabAt(glm::vec3(0, 0, 1), 0.3f), sym);+ doc.undo.push(doc.sculptor.endStroke());+ CHECK(watertight(doc.mesh));+ const std::vector<int16_t> sculpted = doc.mesh.micro->disp;+ const std::string path = tempPath("sf_micro_ooc.sfproj");+ CHECK(saveProject(path, doc, err));+ Document loaded;+ CHECK(loadProject(path, loaded, err));+ CHECK(loaded.mesh.micro && loaded.mesh.micro->disp == sculpted);+ std::filesystem::remove(path);+}++TEST(micro_adaptive_brush_matches_full) {+ // A big brush evaluated on a coarse stride lands close to the same brush on every point.+ Document a = microDoc(4), b = microDoc(4);+ Symmetry sym;+ a.sculptor.microStroke().adaptive = false;+ for (Document* d : {&a, &b}) {+ d->sculptor.beginStroke(d->mesh, "Standard");+ d->sculptor.dab(d->mesh, d->bvh, BrushType::Standard, dabAt(glm::vec3(0, 0, 1), 0.6f, 1.0f), sym);+ d->undo.push(d->sculptor.endStroke());+ }+ CHECK(b.sculptor.microStroke().lastStride > 1);+ CHECK(a.sculptor.microStroke().lastStride == 1);+ const float ha = frontHeight(a), hb = frontHeight(b);+ CHECK(ha > 1.01f);+ CHECK(std::abs(ha - hb) < (ha - 1.0f) * 0.02f);+ CHECK(watertight(b.mesh));+}++TEST(micro_undo_journal_is_small) {+ // A stroke's undo step is its change, packed per tile in Morton order: far below 2 bytes per touched point.+ Document doc = microDoc(4);+ microNoise(doc.mesh, 0.003f, 30.0f); // detail under the brush (old values far from zero)+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, "Standard");+ for (int i = 0; i < 10; ++i)+ doc.sculptor.dab(doc.mesh, doc.bvh, BrushType::Standard, dabAt(glm::normalize(glm::vec3(0.03f * float(i), 0.1f, 1)), 0.15f), sym);+ UndoRecord r = doc.sculptor.endStroke();+ CHECK(r.micro && r.micro->journal);+ const size_t raw = r.micro->tris.size() * doc.mesh.micro->samples * 2;+ std::printf(" micro undo journal: %zu tiles, %.1f KB (whole tiles %.1f KB)\n", r.micro->tris.size(),+ double(r.micro->bytes()) / 1e3, double(raw) / 1e3);+ CHECK(r.micro->bytes() * 2 < raw);+ CHECK(std::is_sorted(r.micro->keys.begin(), r.micro->keys.end()));+ const std::vector<int16_t> after = doc.mesh.micro->disp;+ doc.undo.push(std::move(r));+ doc.undo.undo(doc.mesh, doc.bvh);+ doc.undo.redo(doc.mesh, doc.bvh);+ CHECK(doc.mesh.micro->disp == after);+}++TEST(micro_tier_config_and_page_table) {- const TierConfig saved = tierConfig();- setTierConfig(TierConfig::laptop());- CHECK(tierConfig().activeTriangleBudget < TierConfig::workstation().activeTriangleBudget);- CHECK(!tierConfig().continuousNormals);- // Laptop: big levels go out of core sooner.- CHECK(microWantsOutOfCore(size_t(300) << 20) || std::getenv("SF_MICRO_OUT_OF_CORE"));- setTierConfig(saved);++ // The tier (feat/hw-profile) decides when a level goes out of core: past its resident cache.++ const TierConfig saved = currentTierConfig();++ TierConfig small = saved;++ small.outOfCorePoints = size_t(1) << 20;++ setCurrentTierConfig(small);++ if (!std::getenv("SF_MICRO_OUT_OF_CORE")) {++ CHECK(microWantsOutOfCore(size_t(2) << 20));++ CHECK(!microWantsOutOfCore(size_t(1) << 19));++ }++ setCurrentTierConfig(saved);+ Document doc = microDoc(2, 3000);+ PatchPageTable pages(*doc.mesh.micro);+ CHECK(pages.residentPatches() == doc.mesh.micro->baseTriangles); // in memory: every patch+ MicroPatch p = microPatch(doc.mesh, 5);+ CHECK(p.points() == doc.mesh.micro->samples && p.heights == doc.mesh.micro->disp.data() + 5 * p.points());+ std::string err;+ Document ooc = makeDoc(makeBenchSphere(20000));+ CHECK(microDivide(ooc.mesh, 3, err, 1));+ if (ooc.mesh.micro->disp.mapped()) {+ PatchPageTable cold(*ooc.mesh.micro);+ CHECK(cold.residentPatches() < ooc.mesh.micro->baseTriangles); // untouched: holes, not resident+ microPatch(ooc.mesh, 7).heights[0] = 3;+ CHECK(cold.resident(7));+ cold.trim(1);+ CHECK(ooc.mesh.micro->disp[7 * ooc.mesh.micro->samples] == 3); // trimmed pages come back from the file+ }+}