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
Spike (SF_COARSE_LOD=1, off by default): plain meshes over the triangle budget draw per-cluster coarse levels
islandmed9d582c20473a
diff --git a/src/render/Clusters.cpp b/src/render/Clusters.cppindex 4947f10b..ef0cfa6c 100644--- a/src/render/Clusters.cpp+++ b/src/render/Clusters.cpp@@ -298,6 +298,122 @@ bool clusterProxy(const Mesh& mesh, const UploadOrder& order, uint32_t c, size_treturn true;}+bool clusterLodChain(const Mesh& mesh, const UploadOrder& order, uint32_t c, size_t maxIndices, std::vector<uint16_t>& out,+ ClusterLod& lod, ClusterBounds& bounds) {+ out.clear();+ lod = ClusterLod();+ const uint32_t n = order.clusterTriangles(c);+ const UploadOrder::Cluster& cl = order.clusters()[c];+ const auto fromGpu = order.fromGpu();+ thread_local std::vector<uint16_t> local, rep;+ thread_local std::vector<uint8_t> pinned;+ local.resize(size_t(n) * 3);+ order.localTriangles(mesh, c, local.data());+ const uint32_t nl = cl.vertexCount;+ pinned.assign(nl, 0);+ AABB box;+ for (uint32_t l = 0; l < nl; ++l) {+ const uint32_t v = fromGpu[cl.firstVertex + l];+ pinned[l] = order.shared(v);+ box.expand(mesh.positions[v]);+ }+ auto pos = [&](uint32_t l) { return mesh.positions[fromGpu[cl.firstVertex + l]]; };+ const bool hidden = mesh.hidden.size() == mesh.triangleCount();+ double edges = 0.0;+ size_t counted = 0;+ for (uint32_t i = 0; i < n; i += 7) {+ const uint16_t* t = local.data() + size_t(i) * 3;+ edges += glm::distance(pos(t[0]), pos(t[1])) + glm::distance(pos(t[1]), pos(t[2]));+ counted += 2;+ }+ if (!counted || !box.valid()) return false;+ float cell = float(edges / double(counted)) * 2.0f; // (about a quarter of the triangles at the first level)+ if (!(cell > 0.0f)) return false;+ thread_local CellTable cells;+ thread_local std::vector<uint32_t> cellOfVertex;+ cellOfVertex.resize(nl);+ rep.resize(nl);+ const float span = glm::length(box.max - box.min);+ size_t previous = 0; // the triangles of the level before (the cluster's own at first)+ for (uint32_t i = 0; i < n; ++i) previous += !(hidden && mesh.hidden[order.triangle(c, i)]);+ glm::vec3 sum(0.0f);+ for (; lod.levels < ClusterLod::kMaxLevels; cell *= 2.0f) {+ cells.clear();+ const float inv = 1.0f / cell;+ for (uint32_t l = 0; l < nl; ++l) {+ if (pinned[l]) continue;+ const glm::vec3 p = pos(l);+ const glm::vec3 q = glm::floor((p - box.min) * inv);+ const glm::vec3 centre = box.min + (q + 0.5f) * cell;+ const uint64_t key = uint64_t(uint32_t(q.x)) | (uint64_t(uint32_t(q.y)) << 21) | (uint64_t(uint32_t(q.z)) << 42);+ const float d = glm::distance(p, centre);+ bool found = false;+ const uint32_t h = cells.slot(key, found);+ if (!found) {+ cells.stamps[h] = cells.stamp;+ cells.keys[h] = key;+ cells.reps[h] = uint16_t(l);+ cells.dists[h] = d;+ } else if (d < cells.dists[h]) {+ cells.reps[h] = uint16_t(l);+ cells.dists[h] = d;+ }+ cellOfVertex[l] = h;+ }+ float error = 0.0f;+ for (uint32_t l = 0; l < nl; ++l) {+ rep[l] = pinned[l] ? uint16_t(l) : cells.reps[cellOfVertex[l]];+ if (rep[l] != l) error = std::max(error, glm::distance(pos(l), pos(rep[l])));+ }+ const size_t at = out.size();+ for (uint32_t i = 0; i < n; ++i) {+ if (hidden && mesh.hidden[order.triangle(c, i)]) continue;+ const uint16_t* t = local.data() + size_t(i) * 3;+ const uint16_t a = rep[t[0]], b = rep[t[1]], d = rep[t[2]];+ if (a == b || b == d || a == d) continue;+ out.insert(out.end(), {a, b, d});+ }+ const size_t tris = (out.size() - at) / 3;+ if (tris * 10 > previous * 7 || out.size() > maxIndices) { // no real gain (the seams), or no room+ out.resize(at);+ if (lod.levels == 0 && tris * 10 > previous * 7 && cell < span) continue; // (the first grid too fine: coarser)+ break;+ }+ for (size_t k = at; k < out.size(); k += 3) {+ const glm::vec3 p0 = pos(out[k]);+ const glm::vec3 cr = glm::cross(pos(out[k + 1]) - p0, pos(out[k + 2]) - p0);+ const float l2 = glm::dot(cr, cr);+ if (l2 > 0.0f && std::isfinite(l2)) sum += cr / std::sqrt(l2);+ }+ lod.first[lod.levels] = uint32_t(at);+ lod.count[lod.levels] = uint32_t(out.size() - at);+ lod.error[lod.levels] = std::max(error, lod.levels > 0 ? lod.error[lod.levels - 1] : 0.0f);+ ++lod.levels;+ previous = tris;+ if (tris < 8 || cell > span) break;+ }+ if (lod.levels == 0) return false;+ // One normal cone for every level (whichever is drawn, culling stays safe).+ const float sl = glm::length(sum);+ float minDot = 1.0f;+ bool faces = false;+ for (size_t k = 0; k < out.size() && sl > 1e-6f; k += 3) {+ const glm::vec3 p0 = pos(out[k]);+ const glm::vec3 cr = glm::cross(pos(out[k + 1]) - p0, pos(out[k + 2]) - p0);+ const float l2 = glm::dot(cr, cr);+ if (!(l2 > 0.0f) || !std::isfinite(l2)) continue;+ minDot = std::min(minDot, glm::dot(cr / std::sqrt(l2), sum / sl));+ faces = true;+ }+ bounds.axis = glm::vec3(0.0f, 0.0f, 1.0f);+ bounds.coneAngle = -1.0f;+ if (faces && minDot > 0.0f) {+ bounds.axis = sum / sl;+ bounds.coneAngle = std::acos(std::min(minDot, 1.0f));+ }+ return true;+}+bool closedOriented(const Mesh& mesh) {const size_t nv = mesh.vertexCount(), nt = mesh.triangleCount();if (nt == 0) return false;diff --git a/src/render/Clusters.h b/src/render/Clusters.hindex db16a826..59a675eb 100644--- a/src/render/Clusters.h+++ b/src/render/Clusters.h@@ -73,6 +73,22 @@ ClusterBounds clusterBounds(const Mesh& mesh, const UploadOrder& order, uint32_tbool clusterProxy(const Mesh& mesh, const UploadOrder& order, uint32_t c, size_t maxTriangles, std::vector<uint16_t>& out,ClusterBounds& bounds);+// A cluster's coarse levels (docs/design/micro-coarse-lod.md: Clark 1976, Rossignac-Borrel 1993): versions of it on+// grids twice as coarse each time, built as clusterProxy builds one (vertices snapped to one per cell, seam vertices+// kept, so any mix of levels between neighbours stays closed), each with its error: how far its farthest vertex+// moved. The renderer picks per cluster the coarsest level whose error stays under a pixel or so on screen.+struct ClusterLod {+ static constexpr int kMaxLevels = 6;+ int levels = 0;+ uint32_t first[kMaxLevels] = {}, count[kMaxLevels] = {}; // in the chain's index list (indices, not triangles)+ float error[kMaxLevels] = {}; // world units; grows with the level+};+// The levels of cluster c, at most maxIndices indices in all, as indices into the cluster's vertex range. Stops+// when a level would keep more than 70% of the one before (the seams hold the rest) or fewer than 8 triangles.+// `bounds` gets a normal cone holding every level's triangles. False (and no levels): not even the first fits.+bool clusterLodChain(const Mesh& mesh, const UploadOrder& order, uint32_t c, size_t maxIndices, std::vector<uint16_t>& out,+ ClusterLod& lod, ClusterBounds& bounds);+// 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// back face then lies behind a front face from outside. (Strictly: where no part of the surface is turneddiff --git a/src/render/Renderer.cpp b/src/render/Renderer.cppindex 98bca81a..644fc589 100644--- a/src/render/Renderer.cpp+++ b/src/render/Renderer.cpp@@ -24,6 +24,8 @@#include <thread>#include <unordered_map>#include <cstdlib>+#include <cstdio>+#include <string>#include <limits>#include <vector>@@ -1205,7 +1207,7 @@ size_t Renderer::gpuBytes() const {for (const MeshSlot& s : slots_) {for (size_t b : s.bytes) total += b;total += s.patchBytes;- if (s.proxyAllocated) total += (s.order.triangleCount() / 4) * 3 * sizeof(uint16_t);+ if (s.proxyAllocated) total += (s.order.triangleCount() / proxyShare()) * 3 * sizeof(uint16_t);if (s.paintTexture) total += size_t(s.textureW) * size_t(s.textureH) * 4 * 4 / 3; // with mipmapstotal += size_t(std::popcount(s.pbrPlanes)) * size_t(s.textureW) * size_t(s.textureH) * 4 * 4 / 3;if (s.micro) total += s.micro->gpuBytes();@@ -1815,6 +1817,7 @@ void Renderer::buildProxies(MeshSlot& s, const Mesh& mesh) {const size_t nc = s.order.clusters().size();s.proxyStale.resize(nc, 1);s.proxyCount.resize(nc, 0);+ s.proxyLod.resize(nc);s.proxyBounds.resize(nc);cullScratch_.clear();for (uint32_t c = 0; c < nc; ++c) {@@ -1827,7 +1830,7 @@ void Renderer::buildProxies(MeshSlot& s, const Mesh& mesh) {if (cullScratch_.empty()) return;if (!s.proxyAllocated) {gl::BindVertexArray(s.proxyVao);- gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr((s.order.triangleCount() / 4) * 3 * sizeof(uint16_t)), nullptr, GL_STATIC_DRAW);+ gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr((s.order.triangleCount() / proxyShare()) * 3 * sizeof(uint16_t)), nullptr, GL_STATIC_DRAW);gl::BindVertexArray(0);s.proxyAllocated = true;}@@ -1835,7 +1838,8 @@ void Renderer::buildProxies(MeshSlot& s, const Mesh& mesh) {// moving frame stalled the view (180-300 ms at 33M). Stale clusters draw in full detail until theirs is built.// Batches are sized from the measured cost per cluster: a fixed 1024 took 157 ms a frame on two slow cores.// Still frames (proxyPrebuild_) get less, as nothing waits for them.- const double budgetMs = proxyUsed_ ? 8.0 : 4.0;+ // (SF_COARSE_LOD=1, the spike: all of it at once, when the mesh is first drawn, timed)+ const double budgetMs = coarseLod_ ? 1e9 : proxyUsed_ ? 8.0 : 4.0;constexpr size_t kProxyBatchMin = 16, kProxyBatchMax = 1024; // clusters per parallel batchconst auto start = std::chrono::steady_clock::now();auto elapsedMs = [&] { return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count(); };@@ -1855,7 +1859,14 @@ void Renderer::buildProxies(MeshSlot& s, const Mesh& mesh) {for (size_t i = i0; i < i1; ++i) {const uint32_t c = cullScratch_[at + i];ClusterBounds b = s.bounds[c];- if (!clusterProxy(mesh, s.order, c, s.order.clusterTriangles(c) / 4, built[i], b)) built[i].clear();+ ClusterLod& lod = s.proxyLod[c];+ if (coarseLod_) { // (the spike: every level)+ if (!clusterLodChain(mesh, s.order, c, size_t(s.order.clusterTriangles(c) / 2) * 3, built[i], lod, b)) built[i].clear();+ } else { // the motion proxy alone, as one level+ lod = ClusterLod();+ if (!clusterProxy(mesh, s.order, c, s.order.clusterTriangles(c) / 4, built[i], b)) built[i].clear();+ else lod.levels = 1, lod.count[0] = uint32_t(built[i].size());+ }s.proxyBounds[c] = b;}}, 1, 2);@@ -1864,7 +1875,7 @@ void Renderer::buildProxies(MeshSlot& s, const Mesh& mesh) {s.proxyCount[c] = uint32_t(built[i].size());s.proxyStale[c] = 0;if (!built[i].empty())- gl::BufferSubData(GL_ELEMENT_ARRAY_BUFFER, GLintptr(size_t(s.order.firstTriangle(c) / 4) * 3 * sizeof(uint16_t)),+ gl::BufferSubData(GL_ELEMENT_ARRAY_BUFFER, GLintptr(size_t(s.order.firstTriangle(c) / proxyShare()) * 3 * sizeof(uint16_t)),GLsizeiptr(built[i].size() * sizeof(uint16_t)), built[i].data());}at += n;@@ -1872,6 +1883,12 @@ void Renderer::buildProxies(MeshSlot& s, const Mesh& mesh) {proxyMsPerCluster_ = proxyMsPerCluster_ > 0.0 ? 0.7 * proxyMsPerCluster_ + 0.3 * perCluster : perCluster;}gl::BindVertexArray(0);+ if (coarseLod_) {+ size_t indices = 0;+ for (uint32_t c : cullScratch_) indices += s.proxyCount[c];+ std::fprintf(stderr, "coarse lod: %zu clusters built in %.0f ms (%zu triangles in all levels, %.0f MB)\n", cullScratch_.size(),+ elapsedMs(), indices / 3, double(indices * sizeof(uint16_t)) / 1048576.0);+ }}// ---------------------------------------------------------------------------@@ -2279,6 +2296,7 @@ void Renderer::sync(MeshSlot& s, Mesh& mesh, const NormalMapView* normalMap, booif (full) {s.proxyAllocated = false; // sized for the old meshs.proxyCount.clear();+ s.proxyLod.clear();// (closedOriented also accepts unwelded seams, the same point twice, which the layout's check doesn't.)s.closed = s.order.closed() || closedOriented(mesh);uploadFaces(s, mesh, wantUvs, indicesDone);@@ -2307,7 +2325,8 @@ void Renderer::sync(MeshSlot& s, Mesh& mesh, const NormalMapView* normalMap, boo// Small meshes draw in full while the view moves too (their proxy would save little).constexpr size_t kProxyMinTriangles = size_t(1) << 18;if (syncLog) lapMs(lap);- if ((proxyUsed_ || (proxyPrebuild_ && s.proxyAllocated)) && !s.outOfMemory && s.drawnTriangles >= kProxyMinTriangles)+ const bool overBudget = coarseLod_ && lodBudget_ > 0 && s.drawnTriangles > lodBudget_;+ if ((proxyUsed_ || overBudget || (proxyPrebuild_ && s.proxyAllocated)) && !s.outOfMemory && s.drawnTriangles >= kProxyMinTriangles)buildProxies(s, mesh);if (syncLog) proxyMs = lapMs(lap);syncTexture(s, mesh, pbr);@@ -2855,6 +2874,9 @@ void Renderer::endCapture(std::vector<uint8_t>& rgba) {void Renderer::draw(const Camera& camera, int targetWidth, int targetHeight, const RenderSettings& settings,const Viewport& viewport) {+ static const bool coarseOn = std::getenv("SF_COARSE_LOD") && std::string(std::getenv("SF_COARSE_LOD")) == "1";+ coarseLod_ = coarseOn;+ if (!settings.motionProxy) lodBudget_ = triangleBudget(settings); // (sync builds the levels of meshes over it)// SF_FRAME_LOG=ms (App.cpp): a draw slower than that says where its time went (lit spheres, environment, Parts).static const double drawLogMs = std::getenv("SF_FRAME_LOG") ? std::atof(std::getenv("SF_FRAME_LOG")) : -1.0;const auto drawStart = std::chrono::steady_clock::now();@@ -3084,12 +3106,28 @@ void Renderer::draw(const Camera& camera, int targetWidth, int targetHeight, con// The clusters of `s` inside the view, less those facing away when that can't open a hole: the mesh is closed// and wound consistently (closedOriented) with nothing hidden, the eye is outside its bounds, and no cluster// reaches into the near plane's slab (a cut-open front would show the back faces behind it).-void Renderer::cull(const MeshSlot& s, const CullView& frame, bool proxy) {+void Renderer::cull(const MeshSlot& s, const CullView& frame, bool proxy, float lodPx, size_t budget) {drawClusters_.clear();proxyClusters_.clear();- proxy = proxy && s.proxyCount.size() == s.drawCount.size() && s.proxyBounds.size() == s.drawCount.size();+ proxyLevel_.clear();+ proxy = proxy && s.proxyCount.size() == s.drawCount.size() && s.proxyBounds.size() == s.drawCount.size() &&+ s.proxyLod.size() == s.drawCount.size();CullView v = frame;const glm::vec3 e = v.eye;+ // Coarse levels (lodPx > 0): the visible clusters first, then the threshold, then each one's level.+ lodScratch_.clear();+ auto keep = [&](uint32_t c) {+ const bool ready = proxy && s.proxyCount[c] > 0 && !s.proxyStale[c];+ const bool fullShows = !facingAway(v, s.bounds[c]);+ const bool coarseShows = ready && !facingAway(v, s.proxyBounds[c]);+ if (!ready) {+ if (fullShows) drawClusters_.push_back(c);+ } else if (lodPx <= 0.0f) { // the motion proxy+ if (coarseShows) proxyClusters_.push_back(c), proxyLevel_.push_back(0);+ } else if (fullShows || coarseShows) {+ lodScratch_.push_back({c, 0.0f, fullShows, coarseShows});+ }+ };// Backface culling on (#68): back faces go on any mesh from any view, the GPU skipping each one and whole// clusters facing away going first (in perspective: an orthographic view has no eye to judge them from).if (forceBackfaces_) {@@ -3098,12 +3136,9 @@ void Renderer::cull(const MeshSlot& s, const CullView& frame, bool proxy) {const size_t n = std::min(s.bounds.size(), s.drawCount.size());for (uint32_t c = 0; c < n; ++c) {if (s.drawCount[c] == 0 || !insideFrustum(v, s.bounds[c])) continue;- if (proxy && s.proxyCount[c] > 0 && !s.proxyStale[c]) {- if (!facingAway(v, s.proxyBounds[c])) proxyClusters_.push_back(c);- } else if (!facingAway(v, s.bounds[c])) {- drawClusters_.push_back(c);- }+ keep(c);}+ pickLevels(s, v, lodPx, budget);return;}v.backfaces = !keepBackfaces_ && !v.ortho && s.closed && s.volume > 0.0 && !s.anyHidden && s.box.valid() &&@@ -3132,10 +3167,56 @@ void Renderer::cull(const MeshSlot& s, const CullView& frame, bool proxy) {if (s.drawCount[c] == 0) continue;const ClusterBounds& b = s.bounds[c];if (!insideFrustum(v, b)) continue;- if (proxy && s.proxyCount[c] > 0 && !s.proxyStale[c]) {- if (!facingAway(v, s.proxyBounds[c])) proxyClusters_.push_back(c);- } else if (!facingAway(v, b)) {- drawClusters_.push_back(c);+ keep(c);+ }+ pickLevels(s, v, lodPx, budget);+}++// Clark 1976 / QSplat: per cluster the coarsest level whose error, projected at the cluster's nearest point, stays+// under `px` pixels; `px` is raised (x1.5) until the triangles drawn fit `budget`, and when everything fits in+// full detail, everything is drawn in full.+void Renderer::pickLevels(const MeshSlot& s, const CullView& v, float px, size_t budget) {+ if (lodScratch_.empty()) return;+ // Pixels per world unit at distance 1 (perspective), or anywhere (orthographic).+ const bool ortho = frameProj_[3][3] == 1.0f;+ const float unit = 0.5f * frameViewport_.w * frameProj_[1][1];+ size_t fixed = 0, full = 0;+ for (uint32_t c : drawClusters_) fixed += size_t(s.drawCount[c]) / 3;+ for (LodPick& k : lodScratch_) {+ const ClusterBounds& b = s.bounds[k.c];+ const float d = std::max(glm::dot(b.center - v.eye, v.forward) - b.radius, std::max(v.nearDistance, 1e-6f));+ k.scale = ortho ? unit : unit / d;+ if (k.fullShows) full += size_t(s.drawCount[k.c]) / 3;+ }+ auto level = [&](const LodPick& k, float t) {+ const ClusterLod& lod = s.proxyLod[k.c];+ int pick = -1;+ while (pick + 1 < lod.levels && lod.error[pick + 1] * k.scale <= t) ++pick;+ return pick;+ };+ float t = px;+ if (budget == 0 || fixed + full > budget) {+ for (int round = 0; round < 24; ++round, t *= 1.5f) {+ size_t total = fixed;+ for (const LodPick& k : lodScratch_) {+ const int l = level(k, t);+ if (l < 0) total += k.fullShows ? size_t(s.drawCount[k.c]) / 3 : 0;+ else total += k.coarseShows ? s.proxyLod[k.c].count[l] / 3 : 0;+ }+ if (budget == 0 || total <= budget) break;+ }+ lodPx_ = t;+ } else {+ t = 0.0f; // (all of it fits: full detail)+ lodPx_ = 0.0f;+ }+ for (const LodPick& k : lodScratch_) {+ const int l = t > 0.0f ? level(k, t) : -1;+ if (l < 0) {+ if (k.fullShows) drawClusters_.push_back(k.c);+ } else if (k.coarseShows) {+ proxyClusters_.push_back(k.c);+ proxyLevel_.push_back(uint8_t(l));}}}@@ -3149,7 +3230,7 @@ void Renderer::drawClusters(const MeshSlot& s, const std::vector<uint32_t>& clusdrawBases_.clear();const auto layout = s.order.clusters();size_t indices = 0;- for (uint32_t c : clusters) {+ for (const uint32_t& c : clusters) {GLsizei count = 0;size_t first = 0;switch (part) {@@ -3161,11 +3242,14 @@ void Renderer::drawClusters(const MeshSlot& s, const std::vector<uint32_t>& cluscount = GLsizei(s.lineCount[c]);first = s.lineFirst[c];break;- case DrawPart::Proxy:- count = GLsizei(s.proxyCount[c]);- first = size_t(s.order.firstTriangle(c) / 4) * 3;+ case DrawPart::Proxy: { // (clusters is proxyClusters_: its level in proxyLevel_)+ const ClusterLod& lod = s.proxyLod[c];+ const int l = std::min<int>(proxyLevel_[size_t(&c - clusters.data())], lod.levels - 1);+ count = GLsizei(lod.count[l]);+ first = size_t(s.order.firstTriangle(c) / proxyShare()) * 3 + lod.first[l];break;}+ }drawCounts_.push_back(count);drawOffsets_.push_back(reinterpret_cast<const void*>(first * sizeof(uint16_t)));drawBases_.push_back(GLint(layout[c].firstVertex));@@ -3193,6 +3277,14 @@ static glm::vec3 materialTintShift(const RenderSettings& settings, bool hasColorreturn settings.materialTint - glm::vec3(1.0f);}+// The triangles a frame may draw: the tier's budget, lowered by the governed one (core/HardwareProfile.h: the frame+// 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 uint64_t governed = renderTriangleBudget(); governed > 0) full = std::min(full, size_t(governed));+ return settings.motionProxy ? full / 2 : full;+}+void Renderer::drawMicro(const MeshSlot& s, bool active, bool flat, const RenderSettings& settings) {const MeshProgram* p = meshProgram(kMicro | (flat ? kFlat : 0) | (settings.pbr() && envTexture_ ? kPbr : 0));if (!p) return;@@ -3218,10 +3310,7 @@ void Renderer::drawMicro(const MeshSlot& s, bool active, bool flat, const Rendergl::Uniform1i(p->twoSided, 1);// Moving (Fast Navigation): a coarser target and half the budget, so orbiting stays smooth.const bool moving = settings.motionProxy;- // The tier's budget, lowered by the governed one (core/HardwareProfile.h: the frame governor, SF_HW_SIMULATE=floor).- size_t full = settings.renderTriangleBudget ? settings.renderTriangleBudget : size_t(currentTierConfig().activeTriangleBudget);- if (const uint64_t governed = renderTriangleBudget(); governed > 0) full = std::min(full, size_t(governed));- const size_t budget = moving ? full / 2 : full;+ const size_t budget = triangleBudget(settings);const float target = settings.microTargetPx * (moving ? 2.0f : 1.0f);// (the budget is shared by the micro Parts on screen: each gets it whole; one is the usual case)const_cast<MeshSlot&>(s).microDrawn = s.micro->draw(p->id, frameCull_, frameProj_, frameViewport_, budget, target);@@ -3323,7 +3412,13 @@ void Renderer::drawSlot(const MeshSlot& s, bool active, bool flat, const RenderS// While the view moves, the motion proxy where it is built: not with per-triangle data, which follows the// full triangles, nor under the wireframe, whose edges would sink into it.const bool perTriangle = features & (kPrim | kTextured | kNormalMap); // (not kFlat: no per-triangle data)- cull(s, frameCull_, settings.motionProxy && !perTriangle && !(active && settings.wireframe));+ const bool coarseAllowed = !perTriangle && !(active && settings.wireframe);+ // Coarse levels (coarseLod_, SF_COARSE_LOD=1): a mesh over the budget, or any big one while the view moves.+ const size_t budget = triangleBudget(settings);+ if (coarseLod_ && coarseAllowed && (settings.motionProxy || s.drawnTriangles > budget))+ cull(s, frameCull_, true, 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.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 0b031420..e79c4a9a 100644--- a/src/render/Renderer.h+++ b/src/render/Renderer.h@@ -350,9 +350,11 @@ private:std::vector<uint32_t> primBase; // per cluster: its first drawn trianglestd::vector<uint32_t> lineFirst, lineCount; // per cluster: its edges in lineBuffer (in indices)bool linesValid = false;- // Motion proxy (clusterProxy): per cluster up to a quarter of its triangles, at (firstTriangle / 4) * 3.+ // Coarse levels (clusterLodChain; the first is the motion proxy): per cluster up to half of its triangles+ // in all, at (firstTriangle / 2) * 3.GLuint proxyVao = 0, proxyBuffer = 0;- std::vector<uint32_t> proxyCount; // indices; 0: none (the cluster draws in full)+ std::vector<uint32_t> proxyCount; // indices, every level; 0: none (the cluster draws in full)+ std::vector<ClusterLod> proxyLod; // the levels in that rangestd::vector<uint8_t> proxyStale; // to rebuild before usestd::vector<ClusterBounds> proxyBounds; // the proxy's normal conebool proxyAllocated = false;@@ -409,6 +411,8 @@ 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+ size_t lodBudget_ = 0; // the last draw's triangle budget: sync builds the coarse levels of meshes over it+ float lodPx_ = 0.0f; // the last coarse frame's error threshold (pixels), so the next starts near it// The ghost (setGhost), drawn on the slot ghostId_.GhostStroke ghost_;uint32_t ghostId_ = 0;@@ -453,14 +457,31 @@ private:int envIndex_ = -1, envFailedIndex_ = -1;SH9 envSh_;glm::mat3 frameViewToEnv_{1.0f};- // The clusters of `s` to draw this frame: in full (drawClusters_), and with `proxy` as their motion proxy- // where it is built (proxyClusters_).- void cull(const MeshSlot& s, const CullView& view, bool proxy = false);+ // The clusters of `s` to draw this frame: in full (drawClusters_), and where built and `proxy`, at a coarse+ // level (proxyClusters_, the level in proxyLevel_): the motion proxy (lodPx <= 0), or per cluster the coarsest+ // level whose error stays under lodPx pixels, raised until at most `budget` triangles are drawn.+ void cull(const MeshSlot& s, const CullView& view, bool proxy = false, float lodPx = 0.0f, size_t budget = 0);void drawSlot(const MeshSlot& s, bool active, bool flat, const RenderSettings& settings);enum class DrawPart { Triangles, Lines, Proxy };void drawPatches(const MeshSlot& s, GLenum mode, DrawPart part, GLint primBaseLocation);void drawClusters(const MeshSlot& s, const std::vector<uint32_t>& clusters, GLenum mode, DrawPart part, GLint primBaseLocation);std::vector<uint32_t> proxyClusters_;+ std::vector<uint8_t> proxyLevel_;+ struct LodPick {+ uint32_t c;+ float scale; // pixels per world unit at the cluster's nearest point+ bool fullShows, coarseShows;+ };+ std::vector<LodPick> lodScratch_;+ void pickLevels(const MeshSlot& s, const CullView& v, float px, size_t budget);+ size_t triangleBudget(const RenderSettings& settings) const;+ // Spike (SF_COARSE_LOD=1, off by default; docs/design/micro-coarse-lod.md): plain meshes over the triangle budget+ // draw their clusters' coarse levels (render/Clusters.h: ClusterLod), at rest too: the coarsest whose error stays+ // under kCoarseLodPx on screen, raised until the budget holds. Off: the motion proxy while moving, as before.+ bool coarseLod_ = false;+ static constexpr float kCoarseLodPx = 0.75f;+ // A cluster's part of the proxy buffer: 1/proxyShare of its triangles, at (firstTriangle / proxyShare) * 3.+ uint32_t proxyShare() const { return coarseLod_ ? 2 : 4; }std::vector<GLsizei> drawCounts_;std::vector<const void*> drawOffsets_;std::vector<GLint> drawBases_;diff --git a/tests/test_render_clusters.cpp b/tests/test_render_clusters.cppindex 9c7161e5..7c315caf 100644--- a/tests/test_render_clusters.cpp+++ b/tests/test_render_clusters.cpp@@ -350,3 +350,71 @@ TEST(motion_proxy_is_closed_and_light) {ClusterBounds b;CHECK(clusterProxy(h, order, 0, order.clusterTriangles(0), proxy, b) && proxy.empty());}++TEST(coarse_lod_chain_closed_at_any_mix_of_levels) {+ // Each cluster's coarse levels (clusterLodChain) keep its seam vertices: whatever level each cluster draws,+ // full detail included, a closed mesh stays closed (no cracks). Each level is lighter than the one before and+ // its error no smaller; the coarsest levels together are a small fraction of the mesh.+ Mesh m = makeBenchSphere(1000000);+ 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();+ UploadOrder order;+ order.build(m);+ const uint32_t nc = uint32_t(order.clusters().size());+ std::vector<std::vector<uint16_t>> chain(nc);+ std::vector<ClusterLod> lods(nc);+ std::vector<uint16_t> local;+ bool built = true, shrinking = true, inRange = true;+ size_t coarsest = 0, first = 0, levels = 0;+ for (uint32_t c = 0; c < nc; ++c) {+ ClusterBounds b = clusterBounds(m, order, c);+ const size_t cap = size_t(order.clusterTriangles(c) / 2) * 3;+ built = built && clusterLodChain(m, order, c, cap, chain[c], lods[c], b) && chain[c].size() <= cap;+ const ClusterLod& l = lods[c];+ if (l.levels == 0) continue;+ levels += size_t(l.levels);+ first += l.count[0] / 3;+ coarsest += l.count[l.levels - 1] / 3;+ shrinking = shrinking && l.count[0] / 3 < order.clusterTriangles(c);+ for (int k = 1; k < l.levels; ++k) shrinking = shrinking && l.count[k] < l.count[k - 1] && l.error[k] >= l.error[k - 1];+ for (uint16_t i : chain[c]) inRange = inRange && i < order.clusters()[c].vertexCount;+ }+ std::printf(" coarse levels: %zu clusters, %.1f levels each; first %zu, coarsest %zu of %zu triangles\n", size_t(nc),+ double(levels) / double(nc), first, coarsest, m.triangleCount());+ CHECK(built);+ CHECK(shrinking);+ CHECK(inRange);+ CHECK(coarsest * 8 < m.triangleCount());+ std::mt19937 rng(7);+ for (int round = 0; round < 4; ++round) {+ std::map<std::pair<uint32_t, uint32_t>, int> edges;+ for (uint32_t c = 0; c < nc; ++c) {+ const auto& cl = order.clusters()[c];+ const int pick = round == 0 ? -1 : int(rng() % uint32_t(lods[c].levels + 1)) - 1; // -1: full detail+ const uint16_t* idx = nullptr;+ size_t count = 0;+ if (pick < 0) {+ local.resize(size_t(order.clusterTriangles(c)) * 3);+ order.localTriangles(m, c, local.data());+ idx = local.data();+ count = local.size();+ } else {+ idx = chain[c].data() + lods[c].first[pick];+ count = lods[c].count[pick];+ }+ for (size_t i = 0; i < count; i += 3)+ for (int k = 0; k < 3; ++k) {+ const uint32_t a = order.fromGpu()[cl.firstVertex + idx[i + size_t(k)]];+ const uint32_t e = order.fromGpu()[cl.firstVertex + idx[i + size_t((k + 1) % 3)]];+ ++edges[{a, e}];+ --edges[{e, a}];+ }+ }+ bool closed = true;+ for (const auto& [e, n] : edges) closed = closed && n == 0;+ CHECK(closed);+ }+}