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
Coarse levels: full detail at rest; edits move the cells' points; benchmark still phase
islandmed3065b1825adc
diff --git a/changes/perf-coarse-lod.md b/changes/perf-coarse-lod.mdindex 68137b73..bf0c956e 100644--- a/changes/perf-coarse-lod.md+++ b/changes/perf-coarse-lod.md@@ -1,13 +1,15 @@----whats_new: **Smoother view on very dense meshes**: a scan or import with more triangles than your computer draws comfortably now draws far parts in lighter versions of themselves, sharp where you look and full detail as soon as it all fits. Orbiting a 28-million-triangle scan on an entry-level laptop goes from about 70 to about 170 frames a second.+whats_new: **Smoother view on very dense meshes**: a scan or import with more triangles than your computer draws comfortably now draws a lighter version of itself while you turn the view, and the real detail as soon as the view rests. Parts you sculpt always show in full detail. Orbiting a 28-million-triangle scan on an entry-level laptop goes from about 70 to about 180 frames a second.highlight: Dense scans orbit smoothly on entry-level machines-added: Coarse levels for dense meshes: a plain mesh over the hardware tier's triangle budget draws each part of it at a- lighter level picked from its size on screen (under a pixel of error at rest), so a frame stays within the budget;- full detail when it all fits. Sculpting keeps the edited area in full detail and updates its levels after the stroke.+added: Coarse levels for dense meshes: a plain mesh over the hardware tier's triangle budget draws all of it at one+ lighter level while the view moves (the finest that fits the budget), and in full detail once the view has rested+ for 150 ms, when one full frame fits the still-frame budget (100 ms); otherwise it stays light and the info line says+ **Preview detail**. A stroke draws the mesh in full detail; its edits reach the lighter level right after it.`SF_COARSE_LOD=0` turns it off.testers:- - Open a scan of 20M+ triangles (e.g. a Stanford-style statue): orbit; it should stay smooth, and when you stop the view should look the same as before (no holes, no seams).- - Sculpt on it: the stroke area stays sharp; after the stroke, orbit again and the stroke is still there from afar.- - Windows 8 GB laptop: open the same scan; the app should not use noticeably more memory than 0.11.4.+ - Open a scan of 20M+ triangles (e.g. a Stanford-style statue): orbit; it should stay smooth. Stop: within a moment the view shows the full detail (no holes, no seams, no jump you notice).+ - Sculpt on it: the stroke draws in full detail; orbit right after it and the stroke is there from every side.+ - On a low-end machine (integrated graphics), a very dense scan may stay light at rest: the info line then says Preview detail.+ - Windows 8 GB laptop: open the same scan; the app should not use noticeably more memory than 0.11.6.---Design: docs/design/micro-coarse-lod.md (clean-room rules; pre-2000 sources). Micro levels are not covered yet.diff --git a/src/app/App.cpp b/src/app/App.cppindex dc5ceed0..d5e9a485 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -532,6 +532,7 @@ int App::runUiTest(int w, int h, int fps) {syncScene();notePerformanceFrame(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - syncStart).count());viewSamples(); // keeps Fast Navigation's view of the camera current (UI tests read view_samples)+ noteStillness();hardwareProfileFrameEnd();if (tracing) {tracePhase[4] = tracePhase[5] = tracePhase[6] = double(SDL_GetTicksNS()) * 1e-6;@@ -823,7 +824,8 @@ bool App::wantsFrames(double now) const {timelapseBusy() || hardwareCalibrating() || // both render a step per frame: they stop when the frames dospaceMouseMoving() || // a held SpaceMouse cap sends no events, but the view keeps moving (SpaceMouse.cpp)perf_.framesStill < 10 || // the view just moved: Fast Navigation's full-quality frame comes after it stops- (perf_.proxyPrebuild && renderer_.proxiesPending()); // motion proxies left to build, a few ms a frame+ (perf_.proxyPrebuild && renderer_.proxiesPending()) || // motion proxies left to build, a few ms a frame+ renderer_.coarseStillWanted(); // coarse levels: the full-detail still frame comes once the view rests}uint64_t App::frameKey() const {@@ -1182,6 +1184,7 @@ int App::run() {notePerformanceFrame(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - syncStart).count());const int samples = viewSamples();renderSettings_.motionProxy = perf_.proxyNow; // big meshes draw their lighter proxy while the view moves+ noteStillness();renderSettings_.materialTint = materialTintFor(doc_.paintColor); // (Color > Colour tints the material)renderSettings_.resolutionScale = float(uiPrefs_.viewResolution) / 100.0f; // (#80; only the window's view)if (perf_.movingNow) // while the view moves, the floor tier draws fewer pixels; full resolution when it stopsdiff --git a/src/app/App.h b/src/app/App.hindex 9b6c8550..0dcea562 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -1095,9 +1095,11 @@ private:int viewSamples();void applyPerformancePrefs();void notePerformanceFrame(double syncMs); // after syncScene: upload time, GPU memory warnings+ void noteStillness(); // after viewSamples: RenderSettings::stillSeconds, strokingstruct PerfState {glm::mat4 lastView{0.0f};int framesStill = 0; // frames since the view last moved+ double stillSince = 0.0; // when it last moved (ImGui::GetTime)bool fastNow = false; // this frame draws without antialiasing (fast navigation)bool proxyPrebuild = false; // still frames build stale motion proxies (Renderer::setProxyPrebuild)bool proxyNow = false; // this frame draws big meshes' motion proxy (fast navigation)diff --git a/src/app/I18nSimplifiedChinese.cpp b/src/app/I18nSimplifiedChinese.cppindex 903c1415..fdc0fcc1 100644--- a/src/app/I18nSimplifiedChinese.cpp+++ b/src/app/I18nSimplifiedChinese.cpp@@ -636,6 +636,7 @@ constexpr Entry kSimplifiedChinese[] = {{"Apply", "应用"},{"Reset", "重置"},{"Preview", "预览"},+ {"Preview detail", "预览细节"},{"Finish", "完成"},{"Close", "关闭"},{"OK", "确定"},diff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cppindex 364e1a12..cbca1f9f 100644--- a/src/app/I18nSpanish.cpp+++ b/src/app/I18nSpanish.cpp@@ -770,6 +770,7 @@ constexpr Entry kSpanish[] = {{"Apply", "Aplicar"},{"Reset", "Restablecer"},{"Preview", "Vista previa"},+ {"Preview detail", "Detalle de vista previa"},{"Finish", "Terminar"},{"Close", "Cerrar"},{"OK", "Aceptar"},diff --git a/src/app/I18nTraditionalChinese.cpp b/src/app/I18nTraditionalChinese.cppindex a2118460..cf787c0e 100644--- a/src/app/I18nTraditionalChinese.cpp+++ b/src/app/I18nTraditionalChinese.cpp@@ -636,6 +636,7 @@ constexpr Entry kTraditionalChinese[] = {{"Apply", "套用"},{"Reset", "重設"},{"Preview", "預覽"},+ {"Preview detail", "預覽細節"},{"Finish", "完成"},{"Close", "關閉"},{"OK", "確定"},diff --git a/src/app/PanelPerformance.cpp b/src/app/PanelPerformance.cppindex 52c88930..28216300 100644--- a/src/app/PanelPerformance.cpp+++ b/src/app/PanelPerformance.cpp@@ -187,6 +187,7 @@ int App::viewSamples() {if (view != perf_.lastView) {perf_.lastView = view;perf_.framesStill = 0;+ perf_.stillSince = ImGui::GetTime(); // (the frame clock: scripted time in tests)} else if (perf_.framesStill < 1000) {++perf_.framesStill;}@@ -202,6 +203,14 @@ int App::viewSamples() {return perf_.samplesWanted;}+// How long the view has been still and whether a stroke runs: coarse levels give way to full detail at rest+// (Renderer::coarsePreviewOnly).+void App::noteStillness() {+ renderSettings_.stillSeconds = perf_.movingNow ? 0.0 : ImGui::GetTime() - perf_.stillSince;+ renderSettings_.stroking = doc_.sculptor.strokeActive() || strokeFinishing_ || !dabQueue_.empty();+ renderer_.setStroking(renderSettings_.stroking);+}+void App::notePerformanceFrame(double syncMs) {perf_.lastSyncMs = syncMs;if (doc_.sculptor.strokeActive()) {diff --git a/src/app/PanelPerformanceProfile.cpp b/src/app/PanelPerformanceProfile.cppindex 957169a2..73add9f8 100644--- a/src/app/PanelPerformanceProfile.cpp+++ b/src/app/PanelPerformanceProfile.cpp@@ -193,6 +193,8 @@ void App::applyHardwareProfile(const HardwareProfile& p, bool announce) {}hw.profile.settings.targetFps = s.targetFps;setCurrentPerformanceSettings(s);+ // (the still frame's cost before any is measured: the calibrated rate; the simulated floor tier keeps its budget's)+ renderer_.setTriangleRate(floor ? 0.0 : hw.profile.calibration.trianglesPerSecondM);GovernorConfig cfg;cfg.targetFps = s.targetFps;cfg.minBudget = std::max<uint64_t>(250'000, s.renderTriangleBudget / 8);@@ -266,6 +268,7 @@ void App::hardwareProfileFrameEnd() {hw.pending.pop_front();s.gpuMs = gpuMs;hw.lastGpuMs = gpuMs;+ renderer_.noteGpuFrame(gpuMs, s.drawnTriangles);if (proof_ && proofGpuMs_.size() < 4096) proofGpuMs_.push_back(gpuMs);changed = hw.governor.addFrame(s) || changed;}diff --git a/src/app/ProofMode.cpp b/src/app/ProofMode.cppindex 27166e51..b58a6301 100644--- a/src/app/ProofMode.cpp+++ b/src/app/ProofMode.cpp@@ -402,6 +402,7 @@ struct PhaseResult {std::vector<double> previewLagPx; // the predictive preview's head behind the pointer (the surface's without it)std::vector<double> drawn; // triangles each frame drew (Renderer::lastDrawnTriangles)std::vector<double> gpuMs; // GPU time of the phase's frames (GL_TIME_ELAPSED; empty without timer queries)+ std::vector<double> coarse; // clusters each frame drew at a coarse level (0: full detail)size_t screenStrokeFrames = 0; // frames the view showed pending dabs on the screen (render/ScreenStroke.h)std::vector<double> split[6]; // each frame by part (App::frameSplitMs_, the frame before: the swap comes after)SculptTimings stroke; // the stroke's own work (solver thread: kernel, normals, BVH), when it ended@@ -544,7 +545,8 @@ void App::startProofMode() {p->phases = {{"clay small", 25.0f, p->strokeSeconds, BrushType::Clay, 0.35f},{"clay large", 120.0f, p->strokeSeconds, BrushType::Clay, 0.35f},{"240 px brush", 240.0f, p->strokeSeconds, BrushType::Clay, 0.35f},- {"orbit", 0.0f, 10.0}};+ {"orbit", 0.0f, 10.0},+ {"still", -1.0f, 0.6}}; // (the view at rest: coarse levels give way to full detail, Renderer::coarsePreviewOnly)else if (!p->scene.empty()) p->phases = standardPhases(p->strokeSeconds);else p->phases = {{"stroke", 60.0f, p->strokeSeconds}, {"large brush stroke", 240.0f, p->strokeSeconds}, {"orbit", 0.0f, 3.0}};// SF_BENCH_PHASES=smooth,240: only the phases whose names contain one of these (each on the fresh mesh's@@ -939,12 +941,14 @@ void App::proofBeforeSwap(int fbW, int fbH) {ph.frameMs.push_back(frameMs);for (int k = 0; k < 6; ++k) ph.split[k].push_back(frameSplitMs_[k]);ph.drawn.push_back(double(renderer_.lastDrawnTriangles()));+ ph.coarse.push_back(double(renderer_.coarseDrawnClusters()));ph.screenStrokeFrames += renderer_.screenStrokeDrawn() ? 1 : 0;ph.gpuMs.insert(ph.gpuMs.end(), proofGpuMs_.begin(), proofGpuMs_.end());proofGpuMs_.clear();}const double u = std::min(1.0, (now - p.stageStart) / spec.seconds);- if (spec.radiusPx <= 0) { // orbit: the view turns, as a drag would+ if (spec.radiusPx < 0) { // still: the view at rest (nothing moves)+ } else if (spec.radiusPx <= 0) { // orbit: the view turns, as a drag wouldcamera_.yaw = float(6.2831853 * u);perf_.framesStill = 0;} else if (p.pressed) {@@ -1100,6 +1104,11 @@ void App::proofBeforeSwap(int fbW, int fbH) {for (int k = 0; k < 6; ++k) split.set(names[k], percentilesJson(percentiles(ph.split[k])));j.set("frame_split_ms", split);j.set("triangles_drawn", percentilesJson(percentiles(ph.drawn)));+ if (ph.radiusPx < 0 && !ph.drawn.empty()) { // still: what its last frame drew (after the 150 ms wait)+ j.set("detail", ph.coarse.empty() || ph.coarse.back() == 0 ? "full" : "coarse");+ j.set("still_triangles", ph.drawn.back());+ if (!ph.gpuMs.empty()) j.set("still_gpu_ms", std::round(ph.gpuMs.back() * 100) / 100);+ }if (!ph.gpuMs.empty()) { // (the GPU's own work, no compositor; fewer than "frames": results that came too late)j.set("gpu_ms", percentilesJson(percentiles(ph.gpuMs)));j.set("gpu_frames", double(ph.gpuMs.size()));diff --git a/src/app/Shell.cpp b/src/app/Shell.cppindex 2b7dae2c..cdab8534 100644--- a/src/app/Shell.cpp+++ b/src/app/Shell.cpp@@ -1054,6 +1054,10 @@ void App::drawTitleStrip(const ShellGeometry& g) {? doc_.mesh.layers[size_t(doc_.activeLayer)].name.c_str(): tr("Base"),doc_.splats.empty() ? "" : tr(" Splats "), doc_.splats.empty() ? "" : shortCount(doc_.splats.size()).c_str());+ if (renderer_.coarsePreviewOnly()) { // (a mesh over the triangle budget whose full detail won't fit a still frame)+ std::strncat(info, " ", sizeof info - std::strlen(info) - 1);+ std::strncat(info, tr("Preview detail"), sizeof info - std::strlen(info) - 1);+ }// The frame rate gets a fixed-width slot, refreshed twice a second: a number that changes width every frame// would make everything after it (the status message) jitter.if (ImGui::GetTime() - fpsShownAt_ > 0.5 || fpsShown_ < 0.0f) {diff --git a/src/render/Clusters.cpp b/src/render/Clusters.cppindex cf155897..13503707 100644--- a/src/render/Clusters.cpp+++ b/src/render/Clusters.cpp@@ -355,7 +355,6 @@ bool clusterOnCells(const CoarseLevels& L, const Mesh& mesh, const UploadOrder&return true;}-uint32_t roomFor(size_t indices) { return uint32_t(indices + indices / 4 + 48); } // (an edit may add a few)} // namespace@@ -363,18 +362,7 @@ uint32_t CoarseLevels::cellOf(const glm::vec3& p, int level) const {const Level& l = levels[size_t(level)];const uint64_t key = cellKey(*this, p, level);const auto it = std::lower_bound(l.keys.begin(), l.keys.end(), key);- if (it != l.keys.end() && *it == key) return l.base + uint32_t(it - l.keys.begin());- const auto found = l.added.find(key);- return found != l.added.end() ? found->second : ~0u;-}--uint32_t CoarseLevels::cellOrAdd(const glm::vec3& p, int level) {- if (const uint32_t k = cellOf(p, level); k != ~0u) return k;- const uint32_t k = uint32_t(positions.size());- levels[size_t(level)].added.emplace(cellKey(*this, p, level), k);- positions.push_back(p);- normals.push_back(glm::vec3(0.0f, 0.0f, 1.0f));- return k;+ return it != l.keys.end() && *it == key ? l.base + uint32_t(it - l.keys.begin()) : ~0u;}CoarseLevels buildCoarseLevels(const Mesh& mesh, const UploadOrder& order) {@@ -441,6 +429,47 @@ CoarseLevels buildCoarseLevels(const Mesh& mesh, const UploadOrder& order) {if (cells < 64) break;}cellOfVertex = {};+ // Membership (the build's, kept): each vertex's level-0 cell, each level-0 cell's vertices, the parents and+ // children up the levels, and the weights.+ const uint32_t cells0 = uint32_t(L.levels[0].keys.size()), base0 = L.levels[0].base, cellCount = uint32_t(L.positions.size());+ L.vertexCell.resize(nv);+ poolFor(nv, [&](size_t v0, size_t v1) {+ for (size_t v = v0; v < v1; ++v) L.vertexCell[v] = L.cellOf(mesh.positions[v], 0);+ });+ L.memberFirst.assign(size_t(cells0) + 1, 0);+ for (uint32_t k : L.vertexCell) ++L.memberFirst[k - base0 + 1];+ for (uint32_t k = 0; k < cells0; ++k) L.memberFirst[k + 1] += L.memberFirst[k];+ L.members.resize(nv);+ {+ std::vector<uint32_t> at(L.memberFirst.begin(), L.memberFirst.end() - 1);+ for (uint32_t v = 0; v < uint32_t(nv); ++v) L.members[at[L.vertexCell[v] - base0]++] = v;+ }+ L.parent.assign(cellCount, ~0u);+ L.weight.assign(cellCount, 0);+ for (uint32_t k = 0; k < cells0; ++k) L.weight[base0 + k] = L.memberFirst[k + 1] - L.memberFirst[k];+ for (size_t level = 0; level + 1 < L.levels.size(); ++level) {+ const CoarseLevels::Level& lv = L.levels[level];+ const CoarseLevels::Level& up = L.levels[level + 1];+ for (size_t i = 0; i < lv.keys.size(); ++i) {+ const uint64_t k = lv.keys[i];+ const uint64_t pk = packCell(glm::uvec3(uint32_t(k & 0x1FFFFF), uint32_t((k >> 21) & 0x1FFFFF), uint32_t(k >> 42)) / 2u);+ const auto it = std::lower_bound(up.keys.begin(), up.keys.end(), pk);+ if (it == up.keys.end() || *it != pk) continue;+ const uint32_t child = lv.base + uint32_t(i), par = up.base + uint32_t(it - up.keys.begin());+ L.parent[child] = par;+ L.weight[par] += L.weight[child];+ }+ }+ L.childFirst.assign(size_t(cellCount) + 1, 0);+ for (uint32_t k = 0; k < cellCount; ++k)+ if (L.parent[k] != ~0u) ++L.childFirst[L.parent[k] + 1];+ for (uint32_t k = 0; k < cellCount; ++k) L.childFirst[k + 1] += L.childFirst[k];+ L.children.resize(L.childFirst[cellCount]);+ {+ std::vector<uint32_t> at(L.childFirst.begin(), L.childFirst.end() - 1);+ for (uint32_t k = 0; k < cellCount; ++k)+ if (L.parent[k] != ~0u) L.children[at[L.parent[k]]++] = k;+ }// Per cluster, its levels while they pay.std::vector<std::vector<uint32_t>> lists(nc);poolFor(nc, [&](size_t c0, size_t c1) {@@ -453,11 +482,9 @@ CoarseLevels buildCoarseLevels(const Mesh& mesh, const UploadOrder& order) {if (!clusterOnCells(L, mesh, order, uint32_t(c), level, tris, error)) break; // (every level: one is drawn for all)lod.first[lod.levels] = uint32_t(lists[c].size());lod.count[lod.levels] = uint32_t(tris.size() * 3);- lod.capacity[lod.levels] = roomFor(tris.size() * 3);lod.error[lod.levels] = std::max(error, lod.levels > 0 ? lod.error[lod.levels - 1] : 0.0f);++lod.levels;for (const auto& m : tris) lists[c].insert(lists[c].end(), m.begin(), m.end());- lists[c].resize(lod.first[lod.levels - 1] + lod.capacity[lod.levels - 1], 0);previous = tris.size();}lists[c].shrink_to_fit();@@ -476,104 +503,68 @@ CoarseLevels buildCoarseLevels(const Mesh& mesh, const UploadOrder& order) {}std::vector<uint32_t> updateCoarseLevels(CoarseLevels& L, const Mesh& mesh, const UploadOrder& order,- const std::vector<ClusterBounds>& bounds, const std::vector<uint32_t>& dirty,- std::vector<uint32_t>& points) {- points.clear();+ const std::vector<uint32_t>& dirty) {std::vector<uint32_t> changed;- if (L.levels.empty() || dirty.empty()) return changed;- const auto fromGpu = order.fromGpu();const size_t nv = mesh.vertexCount();- // The region the edit touched: the dirty clusters' vertices now, and the points of the cells their levels used.- AABB reach;- for (uint32_t c : dirty) {- const auto& cl = order.clusters()[c];- for (uint32_t l = 0; l < cl.vertexCount; ++l)- if (const uint32_t v = fromGpu[cl.firstVertex + l]; v < nv) reach.expand(mesh.positions[v]);- const CoarseLevels::Lod& lod = L.clusters[c];- for (int level = 0; level < lod.levels; ++level)- for (uint32_t i = lod.first[level]; i < lod.first[level] + lod.count[level]; ++i) reach.expand(L.positions[L.indices[i]]);- }- if (!reach.valid()) return changed;- // Cells for the vertices an edit moved where the build had none (pushed out of the surface, most often).- for (uint32_t c : dirty) {- const auto& cl = order.clusters()[c];- for (uint32_t l = 0; l < cl.vertexCount; ++l)- if (const uint32_t v = fromGpu[cl.firstVertex + l]; v < nv)- for (int level = 0; level < int(L.levels.size()); ++level) L.cellOrAdd(mesh.positions[v], level);- }- // The cells to recompute: at every level, each one whose box meets the region grown by a cell.+ if (L.levels.empty() || dirty.empty() || L.vertexCell.size() != nv) return changed;+ const auto fromGpu = order.fromGpu();+ const uint32_t base0 = L.levels[0].base;+ // The level-0 cells of the dirty clusters' vertices (the build's cells: membership doesn't change).+ const size_t cells0 = L.levels[0].keys.size();+ std::vector<uint8_t> flagged(cells0, 0);+ poolFor(dirty.size(), [&](size_t d0, size_t d1) {+ for (size_t d = d0; d < d1; ++d) {+ const auto& cl = order.clusters()[dirty[d]];+ for (uint32_t l = 0; l < cl.vertexCount; ++l)+ if (const uint32_t v = fromGpu[cl.firstVertex + l]; v < nv)+ std::atomic_ref<uint8_t>(flagged[L.vertexCell[v] - base0]).store(1, std::memory_order_relaxed);+ }+ }, 16);std::vector<uint32_t> cells;- AABB around = reach; // (the vertices that can be in those cells)- for (int level = 0; level < int(L.levels.size()); ++level) {- const CoarseLevels::Level& lv = L.levels[size_t(level)];- const float size = L.cell * float(1u << level);- const glm::vec3 lo = glm::clamp(glm::floor((reach.min - glm::vec3(size) - L.origin) / size), glm::vec3(0.0f), glm::vec3(float(0x1FFFFF)));- const glm::vec3 hi = glm::clamp(glm::floor((reach.max + glm::vec3(size) - L.origin) / size), glm::vec3(0.0f), glm::vec3(float(0x1FFFFF)));- around.expand(L.origin + lo * size);- around.expand(L.origin + (hi + 1.0f) * size);- for (uint32_t z = uint32_t(lo.z); z <= uint32_t(hi.z); ++z)- for (uint32_t y = uint32_t(lo.y); y <= uint32_t(hi.y); ++y) {- auto it = std::lower_bound(lv.keys.begin(), lv.keys.end(), packCell(glm::uvec3(uint32_t(lo.x), y, z)));- const uint64_t end = packCell(glm::uvec3(uint32_t(hi.x), y, z));- for (; it != lv.keys.end() && *it <= end; ++it) cells.push_back(lv.base + uint32_t(it - lv.keys.begin()));- }- for (const auto& [key, k] : lv.added) cells.push_back(k); // (few)- }- std::sort(cells.begin(), cells.end());- if (cells.empty()) return changed;- reach = around;- // Every vertex in those cells: from the clusters whose bounds reach them (each mesh vertex once, as the build;- // a seam vertex has a copy in each of its clusters).- std::vector<uint32_t> verts;- for (uint32_t c = 0; c < uint32_t(order.clusters().size()) && c < bounds.size(); ++c) {- const ClusterBounds& b = bounds[c];- if (b.radius < 0.0f) continue;- const glm::vec3 nearest = glm::clamp(b.center, reach.min, reach.max);- if (glm::distance(nearest, b.center) > b.radius) continue;- const auto& cl = order.clusters()[c];- for (uint32_t l = 0; l < cl.vertexCount; ++l)- if (const uint32_t v = fromGpu[cl.firstVertex + l]; v < nv) verts.push_back(v);- }- std::sort(verts.begin(), verts.end());- verts.erase(std::unique(verts.begin(), verts.end()), verts.end());- std::vector<glm::dvec3> sum(cells.size(), glm::dvec3(0.0));- std::vector<glm::vec3> nsum(cells.size(), glm::vec3(0.0f));- std::vector<uint32_t> weight(cells.size(), 0);+ for (size_t k = 0; k < cells0; ++k)+ if (flagged[k]) cells.push_back(base0 + uint32_t(k));const bool hasNormals = mesh.normals.size() == nv;- for (uint32_t v : verts)- for (int level = 0; level < int(L.levels.size()); ++level) {- const uint32_t k = L.cellOf(mesh.positions[v], level);- const auto it = std::lower_bound(cells.begin(), cells.end(), k);- if (k == ~0u || it == cells.end() || *it != k) continue;- const size_t i = size_t(it - cells.begin());- sum[i] += glm::dvec3(mesh.positions[v]);- if (hasNormals) nsum[i] += mesh.normals[v];- ++weight[i];- }- for (size_t i = 0; i < cells.size(); ++i) {- if (weight[i] == 0) continue; // (an emptied cell: no triangle maps to it any more)- L.positions[cells[i]] = glm::vec3(sum[i] / double(weight[i]));- const float l = glm::length(nsum[i]);- L.normals[cells[i]] = l > 1e-12f ? nsum[i] / l : glm::vec3(0.0f, 0.0f, 1.0f);- points.push_back(cells[i]);- }- // The dirty clusters' levels on the cells, in their room.- std::vector<std::array<uint32_t, 3>> tris;- for (uint32_t c : dirty) {- CoarseLevels::Lod& lod = L.clusters[c];- bool ok = lod.levels > 0;- for (int level = 0; level < lod.levels && ok; ++level) {- float error = 0.0f;- ok = clusterOnCells(L, mesh, order, c, level, tris, error) && tris.size() * 3 <= lod.capacity[level];- if (!ok) break;- std::fill(L.indices.begin() + lod.first[level], L.indices.begin() + lod.first[level] + lod.capacity[level], 0u);- for (size_t i = 0; i < tris.size(); ++i)- std::copy(tris[i].begin(), tris[i].end(), L.indices.begin() + lod.first[level] + i * 3);- lod.count[level] = uint32_t(tris.size() * 3);- lod.error[level] = std::max(error, level > 0 ? lod.error[level - 1] : 0.0f);+ // Each one the mean of its vertices where they are now; then each level's cells above them from their children.+ poolFor(cells.size(), [&](size_t i0, size_t i1) {+ for (size_t i = i0; i < i1; ++i) {+ const uint32_t k = cells[i] - base0;+ glm::dvec3 sum(0.0);+ glm::vec3 nsum(0.0f);+ for (uint32_t m = L.memberFirst[k]; m < L.memberFirst[k + 1]; ++m) {+ sum += glm::dvec3(mesh.positions[L.members[m]]);+ if (hasNormals) nsum += mesh.normals[L.members[m]];+ }+ const uint32_t w = L.memberFirst[k + 1] - L.memberFirst[k];+ if (w) L.positions[cells[i]] = glm::vec3(sum / double(w));+ const float l = glm::length(nsum);+ if (l > 1e-12f) L.normals[cells[i]] = nsum / l;}- if (!ok) lod.levels = 0; // (drawn in full until the next build)- changed.push_back(c);+ }, 1024);+ changed = cells;+ for (size_t level = 1; level < L.levels.size() && !cells.empty(); ++level) {+ std::vector<uint32_t> up;+ up.reserve(cells.size());+ for (uint32_t k : cells)+ if (L.parent[k] != ~0u) up.push_back(L.parent[k]);+ std::sort(up.begin(), up.end());+ up.erase(std::unique(up.begin(), up.end()), up.end());+ poolFor(up.size(), [&](size_t i0, size_t i1) {+ for (size_t i = i0; i < i1; ++i) {+ const uint32_t p = up[i];+ glm::dvec3 sum(0.0);+ glm::vec3 nsum(0.0f);+ for (uint32_t j = L.childFirst[p]; j < L.childFirst[p + 1]; ++j) {+ const uint32_t ch = L.children[j];+ sum += glm::dvec3(L.positions[ch]) * double(L.weight[ch]);+ nsum += L.normals[ch] * float(L.weight[ch]);+ }+ if (L.weight[p]) L.positions[p] = glm::vec3(sum / double(L.weight[p]));+ const float l = glm::length(nsum);+ if (l > 1e-12f) L.normals[p] = nsum / l;+ }+ }, 1024);+ changed.insert(changed.end(), up.begin(), up.end());+ cells = std::move(up);}return changed;}diff --git a/src/render/Clusters.h b/src/render/Clusters.hindex 7c787c8a..3ecc7ffe 100644--- a/src/render/Clusters.h+++ b/src/render/Clusters.h@@ -17,7 +17,6 @@#include <algorithm>#include <cstdint>-#include <unordered_map>#include <vector>namespace sf {@@ -85,32 +84,34 @@ struct CoarseLevels {static constexpr int kMaxLevels = 5;struct Lod {int levels = 0; // 0: none (drawn in full)- uint32_t first[kMaxLevels] = {}, count[kMaxLevels] = {}, capacity[kMaxLevels] = {}; // in `indices`+ uint32_t first[kMaxLevels] = {}, count[kMaxLevels] = {}; // in `indices`float error[kMaxLevels] = {}; // world units};struct Level {std::vector<uint64_t> keys; // the cells' grid coordinates (packed), sorted; cell i is point base + iuint32_t base = 0;- std::unordered_map<uint64_t, uint32_t> added; // cells edits moved vertices into since the build: key -> point};glm::vec3 origin{0.0f};float cell = 0.0f; // level 0'sstd::vector<Level> levels;std::vector<glm::vec3> positions, normals; // every level's cell points, one level after the other- std::vector<uint32_t> indices; // into positions; each level of each cluster with room to grow+ std::vector<uint32_t> indices; // into positions (the renderer frees them once on the GPU)std::vector<Lod> clusters;- // The cell of point p at a level (cell id into positions), or ~0u: no such cell (p left every cell made).+ // Membership is the build's: an edit moves the cells' points (the means of their vertices where they are now),+ // never which cell a vertex is in, so the triangles stay as built and the surface stays closed.+ std::vector<uint32_t> vertexCell; // per mesh vertex: its level-0 cell (into positions)+ std::vector<uint32_t> memberFirst, members; // level-0 cell k's vertices: members[memberFirst[k - base0] ...)+ std::vector<uint32_t> parent; // per cell: its cell one level up (~0u at the top)+ std::vector<uint32_t> childFirst, children; // per cell: its cells one level down (level 0: none)+ std::vector<uint32_t> weight; // per cell: its vertices+ // The cell of point p at a level by its grid position (cell id into positions), or ~0u: none there at the build.uint32_t cellOf(const glm::vec3& p, int level) const;- uint32_t cellOrAdd(const glm::vec3& p, int level); // (a new cell for p if there is none)};CoarseLevels buildCoarseLevels(const Mesh& mesh, const UploadOrder& order);-// After an edit: the levels of the `dirty` clusters again, and the points of every cell their vertices are in (or-// were in), from all the vertices in those cells (the clusters whose bounds reach them). A cluster that no longer-// fits its room, or whose vertices moved into a cell the build didn't make, loses its levels (drawn in full until-// the next build). `points` gets the cells whose points changed; returns the clusters whose levels changed.+// After an edit: the points (and normals) of the level-0 cells holding the `dirty` clusters' vertices, from those+// vertices where they are now, and of their cells up the levels. Returns the cells changed.std::vector<uint32_t> updateCoarseLevels(CoarseLevels& levels, const Mesh& mesh, const UploadOrder& order,- const std::vector<ClusterBounds>& bounds, const std::vector<uint32_t>& dirty,- std::vector<uint32_t>& points);+ const std::vector<uint32_t>& dirty);// Every directed edge a->b has as many b->a: the mesh is the closed, consistently wound boundary of a volume// (it may intersect itself). Wound outwards (a positive signed volume: the sum of ClusterBounds::volume), everydiff --git a/src/render/Renderer.cpp b/src/render/Renderer.cppindex ff3f9d39..be632408 100644--- a/src/render/Renderer.cpp+++ b/src/render/Renderer.cpp@@ -2321,7 +2321,7 @@ void Renderer::sync(MeshSlot& s, Mesh& mesh, const NormalMapView* normalMap, boobuildProxies(s, mesh);if (coarseLod_ && !s.coarseTried && !s.outOfMemory && s.drawnTriangles > (lodBudget_ ? lodBudget_ : triangleBudget(RenderSettings())))buildCoarse(s, mesh);- if (s.coarse && !s.coarsePending.empty() && !s.coarseEdited) updateCoarse(s, mesh); // (the stroke is over)+ if (s.coarse && !s.coarsePending.empty() && !s.coarseEdited && !stroking_) updateCoarse(s, mesh); // (the stroke is over)s.coarseEdited = false;if (syncLog) proxyMs = lapMs(lap);syncTexture(s, mesh, pbr);@@ -2971,6 +2971,7 @@ void Renderer::draw(const Camera& camera, int targetWidth, int targetHeight, conframeCull_ = CullView::from(view, proj);lastDrawn_ = 0;lastCoarseClusters_ = 0;+ previewOnly_ = stillWanted_ = false;gl::Enable(GL_DEPTH_TEST);gl::DepthFunc(GL_LEQUAL);if (drawList_.empty() || !settings.showMesh) {@@ -3275,6 +3276,8 @@ void Renderer::buildCoarse(MeshSlot& s, const Mesh& mesh) {gl::VertexAttribIPointer(1, 1, GL_UNSIGNED_INT, sizeof(PackedVertex), reinterpret_cast<const void*>(2 * sizeof(uint32_t)));gl::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, s.coarseIndices);gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr(s.coarse->indices.size() * sizeof(uint32_t)), s.coarse->indices.data(), GL_STATIC_DRAW);+ const size_t indexCount = s.coarse->indices.size();+ std::vector<uint32_t>().swap(s.coarse->indices); // (on the GPU; an edit moves points, never triangles)gl::BindVertexArray(0);gl::BindBuffer(GL_ARRAY_BUFFER, 0);if (std::getenv("SF_COARSE_LOG")) {@@ -3282,8 +3285,8 @@ void Renderer::buildCoarse(MeshSlot& s, const Mesh& mesh) {for (const CoarseLevels::Lod& l : s.coarse->clusters)if (l.levels > 0) first += l.count[0] / 3, coarsest += l.count[l.levels - 1] / 3, ++withLevels;std::fprintf(stderr, "coarse lod: %zu of %zu clusters, built in %.0f ms; %zu cells, %zu indices (%.0f MB); level 0 %zu, coarsest %zu of %zu triangles\n",- withLevels, s.coarse->clusters.size(), buildMs, s.coarse->positions.size(), s.coarse->indices.size(),- double(s.coarse->positions.size() * sizeof(PackedVertex) + s.coarse->indices.size() * 4) / 1048576.0, first, coarsest,+ withLevels, s.coarse->clusters.size(), buildMs, s.coarse->positions.size(), indexCount,+ double(s.coarse->positions.size() * sizeof(PackedVertex) + indexCount * 4) / 1048576.0, first, coarsest,s.order.triangleCount());}}@@ -3299,6 +3302,12 @@ void Renderer::uploadCoarsePoints(MeshSlot& s) {gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(packed.size() * sizeof(PackedVertex)), packed.data(), GL_STATIC_DRAW);}+void Renderer::noteGpuFrame(double gpuMs, uint64_t drawnTriangles) {+ if (!(gpuMs > 0.0) || drawnTriangles < 500000) return; // (small frames are mostly fixed costs)+ const double v = gpuMs / double(drawnTriangles);+ gpuMsPerTriangle_ = gpuMsPerTriangle_ > 0.0 ? 0.8 * gpuMsPerTriangle_ + 0.2 * v : v;+}+size_t Renderer::coarsePendingClusters() const {size_t n = 0;for (const MeshSlot& s : slots_) n += s.coarsePending.size();@@ -3311,24 +3320,18 @@ void Renderer::markCoarseDirty(MeshSlot& s, uint32_t c) {if (!s.coarseDirty[c]) s.coarseDirty[c] = 1, s.coarsePending.push_back(c);}-// After a stroke: the edited clusters' levels and the points of the cells they touch (updateCoarseLevels), sent up.+// After a stroke: the points of the cells the edited clusters' vertices are in, and up the levels+// (updateCoarseLevels), sent up whole (a few MB).void Renderer::updateCoarse(MeshSlot& s, const Mesh& mesh) {const auto start = std::chrono::steady_clock::now();- std::vector<uint32_t> points;- const std::vector<uint32_t> changed = updateCoarseLevels(*s.coarse, mesh, s.order, s.bounds, s.coarsePending, points);+ const std::vector<uint32_t> changed = updateCoarseLevels(*s.coarse, mesh, s.order, s.coarsePending);gl::BindVertexArray(s.coarseVao);- if (!points.empty()) uploadCoarsePoints(s);- for (uint32_t c : changed) {- const CoarseLevels::Lod& lod = s.coarse->clusters[c];- for (int l = 0; l < lod.levels; ++l)- gl::BufferSubData(GL_ELEMENT_ARRAY_BUFFER, GLintptr(size_t(lod.first[l]) * sizeof(uint32_t)),- GLsizeiptr(size_t(lod.capacity[l]) * sizeof(uint32_t)), s.coarse->indices.data() + lod.first[l]);- s.coarseDirty[c] = 0;- }+ if (!changed.empty()) uploadCoarsePoints(s);gl::BindVertexArray(0);gl::BindBuffer(GL_ARRAY_BUFFER, 0);+ for (uint32_t c : s.coarsePending) s.coarseDirty[c] = 0;if (std::getenv("SF_COARSE_LOG"))- std::fprintf(stderr, "coarse lod: %zu clusters and %zu points updated in %.1f ms\n", s.coarsePending.size(), points.size(),+ std::fprintf(stderr, "coarse lod: %zu clusters, %zu points updated in %.1f ms\n", s.coarsePending.size(), changed.size(),std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count());s.coarsePending.clear();}@@ -3462,15 +3465,36 @@ void Renderer::drawSlot(const MeshSlot& s, bool active, bool flat, const RenderSconst bool perTriangle = features & (kPrim | kTextured | kNormalMap); // (not kFlat: no per-triangle data)const bool coarseAllowed = !perTriangle && !(active && settings.wireframe);const size_t budget = coarseLod_ ? triangleBudget(settings) : 0;- const bool coarse = coarseLod_ && coarseAllowed && s.coarse && s.coarse->clusters.size() == s.drawCount.size() &&- (settings.motionProxy || s.drawnTriangles > budget);+ // (While a stroke's edits wait for their levels, all of it in full: edited clusters in full beside coarse ones+ // would leave seams, and squeeze the rest to the coarsest level.)+ bool coarse = coarseLod_ && coarseAllowed && s.coarse && s.coarse->clusters.size() == s.drawCount.size() &&+ s.coarsePending.empty() && (settings.motionProxy || s.drawnTriangles > budget);+ // At rest the real detail, if one full frame fits the still-frame budget (a single slow frame is fine).+ if (static const bool log = std::getenv("SF_COARSE_LOG") != nullptr; log && coarse)+ std::fprintf(stderr, "coarse lod: still %.2f s, moving %d, stroking %d, pending %zu, per triangle %.3g ms\n", settings.stillSeconds,+ int(settings.motionProxy), int(settings.stroking), s.coarsePending.size(), gpuMsPerTriangle_);+ if (coarse && !settings.motionProxy && !settings.stroking && s.coarsePending.empty()) {+ constexpr double kStillDelay = 0.15;+ double stillMs = 100.0;+ if (const char* e = std::getenv("SF_STILL_FRAME_MS"); e && std::atof(e) > 0.0) stillMs = std::atof(e); // (tests)+ // (no frame measured yet: the calibrated rate, else the budget as half a 60 Hz frame's worth of triangles)+ const double perTriangle = gpuMsPerTriangle_ > 0.0 ? gpuMsPerTriangle_+ : triangleRateM_ > 0.0 ? 1e-3 / triangleRateM_+ : (1000.0 / 60.0 * 0.5) / double(std::max<size_t>(budget, 1));+ if (double(s.drawnTriangles) * perTriangle > stillMs) previewOnly_ = true;+ else if (settings.stillSeconds >= kStillDelay) coarse = false;+ else stillWanted_ = true;+ }if (static const bool log = std::getenv("SF_COARSE_LOG") != nullptr; log && s.coarse && !coarse)std::fprintf(stderr, "coarse lod: not drawn (per-triangle %d, wireframe %d, drawn %zu, budget %zu)\n", int(perTriangle),int(active && settings.wireframe), s.drawnTriangles, budget);- if (coarse) cullCoarse(s, frameCull_, budget);- else coarseClusters_.clear();+ if (coarse) {+ cullCoarse(s, frameCull_, budget);+ } else {+ coarseClusters_.clear();+ cull(s, frameCull_, settings.motionProxy && coarseAllowed);+ }lastCoarseClusters_ += coarseClusters_.size();- else cull(s, frameCull_, settings.motionProxy && coarseAllowed);// The back faces left in clusters along the silhouette: the GPU skips them too when they can't show.if (cullBackfaces_ || xrayCull_) gl::Enable(GL_CULL_FACE);if (xrayCull_) gl::CullFace(xrayCull_);diff --git a/src/render/Renderer.h b/src/render/Renderer.hindex 64780992..69e709a7 100644--- a/src/render/Renderer.h+++ b/src/render/Renderer.h@@ -43,6 +43,8 @@ struct RenderSettings {float splatOpacity = 1.0f; // global fade for using a capture as referencebool dimInactive = true; // Parts other than the active one render slightly darkerbool motionProxy = false; // the view is moving (Fast Navigation): draw big meshes' lighter proxy (render/Clusters.h)+ double stillSeconds = 0.0; // how long the view has been still (0 while it moves): coarse levels give way to full detail+ bool stroking = false; // a stroke runs (its dabs still landing): coarse levels staybool flatShading = false; // the scene's shading (Material palette): faceted; Parts can override (core/Document.h)// Backface culling (#68, Tool > Display): back faces are never drawn, on any mesh (closed or not, from any// view). Off: they are skipped only where they can't show (a closed mesh seen from outside, Renderer::cull).@@ -254,6 +256,15 @@ public:// are still to be updated (drawn in full until then).size_t coarseDrawnClusters() const { return lastCoarseClusters_; }size_t coarsePendingClusters() const;+ // At rest (still 150 ms, no stroke) an over-budget mesh draws in full detail when one full frame fits the still-frame+ // budget (100 ms, from the measured GPU time per triangle); else it stays coarse (coarsePreviewOnly: the info line+ // says so). coarseStillWanted: the last frame drew coarse and full detail follows once the view has been still long+ // enough (the app draws until then).+ bool coarsePreviewOnly() const { return previewOnly_; }+ bool coarseStillWanted() const { return stillWanted_; }+ void noteGpuFrame(double gpuMs, uint64_t drawnTriangles); // (the frame governor's GPU timer)+ void setTriangleRate(double millionsPerSecond) { triangleRateM_ = millionsPerSecond; } // (calibration; 0 = unknown)+ void setStroking(bool on) { stroking_ = on; } // a stroke runs: sync leaves the edited clusters' levels until it ends// The last syncScene left motion proxies to build (a few milliseconds of them a frame; the rest draw in full).bool proxiesPending() const { return proxyPending_; }// Build stale motion proxies on still frames too (after a stroke, so the next orbit starts with them), at a@@ -483,6 +494,9 @@ private:void cullCoarse(const MeshSlot& s, const CullView& view, size_t budget);std::vector<uint32_t> coarseClusters_;size_t lastCoarseClusters_ = 0;+ bool previewOnly_ = false, stillWanted_ = false, stroking_ = false;+ double gpuMsPerTriangle_ = 0.0; // measured (moving average), 0 = not yet+ double triangleRateM_ = 0.0; // calibrated, million triangles a second (0 = unknown)std::vector<uint8_t> coarseLevel_;void drawSlot(const MeshSlot& s, bool active, bool flat, const RenderSettings& settings);enum class DrawPart { Triangles, Lines, Proxy };diff --git a/tests/test_render_clusters.cpp b/tests/test_render_clusters.cppindex 2ad57b1f..b7b16e60 100644--- a/tests/test_render_clusters.cpp+++ b/tests/test_render_clusters.cpp@@ -14,6 +14,7 @@#include <glm/gtc/matrix_transform.hpp>+#include <chrono>#include <cmath>#include <map>#include <set>@@ -354,13 +355,13 @@ TEST(motion_proxy_is_closed_and_light) {namespace {-// Every cell point the mean of the mesh's vertices in that cell (brute force over the whole mesh).+// Every cell point the mean of its vertices where they are now (the build's membership: a vertex's level-0 cell,+// then its parents up the levels), brute force over the whole mesh.bool cellPointsAreMeans(const CoarseLevels& L, const Mesh& m, float& worst) {std::vector<glm::dvec3> sum(L.positions.size(), glm::dvec3(0.0));std::vector<uint32_t> n(L.positions.size(), 0);- for (const glm::vec3& p : m.positions)- for (int level = 0; level < int(L.levels.size()); ++level)- if (const uint32_t k = L.cellOf(p, level); k != ~0u) sum[k] += glm::dvec3(p), ++n[k];+ for (size_t v = 0; v < m.vertexCount(); ++v)+ for (uint32_t k = L.vertexCell[v]; k != ~0u; k = L.parent[k]) sum[k] += glm::dvec3(m.positions[v]), ++n[k];worst = 0.0f;for (size_t k = 0; k < sum.size(); ++k)if (n[k]) worst = std::max(worst, glm::distance(L.positions[k], glm::vec3(sum[k] / double(n[k]))));@@ -421,21 +422,21 @@ TEST(coarse_levels_closed_at_each_level_and_light) {}TEST(coarse_levels_follow_edits) {- // After a stroke (some vertices pushed out), updateCoarseLevels gives the edited clusters' levels and the points of- // the cells they touch: every cell point is again the mean of its vertices, everywhere, neighbours included.+ // After a stroke (some vertices pushed out), updateCoarseLevels moves the points of the cells those vertices are+ // in and of their cells up the levels: every cell point is again the mean of its vertices, everywhere; the+ // triangles stay as built (closed); updating again changes nothing.Mesh m = detailedSphere(300000);UploadOrder order;order.build(m);CoarseLevels L = buildCoarseLevels(m, order);- std::vector<ClusterBounds> bounds(order.clusters().size());- for (uint32_t c = 0; c < bounds.size(); ++c) bounds[c] = clusterBounds(m, order, c);+ const std::vector<glm::vec3> before(L.positions);const glm::vec3 centre = glm::normalize(glm::vec3(0.3f, 0.8f, 0.5f)) * glm::length(m.positions[0]);const float radius = glm::length(m.positions[0]) * 0.2f;std::vector<uint8_t> moved(m.vertexCount(), 0);for (size_t v = 0; v < m.vertexCount(); ++v) {const float d = glm::distance(m.positions[v], centre);if (d >= radius) continue;- m.positions[v] += m.normals[v] * (radius * 0.04f * (1.0f - d / radius)); // (a clay-like push, under a cell)+ m.positions[v] += m.normals[v] * (radius * 0.08f * (1.0f - d / radius)); // (a clay-like push, over a cell)moved[v] = 1;}std::vector<uint32_t> dirty;@@ -447,21 +448,19 @@ TEST(coarse_levels_follow_edits) {break;}}- for (uint32_t c : dirty) bounds[c] = clusterBounds(m, order, c);- std::vector<uint32_t> points;- const std::vector<uint32_t> changed = updateCoarseLevels(L, m, order, bounds, dirty, points);+ const auto start = std::chrono::steady_clock::now();+ const std::vector<uint32_t> changed = updateCoarseLevels(L, m, order, dirty);+ const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();float worst = 0.0f;const bool means = cellPointsAreMeans(L, m, worst);- size_t kept = 0;- for (uint32_t c : dirty) kept += L.clusters[c].levels > 0;- std::printf(" coarse update: %zu dirty clusters (%zu keep their levels), %zu points; worst point off by %g cells\n", dirty.size(),- kept, points.size(), double(worst / L.cell));+ size_t pointsMoved = 0;+ for (size_t k = 0; k < before.size(); ++k) pointsMoved += before[k] != L.positions[k];+ std::printf(" coarse update: %zu dirty clusters, %zu cells recomputed (%zu moved) in %.1f ms; worst point off by %g cells\n",+ dirty.size(), changed.size(), pointsMoved, ms, double(worst / L.cell));CHECK(!dirty.empty());- CHECK(changed.size() == dirty.size());+ CHECK(pointsMoved > 0);CHECK(means);- CHECK(kept * 2 >= dirty.size());- // The edited clusters' triangles match a fresh mapping on the same cells (re-updating changes nothing).- const std::vector<uint32_t> before(L.indices);- updateCoarseLevels(L, m, order, bounds, dirty, points);- CHECK(L.indices == before);+ const std::vector<glm::vec3> after(L.positions);+ updateCoarseLevels(L, m, order, dirty);+ CHECK(L.positions == after);}diff --git a/tests/ui/coarse_lod.sfui b/tests/ui/coarse_lod.sfuiindex fa1e7e79..16ad50ce 100644--- a/tests/ui/coarse_lod.sfui+++ b/tests/ui/coarse_lod.sfui@@ -1,15 +1,19 @@-# Coarse levels (docs/design/micro-coarse-lod.md): a plain mesh over the triangle budget draws each cluster at a-# coarse level, so a frame stays within the budget, at rest and while the view moves. A stroke draws the clusters it-# moved in full detail; the frame after it updates their levels, and the budget holds again.+# Coarse levels (docs/design/micro-coarse-lod.md): a plain mesh over the triangle budget draws every visible cluster+# at one coarse level while the view moves or a stroke runs, so a frame stays within the budget. At rest (still for+# 150 ms) it draws in full detail when one full frame fits the still-frame budget; if it doesn't, it stays coarse and+# the info line says "Preview detail". A stroke draws the clusters it moved in full; their levels follow after it.run ui_look look=classic layout=classic-# (the budget is the hardware tier's; a small one here, set before the mesh as at startup)+# (the budgets are the hardware tier's; small ones here, set before the mesh as at startup)env SF_TRIANGLE_BUDGET 40000+env SF_STILL_FRAME_MS 0.001run new_sphere subdivisions=6camera 0 0wait 0.6expect_value drawn_triangles <= 40000expect_value drawn_triangles > 2000-shot coarse-still+expect_value coarse_clusters > 0+expect_text "Preview detail"+shot coarse-previewcamera 35 20wait 0.6expect_value drawn_triangles <= 40000@@ -22,6 +26,8 @@ wait 0.6remember coarse_clusters beforeexpect_value coarse_pending == 0stroke 0.42 0.45 0.58 0.55 0.6 hold+# (the dabs land on the stroke thread: the clusters they moved are uploaded a few frames on)+wait 0.3expect_value coarse_pending > 0expect_value coarse_clusters < $beforeshot coarse-during-stroke@@ -32,8 +38,10 @@ expect_value coarse_clusters == $beforeexpect_value drawn_triangles <= 40000shot coarse-after-stroke-# A budget the mesh fits in: all of it in full detail.-env SF_TRIANGLE_BUDGET 100000000-wait 0.6+# A still frame that fits: at rest, full detail (the real surface), and no "Preview detail".+env SF_STILL_FRAME_MS 100000+wait 1.2+expect_value coarse_clusters == 0expect_value drawn_triangles > 60000-shot full-detail+expect_no_text "Preview detail"+shot still-full-detail