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.

Micro levels in the viewport: GPU-evaluated micro surface with a triangle budget

islandmed69e6acd71450
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 5af469bb..f9c1490a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -260,6 +260,7 @@ if(SCULPTFORGE_BUILD_APP)
src/render/Camera.cpp
src/render/Clusters.cpp
src/render/Renderer.cpp
+ src/render/MicroRenderer.cpp
)
target_link_libraries(sculptforge PRIVATE sculptforge_core sculptforge_ai sculptforge_phone imgui SDL3::SDL3)
target_include_directories(sculptforge PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/lucide)
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 20b9c572..eeda775f 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -13,6 +13,7 @@
#include <imgui_internal.h>
#include "ai/Generator3D.h"
+#include "core/Micro.h"
#include "core/EnginePresets.h"
#include "link/UnrealLink.h"
#include "core/BrushLibrary.h"
@@ -914,7 +915,7 @@ bool App::pick(float x, float y, RayHit& hit) const {
if (!doc_.activeSubtoolInfo().visible) return false; // you can't sculpt what you can't see
glm::vec3 origin, dir;
canvasRay(x, y, origin, dir);
- return doc_.bvh.raycast(doc_.mesh, origin, dir, hit);
+ return surfaceRaycast(doc_.mesh, doc_.bvh, origin, dir, hit); // (the micro surface on a micro level)
}
BrushType App::activeBrush() const {
diff --git a/src/core/Micro.cpp b/src/core/Micro.cpp
index 80c2e157..7ec3bddc 100644
--- a/src/core/Micro.cpp
+++ b/src/core/Micro.cpp
@@ -31,6 +31,11 @@ namespace sf {
// MicroMesh
// ---------------------------------------------------------------------------
+uint64_t MicroMesh::newSerial() {
+ static std::atomic<uint64_t> next{1};
+ return next++;
+}
+
size_t MicroMesh::microVertices() const {
size_t edges = size_t(baseTriangles) * 3 / 2;
if (edgeNeighbor.size() == size_t(baseTriangles) * 3) {
@@ -338,6 +343,7 @@ bool microDivide(Mesh& m, int level, std::string& error) {
// 1/4096 of a base edge per unit: +/-8 base edges of range, steps far below a micro edge (1/256 of one at
// level 4). Brushes widen the range when they need more (MicroStroke).
mm->step = std::max(avgEdge / 4096.0f, 1e-12f);
+ mm->serial = MicroMesh::newSerial();
mm->allDirty = true;
m.micro = std::move(mm);
m.topologyDirty = true; // the renderer draws it differently
@@ -385,6 +391,7 @@ bool microAttach(Mesh& m, int level, float step, std::vector<int16_t> disp, std:
for (float g : bulge) mm->bulgeMax = std::max(mm->bulgeMax, g);
for (uint16_t r : mm->triRange) mm->rangeMax = std::max(mm->rangeMax, r);
mm->ensureTopology(m);
+ mm->serial = MicroMesh::newSerial();
mm->allDirty = true;
m.micro = std::move(mm);
m.topologyDirty = true;
@@ -584,11 +591,11 @@ struct GridWork {
} // namespace
void MicroShader::shade(const Mesh& m, std::span<const uint32_t> dirty, bool all, std::vector<uint32_t>& written,
- const std::function<uint32_t*(uint32_t tri)>& out) {
+ const std::function<uint32_t*(uint32_t tri)>& out, const Prepare& prepare) {
written.clear();
if (!m.micro) return;
if (!all) {
- shadeSet(m, dirty, true, written, out);
+ shadeSet(m, dirty, true, written, out, prepare);
return;
}
// Everything: in runs of triangles (neighbours by index on levels made by Divide), each with the ring its
@@ -599,12 +606,12 @@ void MicroShader::shade(const Mesh& m, std::span<const uint32_t> dirty, bool all
for (uint32_t b = 0; b < nt; b += kRun) {
run.resize(std::min(kRun, nt - b));
for (uint32_t i = 0; i < run.size(); ++i) run[i] = b + i;
- shadeSet(m, run, false, written, out);
+ shadeSet(m, run, false, written, out, prepare);
}
}
void MicroShader::shadeSet(const Mesh& m, std::span<const uint32_t> dirty, bool grow, std::vector<uint32_t>& written,
- const std::function<uint32_t*(uint32_t tri)>& out) {
+ const std::function<uint32_t*(uint32_t tri)>& out, const Prepare& prepare) {
const MicroMesh& mm = *m.micro;
const uint32_t n = mm.n, S = mm.samples, nt = mm.baseTriangles;
if (mm.edgeNeighbor.size() != size_t(nt) * 3) return; // (ensureTopology first)
@@ -652,6 +659,7 @@ void MicroShader::shadeSet(const Mesh& m, std::span<const uint32_t> dirty, bool
vertexRing(ring_, ring2_, inR2, v2);
for (size_t i = 0; i < ring_.size(); ++i) slot_[ring_[i]] = uint32_t(i);
for (size_t i = 0; i < ring2_.size(); ++i) slot_[ring2_[i]] = uint32_t(ring_.size() + i);
+ if (prepare) prepare(ring_);
const size_t slots = ring_.size() + ring2_.size();
const size_t edgePoints = size_t(3) * n;
partial_.resize(slots * edgePoints * kPartialFloats);
diff --git a/src/core/Micro.h b/src/core/Micro.h
index 22968ce0..75da70c0 100644
--- a/src/core/Micro.h
+++ b/src/core/Micro.h
@@ -78,6 +78,10 @@ struct MicroMesh {
bool maskDirty = false; // the mask was added or removed (the renderer's shading changes everywhere)
bool rescaled = false; // `step` grew and every value was rescaled (same surface: the renderer re-sends the values only)
uint64_t revision = 0; // bumped by every edit
+ // Which level this is (new on Divide / load; kept by copies, which hold the same values): the renderer keeps
+ // its GPU copy while the serial stays.
+ uint64_t serial = 0;
+ static uint64_t newSerial();
size_t microTriangles() const { return size_t(baseTriangles) * n * n; }
size_t microVertices() const; // unique grid points (shared edges and corners counted once)
@@ -175,13 +179,15 @@ public:
// Recomputes what changes when base triangles `dirty` changed (all of them when `all`): the shading of those
// and of every base triangle sharing a vertex with one (whose shared edges and corners average with them).
// out(tri) gives where that triangle's `samples` values go (each written whole). `written` lists them.
+ // `prepare`, if given, sees the triangles about to be written (before any out() call), once per batch.
+ using Prepare = std::function<void(std::span<const uint32_t> tris)>;
void shade(const Mesh& m, std::span<const uint32_t> dirty, bool all, std::vector<uint32_t>& written,
- const std::function<uint32_t*(uint32_t tri)>& out);
+ const std::function<uint32_t*(uint32_t tri)>& out, const Prepare& prepare = {});
private:
// shade() for the triangles `seeds` (grown by the triangles sharing a vertex when `grow`); appends to `written`.
void shadeSet(const Mesh& m, std::span<const uint32_t> seeds, bool grow, std::vector<uint32_t>& written,
- const std::function<uint32_t*(uint32_t tri)>& out);
+ const std::function<uint32_t*(uint32_t tri)>& out, const Prepare& prepare);
std::vector<uint32_t> seed_, grown_;
std::vector<uint32_t> stamp_, slot_; // per base triangle: in a set of this call (stamp), its partials (slot)
std::vector<uint32_t> vstamp_; // per base vertex
diff --git a/src/core/PathStroke.cpp b/src/core/PathStroke.cpp
index de03b760..7d314c2a 100644
--- a/src/core/PathStroke.cpp
+++ b/src/core/PathStroke.cpp
@@ -1,5 +1,6 @@
// SculptForge - open source digital sculpting
// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Micro.h"
#include "core/PathStroke.h"
#include <algorithm>
@@ -127,7 +128,7 @@ int strokePath(Document& doc, const BrushRecipe* recipe, BrushType type, const P
};
auto project = [&](glm::vec3 p, RayHit& hit) {
const glm::vec3 origin = p - view * (glm::dot(p - box.center(), view) + diag);
- return doc.bvh.raycast(mesh, origin, view, hit);
+ return surfaceRaycast(mesh, doc.bvh, origin, view, hit);
};
DabParams base;
diff --git a/src/render/GL.h b/src/render/GL.h
index d10b24aa..2e1b9b42 100644
--- a/src/render/GL.h
+++ b/src/render/GL.h
@@ -100,6 +100,9 @@ constexpr GLenum GL_UNSIGNED_SHORT = 0x1403;
constexpr GLenum GL_CULL_FACE = 0x0B44;
constexpr GLenum GL_R16UI = 0x8234;
constexpr GLenum GL_RED_INTEGER = 0x8D94;
+constexpr GLenum GL_R16I = 0x8233;
+constexpr GLenum GL_RGBA32UI = 0x8D70;
+constexpr GLbitfield GL_MAP_INVALIDATE_RANGE_BIT = 0x0004;
constexpr GLbitfield GL_DEPTH_BUFFER_BIT = 0x0100;
constexpr GLbitfield GL_COLOR_BUFFER_BIT = 0x4000;
@@ -171,9 +174,11 @@ constexpr GLbitfield GL_COLOR_BUFFER_BIT = 0x4000;
X(void, VertexAttribIPointer, GLuint, GLint, GLenum, GLsizei, const void*) \
X(void, VertexAttribDivisor, GLuint, GLuint) \
X(void, DrawArraysInstanced, GLenum, GLint, GLsizei, GLsizei) \
+ X(void, DrawElementsInstanced, GLenum, GLsizei, GLenum, const void*, GLsizei) \
X(void, ActiveTexture, GLenum) \
X(void, GetIntegerv, GLenum, GLint*) \
X(void, Uniform1i, GLint, GLint) \
+ X(void, Uniform1iv, GLint, GLsizei, const GLint*) \
X(void, Uniform1f, GLint, GLfloat) \
X(void, Uniform2f, GLint, GLfloat, GLfloat) \
X(void, DisableVertexAttribArray, GLuint) \
diff --git a/src/render/MicroRenderer.cpp b/src/render/MicroRenderer.cpp
new file mode 100644
index 00000000..2f020f1d
--- /dev/null
+++ b/src/render/MicroRenderer.cpp
@@ -0,0 +1,646 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "render/MicroRenderer.h"
+
+#include "core/ThreadPool.h"
+
+#include <glm/gtc/type_ptr.hpp>
+
+#include <algorithm>
+#include <bit>
+#include <cmath>
+#include <cstring>
+
+namespace sf {
+
+namespace {
+
+constexpr GLenum kUnitTris = 0x84C8, kUnitBase = 0x84C9, kUnitDisp = 0x84CA, kUnitLevels = 0x84CB, kUnitShade = 0x84CC;
+constexpr uint32_t kChunkTexels = 1u << 26;
+constexpr uint32_t kNoCluster = 0xFFFFFFFFu;
+
+// Evaluates the micro surface exactly as MicroTriangle::evalWeights (corners in ascending vertex order), so
+// both triangles of a shared edge compute bit-identical points there.
+const char* kMicroVS = R"(
+layout(location = 0) in uvec2 aIJ; // the patch's grid point at uLevel
+uniform mat4 uView;
+uniform mat4 uProj;
+uniform usamplerBuffer uTris; // per slot: (corner vertices, -), (cluster across each edge, -)
+uniform samplerBuffer uBase; // per base vertex: position, normal
+uniform isamplerBuffer uDisp; // this chunk's displacement grids
+uniform usamplerBuffer uLevels; // per cluster: the level it draws
+uniform int uSlotBase, uChunkSlot, uLevel, uN, uSamples;
+// > 0: a plain (not instanced) draw with this many corners per base triangle, each corner's grid point packed
+// i | j << 16 in uCorners (small patches: instancing a few triangles at a time costs more than it saves)
+uniform int uUnrolled;
+uniform int uCorners[48];
+uniform float uStep;
+flat out int vSlot;
+out vec2 vIJ;
+#ifdef FLAT
+out vec3 vViewPos;
+#endif
+vec3 P[3];
+vec3 Nn[3];
+int ord[3];
+int localSlot;
+int sampleIndex(int i, int j) { return j * (uN + 1) - (j * (j - 1)) / 2 + i; }
+vec3 microPos(int I, int J) {
+ float inv = 1.0 / float(uN);
+ float wc[3] = float[3](float(uN - I - J) * inv, float(I) * inv, float(J) * inv);
+ float w0 = wc[ord[0]], w1 = wc[ord[1]], w2 = wc[ord[2]];
+ vec3 f = P[0] * w0;
+ f += P[1] * w1;
+ f += P[2] * w2;
+ vec3 nn = Nn[0] * w0;
+ nn += Nn[1] * w1;
+ nn += Nn[2] * w2;
+ vec3 pull = Nn[0] * (w0 * dot(f - P[0], Nn[0]));
+ pull += Nn[1] * (w1 * dot(f - P[1], Nn[1]));
+ pull += Nn[2] * (w2 * dot(f - P[2], Nn[2]));
+ vec3 s = f - pull * 0.75;
+ float len = length(nn);
+ vec3 n = len > 1e-20 ? nn / len : vec3(0.0, 0.0, 1.0);
+ float d = float(texelFetch(uDisp, localSlot * uSamples + sampleIndex(I, J)).r) * uStep;
+ return s + n * d;
+}
+ivec2 edgePoint(int e, int k, int m) {
+ if (e == 0) return ivec2(k, 0);
+ if (e == 1) return ivec2(m - k, k);
+ return ivec2(0, m - k);
+}
+void main() {
+ int instance = gl_InstanceID;
+ uvec2 ij = aIJ;
+ if (uUnrolled > 0) {
+ instance = gl_VertexID / uUnrolled;
+ int c = uCorners[gl_VertexID - instance * uUnrolled];
+ ij = uvec2(uint(c & 0xFFFF), uint(c >> 16));
+ }
+ int slot = uSlotBase + instance;
+ localSlot = slot - uChunkSlot;
+ vSlot = localSlot;
+ uvec4 tv = texelFetch(uTris, slot * 2);
+ uvec4 nb = texelFetch(uTris, slot * 2 + 1);
+ uint v[3] = uint[3](tv.x, tv.y, tv.z);
+ ord[0] = 0; ord[1] = 1; ord[2] = 2;
+ if (v[ord[0]] > v[ord[1]]) { int t = ord[0]; ord[0] = ord[1]; ord[1] = t; }
+ if (v[ord[1]] > v[ord[2]]) { int t = ord[1]; ord[1] = ord[2]; ord[2] = t; }
+ if (v[ord[0]] > v[ord[1]]) { int t = ord[0]; ord[0] = ord[1]; ord[1] = t; }
+ for (int k = 0; k < 3; ++k) {
+ int vi = int(v[ord[k]]);
+ P[k] = texelFetch(uBase, vi * 2).xyz;
+ Nn[k] = texelFetch(uBase, vi * 2 + 1).xyz;
+ }
+ int m = 1 << uLevel, sc = uN >> uLevel;
+ int i = int(ij.x), j = int(ij.y);
+ int edge = -1, k = 0;
+ if (j == 0 && i > 0 && i < m) { edge = 0; k = i; }
+ else if (i + j == m && j > 0 && j < m) { edge = 1; k = j; }
+ else if (i == 0 && j > 0 && j < m) { edge = 2; k = m - j; }
+ vec3 pos;
+ int elevel = uLevel;
+ if (edge >= 0) {
+ uint c = edge == 0 ? nb.x : edge == 1 ? nb.y : nb.z;
+ if (c != 0xFFFFFFFFu) elevel = min(uLevel, int(texelFetch(uLevels, int(c)).r));
+ }
+ int stepE = 1 << (uLevel - elevel);
+ int r = k % stepE;
+ if (edge >= 0 && r != 0) {
+ ivec2 a = edgePoint(edge, k - r, m) * sc, b = edgePoint(edge, k - r + stepE, m) * sc;
+ pos = mix(microPos(a.x, a.y), microPos(b.x, b.y), float(r) / float(stepE));
+ } else {
+ pos = microPos(i * sc, j * sc);
+ }
+ vIJ = vec2(float(i * sc), float(j * sc));
+ vec4 p = uView * vec4(pos, 1.0);
+#ifdef FLAT
+ vViewPos = p.xyz;
+#endif
+ gl_Position = uProj * p;
+}
+)";
+
+uint32_t spread10(uint32_t x) {
+ x &= 0x3FF;
+ x = (x | (x << 16)) & 0x030000FF;
+ x = (x | (x << 8)) & 0x0300F00F;
+ x = (x | (x << 4)) & 0x030C30C3;
+ x = (x | (x << 2)) & 0x09249249;
+ return x;
+}
+
+} // namespace
+
+const char* microVertexShaderSource() { return kMicroVS; }
+
+MicroRenderer::~MicroRenderer() { release(); }
+
+void MicroRenderer::release() {
+ for (Chunk& c : chunks_) {
+ gl::DeleteBuffers(1, &c.disp);
+ gl::DeleteBuffers(1, &c.shade);
+ gl::DeleteTextures(1, &c.dispTex);
+ gl::DeleteTextures(1, &c.shadeTex);
+ }
+ chunks_.clear();
+ for (GLuint* b : {&triData_, &baseData_, &levelData_})
+ if (*b) gl::DeleteBuffers(1, b), *b = 0;
+ for (GLuint* t : {&triTex_, &baseTex_, &levelTex_})
+ if (*t) gl::DeleteTextures(1, t), *t = 0;
+ for (Patch& p : patches_) {
+ if (p.vao) gl::DeleteVertexArrays(1, &p.vao);
+ if (p.vbo) gl::DeleteBuffers(1, &p.vbo);
+ if (p.ibo) gl::DeleteBuffers(1, &p.ibo);
+ }
+ patches_.clear();
+ if (emptyVao_) gl::DeleteVertexArrays(1, &emptyVao_), emptyVao_ = 0;
+ serial_ = 0;
+ bytes_ = 0;
+}
+
+size_t MicroRenderer::gpuBytes() const { return bytes_; }
+
+void MicroRenderer::ensurePatches(int maxLevel) {
+ while (int(patches_.size()) <= maxLevel) {
+ const int l = int(patches_.size());
+ const uint32_t m = 1u << l;
+ std::vector<uint16_t> verts, idx;
+ for (uint32_t j = 0; j <= m; ++j)
+ for (uint32_t i = 0; i + j <= m; ++i) verts.push_back(uint16_t(i)), verts.push_back(uint16_t(j));
+ for (uint32_t j = 0; j < m; ++j) {
+ const uint32_t row = MicroMesh::index(0, j, m), next = MicroMesh::index(0, j + 1, m);
+ for (uint32_t i = 0; i + j < m; ++i) {
+ idx.insert(idx.end(), {uint16_t(row + i), uint16_t(row + i + 1), uint16_t(next + i)});
+ if (i + j + 1 < m) idx.insert(idx.end(), {uint16_t(row + i + 1), uint16_t(next + i + 1), uint16_t(next + i)});
+ }
+ }
+ Patch p;
+ gl::GenVertexArrays(1, &p.vao);
+ gl::GenBuffers(1, &p.vbo);
+ gl::GenBuffers(1, &p.ibo);
+ gl::BindVertexArray(p.vao);
+ gl::BindBuffer(GL_ARRAY_BUFFER, p.vbo);
+ gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(verts.size() * 2), verts.data(), GL_STATIC_DRAW);
+ gl::EnableVertexAttribArray(0);
+ gl::VertexAttribIPointer(0, 2, GL_UNSIGNED_SHORT, 4, nullptr);
+ gl::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, p.ibo);
+ gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr(idx.size() * 2), idx.data(), GL_STATIC_DRAW);
+ gl::BindVertexArray(0);
+ gl::BindBuffer(GL_ARRAY_BUFFER, 0);
+ p.indices = GLsizei(idx.size());
+ if (l <= kUnrolledLevels)
+ for (uint16_t k : idx) p.corners.push_back(GLint(verts[size_t(k) * 2]) | GLint(verts[size_t(k) * 2 + 1]) << 16);
+ patches_.push_back(p);
+ }
+}
+
+void MicroRenderer::buildLayout(const Mesh& mesh) {
+ const MicroMesh& mm = *mesh.micro;
+ const uint32_t nt = mm.baseTriangles;
+ // Slots in Morton order of the triangle centres: clusters of consecutive slots are compact.
+ box_ = AABB();
+ for (const glm::vec3& p : mesh.positions) box_.expand(p);
+ const glm::vec3 lo = box_.min, ext = glm::max(box_.extent(), glm::vec3(1e-20f));
+ std::vector<uint64_t> keys(nt);
+ poolFor(nt, [&](size_t b, size_t e) {
+ for (size_t t = b; t < e; ++t) {
+ const glm::uvec3 tr = mesh.triangles[t];
+ const glm::vec3 c = ((mesh.positions[tr.x] + mesh.positions[tr.y] + mesh.positions[tr.z]) / 3.0f - lo) / ext;
+ const glm::uvec3 q = glm::uvec3(glm::clamp(c, 0.0f, 1.0f) * 1023.0f);
+ keys[t] = uint64_t(spread10(q.x) | spread10(q.y) << 1 | spread10(q.z) << 2) << 32 | t;
+ }
+ }, 1 << 14);
+ std::sort(keys.begin(), keys.end());
+ order_.resize(nt);
+ slotOf_.resize(nt);
+ for (uint32_t s = 0; s < nt; ++s) {
+ order_[s] = uint32_t(keys[s]);
+ slotOf_[order_[s]] = s;
+ }
+ std::vector<uint64_t>().swap(keys);
+ const uint32_t clusterSize = std::clamp(65536u >> (2 * mm.level), 16u, 1024u);
+ clusterShift_ = uint32_t(std::countr_zero(clusterSize));
+ chunkSlots_ = std::max(clusterSize, (kChunkTexels / mm.samples) & ~(clusterSize - 1));
+ const uint32_t clusters = (nt + clusterSize - 1) >> clusterShift_;
+ // Corners and the clusters across the edges, per slot.
+ std::vector<uint32_t> tri(size_t(nt) * 8);
+ poolFor(nt, [&](size_t b, size_t e) {
+ for (size_t s = b; s < e; ++s) {
+ const uint32_t t = order_[s];
+ const glm::uvec3 tr = mesh.triangles[t];
+ uint32_t* o = tri.data() + s * 8;
+ o[0] = tr.x, o[1] = tr.y, o[2] = tr.z, o[3] = 0;
+ for (int k = 0; k < 3; ++k) {
+ const uint32_t nb = mm.edgeNeighbor[size_t(t) * 3 + size_t(k)];
+ o[4 + k] = nb == MicroMesh::kNone ? kNoCluster : slotOf_[nb >> 2] >> clusterShift_;
+ }
+ o[7] = 0;
+ }
+ }, 1 << 14);
+ auto makeTex = [&](GLuint& buffer, GLuint& tex, GLenum format, const void* data, size_t bytes) {
+ if (!buffer) gl::GenBuffers(1, &buffer);
+ if (!tex) gl::GenTextures(1, &tex);
+ gl::BindBuffer(GL_TEXTURE_BUFFER, buffer);
+ gl::BufferData(GL_TEXTURE_BUFFER, GLsizeiptr(bytes), data, GL_STATIC_DRAW);
+ gl::BindTexture(GL_TEXTURE_BUFFER, tex);
+ gl::TexBuffer(GL_TEXTURE_BUFFER, format, buffer);
+ bytes_ += bytes;
+ };
+ bytes_ = 0;
+ makeTex(triData_, triTex_, GL_RGBA32UI, tri.data(), tri.size() * 4);
+ levels_.assign(clusters, 0);
+ makeTex(levelData_, levelTex_, GL_R32UI, levels_.data(), levels_.size() * 4);
+ // Grid chunks.
+ for (Chunk& c : chunks_) {
+ gl::DeleteBuffers(1, &c.disp);
+ gl::DeleteBuffers(1, &c.shade);
+ gl::DeleteTextures(1, &c.dispTex);
+ gl::DeleteTextures(1, &c.shadeTex);
+ }
+ chunks_.clear();
+ for (uint32_t first = 0; first < nt; first += chunkSlots_) {
+ Chunk c;
+ c.firstSlot = first;
+ c.slots = std::min(chunkSlots_, nt - first);
+ const size_t points = size_t(c.slots) * mm.samples;
+ makeTex(c.disp, c.dispTex, GL_R16I, nullptr, points * 2);
+ makeTex(c.shade, c.shadeTex, GL_RGBA8, nullptr, points * 4);
+ chunks_.push_back(c);
+ }
+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);
+ gl::BindTexture(GL_TEXTURE_BUFFER, 0);
+ closed_ = closedOriented(mesh);
+ bounds_.assign(clusters, ClusterBounds());
+ clusterEdge_.assign(clusters, 0.0f);
+ std::vector<uint32_t> all(clusters);
+ for (uint32_t c = 0; c < clusters; ++c) all[c] = c;
+ updateClusterBounds(mesh, all);
+ pending_.assign((size_t(nt) + 63) / 64, 0);
+ pendingCount_ = 0;
+ ensurePatches(mm.level);
+}
+
+void MicroRenderer::uploadBase(const Mesh& mesh) {
+ std::vector<glm::vec4> data(mesh.vertexCount() * 2);
+ poolFor(mesh.vertexCount(), [&](size_t b, size_t e) {
+ for (size_t v = b; v < e; ++v) {
+ data[v * 2] = glm::vec4(mesh.positions[v], 1.0f);
+ data[v * 2 + 1] = glm::vec4(mesh.normals[v], 0.0f);
+ }
+ }, 1 << 14);
+ if (!baseData_) gl::GenBuffers(1, &baseData_);
+ if (!baseTex_) gl::GenTextures(1, &baseTex_);
+ gl::BindBuffer(GL_TEXTURE_BUFFER, baseData_);
+ gl::BufferData(GL_TEXTURE_BUFFER, GLsizeiptr(data.size() * sizeof(glm::vec4)), data.data(), GL_STATIC_DRAW);
+ gl::BindTexture(GL_TEXTURE_BUFFER, baseTex_);
+ gl::TexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, baseData_);
+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);
+ gl::BindTexture(GL_TEXTURE_BUFFER, 0);
+ bytes_ += data.size() * sizeof(glm::vec4);
+}
+
+void MicroRenderer::updateClusterBounds(const Mesh& mesh, const std::vector<uint32_t>& clusters) {
+ const MicroMesh& mm = *mesh.micro;
+ const uint32_t nt = mm.baseTriangles, size = 1u << clusterShift_;
+ poolFor(clusters.size(), [&](size_t b, size_t e) {
+ for (size_t ci = b; ci < e; ++ci) {
+ const uint32_t c = clusters[ci];
+ const uint32_t s0 = c << clusterShift_, s1 = std::min(nt, s0 + size);
+ AABB box;
+ glm::vec3 axis(0.0f);
+ float edge = 0.0f;
+ uint16_t range = 0;
+ for (uint32_t s = s0; s < s1; ++s) {
+ const uint32_t t = order_[s];
+ const glm::uvec3 tr = mesh.triangles[t];
+ for (int k = 0; k < 3; ++k) {
+ box.expand(mesh.positions[tr[k]]);
+ axis += mesh.normals[tr[k]];
+ }
+ edge += glm::distance(mesh.positions[tr.x], mesh.positions[tr.y]) + glm::distance(mesh.positions[tr.y], mesh.positions[tr.z]) +
+ glm::distance(mesh.positions[tr.z], mesh.positions[tr.x]);
+ range = std::max(range, mm.triRange[t]);
+ }
+ ClusterBounds cb;
+ cb.center = box.center();
+ float radius = 0.0f, cosMin = 1.0f;
+ const float al = glm::length(axis);
+ axis = al > 0.0f ? axis / al : glm::vec3(0, 0, 1);
+ for (uint32_t s = s0; s < s1; ++s) {
+ const glm::uvec3 tr = mesh.triangles[order_[s]];
+ for (int k = 0; k < 3; ++k) {
+ radius = std::max(radius, glm::distance(mesh.positions[tr[k]], cb.center));
+ cosMin = std::min(cosMin, glm::dot(mesh.normals[tr[k]], axis));
+ }
+ }
+ cb.radius = radius + mm.bulgeMax + float(range) * mm.step;
+ cb.axis = axis;
+ // Micro detail tilts the surface off the base normals: half a radian of margin, and none when the
+ // displacement is large next to the cluster (its faces could point anywhere).
+ const float angle = std::acos(std::clamp(cosMin, -1.0f, 1.0f)) + 0.5f;
+ cb.coneAngle = angle < 1.45f && float(range) * mm.step < radius * 0.5f ? angle : -1.0f;
+ bounds_[c] = cb;
+ clusterEdge_[c] = edge / float(3 * (s1 - s0)) / float(mm.n) * float(mm.n); // (base edge)
+ }
+ }, 16);
+}
+
+void MicroRenderer::uploadDispTiles(const Mesh& mesh, std::vector<uint32_t>& slots, bool all) {
+ const MicroMesh& mm = *mesh.micro;
+ const size_t S = mm.samples;
+ if (all) {
+ for (Chunk& c : chunks_) {
+ gl::BindBuffer(GL_TEXTURE_BUFFER, c.disp);
+ auto* dst = static_cast<int16_t*>(gl::MapBufferRange(GL_TEXTURE_BUFFER, 0, GLsizeiptr(size_t(c.slots) * S * 2),
+ GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT));
+ if (!dst) continue;
+ poolFor(c.slots, [&](size_t b, size_t e) {
+ for (size_t s = b; s < e; ++s) std::memcpy(dst + s * S, mm.disp.data() + size_t(order_[c.firstSlot + s]) * S, S * 2);
+ }, 1024);
+ gl::UnmapBuffer(GL_TEXTURE_BUFFER);
+ }
+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);
+ return;
+ }
+ if (slots.empty()) return;
+ std::sort(slots.begin(), slots.end());
+ staging_.resize(slots.size() * S * 2);
+ auto* st = reinterpret_cast<int16_t*>(staging_.data());
+ poolFor(slots.size(), [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) std::memcpy(st + i * S, mm.disp.data() + size_t(order_[slots[i]]) * S, S * 2);
+ }, 256);
+ for (size_t i = 0; i < slots.size();) {
+ const uint32_t chunk = slots[i] / chunkSlots_;
+ size_t j = i + 1;
+ while (j < slots.size() && slots[j] == slots[j - 1] + 1 && slots[j] / chunkSlots_ == chunk) ++j;
+ const Chunk& c = chunks_[chunk];
+ gl::BindBuffer(GL_TEXTURE_BUFFER, c.disp);
+ gl::BufferSubData(GL_TEXTURE_BUFFER, GLintptr(size_t(slots[i] - c.firstSlot) * S * 2), GLsizeiptr((j - i) * S * 2),
+ st + i * S);
+ i = j;
+ }
+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);
+}
+
+// Shading for the base triangles marked pending: all of it (`all`), or up to shadeBudget grid points of it.
+void MicroRenderer::shadePending(const Mesh& mesh, bool all) {
+ const MicroMesh& mm = *mesh.micro;
+ const size_t S = mm.samples;
+ if (all) {
+ std::vector<uint32_t*> mapped(chunks_.size(), nullptr);
+ for (size_t i = 0; i < chunks_.size(); ++i) {
+ gl::BindBuffer(GL_TEXTURE_BUFFER, chunks_[i].shade);
+ mapped[i] = static_cast<uint32_t*>(gl::MapBufferRange(GL_TEXTURE_BUFFER, 0, GLsizeiptr(size_t(chunks_[i].slots) * S * 4),
+ GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT));
+ }
+ thread_local std::vector<uint32_t> sink;
+ shader_.shade(mesh, {}, true, written_, [&](uint32_t t) -> uint32_t* {
+ const uint32_t s = slotOf_[t], c = s / chunkSlots_;
+ if (!mapped[c]) {
+ sink.resize(S);
+ return sink.data();
+ }
+ return mapped[c] + size_t(s - chunks_[c].firstSlot) * S;
+ });
+ for (size_t i = 0; i < chunks_.size(); ++i) {
+ gl::BindBuffer(GL_TEXTURE_BUFFER, chunks_[i].shade);
+ if (mapped[i]) gl::UnmapBuffer(GL_TEXTURE_BUFFER);
+ }
+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);
+ std::fill(pending_.begin(), pending_.end(), 0);
+ pendingCount_ = 0;
+ return;
+ }
+ // The pending triangles, newest first (scratch_ holds this sync's dirty ones, already marked).
+ std::vector<uint32_t>& seeds = scratch_;
+ const size_t limit = shadeBudget ? std::max<size_t>(1, shadeBudget / (S * 3)) : SIZE_MAX; // (the ring triples it)
+ if (seeds.size() < limit)
+ for (size_t w = 0; w < pending_.size() && seeds.size() < limit; ++w)
+ for (uint64_t bits = pending_[w]; bits && seeds.size() < limit; bits &= bits - 1) {
+ const uint32_t t = uint32_t(w * 64 + size_t(std::countr_zero(bits)));
+ seeds.push_back(t);
+ }
+ std::sort(seeds.begin(), seeds.end());
+ seeds.erase(std::unique(seeds.begin(), seeds.end()), seeds.end());
+ if (seeds.size() > limit) seeds.resize(limit);
+ if (seeds.empty()) return;
+ std::vector<uint32_t> sorted;
+ if (stageIndex_.size() != mm.baseTriangles) stageIndex_.assign(mm.baseTriangles, 0);
+ shader_.shade(mesh, seeds, false, written_, [&](uint32_t t) -> uint32_t* {
+ return reinterpret_cast<uint32_t*>(staging_.data()) + size_t(stageIndex_[t]) * S;
+ }, [&](std::span<const uint32_t> tris) {
+ sorted.assign(tris.begin(), tris.end());
+ std::sort(sorted.begin(), sorted.end(), [&](uint32_t a, uint32_t b) { return slotOf_[a] < slotOf_[b]; });
+ for (size_t i = 0; i < sorted.size(); ++i) stageIndex_[sorted[i]] = uint32_t(i);
+ staging_.resize(sorted.size() * S * 4);
+ });
+ const auto* st = reinterpret_cast<const uint32_t*>(staging_.data());
+ for (size_t i = 0; i < sorted.size();) {
+ const uint32_t s0 = slotOf_[sorted[i]], chunk = s0 / chunkSlots_;
+ size_t j = i + 1;
+ while (j < sorted.size() && slotOf_[sorted[j]] == slotOf_[sorted[j - 1]] + 1 && slotOf_[sorted[j]] / chunkSlots_ == chunk) ++j;
+ const Chunk& c = chunks_[chunk];
+ gl::BindBuffer(GL_TEXTURE_BUFFER, c.shade);
+ gl::BufferSubData(GL_TEXTURE_BUFFER, GLintptr(size_t(s0 - c.firstSlot) * S * 4), GLsizeiptr((j - i) * S * 4), st + i * S);
+ i = j;
+ }
+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);
+ for (uint32_t t : written_) {
+ uint64_t& w = pending_[t >> 6];
+ const uint64_t bit = uint64_t(1) << (t & 63);
+ if (w & bit) w &= ~bit, --pendingCount_;
+ }
+}
+
+bool MicroRenderer::sync(Mesh& mesh) {
+ MicroMesh& mm = *mesh.micro;
+ mm.ensureTopology(mesh);
+ if (mm.dirtyBits.size() != (size_t(mm.baseTriangles) + 63) / 64) mm.dirtyBits.assign((size_t(mm.baseTriangles) + 63) / 64, 0);
+ const bool baseMoved = mesh.dirtyBegin < mesh.dirtyEnd;
+ const bool full = serial_ != mm.serial || baseTriangles_ != mm.baseTriangles || baseVertices_ != mm.baseVertices ||
+ level_ != mm.level || mesh.topologyDirty;
+ for (int i = 0; i < 16 && gl::GetError() != GL_NO_ERROR; ++i) {
+ }
+ if (full) {
+ serial_ = mm.serial;
+ baseTriangles_ = mm.baseTriangles;
+ baseVertices_ = mm.baseVertices;
+ level_ = mm.level;
+ n_ = mm.n;
+ samples_ = mm.samples;
+ buildLayout(mesh);
+ uploadBase(mesh);
+ uploadDispTiles(mesh, scratch_, true);
+ shadePending(mesh, true);
+ } else {
+ if (baseMoved) { // a transform or a base edit: the base, the bounds and every shading point
+ uploadBase(mesh);
+ bytes_ -= mesh.vertexCount() * 2 * sizeof(glm::vec4);
+ std::vector<uint32_t> all(bounds_.size());
+ for (uint32_t c = 0; c < all.size(); ++c) all[c] = c;
+ updateClusterBounds(mesh, all);
+ }
+ // This sync's dirty triangles.
+ scratch_.clear();
+ for (size_t w = 0; w < mm.dirtyBits.size(); ++w)
+ for (uint64_t bits = mm.dirtyBits[w]; bits; bits &= bits - 1) scratch_.push_back(uint32_t(w * 64 + size_t(std::countr_zero(bits))));
+ if (mm.allDirty || mm.rescaled) {
+ uploadDispTiles(mesh, scratch_, true);
+ } else if (!scratch_.empty()) {
+ std::vector<uint32_t> slots(scratch_.size());
+ for (size_t i = 0; i < scratch_.size(); ++i) slots[i] = slotOf_[scratch_[i]];
+ uploadDispTiles(mesh, slots, false);
+ }
+ if (!scratch_.empty()) { // their clusters may reach further now
+ std::vector<uint32_t> cl;
+ for (uint32_t t : scratch_) cl.push_back(slotOf_[t] >> clusterShift_);
+ std::sort(cl.begin(), cl.end());
+ cl.erase(std::unique(cl.begin(), cl.end()), cl.end());
+ updateClusterBounds(mesh, cl);
+ }
+ if (mm.allDirty || baseMoved) {
+ shadePending(mesh, true);
+ } else {
+ for (uint32_t t : scratch_) {
+ uint64_t& w = pending_[t >> 6];
+ const uint64_t bit = uint64_t(1) << (t & 63);
+ if (!(w & bit)) w |= bit, ++pendingCount_;
+ }
+ if (pendingCount_) shadePending(mesh, false);
+ }
+ }
+ step_ = mm.step;
+ mm.clearDirty();
+ mesh.clearDirty();
+ mesh.topologyDirty = false;
+ mesh.facesDirty = false;
+ bool oom = false;
+ for (int i = 0; i < 16; ++i) {
+ const GLenum e = gl::GetError();
+ if (e == GL_NO_ERROR) break;
+ oom = oom || e == GL_OUT_OF_MEMORY;
+ }
+ return !oom;
+}
+
+size_t MicroRenderer::draw(GLuint program, const CullView& cullIn, const glm::mat4& proj, const glm::vec4& viewport, size_t budget,
+ float targetPx) {
+ if (chunks_.empty() || bounds_.empty()) return 0;
+ const uint32_t clusters = uint32_t(bounds_.size()), size = 1u << clusterShift_;
+ CullView cull = cullIn;
+ // Clusters facing away can go when the mesh is closed and the eye is outside it.
+ const glm::vec3 grow(box_.extent() * 0.1f);
+ const bool eyeInside = glm::all(glm::greaterThanEqual(cull.eye, box_.min - grow)) && glm::all(glm::lessThanEqual(cull.eye, box_.max + grow));
+ cull.backfaces = closed_ && !eyeInside && !cull.ortho;
+ want_.resize(clusters);
+ std::vector<uint8_t> visible(clusters);
+ const float h = std::max(viewport.w, 1.0f);
+ const bool ortho = proj[3][3] == 1.0f;
+ const float scale = h * proj[1][1] * 0.5f;
+ std::vector<float> pxEdge(clusters);
+ for (uint32_t c = 0; c < clusters; ++c) {
+ const ClusterBounds& b = bounds_[c];
+ visible[c] = insideFrustum(cull, b) && !facingAway(cull, b);
+ const float dist = ortho ? 1.0f : std::max(glm::distance(cull.eye, b.center) - b.radius, std::max(cull.nearDistance, 1e-6f));
+ pxEdge[c] = clusterEdge_[c] * scale / dist; // a base edge in pixels
+ }
+ auto choose = [&](float target) {
+ size_t total = 0;
+ for (uint32_t c = 0; c < clusters; ++c) {
+ const float ratio = pxEdge[c] / target;
+ int l = ratio <= 1.0f ? 0 : int(std::ceil(std::log2(ratio)));
+ l = std::clamp(l, 0, level_);
+ want_[c] = int8_t(l);
+ if (visible[c]) total += size_t(std::min(size, baseTriangles_ - (c << clusterShift_))) << (2 * l);
+ }
+ return total;
+ };
+ float target = std::max(targetPx, 0.25f);
+ size_t total = choose(target);
+ for (int it = 0; it < 24 && budget && total > budget; ++it) total = choose(target *= 1.4142f);
+ lastTargetPx = target;
+ for (uint32_t c = 0; c < clusters; ++c) levels_[c] = uint32_t(want_[c]);
+ gl::BindBuffer(GL_TEXTURE_BUFFER, levelData_);
+ gl::BufferSubData(GL_TEXTURE_BUFFER, 0, GLsizeiptr(levels_.size() * 4), levels_.data());
+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);
+
+ if (u_.program != program) {
+ u_.program = program;
+ auto at = [&](const char* name) { return gl::GetUniformLocation(program, name); };
+ u_.slotBase = at("uSlotBase");
+ u_.chunkSlot = at("uChunkSlot");
+ u_.level = at("uLevel");
+ u_.n = at("uN");
+ u_.samples = at("uSamples");
+ u_.step = at("uStep");
+ u_.unrolled = at("uUnrolled");
+ u_.corners = at("uCorners");
+ gl::Uniform1i(at("uTris"), 8);
+ gl::Uniform1i(at("uBase"), 9);
+ gl::Uniform1i(at("uDisp"), 10);
+ gl::Uniform1i(at("uLevels"), 11);
+ gl::Uniform1i(at("uShade"), 12);
+ }
+ gl::Uniform1i(u_.n, int(n_));
+ gl::Uniform1i(u_.samples, int(samples_));
+ gl::Uniform1f(u_.step, step_);
+ gl::ActiveTexture(kUnitTris);
+ gl::BindTexture(GL_TEXTURE_BUFFER, triTex_);
+ gl::ActiveTexture(kUnitBase);
+ gl::BindTexture(GL_TEXTURE_BUFFER, baseTex_);
+ gl::ActiveTexture(kUnitLevels);
+ gl::BindTexture(GL_TEXTURE_BUFFER, levelTex_);
+ if (closed_) gl::Enable(GL_CULL_FACE);
+ size_t drawn = 0;
+ int boundChunk = -1;
+ int unrolledLevel = -2; // the patch uCorners holds (-1: instanced draws)
+ for (uint32_t c = 0; c < clusters;) {
+ if (!visible[c]) {
+ ++c;
+ continue;
+ }
+ const int l = want_[c];
+ const uint32_t chunk = (c << clusterShift_) / chunkSlots_;
+ uint32_t e = c + 1;
+ while (e < clusters && visible[e] && want_[e] == l && (e << clusterShift_) / chunkSlots_ == chunk) ++e;
+ const uint32_t s0 = c << clusterShift_, s1 = std::min(baseTriangles_, e << clusterShift_);
+ if (int(chunk) != boundChunk) {
+ boundChunk = int(chunk);
+ gl::ActiveTexture(kUnitDisp);
+ gl::BindTexture(GL_TEXTURE_BUFFER, chunks_[chunk].dispTex);
+ gl::ActiveTexture(kUnitShade);
+ gl::BindTexture(GL_TEXTURE_BUFFER, chunks_[chunk].shadeTex);
+ gl::Uniform1i(u_.chunkSlot, int(chunks_[chunk].firstSlot));
+ }
+ gl::Uniform1i(u_.level, l);
+ gl::Uniform1i(u_.slotBase, int(s0));
+ const Patch& p = patches_[size_t(l)];
+ if (l <= kUnrolledLevels) {
+ if (!emptyVao_) gl::GenVertexArrays(1, &emptyVao_);
+ if (l != unrolledLevel) {
+ gl::Uniform1i(u_.unrolled, GLsizei(p.corners.size()));
+ gl::Uniform1iv(u_.corners, GLsizei(p.corners.size()), p.corners.data());
+ unrolledLevel = l;
+ }
+ gl::BindVertexArray(emptyVao_);
+ gl::DrawArrays(GL_TRIANGLES, 0, GLsizei(size_t(s1 - s0) * p.corners.size()));
+ } else {
+ if (unrolledLevel != -1) gl::Uniform1i(u_.unrolled, 0), unrolledLevel = -1;
+ gl::BindVertexArray(p.vao);
+ gl::DrawElementsInstanced(GL_TRIANGLES, p.indices, GL_UNSIGNED_SHORT, nullptr, GLsizei(s1 - s0));
+ }
+ drawn += size_t(s1 - s0) << (2 * l);
+ c = e;
+ }
+ gl::Disable(GL_CULL_FACE);
+ gl::BindVertexArray(0);
+ for (GLenum unit : {kUnitTris, kUnitBase, kUnitDisp, kUnitLevels, kUnitShade}) {
+ gl::ActiveTexture(unit);
+ gl::BindTexture(GL_TEXTURE_BUFFER, 0);
+ }
+ gl::ActiveTexture(GL_TEXTURE0);
+ return drawn;
+}
+
+} // namespace sf
diff --git a/src/render/MicroRenderer.h b/src/render/MicroRenderer.h
new file mode 100644
index 00000000..a01cc4c1
--- /dev/null
+++ b/src/render/MicroRenderer.h
@@ -0,0 +1,106 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Draws a mesh's micro-displacement level (core/Micro.h) without ever building its micro triangles:
+//
+// - GPU data per base triangle, in a spatial (Morton) order of "slots": its corners and the clusters across its
+// edges (texture buffer), its grid of 16-bit displacements and its shading grid (RGBA8: octahedral normal,
+// curvature, mask; computed on the CPU by MicroShader). Grids live in chunks of at most 2^26 points (texture
+// buffer limits), each a whole number of clusters.
+// - Clusters of 16-1024 consecutive slots. Every frame each visible cluster gets a level of detail from its
+// projected size (the micro edge it would draw, in pixels), and the levels are lowered until the triangles
+// drawn fit RenderSettings::renderTriangleBudget: the draw cost depends on the screen, not on the micro level.
+// - One instanced draw per run of consecutive clusters at one level: a patch of 4^level triangles per base
+// triangle; the vertex shader evaluates the micro surface (Phong-tessellated base + displacement, the same
+// operations as MicroTriangle::evalWeights). A patch edge whose neighbour draws a coarser level snaps its
+// in-between vertices onto the coarser edge (crack-free). The fragment shader interpolates the full-resolution
+// shading grid, so lighting keeps every micro detail even where the geometry is coarser.
+// - Brushes mark base triangles dirty; their displacement tiles are re-sent at once, their shading (and that of
+// their neighbours) within a per-frame budget of grid points (the rest follows on the next frames).
+// GL 3.3 core: texture buffers, instancing, no tessellation or compute shaders (macOS stops at GL 4.1).
+#pragma once
+
+#include "core/Micro.h"
+#include "render/Clusters.h"
+#include "render/GL.h"
+
+#include <cstdint>
+#include <vector>
+
+namespace sf {
+
+class MicroRenderer {
+public:
+ ~MicroRenderer();
+ void release();
+ // Uploads what changed since the last call (everything the first time, or after the base or the level
+ // changed); clears the micro level's dirty state. Returns false when the GPU ran out of memory.
+ bool sync(Mesh& mesh);
+ // Draws with `program` bound (the mesh program with MICRO): sets the micro uniforms and issues the draws.
+ // `budget`: most triangles to draw; `targetPx`: the micro edge length to aim for on screen. Returns the
+ // triangles drawn.
+ size_t draw(GLuint program, const CullView& cull, const glm::mat4& proj, const glm::vec4& viewport, size_t budget,
+ float targetPx);
+ size_t gpuBytes() const;
+ bool closed() const { return closed_; }
+ // Grid points whose shading still waits for a frame (budget), for tests and the benchmark.
+ size_t pendingShading() const { return pendingCount_; }
+ // Grid points of shading recomputed per sync at most (0 = no limit).
+ size_t shadeBudget = size_t(3) << 20;
+ // The last draw: the level used by each visible cluster (-1 = culled), and the target it settled on.
+ float lastTargetPx = 0.0f;
+
+private:
+ void buildLayout(const Mesh& mesh);
+ void uploadBase(const Mesh& mesh);
+ void updateClusterBounds(const Mesh& mesh, const std::vector<uint32_t>& clusters);
+ void ensurePatches(int level);
+ void uploadDispTiles(const Mesh& mesh, std::vector<uint32_t>& slots, bool all);
+ void shadePending(const Mesh& mesh, bool all);
+
+ uint64_t serial_ = 0;
+ uint32_t baseTriangles_ = 0, baseVertices_ = 0;
+ int level_ = 0;
+ uint32_t n_ = 1, samples_ = 3;
+ float step_ = 0.0f;
+ bool closed_ = false;
+ std::vector<uint32_t> order_; // slot -> base triangle
+ std::vector<uint32_t> slotOf_; // base triangle -> slot
+ uint32_t clusterShift_ = 8;
+ std::vector<ClusterBounds> bounds_;
+ std::vector<float> clusterEdge_; // average base edge per cluster
+ AABB box_;
+ struct Chunk {
+ uint32_t firstSlot = 0, slots = 0;
+ GLuint disp = 0, dispTex = 0, shade = 0, shadeTex = 0;
+ };
+ std::vector<Chunk> chunks_;
+ uint32_t chunkSlots_ = 0;
+ GLuint triData_ = 0, triTex_ = 0, baseData_ = 0, baseTex_ = 0, levelData_ = 0, levelTex_ = 0;
+ struct Patch {
+ GLuint vao = 0, vbo = 0, ibo = 0;
+ GLsizei indices = 0;
+ std::vector<GLint> corners; // levels 0-2: the triangles' corners, packed i | j << 16 (uCorners)
+ };
+ GLuint emptyVao_ = 0;
+ static constexpr int kUnrolledLevels = 1;
+ std::vector<Patch> patches_;
+ size_t bytes_ = 0;
+ MicroShader shader_;
+ std::vector<uint64_t> pending_; // per base triangle: shading out of date
+ size_t pendingCount_ = 0;
+ std::vector<uint32_t> scratch_, written_, stageIndex_;
+ std::vector<uint8_t> staging_;
+ std::vector<uint32_t> levels_;
+ std::vector<int8_t> want_;
+ struct Uniforms {
+ GLuint program = 0;
+ GLint slotBase = -1, chunkSlot = -1, level = -1, n = -1, samples = -1, clusterShift = -1, step = -1, unrolled = -1,
+ corners = -1;
+ } u_;
+};
+
+// The micro mesh shader's vertex stage (with the mesh fragment shader under MICRO).
+const char* microVertexShaderSource();
+
+} // namespace sf
diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cpp
index a19b422e..3c6bf838 100644
--- a/src/render/Renderer.cpp
+++ b/src/render/Renderer.cpp
@@ -1,6 +1,7 @@
// SculptForge - open source digital sculpting
// SPDX-License-Identifier: GPL-3.0-or-later
#include "render/Renderer.h"
+#include "render/MicroRenderer.h"
#include "core/Matcap.h"
#include "core/Texture.h"
@@ -157,7 +158,9 @@ uniform int uHasPaint; // 1: a painted texture is bound to uPaintTex too
uniform int uNormalFlipY; // 1: DirectX convention (green down)
#endif
#else
+#ifndef MICRO
in vec4 vNormalCurv;
+#endif
#ifdef FLAT
in vec3 vViewPos;
#endif
@@ -175,6 +178,54 @@ flat in int vPrimBase;
#define V_COLOR vec3(1.0)
#define V_MASK 0.0
#endif
+#ifdef MICRO
+// Micro-displacement levels (render/MicroRenderer.cpp): the full-resolution shading grid of the base triangle,
+// interpolated on the micro triangle under the pixel (normal, curvature, mask), whatever level the geometry drew.
+flat in int vSlot;
+in vec2 vIJ;
+uniform samplerBuffer uShade;
+uniform int uN;
+uniform int uSamples;
+uniform mat4 uView;
+vec4 gNC;
+float gMask;
+vec4 shadeAt(int i, int j) { return texelFetch(uShade, vSlot * uSamples + j * (uN + 1) - (j * (j - 1)) / 2 + i); }
+vec3 octNormal(vec2 v) {
+ vec2 e = v * 2.0 - 1.0;
+ vec3 n = vec3(e, 1.0 - abs(e.x) - abs(e.y));
+ float t = max(-n.z, 0.0);
+ n.x += n.x >= 0.0 ? -t : t;
+ n.y += n.y >= 0.0 ? -t : t;
+ return normalize(n);
+}
+void microFetch() {
+ float fi = clamp(vIJ.x, 0.0, float(uN)), fj = clamp(vIJ.y, 0.0, float(uN));
+ int i0 = min(int(fi), uN - 1), j0 = min(int(fj), uN - 1);
+ if (i0 + j0 > uN - 1) {
+ if (fi >= fj) i0 = uN - 1 - j0;
+ else j0 = uN - 1 - i0;
+ }
+ float a = fi - float(i0), b = fj - float(j0);
+ vec4 s0, s1, s2;
+ vec3 w;
+ if (a + b <= 1.0 || i0 + j0 + 2 > uN) {
+ s0 = shadeAt(i0, j0); s1 = shadeAt(i0 + 1, j0); s2 = shadeAt(i0, j0 + 1);
+ w = vec3(1.0 - a - b, a, b);
+ } else {
+ s0 = shadeAt(i0 + 1, j0); s1 = shadeAt(i0 + 1, j0 + 1); s2 = shadeAt(i0, j0 + 1);
+ w = vec3(1.0 - b, a + b - 1.0, 1.0 - a);
+ }
+ w = clamp(w, 0.0, 1.0);
+ vec3 n = octNormal(s0.xy) * w.x + octNormal(s1.xy) * w.y + octNormal(s2.xy) * w.z;
+ vec3 c3 = (vec3(s0.z, s1.z, s2.z) * 255.0 - 128.0) / 127.0;
+ float c = dot(c3, w);
+ gNC = vec4(mat3(uView) * normalize(n), c * abs(c));
+ gMask = dot(vec3(s0.w, s1.w, s2.w), w);
+}
+#define vNormalCurv gNC
+#undef V_MASK
+#define V_MASK gMask
+#endif
uniform vec4 uViewport; // the view's rectangle in window pixels
uniform vec2 uProjScale; // projection x and y scale
uniform vec3 uBaseColor;
@@ -211,6 +262,9 @@ vec3 viewRay() {
return normalize(vec3(-ndc / uProjScale, 1.0));
}
void main() {
+#ifdef MICRO
+ microFetch();
+#endif
vec3 albedo = uBaseColor;
vec3 tint = vec3(1.0); // multiplies a matcap: polypaint or polygroup colours
#ifdef PRIM
@@ -519,15 +573,18 @@ bool Renderer::init(std::string& error) {
const Renderer::MeshProgram* Renderer::meshProgram(int features) {
if (features & (kTextured | kNormalMap)) features |= kTextured | kPrim;
- MeshProgram& p = programs_[features & 31];
+ if (features & kMicro) features &= kMicro | kFlat; // (micro levels: no per-vertex paint or per-triangle data)
+ MeshProgram& p = programs_[features & 63];
if (p.id) return &p;
std::string prefix = "#version 330 core\n";
+ if (features & kMicro) prefix += "#define MICRO\n";
if (features & kPaint) prefix += "#define PAINT\n";
if (features & kPrim) prefix += "#define PRIM\n";
if (features & kTextured) prefix += "#define TEXTURED\n";
if (features & kNormalMap) prefix += "#define NORMALMAP\n";
if (features & kFlat) prefix += "#define FLAT\n";
- const std::string vs = prefix + kMeshVS, fs = prefix + kMeshFS, gs = prefix + kMeshGS;
+ const std::string vs = prefix + ((features & kMicro) ? microVertexShaderSource() : kMeshVS), fs = prefix + kMeshFS,
+ gs = prefix + kMeshGS;
p.id = link(vs.c_str(), fs.c_str(), programError_, nullptr, (features & kTextured) ? gs.c_str() : nullptr);
if (!p.id) return nullptr;
auto at = [&](const char* name) { return gl::GetUniformLocation(p.id, name); };
@@ -693,6 +750,7 @@ void Renderer::freeSlot(MeshSlot& s) {
gl::DeleteVertexArrays(1, &s.vao);
gl::DeleteVertexArrays(1, &s.lineVao);
gl::DeleteVertexArrays(1, &s.proxyVao);
+ s.micro.reset();
if (s.patchVao) {
for (GLuint* b : {&s.patchVertices, &s.patchIndices, &s.patchLines, &s.patchColors, &s.patchMask, &s.patchGroupData})
gl::DeleteBuffers(1, b);
@@ -710,6 +768,7 @@ size_t Renderer::gpuBytes() const {
total += s.patchBytes;
if (s.proxyAllocated) total += (s.order.triangleCount() / 4) * 3 * sizeof(uint16_t);
if (s.paintTexture) total += size_t(s.textureW) * size_t(s.textureH) * 4 * 4 / 3; // with mipmaps
+ if (s.micro) total += s.micro->gpuBytes();
}
return total;
}
@@ -1636,6 +1695,17 @@ void Renderer::drawPatches(const MeshSlot& s, GLenum mode, Part part, GLint prim
}
void Renderer::sync(MeshSlot& s, Mesh& mesh, const NormalMapView* normalMap, bool wireframe) {
+ if (mesh.micro && microMatches(mesh)) { // a micro level draws its own way (render/MicroRenderer.h)
+ if (!s.micro) s.micro = std::make_shared<MicroRenderer>();
+ s.outOfMemory = !s.micro->sync(mesh);
+ s.drawnTriangles = s.outOfMemory ? 0 : 1; // (draw() skips empty slots)
+ s.fresh = true; // (back to a mesh: a full upload)
+ return;
+ }
+ if (s.micro) {
+ s.micro.reset();
+ s.fresh = true;
+ }
const size_t nv = mesh.vertexCount();
if (normalMap && (!normalMap->rgb || !normalMap->tangents || normalMap->tangents->size() != mesh.uvs.size() ||
!mesh.hasUvs() || normalMap->rgb->size() != size_t(normalMap->width) * size_t(normalMap->height) * 3))
@@ -2109,7 +2179,7 @@ void Renderer::draw(const Camera& camera, int targetWidth, int targetHeight, con
gl::DepthMask(GL_FALSE);
for (const DrawItem& item : drawList_) {
const MeshSlot* s = item.active ? findSlot(item.id) : nullptr;
- if (!s || s->drawnTriangles == 0) continue;
+ if (!s || s->drawnTriangles == 0 || s->micro) continue; // (micro levels: no wireframe)
gl::Uniform3fv(gl::GetUniformLocation(wireProgram_, "uGridOrigin"), 1, glm::value_ptr(s->grid.origin));
gl::Uniform1f(gl::GetUniformLocation(wireProgram_, "uGridStep"), s->grid.step);
cull(*s, frameCull_);
@@ -2231,7 +2301,38 @@ void Renderer::drawClusters(const MeshSlot& s, const std::vector<uint32_t>& clus
}
// One mesh. Mask and polygroup colours are for the SubTool being edited; polypaint shows on all of them.
+void Renderer::drawMicro(const MeshSlot& s, bool active, bool flat, const RenderSettings& settings) {
+ const MeshProgram* p = meshProgram(kMicro | (flat ? kFlat : 0));
+ if (!p) return;
+ gl::UseProgram(p->id);
+ gl::UniformMatrix4fv(p->view, 1, GL_FALSE, glm::value_ptr(frameView_));
+ gl::UniformMatrix4fv(p->proj, 1, GL_FALSE, glm::value_ptr(frameProj_));
+ gl::Uniform4fv(p->viewport, 1, glm::value_ptr(frameViewport_));
+ const bool orthographic = frameProj_[3][3] == 1.0f;
+ gl::Uniform2f(p->projScale, orthographic ? 1e20f : frameProj_[0][0], orthographic ? 1e20f : frameProj_[1][1]);
+ gl::Uniform3fv(p->baseColor, 1, glm::value_ptr(settings.baseColor));
+ gl::Uniform1i(p->matcap, matcapTexture(settings.matcap) ? 1 : 0);
+ const MatcapCavity cavity = matcapCavity(settings.matcap);
+ gl::Uniform2f(p->matcapCavity, cavity.crease, cavity.ridge);
+ gl::Uniform1i(p->paint, 0);
+ gl::Uniform1i(p->showMask, active && settings.showMask ? 1 : 0);
+ gl::Uniform1i(p->groups, active && settings.showPolygroups ? 2 : 0);
+ gl::Uniform1i(p->dim, !active && settings.dimInactive ? 1 : 0);
+ gl::Uniform1i(p->twoSided, 1);
+ // Moving (Fast Navigation): a coarser target and half the budget, so orbiting stays smooth.
+ const bool moving = settings.motionProxy;
+ const size_t budget = moving ? settings.renderTriangleBudget / 2 : settings.renderTriangleBudget;
+ const float target = settings.microTargetPx * (moving ? 2.0f : 1.0f);
+ // (the budget is shared by the micro SubTools on screen: each gets it whole; one is the usual case)
+ const_cast<MeshSlot&>(s).microDrawn = s.micro->draw(p->id, frameCull_, frameProj_, frameViewport_, budget, target);
+ lastDrawn_ += s.microDrawn;
+}
+
void Renderer::drawSlot(const MeshSlot& s, bool active, bool flat, const RenderSettings& settings) {
+ if (s.micro) {
+ drawMicro(s, active, flat, settings);
+ return;
+ }
// A painted texture shows through the textured program (polypaint still multiplies it).
const bool textured = s.hasUvs && s.paintTexture && settings.showPolypaint && settings.showTexture;
// A baked normal map preview bends the shading normal (core/Bake.h).
diff --git a/src/render/Renderer.h b/src/render/Renderer.h
index db74e32e..f52c466e 100644
--- a/src/render/Renderer.h
+++ b/src/render/Renderer.h
@@ -11,11 +11,14 @@
#include "render/GL.h"
#include <cstdint>
+#include <memory>
#include <string>
#include <vector>
namespace sf {
+class MicroRenderer;
+
struct RenderSettings {
bool wireframe = false;
glm::vec3 baseColor{0.62f, 0.58f, 0.53f}; // Studio's colour: a warm clay grey, like the default Soft Clay
@@ -33,6 +36,10 @@ struct RenderSettings {
// The view's background: the charcoal radial gradient (default) or one flat display (sRGB) colour (#21).
bool gradientBackground = true;
glm::vec3 backgroundColor{0.165f, 0.165f, 0.173f};
+ // Micro-displacement levels (render/MicroRenderer.h): the most triangles a frame draws for them (their level
+ // of detail drops to fit; a hardware profile may set it), and the micro edge length to aim for on screen.
+ size_t renderTriangleBudget = size_t(6) << 20;
+ float microTargetPx = 2.0f;
};
// A baked tangent-space normal map to preview on a mesh (core/Bake.h): RGB8 rows bottom-up, with the
@@ -208,6 +215,9 @@ private:
bool patchColorsOn = false, patchMaskOn = false, patchLinesOn = false;
PositionGrid patchGrid; // the grid the patches' vertices were packed with
size_t patchBytes = 0;
+ // A mesh with a micro level (core/Micro.h) draws through this instead of the buffers above.
+ std::shared_ptr<MicroRenderer> micro;
+ size_t microDrawn = 0;
};
MeshSlot& slot(uint32_t id); // created on first use
static void freeSlot(MeshSlot& s);
@@ -263,8 +273,9 @@ private:
showMask = -1, groups = -1, matcap = -1, matcapCavity = -1, dim = -1, primBase = -1, hasPaint = -1,
normalFlipY = -1, twoSided = -1;
};
- static constexpr int kPaint = 1, kPrim = 2, kTextured = 4, kNormalMap = 8, kFlat = 16;
- MeshProgram programs_[32];
+ static constexpr int kPaint = 1, kPrim = 2, kTextured = 4, kNormalMap = 8, kFlat = 16, kMicro = 32;
+ MeshProgram programs_[64];
+ void drawMicro(const MeshSlot& s, bool active, bool flat, const RenderSettings& settings);
std::string programError_;
const MeshProgram* meshProgram(int features);
bool vertexIdHasBase_ = true; // gl_VertexID includes the base vertex (checked at init; else per-cluster draws)