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
Micro-displacement levels: core module, brushes, undo, projects (format 7) and a headless benchmark
islandmed83b535935392
diff --git a/CMakeLists.txt b/CMakeLists.txtindex ff6dc1f0..5af469bb 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -68,6 +68,9 @@ add_library(sculptforge_core STATICsrc/core/Texture.cppsrc/core/TextureCommands.cppsrc/core/Multires.cpp+ src/core/Micro.cpp+ src/core/MicroSculpt.cpp+ src/core/MicroCommands.cppsrc/core/MultiresCommands.cppsrc/core/AutoUv.cppsrc/core/TextureTransfer.cppdiff --git a/src/app/main.cpp b/src/app/main.cppindex 654bc888..9bc93e37 100644--- a/src/app/main.cpp+++ b/src/app/main.cpp@@ -51,6 +51,8 @@ void usage() {" --bench-no-project Skip the project save / open (it needs twice the memory)\n"" --bench-view Benchmark only what the viewport costs (uploads, orbit)\n"" --bench-dyntopo Benchmark dynamic topology strokes (e.g. --bench-sizes 0.25,1,4)\n"+ " --bench-micro Benchmark micro-displacement levels (sizes = micro triangles, e.g. 33,100,300)\n"+ " --bench-micro-level N Micro level for --bench-micro (default 4: 256 per base triangle)\n"" --bench-out FILE Write the benchmark report (Markdown) to FILE\n"" --log-dir DIR Write sculptforge.log to DIR instead of the user data folder\n"" --crash-test KIND Crash on purpose (segv, abort or throw) to test the crash note in the log");diff --git a/src/cli/main.cpp b/src/cli/main.cppindex dcd9bc4e..d7de1cc4 100644--- a/src/cli/main.cpp+++ b/src/cli/main.cpp@@ -39,6 +39,8 @@ void usage() {" --bench-no-project Skip the project save / open (it needs twice the memory)\n"" --bench-view Benchmark only what the viewport costs (uploads, orbit)\n"" --bench-dyntopo Benchmark dynamic topology strokes (e.g. --bench-sizes 0.25,1,4)\n"+ " --bench-micro Benchmark micro-displacement levels (sizes = micro triangles, e.g. 33,100,300)\n"+ " --bench-micro-level N Micro level for --bench-micro (default 4: 256 per base triangle)\n"" --bench-out FILE Write the benchmark report (Markdown) to FILE\n"" -h, --help Show this help\n""\n"diff --git a/src/core/Benchmark.cpp b/src/core/Benchmark.cppindex 393722e5..f5f4bf64 100644--- a/src/core/Benchmark.cpp+++ b/src/core/Benchmark.cpp@@ -5,6 +5,7 @@#include "core/BrushRecipe.h"#include "core/Commands.h"#include "core/Document.h"+#include "core/Micro.h"#include "core/Multires.h"#include "core/Polypaint.h"#include "core/Primitives.h"@@ -13,6 +14,7 @@#include "core/UploadOrder.h"#include <algorithm>+#include <bit>#include <chrono>#include <cmath>#include <cstdio>@@ -254,6 +256,12 @@ bool parseBenchArg(int argc, char** argv, int& i, BenchCommandLine& cl) {} else if (a == "--bench-dyntopo") {cl.options.dyntopo = true;cl.options.projectRoundTrip = false;+ } else if (a == "--bench-micro") {+ cl.run = true;+ cl.options.micro = true;+ } else if (a == "--bench-micro-level") {+ cl.options.micro = true;+ cl.options.microLevel = std::clamp(std::atoi(next().c_str()), 1, 7);} else if (a == "--bench-out") {cl.outPath = next();} else {@@ -355,10 +363,236 @@ std::string runDyntopoBenchmark(const BenchOptions& o, const BenchGpu* gpu) {return md.str();}+// Micro-displacement levels (core/Micro.h): a base sphere with subdivision levels, divided to micro level+// o.microLevel, so the micro triangle count is each size. Strokes as in the mesh benchmark (X symmetry, dabs+// along a line over the front); "shading" is what the renderer recomputes for a dab (normals, curvature) on the+// CPU before its upload.+std::string runMicroBenchmark(const BenchOptions& o, const BenchGpu* gpu) {+ auto log = [&](const std::string& s) {+ if (o.log) o.log(s);+ };+ std::ostringstream md;+ md << "Threads: " << ThreadPool::shared().threads();+ if (gpu && !gpu->description.empty()) md << ", GPU: " << gpu->description;+ md << ". Micro level " << o.microLevel << " (" << (1 << (2 * o.microLevel))+ << " micro triangles per base triangle). Brushes use X symmetry (two dabs per step), radius 0.12 on a unit sphere "+ "unless noted, "+ << o.dabsPerStroke << " dabs per stroke. Times in milliseconds.\n\n";+ const std::vector<BenchBrush> brushes = {+ {"Standard", Kind::Brush, BrushType::Standard},+ {"Standard (large, r 0.4)", Kind::Brush, BrushType::Standard, 0.4f},+ {"Clay", Kind::Brush, BrushType::Clay},+ {"ClayBuildup", Kind::Brush, BrushType::ClayBuildup},+ {"Smooth", Kind::Brush, BrushType::Smooth},+ {"Smooth (large, r 0.4)", Kind::Brush, BrushType::Smooth, 0.4f},+ {"Inflate", Kind::Brush, BrushType::Inflate},+ {"Flatten", Kind::Brush, BrushType::Flatten},+ {"Pinch", Kind::Brush, BrushType::Pinch},+ {"Crease", Kind::Brush, BrushType::Crease},+ {"Layer", Kind::Brush, BrushType::Layer},+ {"Move", Kind::Move, BrushType::Move},+ {"Mask", Kind::Mask},+ };+ for (double sizeM : o.sizesMillions) {+ const size_t target = size_t(sizeM * 1e6);+ const size_t baseTarget = std::max<size_t>(target >> (2 * o.microLevel), 1000);+ log("Building a " + millions(double(target)) + " micro triangle sphere (" + millions(double(baseTarget)) + " base)...");+ Document doc;+ const size_t rss0 = resetPeakResidentBytes();+ auto t = Clock::now();+ doc.mesh = makeBenchSphere(baseTarget);+ const double baseMs = msSince(t);+ t = Clock::now();+ doc.bvh.build(doc.mesh);+ const double bvhMs = msSince(t);+ Mesh& m = doc.mesh;+ const size_t rssBase = residentBytes();+ std::string err;+ t = Clock::now();+ if (!microDivide(m, o.microLevel, err)) {+ md << "### " << millions(double(target)) << ": " << err << "\n\n";+ continue;+ }+ const double divideMs = msSince(t);+ const MicroMesh& mm = *m.micro;+ const double nt = double(mm.microTriangles()), nv = double(mm.microVertices());+ // The renderer's first full shading pass (into a scratch tile per thread: no GPU here).+ MicroShader shader;+ std::vector<uint32_t> written;+ auto scratch = [&](uint32_t) -> uint32_t* {+ thread_local std::vector<uint32_t> tile;+ tile.resize(mm.samples);+ return tile.data();+ };+ t = Clock::now();+ shader.shade(m, {}, true, written, scratch);+ const double shadeAllMs = msSince(t);+ if (!gpu) m.micro->clearDirty();+ double uploadAll = 0;+ if (gpu && gpu->upload) uploadAll = gpu->upload(m);+ const size_t rss = residentBytes(), peak = peakResidentBytes();+ md << "### " << millions(nt) << " micro triangles (" << millions(nv) << " micro vertices; base "+ << millions(double(m.triangleCount())) << " triangles, " << subdivLevelCount(m) << " subdivision levels)\n\n";+ md << "| Setup | |\n|---|---|\n";+ md << "| Base sphere (Divide) | " << fmt("%.0f", baseMs) << " |\n";+ md << "| BVH build (base) | " << fmt("%.0f", bvhMs) << " |\n";+ md << "| Divide to micro level | " << fmt("%.0f", divideMs) << " |\n";+ md << "| Shading, whole surface (CPU) | " << fmt("%.0f", shadeAllMs) << " |\n";+ if (gpu) md << "| First GPU upload | " << fmt("%.0f", uploadAll) << " |\n";+ if (gpu && gpu->gpuBytes) {+ const double b = double(gpu->gpuBytes());+ md << "| GPU memory (buffers) | " << fmt("%.0f MB", b / 1e6) << " = " << fmt("%.2f", b / nt) << " B/micro triangle |\n";+ }+ md << "| Micro level (displacements, ranges, topology) | " << fmt("%.0f MB", double(mm.bytes()) / 1e6) << " = "+ << fmt("%.2f", double(mm.bytes()) / nt) << " B/micro triangle, " << fmt("%.2f", double(mm.bytes()) / nv)+ << " B/micro vertex |\n";+ md << "| Base mesh + BVH + levels | "+ << fmt("%.0f MB", double(m.memoryBytes() + doc.bvh.memoryBytes() + subdivBytes(m)) / 1e6) << " |\n";+ if (rss)+ md << "| Process memory (RSS) | " << fmt("%.0f MB", double(rss) / 1e6) << " (micro level and shading: +"+ << fmt("%.0f MB", double(rss - std::min(rss, rssBase)) / 1e6) << "; everything: +"+ << fmt("%.0f MB", double(rss - std::min(rss, rss0)) / 1e6) << " = "+ << fmt("%.2f", double(rss - std::min(rss, rss0)) / nt) << " B/micro triangle) |\n";+ if (peak > rss0) md << "| Peak (RSS) | " << fmt("%.0f MB", double(peak) / 1e6) << " |\n";+ md << "\n";++ md << "| Brush | points/dab | pick | find + undo tiles | kernel | stitch | shading | " << (gpu ? "GPU upload | " : "")+ << "**dab total** | stroke end | undo | redo | undo step |\n";+ md << "|---|---:|---:|---:|---:|---:|---:|" << (gpu ? "---:|" : "") << "---:|---:|---:|---:|---:|\n";+ for (const BenchBrush& b : brushes) {+ if (!o.brushFilter.empty() && b.name.find(o.brushFilter) == std::string::npos) continue;+ log(" " + b.name);+ Sculptor& sc = doc.sculptor;+ sc.beginStroke(m, b.name);+ Symmetry sym;+ MicroStroke& ms = sc.microStroke();+ const double f0 = ms.findMs, k0 = ms.kernelMs, s0 = ms.stitchMs;+ const uint64_t p0 = ms.points;+ double pick = 0, shade = 0, upload = 0;+ int dabs = 0;+ const float step = 0.15f * b.radius;+ const auto stroke0 = Clock::now();+ std::vector<uint32_t> dirty;+ for (int i = 0; i < o.dabsPerStroke; ++i) {+ const float x = 0.15f + std::fmod(float(i) * step, 0.6f), y = 0.2f + 0.1f * std::sin(float(i) * 0.3f);+ auto tp = Clock::now();+ RayHit hit;+ const bool ok = surfaceRaycast(m, doc.bvh, glm::vec3(x, y, 5.0f), glm::vec3(0, 0, -1), hit);+ pick += msSince(tp);+ if (!ok) continue;+ DabParams p;+ p.center = hit.position;+ p.viewDir = glm::vec3(0, 0, -1);+ p.radius = b.radius;+ p.strength = 0.5f;+ switch (b.kind) {+ case Kind::Move:+ if (i == 0) sc.beginGrab(m, doc.bvh, p, sym);+ else sc.grab(m, doc.bvh, glm::vec3(0.0f, 0.0f, 0.002f));+ break;+ case Kind::Mask: sc.dabMask(m, doc.bvh, p, sym); break;+ default: sc.dab(m, doc.bvh, b.type, p, sym); break;+ }+ // What the renderer does next: the shading of what changed (and its neighbours), then the upload.+ tp = Clock::now();+ if (gpu && gpu->upload) {+ upload += gpu->upload(m); // (the renderer shades inside its upload)+ } else {+ MicroMesh& live = *m.micro;+ dirty.clear();+ for (size_t w = 0; w < live.dirtyBits.size(); ++w)+ for (uint64_t bits = live.dirtyBits[w]; bits; bits &= bits - 1)+ dirty.push_back(uint32_t(w * 64 + size_t(std::countr_zero(bits))));+ shader.shade(m, dirty, live.allDirty, written, scratch);+ live.clearDirty();+ shade += msSince(tp);+ }+ ++dabs;+ }+ const double total = msSince(stroke0);+ const double d = std::max(dabs, 1);+ auto te = Clock::now();+ UndoRecord r = sc.endStroke();+ const double endMs = msSince(te);+ const size_t undoBytes = r.approxBytes();+ doc.undo.push(std::move(r));+ te = Clock::now();+ doc.undo.undo(m, doc.bvh);+ const double undoMs = msSince(te);+ if (gpu && gpu->upload) gpu->upload(m);+ te = Clock::now();+ doc.undo.redo(m, doc.bvh);+ const double redoMs = msSince(te);+ if (gpu && gpu->upload) gpu->upload(m);+ else m.micro->clearDirty();+ md << "| " << b.name << " | " << millions(double(ms.points - p0) / d) << " | " << fmt("%.2f", pick / d) << " | "+ << fmt("%.2f", (ms.findMs - f0) / d) << " | " << fmt("%.2f", (ms.kernelMs - k0) / d) << " | "+ << fmt("%.2f", (ms.stitchMs - s0) / d) << " | " << (gpu ? std::string("(in upload)") : fmt("%.2f", shade / d)) << " | ";+ if (gpu) md << fmt("%.2f", upload / d) << " | ";+ md << "**" << fmt("%.2f", total / d) << "** | " << fmt("%.1f", endMs) << " | " << fmt("%.1f", undoMs) << " | "+ << fmt("%.1f", redoMs) << " | " << fmt("%.1f MB", double(undoBytes) / 1e6) << " |\n";+ }+ md << "\n";+ md << "| Operation | ms |\n|---|---:|\n";+ {+ log(" surface noise (whole surface)");+ t = Clock::now();+ microNoise(m, 0.002f, 60.0f);+ md << "| Surface noise, every point | " << fmt("%.0f", msSince(t)) << " |\n";+ if (gpu && gpu->upload) {+ t = Clock::now();+ gpu->upload(m);+ md << "| GPU upload after it (shading + displacements) | " << fmt("%.0f", msSince(t)) << " |\n";+ } else {+ m.micro->clearDirty();+ }+ }+ if (o.projectRoundTrip) {+ namespace fs = std::filesystem;+ std::error_code ec;+ const fs::path dir = o.projectDir.empty() ? fs::temp_directory_path(ec) : fs::path(o.projectDir);+ const std::string path = (dir / "sculptforge-bench-micro.sfproj").string();+ log(" project save / open");+ t = Clock::now();+ const bool saved = saveProject(path, doc, err);+ const double saveMs = msSince(t);+ const double fileMb = saved ? double(fs::file_size(path, ec)) / 1e6 : 0.0;+ Document loaded;+ t = Clock::now();+ const bool opened = saved && loadProject(path, loaded, err);+ const double openMs = msSince(t);+ fs::remove(path, ec);+ md << "| Save project (" << fmt("%.0f MB", fileMb) << ") | " << (saved ? fmt("%.0f", saveMs) : "failed: " + err) << " |\n";+ md << "| Open project | " << (opened ? fmt("%.0f", openMs) : "failed: " + err) << " |\n";+ }+ if (gpu && gpu->orbitFrameMs) {+ log(" orbit");+ struct Orbit {+ int samples;+ bool moving;+ const char* name;+ };+ for (const Orbit& ob : {Orbit{4, false, "4x antialiasing"}, Orbit{1, false, "no antialiasing"},+ Orbit{1, true, "Fast Navigation (no antialiasing, coarser)"}}) {+ const double f = gpu->orbitFrameMs(m, ob.samples, ob.moving);+ md << "| Orbit: frame time, " << ob.name << " | " << fmt("%.1f", f) << " (" << fmt("%.0f", 1000.0 / std::max(f, 1e-3))+ << " fps) |\n";+ if (gpu->drawnTriangles && ob.samples == 1)+ md << "| Orbit: triangles drawn" << (ob.moving ? " (moving)" : "") << " | " << millions(double(gpu->drawnTriangles()))+ << " |\n";+ }+ }+ md << "\n";+ if (o.partial) o.partial(md.str());+ }+ return md.str();+}+} // namespacestd::string runBenchmark(const BenchOptions& o, const BenchGpu* gpu) {if (o.dyntopo) return runDyntopoBenchmark(o, gpu);+ if (o.micro) return runMicroBenchmark(o, gpu);auto log = [&](const std::string& s) {if (o.log) o.log(s);};diff --git a/src/core/Benchmark.h b/src/core/Benchmark.hindex 985d040d..b6914695 100644--- a/src/core/Benchmark.h+++ b/src/core/Benchmark.h@@ -46,13 +46,17 @@ struct BenchOptions {bool viewOnly = false;// Dynamic topology instead (--bench-dyntopo): spheres without subdivision levels, strokes that remesh.bool dyntopo = false;+ // Micro-displacement levels instead (--bench-micro, core/Micro.h): sizes are micro triangles (millions), on+ // a base sphere at micro level `microLevel` (4: 256 micro triangles per base triangle).+ bool micro = false;+ int microLevel = 4;std::function<void(const std::string&)> log; // progress lines (optional)std::function<void(const std::string&)> partial; // the report so far, after each size (optional)};// Command-line options shared by sculptforge-cli and the app: --bench, --bench-sizes 4,16,32 (millions of// triangles), --bench-dabs N, --bench-no-project (skip saving / opening, which needs twice the memory),-// --bench-brushes TEXT (only the rows whose name contains TEXT), --bench-view (only the viewport's costs), --bench-dyntopo (dynamic topology strokes), --bench-out FILE. parseBenchArg returns true when argv[i] was one of them+// --bench-brushes TEXT (only the rows whose name contains TEXT), --bench-view (only the viewport's costs), --bench-dyntopo (dynamic topology strokes), --bench-micro (micro-displacement levels; --bench-micro-level N), --bench-out FILE. parseBenchArg returns true when argv[i] was one of them// (advancing i past its value).struct BenchCommandLine {bool run = false;diff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex 5af26762..2e653dbe 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -14,6 +14,7 @@#include "core/ImageTo3D.h"#include "core/Masking.h"#include "core/Multires.h"+#include "core/Micro.h"#include "core/MeshTransform.h"#include "core/PathStroke.h"#include "core/Polygroups.h"@@ -769,6 +770,7 @@ CommandRegistry::CommandRegistry() {registerPolygroupCommands(*this);registerSubToolCommands(*this);registerSubdivCommands(*this); // subdiv_* (core/MultiresCommands.cpp)+ registerMicroCommands(*this); // micro_* (core/MicroCommands.cpp)registerDyntopoCommands(*this); // dyntopo (core/DyntopoCommands.cpp)registerSculptableCommands(*this); // splat_to_mesh, face_guides (core/Sculptable.h)registerTransformCommands(*this); // transform (core/MeshTransform.h)diff --git a/src/core/Masking.cpp b/src/core/Masking.cppindex 8ed72942..4575fc91 100644--- a/src/core/Masking.cpp+++ b/src/core/Masking.cpp@@ -175,6 +175,15 @@ void Sculptor::dabMask(Mesh& mesh, const BVH& bvh, const DabParams& p, Symmetryif (!active_) return;const float s = std::clamp(p.strength, 0.0f, 1.0f) * std::clamp(p.pressure, 0.0f, 1.0f);if (s <= 0.0f) return;+ if (microReady(mesh)) { // the micro level's own mask, per grid point (core/MicroSculpt.cpp)+ const double k0 = micro_.findMs + micro_.kernelMs + micro_.stitchMs;+ for (const glm::vec3& mirror : mirrors(sym))+ micro_.dab(mesh, bvh, BrushType::Standard, p.center * mirror, p.viewDir * mirror, p.radius, 1.0f, p.invert, p.focal,+ p.alphaUp * mirror, true, s);+ timings.kernelMs += micro_.findMs + micro_.kernelMs + micro_.stitchMs - k0;+ ++timings.dabs;+ return;+ }auto clock = std::chrono::steady_clock::now();std::vector<float>& mask = mesh.ensureMask();for (const glm::vec3& mirror : mirrors(sym)) {diff --git a/src/core/Mesh.cpp b/src/core/Mesh.cppindex 2dc24c97..a08344a7 100644--- a/src/core/Mesh.cpp+++ b/src/core/Mesh.cpp@@ -2,6 +2,7 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "core/Mesh.h"#include "core/Multires.h"+#include "core/Micro.h"#include "core/AtomicRef.h"#include "core/Prefetch.h"#include "core/ThreadPool.h"@@ -171,6 +172,7 @@ void Mesh::sanitizeAttributes() {if (!anyQuad) clearQuads();sanitizePaintLayers(*this);if (multires && !subdivMatches(*this)) multires.reset();+ if (micro && !microMatches(*this)) micro.reset();}void Mesh::rebuildTopology() {diff --git a/src/core/Mesh.h b/src/core/Mesh.hindex 2fe4cdf7..0ad059b0 100644--- a/src/core/Mesh.h+++ b/src/core/Mesh.h@@ -22,6 +22,7 @@ struct PaintTexture;struct MultiresStack;struct SubdivTopology;struct ImplicitAdjacency;+struct MicroMesh;// The vertices or triangles around a vertex (Mesh::neighbors, Mesh::vertexTriangles), in ascending order: a view// of the mesh's adjacency lists or, where the mesh's adjacency is implicit, the list itself. Use it like a span@@ -192,6 +193,12 @@ public:// copies of the mesh. Null = a plain mesh. sanitizeAttributes() drops it if the topology no longer fits.std::shared_ptr<MultiresStack> multires;+ // Micro-displacement level (core/Micro.h): above this mesh (the base, its highest subdivision level), a grid of+ // scalar displacements per triangle that the brushes and the renderer use instead of the mesh. Shared+ // copy-on-write by copies of the mesh (mutableMicro). Null = none. sanitizeAttributes() drops it if the+ // triangle or vertex count changes.+ std::shared_ptr<MicroMesh> micro;+// ZSpheres (core/ZSpheres.h): not empty = a ZSphere SubTool, whose triangles are made from this armature (the// spheres and their links, or the skin while `zspherePreview`). Copies, undo steps and projects carry it.std::vector<ZSphere> zspheres;diff --git a/src/core/Micro.cpp b/src/core/Micro.cppnew file mode 100644index 00000000..80c2e157--- /dev/null+++ b/src/core/Micro.cpp@@ -0,0 +1,1133 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Micro-displacement levels (core/Micro.h): the data, evaluation, Divide / Delete, picking, the renderer's+// shading, baking down and displacement maps. The brushes are in MicroSculpt.cpp, the commands in+// MicroCommands.cpp.+#include "core/Micro.h"++#include "core/BakeImage.h"+#include "core/BVH.h"+#include "core/Multires.h"+#include "core/ThreadPool.h"++#include <algorithm>+#include <atomic>+#include <cmath>+#include <cstring>+#include <limits>+#include <mutex>++#if defined(_WIN32)+#define NOMINMAX+#include <windows.h>+#else+#include <unistd.h>+#endif++namespace sf {++// ---------------------------------------------------------------------------+// MicroMesh+// ---------------------------------------------------------------------------++size_t MicroMesh::microVertices() const {+ size_t edges = size_t(baseTriangles) * 3 / 2;+ if (edgeNeighbor.size() == size_t(baseTriangles) * 3) {+ size_t boundary = 0;+ for (uint32_t e : edgeNeighbor) boundary += e == kNone;+ edges = (size_t(baseTriangles) * 3 + boundary) / 2;+ }+ const size_t interior = n >= 2 ? size_t(n - 1) * (n - 2) / 2 : 0;+ return size_t(baseVertices) + edges * (n - 1) + size_t(baseTriangles) * interior;+}++size_t MicroMesh::bytes() const {+ return disp.capacity() * sizeof(int16_t) + mask.capacity() + triRange.capacity() * sizeof(uint16_t) ++ edgeNeighbor.capacity() * sizeof(uint32_t) + dirtyBits.capacity() * sizeof(uint64_t);+}++void MicroMesh::clearDirty() {+ std::fill(dirtyBits.begin(), dirtyBits.end(), 0);+ allDirty = false;+ maskDirty = false;+ rescaled = false;+}++int MicroMesh::widen(float need) {+ if (!(need > rangeWorld())) return 1;+ int doublings = 2;+ while (need > 32767.0f * step * float(1 << doublings) && doublings < 12) ++doublings;+ const int div = 1 << doublings;+ poolFor(disp.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) disp[i] = int16_t(int(disp[i]) / div);+ }, 1 << 16);+ for (uint16_t& v : triRange) v = uint16_t(std::min(int(v) / div + 1, 32767));+ rangeMax = uint16_t(std::min(int(rangeMax) / div + 1, 32767));+ step *= float(div);+ rescaled = true;+ ++revision;+ return div;+}++void MicroMesh::ensureTopology(const Mesh& base) {+ const size_t nt = base.triangleCount();+ if (edgeNeighbor.size() == nt * 3 && nt == baseTriangles) return;+ edgeNeighbor.assign(nt * 3, kNone);+ poolFor(nt, [&](size_t b, size_t e) {+ for (size_t t = b; t < e; ++t) {+ const glm::uvec3 tri = base.triangles[t];+ for (int k = 0; k < 3; ++k) {+ const uint32_t a = tri[k], c = tri[(k + 1) % 3];+ for (uint32_t u : base.vertexTriangles(a)) {+ if (u == t) continue;+ const glm::uvec3 o = base.triangles[u];+ int f = -1;+ for (int q = 0; q < 3 && f < 0; ++q)+ if ((o[q] == a && o[(q + 1) % 3] == c) || (o[q] == c && o[(q + 1) % 3] == a)) f = q;+ if (f >= 0) {+ edgeNeighbor[t * 3 + size_t(k)] = (u << 2) | uint32_t(f);+ break;+ }+ }+ }+ }+ }, 1 << 12);+}++// ---------------------------------------------------------------------------+// Evaluation+// ---------------------------------------------------------------------------++void MicroTriangle::set(const Mesh& base, uint32_t tri, uint32_t segments) {+ const glm::uvec3 t = base.triangles[tri];+ uint8_t o[3] = {0, 1, 2};+ if (t[o[0]] > t[o[1]]) std::swap(o[0], o[1]);+ if (t[o[1]] > t[o[2]]) std::swap(o[1], o[2]);+ if (t[o[0]] > t[o[1]]) std::swap(o[0], o[1]);+ for (int k = 0; k < 3; ++k) {+ slot[k] = o[k];+ p[k] = base.positions[t[o[k]]];+ nrm[k] = base.normals[t[o[k]]];+ }+ n = segments;+ invN = 1.0f / float(segments);+}++// The same operations, in the same order, as the renderer's vertex shader (render/MicroRenderer.cpp): corners in+// ascending vertex order, so a point on a shared edge (whose third weight is exactly 0) comes out bit-identical+// from both triangles.+void MicroTriangle::evalWeights(const float wc[3], glm::vec3& surface, glm::vec3& normal) const {+ const float w0 = wc[slot[0]], w1 = wc[slot[1]], w2 = wc[slot[2]];+ glm::vec3 f = p[0] * w0;+ f += p[1] * w1;+ f += p[2] * w2;+ glm::vec3 nn = nrm[0] * w0;+ nn += nrm[1] * w1;+ nn += nrm[2] * w2;+ // Phong tessellation: the flat point pulled towards each corner's tangent plane.+ glm::vec3 pull = nrm[0] * (w0 * glm::dot(f - p[0], nrm[0]));+ pull += nrm[1] * (w1 * glm::dot(f - p[1], nrm[1]));+ pull += nrm[2] * (w2 * glm::dot(f - p[2], nrm[2]));+ surface = f - pull * MicroMesh::kPhong;+ const float len = glm::length(nn);+ normal = len > 1e-20f ? nn / len : glm::vec3(0.0f, 0.0f, 1.0f);+}++void MicroTriangle::eval(uint32_t i, uint32_t j, glm::vec3& surface, glm::vec3& normal) const {+ const float w[3] = {float(n - i - j) * invN, float(i) * invN, float(j) * invN};+ evalWeights(w, surface, normal);+}++glm::vec3 MicroTriangle::flat(uint32_t i, uint32_t j) const {+ const float wc[3] = {float(n - i - j) * invN, float(i) * invN, float(j) * invN};+ glm::vec3 f = p[0] * wc[slot[0]];+ f += p[1] * wc[slot[1]];+ f += p[2] * wc[slot[2]];+ return f;+}++int microLevel(const Mesh& m) { return m.micro ? m.micro->level : 0; }+size_t microTriangleCount(const Mesh& m) { return m.micro ? m.micro->microTriangles() : 0; }+size_t microBytes(const Mesh& m) { return m.micro ? m.micro->bytes() : 0; }++std::string microText(const Mesh& m) {+ if (!m.micro) return {};+ char buf[64];+ std::snprintf(buf, sizeof buf, "Micro %d (%.1fM)", m.micro->level, double(m.micro->microTriangles()) / 1e6);+ return buf;+}++bool microMatches(const Mesh& m) {+ return m.micro && m.micro->baseTriangles == m.triangleCount() && m.micro->baseVertices == m.vertexCount();+}++MicroMesh& mutableMicro(Mesh& m) {+ if (m.micro.use_count() > 1) m.micro = std::make_shared<MicroMesh>(*m.micro);+ return *m.micro;+}++size_t microMaxTriangles() {+ size_t memory = 0;+#if defined(_WIN32)+ MEMORYSTATUSEX status{};+ status.dwLength = sizeof status;+ if (GlobalMemoryStatusEx(&status)) memory = size_t(status.ullTotalPhys);+#elif defined(_SC_PHYS_PAGES)+ const long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGESIZE);+ if (pages > 0 && page > 0) memory = size_t(pages) * size_t(page);+#endif+ // Per micro triangle about 0.6 grid points (level 4) x (2 bytes + 1 of mask + 6 on the GPU) + undo: ~6 bytes.+ return std::clamp<size_t>(memory / 10 * 5 / 6, 100'000'000, size_t(8'000'000'000));+}++int microLevelFor(const Mesh& m, size_t target) {+ const double nt = double(std::max<size_t>(m.triangleCount(), 1));+ int best = 1;+ double bestErr = 1e300;+ for (int l = 1; l <= MicroMesh::kMaxLevel; ++l) {+ const double err = std::abs(std::log(nt * std::pow(4.0, l) / double(std::max<size_t>(target, 1))));+ if (err < bestErr) bestErr = err, best = l;+ }+ return best;+}++glm::vec3 microPoint(const Mesh& m, uint32_t tri, uint32_t i, uint32_t j) {+ const MicroMesh& mm = *m.micro;+ MicroTriangle T;+ T.set(m, tri, mm.n);+ glm::vec3 s, nn;+ T.eval(i, j, s, nn);+ return s + nn * (float(mm.disp[size_t(tri) * mm.samples + MicroMesh::index(i, j, mm.n)]) * mm.step);+}++namespace {++// The micro triangle holding barycentric point w of a base triangle: its three grid points (i, j) and weights.+struct Cell {+ uint32_t i[3], j[3];+ float w[3];+};+Cell cellAt(const float wc[3], uint32_t n) {+ const float fi = std::clamp(wc[1], 0.0f, 1.0f) * float(n), fj = std::clamp(wc[2], 0.0f, 1.0f) * float(n);+ uint32_t i0 = std::min(uint32_t(fi), n - 1), j0 = std::min(uint32_t(fj), n - 1);+ if (i0 + j0 > n - 1) { // outside the last full cell along the hypotenuse+ if (fi >= fj) i0 = n - 1 - j0;+ else j0 = n - 1 - i0;+ }+ const float a = fi - float(i0), b = fj - float(j0);+ Cell c;+ if (a + b <= 1.0f || i0 + j0 + 2 > n) {+ c.i[0] = i0, c.j[0] = j0, c.i[1] = i0 + 1, c.j[1] = j0, c.i[2] = i0, c.j[2] = j0 + 1;+ c.w[0] = 1.0f - a - b, c.w[1] = a, c.w[2] = b;+ } else {+ c.i[0] = i0 + 1, c.j[0] = j0, c.i[1] = i0 + 1, c.j[1] = j0 + 1, c.i[2] = i0, c.j[2] = j0 + 1;+ c.w[0] = 1.0f - b, c.w[1] = a + b - 1.0f, c.w[2] = 1.0f - a;+ }+ return c;+}++} // namespace++glm::vec3 microPointAt(const Mesh& m, uint32_t tri, const float wc[3], glm::vec3* normal) {+ const MicroMesh& mm = *m.micro;+ MicroTriangle T;+ T.set(m, tri, mm.n);+ const Cell c = cellAt(wc, mm.n);+ glm::vec3 q[3];+ for (int k = 0; k < 3; ++k) {+ glm::vec3 s, nn;+ T.eval(c.i[k], c.j[k], s, nn);+ q[k] = s + nn * (float(mm.disp[size_t(tri) * mm.samples + MicroMesh::index(c.i[k], c.j[k], mm.n)]) * mm.step);+ }+ if (normal) {+ const glm::vec3 g = glm::cross(q[1] - q[0], q[2] - q[0]);+ const float len = glm::length(g);+ *normal = len > 0.0f ? g / len : glm::vec3(0.0f, 0.0f, 1.0f);+ }+ return q[0] * c.w[0] + q[1] * c.w[1] + q[2] * c.w[2];+}++// ---------------------------------------------------------------------------+// Divide / Delete+// ---------------------------------------------------------------------------++namespace {++// The most a base triangle's Phong surface leaves its plane (an upper bound).+float triangleBulge(const MicroTriangle& T) {+ float e = 0.0f;+ for (int k = 0; k < 3; ++k)+ for (int q = 0; q < 3; ++q) e = std::max(e, std::abs(glm::dot(T.p[q] - T.p[k], T.nrm[k])));+ return e * MicroMesh::kPhong;+}++} // namespace++bool microDivide(Mesh& m, int level, std::string& error) {+ if (level < 1 || level > MicroMesh::kMaxLevel) {+ error = "Micro level must be 1 to " + std::to_string(MicroMesh::kMaxLevel);+ return false;+ }+ const size_t nt = m.triangleCount();+ if (nt == 0) {+ error = "Nothing to divide";+ return false;+ }+ if (m.micro) {+ error = "This SubTool already has a micro level (Delete micro or Bake it first)";+ return false;+ }+ if (subdivLevelCount(m) > 0 && subdivCurrentLevel(m) != subdivLevelCount(m) - 1) {+ error = "Go to the highest subdivision level first: the micro level goes on top of it";+ return false;+ }+ if (!m.zspheres.empty()) {+ error = "ZSphere SubTools can't have a micro level (make an adaptive skin first)";+ return false;+ }+ if (!m.layers.empty()) {+ error = "Sculpt layers can't carry a micro level yet: bake or delete the layers first";+ return false;+ }+ if (nt > (size_t(1) << 30)) {+ error = "Too many base triangles for a micro level";+ return false;+ }+ const size_t micro = nt << (2 * level);+ if (micro > microMaxTriangles()) {+ char buf[200];+ std::snprintf(buf, sizeof buf, "%.0fM micro triangles is more than this computer allows (%.0fM): pick a lower micro level",+ double(micro) / 1e6, double(microMaxTriangles()) / 1e6);+ error = buf;+ return false;+ }+ if (m.normals.size() != m.vertexCount()) m.recomputeAllNormals();+ auto mm = std::make_shared<MicroMesh>();+ mm->level = level;+ mm->n = 1u << level;+ mm->samples = (mm->n + 1) * (mm->n + 2) / 2;+ mm->baseTriangles = uint32_t(nt);+ mm->baseVertices = uint32_t(m.vertexCount());+ mm->disp.assign(nt * mm->samples, 0);+ mm->triRange.assign(nt, 0);+ mm->dirtyBits.assign((nt + 63) / 64, 0);+ mm->ensureTopology(m);+ // Edge length and bulge, in parallel blocks (combined in order: deterministic).+ const size_t block = 1 << 14, blocks = (nt + block - 1) / block;+ std::vector<double> edgeSum(blocks, 0.0);+ std::vector<float> bulge(blocks, 0.0f);+ poolFor(nt, [&](size_t b, size_t e) {+ double s = 0.0;+ float g = 0.0f;+ MicroTriangle T;+ for (size_t t = b; t < e; ++t) {+ T.set(m, uint32_t(t), mm->n);+ s += double(glm::distance(T.p[0], T.p[1]) + glm::distance(T.p[1], T.p[2]) + glm::distance(T.p[2], T.p[0]));+ g = std::max(g, triangleBulge(T));+ }+ edgeSum[b / block] = s;+ bulge[b / block] = g;+ }, block);+ double total = 0.0;+ for (size_t i = 0; i < blocks; ++i) {+ total += edgeSum[i];+ mm->bulgeMax = std::max(mm->bulgeMax, bulge[i]);+ }+ const float avgEdge = float(total / double(nt * 3));+ // 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->allDirty = true;+ m.micro = std::move(mm);+ m.topologyDirty = true; // the renderer draws it differently+ return true;+}++bool microAttach(Mesh& m, int level, float step, std::vector<int16_t> disp, std::vector<uint8_t> mask, std::string& error) {+ if (level < 1 || level > MicroMesh::kMaxLevel || !(step > 0.0f) || !std::isfinite(step)) {+ error = "Project micro level is invalid";+ return false;+ }+ const size_t nt = m.triangleCount();+ const uint32_t n = 1u << level, S = (n + 1) * (n + 2) / 2;+ if (disp.size() != nt * S || (!mask.empty() && mask.size() != disp.size())) {+ error = "Project micro level doesn't fit its mesh";+ return false;+ }+ if (m.normals.size() != m.vertexCount()) m.recomputeAllNormals();+ auto mm = std::make_shared<MicroMesh>();+ mm->level = level;+ mm->n = n;+ mm->samples = S;+ mm->step = step;+ mm->baseTriangles = uint32_t(nt);+ mm->baseVertices = uint32_t(m.vertexCount());+ mm->disp = std::move(disp);+ mm->mask = std::move(mask);+ mm->triRange.assign(nt, 0);+ mm->dirtyBits.assign((nt + 63) / 64, 0);+ const size_t block = 1 << 12, blocks = (nt + block - 1) / block;+ std::vector<float> bulge(blocks, 0.0f);+ poolFor(nt, [&](size_t b, size_t e) {+ MicroTriangle T;+ float g = 0.0f;+ for (size_t t = b; t < e; ++t) {+ const int16_t* d = mm->disp.data() + t * S;+ int r = 0;+ for (uint32_t k = 0; k < S; ++k) r = std::max(r, std::abs(int(d[k])));+ mm->triRange[t] = uint16_t(std::min(r, 32767));+ T.set(m, uint32_t(t), n);+ g = std::max(g, triangleBulge(T));+ }+ bulge[b / block] = g;+ }, block);+ for (float g : bulge) mm->bulgeMax = std::max(mm->bulgeMax, g);+ for (uint16_t r : mm->triRange) mm->rangeMax = std::max(mm->rangeMax, r);+ mm->ensureTopology(m);+ mm->allDirty = true;+ m.micro = std::move(mm);+ m.topologyDirty = true;+ return true;+}++void microDelete(Mesh& m) {+ if (!m.micro) return;+ m.micro.reset();+ m.topologyDirty = true;+}++// ---------------------------------------------------------------------------+// Picking+// ---------------------------------------------------------------------------++namespace {++bool rayTriangle(const glm::vec3& o, const glm::vec3& d, const glm::vec3& a, const glm::vec3& b, const glm::vec3& c, float& t) {+ const glm::vec3 e1 = b - a, e2 = c - a, pv = glm::cross(d, e2);+ const float det = glm::dot(e1, pv);+ if (std::abs(det) < 1e-30f) return false;+ const float inv = 1.0f / det;+ const glm::vec3 tv = o - a;+ const float u = glm::dot(tv, pv) * inv;+ if (u < 0.0f || u > 1.0f) return false;+ const glm::vec3 qv = glm::cross(tv, e1);+ const float v = glm::dot(d, qv) * inv;+ if (v < 0.0f || u + v > 1.0f) return false;+ t = glm::dot(e2, qv) * inv;+ return t > 0.0f;+}++} // namespace++bool microRaycast(const Mesh& m, const BVH& bvh, const glm::vec3& origin, const glm::vec3& dir, RayHit& hit) {+ if (!microMatches(m)) return bvh.raycast(m, origin, dir, hit);+ const MicroMesh& mm = *m.micro;+ RayHit base;+ if (!bvh.raycast(m, origin, dir, base)) return false;+ const float reach = mm.bulgeMax + float(mm.rangeMax) * mm.step;+ std::vector<uint32_t> cand;+ bvh.queryTriangles(m, base.position, 2.0f * reach + 1e-7f, cand);+ if (std::find(cand.begin(), cand.end(), base.triangle) == cand.end()) cand.push_back(base.triangle);+ constexpr size_t kMaxCandidates = 4096;+ if (cand.size() > kMaxCandidates) { // a huge displacement range: rank by distance and keep the nearest+ std::nth_element(cand.begin(), cand.begin() + kMaxCandidates, cand.end(), [&](uint32_t a, uint32_t b) {+ auto c = [&](uint32_t t) {+ const glm::uvec3 tr = m.triangles[t];+ return glm::distance(base.position, (m.positions[tr.x] + m.positions[tr.y] + m.positions[tr.z]) / 3.0f);+ };+ return c(a) < c(b);+ });+ cand.resize(kMaxCandidates);+ }+ const uint32_t n = mm.n, S = mm.samples;+ struct Best {+ float t = std::numeric_limits<float>::max();+ uint32_t tri = 0;+ glm::vec3 a{0.0f}, b{0.0f}, c{0.0f};+ };+ const size_t block = 4;+ std::vector<Best> best((cand.size() + block - 1) / block);+ poolFor(cand.size(), [&](size_t b0, size_t e0) {+ thread_local std::vector<glm::vec3> P;+ P.resize(S);+ Best bb;+ MicroTriangle T;+ for (size_t ci = b0; ci < e0; ++ci) {+ const uint32_t tri = cand[ci];+ if (m.triangleHidden(tri)) continue;+ T.set(m, tri, n);+ const int16_t* g = mm.disp.data() + size_t(tri) * S;+ uint32_t idx = 0;+ for (uint32_t j = 0; j <= n; ++j)+ for (uint32_t i = 0; i + j <= n; ++i, ++idx) {+ glm::vec3 s, nn;+ T.eval(i, j, s, nn);+ P[idx] = s + nn * (float(g[idx]) * mm.step);+ }+ for (uint32_t j = 0; j < n; ++j) {+ const uint32_t row = MicroMesh::index(0, j, n), next = MicroMesh::index(0, j + 1, n);+ for (uint32_t i = 0; i + j < n; ++i) {+ float t;+ const glm::vec3 &a = P[row + i], &b = P[row + i + 1], &c = P[next + i];+ if (rayTriangle(origin, dir, a, b, c, t) && t < bb.t) bb = {t, tri, a, b, c};+ if (i + j + 1 < n) {+ const glm::vec3 &d = P[next + i + 1];+ if (rayTriangle(origin, dir, b, d, c, t) && t < bb.t) bb = {t, tri, b, d, c};+ }+ }+ }+ }+ best[b0 / block] = bb;+ }, block, 2);+ Best win;+ for (const Best& b : best)+ if (b.t < win.t) win = b;+ if (win.t == std::numeric_limits<float>::max()) {+ // Missed every micro triangle near the base hit (a grazing ray): the micro point under the base hit.+ const glm::uvec3 tr = m.triangles[base.triangle];+ const glm::vec3 a = m.positions[tr.x], b = m.positions[tr.y], c = m.positions[tr.z];+ const glm::vec3 v0 = b - a, v1 = c - a, v2 = base.position - a;+ const float d00 = glm::dot(v0, v0), d01 = glm::dot(v0, v1), d11 = glm::dot(v1, v1), d20 = glm::dot(v2, v0),+ d21 = glm::dot(v2, v1), den = d00 * d11 - d01 * d01;+ float w[3] = {1.0f, 0.0f, 0.0f};+ if (std::abs(den) > 0.0f) {+ w[1] = (d11 * d20 - d01 * d21) / den;+ w[2] = (d00 * d21 - d01 * d20) / den;+ w[0] = 1.0f - w[1] - w[2];+ }+ hit = base;+ hit.position = microPointAt(m, base.triangle, w, &hit.normal);+ hit.t = glm::dot(hit.position - origin, dir);+ return true;+ }+ hit.t = win.t;+ hit.triangle = win.tri;+ hit.position = origin + dir * win.t;+ const glm::vec3 g = glm::cross(win.b - win.a, win.c - win.a);+ const float len = glm::length(g);+ hit.normal = len > 0.0f ? g / len : base.normal;+ return true;+}++bool surfaceRaycast(const Mesh& m, const BVH& bvh, const glm::vec3& origin, const glm::vec3& dir, RayHit& hit) {+ if (m.micro && microMatches(m)) return microRaycast(m, bvh, origin, dir, hit);+ return bvh.raycast(m, origin, dir, hit);+}++// ---------------------------------------------------------------------------+// Shading for the renderer+// ---------------------------------------------------------------------------++namespace {++constexpr int kPartialFloats = 5; // normal sum (3), neighbour displacement sum, neighbour count++uint32_t encodeShade(glm::vec3 nrm, float curvature, uint8_t mask) {+ const float l1 = std::abs(nrm.x) + std::abs(nrm.y) + std::abs(nrm.z);+ glm::vec2 e(0.0f);+ if (l1 > 0.0f) {+ nrm /= l1;+ e = glm::vec2(nrm.x, nrm.y);+ if (nrm.z < 0.0f)+ e = glm::vec2((1.0f - std::abs(nrm.y)) * (nrm.x >= 0.0f ? 1.0f : -1.0f),+ (1.0f - std::abs(nrm.x)) * (nrm.y >= 0.0f ? 1.0f : -1.0f));+ }+ auto q = [](float v) { return uint32_t(std::clamp(std::lround((v * 0.5f + 0.5f) * 255.0f), 0L, 255L)); };+ const float c = std::clamp(curvature, -1.0f, 1.0f);+ const float s = (c >= 0.0f ? 1.0f : -1.0f) * std::sqrt(std::abs(c));+ const uint32_t cq = uint32_t(std::clamp(std::lround(s * 127.0f) + 128L, 1L, 255L));+ return q(e.x) | q(e.y) << 8 | cq << 16 | uint32_t(mask) << 24;+}++// The grid of one base triangle: positions, then per point the sum of the face normals of its micro triangles+// (area weighted) and of its neighbours' displacements, within this triangle.+struct GridWork {+ std::vector<glm::vec3> pos, nsum;+ std::vector<float> dsum, cnt;+ void compute(const Mesh& m, const MicroMesh& mm, uint32_t tri) {+ const uint32_t n = mm.n, S = mm.samples;+ pos.resize(S);+ nsum.assign(S, glm::vec3(0.0f));+ dsum.assign(S, 0.0f);+ cnt.assign(S, 0.0f);+ MicroTriangle T;+ T.set(m, tri, n);+ const int16_t* g = mm.disp.data() + size_t(tri) * S;+ uint32_t idx = 0;+ for (uint32_t j = 0; j <= n; ++j)+ for (uint32_t i = 0; i + j <= n; ++i, ++idx) {+ glm::vec3 s, nn;+ T.eval(i, j, s, nn);+ pos[idx] = s + nn * (float(g[idx]) * mm.step);+ }+ for (uint32_t j = 0; j < n; ++j) {+ const uint32_t row = MicroMesh::index(0, j, n), next = MicroMesh::index(0, j + 1, n);+ for (uint32_t i = 0; i + j < n; ++i) {+ const uint32_t a = row + i, b = row + i + 1, c = next + i;+ const glm::vec3 f = glm::cross(pos[b] - pos[a], pos[c] - pos[a]);+ nsum[a] += f, nsum[b] += f, nsum[c] += f;+ // the lattice edges a-b, a-c, b-c (each once: every edge belongs to one upward triangle)+ const float da = g[a], db = g[b], dc = g[c];+ dsum[a] += db + dc, dsum[b] += da + dc, dsum[c] += da + db;+ cnt[a] += 2.0f, cnt[b] += 2.0f, cnt[c] += 2.0f;+ if (i + j + 1 < n) {+ const uint32_t d = next + i + 1;+ const glm::vec3 f2 = glm::cross(pos[d] - pos[b], pos[c] - pos[b]);+ nsum[b] += f2, nsum[d] += f2, nsum[c] += f2;+ }+ }+ }+ }+};++} // namespace++void MicroShader::shade(const Mesh& m, std::span<const uint32_t> dirty, bool all, std::vector<uint32_t>& written,+ const std::function<uint32_t*(uint32_t tri)>& out) {+ written.clear();+ if (!m.micro) return;+ if (!all) {+ shadeSet(m, dirty, true, written, out);+ return;+ }+ // Everything: in runs of triangles (neighbours by index on levels made by Divide), each with the ring its+ // shared points need, so the edge sums stay a few MB instead of 20 bytes per edge point of the whole mesh.+ const uint32_t nt = m.micro->baseTriangles;+ constexpr uint32_t kRun = 1u << 16;+ std::vector<uint32_t> run;+ for (uint32_t b = 0; b < nt; b += kRun) {+ run.resize(std::min(kRun, nt - b));+ for (uint32_t i = 0; i < run.size(); ++i) run[i] = b + i;+ shadeSet(m, run, false, written, out);+ }+}++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 MicroMesh& mm = *m.micro;+ const uint32_t n = mm.n, S = mm.samples, nt = mm.baseTriangles;+ if (mm.edgeNeighbor.size() != size_t(nt) * 3) return; // (ensureTopology first)+ if (stamp_.size() != nt) {+ stamp_.assign(nt, 0);+ slot_.assign(nt, 0);+ epoch_ = 0;+ }+ if (vstamp_.size() != m.vertexCount()) vstamp_.assign(m.vertexCount(), 0);+ if (epoch_ > 0xFFFFFF00u) {+ std::fill(stamp_.begin(), stamp_.end(), 0);+ std::fill(vstamp_.begin(), vstamp_.end(), 0);+ epoch_ = 0;+ }+ // R = the triangles to write: dirty ones and those sharing a vertex; R2 = R and those sharing a vertex with+ // R (whose edge sums the shared points need). stamp_: epoch + 1 = in R, epoch + 2 = only in R2.+ const uint32_t inR = ++epoch_;+ const uint32_t inR2 = ++epoch_;+ auto vertexRing = [&](const std::vector<uint32_t>& from, std::vector<uint32_t>& into, uint32_t mark, uint32_t vmark) {+ for (uint32_t t : from) {+ const glm::uvec3 tri = m.triangles[t];+ for (int k = 0; k < 3; ++k) {+ if (vstamp_[tri[k]] == vmark) continue;+ vstamp_[tri[k]] = vmark;+ for (uint32_t u : m.vertexTriangles(tri[k]))+ if (stamp_[u] != inR && stamp_[u] != mark) {+ stamp_[u] = mark;+ into.push_back(u);+ }+ }+ }+ };+ ring_.clear();+ ring2_.clear();+ for (uint32_t t : dirty)+ if (t < nt && stamp_[t] != inR) stamp_[t] = inR, ring_.push_back(t);+ if (grow) {+ seed_.assign(ring_.begin(), ring_.end());+ grown_.clear();+ const uint32_t v1 = ++epoch_;+ vertexRing(seed_, grown_, inR, v1); // (marks them inR directly: they're written too)+ ring_.insert(ring_.end(), grown_.begin(), grown_.end());+ }+ const uint32_t v2 = ++epoch_;+ vertexRing(ring_, ring2_, inR2, v2);+ for (size_t i = 0; i < ring_.size(); ++i) slot_[ring_[i]] = uint32_t(i);+ for (size_t i = 0; i < ring2_.size(); ++i) slot_[ring2_[i]] = uint32_t(ring_.size() + i);+ const size_t slots = ring_.size() + ring2_.size();+ const size_t edgePoints = size_t(3) * n;+ partial_.resize(slots * edgePoints * kPartialFloats);+ auto tileOf = [&](size_t i) { return i < ring_.size() ? ring_[i] : ring2_[i - ring_.size()]; };+ auto microEdge = [&](uint32_t tri) {+ const glm::uvec3 t = m.triangles[tri];+ const float e = glm::distance(m.positions[t.x], m.positions[t.y]) + glm::distance(m.positions[t.y], m.positions[t.z]) ++ glm::distance(m.positions[t.z], m.positions[t.x]);+ return std::max(e / (3.0f * float(n)), 1e-20f);+ };+ auto finish = [&](const glm::vec3& ns, float ds, float c, float d, float h, uint8_t mk) {+ const float len = glm::length(ns);+ const glm::vec3 nn = len > 0.0f ? ns / len : glm::vec3(0.0f, 0.0f, 1.0f);+ const float curv = c > 0.0f ? (ds / c - d) * mm.step / h : 0.0f;+ return encodeShade(nn, curv, mk);+ };+ // Phase 1: every R2 triangle's edge partials; R triangles' interior points written.+ poolFor(slots, [&](size_t b, size_t e) {+ thread_local GridWork w;+ for (size_t s = b; s < e; ++s) {+ const uint32_t tri = tileOf(s);+ w.compute(m, mm, tri);+ float* part = partial_.data() + s * edgePoints * kPartialFloats;+ for (int ed = 0; ed < 3; ++ed)+ for (uint32_t k = 0; k < n; ++k) {+ uint32_t i, j;+ MicroMesh::edgePoint(ed, k, n, i, j);+ const uint32_t idx = MicroMesh::index(i, j, n);+ float* p = part + (size_t(ed) * n + k) * kPartialFloats;+ p[0] = w.nsum[idx].x, p[1] = w.nsum[idx].y, p[2] = w.nsum[idx].z, p[3] = w.dsum[idx], p[4] = w.cnt[idx];+ }+ if (s >= ring_.size()) continue;+ uint32_t* dst = out(tri);+ const int16_t* g = mm.disp.data() + size_t(tri) * S;+ const uint8_t* mk = mm.hasMask() ? mm.mask.data() + size_t(tri) * S : nullptr;+ const float h = microEdge(tri);+ for (uint32_t j = 1; j + 1 < n; ++j)+ for (uint32_t i = 1; i + j < n; ++i) {+ const uint32_t idx = MicroMesh::index(i, j, n);+ dst[idx] = finish(w.nsum[idx], w.dsum[idx], w.cnt[idx], float(g[idx]), h, mk ? mk[idx] : 0);+ }+ }+ }, 16);+ // Phase 2: R triangles' edge and corner points, summed with the other triangles holding them.+ poolFor(ring_.size(), [&](size_t b, size_t e) {+ for (size_t s = b; s < e; ++s) {+ const uint32_t tri = ring_[s];+ uint32_t* dst = out(tri);+ const int16_t* g = mm.disp.data() + size_t(tri) * S;+ const uint8_t* mk = mm.hasMask() ? mm.mask.data() + size_t(tri) * S : nullptr;+ const float h = microEdge(tri);+ const float* own = partial_.data() + s * edgePoints * kPartialFloats;+ const glm::uvec3 ttri = m.triangles[tri];+ for (int ed = 0; ed < 3; ++ed) {+ const uint32_t nb = mm.edgeNeighbor[size_t(tri) * 3 + size_t(ed)];+ const float* other = nullptr;+ bool reversed = true;+ int f = 0;+ if (nb != MicroMesh::kNone && (stamp_[nb >> 2] == inR || stamp_[nb >> 2] == inR2)) {+ const uint32_t u = nb >> 2;+ f = int(nb & 3);+ other = partial_.data() + size_t(slot_[u]) * edgePoints * kPartialFloats;+ reversed = m.triangles[u][f] != ttri[ed]; // usual: the neighbour runs the edge the other way+ }+ for (uint32_t k = 1; k < n; ++k) {+ const float* p = own + (size_t(ed) * n + k) * kPartialFloats;+ glm::vec3 ns(p[0], p[1], p[2]);+ float ds = p[3], c = p[4];+ if (other) {+ const float* q = other + (size_t(f) * n + (reversed ? n - k : k)) * kPartialFloats;+ ns += glm::vec3(q[0], q[1], q[2]);+ ds += q[3];+ c += q[4];+ }+ uint32_t i, j;+ MicroMesh::edgePoint(ed, k, n, i, j);+ const uint32_t idx = MicroMesh::index(i, j, n);+ dst[idx] = finish(ns, ds, c, float(g[idx]), h, mk ? mk[idx] : 0);+ }+ // The corner at the start of this edge: every triangle around the vertex.+ const uint32_t v = ttri[ed];+ glm::vec3 ns(0.0f);+ float ds = 0.0f, c = 0.0f;+ for (uint32_t u : m.vertexTriangles(v)) {+ if (stamp_[u] != inR && stamp_[u] != inR2) continue;+ const glm::uvec3 ut = m.triangles[u];+ const int corner = ut.x == v ? 0 : ut.y == v ? 1 : 2;+ const float* q = partial_.data() + (size_t(slot_[u]) * edgePoints + size_t(corner) * n) * kPartialFloats;+ ns += glm::vec3(q[0], q[1], q[2]);+ ds += q[3];+ c += q[4];+ }+ uint32_t i, j;+ MicroMesh::edgePoint(ed, 0, n, i, j);+ const uint32_t idx = MicroMesh::index(i, j, n);+ dst[idx] = finish(ns, ds, c, float(g[idx]), h, mk ? mk[idx] : 0);+ }+ }+ }, 16);+ written.insert(written.end(), ring_.begin(), ring_.end());+}++// ---------------------------------------------------------------------------+// Undo+// ---------------------------------------------------------------------------++void MicroUndo::swapWith(Mesh& m) {+ if (swapWhole) {+ std::swap(m.micro, whole);+ if (m.micro) {+ m.micro->allDirty = true;+ m.micro->ensureTopology(m);+ if (m.micro->dirtyBits.size() != (size_t(m.micro->baseTriangles) + 63) / 64)+ m.micro->dirtyBits.assign((size_t(m.micro->baseTriangles) + 63) / 64, 0);+ }+ m.topologyDirty = true;+ return;+ }+ if (!m.micro || !microMatches(m) || m.micro->samples != samples) return;+ MicroMesh& mm = mutableMicro(m);+ const size_t S = samples;+ // Values kept in another step size (the range grew since): convert to the current one.+ if (step != mm.step && step > 0.0f) {+ const float r = step / mm.step;+ for (int16_t& v : disp) v = int16_t(std::clamp(std::lround(float(v) * r), -32767L, 32767L));+ step = mm.step;+ }+ if (maskAdded) {+ if (mm.hasMask()) {+ poolFor(tris.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i)+ std::swap_ranges(mask.begin() + std::ptrdiff_t(i * S), mask.begin() + std::ptrdiff_t((i + 1) * S),+ mm.mask.begin() + std::ptrdiff_t(size_t(tris[i]) * S));+ }, 64);+ std::vector<uint8_t>().swap(mm.mask);+ } else {+ mm.mask.assign(mm.disp.size(), 0);+ poolFor(tris.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i)+ std::swap_ranges(mask.begin() + std::ptrdiff_t(i * S), mask.begin() + std::ptrdiff_t((i + 1) * S),+ mm.mask.begin() + std::ptrdiff_t(size_t(tris[i]) * S));+ }, 64);+ }+ mm.maskDirty = true;+ } else if (!mask.empty() && mm.hasMask()) {+ poolFor(tris.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i)+ std::swap_ranges(mask.begin() + std::ptrdiff_t(i * S), mask.begin() + std::ptrdiff_t((i + 1) * S),+ mm.mask.begin() + std::ptrdiff_t(size_t(tris[i]) * S));+ }, 64);+ }+ if (!disp.empty()) {+ poolFor(tris.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) {+ int16_t* g = mm.disp.data() + size_t(tris[i]) * S;+ std::swap_ranges(disp.begin() + std::ptrdiff_t(i * S), disp.begin() + std::ptrdiff_t((i + 1) * S), g);+ int r = 0;+ for (size_t k = 0; k < S; ++k) r = std::max(r, std::abs(int(g[k])));+ mm.triRange[tris[i]] = uint16_t(r);+ }+ }, 64);+ for (uint32_t t : tris) mm.rangeMax = std::max(mm.rangeMax, mm.triRange[t]);+ }+ for (uint32_t t : tris) mm.markDirty(t);+ ++mm.revision;+}++size_t MicroUndo::bytes() const {+ return tris.size() * sizeof(uint32_t) + disp.size() * sizeof(int16_t) + mask.size() + (swapWhole && whole ? whole->bytes() : 0);+}++// ---------------------------------------------------------------------------+// Bake down+// ---------------------------------------------------------------------------++bool microBakeMesh(const Mesh& m, int level, Mesh& out, std::string& error, size_t maxTriangles) {+ if (!m.micro || !microMatches(m)) {+ error = "This SubTool has no micro level";+ return false;+ }+ const MicroMesh& mm = *m.micro;+ if (level < 0 || level > mm.level) level = mm.level;+ if (mm.edgeNeighbor.size() != size_t(mm.baseTriangles) * 3) {+ error = "Micro level topology missing";+ return false;+ }+ if (maxTriangles == 0) maxTriangles = subdivMaxTriangles();+ const uint32_t q = 1u << level, step = mm.n / q, nt = mm.baseTriangles, nv = mm.baseVertices;+ const size_t tris = size_t(nt) * q * q;+ if (tris > maxTriangles || tris >= (size_t(1) << 32)) {+ char buf[200];+ std::snprintf(buf, sizeof buf, "Baking micro level %d makes %.0fM triangles, more than this computer allows (%.0fM): pick a lower level",+ level, double(tris) / 1e6, double(maxTriangles) / 1e6);+ error = buf;+ return false;+ }+ // Vertex numbering: base vertices, then each base edge's q - 1 inner points (numbered by the triangle that+ // owns the edge: the lower index of the two), then each triangle's inner points.+ std::vector<uint32_t> edgeStart(size_t(nt) * 3, 0);+ uint32_t next = nv;+ for (uint32_t t = 0; t < nt; ++t)+ for (int e = 0; e < 3; ++e) {+ const uint32_t nb = mm.edgeNeighbor[size_t(t) * 3 + size_t(e)];+ if (nb == MicroMesh::kNone || (nb >> 2) > t) {+ edgeStart[size_t(t) * 3 + size_t(e)] = next;+ next += q - 1;+ }+ }+ for (uint32_t t = 0; t < nt; ++t)+ for (int e = 0; e < 3; ++e) {+ const uint32_t nb = mm.edgeNeighbor[size_t(t) * 3 + size_t(e)];+ if (nb != MicroMesh::kNone && (nb >> 2) < t) edgeStart[size_t(t) * 3 + size_t(e)] = edgeStart[size_t(nb >> 2) * 3 + (nb & 3)];+ }+ const uint32_t inner = q >= 2 ? (q - 1) * (q - 2) / 2 : 0;+ const size_t verts = size_t(next) + size_t(nt) * inner;+ if (verts >= (size_t(1) << 32)) {+ error = "Too many vertices";+ return false;+ }+ out = Mesh();+ out.positions.resize(verts);+ out.triangles.resize(tris);+ const bool uvs = m.hasUvs(), groups = m.hasPolygroups(), hidden = m.hasHidden(), masked = mm.hasMask();+ if (uvs) out.uvs.resize(tris * 3);+ if (groups) out.polygroups.resize(tris);+ if (hidden) out.hidden.resize(tris);+ if (masked) out.mask.assign(verts, 0.0f);+ // The vertex of grid point (a, b) (bake level) of triangle t.+ auto vertexOf = [&](uint32_t t, uint32_t a, uint32_t b) -> uint32_t {+ const glm::uvec3 tr = m.triangles[t];+ if (a == 0 && b == 0) return tr.x;+ if (a == q && b == 0) return tr.y;+ if (a == 0 && b == q) return tr.z;+ int e = -1;+ uint32_t k = 0;+ if (b == 0) e = 0, k = a;+ else if (a + b == q) e = 1, k = b;+ else if (a == 0) e = 2, k = q - b;+ if (e >= 0) {+ const uint32_t nb = mm.edgeNeighbor[size_t(t) * 3 + size_t(e)];+ const bool owner = nb == MicroMesh::kNone || (nb >> 2) > t;+ if (!owner) { // numbered from the owner's start corner+ const uint32_t u = nb >> 2;+ const bool reversed = m.triangles[u][nb & 3] != tr[e];+ if (reversed) k = q - k;+ }+ return edgeStart[size_t(t) * 3 + size_t(e)] + k - 1;+ }+ // inner point: rows b = 1..q-2, a = 1..q-1-b+ const uint32_t r = b - 1;+ const uint32_t before = r * (q - 2) - r * (r - 1) / 2; // points in rows 1..b-1: sum (q - 1 - b')+ return next + t * inner + before + (a - 1);+ };+ poolFor(nt, [&](size_t b0, size_t e0) {+ MicroTriangle T;+ for (size_t tt = b0; tt < e0; ++tt) {+ const uint32_t t = uint32_t(tt);+ T.set(m, t, mm.n);+ const int16_t* g = mm.disp.data() + size_t(t) * mm.samples;+ const uint8_t* mk = masked ? mm.mask.data() + size_t(t) * mm.samples : nullptr;+ for (uint32_t b = 0; b <= q; ++b)+ for (uint32_t a = 0; a + b <= q; ++a) {+ const uint32_t v = vertexOf(t, a, b);+ // Each shared point is written by every triangle holding it, with the same value (stitched).+ const uint32_t i = a * step, j = b * step, idx = MicroMesh::index(i, j, mm.n);+ glm::vec3 s, nn;+ T.eval(i, j, s, nn);+ out.positions[v] = s + nn * (float(g[idx]) * mm.step);+ if (mk) out.mask[v] = float(mk[idx]) / 255.0f;+ }+ const size_t first = size_t(t) * q * q;+ size_t o = first;+ glm::vec2 uv[3];+ if (uvs) uv[0] = m.uvs[size_t(t) * 3], uv[1] = m.uvs[size_t(t) * 3 + 1], uv[2] = m.uvs[size_t(t) * 3 + 2];+ auto uvAt = [&](uint32_t a, uint32_t b) {+ const float fa = float(a) / float(q), fb = float(b) / float(q);+ return uv[0] * (1.0f - fa - fb) + uv[1] * fa + uv[2] * fb;+ };+ for (uint32_t b = 0; b < q; ++b)+ for (uint32_t a = 0; a + b < q; ++a) {+ out.triangles[o] = {vertexOf(t, a, b), vertexOf(t, a + 1, b), vertexOf(t, a, b + 1)};+ if (uvs) out.uvs[o * 3] = uvAt(a, b), out.uvs[o * 3 + 1] = uvAt(a + 1, b), out.uvs[o * 3 + 2] = uvAt(a, b + 1);+ ++o;+ if (a + b + 1 < q) {+ out.triangles[o] = {vertexOf(t, a + 1, b), vertexOf(t, a + 1, b + 1), vertexOf(t, a, b + 1)};+ if (uvs)+ out.uvs[o * 3] = uvAt(a + 1, b), out.uvs[o * 3 + 1] = uvAt(a + 1, b + 1), out.uvs[o * 3 + 2] = uvAt(a, b + 1);+ ++o;+ }+ }+ for (size_t k = first; k < o; ++k) {+ if (groups) out.polygroups[k] = m.polygroups[t];+ if (hidden) out.hidden[k] = m.hidden[t];+ }+ }+ }, 256);+ out.texture = m.texture;+ out.paintToTexture = m.paintToTexture;+ out.rebuildTopology();+ out.recomputeAllNormals();+ return true;+}++// ---------------------------------------------------------------------------+// Displacement maps+// ---------------------------------------------------------------------------++bool microExportDisplacement(const Mesh& m, const std::string& path, int size, bool vector, const std::string& format,+ float& scaleOut, std::string& error) {+ if (!m.micro || !microMatches(m)) {+ error = "This SubTool has no micro level";+ return false;+ }+ if (!m.hasUvs()) {+ error = "Displacement maps need UVs on the base (Tool > UV Map, at the lowest level)";+ return false;+ }+ if (size < 16 || size > 16384) {+ error = "Map size must be 16 to 16384";+ return false;+ }+ if (format != "exr" && format != "png") {+ error = "Format must be exr or png";+ return false;+ }+ const MicroMesh& mm = *m.micro;+ const int W = size, H = size, C = vector ? 3 : 1;+ std::vector<float> px(size_t(W) * H * C, 0.0f);+ std::vector<uint8_t> covered(size_t(W) * H, 0);+ const uint32_t n = mm.n, S = mm.samples;+ poolFor(mm.baseTriangles, [&](size_t b0, size_t e0) {+ MicroTriangle T;+ thread_local std::vector<glm::vec3> P, F, N;+ P.resize(S), F.resize(S), N.resize(S);+ for (size_t tt = b0; tt < e0; ++tt) {+ const uint32_t t = uint32_t(tt);+ if (m.triangleHidden(t)) continue;+ const glm::vec2 a = m.uvs[size_t(t) * 3], b = m.uvs[size_t(t) * 3 + 1], c = m.uvs[size_t(t) * 3 + 2];+ // texel space, top-down+ const glm::vec2 A(a.x * W, (1.0f - a.y) * H), B(b.x * W, (1.0f - b.y) * H), Cc(c.x * W, (1.0f - c.y) * H);+ const float area = (B.x - A.x) * (Cc.y - A.y) - (Cc.x - A.x) * (B.y - A.y);+ if (std::abs(area) < 1e-12f) continue;+ T.set(m, t, n);+ const int16_t* g = mm.disp.data() + size_t(t) * S;+ uint32_t idx = 0;+ for (uint32_t j = 0; j <= n; ++j)+ for (uint32_t i = 0; i + j <= n; ++i, ++idx) {+ glm::vec3 s, nn;+ T.eval(i, j, s, nn);+ P[idx] = s + nn * (float(g[idx]) * mm.step);+ F[idx] = T.flat(i, j);+ N[idx] = nn;+ }+ const int x0 = std::max(0, int(std::floor(std::min({A.x, B.x, Cc.x})))),+ x1 = std::min(W - 1, int(std::ceil(std::max({A.x, B.x, Cc.x})))),+ y0 = std::max(0, int(std::floor(std::min({A.y, B.y, Cc.y})))),+ y1 = std::min(H - 1, int(std::ceil(std::max({A.y, B.y, Cc.y}))));+ for (int y = y0; y <= y1; ++y)+ for (int x = x0; x <= x1; ++x) {+ const glm::vec2 p(float(x) + 0.5f, float(y) + 0.5f);+ const float w1 = ((p.x - A.x) * (Cc.y - A.y) - (Cc.x - A.x) * (p.y - A.y)) / area;+ const float w2 = ((B.x - A.x) * (p.y - A.y) - (p.x - A.x) * (B.y - A.y)) / area;+ const float w0 = 1.0f - w1 - w2;+ if (w0 < -1e-5f || w1 < -1e-5f || w2 < -1e-5f) continue;+ const float w[3] = {w0, w1, w2};+ const Cell cl = cellAt(w, n);+ glm::vec3 pm(0.0f), pf(0.0f), pn(0.0f);+ for (int k = 0; k < 3; ++k) {+ const uint32_t id = MicroMesh::index(cl.i[k], cl.j[k], n);+ pm += P[id] * cl.w[k], pf += F[id] * cl.w[k], pn += N[id] * cl.w[k];+ }+ const size_t o = size_t(y) * W + size_t(x);+ const glm::vec3 off = pm - pf;+ if (vector) px[o * 3] = off.x, px[o * 3 + 1] = off.y, px[o * 3 + 2] = off.z;+ else px[o] = glm::dot(off, glm::normalize(pn));+ covered[o] = 1;+ }+ }+ }, 256);+ // Padding: 8 rings of texels around the islands take their neighbours' values (mip and filter seams).+ for (int pass = 0; pass < 8; ++pass) {+ std::vector<uint8_t> grow = covered;+ for (int y = 0; y < H; ++y)+ for (int x = 0; x < W; ++x) {+ const size_t o = size_t(y) * W + size_t(x);+ if (covered[o]) continue;+ float sum[3] = {0, 0, 0};+ int cnt = 0;+ for (int dy = -1; dy <= 1; ++dy)+ for (int dx = -1; dx <= 1; ++dx) {+ const int xx = x + dx, yy = y + dy;+ if (xx < 0 || yy < 0 || xx >= W || yy >= H) continue;+ const size_t q = size_t(yy) * W + size_t(xx);+ if (!covered[q]) continue;+ for (int k = 0; k < C; ++k) sum[k] += px[q * C + size_t(k)];+ ++cnt;+ }+ if (!cnt) continue;+ for (int k = 0; k < C; ++k) px[o * C + size_t(k)] = sum[k] / float(cnt);+ grow[o] = 1;+ }+ covered.swap(grow);+ }+ float maxAbs = 0.0f;+ for (float v : px) maxAbs = std::max(maxAbs, std::abs(v));+ scaleOut = maxAbs;+ if (format == "exr") return saveExr(path, W, H, C, px, error);+ std::vector<uint16_t> q(px.size());+ const float s = maxAbs > 0.0f ? 32767.0f / maxAbs : 0.0f;+ for (size_t i = 0; i < px.size(); ++i) q[i] = uint16_t(std::clamp(std::lround(px[i] * s) + 32768L, 0L, 65535L));+ return savePng16(path, W, H, C, q, error);+}++// ---------------------------------------------------------------------------+// Procedural detail+// ---------------------------------------------------------------------------++namespace {++float hashFloat(int x, int y, int z, uint32_t seed) {+ uint32_t h = uint32_t(x) * 0x8da6b343u ^ uint32_t(y) * 0xd8163841u ^ uint32_t(z) * 0xcb1ab31fu ^ seed * 0x9E3779B9u;+ h ^= h >> 13;+ h *= 0x85EBCA6Bu;+ h ^= h >> 16;+ return float(h & 0xFFFFFF) / float(0xFFFFFF) * 2.0f - 1.0f;+}++float valueNoise(const glm::vec3& p, uint32_t seed) {+ const glm::vec3 f = glm::floor(p);+ const glm::vec3 t = p - f;+ const glm::vec3 u = t * t * (3.0f - 2.0f * t);+ const int x = int(f.x), y = int(f.y), z = int(f.z);+ auto h = [&](int dx, int dy, int dz) { return hashFloat(x + dx, y + dy, z + dz, seed); };+ const float a = glm::mix(glm::mix(h(0, 0, 0), h(1, 0, 0), u.x), glm::mix(h(0, 1, 0), h(1, 1, 0), u.x), u.y);+ const float b = glm::mix(glm::mix(h(0, 0, 1), h(1, 0, 1), u.x), glm::mix(h(0, 1, 1), h(1, 1, 1), u.x), u.y);+ return glm::mix(a, b, u.z);+}++} // namespace++void microNoise(Mesh& m, float amplitude, float frequency, uint32_t seed) {+ if (!m.micro) return;+ MicroMesh& mm = mutableMicro(m);+ mm.ensureTopology(m);+ mm.widen(float(mm.rangeMax) * mm.step + std::abs(amplitude) * 1.5f);+ const uint32_t n = mm.n, S = mm.samples;+ poolFor(mm.baseTriangles, [&](size_t b0, size_t e0) {+ MicroTriangle T;+ for (size_t tt = b0; tt < e0; ++tt) {+ const uint32_t t = uint32_t(tt);+ if (m.triangleHidden(t)) continue;+ T.set(m, t, n);+ int16_t* g = mm.disp.data() + size_t(t) * S;+ const uint8_t* mk = mm.hasMask() ? mm.mask.data() + size_t(t) * S : nullptr;+ uint32_t idx = 0;+ int r = mm.triRange[t];+ for (uint32_t j = 0; j <= n; ++j)+ for (uint32_t i = 0; i + j <= n; ++i, ++idx) {+ glm::vec3 s, nn;+ T.eval(i, j, s, nn);+ const glm::vec3 p = s * frequency;+ // three octaves, ridged a little so it reads as skin-like pores and wrinkles+ float v = valueNoise(p, seed) * 0.6f + valueNoise(p * 2.03f, seed + 1) * 0.28f ++ valueNoise(p * 4.11f, seed + 2) * 0.12f;+ v = 1.0f - std::abs(v) * 2.0f;+ float d = float(g[idx]) * mm.step + amplitude * v * (mk ? 1.0f - float(mk[idx]) / 255.0f : 1.0f);+ const long q = std::clamp(std::lround(d / mm.step), -32767L, 32767L);+ g[idx] = int16_t(q);+ r = std::max(r, int(std::abs(q)));+ }+ mm.triRange[t] = uint16_t(r);+ }+ }, 256);+ for (uint16_t r : mm.triRange) mm.rangeMax = std::max(mm.rangeMax, r);+ mm.allDirty = true;+ ++mm.revision;+}++} // namespace sfdiff --git a/src/core/Micro.h b/src/core/Micro.hnew file mode 100644index 00000000..22968ce0--- /dev/null+++ b/src/core/Micro.h@@ -0,0 +1,266 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Micro-displacement levels: hundreds of millions of sculptable triangles without a mesh that size.+//+// Above the top subdivision level a SubTool can carry a micro level (Mesh::micro). The surface is then+//+// micro point = S(t, i, j) + d(t, i, j) * N(t, i, j)+//+// for every base triangle t (the mesh itself: its current, highest subdivision level) and every point (i, j) of+// a regular grid of n = 2^level segments per base edge on it (n^2 micro triangles per base triangle):+// - S is the base triangle's Phong-tessellated surface (Boubekeur & Alexa 2008, shape factor 3/4): the flat+// point pulled towards the tangent planes of the three corners, which is smooth across base edges and needs+// nothing but the base positions and normals;+// - N is the interpolated base vertex normal (normalised);+// - d is ONE scalar per grid point, stored as a 16-bit integer times `step` (world units).+// Micro triangles are never stored: positions are generated on the fly (brushes on the CPU, the renderer in its+// vertex shader). Memory is 2 bytes per grid point (+1 with a mask): 300 million micro triangles at level 4 on+// 1.2 million base triangles are about 360 MB, against roughly 30 GB as a plain mesh.+//+// Each base triangle keeps its whole grid, so the points on a base edge exist once per triangle beside it (and a+// corner once per triangle around it): about 20% extra at level 4 for grids that are contiguous per triangle (a+// brush, an undo tile and a GPU upload are one memcpy-able run each). After every edit the copies are made equal+// again ("stitching"), so the surface stays watertight. Positions on shared edges are computed from the base+// corners in ascending vertex-index order on the CPU and GPU alike, so both sides of an edge get bit-identical+// points even where the compiler fuses multiply-adds.+//+// Grid layout per triangle (corners c0, c1, c2 = triangle.x, .y, .z): point (i, j) with i, j >= 0, i + j <= n+// has barycentric weights ((n - i - j) / n, i / n, j / n); row j holds n + 1 - j points, so its index is+// j * (n + 1) - j * (j - 1) / 2 + i. Corner c0 = (0, 0), c1 = (n, 0), c2 = (0, n). Edge e runs from corner e to+// corner e + 1: e0 = (k, 0), e1 = (n - k, k), e2 = (0, n - k), k = 0..n.+//+// What a scalar displacement can't do: move points sideways. Brushes that slide the surface (Move's sideways+// part, Snake Hook, Nudge, VDM stamps with overhangs) work on real subdivision levels; on a micro level Pinch+// sharpens the height profile instead (see microBrushSupport).+#pragma once++#include "core/Mesh.h"++#include <cstdint>+#include <functional>+#include <memory>+#include <span>+#include <string>+#include <vector>++namespace sf {++class BVH;+class CommandRegistry;+struct Document;+struct RayHit;+enum class BrushType;++struct MicroMesh {+ static constexpr int kMaxLevel = 7; // 128 x 128 segments per base triangle (8,385 points)+ static constexpr float kPhong = 0.75f; // Phong tessellation shape factor+ static constexpr uint32_t kNone = ~0u;++ int level = 0; // n = 2^level segments per base edge+ uint32_t n = 1;+ uint32_t samples = 3; // grid points per base triangle: (n + 1)(n + 2) / 2+ float step = 1e-6f; // world units per integer unit of `disp`+ uint32_t baseTriangles = 0, baseVertices = 0;+ std::vector<int16_t> disp; // baseTriangles * samples+ std::vector<uint8_t> mask; // empty, or one per grid point (0 = free, 255 = masked)+ std::vector<uint16_t> triRange; // per base triangle: the largest |disp| (an upper bound; brushes find triangles with it)+ uint16_t rangeMax = 0; // the largest triRange (an upper bound)+ float bulgeMax = 0.0f; // the most S leaves a base triangle's plane (world units, an upper bound)++ // Base topology this level needs (derived, not saved; rebuilt when the base changes): per triangle edge the+ // neighbouring triangle (tri << 2 | its edge), or kNone on a boundary.+ std::vector<uint32_t> edgeNeighbor;++ // What changed since the renderer last looked: per base triangle a bit, or everything.+ std::vector<uint64_t> dirtyBits;+ bool allDirty = true;+ bool maskDirty = false; // the mask was added or removed (the renderer's shading changes everywhere)+ bool 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++ size_t microTriangles() const { return size_t(baseTriangles) * n * n; }+ size_t microVertices() const; // unique grid points (shared edges and corners counted once)+ size_t bytes() const;+ bool hasMask() const { return !mask.empty(); }+ float rangeWorld() const { return 32767.0f * step; } // the largest |d| `step` can hold++ static uint32_t index(uint32_t i, uint32_t j, uint32_t n) { return j * (n + 1) - j * (j - 1) / 2 + i; }+ // The grid point of edge e at k (from corner e towards corner e + 1).+ static void edgePoint(int e, uint32_t k, uint32_t n, uint32_t& i, uint32_t& j) {+ if (e == 0) i = k, j = 0;+ else if (e == 1) i = n - k, j = k;+ else i = 0, j = n - k;+ }+ void markDirty(uint32_t tri) { dirtyBits[tri >> 6] |= uint64_t(1) << (tri & 63); }+ // Grows `step` (by powers of two, at least 4x) until +/-`need` world units fit, rescaling every value (each+ // loses its lowest bits). Returns the divisor applied (1 = it fitted already).+ int widen(float need);+ void markAllDirty() { allDirty = true; }+ void clearDirty();+ // Builds edgeNeighbor for `base` (if it doesn't fit already).+ void ensureTopology(const Mesh& base);+};++// The base triangle's corners and normals, sorted by vertex index, for evaluating its grid points.+struct MicroTriangle {+ glm::vec3 p[3], nrm[3]; // in vertex-index order+ uint8_t slot[3]; // which corner (0..2 of the triangle) each is+ float invN = 1.0f;+ uint32_t n = 1;+ void set(const Mesh& base, uint32_t tri, uint32_t n);+ // The reference surface S and direction N at grid point (i, j).+ void eval(uint32_t i, uint32_t j, glm::vec3& surface, glm::vec3& normal) const;+ // ... and at barycentric weights of corners 0..2 (sum 1).+ void evalWeights(const float w[3], glm::vec3& surface, glm::vec3& normal) const;+ // The flat point (no Phong) at grid point (i, j): what displacement maps are measured from.+ glm::vec3 flat(uint32_t i, uint32_t j) const;+};++// --- Queries ---+inline bool hasMicro(const Mesh& m) { return m.micro != nullptr; }+int microLevel(const Mesh& m); // 0 = none+size_t microTriangleCount(const Mesh& m);+size_t microBytes(const Mesh& m);+// "Micro 4 (300.0M)" or "".+std::string microText(const Mesh& m);+// True when the micro level still fits the mesh (base triangle and vertex counts).+bool microMatches(const Mesh& m);+// The micro level to change in place: copied first when another Mesh (an undo snapshot, a copy) shares it.+MicroMesh& mutableMicro(Mesh& m);+// The most micro triangles this computer is allowed to make (RAM: about 4 bytes a grid point with the GPU's share).+size_t microMaxTriangles();+// The level that brings the mesh closest to `targetTriangles` micro triangles (1..kMaxLevel).+int microLevelFor(const Mesh& m, size_t targetTriangles);++// The micro surface point at grid point (i, j) of base triangle t (reads the stored displacement).+glm::vec3 microPoint(const Mesh& m, uint32_t tri, uint32_t i, uint32_t j);+// The micro surface at barycentric weights of base triangle t (displacement interpolated on the micro triangle+// holding the point), with its geometric normal.+glm::vec3 microPointAt(const Mesh& m, uint32_t tri, const float w[3], glm::vec3* normal = nullptr);++// --- Operations (no undo; see the commands) ---+// Adds a micro level of `level` (1..kMaxLevel) to the mesh: its current level must be the highest (or it has no+// subdivision levels). The surface starts as S (smooth, d = 0).+bool microDivide(Mesh& m, int level, std::string& error);+// Removes the micro level.+void microDelete(Mesh& m);+// Gives a loaded mesh (with normals) a micro level from saved data: `disp` holds baseTriangles * samples values+// (`mask` that many or none). Works out the derived data (ranges, bulge, edge neighbours).+bool microAttach(Mesh& m, int level, float step, std::vector<int16_t> disp, std::vector<uint8_t> mask, std::string& error);+// A regular mesh of the micro surface at micro level `level` (<= the micro level): shared points welded, the base+// triangles' UVs, polygroups and hidden flags carried to their micro triangles, mask from the micro mask. Fails+// when it would exceed `maxTriangles` (0 = what subdivision Divide allows on this computer).+bool microBakeMesh(const Mesh& m, int level, Mesh& out, std::string& error, size_t maxTriangles = 0);+// Displacement maps over the base UVs (needs UVs): `vector` = object-space offset of the micro surface from the+// flat base triangles (RGB), else the height along the interpolated normal from the flat base triangles.+// `format` "exr" (32-bit float, world units) or "png" (16-bit; scalar: 32768 = 0 and +/-`scaleOut` at white /+// black; vector: each channel likewise). Writes `path`.+bool microExportDisplacement(const Mesh& m, const std::string& path, int size, bool vector, const std::string& format,+ float& scaleOut, std::string& error);+// Adds procedural detail (value noise of `frequency` cycles per unit, `amplitude` world units) over the whole+// micro surface, for demos and benchmarks.+void microNoise(Mesh& m, float amplitude, float frequency, uint32_t seed = 1);++// Ray against the micro surface: the base triangle hit (BVH) and its neighbourhood within the displacement range,+// at full micro resolution. hit.triangle is the base triangle; hit.position / normal are on the micro surface.+bool microRaycast(const Mesh& m, const BVH& bvh, const glm::vec3& origin, const glm::vec3& dir, RayHit& hit);+// bvh.raycast, or microRaycast on a mesh with a micro level: what brushes and the cursor pick.+bool surfaceRaycast(const Mesh& m, const BVH& bvh, const glm::vec3& origin, const glm::vec3& dir, RayHit& hit);++// --- Shading for the renderer: per grid point an octahedral normal (2 x 8 bits), curvature (8 bits,+// sign(c) sqrt|c| like the mesh shader's) and mask (8 bits), packed little-endian in a uint32. ---+class MicroShader {+public:+ // Recomputes what changes when base triangles `dirty` changed (all of them when `all`): the shading of those+ // and of every base triangle sharing a vertex with one (whose shared edges and corners average with them).+ // out(tri) gives where that triangle's `samples` values go (each written whole). `written` lists them.+ 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);++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);+ std::vector<uint32_t> seed_, grown_;+ std::vector<uint32_t> stamp_, slot_; // per base triangle: in a set of this call (stamp), its partials (slot)+ std::vector<uint32_t> vstamp_; // per base vertex+ uint32_t epoch_ = 0;+ std::vector<uint32_t> ring_, ring2_;+ std::vector<float> partial_; // per slot: 3n edge points x 6 floats+};++// --- Brushes (driven by Sculptor, which calls these when the mesh has a micro level) ---++// Whether a brush works on micro levels: 2 = as on a mesh, 1 = approximated (Pinch, Crease and Dam Standard+// sharpen instead of pulling sideways; Move moves along the normal), 0 = not at all.+int microBrushSupport(BrushType type);++struct MicroUndo;+class MicroStroke {+public:+ void begin(Mesh& m);+ // One dab (one mirror) of a displacement brush, or the mask brush (`maskBrush`: raises the mask to 1, or+ // lowers it with invert).+ void dab(Mesh& m, const BVH& bvh, BrushType type, const glm::vec3& center, const glm::vec3& viewDir, float radius,+ float strength, bool invert, float focal, const glm::vec3& alphaUp, bool maskBrush, float maskStrength);+ // Move: captures the points within the dab (with each mirror's signs), then moves them along their normals.+ void beginGrab(Mesh& m, const BVH& bvh, const glm::vec3& center, float radius, float focal, const glm::vec3& mirror);+ void grab(Mesh& m, const glm::vec3& delta);+ // Puts every grid point the stroke changed back (the stroke stays open).+ void restore(Mesh& m);+ // The stroke's undo step (null when nothing changed).+ std::unique_ptr<MicroUndo> end(Mesh& m);+ bool active() const { return active_; }+ // Timings of the last dabs (ms): finding the triangles + saving undo tiles, the kernel, stitching.+ double findMs = 0, kernelMs = 0, stitchMs = 0;+ uint64_t points = 0; // grid points visited++private:+ void touch(MicroMesh& mm, std::span<const uint32_t> tris);+ void widen(MicroMesh& mm, float need); // MicroMesh::widen, keeping this stroke's saved tiles in step+ void stitch(const Mesh& m, MicroMesh& mm, std::span<const uint32_t> tris);+ bool active_ = false;+ float strokeStep_ = 0.0f;+ std::vector<uint32_t> tileOf_; // per base triangle: its undo tile + 1 (0 = not yet touched)+ std::vector<uint32_t> tiles_; // the touched base triangles, in order+ std::vector<int16_t> oldDisp_; // tiles_.size() * samples+ std::vector<uint8_t> oldMask_; // likewise, while the mask exists+ bool maskAdded_ = false; // the stroke allocated the mask+ std::vector<uint32_t> cand_; // this dab's base triangles+ std::vector<uint32_t> dabStamp_; // per base triangle: == dabEpoch_ when in cand_+ uint32_t dabEpoch_ = 0;+ std::vector<uint32_t> vertStamp_;+ std::vector<uint32_t> corners_;+ struct GrabPoint {+ uint32_t tri;+ uint16_t index;+ float weight;+ glm::vec3 normal; // the direction the point moves along+ };+ std::vector<GrabPoint> grab_;+};++// One micro step: the old grid points of the base triangles a stroke touched (in units of `step`), or a whole+// micro level swapped in or out (Divide to micro, Delete micro: `whole`, with `swapWhole`).+struct MicroUndo {+ float step = 0.0f;+ uint32_t samples = 0;+ std::vector<uint32_t> tris;+ std::vector<int16_t> disp;+ std::vector<uint8_t> mask;+ bool maskAdded = false; // the step allocated the mask: undo frees it again (redo brings it back)+ bool swapWhole = false;+ std::shared_ptr<MicroMesh> whole;+ void swapWith(Mesh& m);+ size_t bytes() const;+};++// --- Undoable document operations ---+bool microDivideUndoable(Document& doc, int level, std::string& message);+bool microDeleteUndoable(Document& doc, std::string& message);++// micro_divide, micro_delete, micro_info, micro_bake, micro_export_displacement, micro_noise.+void registerMicroCommands(CommandRegistry& registry);++} // namespace sfdiff --git a/src/core/MicroCommands.cpp b/src/core/MicroCommands.cppnew file mode 100644index 00000000..a9545ecc--- /dev/null+++ b/src/core/MicroCommands.cpp@@ -0,0 +1,190 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// micro_* commands (core/Micro.h): Tool > Geometry > Micro for scripts, the console, the CLI, MCP and the AI+// assistant.+#include "core/Commands.h"+#include "core/Micro.h"+#include "core/Multires.h"++#include <algorithm>+#include <cctype>+#include <cmath>+#include <cstdio>+#include <filesystem>++namespace sf {++namespace {++using T = ParamSpec::Type;++std::string mb(size_t bytes) {+ char buf[32];+ std::snprintf(buf, sizeof buf, "%.0f MB", double(bytes) / 1e6);+ return buf;+}++std::string millions(double n) {+ char buf[32];+ if (n >= 1e9) std::snprintf(buf, sizeof buf, "%.2fB", n / 1e9);+ else std::snprintf(buf, sizeof buf, "%.1fM", n / 1e6);+ return buf;+}++std::string summary(const Mesh& m) {+ if (!m.micro) return "no micro level";+ const MicroMesh& mm = *m.micro;+ char buf[256];+ std::snprintf(buf, sizeof buf, "Micro level %d: %s micro triangles on %s base triangles (%ux%u grid each), %s",+ mm.level, millions(double(mm.microTriangles())).c_str(), millions(double(mm.baseTriangles)).c_str(), mm.n,+ mm.n, mb(mm.bytes()).c_str());+ return buf;+}++// An undo step holding every grid tile (whole-surface edits such as micro_noise).+std::unique_ptr<MicroUndo> captureAll(const Mesh& m) {+ const MicroMesh& mm = *m.micro;+ auto u = std::make_unique<MicroUndo>();+ u->step = mm.step;+ u->samples = mm.samples;+ u->tris.resize(mm.baseTriangles);+ for (uint32_t t = 0; t < mm.baseTriangles; ++t) u->tris[t] = t;+ u->disp = mm.disp;+ return u;+}++} // namespace++bool microDivideUndoable(Document& doc, int level, std::string& message) {+ std::shared_ptr<MicroMesh> before = doc.mesh.micro;+ if (!microDivide(doc.mesh, level, message)) return false;+ UndoRecord r;+ r.label = "Micro divide";+ r.micro = std::make_unique<MicroUndo>();+ r.micro->swapWhole = true;+ r.micro->whole = std::move(before);+ doc.undo.push(std::move(r));+ message = "Divided to micro: " + summary(doc.mesh);+ return true;+}++bool microDeleteUndoable(Document& doc, std::string& message) {+ if (!doc.mesh.micro) {+ message = "This SubTool has no micro level";+ return false;+ }+ UndoRecord r;+ r.label = "Delete micro";+ r.micro = std::make_unique<MicroUndo>();+ r.micro->swapWhole = true;+ r.micro->whole = doc.mesh.micro;+ microDelete(doc.mesh);+ doc.undo.push(std::move(r));+ message = "Micro level deleted (Undo brings it back)";+ return true;+}++void registerMicroCommands(CommandRegistry& reg) {+ reg.add({"micro_divide",+ "Divide to micro level (Tool > Geometry > Micro): store the surface above the highest subdivision level as "+ "a grid of scalar displacements per triangle (2 bytes per point) instead of a mesh, so hundreds of millions "+ "of triangles stay sculptable: 300M micro triangles take about 0.4 GB. Each micro level has 4x the "+ "triangles of the one below. The standard, clay, smooth, inflate, flatten, trim, layer, pinch / crease "+ "and mask brushes work on it; it bakes down to a mesh or to displacement maps.",+ {{"level", T::Number, "Micro levels above the base: 1-7 (each 4x; 4 = 256 micro triangles per triangle).", false},+ {"triangles", T::Number, "Instead of level: about this many micro triangles, in millions (e.g. 300).", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ int level = int(argNumber(a, "level", 0));+ if (a.contains("triangles"))+ level = microLevelFor(doc.mesh, size_t(std::max(1.0, argNumber(a, "triangles", 100)) * 1e6));+ if (level <= 0) level = microLevelFor(doc.mesh, size_t(100e6));+ std::string msg;+ const bool ok = microDivideUndoable(doc, level, msg);+ return {ok, msg};+ }});++ reg.add({"micro_delete", "Delete the micro level (the highest subdivision level stays). Undoable.", {},+ [](Document& doc, const Args&) -> CommandResult {+ std::string msg;+ const bool ok = microDeleteUndoable(doc, msg);+ return {ok, msg};+ }});++ reg.add({"micro_info", "The micro level of the active SubTool: level, micro triangles, memory, displacement range.", {},+ [](Document& doc, const Args&) -> CommandResult {+ if (!doc.mesh.micro) return {true, "No micro level (micro_divide adds one above the highest subdivision level)"};+ const MicroMesh& mm = *doc.mesh.micro;+ char buf[160];+ std::snprintf(buf, sizeof buf, "; displacement step %.3g, range +/-%.3g (used %.3g)%s", double(mm.step),+ double(mm.rangeWorld()), double(mm.rangeMax) * double(mm.step), mm.hasMask() ? "; masked" : "");+ return {true, summary(doc.mesh) + buf};+ }});++ reg.add({"micro_bake",+ "Bake down: turn the micro level into a regular mesh (for export or tools that need real geometry). By "+ "default a new SubTool next to this one; replace=true replaces this SubTool's mesh (undoable). Its UVs, "+ "polygroups, hidden faces and the micro mask carry over.",+ {{"level", T::Number, "Micro level to bake (default: the full micro level; lower = 1/4 the triangles each).", false},+ {"replace", T::Bool, "Replace this SubTool's mesh instead of adding a SubTool (default false).", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ if (!doc.mesh.micro) return {false, "This SubTool has no micro level"};+ const int level = int(argNumber(a, "level", doc.mesh.micro->level));+ Mesh baked;+ std::string err;+ if (!microBakeMesh(doc.mesh, level, baked, err)) return {false, err};+ const std::string tris = millions(double(baked.triangleCount()));+ if (argBool(a, "replace", false)) {+ doc.replaceMeshUndoable(std::move(baked), "Bake micro");+ return {true, "Baked the micro level into this SubTool: " + tris + " triangles"};+ }+ const std::string name = doc.uniqueSubtoolName(doc.activeSubtoolInfo().name + " baked");+ doc.addSubtool(std::move(baked), name, false, doc.activeSubtool + 1);+ return {true, "Baked the micro level into SubTool \"" + name + "\": " + tris + " triangles"};+ }});++ reg.add({"micro_export_displacement",+ "Export a displacement map of the micro level over the base UVs, for game and film pipelines: scalar "+ "(height along the interpolated normal) or vector (object-space offset), measured from the flat base "+ "triangles. .exr = 32-bit float in world units; .png = 16-bit, mid-grey = 0 (the scale is in the message).",+ {{"path", T::String, "Output file (.exr or .png).", true},+ {"size", T::Number, "Map size in pixels (default 4096).", false},+ {"type", T::String, "scalar (default) or vector.", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ const std::string path = argString(a, "path");+ if (path.empty()) return {false, "Give path= (.exr or .png)"};+ std::string ext = std::filesystem::path(std::u8string(path.begin(), path.end())).extension().string();+ std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::tolower(c)); });+ const std::string format = ext == ".png" ? "png" : "exr";+ const bool vector = argString(a, "type", "scalar") == "vector";+ float scale = 0.0f;+ std::string err;+ if (!microExportDisplacement(doc.mesh, path, int(argNumber(a, "size", 4096)), vector, format, scale, err))+ return {false, err};+ char buf[128];+ std::snprintf(buf, sizeof buf, " (largest offset %.4g world units%s)", double(scale),+ format == "png" ? ", at white / black" : "");+ return {true, "Wrote " + std::string(vector ? "vector" : "scalar") + " displacement " + path + buf};+ }});++ reg.add({"micro_noise",+ "Surface noise on the micro level: procedural pore / wrinkle detail over the whole surface (respects the "+ "mask). Undoable.",+ {{"amplitude", T::Number, "Height as a fraction of the model's size (default 0.0015).", false},+ {"scale", T::Number, "Noise features across the model (default 120).", false},+ {"seed", T::Number, "Random seed (default 1).", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ if (!doc.mesh.micro) return {false, "This SubTool has no micro level"};+ const float diag = glm::length(doc.mesh.bounds().extent());+ const float amp = float(argNumber(a, "amplitude", 0.0015)) * diag;+ const float freq = float(argNumber(a, "scale", 120)) / std::max(diag, 1e-6f);+ UndoRecord r;+ r.label = "Micro noise";+ r.micro = captureAll(doc.mesh);+ microNoise(doc.mesh, amp, freq, uint32_t(argNumber(a, "seed", 1)));+ doc.undo.push(std::move(r));+ return {true, "Added surface noise to " + millions(double(microTriangleCount(doc.mesh))) + " micro triangles"};+ }});+}++} // namespace sfdiff --git a/src/core/MicroSculpt.cpp b/src/core/MicroSculpt.cppnew file mode 100644index 00000000..50adf87b--- /dev/null+++ b/src/core/MicroSculpt.cpp@@ -0,0 +1,552 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Brushes on micro-displacement levels (core/Micro.h). A dab:+// 1. finds the base triangles it can reach: the BVH over the base, with the radius grown by how far the micro+// surface can leave the base (the Phong bulge plus the largest displacement), then each triangle's own box;+// 2. saves the grids of triangles the stroke touches for the first time (the undo step: whole tiles);+// 3. finds the brush plane (area normal and centre) from every second grid point under the brush;+// 4. runs the kernel over the triangles in parallel: each grid point inside the brush gets a new scalar;+// 5. stitches: copies of a point on a shared edge or corner are averaged (they differ only where a brush read+// neighbours, like Smooth), so the surface stays closed.+#include "core/Micro.h"++#include "core/BVH.h"+#include "core/Sculpt.h"+#include "core/ThreadPool.h"++#include <algorithm>+#include <cmath>++namespace sf {++int microBrushSupport(BrushType type) {+ switch (type) {+ case BrushType::Standard:+ case BrushType::Clay:+ case BrushType::ClayBuildup:+ case BrushType::Smooth:+ case BrushType::Inflate:+ case BrushType::Flatten:+ case BrushType::Trim:+ case BrushType::Layer: return 2;+ case BrushType::Pinch:+ case BrushType::Crease:+ case BrushType::DamStandard:+ case BrushType::Move: return 1;+ default: return 0;+ }+}++namespace {++glm::vec3 projectOnPlane(const glm::vec3& v, const glm::vec3& n) { return v - n * glm::dot(v, n); }++// A base triangle's box grown by its Phong bulge and displacement range.+bool triangleNear(const Mesh& m, const MicroMesh& mm, uint32_t t, const glm::vec3& c, float r) {+ const glm::uvec3 tr = m.triangles[t];+ const glm::vec3 a = m.positions[tr.x], b = m.positions[tr.y], d = m.positions[tr.z];+ const glm::vec3 na = m.normals[tr.x], nb = m.normals[tr.y], nd = m.normals[tr.z];+ float bulge = 0.0f;+ bulge = std::max({bulge, std::abs(glm::dot(b - a, na)), std::abs(glm::dot(d - a, na)), std::abs(glm::dot(a - b, nb)),+ std::abs(glm::dot(d - b, nb)), std::abs(glm::dot(a - d, nd)), std::abs(glm::dot(b - d, nd))});+ const float grow = bulge * MicroMesh::kPhong + float(mm.triRange[t]) * mm.step;+ const glm::vec3 lo = glm::min(a, glm::min(b, d)) - grow, hi = glm::max(a, glm::max(b, d)) + grow;+ const glm::vec3 q = glm::clamp(c, lo, hi);+ return glm::dot(q - c, q - c) <= r * r;+}++int16_t quantize(float d, float step) { return int16_t(std::clamp(std::lround(d / step), -32767L, 32767L)); }++// The six lattice neighbours of (i, j) inside the triangle.+template <class F>+void forNeighbors(uint32_t i, uint32_t j, uint32_t n, F&& f) {+ if (i > 0) f(i - 1, j);+ if (i + j < n) f(i + 1, j);+ if (j > 0) f(i, j - 1);+ if (i + j < n) f(i, j + 1);+ if (j > 0) f(i + 1, j - 1);+ if (i > 0) f(i - 1, j + 1);+}++} // namespace++void MicroStroke::begin(Mesh& m) {+ MicroMesh& mm = mutableMicro(m);+ mm.ensureTopology(m);+ if (mm.dirtyBits.size() != (size_t(mm.baseTriangles) + 63) / 64) mm.dirtyBits.assign((size_t(mm.baseTriangles) + 63) / 64, 0);+ tileOf_.assign(mm.baseTriangles, 0);+ tiles_.clear();+ oldDisp_.clear();+ oldMask_.clear();+ maskAdded_ = false;+ if (dabStamp_.size() != mm.baseTriangles) {+ dabStamp_.assign(mm.baseTriangles, 0);+ dabEpoch_ = 0;+ }+ if (vertStamp_.size() != m.vertexCount()) vertStamp_.assign(m.vertexCount(), 0);+ strokeStep_ = mm.step;+ grab_.clear();+ active_ = true;+}++// Saves the grids of the triangles in `tris` that this stroke hasn't touched yet.+void MicroStroke::touch(MicroMesh& mm, std::span<const uint32_t> tris) {+ const size_t S = mm.samples, before = tiles_.size();+ for (uint32_t t : tris)+ if (!tileOf_[t]) {+ tiles_.push_back(t);+ tileOf_[t] = uint32_t(tiles_.size());+ }+ if (tiles_.size() == before) return;+ oldDisp_.resize(tiles_.size() * S);+ if (mm.hasMask()) oldMask_.resize(tiles_.size() * S);+ poolFor(tiles_.size() - before, [&](size_t b, size_t e) {+ for (size_t i = before + b; i < before + e; ++i) {+ const size_t t = tiles_[i];+ std::copy_n(mm.disp.data() + t * S, S, oldDisp_.data() + i * S);+ if (mm.hasMask()) std::copy_n(mm.mask.data() + t * S, S, oldMask_.data() + i * S);+ }+ }, 64);+}++// Makes the copies of every shared point of triangles `tris` equal again (see the file comment).+void MicroStroke::stitch(const Mesh& m, MicroMesh& mm, std::span<const uint32_t> tris) {+ const uint32_t n = mm.n, S = mm.samples;+ const uint32_t epoch = dabEpoch_;+ auto inDab = [&](uint32_t t) { return dabStamp_[t] == epoch; };+ // Edges: each shared edge once, by the lower triangle of the two (both in this dab), or copied from a hidden+ // neighbour (which brushes leave alone).+ poolFor(tris.size(), [&](size_t b, size_t e) {+ for (size_t s = b; s < e; ++s) {+ const uint32_t t = tris[s];+ const glm::uvec3 tt = m.triangles[t];+ int16_t* g = mm.disp.data() + size_t(t) * S;+ uint8_t* mk = mm.hasMask() ? mm.mask.data() + size_t(t) * S : nullptr;+ for (int ed = 0; ed < 3; ++ed) {+ const uint32_t nb = mm.edgeNeighbor[size_t(t) * 3 + size_t(ed)];+ if (nb == MicroMesh::kNone) continue;+ const uint32_t u = nb >> 2;+ const int f = int(nb & 3);+ const bool hiddenU = m.triangleHidden(u);+ if (!(inDab(u) && t < u) && !(hiddenU && !inDab(u))) continue;+ int16_t* h = mm.disp.data() + size_t(u) * S;+ uint8_t* hk = mk ? mm.mask.data() + size_t(u) * S : nullptr;+ const bool reversed = m.triangles[u][f] != tt[ed];+ for (uint32_t k = 1; k < n; ++k) {+ uint32_t i, j, i2, j2;+ MicroMesh::edgePoint(ed, k, n, i, j);+ MicroMesh::edgePoint(f, reversed ? n - k : k, n, i2, j2);+ const uint32_t a = MicroMesh::index(i, j, n), c = MicroMesh::index(i2, j2, n);+ if (hiddenU) {+ g[a] = h[c];+ if (mk) mk[a] = hk[c];+ } else {+ const int16_t v = int16_t((int(g[a]) + int(h[c]) + (int(g[a]) + int(h[c]) >= 0 ? 1 : 0)) / 2);+ g[a] = h[c] = v;+ if (mk) mk[a] = hk[c] = uint8_t((int(mk[a]) + int(hk[c]) + 1) / 2);+ }+ }+ }+ }+ }, 64);+ // Corners: every base vertex of these triangles once, averaged over the triangles around it in this dab (or+ // taken from a hidden one).+ corners_.clear();+ const uint32_t vmark = epoch;+ for (uint32_t t : tris) {+ const glm::uvec3 tt = m.triangles[t];+ for (int k = 0; k < 3; ++k)+ if (vertStamp_[tt[k]] != vmark) {+ vertStamp_[tt[k]] = vmark;+ corners_.push_back(tt[k]);+ }+ }+ poolFor(corners_.size(), [&](size_t b, size_t e) {+ for (size_t s = b; s < e; ++s) {+ const uint32_t v = corners_[s];+ const IndexRing ring = m.vertexTriangles(v);+ auto cornerIndex = [&](uint32_t u) {+ const glm::uvec3 ut = m.triangles[u];+ const int c = ut.x == v ? 0 : ut.y == v ? 1 : 2;+ return size_t(u) * S + (c == 0 ? 0 : c == 1 ? MicroMesh::index(n, 0, n) : MicroMesh::index(0, n, n));+ };+ long sum = 0, msum = 0;+ int count = 0;+ int hiddenValue = 0, hiddenMask = 0;+ bool fromHidden = false;+ for (uint32_t u : ring) {+ const size_t ci = cornerIndex(u);+ if (!inDab(u)) {+ if (m.triangleHidden(u) && !fromHidden) {+ fromHidden = true;+ hiddenValue = mm.disp[ci];+ hiddenMask = mm.hasMask() ? mm.mask[ci] : 0;+ }+ continue;+ }+ sum += mm.disp[ci];+ if (mm.hasMask()) msum += mm.mask[ci];+ ++count;+ }+ if (!count) continue;+ const int16_t value = fromHidden ? int16_t(hiddenValue)+ : int16_t((sum + (sum >= 0 ? count / 2 : -(count / 2))) / count);+ const uint8_t mval = fromHidden ? uint8_t(hiddenMask) : uint8_t((msum + count / 2) / count);+ for (uint32_t u : ring) {+ if (!inDab(u)) continue;+ const size_t ci = cornerIndex(u);+ mm.disp[ci] = value;+ if (mm.hasMask()) mm.mask[ci] = mval;+ }+ }+ }, 256);+ // Ranges: stitching averages between triangles, so a triangle may now hold its neighbour's larger value.+ poolFor(tris.size(), [&](size_t b, size_t e) {+ for (size_t s = b; s < e; ++s) {+ const uint32_t t = tris[s];+ const int16_t* g = mm.disp.data() + size_t(t) * S;+ int r = 0;+ for (uint32_t k = 0; k < S; ++k) r = std::max(r, std::abs(int(g[k])));+ mm.triRange[t] = uint16_t(r);+ }+ }, 64);+ for (uint32_t t : tris) {+ mm.rangeMax = std::max(mm.rangeMax, mm.triRange[t]);+ mm.markDirty(t);+ }+ ++mm.revision;+}++void MicroStroke::dab(Mesh& m, const BVH& bvh, BrushType type, const glm::vec3& center, const glm::vec3& viewDir, float radius,+ float strength, bool invert, float focal, const glm::vec3& alphaUp, bool maskBrush, float maskStrength) {+ if (!active_ || !m.micro || radius <= 0.0f) return;+ if (!maskBrush && microBrushSupport(type) == 0) return;+ auto clock = std::chrono::steady_clock::now();+ MicroMesh& mm = *m.micro; // (made unique by begin)+ const uint32_t n = mm.n, S = mm.samples;+ const float r = radius, r2 = r * r;+ const float s = std::clamp(strength, 0.0f, 1.0f);+ const float sign = invert ? -1.0f : 1.0f;+ const float reach = type == BrushType::ClayBuildup && !maskBrush ? 1.3f : 1.0f;++ // The displacement range this dab may need: widened first (it costs precision) when what a dab adds could+ // pass it; a dab that still clips (planes far off) widens it for the next one.+ if (!maskBrush) widen(mm, float(mm.rangeMax) * mm.step + 0.12f * r * s);++ // 1. The base triangles within reach.+ if (++dabEpoch_ == 0) {+ std::fill(dabStamp_.begin(), dabStamp_.end(), 0);+ std::fill(vertStamp_.begin(), vertStamp_.end(), 0);+ dabEpoch_ = 1;+ }+ bvh.queryTriangles(m, center, r * reach + mm.bulgeMax + float(mm.rangeMax) * mm.step, cand_);+ std::erase_if(cand_, [&](uint32_t t) { return m.triangleHidden(t) || !triangleNear(m, mm, t, center, r * reach); });+ if (cand_.empty()) return;+ for (uint32_t t : cand_) dabStamp_[t] = dabEpoch_;+ if (maskBrush && !mm.hasMask()) {+ mm.mask.assign(mm.disp.size(), 0);+ oldMask_.assign(tiles_.size() * S, 0); // (the tiles saved so far had no mask: zeros)+ maskAdded_ = true;+ mm.maskDirty = true;+ }+ touch(mm, cand_);+ findMs += lapMs(clock);++ // 2. The brush plane: weighted area normal and centre over every second grid point under the brush.+ glm::vec3 areaNormal(0.0f), areaCenter(0.0f);+ const bool needPlane = !maskBrush && type != BrushType::Smooth && type != BrushType::Inflate && type != BrushType::Pinch;+ if (needPlane) {+ const uint32_t stride = n >= 4 ? 2 : 1;+ struct Sum {+ glm::dvec3 nrm{0.0}, ctr{0.0};+ double w = 0.0;+ };+ const size_t block = 8;+ std::vector<Sum> sums((cand_.size() + block - 1) / block);+ poolFor(cand_.size(), [&](size_t b, size_t e) {+ Sum acc;+ MicroTriangle T;+ for (size_t ci = b; ci < e; ++ci) {+ const uint32_t t = cand_[ci];+ T.set(m, t, n);+ const int16_t* g = mm.disp.data() + size_t(t) * S;+ for (uint32_t j = 0; j <= n; j += stride)+ for (uint32_t i = 0; i + j <= n; i += stride) {+ glm::vec3 sp, nn;+ T.eval(i, j, sp, nn);+ const glm::vec3 p = sp + nn * (float(g[MicroMesh::index(i, j, n)]) * mm.step);+ const float d2 = glm::dot(p - center, p - center);+ if (d2 >= r2) continue;+ const float w = brushFalloff(std::sqrt(d2), r, focal);+ acc.nrm += glm::dvec3(nn * w);+ acc.ctr += glm::dvec3(p * w);+ acc.w += w;+ }+ }+ sums[b / block] = acc;+ }, block, 2);+ Sum total;+ for (const Sum& x : sums) total.nrm += x.nrm, total.ctr += x.ctr, total.w += x.w;+ if (total.w <= 0.0) {+ // nothing under the brush (it only grazed the boxes): the stitch below still runs for the saved tiles+ areaNormal = -viewDir;+ areaCenter = center;+ } else {+ areaCenter = glm::vec3(total.ctr / total.w);+ const double len = glm::length(total.nrm);+ areaNormal = len > 1e-12 ? glm::vec3(total.nrm / len) : -viewDir;+ }+ }+ glm::vec3 up = projectOnPlane(alphaUp, areaNormal);+ if (glm::length(up) < 1e-6f)+ up = projectOnPlane(std::abs(areaNormal.x) < 0.9f ? glm::vec3(1, 0, 0) : glm::vec3(0, 1, 0), areaNormal);+ up = glm::normalize(up);+ const glm::vec3 right = glm::cross(up, areaNormal);+ const float layerHeight = r * 0.08f * s;+ const bool readsNeighbours = type == BrushType::Smooth || type == BrushType::Pinch || type == BrushType::Crease ||+ type == BrushType::DamStandard;++ // 3. The kernel, in parallel over the triangles (each writes only its own grid).+ std::vector<uint64_t> visited((cand_.size() + 7) / 8, 0);+ std::vector<float> clipped((cand_.size() + 7) / 8, 0.0f); // per block: the largest |d| that didn't fit+ const float range = mm.rangeWorld();+ poolFor(cand_.size(), [&](size_t b, size_t e) {+ thread_local std::vector<int16_t> before;+ MicroTriangle T;+ uint64_t count = 0;+ float over = 0.0f;+ for (size_t ci = b; ci < e; ++ci) {+ const uint32_t t = cand_[ci];+ T.set(m, t, n);+ int16_t* g = mm.disp.data() + size_t(t) * S;+ uint8_t* mk = mm.hasMask() ? mm.mask.data() + size_t(t) * S : nullptr;+ if (readsNeighbours && !maskBrush) before.assign(g, g + S); // Jacobi: neighbours as they were+ const int16_t* old = !maskBrush && type == BrushType::Layer ? oldDisp_.data() + size_t(tileOf_[t] - 1) * S : nullptr;+ uint32_t idx = 0;+ for (uint32_t j = 0; j <= n; ++j)+ for (uint32_t i = 0; i + j <= n; ++i, ++idx) {+ glm::vec3 sp, nn;+ T.eval(i, j, sp, nn);+ const float d = float(g[idx]) * mm.step;+ const glm::vec3 p = sp + nn * d;+ const glm::vec3 o = p - center;+ const float dist2 = glm::dot(o, o);+ if (dist2 >= r2 * reach * reach) continue;+ ++count;+ if (maskBrush) {+ if (dist2 >= r2) continue;+ const float a = std::clamp(maskStrength, 0.0f, 1.0f) * brushFalloff(std::sqrt(dist2), r, focal);+ const float cur = float(mk[idx]) / 255.0f;+ const float nv = invert ? cur * (1.0f - a) : cur + (1.0f - cur) * a;+ mk[idx] = uint8_t(std::clamp(std::lround(nv * 255.0f), 0L, 255L));+ continue;+ }+ float f = brushFalloff(std::sqrt(dist2), r, focal);+ if (type == BrushType::ClayBuildup) { // square tip, rounded corners (as Sculpt.cpp)+ const float cheb = std::max(std::abs(glm::dot(o, right)), std::abs(glm::dot(o, up))) / r;+ const float corner = std::clamp((1.3f - std::sqrt(dist2) / r) / 0.3f, 0.0f, 1.0f);+ const float edge = std::clamp((1.0f - cheb) / 0.35f, 0.0f, 1.0f);+ f = edge * edge * (3.0f - 2.0f * edge) * corner;+ }+ if (mk) f *= 1.0f - float(mk[idx]) / 255.0f;+ if (f <= 0.0f) continue;+ const float facing = std::max(glm::dot(nn, areaNormal), 0.3f); // moving along nn reaches a plane this much slower+ float delta = 0.0f;+ auto neighbourAverage = [&](float& lo, float& hi) {+ float sum = 0.0f;+ int c = 0;+ lo = 1e30f, hi = -1e30f;+ forNeighbors(i, j, n, [&](uint32_t a, uint32_t bb) {+ const float v = float(before[MicroMesh::index(a, bb, n)]);+ sum += v, ++c;+ lo = std::min(lo, v), hi = std::max(hi, v);+ });+ return c ? sum / float(c) : float(before[idx]);+ };+ auto sharpen = [&](float k) { // pinch, on a height field: away from the neighbour average, kept within them+ float lo, hi;+ const float avg = neighbourAverage(lo, hi);+ const float cur = float(before[idx]);+ const float target = std::clamp(cur + (cur - avg) * k, lo, hi);+ return (target - cur) * mm.step;+ };+ switch (type) {+ case BrushType::Standard: delta = sign * s * r * 0.06f * f * glm::dot(areaNormal, nn); break;+ case BrushType::Inflate: delta = sign * s * r * 0.05f * f; break;+ case BrushType::Smooth: {+ float lo, hi;+ const float avg = neighbourAverage(lo, hi);+ delta = (avg - float(before[idx])) * mm.step * std::min(1.0f, s * f);+ break;+ }+ case BrushType::Flatten: {+ const float h = glm::dot(p - areaCenter, areaNormal);+ delta = -h * s * f * (invert ? -0.5f : 1.0f) / facing;+ break;+ }+ case BrushType::Clay: {+ const glm::vec3 pp = areaCenter + areaNormal * (sign * r * 0.05f * s);+ const float h = glm::dot(p - pp, areaNormal);+ if (sign * h < 0.0f) delta = -h * f / facing;+ break;+ }+ case BrushType::ClayBuildup: {+ const glm::vec3 pp = areaCenter + areaNormal * (sign * r * 0.08f * s);+ const float h = glm::dot(p - pp, areaNormal);+ if (sign * h < 0.0f) delta = -h * f / facing;+ break;+ }+ case BrushType::Trim: {+ const glm::vec3 pp = areaCenter - areaNormal * (sign * r * 0.02f * s);+ const float h = glm::dot(p - pp, areaNormal);+ if (sign * h > 0.0f) delta = -h * std::min(1.0f, std::sqrt(f) * (0.5f + s)) / facing;+ break;+ }+ case BrushType::Layer: {+ // Up to one height per stroke above where the point started (overlaps never stack).+ const float start = float(old[idx]) * mm.step;+ const float target = start + sign * layerHeight * f;+ delta = sign > 0.0f ? std::max(0.0f, target - d) : std::min(0.0f, target - d);+ break;+ }+ case BrushType::Pinch: delta = sign * sharpen(0.6f * s * f); break;+ case BrushType::Crease:+ delta = -sign * s * r * 0.05f * f * f + sharpen(0.5f * s * f);+ break;+ case BrushType::DamStandard:+ delta = -sign * s * r * 0.08f * f * f * f * f + sharpen(0.7f * s * f);+ break;+ default: break;+ }+ if (delta != 0.0f) {+ const float nd = d + delta;+ if (std::abs(nd) > range) over = std::max(over, std::abs(nd));+ g[idx] = quantize(nd, mm.step);+ }+ }+ }+ visited[b / 8] = count;+ clipped[b / 8] = over;+ }, 8, 2);+ for (uint64_t c : visited) points += c;+ kernelMs += lapMs(clock);+ float over = 0.0f;+ for (float c : clipped) over = std::max(over, c);++ // 4. Stitch the shared points.+ stitch(m, mm, cand_);+ if (over > 0.0f) widen(mm, over * 1.5f);+ stitchMs += lapMs(clock);+}++void MicroStroke::widen(MicroMesh& mm, float need) {+ const int div = mm.widen(need);+ if (div == 1) return;+ for (int16_t& v : oldDisp_) v = int16_t(int(v) / div);+ strokeStep_ = mm.step;+}++void MicroStroke::beginGrab(Mesh& m, const BVH& bvh, const glm::vec3& center, float radius, float focal, const glm::vec3& mirror) {+ if (!active_ || !m.micro) return;+ MicroMesh& mm = *m.micro;+ const uint32_t n = mm.n, S = mm.samples;+ widen(mm, float(mm.rangeMax) * mm.step + radius); // room to move a radius either way+ std::vector<uint32_t> cand;+ bvh.queryTriangles(m, center, radius + mm.bulgeMax + float(mm.rangeMax) * mm.step, cand);+ std::erase_if(cand, [&](uint32_t t) { return m.triangleHidden(t) || !triangleNear(m, mm, t, center, radius); });+ touch(mm, cand);+ GrabPoint mirrorMark{MicroMesh::kNone, 0, 0.0f, mirror}; // a range marker: the points after it use this mirror+ grab_.push_back(mirrorMark);+ MicroTriangle T;+ for (uint32_t t : cand) {+ T.set(m, t, n);+ const int16_t* g = mm.disp.data() + size_t(t) * S;+ const uint8_t* mk = mm.hasMask() ? mm.mask.data() + size_t(t) * S : nullptr;+ uint32_t idx = 0;+ for (uint32_t j = 0; j <= n; ++j)+ for (uint32_t i = 0; i + j <= n; ++i, ++idx) {+ glm::vec3 sp, nn;+ T.eval(i, j, sp, nn);+ const glm::vec3 p = sp + nn * (float(g[idx]) * mm.step);+ const float d = glm::distance(p, center);+ if (d >= radius) continue;+ float w = brushFalloff(d, radius, focal);+ if (mk) w *= 1.0f - float(mk[idx]) / 255.0f;+ if (w <= 0.0f) continue;+ grab_.push_back({t, uint16_t(idx), w, nn});+ ++points;+ }+ }+}++void MicroStroke::grab(Mesh& m, const glm::vec3& delta) {+ if (!active_ || !m.micro || grab_.empty()) return;+ auto clock = std::chrono::steady_clock::now();+ MicroMesh& mm = *m.micro;+ const size_t S = mm.samples;+ // Mirror ranges one after another (a point may be in two), each point once within its range.+ size_t i = 0;+ while (i < grab_.size()) {+ const glm::vec3 mirror = grab_[i].normal;+ size_t end = i + 1;+ while (end < grab_.size() && grab_[end].tri != MicroMesh::kNone) ++end;+ const glm::vec3 dm = delta * mirror;+ poolFor(end - i - 1, [&](size_t b, size_t e) {+ for (size_t k = i + 1 + b; k < i + 1 + e; ++k) {+ const GrabPoint& gp = grab_[k];+ int16_t& v = mm.disp[size_t(gp.tri) * S + gp.index];+ v = quantize(float(v) * mm.step + glm::dot(dm, gp.normal) * gp.weight, mm.step);+ }+ }, 1 << 14);+ i = end;+ }+ kernelMs += lapMs(clock);+ cand_.clear();+ if (++dabEpoch_ == 0) dabEpoch_ = 1;+ for (const GrabPoint& gp : grab_)+ if (gp.tri != MicroMesh::kNone && dabStamp_[gp.tri] != dabEpoch_) {+ dabStamp_[gp.tri] = dabEpoch_;+ cand_.push_back(gp.tri);+ }+ stitch(m, mm, cand_);+ stitchMs += lapMs(clock);+}++void MicroStroke::restore(Mesh& m) {+ if (!active_ || !m.micro || tiles_.empty()) return;+ MicroMesh& mm = *m.micro;+ const size_t S = mm.samples;+ poolFor(tiles_.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) {+ const size_t t = tiles_[i];+ std::copy_n(oldDisp_.data() + i * S, S, mm.disp.data() + t * S);+ if (mm.hasMask() && oldMask_.size() == tiles_.size() * S) std::copy_n(oldMask_.data() + i * S, S, mm.mask.data() + t * S);+ }+ }, 64);+ for (uint32_t t : tiles_) mm.markDirty(t);+ ++mm.revision;+}++std::unique_ptr<MicroUndo> MicroStroke::end(Mesh& m) {+ active_ = false;+ grab_.clear();+ if (tiles_.empty() || !m.micro) {+ tiles_.clear();+ return nullptr;+ }+ auto u = std::make_unique<MicroUndo>();+ u->step = strokeStep_;+ u->samples = m.micro->samples;+ u->tris = std::move(tiles_);+ u->disp = std::move(oldDisp_);+ if (m.micro->hasMask() && oldMask_.size() == u->tris.size() * u->samples) u->mask = std::move(oldMask_);+ u->maskAdded = maskAdded_;+ for (uint32_t t : u->tris) tileOf_[t] = 0;+ tiles_.clear();+ oldDisp_.clear();+ oldMask_.clear();+ return u;+}++} // namespace sfdiff --git a/src/core/Multires.cpp b/src/core/Multires.cppindex 8f5506b2..715b9733 100644--- a/src/core/Multires.cpp+++ b/src/core/Multires.cpp@@ -1,6 +1,7 @@// SculptForge - open source digital sculpting// SPDX-License-Identifier: GPL-3.0-or-later#include "core/Multires.h"+#include "core/Micro.h"#include "core/BVH.h"#include "core/Document.h"@@ -1525,6 +1526,10 @@ bool subdivSetLevel(Mesh& mesh, int level, std::string& error, BVH* bvh) {error = "This SubTool has no subdivision levels (Divide adds them)";return false;}+ if (mesh.micro && level != mesh.multires->current) {+ error = "This SubTool has a micro level: Bake it down or delete it (Tool > Geometry > Micro) before changing subdivision levels";+ return false;+ }if (!subdivCommit(mesh)) {error = "The mesh topology changed, so its subdivision levels were dropped";return false;@@ -1558,6 +1563,10 @@ size_t subdivMaxTriangles() {}bool subdivDivide(Mesh& mesh, bool smooth, std::string& error, BVH* bvh, size_t maxTriangles) {+ if (mesh.micro) {+ error = "This SubTool has a micro level: Bake it down or delete it (Tool > Geometry > Micro) before changing subdivision levels";+ return false;+ }if (maxTriangles == 0) maxTriangles = subdivMaxTriangles();if (mesh.triangleCount() == 0) {error = "Nothing to divide";@@ -1604,6 +1613,10 @@ bool subdivDivide(Mesh& mesh, bool smooth, std::string& error, BVH* bvh, size_t}bool subdivDeleteLower(Mesh& mesh, std::string& error) {+ if (mesh.micro) {+ error = "This SubTool has a micro level: Bake it down or delete it (Tool > Geometry > Micro) before changing subdivision levels";+ return false;+ }if (!mesh.multires || !subdivCommit(mesh)) {error = "This SubTool has no subdivision levels";return false;@@ -2081,6 +2094,10 @@ bool reconstructLoop(const Mesh& m, Reconstruction& out, std::string& error) {} // namespacebool subdivReconstruct(Mesh& mesh, std::string& error, BVH* bvh) {+ if (mesh.micro) {+ error = "This SubTool has a micro level: Bake it down or delete it (Tool > Geometry > Micro) before changing subdivision levels";+ return false;+ }if (mesh.multires) {if (!subdivCommit(mesh)) {// dropped: reconstruct from this mesh alonediff --git a/src/core/Project.cpp b/src/core/Project.cppindex eb4418dd..36e81ae8 100644--- a/src/core/Project.cpp+++ b/src/core/Project.cpp@@ -1,6 +1,7 @@// SculptForge - open source digital sculpting// SPDX-License-Identifier: GPL-3.0-or-later#include "core/Project.h"+#include "core/Micro.h"#include "core/Multires.h"@@ -141,6 +142,29 @@ public:return add(file, Scalar::U32, 1, v.size(), littleEndian(v.data(), v.size()));}Json bytes(const std::string& file, const std::vector<uint8_t>& v) { return add(file, Scalar::U8, 1, v.size(), v); }+ // `count` 16-bit integers at `v` (which must outlive the save), as u8 x 2, written straight from memory on+ // little-endian machines.+ Json int16s(const std::string& file, const int16_t* v, size_t count) {+ if constexpr (std::endian::native == std::endian::little) {+ ZipEntry e{file, {}};+ e.external = count ? reinterpret_cast<const uint8_t*>(v) : nullptr;+ e.externalSize = count * 2;+ entries.push_back(std::move(e));+ return descriptor(file, Scalar::U8, 2, count);+ } else {+ std::vector<uint8_t> data(count * 2);+ for (size_t i = 0; i < count; ++i) data[2 * i] = uint8_t(uint16_t(v[i])), data[2 * i + 1] = uint8_t(uint16_t(v[i]) >> 8);+ return add(file, Scalar::U8, 2, count, std::move(data));+ }+ }+ // Copied external-free: a byte array that must outlive the save.+ Json externalBytes(const std::string& file, const std::vector<uint8_t>& v) {+ ZipEntry e{file, {}};+ e.external = v.empty() ? nullptr : v.data();+ e.externalSize = v.size();+ entries.push_back(std::move(e));+ return descriptor(file, Scalar::U8, 1, v.size());+ }std::vector<ZipEntry> entries;@@ -220,6 +244,16 @@ public:out.resize(count);return read(desc, what, Scalar::U8, 1, count, out.data());}+ bool int16s(const Json& desc, const char* what, size_t count, std::vector<int16_t>& out) {+ out.resize(count);+ if (!read(desc, what, Scalar::U8, 2, count, out.data())) return false;+ if constexpr (std::endian::native != std::endian::little)+ for (int16_t& v : out) {+ const uint8_t* p = reinterpret_cast<const uint8_t*>(&v);+ v = int16_t(uint16_t(p[0]) | uint16_t(p[1]) << 8);+ }+ return true;+ }private:std::ifstream file_;@@ -767,6 +801,7 @@ bool saveProject(const std::string& path, const Document& doc, std::string& erromanifest.set("format", kFormatName);manifest.set("version", kProjectVersion);manifest.set("app_version", SCULPTFORGE_VERSION);+ bool anyMicro = false; // projects without micro levels stay format 6, so 0.9.7 and older still open them// Every SubTool with its mesh, layers and state; blobs live under subtools/<i>/.Json subtools = Json::array();@@ -785,6 +820,17 @@ bool saveProject(const std::string& path, const Document& doc, std::string& errost.set("texture", writeTexture(w, "subtools/" + std::to_string(i) + "/", doc.subtoolMesh(i)));if (subdivLevelCount(doc.subtoolMesh(i)))st.set("subdiv", writeSubdiv(w, "subtools/" + std::to_string(i) + "/", doc.subtoolMesh(i)));+ if (const Mesh& m = doc.subtoolMesh(i); m.micro && microMatches(m)) { // format 7: the micro level (core/Micro.h)+ const MicroMesh& mm = *m.micro;+ const std::string p = "subtools/" + std::to_string(i) + "/micro/";+ Json mj = Json::object();+ mj.set("level", mm.level);+ mj.set("step", double(mm.step));+ mj.set("displacement", w.int16s(p + "displacement.bin", mm.disp.data(), mm.disp.size()));+ if (mm.hasMask()) mj.set("mask", w.externalBytes(p + "mask.bin", mm.mask));+ st.set("micro", std::move(mj));+ anyMicro = true;+ }const std::string& gozName = active ? doc.gozName : s.gozName;if (!gozName.empty()) st.set("goz_name", gozName);const std::vector<QRemeshGuide>& guides = active ? doc.qremeshGuides : s.qremeshGuides;@@ -797,6 +843,7 @@ bool saveProject(const std::string& path, const Document& doc, std::string& erro}manifest.set("subtools", std::move(subtools));manifest.set("active_subtool", doc.activeSubtool);+ if (!anyMicro) manifest.set("version", kProjectVersionWithoutMicro);Json brushes = Json::array();for (const auto& b : doc.brushes) brushes.push(b.toJson());@@ -926,6 +973,23 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {s.finishBvh();r.parallelReads = true;s.mesh.recomputeAllNormals();+ if (const Json& mj = sj["micro"]; mj.isObject() && version >= 7) {+ const int level = int(mj["level"].asNumber(0));+ if (level < 1 || level > MicroMesh::kMaxLevel) {+ error = "Project micro level is invalid";+ return false;+ }+ const uint32_t n = 1u << level;+ const size_t count = s.mesh.triangleCount() * size_t((n + 1) * (n + 2) / 2);+ std::vector<int16_t> disp;+ std::vector<uint8_t> mask;+ if (!r.int16s(mj["displacement"], "micro displacement", count, disp) ||+ (mj["mask"].isObject() && !r.bytes(mj["mask"], "micro mask", count, mask))) {+ error = r.error;+ return false;+ }+ if (!microAttach(s.mesh, level, float(mj["step"].asNumber(0)), std::move(disp), std::move(mask), error)) return false;+ }s.activeLayer = int(sj["active_layer"].asNumber(-1));}const double active = manifest["active_subtool"].asNumber(0);diff --git a/src/core/Project.h b/src/core/Project.hindex 4ad2eae5..80ca0168 100644--- a/src/core/Project.h+++ b/src/core/Project.h@@ -24,8 +24,11 @@ namespace sf {// painted texture with layers ("texture"; older files still load). 4: SubTools may carry subdivision levels// ("subdiv"; older files still load). 5: sculpt-layer details of subdivision levels are in the levels' local// frames, not world space (format 4 files are converted when they load). 6: levels made by Divide keep no-// triangles, child maps or (where their positions say it) details; older files still load.-constexpr int kProjectVersion = 6;+// triangles, child maps or (where their positions say it) details; older files still load. 7: SubTools may carry a+// micro-displacement level ("micro", core/Micro.h); only projects with one are written as 7.+constexpr int kProjectVersion = 7;+// Projects without a micro level (core/Micro.h) are written as format 6, which older versions read.+constexpr int kProjectVersionWithoutMicro = 6;constexpr const char* kProjectExtension = ".sfproj";// True for paths ending in .sfproj (any case).diff --git a/src/core/Sculpt.cpp b/src/core/Sculpt.cppindex 389b0545..4045657a 100644--- a/src/core/Sculpt.cpp+++ b/src/core/Sculpt.cpp@@ -209,10 +209,20 @@ bool Sculptor::beginStroke(const Mesh& mesh, std::string label, int layer) {strokeDiagonal_ = 0.0f;lastRemesh_ = false;topologyHeld_ = false;+ microMesh_ = nullptr;active_ = true;return true;}+bool Sculptor::microReady(Mesh& mesh) {+ if (!mesh.micro || !microMatches(mesh)) return false;+ if (!micro_.active() || microMesh_ != &mesh) {+ micro_.begin(mesh);+ microMesh_ = &mesh;+ }+ return true;+}+void Sculptor::remeshDab(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym, float scale, float reach) {if (!dyntopo.enabled || topologyHeld_) return;auto clock = std::chrono::steady_clock::now();@@ -444,6 +454,8 @@ UndoRecord Sculptor::endStroke() {record_.topology = std::move(topo);}}+ if (micro_.active() && microMesh_) record_.micro = micro_.end(*microMesh_);+ microMesh_ = nullptr;clearRecorded();active_ = false;grabVerts_.clear();@@ -453,6 +465,18 @@ UndoRecord Sculptor::endStroke() {void Sculptor::dab(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p, Symmetry sym) {if (!active_) return;+ if (microReady(mesh)) { // a micro level: the grid takes the dab (core/MicroSculpt.cpp)+ const double k0 = micro_.findMs + micro_.kernelMs, s0 = micro_.stitchMs;+ const uint64_t pts = micro_.points;+ for (const glm::vec3& m : mirrors(sym))+ micro_.dab(mesh, bvh, type, p.center * m, p.viewDir * m, p.radius, p.strength * std::clamp(p.pressure, 0.0f, 1.0f),+ p.invert, p.focal, p.alphaUp * m, false, 0.0f);+ timings.kernelMs += micro_.findMs + micro_.kernelMs - k0;+ timings.normalsMs += micro_.stitchMs - s0;+ timings.vertices += micro_.points - pts;+ ++timings.dabs;+ return;+ }if (type != BrushType::Move) {const bool useAlpha = p.alpha && !p.alpha->empty(); // (the reach dabSingle gives the brush)const float reach = useAlpha ? 1.4143f : type == BrushType::ClayBuildup ? 1.3f : 1.0f;@@ -677,6 +701,10 @@ void Sculptor::updateDabNormals(Mesh& mesh, const BVH& bvh) {void Sculptor::dabRecipe(Mesh& mesh, BVH& bvh, const BrushRecipe& recipe, const DabParams& p, Symmetry sym) {if (!active_) return;+ if (mesh.micro && microMatches(mesh)) { // recipes aren't grid brushes: a micro level gets the Standard dab+ dab(mesh, bvh, BrushType::Standard, p, sym);+ return;+ }remeshDab(mesh, bvh, p, sym, 1.0f, 1.0f);DabParams base = p;base.pressure = std::pow(std::clamp(p.pressure, 0.0f, 1.0f), recipe.pressureCurve);@@ -829,6 +857,10 @@ void Sculptor::beginGrab(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym)grabAll_.clear();grabLeaves_.clear();if (!active_) return;+ if (microReady(mesh)) { // along the normals (a micro level can't move sideways)+ for (const glm::vec3& m : mirrors(sym)) micro_.beginGrab(mesh, bvh, p.center * m, p.radius, p.focal, m);+ return;+ }for (const glm::vec3& m : mirrors(sym)) {glm::vec3 c = p.center * m;brushVertices(mesh, bvh, c, p.radius, verts_);@@ -856,6 +888,14 @@ void Sculptor::beginGrab(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym)}void Sculptor::grab(Mesh& mesh, BVH& bvh, const glm::vec3& delta) {+ if (micro_.active() && microMesh_ == &mesh) {+ const double k0 = micro_.kernelMs, s0 = micro_.stitchMs;+ micro_.grab(mesh, delta);+ timings.kernelMs += micro_.kernelMs - k0;+ timings.normalsMs += micro_.stitchMs - s0;+ ++timings.dabs;+ return;+ }if (grabVerts_.empty()) return;auto clock = std::chrono::steady_clock::now();// One mirror after another (a vertex may be in two), each in parallel.@@ -881,6 +921,10 @@ void Sculptor::grab(Mesh& mesh, BVH& bvh, const glm::vec3& delta) {// Puts every vertex the current stroke moved back to its stroke-start position.void Sculptor::restoreStroke(Mesh& mesh, BVH& bvh) {if (!active_) return;+ if (micro_.active() && microMesh_ == &mesh) {+ micro_.restore(mesh);+ return;+ }topologyHeld_ = true; // (positions come back, topology wouldn't)// Polypaint laid down by the stroke so far (Paint brush / RGB while sculpting).if (!record_.colors.empty() && mesh.hasColors()) {diff --git a/src/core/Sculpt.h b/src/core/Sculpt.hindex 674e5c8a..fa86d31d 100644--- a/src/core/Sculpt.h+++ b/src/core/Sculpt.h@@ -118,6 +118,9 @@ public:// DragDot; restoreStroke) put positions back, not topology. restoreStroke holds it too.void holdTopology() { topologyHeld_ = true; }+ // Micro level timings (findMs, kernelMs, stitchMs, points) of the current stroke (core/Micro.h).+ const MicroStroke& microStroke() const { return micro_; }+ MicroStroke& microStroke() { return micro_; }// Mirror sign vectors for the enabled symmetry axes (always starts with (1,1,1)).static std::vector<glm::vec3> mirrors(Symmetry sym);@@ -143,6 +146,10 @@ private:void followRemesh(Mesh& mesh);void mergeTopologyUndo(TopologyUndo& topo, const Mesh& mesh);DynamicTopology dynTopo_;+ // Micro-displacement levels (core/Micro.h): strokes on a mesh with one go to its grid instead.+ MicroStroke micro_;+ Mesh* microMesh_ = nullptr;+ bool microReady(Mesh& mesh); // the mesh has a micro level: starts the micro stroke on first usefloat strokeDiagonal_ = 0.0f;// The last remesh (repairDab remeshes it again when the brush squashed a triangle).bool lastRemesh_ = false;diff --git a/src/core/Undo.cpp b/src/core/Undo.cppindex 84e46d5a..1e76d364 100644--- a/src/core/Undo.cpp+++ b/src/core/Undo.cpp@@ -10,7 +10,8 @@ size_t UndoRecord::approxBytes() const {size_t bytes = positions.bytes() + mask.bytes() + colors.bytes() + paintAlpha.bytes() + hidden.bytes() +polygroups.bytes() + (paint ? paint->bytes() : 0) +(textureTiles ? textureTiles->bytes() : 0) + (texture ? texture->bytes() : 0) +- (subdiv ? subdiv->bytes() : 0) + (topology ? topology->bytes() : 0);+ (subdiv ? subdiv->bytes() : 0) + (topology ? topology->bytes() : 0) ++ (micro ? micro->bytes() : 0);for (const auto& l : layerOffsets) bytes += l.bytes();if (mesh)bytes += mesh->vertexCount() * ((2 + (mesh->base.empty() ? 0 : 1 + mesh->layers.size())) * sizeof(glm::vec3) +@@ -152,6 +153,7 @@ void UndoStack::apply(UndoRecord& r, Mesh& mesh, BVH& bvh) {applySubdivUndo(*r.subdiv, mesh, bvh);return;}+ if (r.micro) r.micro->swapWith(mesh); // (the base doesn't move: no BVH work)if (r.mesh) {std::swap(*r.mesh, mesh);mesh.topologyDirty = true;diff --git a/src/core/Undo.h b/src/core/Undo.hindex 2f3e4de0..a17e0b78 100644--- a/src/core/Undo.h+++ b/src/core/Undo.h@@ -5,6 +5,7 @@#include "core/BVH.h"#include "core/Dyntopo.h"#include "core/Mesh.h"+#include "core/Micro.h"#include "core/Multires.h"#include "core/ThreadPool.h"@@ -110,6 +111,7 @@ inline constexpr int kActivePaintLayer = -2;// - subdiv: a subdivision level step or level edit (core/Multires.h), applied on its own// - topology: the slots a dynamic-topology stroke changed (core/Dyntopo.h), applied before the channels// - subtool: a SubTool added to the scene (Extract), taken out on undo and put back on redo+// - micro: the grid tiles a stroke on a micro level changed, or a whole micro level (core/Micro.h)// Record old values before changing them (ensureX() the attribute first);// undo allocates a missing attribute so values can always be restored.struct UndoRecord {@@ -132,10 +134,11 @@ struct UndoRecord {std::unique_ptr<SubdivUndo> subdiv;std::unique_ptr<TopologyUndo> topology;std::shared_ptr<SubtoolStep> subtool; // (shared: SubtoolStep is defined in core/Document.h)+ std::unique_ptr<MicroUndo> micro; // micro-displacement tiles of a stroke, or a micro level added / removed (core/Micro.h)bool empty() const {return positions.empty() && mask.empty() && colors.empty() && paintAlpha.empty() && hidden.empty() &&- polygroups.empty() && !mesh && !paint && !textureTiles && !texture && !subdiv && !topology && !subtool;+ polygroups.empty() && !mesh && !paint && !textureTiles && !texture && !subdiv && !topology && !subtool && !micro;}size_t approxBytes() const;diff --git a/tests/test_micro.cpp b/tests/test_micro.cppnew file mode 100644index 00000000..cf10b9ad--- /dev/null+++ b/tests/test_micro.cpp@@ -0,0 +1,433 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Micro-displacement levels (core/Micro.h): divide, brushes, stitching, undo, picking, shading, bake, maps,+// projects and the commands.+#include "TestHarness.h"++#include "core/Benchmark.h"+#include "core/Commands.h"+#include "core/Micro.h"+#include "core/Multires.h"+#include "core/Primitives.h"+#include "core/Project.h"+#include "io/Zip.h"++#include <chrono>+#include <cmath>+#include <cstdlib>+#include <cstring>+#include <filesystem>+#include <map>++using namespace sf;++namespace {++Document microDoc(int level, size_t baseTriangles = 20000) {+ Document doc = makeDoc(makeBenchSphere(baseTriangles));+ std::string err;+ CHECK(microDivide(doc.mesh, level, err));+ return doc;+}++// Every point shared by two base triangles (edges) or more (corners) has the same displacement in each copy, and+// the micro positions there are bit-identical.+bool watertight(const Mesh& m) {+ const MicroMesh& mm = *m.micro;+ const uint32_t n = mm.n, S = mm.samples;+ for (uint32_t t = 0; t < mm.baseTriangles; ++t)+ for (int e = 0; e < 3; ++e) {+ const uint32_t nb = mm.edgeNeighbor[size_t(t) * 3 + size_t(e)];+ if (nb == MicroMesh::kNone) continue;+ const uint32_t u = nb >> 2;+ const int f = int(nb & 3);+ const bool reversed = m.triangles[u][f] != m.triangles[t][e];+ for (uint32_t k = 0; k <= n; ++k) {+ uint32_t i, j, i2, j2;+ MicroMesh::edgePoint(e, k, n, i, j);+ MicroMesh::edgePoint(f, reversed ? n - k : k, n, i2, j2);+ if (mm.disp[size_t(t) * S + MicroMesh::index(i, j, n)] != mm.disp[size_t(u) * S + MicroMesh::index(i2, j2, n)])+ return false;+ const glm::vec3 a = microPoint(m, t, i, j), b = microPoint(m, u, i2, j2);+ if (std::memcmp(&a, &b, sizeof a) != 0) return false;+ }+ }+ return true;+}++DabParams dabAt(const glm::vec3& c, float r, float strength = 0.5f) {+ DabParams p;+ p.center = c;+ p.radius = r;+ p.strength = strength;+ p.viewDir = glm::vec3(0, 0, -1);+ return p;+}++// The micro surface's distance from the origin under the point (0, 0, 1) (the sphere's front).+float frontHeight(const Document& doc) {+ RayHit hit;+ CHECK(microRaycast(doc.mesh, doc.bvh, glm::vec3(0.001f, 0.002f, 5.0f), glm::vec3(0, 0, -1), hit));+ return glm::length(hit.position);+}++} // namespace++TEST(micro_divide_counts_and_memory) {+ Document doc = microDoc(3);+ const MicroMesh& mm = *doc.mesh.micro;+ CHECK(mm.n == 8);+ CHECK(mm.samples == 45);+ CHECK(microTriangleCount(doc.mesh) == doc.mesh.triangleCount() * 64);+ CHECK(mm.disp.size() == doc.mesh.triangleCount() * 45);+ // 2 bytes a point, about 1.4 points per unique micro vertex at level 3: well under 4 bytes per micro vertex.+ CHECK(double(mm.disp.size() * 2) / double(mm.microVertices()) < 3.0);+ CHECK(microText(doc.mesh).rfind("Micro 3", 0) == 0);+ // Every base edge has a neighbour on a closed sphere.+ for (uint32_t e : mm.edgeNeighbor) CHECK(e != MicroMesh::kNone);+ // d = 0 everywhere: the surface is the smooth Phong surface, close to the unit sphere.+ // (The bench sphere is a subdivided cube: compare with the radius of each base triangle's corners. The flat+ // triangles sag inwards by up to e^2 / 8; Phong tessellation takes most of that back.)+ float worstMicro = 0.0f, worstFlat = 0.0f;+ for (uint32_t t = 0; t < mm.baseTriangles; t += 97) {+ const glm::uvec3 tr = doc.mesh.triangles[t];+ const float r = (glm::length(doc.mesh.positions[tr.x]) + glm::length(doc.mesh.positions[tr.y]) + glm::length(doc.mesh.positions[tr.z])) / 3.0f;+ MicroTriangle T;+ T.set(doc.mesh, t, mm.n);+ for (uint32_t j = 0; j <= mm.n; ++j)+ for (uint32_t i = 0; i + j <= mm.n; ++i) {+ worstMicro = std::max(worstMicro, std::abs(glm::length(microPoint(doc.mesh, t, i, j)) - r));+ worstFlat = std::max(worstFlat, std::abs(glm::length(T.flat(i, j)) - r));+ }+ }+ CHECK(worstMicro < worstFlat * 0.5f);+ CHECK(watertight(doc.mesh));+ std::string err;+ CHECK(!microDivide(doc.mesh, 2, err)); // one micro level per SubTool+}++TEST(micro_divide_needs_top_level) {+ Document doc = makeDoc(makeBenchSphere(20000));+ std::string err;+ CHECK(subdivSetLevel(doc.mesh, 0, err, &doc.bvh));+ CHECK(!microDivide(doc.mesh, 2, err));+ CHECK(err.find("highest") != std::string::npos);+ CHECK(subdivSetLevel(doc.mesh, subdivLevelCount(doc.mesh) - 1, err, &doc.bvh));+ CHECK(microDivide(doc.mesh, 2, err));+ // ... and blocks subdivision changes while it exists.+ CHECK(!subdivSetLevel(doc.mesh, 0, err, &doc.bvh));+ CHECK(err.find("micro") != std::string::npos);+ CHECK(!subdivDivide(doc.mesh, true, err));+}++TEST(micro_standard_brush_raises_and_undoes) {+ Document doc = microDoc(4);+ const std::vector<int16_t> before = doc.mesh.micro->disp;+ const float h0 = frontHeight(doc);+ Symmetry sym;+ CHECK(doc.sculptor.beginStroke(doc.mesh, "Standard"));+ for (int i = 0; i < 10; ++i) doc.sculptor.dab(doc.mesh, doc.bvh, BrushType::Standard, dabAt(glm::vec3(0, 0, 1), 0.3f), sym);+ UndoRecord r = doc.sculptor.endStroke();+ CHECK(r.micro != nullptr);+ CHECK(!r.empty());+ CHECK(r.micro->tris.size() > 0 && r.micro->tris.size() < doc.mesh.triangleCount());+ doc.undo.push(std::move(r));+ const float h1 = frontHeight(doc);+ CHECK(h1 > h0 + 0.01f);+ CHECK(watertight(doc.mesh));+ // X symmetry: the mirrored side moved too, the back didn't.+ CHECK(doc.mesh.micro->rangeMax > 0);+ const std::vector<int16_t> after = doc.mesh.micro->disp;+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));+ CHECK(doc.mesh.micro->disp == before);+ CHECK(doc.undo.redo(doc.mesh, doc.bvh));+ CHECK(doc.mesh.micro->disp == after);+}++TEST(micro_brushes_each_change_the_surface_and_stay_closed) {+ struct Case {+ BrushType type;+ bool invert;+ };+ for (const Case c : {Case{BrushType::Clay, false}, Case{BrushType::ClayBuildup, false}, Case{BrushType::Inflate, false},+ Case{BrushType::Flatten, false}, Case{BrushType::Crease, false}, Case{BrushType::Pinch, false},+ Case{BrushType::DamStandard, false}, Case{BrushType::Layer, false}, Case{BrushType::Trim, false},+ Case{BrushType::Standard, true}}) {+ Document doc = microDoc(3);+ microNoise(doc.mesh, 0.01f, 12.0f); // something to flatten, trim and pinch+ const std::vector<int16_t> before = doc.mesh.micro->disp;+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, brushName(c.type));+ for (int i = 0; i < 6; ++i) {+ DabParams p = dabAt(glm::normalize(glm::vec3(0.1f * float(i), 0.2f, 1.0f)), 0.25f, 0.8f);+ p.invert = c.invert;+ doc.sculptor.dab(doc.mesh, doc.bvh, c.type, p, sym);+ }+ UndoRecord r = doc.sculptor.endStroke();+ CHECK(doc.mesh.micro->disp != before);+ CHECK(watertight(doc.mesh));+ doc.undo.push(std::move(r));+ doc.undo.undo(doc.mesh, doc.bvh);+ CHECK(doc.mesh.micro->disp == before);+ }+}++TEST(micro_smooth_flattens_noise) {+ Document doc = microDoc(3);+ microNoise(doc.mesh, 0.01f, 30.0f);+ auto roughness = [&] { // spread of the displacement in the triangles near the front+ double sum = 0, sq = 0;+ size_t count = 0;+ const MicroMesh& mm = *doc.mesh.micro;+ for (uint32_t t = 0; t < mm.baseTriangles; ++t) {+ const glm::uvec3 tr = doc.mesh.triangles[t];+ if (doc.mesh.positions[tr.x].z < 0.97f) continue;+ for (uint32_t k = 0; k < mm.samples; ++k) {+ const double v = mm.disp[size_t(t) * mm.samples + k];+ sum += v, sq += v * v, ++count;+ }+ }+ const double mean = sum / double(count);+ return sq / double(count) - mean * mean;+ };+ const double r0 = roughness();+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, "Smooth");+ for (int i = 0; i < 8; ++i) doc.sculptor.dab(doc.mesh, doc.bvh, BrushType::Smooth, dabAt(glm::vec3(0, 0, 1), 0.4f, 1.0f), sym);+ doc.undo.push(doc.sculptor.endStroke());+ CHECK(roughness() < r0 * 0.5);+ CHECK(watertight(doc.mesh));+}++TEST(micro_mask_brush_protects) {+ Document doc = microDoc(3);+ Symmetry sym;+ sym.x = false;+ // Mask the front.+ CHECK(doc.sculptor.beginStroke(doc.mesh, "Mask"));+ DabParams mp = dabAt(glm::vec3(0, 0, 1), 0.5f, 1.0f);+ for (int i = 0; i < 8; ++i) doc.sculptor.dabMask(doc.mesh, doc.bvh, mp, sym);+ UndoRecord mr = doc.sculptor.endStroke();+ CHECK(doc.mesh.micro->hasMask());+ CHECK(mr.micro && mr.micro->maskAdded);+ doc.undo.push(std::move(mr));+ const float h0 = frontHeight(doc);+ doc.sculptor.beginStroke(doc.mesh, "Standard");+ for (int i = 0; i < 5; ++i) doc.sculptor.dab(doc.mesh, doc.bvh, BrushType::Standard, dabAt(glm::vec3(0, 0, 1), 0.3f), sym);+ doc.undo.push(doc.sculptor.endStroke());+ CHECK(std::abs(frontHeight(doc) - h0) < 1e-4f); // fully masked at the centre+ // Undo both: the mask goes away again (it didn't exist before).+ doc.undo.undo(doc.mesh, doc.bvh);+ doc.undo.undo(doc.mesh, doc.bvh);+ CHECK(!doc.mesh.micro->hasMask());+ doc.undo.redo(doc.mesh, doc.bvh);+ CHECK(doc.mesh.micro->hasMask());+}++TEST(micro_move_brush_moves_along_normals) {+ Document doc = microDoc(3);+ const float h0 = frontHeight(doc);+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, "Move");+ doc.sculptor.beginGrab(doc.mesh, doc.bvh, dabAt(glm::vec3(0, 0, 1), 0.3f, 1.0f), sym);+ for (int i = 0; i < 5; ++i) doc.sculptor.grab(doc.mesh, doc.bvh, glm::vec3(0, 0, 0.02f));+ doc.undo.push(doc.sculptor.endStroke());+ CHECK(frontHeight(doc) > h0 + 0.05f);+ CHECK(watertight(doc.mesh));+}++TEST(micro_range_widens_for_big_strokes) {+ Document doc = microDoc(2);+ const float step0 = doc.mesh.micro->step;+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, "Standard");+ for (int i = 0; i < 60; ++i) doc.sculptor.dab(doc.mesh, doc.bvh, BrushType::Standard, dabAt(glm::vec3(0, 0, 1), 0.8f, 1.0f), sym);+ UndoRecord r = doc.sculptor.endStroke();+ CHECK(doc.mesh.micro->step > step0);+ CHECK(frontHeight(doc) > 1.5f); // nothing clipped at the old range (+/- 8 base edges)+ doc.undo.push(std::move(r));+ doc.undo.undo(doc.mesh, doc.bvh);+ CHECK(std::abs(frontHeight(doc) - 1.0f) < 0.01f);+}++TEST(micro_raycast_hits_the_micro_surface) {+ Document doc = microDoc(4);+ RayHit base, micro;+ CHECK(doc.bvh.raycast(doc.mesh, glm::vec3(0.01f, 0.01f, 5), glm::vec3(0, 0, -1), base));+ CHECK(microRaycast(doc.mesh, doc.bvh, glm::vec3(0.01f, 0.01f, 5), glm::vec3(0, 0, -1), micro));+ CHECK(std::abs(micro.position.z - base.position.z) < 1e-3f); // flat: the Phong surface is near the base+ microNoise(doc.mesh, 0.02f, 8.0f);+ CHECK(surfaceRaycast(doc.mesh, doc.bvh, glm::vec3(0.01f, 0.01f, 5), glm::vec3(0, 0, -1), micro));+ // The hit lies on the micro surface: its point at the hit's base triangle and weights matches.+ const float h = glm::length(micro.position);+ CHECK(std::abs(h - 1.0f) < 0.03f);+ CHECK(std::abs(micro.t - (5.0f - micro.position.z)) < 1e-4f);+}++TEST(micro_shading_partial_matches_full) {+ Document doc = microDoc(3, 5000);+ microNoise(doc.mesh, 0.01f, 10.0f);+ const MicroMesh& mm = *doc.mesh.micro;+ std::vector<uint32_t> full(size_t(mm.baseTriangles) * mm.samples, 0), part(full.size(), 0);+ MicroShader shader;+ std::vector<uint32_t> written;+ shader.shade(doc.mesh, {}, true, written, [&](uint32_t t) { return full.data() + size_t(t) * mm.samples; });+ CHECK(written.size() == mm.baseTriangles);+ // A brush changes a few triangles; shading just what changed must agree with shading everything.+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, "Standard");+ doc.sculptor.dab(doc.mesh, doc.bvh, BrushType::Standard, dabAt(glm::vec3(0, 0, 1), 0.2f, 1.0f), sym);+ UndoRecord r = doc.sculptor.endStroke();+ std::vector<uint32_t> dirty = r.micro->tris;+ part = full;+ shader.shade(doc.mesh, dirty, false, written, [&](uint32_t t) { return part.data() + size_t(t) * mm.samples; });+ CHECK(written.size() > dirty.size());+ shader.shade(doc.mesh, {}, true, written, [&](uint32_t t) { return full.data() + size_t(t) * mm.samples; });+ CHECK(part == full);+ // Normals point outwards on the sphere.+ int outward = 0, total = 0;+ for (uint32_t t = 0; t < mm.baseTriangles; t += 53) {+ const uint32_t v = full[size_t(t) * mm.samples];+ const float ex = float(v & 255) / 255.0f * 2.0f - 1.0f, ey = float((v >> 8) & 255) / 255.0f * 2.0f - 1.0f;+ glm::vec3 nn(ex, ey, 1.0f - std::abs(ex) - std::abs(ey));+ const float tt = std::max(-nn.z, 0.0f);+ nn.x += nn.x >= 0.0f ? -tt : tt;+ nn.y += nn.y >= 0.0f ? -tt : tt;+ outward += glm::dot(glm::normalize(nn), doc.mesh.positions[doc.mesh.triangles[t].x]) > 0.8f;+ ++total;+ }+ CHECK(outward >= total * 9 / 10);+}++TEST(micro_bake_mesh_is_closed_and_matches) {+ Document doc = microDoc(3, 3000);+ microNoise(doc.mesh, 0.01f, 10.0f);+ Mesh baked;+ std::string err;+ CHECK(microBakeMesh(doc.mesh, 3, baked, err));+ CHECK(baked.triangleCount() == microTriangleCount(doc.mesh));+ CHECK(baked.vertexCount() == doc.mesh.micro->microVertices());+ // Closed: Euler characteristic 2 (V - E + F with E = 3F/2).+ CHECK(long(baked.vertexCount()) - long(baked.triangleCount()) * 3 / 2 + long(baked.triangleCount()) == 2);+ // The base corners are the micro points there.+ const glm::vec3 c = microPoint(doc.mesh, 0, 0, 0);+ CHECK(glm::distance(baked.positions[doc.mesh.triangles[0].x], c) < 1e-6f);+ // Half the level: a quarter of the triangles.+ Mesh half;+ CHECK(microBakeMesh(doc.mesh, 2, half, err));+ CHECK(half.triangleCount() * 4 == baked.triangleCount());+ CHECK(!microBakeMesh(doc.mesh, 3, baked, err, 1000)); // the size limit+}++TEST(micro_displacement_maps) {+ Mesh plane = makePlane(16, 2.0f);+ plane.uvs.resize(plane.triangleCount() * 3);+ for (size_t t = 0; t < plane.triangleCount(); ++t)+ for (int k = 0; k < 3; ++k) {+ const glm::vec3 p = plane.positions[plane.triangles[t][k]];+ plane.uvs[t * 3 + size_t(k)] = glm::vec2(p.x * 0.5f + 0.5f, p.z * 0.5f + 0.5f);+ }+ Document doc = makeDoc(std::move(plane));+ std::string err;+ CHECK(microDivide(doc.mesh, 3, err));+ microNoise(doc.mesh, 0.02f, 6.0f);+ float scale = 0.0f;+ const std::string exr = tempPath("sf_micro_disp.exr"), png = tempPath("sf_micro_disp.png");+ CHECK(microExportDisplacement(doc.mesh, exr, 128, false, "exr", scale, err));+ CHECK(scale > 0.001f && scale < 0.1f);+ CHECK(std::filesystem::file_size(exr) > 128 * 128 * 4);+ CHECK(microExportDisplacement(doc.mesh, png, 64, true, "png", scale, err));+ CHECK(std::filesystem::exists(png));+ std::filesystem::remove(exr);+ std::filesystem::remove(png);+ Document sphere = microDoc(2, 3000);+ CHECK(!microExportDisplacement(sphere.mesh, exr, 64, false, "exr", scale, err)); // no UVs+ CHECK(err.find("UV") != std::string::npos);+}++TEST(micro_project_round_trip) {+ Document doc = microDoc(3, 5000);+ microNoise(doc.mesh, 0.01f, 10.0f);+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, "Mask");+ doc.sculptor.dabMask(doc.mesh, doc.bvh, dabAt(glm::vec3(0, 0, 1), 0.3f, 1.0f), sym);+ doc.undo.push(doc.sculptor.endStroke());+ const std::string path = tempPath("sf_micro_round_trip.sfproj");+ std::string err;+ CHECK(saveProject(path, doc, err));+ auto version = [&] {+ std::vector<ZipEntry> entries;+ Json manifest;+ std::string e;+ if (!readStoredZip(path, entries, e) || entries.empty() ||+ !Json::parse(std::string(entries[0].data.begin(), entries[0].data.end()), manifest, e))+ return -1;+ return int(manifest["version"].asNumber());+ };+ CHECK(version() == 7);+ Document loaded;+ CHECK(loadProject(path, loaded, err));+ CHECK(loaded.mesh.micro != nullptr);+ if (loaded.mesh.micro) {+ CHECK(loaded.mesh.micro->level == 3);+ CHECK(loaded.mesh.micro->step == doc.mesh.micro->step);+ CHECK(loaded.mesh.micro->disp == doc.mesh.micro->disp);+ CHECK(loaded.mesh.micro->mask == doc.mesh.micro->mask);+ CHECK(loaded.mesh.micro->rangeMax == doc.mesh.micro->rangeMax);+ }+ std::filesystem::remove(path);+ // Without a micro level a project stays format 6 (0.9.7 and older open it).+ Document plain = makeDoc(makeIcosphere(2));+ CHECK(saveProject(path, plain, err));+ CHECK(version() == 6);+ Document again;+ CHECK(loadProject(path, again, err));+ CHECK(again.projectSettings.isObject());+ std::filesystem::remove(path);+}++TEST(micro_commands) {+ CommandRegistry reg;+ Document doc = makeDoc(makeBenchSphere(20000));+ CHECK(reg.execute(doc, "micro_info").ok);+ CommandResult r = reg.execute(doc, "micro_divide", {{"triangles", 1.0}});+ CHECK(r.ok);+ CHECK(doc.mesh.micro != nullptr);+ CHECK(microLevel(doc.mesh) == microLevelFor(doc.mesh, 1000000));+ CHECK(reg.execute(doc, "micro_noise", {{"amplitude", 0.002}}).ok);+ CHECK(reg.execute(doc, "micro_info").message.find("Micro level") != std::string::npos);+ CHECK(reg.execute(doc, "micro_bake", {{"level", 1.0}}).ok);+ CHECK(doc.subtoolCount() == 2);+ CHECK(reg.execute(doc, "micro_delete").ok);+ CHECK(doc.mesh.micro == nullptr);+ CHECK(reg.execute(doc, "undo").ok);+ CHECK(doc.mesh.micro != nullptr);+ CHECK(reg.execute(doc, "undo").ok); // the noise+ CHECK(reg.execute(doc, "undo").ok); // the divide+ CHECK(doc.mesh.micro == nullptr);+}++// The point of micro levels: memory and dab time on a dense surface. 5M micro triangles here (fast enough for+// every ctest run); --bench-micro measures 33M - 300M. Timing limits only with SF_BENCH_LIMITS=1.+TEST(micro_memory_and_dab_time) {+ Document doc = makeDoc(makeBenchSphere(80000));+ std::string err;+ const size_t rss0 = residentBytes();+ CHECK(microDivide(doc.mesh, 3, err));+ const MicroMesh& mm = *doc.mesh.micro;+ CHECK(mm.microTriangles() > 4'000'000);+ const double bytesPerMicroTriangle = double(mm.bytes()) / double(mm.microTriangles());+ CHECK(bytesPerMicroTriangle < 2.0);+ (void)rss0;+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, "Standard");+ const auto t0 = std::chrono::steady_clock::now();+ for (int i = 0; i < 20; ++i)+ doc.sculptor.dab(doc.mesh, doc.bvh, BrushType::Standard, dabAt(glm::normalize(glm::vec3(0.02f * float(i), 0.1f, 1)), 0.12f), sym);+ const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count() / 20.0;+ doc.undo.push(doc.sculptor.endStroke());+ std::printf(" micro dab at %.1fM micro triangles: %.2f ms, %.2f bytes/micro triangle\n", double(mm.microTriangles()) / 1e6,+ ms, bytesPerMicroTriangle);+ if (std::getenv("SF_BENCH_LIMITS")) CHECK(ms < 10.0);+}diff --git a/tests/test_project.cpp b/tests/test_project.cppindex 556aba14..175841fb 100644--- a/tests/test_project.cpp+++ b/tests/test_project.cpp@@ -248,7 +248,7 @@ TEST(project_version_handling) {std::string err;CHECK(saveProject(path, doc, err));const std::string manifest = readManifest(path);- const std::string v = std::to_string(kProjectVersion);+ const std::string v = std::to_string(kProjectVersionWithoutMicro); // (7 only with a micro level: test_micro.cpp)CHECK(manifest.find("\"version\": " + v) != std::string::npos || manifest.find("\"version\":" + v) != std::string::npos);CHECK(manifest.find("app_version") != std::string::npos);diff --git a/tests/test_subtool_io.cpp b/tests/test_subtool_io.cppindex 7a6538a2..df04644b 100644--- a/tests/test_subtool_io.cpp+++ b/tests/test_subtool_io.cpp@@ -179,7 +179,7 @@ TEST(subtool_project_v2_round_trip) {CHECK(readStoredZip(path, entries, err));Json manifest;CHECK(!entries.empty() && Json::parse(std::string(entries[0].data.begin(), entries[0].data.end()), manifest, err));- CHECK(manifest["version"].asNumber() == kProjectVersion && manifest["subtools"].size() == 3);+ CHECK(manifest["version"].asNumber() == kProjectVersionWithoutMicro && manifest["subtools"].size() == 3);CHECK(manifest["active_subtool"].asNumber() == 1 && !manifest.has("mesh"));CHECK(manifest["subtools"][1]["goz_name"].asString() == "Eye_ZB");