Skip to content

Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.

Coarse levels for dense plain meshes, on by default over the tier's triangle budget (SF_COARSE_LOD=0: off)

islandmedd78cbfaa5f08
diff --git a/changes/perf-coarse-lod.md b/changes/perf-coarse-lod.md
new file mode 100644
index 00000000..68137b73
--- /dev/null
+++ b/changes/perf-coarse-lod.md
@@ -0,0 +1,13 @@
+---
+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.
+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.
+ `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.
+---
+Design: docs/design/micro-coarse-lod.md (clean-room rules; pre-2000 sources). Micro levels are not covered yet.
diff --git a/docs/design/micro-coarse-lod.md b/docs/design/micro-coarse-lod.md
new file mode 100644
index 00000000..adc7bbfd
--- /dev/null
+++ b/docs/design/micro-coarse-lod.md
@@ -0,0 +1,70 @@
+# Coarse levels below the base: plain meshes and micro levels (design note, 2026-11-04)
+
+Status: built for plain meshes in perf/coarse-lod (render/Clusters.h: CoarseLevels; Renderer::cullCoarse). The
+maintainer lifted the freedom-to-operate gate on 2026-11-05; the clean-room rules below still hold. Micro levels (item
+8 proper, below their base) are not done yet: the same grids on the displaced base corners are the next step.
+
+## Clean-room rules for this work (mandatory)
+
+- Designed only from the public literature listed below. Nobody working on it reads or searches patents, and nobody
+ studies, decompiles or copies any commercial engine's implementation, or documentation of its internals.
+ Anything that starts to look like a specific product's technique stops and goes to the perf lead first.
+- What we deliberately **do not** do: no cluster DAG; no grouping of clusters whose shared boundaries are locked while
+ the group is simplified and re-split; no runtime "cut" selected through such a graph by parent/child error bounds.
+ Each cluster has its own short chain of coarser versions (a per-cluster tree of depth a few), nothing is shared
+ between clusters except the global grid below.
+
+## Sources (public, 1976-2000)
+
+- J. Clark, "Hierarchical geometric models for visible surface algorithms", CACM 1976: pick a model's detail from
+ its size on screen.
+- J. Rossignac and P. Borrel, "Multi-resolution 3D approximations for rendering complex scenes", 1993: vertex
+ clustering on a uniform grid; each cell's vertices merge to one representative, degenerate triangles drop.
+- H. Hoppe, "Progressive meshes", SIGGRAPH 1996: a mesh as a coarse base plus refinements; error measured as distance
+ to the full surface.
+- S. Rusinkiewicz and M. Levoy, "QSplat", SIGGRAPH 2000: a bounding-sphere hierarchy used both to cull and to stop
+ refining once a node projects below a pixel threshold.
+
+## The problem
+
+On a dense base (a 28M triangle scan: about 14 base triangles per pixel at 1080p) the micro renderer's coarsest level
+is one triangle per base triangle, so it never draws fewer than the base, and the floor tier's 2M triangle budget
+can't hold. Orbit cost should follow the pixels, not the base.
+
+## What we build
+
+1. **Global nested grids** (Rossignac-Borrel). Levels -1, -2, ...: cell size = 2^k x the base's mean edge, cells
+ aligned to the model's box so each level's cells nest in the next. Each cell's representative point is the mean
+ of the **displaced base corners** inside it, computed over the whole mesh (not per cluster). Two clusters that
+ touch the same cell therefore place it at the same point with no boundary rule at all.
+2. **Per-cluster coarse versions** (a per-cluster tree). For each cluster (n2stroke's layout) and each level, map its
+ base triangles' corners to cells, drop degenerate and duplicate triangles, store the index list (cell ids into
+ that level's representative buffer). Stop a cluster's chain when a level would keep fewer than ~16 triangles.
+ Built off the main thread, per frame within a measured time budget; rebuilt per cluster when a stroke dirties it.
+3. **Selection** (Clark, QSplat). Per cluster per frame: error of level -k = its cell diagonal projected at the
+ cluster's nearest point (bounding sphere); draw the coarsest level with error < ~1 px, else the existing micro
+ levels. The triangle budget then lowers detail by raising that threshold, as today.
+4. **Seams between clusters on different grid levels.** Same level: none (shared cells, item 1). Different levels: a
+ gap of at most the coarser cell, which item 3 keeps under about a pixel. Adjacent clusters are kept within one
+ level of each other (a balance pass over the cluster neighbours, as in restricted quadtrees), and the coarse
+ triangles are drawn with the existing micro shading (normals from the shading grid's corners), so a sub-pixel gap
+ shows the surface behind it, not the background, in the closed models this targets. If pinholes still show,
+ the next step is to fall back to the finer level on the cluster's border cells, not to lock boundaries.
+5. **Flag.** `RenderSettings` / Preferences > Performance "Coarse micro levels (Experimental)", off by default;
+ off = today's renderer exactly.
+
+## Measure
+
+Lucy 112M / 448M and core-200m: orbit fps and GPU ms on the E-core floor, the laptop, the Windows 3060; triangles
+drawn vs the floor's 2M budget; png_diff against the flag off where the base edge is > 1 px (must match).
+
+## What shipped first (plain meshes, 2026-11-05)
+
+- Grids as in item 1, the first cell 4x the mean edge (a 2x level drew too much to pay for its memory), up to five
+ levels; each cell's point and normal kept, so an edit can recompute them. Clusters are main's UploadOrder ones
+ (not yet n2stroke's micro layout: join there when it lands, MicroRenderer's clusters would take the same lists).
+- Selection as item 3 (0.75 px at rest, twice that while the view moves), raised x1.5 until the tier's budget holds;
+ everything fitting in full detail draws in full. No balance pass yet: clusters at different levels may leave a gap
+ of a coarse cell along their seam, under a pixel or two at the thresholds used.
+- Edits: clusters a stroke moved draw in full until the first frame without new edits, which recomputes their levels
+ and every cell point within a cell of the edit (cells for vertices pushed where none were are added).
diff --git a/src/render/Clusters.cpp b/src/render/Clusters.cpp
index 50106908..1b2a9e51 100644
--- a/src/render/Clusters.cpp
+++ b/src/render/Clusters.cpp
@@ -300,35 +300,89 @@ bool clusterProxy(const Mesh& mesh, const UploadOrder& order, uint32_t c, size_t
namespace {
-// Sorts by key: blocks in parallel, then merged pairwise.
-void sortByKey(std::vector<std::pair<uint64_t, uint32_t>>& v) {
+uint64_t packCell(glm::uvec3 q) { return uint64_t(q.x) | (uint64_t(q.y) << 21) | (uint64_t(q.z) << 42); }
+
+uint64_t cellKey(const CoarseLevels& L, const glm::vec3& p, int level) {
+ const float size = L.cell * float(1u << level);
+ const glm::vec3 q = glm::clamp(glm::floor((p - L.origin) / size), glm::vec3(0.0f), glm::vec3(float(0x1FFFFF)));
+ return packCell(glm::uvec3(q));
+}
+
+// Sorts keys in parallel blocks, merged pairwise.
+void parallelSort(std::vector<uint64_t>& v) {
const size_t blocks = 16, n = v.size(), step = (n + blocks - 1) / blocks;
if (n < 65536) {
std::sort(v.begin(), v.end());
return;
}
+ auto at = [&](size_t i) { return v.begin() + std::ptrdiff_t(std::min(n, i)); };
poolFor(blocks, [&](size_t b0, size_t b1) {
- for (size_t b = b0; b < b1; ++b) std::sort(v.begin() + std::ptrdiff_t(std::min(n, b * step)), v.begin() + std::ptrdiff_t(std::min(n, (b + 1) * step)));
+ for (size_t b = b0; b < b1; ++b) std::sort(at(b * step), at((b + 1) * step));
}, 1, 1);
- for (size_t width = step; width < n; width *= 2) {
- const size_t pairs = (n + 2 * width - 1) / (2 * width);
- poolFor(pairs, [&](size_t p0, size_t p1) {
- for (size_t p = p0; p < p1; ++p) {
- const size_t a = p * 2 * width, m = std::min(n, a + width), e = std::min(n, a + 2 * width);
- if (m < e) std::inplace_merge(v.begin() + std::ptrdiff_t(a), v.begin() + std::ptrdiff_t(m), v.begin() + std::ptrdiff_t(e));
- }
+ for (size_t width = step; width < n; width *= 2)
+ poolFor((n + 2 * width - 1) / (2 * width), [&](size_t p0, size_t p1) {
+ for (size_t p = p0; p < p1; ++p) std::inplace_merge(at(p * 2 * width), at(p * 2 * width + width), at(p * 2 * width + 2 * width));
}, 1, 1);
+}
+
+// Cluster c's triangles on the cells of `level` (degenerate and repeated ones dropped) and its error; false: a
+// vertex is in no cell of the build.
+bool clusterOnCells(const CoarseLevels& L, const Mesh& mesh, const UploadOrder& order, uint32_t c, int level,
+ std::vector<std::array<uint32_t, 3>>& tris, float& error) {
+ const size_t nv = mesh.vertexCount(), nt = mesh.triangleCount();
+ const bool hidden = mesh.hidden.size() == nt;
+ tris.clear();
+ error = 0.0f;
+ const uint32_t n = order.clusterTriangles(c);
+ for (uint32_t i = 0; i < n; ++i) {
+ const uint32_t t = order.triangle(c, i);
+ if (t >= nt || (hidden && mesh.hidden[t])) continue;
+ const glm::uvec3 tri = mesh.triangles[t];
+ if (tri.x >= nv || tri.y >= nv || tri.z >= nv) continue;
+ std::array<uint32_t, 3> m;
+ for (int k = 0; k < 3; ++k) {
+ const glm::vec3& p = mesh.positions[tri[k]];
+ m[size_t(k)] = L.cellOf(p, level);
+ if (m[size_t(k)] == ~0u) return false;
+ error = std::max(error, glm::distance(p, L.positions[m[size_t(k)]]));
+ }
+ if (m[0] == m[1] || m[1] == m[2] || m[0] == m[2]) continue;
+ std::rotate(m.begin(), std::min_element(m.begin(), m.end()), m.end()); // (one rotation per triangle)
+ tris.push_back(m);
}
+ std::sort(tris.begin(), tris.end());
+ tris.erase(std::unique(tris.begin(), tris.end()), tris.end());
+ return true;
}
+uint32_t roomFor(size_t indices) { return uint32_t(indices + indices / 4 + 48); } // (an edit may add a few)
+
} // namespace
+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;
+}
+
CoarseLevels buildCoarseLevels(const Mesh& mesh, const UploadOrder& order) {
- CoarseLevels out;
+ CoarseLevels L;
const size_t nv = mesh.vertexCount(), nt = mesh.triangleCount();
const uint32_t nc = uint32_t(order.clusters().size());
- out.clusters.resize(nc);
- if (nv == 0 || nt == 0 || nc == 0) return out;
+ L.clusters.resize(nc);
+ if (nv == 0 || nt == 0 || nc == 0) return L;
AABB box;
for (const glm::vec3& p : mesh.positions) box.expand(p);
double edges = 0.0;
@@ -339,130 +393,190 @@ CoarseLevels buildCoarseLevels(const Mesh& mesh, const UploadOrder& order) {
edges += glm::distance(mesh.positions[tri.x], mesh.positions[tri.y]) + glm::distance(mesh.positions[tri.y], mesh.positions[tri.z]);
counted += 2;
}
- if (!counted || !box.valid()) return out;
- const float cell1 = float(edges / double(counted)) * 2.0f;
- if (!(cell1 > 0.0f)) return out;
+ if (!counted || !box.valid()) return L;
+ L.cell = float(edges / double(counted)) * 4.0f;
+ if (!(L.cell > 0.0f)) return L;
+ // Room on the grid for the mesh to move a little (as PositionGrid's margin).
+ L.origin = box.min - (box.max - box.min) * 0.125f - glm::vec3(L.cell);
const bool hasNormals = mesh.normals.size() == nv;
- const bool hidden = mesh.hidden.size() == nt;
- auto pack = [](glm::uvec3 q) { return uint64_t(q.x) | (uint64_t(q.y) << 21) | (uint64_t(q.z) << 42); };
- auto unpack = [](uint64_t k) { return glm::uvec3(uint32_t(k & 0x1FFFFF), uint32_t((k >> 21) & 0x1FFFFF), uint32_t(k >> 42)); };
- // The items of a level: the vertices at first, then the cells of the level before (weighted sums).
- std::vector<uint64_t> itemKey(nv);
- std::vector<glm::dvec3> itemSum; // (level 0: the mesh's own positions, normals and a weight of 1)
- std::vector<glm::vec3> itemNormal;
- std::vector<uint32_t> itemWeight;
- poolFor(nv, [&](size_t v0, size_t v1) {
- for (size_t v = v0; v < v1; ++v) {
- const glm::vec3 q = glm::clamp(glm::floor((mesh.positions[v] - box.min) / cell1), glm::vec3(0.0f), glm::vec3(float(0x1FFFFF)));
- itemKey[v] = pack(glm::uvec3(q));
- }
- });
- std::vector<uint32_t> vertexCell(nv); // each vertex's cell at the current level (into out.positions)
- std::vector<uint32_t> itemCell;
- std::vector<std::vector<uint32_t>> lists(nc);
- std::vector<uint8_t> done(nc, 0);
- std::vector<size_t> previous(nc, 0);
- for (uint32_t c = 0; c < nc; ++c) previous[c] = order.clusterTriangles(c);
- std::vector<std::pair<uint64_t, uint32_t>> sorted;
+ // The cells of each level: the sorted keys of the vertices' cells, each once.
+ std::vector<uint32_t> cellOfVertex(nv);
for (int level = 0; level < CoarseLevels::kMaxLevels; ++level) {
- const size_t items = itemKey.size();
- sorted.resize(items);
- poolFor(items, [&](size_t i0, size_t i1) {
- for (size_t i = i0; i < i1; ++i) sorted[i] = {itemKey[i], uint32_t(i)};
- });
- sortByKey(sorted);
- // The cells: runs of one key.
- const uint32_t base = uint32_t(out.positions.size());
- itemCell.assign(items, 0);
- std::vector<uint64_t> cellKey;
- std::vector<glm::dvec3> cellSum;
- std::vector<glm::vec3> cellNormal;
- std::vector<uint32_t> cellWeight;
- for (size_t i = 0; i < items;) {
- size_t j = i;
- glm::dvec3 sum(0.0);
- glm::vec3 nsum(0.0f);
- uint32_t w = 0;
- for (; j < items && sorted[j].first == sorted[i].first; ++j) {
- const uint32_t it = sorted[j].second;
- if (level == 0) {
- sum += glm::dvec3(mesh.positions[it]);
- if (hasNormals) nsum += mesh.normals[it];
- ++w;
- } else {
- sum += itemSum[it];
- nsum += itemNormal[it];
- w += itemWeight[it];
- }
- itemCell[it] = uint32_t(cellKey.size());
+ CoarseLevels::Level& lv = L.levels.emplace_back();
+ lv.base = uint32_t(L.positions.size());
+ {
+ std::vector<uint64_t> keys;
+ if (level == 0) {
+ keys.resize(nv);
+ poolFor(nv, [&](size_t v0, size_t v1) {
+ for (size_t v = v0; v < v1; ++v) keys[v] = cellKey(L, mesh.positions[v], 0);
+ });
+ } else {
+ keys.reserve(L.levels[size_t(level) - 1].keys.size());
+ for (uint64_t k : L.levels[size_t(level) - 1].keys) // (nested: each axis index halves)
+ keys.push_back(packCell(glm::uvec3(uint32_t(k & 0x1FFFFF), uint32_t((k >> 21) & 0x1FFFFF), uint32_t(k >> 42)) / 2u));
}
- cellKey.push_back(sorted[i].first);
- cellSum.push_back(sum);
- cellNormal.push_back(nsum);
- cellWeight.push_back(w);
- i = j;
- }
- const size_t cells = cellKey.size();
- for (size_t k = 0; k < cells; ++k) {
- out.positions.push_back(glm::vec3(cellSum[k] / double(cellWeight[k])));
- const float l = glm::length(cellNormal[k]);
- out.normals.push_back(l > 1e-12f ? cellNormal[k] / l : glm::vec3(0.0f, 0.0f, 1.0f));
+ parallelSort(keys);
+ keys.erase(std::unique(keys.begin(), keys.end()), keys.end());
+ lv.keys.assign(keys.begin(), keys.end()); // (exact size)
}
+ const size_t cells = lv.keys.size();
poolFor(nv, [&](size_t v0, size_t v1) {
- for (size_t v = v0; v < v1; ++v) vertexCell[v] = base + itemCell[level == 0 ? v : vertexCell[v] - (base - uint32_t(items))];
+ for (size_t v = v0; v < v1; ++v) cellOfVertex[v] = L.cellOf(mesh.positions[v], level) - lv.base;
});
- // Per cluster: its triangles on these cells, and its error.
- poolFor(nc, [&](size_t c0, size_t c1) {
- std::vector<std::array<uint32_t, 3>> tris;
- for (size_t c = c0; c < c1; ++c) {
- if (done[c]) continue;
- const uint32_t n = order.clusterTriangles(uint32_t(c));
- tris.clear();
+ std::vector<glm::dvec3> sum(cells, glm::dvec3(0.0));
+ std::vector<glm::vec3> nsum(cells, glm::vec3(0.0f));
+ std::vector<uint32_t> weight(cells, 0);
+ for (size_t v = 0; v < nv; ++v) {
+ const uint32_t k = cellOfVertex[v];
+ sum[k] += glm::dvec3(mesh.positions[v]);
+ if (hasNormals) nsum[k] += mesh.normals[v];
+ ++weight[k];
+ }
+ for (size_t k = 0; k < cells; ++k) {
+ L.positions.push_back(glm::vec3(sum[k] / double(std::max(weight[k], 1u))));
+ const float l = glm::length(nsum[k]);
+ L.normals.push_back(l > 1e-12f ? nsum[k] / l : glm::vec3(0.0f, 0.0f, 1.0f));
+ }
+ if (cells < 64) break;
+ }
+ cellOfVertex = {};
+ // Per cluster, its levels while they pay.
+ std::vector<std::vector<uint32_t>> lists(nc);
+ poolFor(nc, [&](size_t c0, size_t c1) {
+ std::vector<std::array<uint32_t, 3>> tris;
+ for (size_t c = c0; c < c1; ++c) {
+ CoarseLevels::Lod& lod = L.clusters[c];
+ size_t previous = order.clusterTriangles(uint32_t(c));
+ for (int level = 0; level < int(L.levels.size()); ++level) {
float error = 0.0f;
- for (uint32_t i = 0; i < n; ++i) {
- const uint32_t t = order.triangle(uint32_t(c), i);
- if (t >= nt || (hidden && mesh.hidden[t])) continue;
- const glm::uvec3 tri = mesh.triangles[t];
- if (tri.x >= nv || tri.y >= nv || tri.z >= nv) continue;
- std::array<uint32_t, 3> m{vertexCell[tri.x], vertexCell[tri.y], vertexCell[tri.z]};
- for (int k = 0; k < 3; ++k) error = std::max(error, glm::distance(mesh.positions[tri[k]], out.positions[m[size_t(k)]]));
- if (m[0] == m[1] || m[1] == m[2] || m[0] == m[2]) continue;
- std::rotate(m.begin(), std::min_element(m.begin(), m.end()), m.end()); // (one rotation per triangle)
- tris.push_back(m);
- }
- std::sort(tris.begin(), tris.end());
- tris.erase(std::unique(tris.begin(), tris.end()), tris.end());
- CoarseLevels::Lod& lod = out.clusters[c];
- if (tris.empty() || tris.size() * 10 > previous[c] * 8) {
- done[c] = 1;
- continue;
- }
+ if (!clusterOnCells(L, mesh, order, uint32_t(c), level, tris, error) || tris.empty() || tris.size() * 10 > previous * 8) break;
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());
- previous[c] = tris.size();
- if (tris.size() < 8) done[c] = 1;
+ lists[c].resize(lod.first[lod.levels - 1] + lod.capacity[lod.levels - 1], 0);
+ previous = tris.size();
+ if (tris.size() < 8) break;
}
- }, 16, 1);
- if (cells < 64) break;
- // The next level's items: these cells, each axis index halved.
- itemKey.resize(cells);
- itemSum = std::move(cellSum);
- itemNormal = std::move(cellNormal);
- itemWeight = std::move(cellWeight);
- for (size_t k = 0; k < cells; ++k) {
- const glm::uvec3 q = unpack(cellKey[k]);
- itemKey[k] = pack(q / 2u);
+ lists[c].shrink_to_fit();
}
- }
+ }, 16, 1);
+ size_t total = 0;
+ for (const auto& l : lists) total += l.size();
+ L.indices.reserve(total);
for (uint32_t c = 0; c < nc; ++c) {
- const uint32_t at = uint32_t(out.indices.size());
- for (int l = 0; l < out.clusters[c].levels; ++l) out.clusters[c].first[l] += at;
- out.indices.insert(out.indices.end(), lists[c].begin(), lists[c].end());
+ const uint32_t at = uint32_t(L.indices.size());
+ for (int l = 0; l < L.clusters[c].levels; ++l) L.clusters[c].first[l] += at;
+ L.indices.insert(L.indices.end(), lists[c].begin(), lists[c].end());
+ std::vector<uint32_t>().swap(lists[c]);
+ }
+ return L;
+}
+
+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();
+ 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.
+ 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);
+ 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);
+ }
+ if (!ok) lod.levels = 0; // (drawn in full until the next build)
+ changed.push_back(c);
}
- return out;
+ return changed;
}
bool closedOriented(const Mesh& mesh) {
diff --git a/src/render/Clusters.h b/src/render/Clusters.h
index 3cc35f4f..39d6e2c4 100644
--- a/src/render/Clusters.h
+++ b/src/render/Clusters.h
@@ -17,6 +17,8 @@
#include <algorithm>
#include <cstdint>
+#include <unordered_map>
+#include <vector>
namespace sf {
@@ -73,24 +75,42 @@ ClusterBounds clusterBounds(const Mesh& mesh, const UploadOrder& order, uint32_t
bool clusterProxy(const Mesh& mesh, const UploadOrder& order, uint32_t c, size_t maxTriangles, std::vector<uint16_t>& out,
ClusterBounds& bounds);
-// Coarse levels below the mesh (spike, SF_COARSE_LOD=1; docs/design/micro-coarse-lod.md, Rossignac-Borrel 1993):
-// nested grids over the whole mesh, the first cell twice the mean edge, each next level twice as coarse; a cell's
-// point is the mean of the vertices in it (its normal their normals' sum). Every cluster gets per level its triangles
-// mapped to cells (degenerate and repeated ones dropped) and its error, the farthest any of its vertices moved. Two
-// clusters at one level share their cells' points: no cracks between them. A cluster's chain stops when a level
-// would keep more than 80% of the one before.
+// Coarse levels below the mesh (docs/design/micro-coarse-lod.md; Clark 1976, Rossignac-Borrel 1993): nested grids
+// over the whole mesh, the first cell four times the mean edge, each next level twice as coarse; a cell's point is the
+// mean of the vertices in it (its normal their normals' sum). Every cluster gets per level its triangles mapped to
+// cells (degenerate and repeated ones dropped) and its error, the farthest any of its vertices is from its cell's
+// point. Two clusters at one level share their cells' points: no cracks between them. A cluster's chain stops when a
+// level would keep more than 80% of the one before.
struct CoarseLevels {
- static constexpr int kMaxLevels = 6;
+ static constexpr int kMaxLevels = 5;
struct Lod {
- int levels = 0;
- uint32_t first[kMaxLevels] = {}, count[kMaxLevels] = {}; // in `indices` (indices, not triangles)
- float error[kMaxLevels] = {}; // world units
+ int levels = 0; // 0: none (drawn in full)
+ uint32_t first[kMaxLevels] = {}, count[kMaxLevels] = {}, capacity[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 + i
+ uint32_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's
+ std::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
+ std::vector<uint32_t> indices; // into positions; each level of each cluster with room to grow
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).
+ 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.
+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);
// 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), every
diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cpp
index be46ead8..95bfbb19 100644
--- a/src/render/Renderer.cpp
+++ b/src/render/Renderer.cpp
@@ -1580,8 +1580,7 @@ void Renderer::updateBounds(MeshSlot& s, const Mesh& mesh, bool all, bool comput
}
}
s.proxyStale.resize(clusters.size(), 1);
- for (uint32_t c : cullScratch_) s.proxyStale[c] = 1;
- if (!cullScratch_.empty()) s.coarseValid = false; // (the spike doesn't rebuild: the normal draw)
+ for (uint32_t c : cullScratch_) s.proxyStale[c] = 1, markCoarseDirty(s, c);
if (computed) cullScratch_.clear();
poolFor(cullScratch_.size(), [&](size_t i0, size_t i1) {
for (size_t i = i0; i < i1; ++i) {
@@ -2285,7 +2284,7 @@ void Renderer::sync(MeshSlot& s, Mesh& mesh, const NormalMapView* normalMap, boo
}
if (full) {
s.proxyAllocated = false; // sized for the old mesh
- s.coarseValid = s.coarseTried = false;
+ s.coarse.reset(), s.coarseTried = false, s.coarseDirty.clear(), s.coarsePending.clear();
s.proxyCount.clear();
// (closedOriented also accepts unwelded seams, the same point twice, which the layout's check doesn't.)
s.closed = s.order.closed() || closedOriented(mesh);
@@ -2319,6 +2318,8 @@ void Renderer::sync(MeshSlot& s, Mesh& mesh, const NormalMapView* normalMap, boo
buildProxies(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)
+ s.coarseEdited = false;
if (syncLog) proxyMs = lapMs(lap);
syncTexture(s, mesh, pbr);
syncNormalMap(s, mesh, normalMap);
@@ -3176,7 +3177,8 @@ void Renderer::cullCoarse(const MeshSlot& s, const CullView& frame, float px, si
}
drawClusters_.clear();
auto level = [&](const LodPick& k, float t) {
- const CoarseLevels::Lod& lod = s.coarse[k.c];
+ const CoarseLevels::Lod& lod = s.coarse->clusters[k.c];
+ if (s.coarseDirty[k.c]) return -1; // (edited: in full until updated)
int pick = -1;
while (pick + 1 < lod.levels && lod.error[pick + 1] * k.scale <= t) ++pick;
return pick;
@@ -3187,7 +3189,7 @@ void Renderer::cullCoarse(const MeshSlot& s, const CullView& frame, float px, si
size_t total = 0;
for (const LodPick& k : lodScratch_) {
const int l = level(k, t);
- total += l < 0 ? (k.fullShows ? size_t(s.drawCount[k.c]) / 3 : 0) : s.coarse[k.c].count[l] / 3;
+ total += l < 0 ? (k.fullShows ? size_t(s.drawCount[k.c]) / 3 : 0) : s.coarse->clusters[k.c].count[l] / 3;
}
if (total <= budget) break;
}
@@ -3262,43 +3264,84 @@ static glm::vec3 materialTintShift(const RenderSettings& settings, bool hasColor
// governor, SF_HW_SIMULATE=floor); half of it while the view moves (Fast Navigation), so orbiting stays smooth.
size_t Renderer::triangleBudget(const RenderSettings& settings) const {
size_t full = settings.renderTriangleBudget ? settings.renderTriangleBudget : size_t(currentTierConfig().activeTriangleBudget);
+ if (const char* forced = std::getenv("SF_TRIANGLE_BUDGET"); forced && std::atoll(forced) > 0) full = size_t(std::atoll(forced)); // (tests)
if (const uint64_t governed = renderTriangleBudget(); governed > 0) full = std::min(full, size_t(governed));
return settings.motionProxy ? full / 2 : full;
}
-// The spike's coarse levels (render/Clusters.h): built once, at once, timed; their own vertices and 32-bit indices.
+// The coarse levels (render/Clusters.h): built at once, timed; their own vertices and 32-bit indices.
void Renderer::buildCoarse(MeshSlot& s, const Mesh& mesh) {
s.coarseTried = true;
const auto start = std::chrono::steady_clock::now();
- CoarseLevels levels = buildCoarseLevels(mesh, s.order);
+ auto levels = std::make_unique<CoarseLevels>(buildCoarseLevels(mesh, s.order));
const double buildMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
- if (levels.clusters.size() != s.order.clusters().size() || levels.indices.empty()) return;
- std::vector<PackedVertex> packed(levels.positions.size());
- for (size_t i = 0; i < packed.size(); ++i) packVertex(s.grid, levels.positions[i], levels.normals[i], 0.0f, packed[i]);
+ if (levels->clusters.size() != s.order.clusters().size() || levels->indices.empty()) return;
if (!s.coarseVao) {
gl::GenVertexArrays(1, &s.coarseVao);
gl::GenBuffers(1, &s.coarseVertices);
gl::GenBuffers(1, &s.coarseIndices);
}
+ s.coarse = std::move(levels);
+ s.coarseDirty.assign(s.coarse->clusters.size(), 0);
+ s.coarsePending.clear();
gl::BindVertexArray(s.coarseVao);
- gl::BindBuffer(GL_ARRAY_BUFFER, s.coarseVertices);
- gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(packed.size() * sizeof(PackedVertex)), packed.data(), GL_STATIC_DRAW);
+ uploadCoarsePoints(s);
gl::EnableVertexAttribArray(0);
gl::VertexAttribIPointer(0, 2, GL_UNSIGNED_INT, sizeof(PackedVertex), nullptr);
gl::EnableVertexAttribArray(1);
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(levels.indices.size() * sizeof(uint32_t)), levels.indices.data(), GL_STATIC_DRAW);
+ gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr(s.coarse->indices.size() * sizeof(uint32_t)), s.coarse->indices.data(), GL_STATIC_DRAW);
+ gl::BindVertexArray(0);
+ gl::BindBuffer(GL_ARRAY_BUFFER, 0);
+ if (std::getenv("SF_COARSE_LOG")) {
+ size_t first = 0, coarsest = 0, withLevels = 0;
+ 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,
+ s.order.triangleCount());
+ }
+}
+
+// The cells' points, packed on the mesh's position grid (whole: a few MB).
+void Renderer::uploadCoarsePoints(MeshSlot& s) {
+ const CoarseLevels& L = *s.coarse;
+ std::vector<PackedVertex> packed(L.positions.size());
+ poolFor(packed.size(), [&](size_t i0, size_t i1) {
+ for (size_t i = i0; i < i1; ++i) packVertex(s.grid, L.positions[i], L.normals[i], 0.0f, packed[i]);
+ });
+ gl::BindBuffer(GL_ARRAY_BUFFER, s.coarseVertices);
+ gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(packed.size() * sizeof(PackedVertex)), packed.data(), GL_STATIC_DRAW);
+}
+
+void Renderer::markCoarseDirty(MeshSlot& s, uint32_t c) {
+ if (!s.coarse || c >= s.coarseDirty.size()) return;
+ s.coarseEdited = true;
+ 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.
+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);
+ 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;
+ }
gl::BindVertexArray(0);
gl::BindBuffer(GL_ARRAY_BUFFER, 0);
- s.coarse = std::move(levels.clusters);
- s.coarseValid = true;
- size_t first = 0, coarsest = 0, withLevels = 0;
- for (const CoarseLevels::Lod& l : s.coarse)
- 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 GPU); level 1 %zu, coarsest %zu of %zu triangles\n",
- withLevels, s.coarse.size(), buildMs, packed.size(), levels.indices.size(),
- double(packed.size() * sizeof(PackedVertex) + levels.indices.size() * 4) / 1048576.0, first, coarsest, s.order.triangleCount());
+ 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::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count());
+ s.coarsePending.clear();
}
void Renderer::drawMicro(const MeshSlot& s, bool active, bool flat, const RenderSettings& settings) {
@@ -3430,8 +3473,11 @@ void Renderer::drawSlot(const MeshSlot& s, bool active, bool flat, const RenderS
const 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.coarseValid && s.coarse.size() == s.drawCount.size() &&
+ const bool coarse = coarseLod_ && coarseAllowed && s.coarse && s.coarse->clusters.size() == s.drawCount.size() &&
(settings.motionProxy || s.drawnTriangles > budget);
+ 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_, kCoarseLodPx * (settings.motionProxy ? 2.0f : 1.0f), budget);
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.
@@ -3490,7 +3536,7 @@ void Renderer::drawSlot(const MeshSlot& s, bool active, bool flat, const RenderS
drawOffsets_.clear();
size_t indices = 0;
for (size_t i = 0; i < coarseClusters_.size(); ++i) {
- const CoarseLevels::Lod& l = s.coarse[coarseClusters_[i]];
+ const CoarseLevels::Lod& l = s.coarse->clusters[coarseClusters_[i]];
drawCounts_.push_back(GLsizei(l.count[coarseLevel_[i]]));
drawOffsets_.push_back(reinterpret_cast<const void*>(size_t(l.first[coarseLevel_[i]]) * sizeof(uint32_t)));
indices += l.count[coarseLevel_[i]];
@@ -3768,7 +3814,7 @@ void Renderer::commitStrokeUpload(StrokeUpload& up) {
s.proxyStale.resize(s.bounds.size(), 1);
for (size_t i = 0; i < up.movedClusters.size(); ++i) {
s.bounds[up.movedClusters[i]] = up.bounds[i];
- s.proxyStale[up.movedClusters[i]] = 1, s.coarseValid = false;
+ s.proxyStale[up.movedClusters[i]] = 1, markCoarseDirty(s, up.movedClusters[i]);
}
s.looseClusters.insert(s.looseClusters.end(), up.movedClusters.begin(), up.movedClusters.end());
s.looseMark.resize(s.bounds.size(), 0);
diff --git a/src/render/Renderer.h b/src/render/Renderer.h
index 6274baca..15dfa560 100644
--- a/src/render/Renderer.h
+++ b/src/render/Renderer.h
@@ -357,11 +357,13 @@ private:
std::vector<uint8_t> proxyStale; // to rebuild before use
std::vector<ClusterBounds> proxyBounds; // the proxy's normal cone
bool proxyAllocated = false;
- // Coarse levels (spike, SF_COARSE_LOD=1: buildCoarseLevels at the first sync over the budget). Any edit to
- // the mesh drops them (the normal draw again): no rebuild in the spike.
+ // Coarse levels (buildCoarseLevels at the first sync over the budget, again after a new layout). Clusters an
+ // edit moved draw in full (coarseDirty) until the first sync without new edits updates their levels.
GLuint coarseVao = 0, coarseVertices = 0, coarseIndices = 0;
- std::vector<CoarseLevels::Lod> coarse;
- bool coarseValid = false, coarseTried = false;
+ std::unique_ptr<CoarseLevels> coarse;
+ std::vector<uint8_t> coarseDirty;
+ std::vector<uint32_t> coarsePending; // the dirty clusters, to update
+ bool coarseTried = false, coarseEdited = false; // (coarseEdited: this sync marked some)
std::vector<uint32_t> drawnOrder; // the mesh triangle of each drawn triangle (meshes with UVs only)
size_t drawnTriangles = 0;
size_t vertexCapacity = 0;
@@ -415,13 +417,16 @@ private:
bool proxyPending_ = false; // (proxiesPending)
bool proxyPrebuild_ = false; // (setProxyPrebuild)
double proxyMsPerCluster_ = 0.0; // measured, so a frame's batches fit its budget on slow cores too
- // Spike (SF_COARSE_LOD=1, off by default; docs/design/micro-coarse-lod.md): plain meshes over the triangle budget
- // draw per cluster a coarse level (render/Clusters.h: CoarseLevels), at rest too: the coarsest whose error stays
- // under kCoarseLodPx on screen, raised until the budget holds; full detail when it all fits.
- const bool coarseLod_ = std::getenv("SF_COARSE_LOD") && std::string(std::getenv("SF_COARSE_LOD")) == "1";
+ // Coarse levels (docs/design/micro-coarse-lod.md; SF_COARSE_LOD=0 turns them off): plain meshes over the triangle
+ // budget draw per cluster a coarse level (render/Clusters.h: CoarseLevels), at rest too: the coarsest whose error
+ // stays under kCoarseLodPx on screen, raised until the budget holds; full detail when it all fits.
+ const bool coarseLod_ = !(std::getenv("SF_COARSE_LOD") && std::string(std::getenv("SF_COARSE_LOD")) == "0");
+ void markCoarseDirty(MeshSlot& s, uint32_t c);
+ void updateCoarse(MeshSlot& s, const Mesh& mesh);
static constexpr float kCoarseLodPx = 0.75f;
size_t lodBudget_ = 0; // the last still draw's triangle budget: sync builds the coarse levels of meshes over it
void buildCoarse(MeshSlot& s, const Mesh& mesh);
+ void uploadCoarsePoints(MeshSlot& s);
size_t triangleBudget(const RenderSettings& settings) const;
// The ghost (setGhost), drawn on the slot ghostId_.
GhostStroke ghost_;
diff --git a/tests/test_render_clusters.cpp b/tests/test_render_clusters.cpp
index 9c7161e5..3d8f023e 100644
--- a/tests/test_render_clusters.cpp
+++ b/tests/test_render_clusters.cpp
@@ -16,6 +16,7 @@
#include <cmath>
#include <map>
+#include <set>
#include <random>
using namespace sf;
@@ -350,3 +351,117 @@ TEST(motion_proxy_is_closed_and_light) {
ClusterBounds b;
CHECK(clusterProxy(h, order, 0, order.clusterTriangles(0), proxy, b) && proxy.empty());
}
+
+namespace {
+
+// Every cell point the mean of the mesh's vertices in that cell (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];
+ 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]))));
+ return worst < L.cell * 1e-4f;
+}
+
+Mesh detailedSphere(size_t triangles) {
+ Mesh m = makeBenchSphere(triangles);
+ for (size_t v = 0; v < m.vertexCount(); ++v) {
+ const glm::vec3 p = m.positions[v];
+ m.positions[v] = p * (1.0f + 0.02f * std::sin(p.x * 31.0f) * std::sin(p.z * 29.0f));
+ }
+ m.recomputeAllNormals();
+ return m;
+}
+
+} // namespace
+
+TEST(coarse_levels_closed_at_each_level_and_light) {
+ // Coarse levels (buildCoarseLevels) on one grid per level for the whole mesh: with every cluster at one level the
+ // surface stays closed (neighbours share their cells' points), each level lighter than the one before.
+ Mesh m = detailedSphere(1000000);
+ UploadOrder order;
+ order.build(m);
+ const CoarseLevels L = buildCoarseLevels(m, order);
+ CHECK(L.clusters.size() == order.clusters().size());
+ float worst = 0.0f;
+ CHECK(cellPointsAreMeans(L, m, worst));
+ size_t first = 0, coarsest = 0, minLevels = CoarseLevels::kMaxLevels;
+ bool shrinking = true;
+ for (const CoarseLevels::Lod& l : L.clusters) {
+ minLevels = std::min(minLevels, size_t(l.levels));
+ if (l.levels == 0) continue;
+ first += l.count[0] / 3;
+ coarsest += l.count[l.levels - 1] / 3;
+ for (int k = 1; k < l.levels; ++k) shrinking = shrinking && l.count[k] < l.count[k - 1] && l.error[k] >= l.error[k - 1];
+ }
+ std::printf(" coarse levels: %zu cells; level 0 %zu, coarsest %zu of %zu triangles; every cluster has %zu levels or more\n",
+ L.positions.size(), first, coarsest, m.triangleCount(), minLevels);
+ CHECK(shrinking);
+ CHECK(minLevels >= 1);
+ CHECK(first * 8 < m.triangleCount());
+ // No cracks: every edge of the level's distinct triangles is shared by two of them or more (a cluster drops
+ // the repeats of a triangle, so counting oriented edges exactly would be too strict).
+ for (int level = 0; level < int(minLevels); ++level) {
+ std::set<std::array<uint32_t, 3>> tris;
+ for (const CoarseLevels::Lod& l : L.clusters)
+ for (uint32_t i = l.first[level]; i < l.first[level] + l.count[level]; i += 3)
+ tris.insert({L.indices[i], L.indices[i + 1], L.indices[i + 2]});
+ std::map<std::pair<uint32_t, uint32_t>, int> edges;
+ for (const auto& t : tris)
+ for (int k = 0; k < 3; ++k) ++edges[std::minmax(t[size_t(k)], t[size_t((k + 1) % 3)])];
+ size_t open = 0;
+ for (const auto& [e, n] : edges) open += n < 2;
+ if (open) std::printf(" level %d: %zu of %zu edges with one triangle\n", level, open, edges.size());
+ CHECK(open == 0);
+ }
+}
+
+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.
+ 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 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)
+ moved[v] = 1;
+ }
+ std::vector<uint32_t> dirty;
+ for (uint32_t c = 0; c < order.clusters().size(); ++c) {
+ const auto& cl = order.clusters()[c];
+ for (uint32_t l = 0; l < cl.vertexCount; ++l)
+ if (moved[order.fromGpu()[cl.firstVertex + l]]) {
+ dirty.push_back(c);
+ 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);
+ 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));
+ CHECK(!dirty.empty());
+ CHECK(changed.size() == dirty.size());
+ 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);
+}
diff --git a/tests/ui/coarse_lod.sfui b/tests/ui/coarse_lod.sfui
new file mode 100644
index 00000000..1b88e557
--- /dev/null
+++ b/tests/ui/coarse_lod.sfui
@@ -0,0 +1,30 @@
+# 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.
+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)
+env SF_TRIANGLE_BUDGET 40000
+run new_sphere subdivisions=6
+camera 0 0
+wait 0.6
+expect_value drawn_triangles <= 40000
+expect_value drawn_triangles > 2000
+shot coarse-still
+camera 35 20
+wait 0.6
+expect_value drawn_triangles <= 40000
+shot coarse-turned
+
+# A stroke: the clusters it moved draw in full while it runs; the levels are updated after it.
+camera 0 0
+wait 0.6
+drag_path 0.42 0.45 0.58 0.45 0.58 0.55
+wait 0.6
+expect_value drawn_triangles <= 40000
+shot coarse-after-stroke
+
+# A budget the mesh fits in: all of it in full detail.
+env SF_TRIANGLE_BUDGET 100000000
+wait 0.6
+expect_value drawn_triangles > 60000
+shot full-detail