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
Mesh Maps bake (phase 2): curvature, thickness, position, ID; own-level sources; UDIM; in-texture maps
islandmed0fc814d39005
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5762d696..52595821 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,16 @@ All notable changes to SculptForge are listed here. The format followstexture use a roughness and metallic set there. A new environment is prepared on a worker thread, and a20.9-million-triangle mesh draws in about 8 ms in PBR next to about 6 ms with Lit Sphere (Apple M1 Pro).Saved with the project (`viewport_shading mode=pbr environment=outdoor_sky exposure=0.5 tone_map=agx`).+- Mesh Maps bake: **Tool > Bake** adds **Curvature** (convex edges bright, creases dark, from the surface's mean+ curvature at a set radius), **Thickness** (how far rays travel inside), **Position** (16-bit) and **ID** (a colour+ per polygroup or per Part) to the normal, world normal, displacement, AO, cavity and colour maps. The source can+ be the Part's own **top subdivision level** (baked onto its lowest level) or its **micro level** (onto its base),+ besides other Parts. UVs outside 0..1 bake as **UDIM tiles** (`name_normal.1001.png`, `1002`, ...). The bake runs+ on a worker thread with progress and Cancel (`bake source=subdivision maps=normal,ao,curvature,thickness,position,id`).+- Mesh Maps in the texture (`mesh_maps`): AO, curvature, thickness, position, world normal and ID baked on the+ texture's own UVs and size, tile by tile on every core, for Fill layers to read. After sculpting, only the tiles+ near the change are baked again, from a compact copy of the nearby triangles, and the result matches a full bake+ texel for texel (2K maps of an 82k-triangle Part: about 10 s in full, about 0.5 s for a local change).## [0.10.4] - 2026-11-01diff --git a/CMakeLists.txt b/CMakeLists.txtindex 49b3df1d..832f08c0 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -74,6 +74,7 @@ add_library(sculptforge_core STATICsrc/core/TextureCommands.cppsrc/core/TileImage.cppsrc/core/EnvironmentMath.cpp+ src/core/MeshMaps.cppsrc/core/TextureChannels.cppsrc/core/TextureChannelCommands.cppsrc/core/LayerStackIO.cppdiff --git a/src/app/PanelBake.cpp b/src/app/PanelBake.cppindex ae253c1a..86fc15e0 100644--- a/src/app/PanelBake.cpp+++ b/src/app/PanelBake.cpp@@ -13,6 +13,8 @@#include "app/Ui.h"#include "core/Bake.h"+#include "core/Micro.h"+#include "core/Multires.h"#include <IconsLucide.h>@@ -78,6 +80,7 @@ struct BakeUiState {BakeSettings settings;int sizeChoice = 1; // 2Kuint32_t source = 0; // SubTool id to bake from; 0 = every visible SubTool but the active one+ int levelSource = 0; // 1: the active Part's top subdivision level onto its lowest, 2: its micro levelchar folder[1024] = ""; // empty = beside the last export / the project / <library>/Bakesbool exr = true;bool preview = true; // show the baked normal map on the low-poly@@ -93,6 +96,8 @@ struct BakeUiState {uint32_t subtool = 0;size_t triangles = 0;std::string folder;+ bool preview = true; // the bake is of the active Part as it is (no other level, no UDIM tiles)+ std::shared_ptr<int> tiles; // UDIM tiles baked (0: a plain bake)};std::unique_ptr<Job> job;@@ -208,9 +213,10 @@ void App::registerBakeUiActions() {actions_.add(std::move(a));};add("bake.run", "Bake", [this] { startBake(); }, nullptr,- [this] { return !bake_->job && doc_.mesh.hasUvs() && doc_.subtoolCount() > 1; },- "Bake the chosen maps from the source SubTool(s) onto this SubTool's UVs, in the background. Maps are saved as "- "PNGs (displacement also as a 32-bit EXR) in the output folder, and the normal map shows on the model.",+ [this] { return !bake_->job && doc_.mesh.hasUvs() && (doc_.subtoolCount() > 1 || bake_->levelSource); },+ "Bake the chosen maps from the source SubTool(s), or this Part's own top subdivision or micro level, onto its "+ "UVs, in the background. Maps are saved as PNGs (displacement also as a 32-bit EXR, position as a 16-bit PNG) "+ "in the output folder, one set per UDIM tile when the UVs use them, and the normal map shows on the model.","bake");add("bake.cancel", "Cancel Bake", [this] {if (bake_->job) bake_->job->cancel->store(true);@@ -240,19 +246,30 @@ void App::registerBakeUiActions() {void App::startBake() {BakeUiState& b = *bake_;if (b.job) return;- if (!doc_.mesh.hasUvs()) {- status_ = "Bake needs UVs on this SubTool (the low-poly): Tool > Texture Map > Auto UV";- return;- }- // Source SubTools: the chosen one, or every visible SubTool but this one.- std::string source = "all";- for (int i = 0; i < doc_.subtoolCount(); ++i)- if (b.source && doc_.subtools[size_t(i)].id == b.source) source = doc_.subtools[size_t(i)].name;+ // Source: the active Part's own levels, or other Parts (the chosen one, or every visible Part but this one).+ auto low = std::make_shared<Mesh>();+ auto sources = std::make_shared<std::vector<Mesh>>();std::vector<int> idx;std::string err;- if (!bakeSourceSubtools(doc_, source, idx, err)) {- status_ = err;- return;+ if (b.levelSource) {+ Mesh high;+ if (!bakeLevelSources(doc_.mesh, b.levelSource == 1 ? "subdivision" : "micro", *low, high, err)) {+ status_ = err;+ return;+ }+ sources->push_back(std::move(high));+ } else {+ if (!doc_.mesh.hasUvs()) {+ status_ = "Bake needs UVs on this SubTool (the low-poly): Tool > Texture Map > Auto UV";+ return;+ }+ std::string source = "all";+ for (int i = 0; i < doc_.subtoolCount(); ++i)+ if (b.source && doc_.subtools[size_t(i)].id == b.source) source = doc_.subtools[size_t(i)].name;+ if (!bakeSourceSubtools(doc_, source, idx, err)) {+ status_ = err;+ return;+ }}if (doc_.sculptor.strokeActive()) endStroke();BakeSettings st = b.settings;@@ -281,26 +298,40 @@ void App::startBake() {job->triangles = doc_.mesh.triangleCount();job->folder = folder;// The worker bakes copies, so sculpting can go on meanwhile.- auto low = std::make_shared<Mesh>(doc_.mesh);- auto sources = std::make_shared<std::vector<Mesh>>();- for (int i : idx) sources->push_back(doc_.subtoolMesh(i));+ if (!b.levelSource) {+ *low = doc_.mesh;+ for (int i : idx) sources->push_back(doc_.subtoolMesh(i));+ }+ job->preview = !b.levelSource && udimTiles(*low).empty();+ job->tiles = std::make_shared<int>(0);std::promise<bool> promise;job->done = promise.get_future();std::thread([promise = std::move(promise), low, sources, st, folder, name = safeName(doc_.activeSubtoolInfo().name),exr = b.exr, progress = job->progress, cancel = job->cancel, result = job->result, error = job->error,- files = job->files]() mutable {+ files = job->files, tiles = job->tiles]() mutable {std::vector<const Mesh*> src;for (const Mesh& m : *sources) src.push_back(&m);- bool ok = bakeMaps(*low, src, st, *result, *error, [&](float f) {+ std::vector<BakeResult> results;+ bool ok = bakeMapsUdim(*low, src, st, results, *error, [&](float f) {progress->store(f);return !cancel->load();});- if (ok) ok = saveBakeMaps(*result, folder, name, exr, *files, *error);+ for (size_t i = 0; ok && i < results.size(); ++i) {+ std::vector<std::string> written;+ ok = saveBakeMaps(results[i], folder, name, exr, written, *error);+ files->insert(files->end(), written.begin(), written.end());+ }+ if (ok) {+ *tiles = results.size() > 1 || results.front().udim ? int(results.size()) : 0;+ *result = std::move(results.front());+ }promise.set_value(ok);}).detach();b.job = std::move(job);- status_ = "Baking " + std::to_string(st.size) + " maps from " + std::to_string(idx.size()) + " SubTool" +- (idx.size() == 1 ? "" : "s") + "...";+ status_ = b.levelSource ? "Baking " + std::to_string(st.size) + " maps from the " ++ (b.levelSource == 1 ? "top subdivision level" : "micro level") + "..."+ : "Baking " + std::to_string(st.size) + " maps from " + std::to_string(idx.size()) + " SubTool" ++ (idx.size() == 1 ? "" : "s") + "...";}void App::pollBake() {@@ -326,11 +357,12 @@ void App::pollBake() {int index = -1;for (int i = 0; i < doc_.subtoolCount(); ++i)if (doc_.subtools[size_t(i)].id == job->subtool) index = i;- if (index >= 0 && doc_.subtoolMesh(index).triangleCount() == job->triangles)+ if (job->preview && index >= 0 && doc_.subtoolMesh(index).triangleCount() == job->triangles)b.show(job->subtool, doc_.subtoolMesh(index), job->result, *job->files, job->folder);elseb.files = *job->files, b.writtenFolder = job->folder;- status_ = bakeSummary(*job->result) + ". Saved to " + job->folder;+ status_ = bakeSummary(*job->result) + (*job->tiles ? " (" + std::to_string(*job->tiles) + " UDIM tiles)" : std::string()) ++ ". Saved to " + job->folder;}void App::drawBakeContents() {@@ -364,20 +396,28 @@ void App::drawBakeContents() {ImGui::TextUnformatted("Source");ImGui::SameLine();ImGui::SetNextItemWidth(-1);+ const bool hasLevels = subdivLevelCount(m) >= 2, hasMicroLevel = hasMicro(m);+ if (b.levelSource == 1 && !hasLevels) b.levelSource = 0;+ if (b.levelSource == 2 && !hasMicroLevel) b.levelSource = 0;+ if (b.levelSource == 1) current = "Own top subdivision level";+ if (b.levelSource == 2) current = "Own micro level";if (ImGui::BeginCombo("##bakesource", current.c_str())) {- if (ImGui::Selectable("All visible SubTools", b.source == 0)) b.source = 0;+ if (hasLevels && ImGui::Selectable("Own top subdivision level##level", b.levelSource == 1)) b.levelSource = 1, b.source = 0;+ if (hasMicroLevel && ImGui::Selectable("Own micro level##micro", b.levelSource == 2)) b.levelSource = 2, b.source = 0;+ if (ImGui::Selectable("All visible SubTools", b.source == 0 && !b.levelSource)) b.source = 0, b.levelSource = 0;for (int i = 0; i < doc_.subtoolCount(); ++i) {if (i == doc_.activeSubtool) continue;const SubTool& st = doc_.subtools[size_t(i)];ImGui::PushID(int(st.id));- if (ImGui::Selectable(st.name.c_str(), b.source == st.id)) b.source = st.id;+ if (ImGui::Selectable(st.name.c_str(), b.source == st.id && !b.levelSource)) b.source = st.id, b.levelSource = 0;ImGui::PopID();}ImGui::EndCombo();}ui::HelpText("Source", nullptr,- "The high-poly to bake from: one SubTool, or every visible SubTool except the active one (the low-poly). "- "Hidden faces of the source are ignored.",+ "The high-poly to bake from: one SubTool, or every visible SubTool except the active one (the low-poly), "+ "or this Part's own top subdivision level baked onto its lowest level, or its micro level baked onto its "+ "base. Hidden faces of the source are ignored. UVs outside 0..1 bake as UDIM tiles (name.1001.png, ...).",kPath);// Maps, two columns.@@ -390,6 +430,13 @@ void App::drawBakeContents() {"Ambient occlusion: how much of the sky each point of the high-poly sees. Darker in creases and folds.","Cavity: the high-poly's fine surface curvature. Mid-grey on smooth surfaces, dark in cracks, light on ridges.","Colour transfer: the source's polypaint, or its painted texture.",+ "Curvature: the high-poly's surface bend at the radius below: mid-grey flat, bright on convex edges, dark in "+ "concave ones. Drives edge wear.",+ "Thickness: how far rays travel through the high-poly before leaving it. Dark where it is thin (ears, fins, "+ "edges). Drives subsurface and translucency.",+ "Position: each point's place in the bounding box as colour, 16-bit. Drives gradients and noise that ignore "+ "UV seams.",+ "ID: a flat colour per polygroup of the high-poly, for selecting areas in other programs.",};for (int i = 0; i < kBakeMapCount; ++i) {if (i % 2) {diff --git a/src/app/PanelPbr.cpp b/src/app/PanelPbr.cppindex d2625288..a80baf8d 100644--- a/src/app/PanelPbr.cpp+++ b/src/app/PanelPbr.cpp@@ -14,6 +14,7 @@#include "app/Ui.h"#include "core/MapExport.h"+#include "core/MeshMaps.h"#include "core/Polypaint.h"#include "core/Texture.h"#include "core/TextureChannels.h"@@ -389,6 +390,7 @@ double App::pbrTestValue(const std::string& name) const {if (name == "channel_view") return double(int(doc_.channelView));if (name == "frame_ms") return frameSeconds_ * 1000.0; // (smoothed frame interval; fixed in UI tests)if (name == "draw_ms") return const_cast<App*>(this)->benchmarkDrawMs(20); // the 3D view drawn 20 times, GPU included+ if (name == "mesh_maps") return tex && m.texture->meshMaps ? double(m.texture->meshMaps->kinds) : 0.0;if (name == "view_pbr") return renderSettings_.pbr() ? 1.0 : 0.0;if (name == "environment") return double(renderSettings_.environment);if (name == "environment_pending") return renderer_.environmentPending() ? 1.0 : 0.0;diff --git a/src/core/Bake.cpp b/src/core/Bake.cppindex d83470d2..80d91a5c 100644--- a/src/core/Bake.cpp+++ b/src/core/Bake.cpp@@ -3,6 +3,10 @@#include "core/Bake.h"#include "core/BakeImage.h"+#include "core/MeshMaps.h"+#include "core/Micro.h"+#include "core/Multires.h"+#include "core/RayBvh.h"#include "core/Document.h"#include "core/Tangents.h"#include "core/Texture.h"@@ -33,261 +37,6 @@ std::string utf8(const std::filesystem::path& p) {return std::string(s.begin(), s.end());}-// ----------------------------------------------------------------------------// Ray BVH: binned-SAH tree over the source triangles. Queries are const and keep their state on the stack,-// so any number of threads can cast at once.-// -----------------------------------------------------------------------------struct RayHitInfo {- float t = 0, u = 0, v = 0;- uint32_t tri = 0;-};--class RayBvh {-public:- void build(const std::vector<glm::vec3>& pos, const std::vector<glm::uvec3>& tris) {- const size_t n = tris.size();- nodes_.clear();- order_.resize(n);- std::vector<glm::vec3> centroid(n);- std::vector<Box> box(n);- for (size_t i = 0; i < n; ++i) {- order_[i] = uint32_t(i);- const glm::vec3 &a = pos[tris[i].x], &b = pos[tris[i].y], &c = pos[tris[i].z];- box[i].lo = glm::min(a, glm::min(b, c));- box[i].hi = glm::max(a, glm::max(b, c));- centroid[i] = (box[i].lo + box[i].hi) * 0.5f;- }- nodes_.reserve(n ? 2 * n / kLeaf + 16 : 1);- nodes_.push_back({});- if (n == 0) {- nodes_[0].lo = nodes_[0].hi = glm::vec3(0.0f);- return;- }- struct Job {- uint32_t node, first, count;- };- std::vector<Job> stack = {{0, 0, uint32_t(n)}};- while (!stack.empty()) {- const Job j = stack.back();- stack.pop_back();- Box nb, cb;- for (uint32_t i = j.first; i < j.first + j.count; ++i) {- nb.grow(box[order_[i]]);- cb.grow(centroid[order_[i]]);- }- nodes_[j.node].lo = nb.lo;- nodes_[j.node].hi = nb.hi;- uint32_t mid = 0;- if (j.count > kLeaf && split(j.first, j.count, nb, cb, box, centroid, mid)) {- const uint32_t left = uint32_t(nodes_.size());- nodes_.push_back({});- nodes_.push_back({});- nodes_[j.node].index = left;- nodes_[j.node].count = 0;- stack.push_back({left, j.first, mid - j.first});- stack.push_back({left + 1, mid, j.first + j.count - mid});- } else {- nodes_[j.node].index = j.first;- nodes_[j.node].count = j.count;- }- }- tris_.resize(n);- for (size_t i = 0; i < n; ++i) {- const glm::uvec3& t = tris[order_[i]];- tris_[i] = {pos[t.x], pos[t.y] - pos[t.x], pos[t.z] - pos[t.x]};- }- }-- // The hit with t in [tmin, tmax] nearest to `target`.- bool nearest(const glm::vec3& o, const glm::vec3& d, float tmin, float tmax, float target, RayHitInfo& hit) const {- if (tris_.empty()) return false;- const glm::vec3 inv = invDir(d);- float best = std::numeric_limits<float>::max();- bool found = false;- uint32_t stack[64];- int sp = 0;- float tn, tf;- if (!slab(nodes_[0], o, inv, tmin, tmax, tn, tf)) return false;- stack[sp++] = 0;- while (sp) {- const Node& n = nodes_[stack[--sp]];- if (!slab(n, o, inv, tmin, tmax, tn, tf) || bound(tn, tf, target) >= best) continue;- if (n.count) {- for (uint32_t i = n.index; i < n.index + n.count; ++i) {- float t, u, v;- if (!intersect(tris_[i], o, d, t, u, v) || t < tmin || t > tmax) continue;- const float e = std::abs(t - target);- if (e < best) {- best = e;- hit = {t, u, v, order_[i]};- found = true;- }- }- continue;- }- float an, af, bn, bf;- const bool ha = slab(nodes_[n.index], o, inv, tmin, tmax, an, af);- const bool hb = slab(nodes_[n.index + 1], o, inv, tmin, tmax, bn, bf);- const float la = ha ? bound(an, af, target) : best, lb = hb ? bound(bn, bf, target) : best;- // Push the less promising child first so the better one is visited next.- if (la < best && lb < best) {- if (sp + 2 > 64) continue;- if (la <= lb) {- stack[sp++] = n.index + 1;- stack[sp++] = n.index;- } else {- stack[sp++] = n.index;- stack[sp++] = n.index + 1;- }- } else if (la < best && sp < 64) {- stack[sp++] = n.index;- } else if (lb < best && sp < 64) {- stack[sp++] = n.index + 1;- }- }- return found;- }-- // Any hit with t in [tmin, tmax].- bool occluded(const glm::vec3& o, const glm::vec3& d, float tmin, float tmax) const {- if (tris_.empty()) return false;- const glm::vec3 inv = invDir(d);- uint32_t stack[64];- int sp = 0;- stack[sp++] = 0;- float tn, tf;- while (sp) {- const Node& n = nodes_[stack[--sp]];- if (!slab(n, o, inv, tmin, tmax, tn, tf)) continue;- if (n.count) {- for (uint32_t i = n.index; i < n.index + n.count; ++i) {- float t, u, v;- if (intersect(tris_[i], o, d, t, u, v) && t >= tmin && t <= tmax) return true;- }- continue;- }- if (sp + 2 <= 64) {- stack[sp++] = n.index + 1;- stack[sp++] = n.index;- }- }- return false;- }--private:- static constexpr uint32_t kLeaf = 4;- static constexpr int kBins = 16;- struct Box {- glm::vec3 lo{std::numeric_limits<float>::max()}, hi{std::numeric_limits<float>::lowest()};- void grow(const glm::vec3& p) { lo = glm::min(lo, p), hi = glm::max(hi, p); }- void grow(const Box& b) { lo = glm::min(lo, b.lo), hi = glm::max(hi, b.hi); }- float area() const {- if (lo.x > hi.x) return 0.0f;- const glm::vec3 e = hi - lo;- return e.x * e.y + e.y * e.z + e.z * e.x;- }- };- struct Node {- glm::vec3 lo{0.0f};- uint32_t index = 0; // leaf: first triangle, inner: left child (right = index + 1)- glm::vec3 hi{0.0f};- uint32_t count = 0; // > 0 for leaves- };- struct Tri {- glm::vec3 v0, e1, e2;- };-- bool split(uint32_t first, uint32_t count, const Box& nb, const Box& cb, const std::vector<Box>& box,- const std::vector<glm::vec3>& centroid, uint32_t& mid) {- float bestCost = std::numeric_limits<float>::max();- int bestAxis = -1, bestBin = 0;- const glm::vec3 ext = cb.hi - cb.lo;- for (int axis = 0; axis < 3; ++axis) {- if (ext[axis] <= 0.0f) continue;- Box bins[kBins];- uint32_t cnt[kBins] = {};- const float k = float(kBins) * 0.9999f / ext[axis];- for (uint32_t i = first; i < first + count; ++i) {- const int b = std::min(kBins - 1, int((centroid[order_[i]][axis] - cb.lo[axis]) * k));- bins[b].grow(box[order_[i]]);- ++cnt[b];- }- float rightArea[kBins];- uint32_t rightCount[kBins];- Box acc;- uint32_t c = 0;- for (int b = kBins - 1; b > 0; --b) {- acc.grow(bins[b]);- c += cnt[b];- rightArea[b] = acc.area();- rightCount[b] = c;- }- acc = Box();- c = 0;- for (int b = 0; b < kBins - 1; ++b) {- acc.grow(bins[b]);- c += cnt[b];- if (!c || !rightCount[b + 1]) continue;- const float cost = acc.area() * float(c) + rightArea[b + 1] * float(rightCount[b + 1]);- if (cost < bestCost) {- bestCost = cost;- bestAxis = axis;- bestBin = b;- }- }- }- if (bestAxis < 0) { // all centroids in one spot: split in the middle of the list- if (count <= 16) return false;- mid = first + count / 2;- return true;- }- // A leaf costs about one intersection per triangle; stop when splitting doesn't pay.- if (count <= 8 && bestCost >= nb.area() * float(count)) return false;- const float k = float(kBins) * 0.9999f / ext[bestAxis];- auto* b = order_.data() + first;- auto* e = b + count;- auto* m = std::partition(b, e, [&](uint32_t t) {- return std::min(kBins - 1, int((centroid[t][bestAxis] - cb.lo[bestAxis]) * k)) <= bestBin;- });- mid = uint32_t(m - order_.data());- if (mid == first || mid == first + count) mid = first + count / 2;- return true;- }-- static glm::vec3 invDir(const glm::vec3& d) {- auto inv = [](float x) { return std::abs(x) > 1e-20f ? 1.0f / x : (x < 0 ? -1e20f : 1e20f); };- return {inv(d.x), inv(d.y), inv(d.z)};- }- static bool slab(const Node& n, const glm::vec3& o, const glm::vec3& inv, float tmin, float tmax, float& tn, float& tf) {- const glm::vec3 t0 = (n.lo - o) * inv, t1 = (n.hi - o) * inv;- const glm::vec3 a = glm::min(t0, t1), b = glm::max(t0, t1);- tn = std::max(std::max(a.x, a.y), std::max(a.z, tmin));- tf = std::min(std::min(b.x, b.y), std::min(b.z, tmax));- return tn <= tf;- }- static float bound(float tn, float tf, float target) { return target < tn ? tn - target : target > tf ? target - tf : 0.0f; }- // Two-sided Moller-Trumbore.- static bool intersect(const Tri& tr, const glm::vec3& o, const glm::vec3& d, float& t, float& u, float& v) {- const glm::vec3 p = glm::cross(d, tr.e2);- const float det = glm::dot(tr.e1, p);- if (std::abs(det) < 1e-20f) return false;- const float inv = 1.0f / det;- const glm::vec3 s = o - tr.v0;- u = glm::dot(s, p) * inv;- if (u < 0.0f || u > 1.0f) return false;- const glm::vec3 q = glm::cross(s, tr.e1);- v = glm::dot(d, q) * inv;- if (v < 0.0f || u + v > 1.0f) return false;- t = glm::dot(tr.e2, q) * inv;- return true;- }-- std::vector<Node> nodes_;- std::vector<uint32_t> order_;- std::vector<Tri> tris_;-};-// ---------------------------------------------------------------------------// The high-poly side: every source mesh's visible triangles in one list.// ---------------------------------------------------------------------------@@ -298,6 +47,7 @@ struct Source {std::vector<uint32_t> triMesh, triLocal; // which source mesh / which of its trianglesstd::vector<uint32_t> vertexOffset; // first vertex of each source meshstd::vector<float> curvature; // per vertex, normalised to about -1..1 (cavity map)+ std::vector<float> meanCurvature; // per vertex, 1 / length (curvature map; meshMeanCurvature)std::vector<const Mesh*> meshes;};@@ -466,6 +216,10 @@ const char* bakeMapId(BakeMap m) {case BakeMap::AmbientOcclusion: return "ao";case BakeMap::Cavity: return "cavity";case BakeMap::Color: return "color";+ case BakeMap::Curvature: return "curvature";+ case BakeMap::Thickness: return "thickness";+ case BakeMap::Position: return "position";+ case BakeMap::Id: return "id";}return "";}@@ -473,11 +227,15 @@ const char* bakeMapId(BakeMap m) {const char* bakeMapLabel(BakeMap m) {switch (m) {case BakeMap::Normal: return "Normal (tangent)";- case BakeMap::ObjectNormal: return "Normal (object)";+ case BakeMap::ObjectNormal: return "Normal (object / world)";case BakeMap::Displacement: return "Displacement";case BakeMap::AmbientOcclusion: return "Ambient Occlusion";case BakeMap::Cavity: return "Cavity";case BakeMap::Color: return "Colour";+ case BakeMap::Curvature: return "Curvature";+ case BakeMap::Thickness: return "Thickness";+ case BakeMap::Position: return "Position";+ case BakeMap::Id: return "ID";}return "";}@@ -500,7 +258,10 @@ bool parseBakeMaps(const std::string& list, uint32_t& maps, std::string& error)if (s == "object" || s == "objectnormal" || s == "object_space" || s == "world_normal") s = "object_normal";if (s == "disp" || s == "height") s = "displacement";if (s == "occlusion" || s == "ambient_occlusion") s = "ao";- if (s == "curvature") s = "cavity";+ if (s == "convexity") s = "curvature";+ if (s == "thick" || s == "translucency") s = "thickness";+ if (s == "pos") s = "position";+ if (s == "material_id" || s == "polygroups" || s == "polygroup") s = "id";if (s == "colour" || s == "polypaint" || s == "albedo" || s == "texture") s = "color";bool found = false;for (int i = 0; i < kBakeMapCount; ++i)@@ -509,7 +270,8 @@ bool parseBakeMaps(const std::string& list, uint32_t& maps, std::string& error)found = true;}if (!found) {- error = "Unknown map '" + item + "' (use normal, object_normal, displacement, ao, cavity, color or all)";+ error = "Unknown map '" + item + "' (use normal, object_normal, displacement, ao, cavity, color, curvature, "+ "thickness, position, id or all)";return false;}}@@ -587,6 +349,13 @@ bool bakeMaps(const Mesh& low, const std::vector<const Mesh*>& sources, const BaRayBvh bvh;bvh.build(src.pos, src.tris);if (st.maps & bakeBit(BakeMap::Cavity)) computeCurvature(src);+ if (st.maps & bakeBit(BakeMap::Curvature)) {+ src.meanCurvature.assign(src.pos.size(), 0.0f);+ for (size_t m = 0; m < src.meshes.size(); ++m) {+ const std::vector<float> h = meshMeanCurvature(*src.meshes[m]);+ std::copy(h.begin(), h.end(), src.meanCurvature.begin() + std::ptrdiff_t(src.vertexOffset[m]));+ }+ }out.bvhSeconds = secondsSince(bvhStart);out.sourceTriangles = src.tris.size();@@ -596,6 +365,10 @@ bool bakeMaps(const Mesh& low, const std::vector<const Mesh*>& sources, const Baconst bool wantAo = st.maps & bakeBit(BakeMap::AmbientOcclusion);const bool wantCavity = st.maps & bakeBit(BakeMap::Cavity);const bool wantColor = st.maps & bakeBit(BakeMap::Color);+ const bool wantCurv = st.maps & bakeBit(BakeMap::Curvature);+ const bool wantThick = st.maps & bakeBit(BakeMap::Thickness);+ const bool wantPos = st.maps & bakeBit(BakeMap::Position);+ const bool wantId = st.maps & bakeBit(BakeMap::Id);AABB lb = low.bounds();AABB all = lb;@@ -650,6 +423,15 @@ bool bakeMaps(const Mesh& low, const std::vector<const Mesh*>& sources, const Bareturn false;}const float aoDist = std::max(st.aoDistance, 1e-4f) * diag;+ const float thickDist = std::max(st.thicknessDistance, 1e-4f) * diag;+ const float curvRadius = std::max(st.curvatureRadius, 1e-5f) * diag;+ out.positionMin = all.min;+ out.positionMax = all.max;+ const glm::vec3 posScale = 1.0f / glm::max(all.max - all.min, glm::vec3(1e-12f));+ // ID colours: by polygroup (when any source has them and IdSource::Polygroups) or by source mesh.+ bool anyGroups = false;+ for (const Mesh* m : src.meshes) anyGroups = anyGroups || m->hasPolygroups();+ const bool idByGroup = st.idSource == BakeSettings::IdSource::Polygroups && anyGroups;// --- Output planes ---const int W = st.size, H = st.size, S = st.samples;@@ -664,6 +446,10 @@ bool bakeMaps(const Mesh& low, const std::vector<const Mesh*>& sources, const Baif (wantAo) out.ao.assign(texels, 255);if (wantCavity) out.cavity.assign(texels, 128);if (wantDisp) out.displacement.assign(texels, 0.0f);+ if (wantCurv) out.curvature.assign(texels, 128);+ if (wantThick) out.thickness.assign(texels, 255);+ if (wantPos) out.position.assign(texels * 3, 0);+ if (wantId) out.id.assign(texels * 3, 0);out.coverage.assign(texels, 0);// Float copies of the normals for padding (averaged and renormalised there), only while baking.std::vector<glm::vec3> nTs, nOs, col;@@ -703,11 +489,12 @@ bool bakeMaps(const Mesh& low, const std::vector<const Mesh*>& sources, const Bastd::mutex rangeMutex;float dMin = std::numeric_limits<float>::max(), dMax = std::numeric_limits<float>::lowest();const int aoPerSample = std::max(1, (st.aoRays + S * S - 1) / (S * S));+ const int thickPerSample = std::max(1, (st.thicknessRays + S * S - 1) / (S * S));runWorkers(threads, [&](int worker) {struct Acc {- glm::vec3 ts{0}, os{0}, color{0}, lowN{0};- float disp = 0, ao = 0, cav = 0;+ glm::vec3 ts{0}, os{0}, color{0}, lowN{0}, pos{0}, id{0};+ float disp = 0, ao = 0, cav = 0, curv = 0, thick = 0;uint16_t hits = 0, samples = 0;};std::vector<Acc> acc(size_t(kTile) * kTile);@@ -817,6 +604,40 @@ bool bakeMaps(const Mesh& low, const std::vector<const Mesh*>& sources, const Ba}a.ao += 1.0f - float(hits) / float(aoPerSample);}+ if (wantCurv) { // mean curvature at the hit, scaled by the radius: > 0 convex+ const float hc = src.meanCurvature[ht.x] * w0 + src.meanCurvature[ht.y] * h.u ++ src.meanCurvature[ht.z] * h.v;+ a.curv += std::clamp(hc * curvRadius, -1.0f, 1.0f);+ }+ if (wantThick) {+ // Cosine-weighted rays into the surface: the mean distance to the far side.+ glm::vec3 in = -nh;+ if (glm::dot(in, n) > 0.0f) in = -in; // (nh faces outwards here)+ glm::vec3 bt, bb;+ basis(in, bt, bb);+ const uint32_t seed = hash32(uint32_t(sx) * 2654435761u ^ uint32_t(sy) * 40503u);+ const float r1 = float(seed & 0xFFFF) / 65536.0f, r2 = float(seed >> 16) / 65536.0f;+ const glm::vec3 o = hp + in * (eps * 4.0f);+ float sum = 0.0f;+ for (int r = 0; r < thickPerSample; ++r) {+ float u1 = (float(r) + 0.5f) / float(thickPerSample) + r1, u2 = radicalInverse(uint32_t(r)) + r2;+ u1 -= std::floor(u1);+ u2 -= std::floor(u2);+ const float rad = std::sqrt(u1), phi = 6.2831853f * u2;+ const glm::vec3 dir = bt * (rad * std::cos(phi)) + bb * (rad * std::sin(phi)) ++ in * std::sqrt(std::max(0.0f, 1.0f - u1));+ RayHitInfo th;+ sum += bvh.nearest(o, dir, eps, thickDist, 0.0f, th) ? th.t : thickDist;+ }+ a.thick += sum / (float(thickPerSample) * thickDist);+ }+ if (wantPos) a.pos += (hp - all.min) * posScale;+ if (wantId) {+ const Mesh& m = *src.meshes[src.triMesh[h.tri]];+ const uint32_t key = idByGroup ? m.polygroupAt(src.triLocal[h.tri]) * 2654435761u + src.triMesh[h.tri]+ : src.triMesh[h.tri] * 2246822519u + 7u;+ a.id += idMapColor(key);+ }}}}@@ -854,6 +675,13 @@ bool bakeMaps(const Mesh& low, const std::vector<const Mesh*>& sources, const Baconst glm::vec3 c = linearToSrgb(glm::clamp(a.color * inv, 0.0f, 1.0f));for (int k = 0; k < 3; ++k) out.color[i * 3 + size_t(k)] = unorm8(c[k]);}+ if (wantCurv) out.curvature[i] = unorm8(0.5f + 0.5f * a.curv * inv);+ if (wantThick) out.thickness[i] = unorm8(a.thick * inv);+ if (wantPos)+ for (int k = 0; k < 3; ++k)+ out.position[i * 3 + size_t(k)] = uint16_t(std::lround(std::clamp(a.pos[k] * inv, 0.0f, 1.0f) * 65535.0f));+ if (wantId)+ for (int k = 0; k < 3; ++k) out.id[i * 3 + size_t(k)] = unorm8(a.id[k] * inv);}const size_t d = done.fetch_add(1) + 1;if (worker == 0 && progress && !progress(0.95f * float(d) / float(work.size()))) cancel = true;@@ -921,8 +749,8 @@ bool bakeMaps(const Mesh& low, const std::vector<const Mesh*>& sources, const Bafor (size_t q = f; q < std::min(front.size(), f + 256); ++q) {const size_t i = front[q];const int x = int(i % size_t(W)), y = int(i / size_t(W));- glm::vec3 ts(0), os(0), cl(0);- float dp = 0, ao = 0, cv = 0;+ glm::vec3 ts(0), os(0), cl(0), ps(0), idc(0);+ float dp = 0, ao = 0, cv = 0, cu = 0, th = 0;int n = 0;for (int dy = -1; dy <= 1; ++dy)for (int dx = -1; dx <= 1; ++dx) {@@ -939,6 +767,10 @@ bool bakeMaps(const Mesh& low, const std::vector<const Mesh*>& sources, const Baif (wantDisp) dp += out.displacement[j];if (wantAo) ao += out.ao[j];if (wantCavity) cv += out.cavity[j];+ if (wantCurv) cu += out.curvature[j];+ if (wantThick) th += out.thickness[j];+ if (wantPos) ps += glm::vec3(out.position[j * 3], out.position[j * 3 + 1], out.position[j * 3 + 2]);+ if (wantId) idc += glm::vec3(out.id[j * 3], out.id[j * 3 + 1], out.id[j * 3 + 2]);}if (!n) continue;const float inv = 1.0f / float(n);@@ -955,6 +787,12 @@ bool bakeMaps(const Mesh& low, const std::vector<const Mesh*>& sources, const Baif (wantDisp) out.displacement[i] = dp * inv;if (wantAo) out.ao[i] = uint8_t(std::lround(ao * inv));if (wantCavity) out.cavity[i] = uint8_t(std::lround(cv * inv));+ if (wantCurv) out.curvature[i] = uint8_t(std::lround(cu * inv));+ if (wantThick) out.thickness[i] = uint8_t(std::lround(th * inv));+ for (int c = 0; c < 3; ++c) {+ if (wantPos) out.position[i * 3 + size_t(c)] = uint16_t(std::lround(ps[c] * inv));+ if (wantId) out.id[i * 3 + size_t(c)] = uint8_t(std::lround(idc[c] * inv));+ }}}});@@ -975,6 +813,91 @@ bool bakeMaps(const Mesh& low, const std::vector<const Mesh*>& sources, const Bareturn true;}+// ---------------------------------------------------------------------------+// UDIM tiles and level sources+// ---------------------------------------------------------------------------++std::vector<int> udimTiles(const Mesh& low) {+ std::vector<int> tiles;+ if (low.uvs.size() != low.triangleCount() * 3) return tiles;+ bool outside = false;+ std::vector<uint8_t> seen(100, 0); // u 0..9, v 0..9+ for (size_t t = 0; t < low.triangleCount(); ++t) {+ const glm::vec2 c = (low.uvs[t * 3] + low.uvs[t * 3 + 1] + low.uvs[t * 3 + 2]) / 3.0f;+ if (!std::isfinite(c.x) || !std::isfinite(c.y)) continue;+ const int u = int(std::floor(c.x)), v = int(std::floor(c.y));+ if (u != 0 || v != 0) outside = true;+ if (u < 0 || u > 9 || v < 0 || v > 9) continue; // (UDIM covers 10 columns; others are skipped)+ seen[size_t(v * 10 + u)] = 1;+ }+ if (!outside) return tiles;+ for (int i = 0; i < 100; ++i)+ if (seen[size_t(i)]) tiles.push_back(1001 + i);+ return tiles;+}++bool bakeMapsUdim(const Mesh& low, const std::vector<const Mesh*>& sources, const BakeSettings& settings,+ std::vector<BakeResult>& results, std::string& error, const BakeProgress& progress) {+ results.clear();+ const std::vector<int> tiles = udimTiles(low);+ if (tiles.empty()) {+ results.emplace_back();+ return bakeMaps(low, sources, settings, results.back(), error, progress);+ }+ // Per tile, a copy of the low-poly whose UVs in that tile move to 0..1 and whose other triangles move far+ // outside (their samples are skipped).+ Mesh shifted = low;+ shifted.texture.reset();+ for (size_t k = 0; k < tiles.size(); ++k) {+ const int u = (tiles[k] - 1001) % 10, v = (tiles[k] - 1001) / 10;+ for (size_t t = 0; t < low.triangleCount(); ++t) {+ const glm::vec2 c = (low.uvs[t * 3] + low.uvs[t * 3 + 1] + low.uvs[t * 3 + 2]) / 3.0f;+ const bool in = int(std::floor(c.x)) == u && int(std::floor(c.y)) == v;+ for (size_t i = 0; i < 3; ++i)+ shifted.uvs[t * 3 + i] = in ? low.uvs[t * 3 + i] - glm::vec2(float(u), float(v)) : glm::vec2(-8.0f);+ }+ BakeResult r;+ const float lo = float(k) / float(tiles.size()), span = 1.0f / float(tiles.size());+ const BakeProgress tileProgress = [&](float f) { return !progress || progress(lo + f * span); };+ if (!bakeMaps(shifted, sources, settings, r, error, tileProgress)) return false;+ r.udim = tiles[k];+ results.push_back(std::move(r));+ }+ return true;+}++bool bakeLevelSources(const Mesh& part, const std::string& source, Mesh& low, Mesh& high, std::string& error) {+ if (source == "subdivision" || source == "levels" || source == "subdiv") {+ const int levels = subdivLevelCount(part);+ if (levels < 2) {+ error = "The Part has no subdivision levels (Tool > Geometry > Divide)";+ return false;+ }+ low = subdivLevelMesh(part, 0);+ high = subdivLevelMesh(part, levels - 1);+ } else if (source == "micro") {+ if (!hasMicro(part)) {+ error = "The Part has no micro level (Tool > Geometry > Micro)";+ return false;+ }+ low = part;+ low.micro.reset();+ if (!microBakeMesh(part, microLevel(part), high, error)) return false;+ } else {+ error = "Unknown level source '" + source + "' (use subdivision or micro)";+ return false;+ }+ low.texture.reset();+ high.texture = part.texture; // (colour comes from the Part's own texture)+ if (low.uvs.size() != low.triangleCount() * 3) {+ error = "The Part's lowest level has no UVs: run Auto UV on it first (Tool > Texture Map)";+ return false;+ }+ if (low.normals.size() != low.vertexCount()) low.recomputeAllNormals();+ if (high.normals.size() != high.vertexCount()) high.recomputeAllNormals();+ return true;+}+// ---------------------------------------------------------------------------// Images and files// ---------------------------------------------------------------------------@@ -999,8 +922,9 @@ Image bakeMapImage(const BakeResult& r, BakeMap map) {img.height = r.height;img.rgba.assign(size_t(r.width) * size_t(r.height) * 4, 255);const std::vector<uint8_t>* rgb = map == BakeMap::Normal ? &r.normal : map == BakeMap::ObjectNormal ? &r.objectNormal- : map == BakeMap::Color ? &r.color : nullptr;- const std::vector<uint8_t>* grey = map == BakeMap::AmbientOcclusion ? &r.ao : map == BakeMap::Cavity ? &r.cavity : nullptr;+ : map == BakeMap::Color ? &r.color : map == BakeMap::Id ? &r.id : nullptr;+ const std::vector<uint8_t>* grey = map == BakeMap::AmbientOcclusion ? &r.ao : map == BakeMap::Cavity ? &r.cavity+ : map == BakeMap::Curvature ? &r.curvature : map == BakeMap::Thickness ? &r.thickness : nullptr;const float k = r.displacementScale > 0.0f ? 0.5f / r.displacementScale : 0.0f;for (int y = 0; y < r.height; ++y)for (int x = 0; x < r.width; ++x) {@@ -1010,6 +934,8 @@ Image bakeMapImage(const BakeResult& r, BakeMap map) {p[0] = (*rgb)[i * 3], p[1] = (*rgb)[i * 3 + 1], p[2] = (*rgb)[i * 3 + 2];} else if (grey) {p[0] = p[1] = p[2] = (*grey)[i];+ } else if (map == BakeMap::Position) {+ for (int c = 0; c < 3; ++c) p[c] = uint8_t(r.position[i * 3 + size_t(c)] >> 8);} else {p[0] = p[1] = p[2] = unorm8(0.5f + r.displacement[i] * k);}@@ -1017,9 +943,9 @@ Image bakeMapImage(const BakeResult& r, BakeMap map) {return img;}-std::string bakeFileName(const std::string& base, BakeMap map, const char* ext) {+std::string bakeFileName(const std::string& base, BakeMap map, const char* ext, int udim) {const char* suffix = map == BakeMap::ObjectNormal ? "normal_object" : bakeMapId(map);- return base + "_" + suffix + ext;+ return base + "_" + suffix + (udim > 0 ? "." + std::to_string(udim) : std::string()) + ext;}bool saveBakeMaps(const BakeResult& r, const std::string& folder, const std::string& base, bool exr,@@ -1031,7 +957,16 @@ bool saveBakeMaps(const BakeResult& r, const std::string& folder, const std::strfor (int i = 0; i < kBakeMapCount; ++i) {const BakeMap m = BakeMap(i);if (!r.has(m)) continue;- const std::string path = utf8(dir / fsPath(bakeFileName(base, m)));+ const std::string path = utf8(dir / fsPath(bakeFileName(base, m, ".png", r.udim)));+ if (m == BakeMap::Position) { // 16-bit RGB, top-down+ std::vector<uint16_t> px(r.position.size());+ for (int y = 0; y < r.height; ++y)+ std::memcpy(&px[size_t(r.height - 1 - y) * size_t(r.width) * 3], &r.position[size_t(y) * size_t(r.width) * 3],+ size_t(r.width) * 3 * sizeof(uint16_t));+ if (!savePng16(path, r.width, r.height, 3, px, error)) return false;+ written.push_back(path);+ continue;+ }if (m == BakeMap::Displacement) {if (!savePng16(path, r.width, r.height, 1, displacement16(r), error)) return false;written.push_back(path);@@ -1040,7 +975,7 @@ bool saveBakeMaps(const BakeResult& r, const std::string& folder, const std::strfor (int y = 0; y < r.height; ++y)std::memcpy(&f[size_t(r.height - 1 - y) * size_t(r.width)], &r.displacement[size_t(y) * size_t(r.width)],size_t(r.width) * sizeof(float));- const std::string exrPath = utf8(dir / fsPath(bakeFileName(base, m, ".exr")));+ const std::string exrPath = utf8(dir / fsPath(bakeFileName(base, m, ".exr", r.udim)));if (!saveExr(exrPath, r.width, r.height, 1, f, error)) return false;written.push_back(exrPath);}@@ -1059,8 +994,9 @@ std::string bakeSummary(const BakeResult& r) {std::string names;for (int i = 0; i < kBakeMapCount; ++i)if (r.has(BakeMap(i))) names += std::string(names.empty() ? "" : ", ") + bakeMapId(BakeMap(i));- s << "Baked " << names << " at " << r.width << "x" << r.height << " from " << r.sourceTriangles << " triangles in "- << r.seconds << " s";+ s << "Baked " << names << " at " << r.width << "x" << r.height;+ if (r.udim > 0) s << " (UDIM " << r.udim << ")";+ s << " from " << r.sourceTriangles << " triangles in " << r.seconds << " s";s.precision(4);s << "; rays " << r.front << " in front, " << r.rear << " behind";if (r.has(BakeMap::Displacement))@@ -1124,12 +1060,17 @@ void notifyBakeListener(const Document& doc, std::shared_ptr<const BakeResult> rvoid registerBakeCommands(CommandRegistry& reg) {using T = ParamSpec::Type;reg.add({"bake",- "Bake maps from a high-poly source onto the active SubTool's UVs (the low-poly): tangent-space normal "- "(MikkTSpace), object-space normal, displacement (16-bit PNG + 32-bit EXR), ambient occlusion, cavity and "- "colour. Rays go along the low-poly's smooth normals from 'front' in front of it to 'rear' behind it. "- "Writes <name>_<map>.png into the output folder.",- {{"source", T::String, "SubTool to bake from, or all (default: every visible SubTool but the active one).", false},- {"maps", T::String, "Comma list: normal, object_normal, displacement, ao, cavity, color, or all. Default normal.", false},+ "Bake maps from a high-poly source onto the active Part's UVs (the low-poly): tangent-space normal "+ "(MikkTSpace), object-space (world) normal, displacement (16-bit PNG + 32-bit EXR), ambient occlusion, cavity, "+ "colour, curvature, thickness, position (16-bit) and ID (polygroups or Parts). Rays go along the low-poly's "+ "smooth normals from 'front' in front of it to 'rear' behind it. The source can be other Parts, or the "+ "active Part's own top subdivision level (baked onto its lowest level) or micro level (onto its base). "+ "UVs outside 0..1 bake as UDIM tiles. Writes <name>_<map>.png (<name>_<map>.1001.png per UDIM tile) into "+ "the output folder.",+ {{"source", T::String, "A Part to bake from, all (default: every visible Part but the active one), subdivision "+ "(the active Part's top level onto its lowest) or micro (its micro level onto its base).", false},+ {"maps", T::String, "Comma list: normal, object_normal (world_normal), displacement, ao, cavity, color, curvature, "+ "thickness, position, id, or all. Default normal.", false},{"size", T::Number, "Map size in texels: 512, 1024, 2048 (default), 4096 or 8192 (1k...8k also work).", false},{"out", T::String, "Output folder (default: the project's folder, or the current folder).", false},{"name", T::String, "File name prefix (default: the active SubTool's name).", false},@@ -1141,7 +1082,12 @@ void registerBakeCommands(CommandRegistry& reg) {{"ao_distance", T::Number, "How far occluders count, as a fraction of the size. Default 0.05.", false},{"green", T::String, "Normal map convention: opengl (default; Blender, Unity, Godot) or directx (Unreal).", false},{"displacement_scale", T::Number, "World units at white in the displacement PNG (default: the largest distance).", false},- {"exr", T::Bool, "Also write the displacement as a 32-bit float EXR in world units. Default true.", false}},+ {"exr", T::Bool, "Also write the displacement as a 32-bit float EXR in world units. Default true.", false},+ {"thickness_rays", T::Number, "Thickness rays per texel. Default 24.", false},+ {"thickness_distance", T::Number, "Rays longer than this (a fraction of the size) count as thick. Default 0.1.", false},+ {"curvature_radius", T::Number, "A bend of this radius (a fraction of the size) is fully bright or dark. Default 0.02.", false},+ {"id", T::String, "What the ID map colours: polygroups (default) or parts.", false},+ {"udim", T::Bool, "Bake UVs outside 0..1 as UDIM tiles (default true; false bakes the 0..1 square only).", false}},[](Document& doc, const Args& a) -> CommandResult {BakeSettings st;std::string err;@@ -1184,25 +1130,53 @@ void registerBakeCommands(CommandRegistry& reg) {const std::string green = argString(a, "green", "opengl");if (green != "opengl" && green != "directx") return {false, "green must be opengl or directx"};st.flipGreen = green == "directx";+ st.thicknessRays = int(argNumber(a, "thickness_rays", st.thicknessRays));+ st.thicknessDistance = float(argNumber(a, "thickness_distance", st.thicknessDistance));+ st.curvatureRadius = float(argNumber(a, "curvature_radius", st.curvatureRadius));+ const std::string id = argString(a, "id", "polygroups");+ if (id != "polygroups" && id != "parts") return {false, "id must be polygroups or parts"};+ st.idSource = id == "parts" ? BakeSettings::IdSource::Parts : BakeSettings::IdSource::Polygroups;- std::vector<int> idx;- if (!bakeSourceSubtools(doc, argString(a, "source", "all"), idx, err)) return {false, err};+ // The meshes: other Parts onto the active one, or the active Part's own levels.+ const std::string sourceArg = argString(a, "source", "all");+ Mesh levelLow, levelHigh;+ const Mesh* low = &doc.mesh;std::vector<const Mesh*> sources;- for (int i : idx) sources.push_back(&doc.subtoolMesh(i));- auto result = std::make_shared<BakeResult>();- if (!bakeMaps(doc.mesh, sources, st, *result, err)) return {false, err};+ if (sourceArg == "subdivision" || sourceArg == "micro") {+ if (!bakeLevelSources(doc.mesh, sourceArg, levelLow, levelHigh, err)) return {false, err};+ low = &levelLow;+ sources.push_back(&levelHigh);+ } else {+ std::vector<int> idx;+ if (!bakeSourceSubtools(doc, sourceArg, idx, err)) return {false, err};+ for (int i : idx) sources.push_back(&doc.subtoolMesh(i));+ }+ std::vector<BakeResult> results;+ if (argBool(a, "udim", true)) {+ if (!bakeMapsUdim(*low, sources, st, results, err)) return {false, err};+ } else {+ results.emplace_back();+ if (!bakeMaps(*low, sources, st, results.back(), err)) return {false, err};+ }+ auto result = std::make_shared<BakeResult>(results.front());std::string name = argString(a, "name", doc.activeSubtoolInfo().name);for (char& c : name)if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' || c == '"' || c == '<' || c == '>' || c == '|')c = '_';if (name.empty()) name = "bake";const std::string folder = argString(a, "out", defaultBakeFolder(doc));- std::vector<std::string> written;- if (!saveBakeMaps(*result, folder, name, argBool(a, "exr", true), written, err)) return {false, err};- notifyBakeListener(doc, result, written);+ std::vector<std::string> written, all;+ std::string summary;+ for (const BakeResult& r : results) {+ if (!saveBakeMaps(r, folder, name, argBool(a, "exr", true), written, err)) return {false, err};+ all.insert(all.end(), written.begin(), written.end());+ summary += (summary.empty() ? "" : "\n") + bakeSummary(r);+ }+ // (the preview shows the bake on the active Part, which is the low-poly only for Part sources)+ if (low == &doc.mesh && results.size() == 1) notifyBakeListener(doc, result, all);std::string files;- for (const std::string& w : written) files += "\n " + w;- return {true, bakeSummary(*result) + "\nWrote:" + files};+ for (const std::string& w : all) files += "\n " + w;+ return {true, summary + "\nWrote:" + files};}});}diff --git a/src/core/Bake.h b/src/core/Bake.hindex 1bb60ece..279c9ce2 100644--- a/src/core/Bake.h+++ b/src/core/Bake.h@@ -3,8 +3,15 @@//// Map baking: the detail of a high-poly sculpt (one or more SubTools) captured as images on the UVs of a// low-poly SubTool, for game engines and renderers. Maps: tangent-space normal (MikkTSpace, core/Tangents.h,-// so Blender, Unreal, Unity and Godot show it right), object-space normal, displacement, ambient occlusion,-// cavity and colour (polypaint or the source's painted texture).+// so Blender, Unreal, Unity and Godot show it right), object-space (= world) normal, displacement, ambient+// occlusion, cavity, colour (polypaint or the source's painted texture), and the Mesh Maps texturing reads:+// curvature (convex edges bright, concave dark, from the surface's mean curvature at a set radius), thickness+// (how far rays travel inside the surface), position (in the bounding box, 16-bit) and ID (a flat colour per+// polygroup or per Part).+//+// Sources: other Parts (the classic high-to-low bake), or the active Part's own top subdivision level baked onto+// its lowest level, or its micro level onto its base (bakeLevelSources). UVs outside 0..1 bake as UDIM tiles,+// one set of images per tile (<name>_<map>.1001.png, 1002, ... 1011 for the second row).//// How it works, as xNormal and Substance do it: every texel sample on the low-poly surface casts a ray along// its smooth (interpolated) normal through a "cage" from `front` in front of the surface to `rear` behind it,@@ -31,10 +38,11 @@namespace sf {-enum class BakeMap : int { Normal, ObjectNormal, Displacement, AmbientOcclusion, Cavity, Color };-constexpr int kBakeMapCount = 6;+enum class BakeMap : int { Normal, ObjectNormal, Displacement, AmbientOcclusion, Cavity, Color, Curvature, Thickness, Position, Id };+constexpr int kBakeMapCount = 10;constexpr uint32_t bakeBit(BakeMap m) { return 1u << int(m); }-const char* bakeMapId(BakeMap m); // "normal", "object_normal", "displacement", "ao", "cavity", "color"+const char* bakeMapId(BakeMap m); // "normal", "object_normal", "displacement", "ao", "cavity", "color",+ // "curvature", "thickness", "position", "id"const char* bakeMapLabel(BakeMap m); // "Normal (tangent)", ...// A comma-separated list of ids ("normal,ao", or "all"); false + error naming the bad entry.bool parseBakeMaps(const std::string& list, uint32_t& maps, std::string& error);@@ -51,6 +59,11 @@ struct BakeSettings {bool flipGreen = false; // DirectX-style normal map (green = down), as Unreal expects nativelyfloat displacementScale = 0.0f; // world units that map to white in the PNG; 0 = the largest distance foundint threads = 0; // 0 = every core+ int thicknessRays = 24; // per texel+ float thicknessDistance = 0.1f; // rays longer than this count as thick, x bounding-box diagonal+ float curvatureRadius = 0.02f; // a bend of this radius (x diagonal) is fully bright / dark+ enum class IdSource : uint8_t { Polygroups, Parts };+ IdSource idSource = IdSource::Polygroups;};struct BakeResult {@@ -58,7 +71,8 @@ struct BakeResult {uint32_t maps = 0;bool flipGreen = false;// Present for the maps baked. RGB8 / grey8, rows bottom-up.- std::vector<uint8_t> normal, objectNormal, color, ao, cavity;+ std::vector<uint8_t> normal, objectNormal, color, ao, cavity, curvature, thickness, id;+ std::vector<uint16_t> position; // RGB16: the point in [positionMin, positionMax]std::vector<float> displacement; // world units along the low-poly normal, + = the high-poly is outsidestd::vector<uint8_t> coverage; // 1 = inside a UV island, 2 = padding, 0 = emptystd::vector<glm::vec4> tangents; // MikkTSpace tangent + sign per low-poly corner (for previews)@@ -66,6 +80,8 @@ struct BakeResult {float diagonal = 0; // the low-poly's bounding-box diagonalfloat displacementMin = 0, displacementMax = 0; // range found (world units)float displacementScale = 0; // world units at white / black of the 16-bit PNG (mid-grey = 0)+ glm::vec3 positionMin{0.0f}, positionMax{0.0f}; // the box the position map spans+ int udim = 0; // the UDIM tile this result is (bakeMapsUdim), 0 = plain 0..1 UVssize_t islandTexels = 0, missedTexels = 0; // texels inside islands, and those whose rays found nothingsize_t sourceTriangles = 0;double seconds = 0, bvhSeconds = 0;@@ -81,14 +97,28 @@ using BakeProgress = std::function<bool(float)>;bool bakeMaps(const Mesh& low, const std::vector<const Mesh*>& sources, const BakeSettings& settings, BakeResult& result,std::string& error, const BakeProgress& progress = {});+// The UDIM tiles (1001 + u + 10 v) the low-poly's triangles lie in (by their UV centres), in order; empty when+// every triangle is inside 0..1 (a plain bake).+std::vector<int> udimTiles(const Mesh& low);+// bakeMaps once per UDIM tile of `low` (or once, as a plain bake, without UDIMs): each result has its `udim`.+// Progress covers all tiles.+bool bakeMapsUdim(const Mesh& low, const std::vector<const Mesh*>& sources, const BakeSettings& settings,+ std::vector<BakeResult>& results, std::string& error, const BakeProgress& progress = {});++// The meshes of a bake from the Part's own levels: `low` its lowest subdivision level and `high` its top one+// (source = "subdivision"), or `low` the Part itself and `high` its micro level baked to triangles+// (source = "micro"). False + error when the Part has no such level or its low mesh has no UVs.+bool bakeLevelSources(const Mesh& part, const std::string& source, Mesh& low, Mesh& high, std::string& error);+// A baked map as a top-down 8-bit image (displacement mid-grey = 0, +/- displacementScale at white / black).Image bakeMapImage(const BakeResult& result, BakeMap map);// The displacement as 16-bit grey (top-down; 32768 = 0) and as floats in world units (top-down).std::vector<uint16_t> displacement16(const BakeResult& result);// File name of a map: "<base>_normal.png", "<base>_normal_object.png", "<base>_displacement.png" (+ .exr),-// "<base>_ao.png", "<base>_cavity.png", "<base>_color.png".-std::string bakeFileName(const std::string& base, BakeMap map, const char* extension = ".png");+// "<base>_ao.png", "<base>_cavity.png", "<base>_color.png", "<base>_curvature.png", "<base>_thickness.png",+// "<base>_position.png" (16-bit), "<base>_id.png"; with a UDIM tile "<base>_normal.1001.png".+std::string bakeFileName(const std::string& base, BakeMap map, const char* extension = ".png", int udim = 0);// Writes every baked map into `folder` (created if needed); `written` gets the paths. Displacement goes out as// a 16-bit PNG and, with `exr`, as a 32-bit float EXR in world units.bool saveBakeMaps(const BakeResult& result, const std::string& folder, const std::string& base, bool exr,diff --git a/src/core/MeshMaps.cpp b/src/core/MeshMaps.cppnew file mode 100644index 00000000..75a69fb1--- /dev/null+++ b/src/core/MeshMaps.cpp@@ -0,0 +1,651 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/MeshMaps.h"++#include "core/Commands.h"+#include "core/Document.h"+#include "core/RayBvh.h"+#include "core/Texture.h"++#include <algorithm>+#include <chrono>+#include <cmath>+#include <cstring>+#include <mutex>+#include <sstream>+#include <thread>++namespace sf {++namespace {++using Clock = std::chrono::steady_clock;++inline uint32_t hash32(uint32_t x) {+ x ^= x >> 16;+ x *= 0x7feb352dU;+ x ^= x >> 15;+ x *= 0x846ca68bU;+ x ^= x >> 16;+ return x;+}+inline float radicalInverse(uint32_t b) {+ b = (b << 16u) | (b >> 16u);+ b = ((b & 0x55555555u) << 1u) | ((b & 0xAAAAAAAAu) >> 1u);+ b = ((b & 0x33333333u) << 2u) | ((b & 0xCCCCCCCCu) >> 2u);+ b = ((b & 0x0F0F0F0Fu) << 4u) | ((b & 0xF0F0F0F0u) >> 4u);+ b = ((b & 0x00FF00FFu) << 8u) | ((b & 0xFF00FF00u) >> 8u);+ return float(b) * 2.3283064365386963e-10f;+}+inline void basis(const glm::vec3& n, glm::vec3& t, glm::vec3& b) {+ const float sign = std::copysign(1.0f, n.z);+ const float a = -1.0f / (sign + n.z);+ const float bb = n.x * n.y * a;+ t = glm::vec3(1.0f + sign * n.x * n.x * a, sign * bb, -sign * n.x);+ b = glm::vec3(bb, sign + n.y * n.y * a, -n.y);+}+inline glm::vec3 cosineDir(const glm::vec3& n, const glm::vec3& t, const glm::vec3& b, float u1, float u2) {+ const float r = std::sqrt(u1), phi = 6.2831853f * u2;+ return t * (r * std::cos(phi)) + b * (r * std::sin(phi)) + n * std::sqrt(std::max(0.0f, 1.0f - u1));+}++template <class Fn>+void runWorkers(Fn fn) {+ const int threads = int(std::clamp(std::thread::hardware_concurrency(), 1u, 32u));+ std::vector<std::thread> pool;+ for (int i = 1; i < threads; ++i) pool.emplace_back([&fn, i] { fn(i); });+ fn(0);+ for (auto& t : pool) t.join();+}++struct Format {+ int components, bits;+ std::array<float, 4> fill;+};+Format formatOf(MeshMapKind k) {+ switch (k) {+ case MeshMapKind::AmbientOcclusion: return {1, 8, {1, 0, 0, 0}};+ case MeshMapKind::Curvature: return {1, 8, {0.5f, 0, 0, 0}};+ case MeshMapKind::Thickness: return {1, 8, {1, 0, 0, 0}};+ case MeshMapKind::Position: return {3, 16, {0, 0, 0, 0}};+ case MeshMapKind::WorldNormal: return {3, 8, {0.5f, 1.0f, 0.5f, 0}};+ case MeshMapKind::Id: return {3, 8, {0, 0, 0, 0}};+ }+ return {1, 8, {0, 0, 0, 0}};+}++// What baking needs of a mesh (the whole Part, or the compact copy of an update) and its rays.+struct Baker {+ const Mesh& mesh;+ RayBvh bvh;+ std::vector<float> curvature;+ uint32_t kinds = 0;+ MeshMapSettings st;+ float aoDist = 0, thickDist = 0, curvRadius = 0, eps = 0;+ glm::vec3 boxMin{0.0f}, boxScale{1.0f};++ Baker(const Mesh& m, uint32_t k, const MeshMapSettings& s, float diagonal, const glm::vec3& bmin, const glm::vec3& bmax)+ : mesh(m), kinds(k), st(s) {+ const bool rays = kinds & (meshMapBit(MeshMapKind::AmbientOcclusion) | meshMapBit(MeshMapKind::Thickness));+ if (rays) bvh.build(m.positions, m.triangles);+ if (kinds & meshMapBit(MeshMapKind::Curvature)) curvature = meshMeanCurvature(m);+ aoDist = std::max(s.aoDistance, 1e-4f) * diagonal;+ thickDist = std::max(s.thicknessDistance, 1e-4f) * diagonal;+ curvRadius = std::max(s.curvatureRadius, 1e-5f) * diagonal;+ eps = diagonal * 2e-6f;+ boxMin = bmin;+ boxScale = 1.0f / glm::max(bmax - bmin, glm::vec3(1e-12f));+ }++ // Texels of tile `ti` (origin x0, y0) whose texel map names a triangle, into the writable tiles `out`.+ size_t bakeTile(const TexelTile& tt, int x0, int y0, int width, int height, const std::array<uint8_t*, kMeshMapCount>& out) const {+ size_t n = 0;+ for (int ly = 0; ly < kTextureTile; ++ly) {+ const int y = y0 + ly;+ if (y >= height) break;+ for (int lx = 0; lx < kTextureTile; ++lx) {+ const int x = x0 + lx;+ if (x >= width) break;+ const size_t li = size_t(ly) * kTextureTile + size_t(lx);+ const uint32_t t = tt.tri[li];+ if (t == kNoTexelTriangle) continue;+ ++n;+ const glm::vec2 b12 = tt.bary[li];+ const float b0 = 1.0f - b12.x - b12.y;+ const glm::uvec3& tv = mesh.triangles[t];+ const glm::vec3 p = mesh.positions[tv.x] * b0 + mesh.positions[tv.y] * b12.x + mesh.positions[tv.z] * b12.y;+ const glm::vec3 face = glm::cross(mesh.positions[tv.y] - mesh.positions[tv.x], mesh.positions[tv.z] - mesh.positions[tv.x]);+ glm::vec3 nrm = mesh.normals.size() == mesh.vertexCount()+ ? mesh.normals[tv.x] * b0 + mesh.normals[tv.y] * b12.x + mesh.normals[tv.z] * b12.y+ : face;+ const float len = glm::length(nrm);+ nrm = len > 1e-12f ? nrm / len : (glm::length(face) > 0 ? glm::normalize(face) : glm::vec3(0, 1, 0));+ const uint32_t seed = hash32(uint32_t(x) * 73856093u ^ uint32_t(y) * 19349663u);+ const float r1 = float(seed & 0xFFFF) / 65536.0f, r2 = float(seed >> 16) / 65536.0f;+ auto put8 = [&](MeshMapKind k, int c, float v) {+ out[size_t(k)][li * size_t(formatOf(k).components) + size_t(c)] = uint8_t(std::lround(std::clamp(v, 0.0f, 1.0f) * 255.0f));+ };+ if (out[size_t(MeshMapKind::AmbientOcclusion)]) {+ glm::vec3 bt, bb;+ basis(nrm, bt, bb);+ const glm::vec3 o = p + nrm * (eps * 4.0f);+ const int rays = std::max(1, st.aoRays);+ int hits = 0;+ for (int r = 0; r < rays; ++r) {+ float u1 = (float(r) + 0.5f) / float(rays) + r1, u2 = radicalInverse(uint32_t(r)) + r2;+ u1 -= std::floor(u1);+ u2 -= std::floor(u2);+ if (bvh.occluded(o, cosineDir(nrm, bt, bb, u1, u2), eps, aoDist)) ++hits;+ }+ put8(MeshMapKind::AmbientOcclusion, 0, 1.0f - float(hits) / float(rays));+ }+ if (out[size_t(MeshMapKind::Thickness)]) {+ const glm::vec3 in = -nrm;+ glm::vec3 bt, bb;+ basis(in, bt, bb);+ const glm::vec3 o = p + in * (eps * 4.0f);+ const int rays = std::max(1, st.thicknessRays);+ float sum = 0.0f;+ for (int r = 0; r < rays; ++r) {+ float u1 = (float(r) + 0.5f) / float(rays) + r2, u2 = radicalInverse(uint32_t(r)) + r1;+ u1 -= std::floor(u1);+ u2 -= std::floor(u2);+ RayHitInfo h;+ sum += bvh.nearest(o, cosineDir(in, bt, bb, u1, u2), eps, thickDist, 0.0f, h) ? h.t : thickDist;+ }+ put8(MeshMapKind::Thickness, 0, sum / (float(rays) * thickDist));+ }+ if (out[size_t(MeshMapKind::Curvature)]) {+ const float h = curvature[tv.x] * b0 + curvature[tv.y] * b12.x + curvature[tv.z] * b12.y;+ put8(MeshMapKind::Curvature, 0, 0.5f + 0.5f * std::clamp(h * curvRadius, -1.0f, 1.0f));+ }+ if (uint8_t* o = out[size_t(MeshMapKind::Position)]) {+ const glm::vec3 q = glm::clamp((p - boxMin) * boxScale, 0.0f, 1.0f);+ uint16_t v[3];+ for (int c = 0; c < 3; ++c) v[c] = uint16_t(std::lround(q[c] * 65535.0f));+ std::memcpy(o + li * 6, v, 6);+ }+ if (out[size_t(MeshMapKind::WorldNormal)])+ for (int c = 0; c < 3; ++c) put8(MeshMapKind::WorldNormal, c, nrm[c] * 0.5f + 0.5f);+ if (out[size_t(MeshMapKind::Id)]) {+ const glm::vec3 col = idMapColor(mesh.polygroupAt(t) * 2654435761u + 1u);+ for (int c = 0; c < 3; ++c) put8(MeshMapKind::Id, c, col[c]);+ }+ }+ }+ return n;+ }+};++void resetImage(TileImage& img, MeshMapKind k, int w, int h) {+ const Format f = formatOf(k);+ img.reset(w, h, f.components, f.bits, TileImage::toUnits(f.bits, f.fill[0], f.fill[1], f.fill[2], f.fill[3]));+}++} // namespace++// ---------------------------------------------------------------------------+// Names+// ---------------------------------------------------------------------------++const char* meshMapId(MeshMapKind k) {+ switch (k) {+ case MeshMapKind::AmbientOcclusion: return "ao";+ case MeshMapKind::Curvature: return "curvature";+ case MeshMapKind::Thickness: return "thickness";+ case MeshMapKind::Position: return "position";+ case MeshMapKind::WorldNormal: return "world_normal";+ case MeshMapKind::Id: return "id";+ }+ return "";+}++const char* meshMapLabel(MeshMapKind k) {+ switch (k) {+ case MeshMapKind::AmbientOcclusion: return "Ambient Occlusion";+ case MeshMapKind::Curvature: return "Curvature";+ case MeshMapKind::Thickness: return "Thickness";+ case MeshMapKind::Position: return "Position";+ case MeshMapKind::WorldNormal: return "World Normal";+ case MeshMapKind::Id: return "ID";+ }+ return "";+}++bool parseMeshMap(const std::string& text, MeshMapKind& out) {+ std::string s;+ for (char c : text)+ if (!std::isspace(static_cast<unsigned char>(c))) s += char(std::tolower(static_cast<unsigned char>(c)));+ if (s == "occlusion" || s == "ambient_occlusion") s = "ao";+ if (s == "normal" || s == "worldnormal" || s == "object_normal") s = "world_normal";+ if (s == "polygroups" || s == "polygroup") s = "id";+ for (int i = 0; i < kMeshMapCount; ++i)+ if (s == meshMapId(MeshMapKind(i))) {+ out = MeshMapKind(i);+ return true;+ }+ return false;+}++bool parseMeshMaps(const std::string& list, uint32_t& kinds, std::string& error) {+ kinds = 0;+ std::stringstream ss(list);+ std::string item;+ while (std::getline(ss, item, ',')) {+ if (item.find_first_not_of(" \t") == std::string::npos) continue;+ if (item == "all") {+ kinds = kAllMeshMaps;+ continue;+ }+ MeshMapKind k;+ if (!parseMeshMap(item, k)) {+ error = "Unknown mesh map '" + item + "' (use ao, curvature, thickness, position, world_normal, id or all)";+ return false;+ }+ kinds |= meshMapBit(k);+ }+ if (!kinds) {+ error = "Choose at least one mesh map";+ return false;+ }+ return true;+}++// ---------------------------------------------------------------------------+// Values+// ---------------------------------------------------------------------------++bool MeshMapSet::matches(const Mesh& m, int w, int h) const {+ return w == width && h == height && kinds && vertexCount == m.vertexCount() && triangleCount == m.triangleCount() &&+ uvKey == meshUvFingerprint(m);+}++size_t MeshMapSet::bytes() const {+ size_t n = sizeof(MeshMapSet);+ for (const TileImage& img : images) n += img.bytes();+ if (positions) n += positions->size() * sizeof(glm::vec3);+ return n;+}++float MeshMapSet::value(MeshMapKind k, int x, int y) const {+ const TileImage& img = images[size_t(k)];+ if (!img.valid()) return formatOf(k).fill[0];+ return img.value(std::clamp(x, 0, width - 1), std::clamp(y, 0, height - 1), 0);+}++glm::vec3 MeshMapSet::vector(MeshMapKind k, int x, int y) const {+ const TileImage& img = images[size_t(k)];+ float v[4] = {formatOf(k).fill[0], formatOf(k).fill[1], formatOf(k).fill[2], 0};+ if (img.valid()) img.values(std::clamp(x, 0, width - 1), std::clamp(y, 0, height - 1), v);+ glm::vec3 r(v[0], v[1], v[2]);+ if (k == MeshMapKind::WorldNormal) {+ r = r * 2.0f - 1.0f;+ const float l = glm::length(r);+ r = l > 1e-6f ? r / l : glm::vec3(0, 1, 0);+ }+ return r;+}++std::vector<float> meshMeanCurvature(const Mesh& m) {+ const size_t nv = m.vertexCount();+ std::vector<glm::vec3> sum(nv, glm::vec3(0.0f));+ std::vector<float> sq(nv, 0.0f), count(nv, 0.0f);+ for (const glm::uvec3& t : m.triangles)+ for (int e = 0; e < 3; ++e) { // each directed edge of the triangle, both ways+ const uint32_t a = t[e], b = t[(e + 1) % 3];+ const glm::vec3 d = m.positions[b] - m.positions[a];+ const float l2 = glm::dot(d, d);+ sum[a] += d, sq[a] += l2, count[a] += 1.0f;+ sum[b] -= d, sq[b] += l2, count[b] += 1.0f;+ }+ std::vector<float> h(nv, 0.0f);+ const bool normals = m.normals.size() == nv;+ for (size_t v = 0; v < nv; ++v) {+ if (count[v] <= 0.0f || sq[v] <= 0.0f || !normals) continue;+ // centroid - p = sum / count; mean squared edge = sq / count; H = -2 (centroid - p) . n / mean squared edge.+ h[v] = -2.0f * glm::dot(sum[v], m.normals[v]) / sq[v];+ }+ // One smoothing pass over the ring (as triangles see it).+ std::vector<float> acc(nv, 0.0f), w(nv, 0.0f);+ for (const glm::uvec3& t : m.triangles) {+ const float avg = (h[t.x] + h[t.y] + h[t.z]) / 3.0f;+ for (int c = 0; c < 3; ++c) acc[t[c]] += avg, w[t[c]] += 1.0f;+ }+ for (size_t v = 0; v < nv; ++v)+ if (w[v] > 0.0f) h[v] = 0.5f * h[v] + 0.5f * acc[v] / w[v];+ return h;+}++glm::vec3 idMapColor(uint32_t key) {+ const uint32_t h = hash32(key ^ 0x9E3779B9u);+ const float hue = float(h & 0xFFFF) / 65536.0f;+ const float sat = 0.55f + 0.35f * float((h >> 16) & 0xFF) / 255.0f;+ const float val = 0.75f + 0.25f * float((h >> 24) & 0xFF) / 255.0f;+ const glm::vec3 rgb = glm::clamp(glm::abs(glm::fract(hue + glm::vec3(0.0f, 2.0f / 3.0f, 1.0f / 3.0f)) * 6.0f - 3.0f) - 1.0f, 0.0f, 1.0f);+ return val * glm::mix(glm::vec3(1.0f), rgb, sat);+}++// ---------------------------------------------------------------------------+// Full bake+// ---------------------------------------------------------------------------++bool bakeMeshMaps(const Mesh& mesh, int width, int height, uint32_t kinds, const MeshMapSettings& settings, MeshMapSet& out,+ std::string& error, const BakeProgress& progress) {+ const auto start = Clock::now();+ if (mesh.triangleCount() == 0 || mesh.uvs.size() != mesh.triangleCount() * 3) {+ error = "The Part has no UVs: run Auto UV (Tool > Texture Map) first";+ return false;+ }+ if (width < 64 || height < 64 || width > 16384 || height > 16384) {+ error = "Mesh Maps need a texture of 64 to 16384 texels";+ return false;+ }+ kinds &= kAllMeshMaps;+ if (!kinds) {+ error = "Choose at least one mesh map";+ return false;+ }+ MeshMapSet set;+ set.width = width;+ set.height = height;+ set.kinds = kinds;+ set.settings = settings;+ const AABB box = mesh.bounds();+ set.boundsMin = box.min;+ set.boundsMax = box.max;+ set.diagonal = std::max(glm::length(box.extent()), 1e-6f);+ set.uvKey = meshUvFingerprint(mesh);+ set.vertexCount = mesh.vertexCount();+ set.triangleCount = mesh.triangleCount();+ set.positions = std::make_shared<const std::vector<glm::vec3>>(mesh.positions);+ for (int k = 0; k < kMeshMapCount; ++k)+ if (kinds & (1u << k)) resetImage(set.images[size_t(k)], MeshMapKind(k), width, height);+ const Baker baker(mesh, kinds, settings, set.diagonal, set.boundsMin, set.boundsMax);+ const int tilesX = (width + kTextureTile - 1) / kTextureTile, tilesY = (height + kTextureTile - 1) / kTextureTile;+ const uint32_t tiles = uint32_t(tilesX * tilesY);+ std::atomic<uint32_t> next{0}, done{0};+ std::atomic<size_t> texels{0};+ std::atomic<bool> cancel{false};+ std::mutex writable;+ runWorkers([&](int worker) {+ TexelTile tt;+ for (;;) {+ if (cancel.load(std::memory_order_relaxed)) return;+ const uint32_t ti = next.fetch_add(1);+ if (ti >= tiles) break;+ if (!texelTile(mesh, width, height, ti, tt)) continue;+ if (std::all_of(tt.tri.begin(), tt.tri.end(), [](uint32_t t) { return t == kNoTexelTriangle; })) {+ done.fetch_add(1);+ continue;+ }+ std::array<uint8_t*, kMeshMapCount> outs{};+ {+ std::lock_guard lock(writable);+ for (int k = 0; k < kMeshMapCount; ++k)+ if (kinds & (1u << k)) outs[size_t(k)] = set.images[size_t(k)].writableTile(ti);+ }+ texels += baker.bakeTile(tt, int(ti % uint32_t(tilesX)) * kTextureTile, int(ti / uint32_t(tilesX)) * kTextureTile,+ width, height, outs);+ const uint32_t d = done.fetch_add(1) + 1;+ if (worker == 0 && progress && !progress(float(d) / float(tiles))) cancel = true;+ }+ });+ if (cancel || (progress && !progress(1.0f))) {+ error = "Cancelled";+ return false;+ }+ for (TileImage& img : set.images)+ if (img.valid()) img.compact();+ set.texelsBaked = texels;+ set.seconds = std::chrono::duration<double>(Clock::now() - start).count();+ set.revision = out.revision + 1;+ out = std::move(set);+ return true;+}++// ---------------------------------------------------------------------------+// Live updates+// ---------------------------------------------------------------------------++AABB changedRegion(const MeshMapSet& set, const Mesh& mesh, std::vector<uint32_t>* moved) {+ AABB box;+ if (!set.positions || set.positions->size() != mesh.vertexCount()) return box;+ const std::vector<glm::vec3>& old = *set.positions;+ const size_t n = old.size();+ const int threads = int(std::clamp<size_t>(n / 200000 + 1, 1, 16));+ std::vector<AABB> boxes(static_cast<size_t>(threads));+ std::vector<std::vector<uint32_t>> lists(static_cast<size_t>(threads));+ std::vector<std::thread> pool;+ auto work = [&](int t) {+ const size_t b = n * size_t(t) / size_t(threads), e = n * size_t(t + 1) / size_t(threads);+ for (size_t i = b; i < e; ++i)+ if (old[i] != mesh.positions[i]) {+ boxes[size_t(t)].expand(old[i]);+ boxes[size_t(t)].expand(mesh.positions[i]);+ if (moved) lists[size_t(t)].push_back(uint32_t(i));+ }+ };+ for (int t = 1; t < threads; ++t) pool.emplace_back(work, t);+ work(0);+ for (auto& th : pool) th.join();+ for (int t = 0; t < threads; ++t) {+ if (boxes[size_t(t)].valid()) box.expand(boxes[size_t(t)]);+ if (moved) moved->insert(moved->end(), lists[size_t(t)].begin(), lists[size_t(t)].end());+ }+ return box;+}++bool prepareMeshMapUpdate(const Mesh& mesh, const std::shared_ptr<const MeshMapSet>& set, const AABB& region,+ std::vector<uint32_t> moved, MeshMapUpdate& up) {+ up = MeshMapUpdate();+ if (!set || !region.valid() || !set->matches(mesh, set->width, set->height)) return false;+ const MeshMapSettings& st = set->settings;+ float reach = 0.0f;+ if (set->has(MeshMapKind::AmbientOcclusion)) reach = std::max(reach, st.aoDistance * set->diagonal);+ if (set->has(MeshMapKind::Thickness)) reach = std::max(reach, st.thicknessDistance * set->diagonal);+ const glm::vec3 r1(reach * 1.01f + set->diagonal * 1e-5f), r2(2.0f * reach * 1.01f + set->diagonal * 1e-5f);+ const AABB zone{region.min - r1, region.max + r1}, occ{region.min - r2, region.max + r2};+ const size_t nt = mesh.triangleCount();+ auto overlaps = [&](const AABB& a, uint32_t t) {+ const glm::uvec3& tv = mesh.triangles[t];+ const glm::vec3 lo = glm::min(mesh.positions[tv.x], glm::min(mesh.positions[tv.y], mesh.positions[tv.z]));+ const glm::vec3 hi = glm::max(mesh.positions[tv.x], glm::max(mesh.positions[tv.y], mesh.positions[tv.z]));+ return glm::all(glm::lessThanEqual(lo, a.max)) && glm::all(glm::greaterThanEqual(hi, a.min));+ };+ // 0: untouched, 1: occluder / curvature ring only, 2: baked again.+ std::vector<uint8_t> role(nt, 0);+ std::vector<uint8_t> ringVertex(mesh.vertexCount(), 0);+ for (uint32_t t = 0; t < nt; ++t) {+ if (overlaps(zone, t)) {+ role[t] = 2;+ for (int c = 0; c < 3; ++c) ringVertex[mesh.triangles[t][c]] = 1;+ } else if (overlaps(occ, t)) {+ role[t] = 1;+ }+ }+ // The curvature of a baked triangle's corners needs their ring, and its smoothing their neighbours' rings: two+ // rings of triangles around the baked ones.+ for (int pass = 0; pass < 2; ++pass) {+ std::vector<uint8_t> next = ringVertex;+ for (uint32_t t = 0; t < nt; ++t) {+ const glm::uvec3& tv = mesh.triangles[t];+ if (!(ringVertex[tv.x] || ringVertex[tv.y] || ringVertex[tv.z])) continue;+ if (!role[t]) role[t] = 1;+ next[tv.x] = next[tv.y] = next[tv.z] = 1;+ }+ ringVertex.swap(next);+ }+ // The compact copy: every triangle with a role, its vertices renumbered.+ std::vector<uint32_t> localTri(nt, kNoTexelTriangle), vmap(mesh.vertexCount(), kNoTexelTriangle);+ Mesh& L = up.local;+ const bool normals = mesh.normals.size() == mesh.vertexCount();+ for (uint32_t t = 0; t < nt; ++t) {+ if (!role[t]) continue;+ glm::uvec3 lt;+ for (int c = 0; c < 3; ++c) {+ uint32_t& v = vmap[mesh.triangles[t][c]];+ if (v == kNoTexelTriangle) {+ v = uint32_t(L.positions.size());+ L.positions.push_back(mesh.positions[mesh.triangles[t][c]]);+ L.normals.push_back(normals ? mesh.normals[mesh.triangles[t][c]] : glm::vec3(0, 1, 0));+ }+ lt[c] = v;+ }+ localTri[t] = uint32_t(L.triangles.size());+ L.triangles.push_back(lt);+ for (int c = 0; c < 3; ++c) L.uvs.push_back(mesh.uvs[size_t(t) * 3 + size_t(c)]);+ if (mesh.hasPolygroups()) L.polygroups.push_back(mesh.polygroups[t]);+ }+ // The tiles the baked triangles reach, and their texel maps in local triangles (others keep their values).+ const int tilesX = (set->width + kTextureTile - 1) / kTextureTile;+ std::vector<uint8_t> tileOn(size_t(tilesX) * size_t((set->height + kTextureTile - 1) / kTextureTile), 0);+ for (uint32_t t = 0; t < nt; ++t) {+ int tx0, ty0, tx1, ty1;+ if (role[t] != 2 || !triangleTiles(mesh, set->width, set->height, t, tx0, ty0, tx1, ty1)) continue;+ for (int ty = ty0; ty <= ty1; ++ty)+ for (int tx = tx0; tx <= tx1; ++tx) tileOn[size_t(ty) * size_t(tilesX) + size_t(tx)] = 1;+ }+ for (uint32_t ti = 0; ti < tileOn.size(); ++ti) {+ if (!tileOn[ti]) continue;+ TexelTile tt;+ if (!texelTile(mesh, set->width, set->height, ti, tt)) continue;+ bool any = false;+ for (uint32_t& t : tt.tri) {+ if (t == kNoTexelTriangle) continue;+ t = role[t] == 2 ? localTri[t] : kNoTexelTriangle;+ any = any || t != kNoTexelTriangle;+ }+ if (!any) continue;+ up.tiles.push_back(ti);+ up.texels.push_back(std::move(tt));+ }+ if (up.tiles.empty()) return false;+ up.movedVertices = std::move(moved);+ up.movedPositions.reserve(up.movedVertices.size());+ for (uint32_t v : up.movedVertices) up.movedPositions.push_back(mesh.positions[v]);+ up.base = set;+ return true;+}++void runMeshMapUpdate(MeshMapUpdate& up, const std::atomic<bool>* cancel) {+ const auto start = Clock::now();+ up.ok = false;+ if (!up.base || up.tiles.empty()) return;+ const MeshMapSet& set = *up.base;+ const Baker baker(up.local, set.kinds, set.settings, set.diagonal, set.boundsMin, set.boundsMax);+ // Copies of the maps share every tile; the ones baked again are made writable (copied) here.+ std::array<TileImage, kMeshMapCount> images = set.images;+ std::array<std::vector<uint8_t*>, kMeshMapCount> outs;+ for (int k = 0; k < kMeshMapCount; ++k) {+ if (!set.has(MeshMapKind(k))) continue;+ outs[size_t(k)].resize(up.tiles.size());+ for (size_t i = 0; i < up.tiles.size(); ++i) outs[size_t(k)][i] = images[size_t(k)].writableTile(up.tiles[i]);+ }+ const int tilesX = (set.width + kTextureTile - 1) / kTextureTile;+ std::atomic<size_t> next{0}, texels{0};+ runWorkers([&](int) {+ for (;;) {+ if (cancel && cancel->load(std::memory_order_relaxed)) return;+ const size_t i = next.fetch_add(1);+ if (i >= up.tiles.size()) break;+ std::array<uint8_t*, kMeshMapCount> o{};+ for (int k = 0; k < kMeshMapCount; ++k)+ if (!outs[size_t(k)].empty()) o[size_t(k)] = outs[size_t(k)][i];+ const uint32_t ti = up.tiles[i];+ texels += baker.bakeTile(up.texels[i], int(ti % uint32_t(tilesX)) * kTextureTile,+ int(ti / uint32_t(tilesX)) * kTextureTile, set.width, set.height, o);+ }+ });+ if (cancel && cancel->load()) return;+ for (int k = 0; k < kMeshMapCount; ++k) {+ up.result[size_t(k)].clear();+ if (!set.has(MeshMapKind(k))) continue;+ for (uint32_t ti : up.tiles) up.result[size_t(k)].push_back(images[size_t(k)].tilePtr(ti));+ }+ up.texelsBaked = texels;+ up.seconds = std::chrono::duration<double>(Clock::now() - start).count();+ up.ok = true;+}++std::shared_ptr<MeshMapSet> applyMeshMapUpdate(const MeshMapUpdate& up) {+ if (!up.ok || !up.base) return nullptr;+ auto set = std::make_shared<MeshMapSet>(*up.base);+ for (int k = 0; k < kMeshMapCount; ++k) {+ if (up.result[size_t(k)].size() != up.tiles.size()) continue;+ for (size_t i = 0; i < up.tiles.size(); ++i) set->images[size_t(k)].setTilePtr(up.tiles[i], up.result[size_t(k)][i]);+ }+ if (set->positions && !up.movedVertices.empty()) {+ auto pos = std::make_shared<std::vector<glm::vec3>>(*set->positions);+ for (size_t i = 0; i < up.movedVertices.size(); ++i)+ if (up.movedVertices[i] < pos->size()) (*pos)[up.movedVertices[i]] = up.movedPositions[i];+ set->positions = std::move(pos);+ }+ set->revision = up.base->revision + 1;+ set->texelsBaked = up.texelsBaked;+ set->seconds = up.seconds;+ return set;+}++// ---------------------------------------------------------------------------+// Command+// ---------------------------------------------------------------------------++std::string describeMeshMaps(const MeshMapSet& s) {+ std::string names;+ for (int k = 0; k < kMeshMapCount; ++k)+ if (s.has(MeshMapKind(k))) names += std::string(names.empty() ? "" : ", ") + meshMapId(MeshMapKind(k));+ char buf[256];+ std::snprintf(buf, sizeof buf, "Mesh Maps %s at %dx%d (%.1f MB, last bake %.2f s, %zu texels)%s", names.c_str(), s.width,+ s.height, double(s.bytes()) / 1048576.0, s.seconds, s.texelsBaked, s.live ? ", live" : "");+ return buf;+}++void notifyMeshMapsChanged(Document&, Mesh&, const std::vector<uint32_t>*) {}++void registerMeshMapCommands(CommandRegistry& reg) {+ using T = ParamSpec::Type;+ reg.add({"mesh_maps",+ "Mesh Maps of the active Part, on its texture's UVs at the texture's size, for Fill layers: ambient "+ "occlusion, curvature, thickness, position, world normal and ID (polygroups). bake makes them, info "+ "describes them, clear drops them, live=true re-bakes the changed tiles after sculpting (in the app). "+ "Derived data: not saved, not an undo step.",+ {{"action", T::String, "bake (default), info or clear.", false},+ {"maps", T::String, "Comma list: ao, curvature, thickness, position, world_normal, id, or all (default).", false},+ {"ao_rays", T::Number, "Ambient occlusion rays per texel (default 24).", false},+ {"ao_distance", T::Number, "How far occluders count, a fraction of the Part's size (default 0.05).", false},+ {"thickness_rays", T::Number, "Thickness rays per texel (default 12).", false},+ {"thickness_distance", T::Number, "Rays longer than this count as thick (default 0.1).", false},+ {"curvature_radius", T::Number, "A bend of this radius is fully bright / dark (default 0.02).", false},+ {"live", T::Bool, "Re-bake changed tiles after sculpting (default true).", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ Mesh& m = doc.mesh;+ if (!hasTexture(m)) return {false, "The Part has no texture: Tool > Texture Map > New Texture"};+ const std::string action = argString(a, "action", "bake");+ PaintTexture& tex = *m.texture;+ if (action == "info") return {true, tex.meshMaps ? describeMeshMaps(*tex.meshMaps) : std::string("No Mesh Maps")};+ if (action == "clear") {+ mutableTexture(m).meshMaps.reset();+ return {true, "Mesh Maps cleared"};+ }+ if (action != "bake") return {false, "action must be bake, info or clear"};+ uint32_t kinds = kAllMeshMaps;+ std::string err;+ if (a.contains("maps") && !parseMeshMaps(argString(a, "maps"), kinds, err)) return {false, err};+ MeshMapSettings st;+ st.aoRays = std::clamp(int(argNumber(a, "ao_rays", 24)), 1, 512);+ st.aoDistance = std::clamp(float(argNumber(a, "ao_distance", st.aoDistance)), 0.001f, 1.0f);+ st.thicknessRays = std::clamp(int(argNumber(a, "thickness_rays", 12)), 1, 512);+ st.thicknessDistance = std::clamp(float(argNumber(a, "thickness_distance", st.thicknessDistance)), 0.001f, 1.0f);+ st.curvatureRadius = std::clamp(float(argNumber(a, "curvature_radius", st.curvatureRadius)), 0.0001f, 1.0f);+ auto set = std::make_shared<MeshMapSet>();+ if (tex.meshMaps) set->revision = tex.meshMaps->revision;+ if (!bakeMeshMaps(m, tex.width, tex.height, kinds, st, *set, err)) return {false, err};+ set->live = argBool(a, "live", true);+ const std::string text = describeMeshMaps(*set);+ mutableTexture(m).meshMaps = std::move(set);+ notifyMeshMapsChanged(doc, m);+ return {true, text};+ }});+}++} // namespace sfdiff --git a/src/core/MeshMaps.h b/src/core/MeshMaps.hindex 82b8ad51..05019ec9 100644--- a/src/core/MeshMaps.h+++ b/src/core/MeshMaps.h@@ -1,16 +1,135 @@// SculptForge - open source digital sculpting// SPDX-License-Identifier: GPL-3.0-or-later//-// Mesh Maps (PBR texturing phase 2A; scaffolding only). Will bake the texture-space maps the layer stack reads:-// curvature, position, thickness, ID, world normal and bent normal, from the mesh itself, from the SubTool's own-// top subdivision level, from a name-matched high-poly SubTool (_high / _low) or through a cage. Maps will be-// fingerprinted (mesh, UVs, settings) so stale ones are detected after sculpting. Today's bakes: core/Bake.h.+// Mesh Maps: texture-space maps of a Part's own surface, baked on its UVs at the texture's size and kept with its+// texture (PaintTexture::meshMaps), for Fill layers to read (core/LayerStack.h): ambient occlusion, curvature,+// thickness, position, world normal and ID (polygroups). Files for other programs come from the bake command+// (core/Bake.h), which also bakes from other Parts, subdivision levels and micro levels, and to UDIM tiles.+//+// Maps are TileImages (64 x 64 tiles, the texture's tiles) and are baked tile by tile on every core:+// - each texel's surface point and smooth normal come from its triangle (gutter texels from the nearest island+// point, as painting pads islands), so maps line up with the paint texel for texel;+// - AO: cosine-weighted rays from the point; occluders within settings.aoDistance (x the size) count;+// - thickness: cosine-weighted rays into the surface, the mean distance to the far side over thicknessDistance;+// - curvature: the mean curvature of the surface (meshMeanCurvature) times curvatureRadius: 0.5 is flat, brighter+// is convex (edges, ridges), darker concave (creases);+// - position: the point in the Part's bounding box (16-bit RGB); world normal: the smooth normal (RGB);+// - ID: a flat colour per polygroup.+//+// Live updates (the app, App::updateMeshMaps): the set remembers the positions it was baked from. When the Part is+// sculpted, the changed region is found by comparing them (changedRegion), and only the tiles whose texels lie+// within reach of it are baked again (MeshMapUpdate), on a worker thread from a compact copy of the triangles near+// it; Fill layers then re-evaluate those tiles (core/LayerStack.h). Unchanged texels keep their values, so the+// result equals a full bake of the sculpted mesh (tested).#pragma once+#include "core/Bake.h"+#include "core/Mesh.h"+#include "core/Texture.h"+#include "core/TileImage.h"++#include <glm/glm.hpp>++#include <array>+#include <atomic>#include <cstdint>+#include <memory>+#include <string>+#include <vector>namespace sf {-enum class MeshMapKind : uint8_t { Curvature, Position, Thickness, Id, WorldNormal, BentNormal };+class CommandRegistry;+struct Document;+struct PaintTexture;++enum class MeshMapKind : uint8_t { AmbientOcclusion, Curvature, Thickness, Position, WorldNormal, Id };+constexpr int kMeshMapCount = 6;+constexpr uint32_t kAllMeshMaps = (1u << kMeshMapCount) - 1;+inline uint32_t meshMapBit(MeshMapKind k) { return 1u << uint32_t(k); }+const char* meshMapId(MeshMapKind k); // "ao", "curvature", "thickness", "position", "world_normal", "id"+const char* meshMapLabel(MeshMapKind k); // "Ambient Occlusion", ...+bool parseMeshMap(const std::string& text, MeshMapKind& out);+// A comma list of ids, or "all".+bool parseMeshMaps(const std::string& list, uint32_t& kinds, std::string& error);++struct MeshMapSettings {+ int aoRays = 32;+ float aoDistance = 0.05f; // x the Part's bounding-box diagonal+ int thicknessRays = 16;+ float thicknessDistance = 0.1f;+ float curvatureRadius = 0.02f;+ bool operator==(const MeshMapSettings&) const = default;+};++struct MeshMapSet {+ int width = 0, height = 0;+ uint32_t kinds = 0; // baked maps (meshMapBit)+ MeshMapSettings settings;+ std::array<TileImage, kMeshMapCount> images;+ glm::vec3 boundsMin{0.0f}, boundsMax{1.0f}; // the box Position spans+ float diagonal = 1.0f;+ uint64_t uvKey = 0; // meshUvFingerprint of the UVs baked on+ size_t vertexCount = 0, triangleCount = 0;+ // The positions baked from (live updates compare against them); shared with copies.+ std::shared_ptr<const std::vector<glm::vec3>> positions;+ uint64_t revision = 1; // changes with every bake (Fill layers re-evaluate)+ bool live = true; // bake the changed tiles again after sculpting+ double seconds = 0.0; // the last bake's time+ size_t texelsBaked = 0;++ bool has(MeshMapKind k) const { return (kinds & meshMapBit(k)) != 0; }+ // Still describes `mesh` (same topology and UV layout) at this size.+ bool matches(const Mesh& mesh, int width, int height) const;+ size_t bytes() const;+ // Values at texel (x, y): scalar maps 0..1; Position 0..1 in the box; WorldNormal a unit vector; Id the colour.+ float value(MeshMapKind k, int x, int y) const;+ glm::vec3 vector(MeshMapKind k, int x, int y) const;+};++// Per-vertex mean curvature in 1 / length (> 0 convex): 2 (p - mean of the one-ring) . n over the ring's mean squared+// edge length, so a sphere of radius R gives 1 / R at any density; smoothed once over the ring.+std::vector<float> meshMeanCurvature(const Mesh& mesh);+// The ID map's colour for a key (a polygroup, a Part): bright, well spread hues (sRGB 0..1).+glm::vec3 idMapColor(uint32_t key);++// Bakes `kinds` of `mesh` (its UVs) at width x height into `out` (every tile). False + error when the mesh has no+// UVs; "Cancelled" when `progress` returns false.+bool bakeMeshMaps(const Mesh& mesh, int width, int height, uint32_t kinds, const MeshMapSettings& settings,+ MeshMapSet& out, std::string& error, const BakeProgress& progress = {});++// --- Live updates ---+// The box around the vertices that moved since `set` was baked (empty box: none moved), and their indices.+AABB changedRegion(const MeshMapSet& set, const Mesh& mesh, std::vector<uint32_t>* moved = nullptr);++// One incremental re-bake: made on the main thread from the mesh (prepare), run anywhere (run: no access to the+// document), applied on the main thread (apply). Holds a compact copy of the triangles near the change.+struct MeshMapUpdate {+ std::vector<uint32_t> tiles; // tiles to bake again+ std::vector<TexelTile> texels; // per tile: texel -> local triangle (kNoTexelTriangle: keep the old value)+ Mesh local; // the triangles near the change (positions, normals, UVs, polygroups)+ std::vector<uint32_t> movedVertices; // mesh vertices that moved, and where they are now+ std::vector<glm::vec3> movedPositions;+ std::shared_ptr<const MeshMapSet> base; // the set it updates+ std::array<std::vector<TileImage::TilePtr>, kMeshMapCount> result; // per kind, per tile+ size_t texelsBaked = 0;+ double seconds = 0.0;+ bool ok = false;+};+// Readies an update for the change `region` (changedRegion); false when nothing needs baking.+bool prepareMeshMapUpdate(const Mesh& mesh, const std::shared_ptr<const MeshMapSet>& set, const AABB& region,+ std::vector<uint32_t> moved, MeshMapUpdate& update);+void runMeshMapUpdate(MeshMapUpdate& update, const std::atomic<bool>* cancel = nullptr);+// A new set with the update's tiles and positions in it (the old one may be shared with undo steps and copies).+std::shared_ptr<MeshMapSet> applyMeshMapUpdate(const MeshMapUpdate& update);++// One line for people: which maps, size, memory, time.+std::string describeMeshMaps(const MeshMapSet& set);+// After the active Part's Mesh Maps changed (baked, cleared, updated): Fill layers that read them re-evaluate+// (core/LayerStack.cpp). Every tile when `tiles` is null.+void notifyMeshMapsChanged(Document& doc, Mesh& mesh, const std::vector<uint32_t>* tiles = nullptr);++// mesh_maps (bake / clear / info / live).+void registerMeshMapCommands(CommandRegistry& registry);} // namespace sfdiff --git a/src/core/Polypaint.cpp b/src/core/Polypaint.cppindex 48b3abcc..27ff9aea 100644--- a/src/core/Polypaint.cpp+++ b/src/core/Polypaint.cpp@@ -1,6 +1,7 @@// SculptForge - open source digital sculpting// SPDX-License-Identifier: GPL-3.0-or-later#include "core/Polypaint.h"+#include "core/MeshMaps.h"#include "core/MapExport.h"#include "core/Commands.h"@@ -404,6 +405,7 @@ void registerPaintCommands(CommandRegistry& registry) {registerPaintLayerCommands(registry); // paint_layer_* (core/PaintLayer.cpp)registerTextureCommands(registry); // texture_*, uv_auto, paint_target (core/TextureCommands.cpp)registerTextureChannelCommands(registry); // texture_channels, paint_material, channel_view (core/TextureChannelCommands.cpp)+ registerMeshMapCommands(registry); // mesh_maps (core/MeshMaps.cpp)registerMapExportCommands(registry); // export_maps (core/MapExport.cpp)}diff --git a/src/core/RayBvh.h b/src/core/RayBvh.hnew file mode 100644index 00000000..e4eafc21--- /dev/null+++ b/src/core/RayBvh.h@@ -0,0 +1,270 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Ray BVH for baking (core/Bake.h, core/MeshMaps.h): a binned-SAH tree over a triangle list with a nearest-hit+// query (the hit nearest a target distance along the ray, for cage rays) and an any-hit query (occlusion).+// Queries are const and keep their state on the stack, so any number of threads can cast at once. Unlike the+// brush BVH (core/BVH.h) it is built once and never refitted.+#pragma once++#include <glm/glm.hpp>++#include <algorithm>+#include <cmath>+#include <cstdint>+#include <limits>+#include <vector>++namespace sf {++struct RayHitInfo {+ float t = 0, u = 0, v = 0;+ uint32_t tri = 0;+};++class RayBvh {+public:+ void build(const std::vector<glm::vec3>& pos, const std::vector<glm::uvec3>& tris) {+ const size_t n = tris.size();+ nodes_.clear();+ order_.resize(n);+ std::vector<glm::vec3> centroid(n);+ std::vector<Box> box(n);+ for (size_t i = 0; i < n; ++i) {+ order_[i] = uint32_t(i);+ const glm::vec3 &a = pos[tris[i].x], &b = pos[tris[i].y], &c = pos[tris[i].z];+ box[i].lo = glm::min(a, glm::min(b, c));+ box[i].hi = glm::max(a, glm::max(b, c));+ centroid[i] = (box[i].lo + box[i].hi) * 0.5f;+ }+ nodes_.reserve(n ? 2 * n / kLeaf + 16 : 1);+ nodes_.push_back({});+ if (n == 0) {+ nodes_[0].lo = nodes_[0].hi = glm::vec3(0.0f);+ return;+ }+ struct Job {+ uint32_t node, first, count;+ };+ std::vector<Job> stack = {{0, 0, uint32_t(n)}};+ while (!stack.empty()) {+ const Job j = stack.back();+ stack.pop_back();+ Box nb, cb;+ for (uint32_t i = j.first; i < j.first + j.count; ++i) {+ nb.grow(box[order_[i]]);+ cb.grow(centroid[order_[i]]);+ }+ nodes_[j.node].lo = nb.lo;+ nodes_[j.node].hi = nb.hi;+ uint32_t mid = 0;+ if (j.count > kLeaf && split(j.first, j.count, nb, cb, box, centroid, mid)) {+ const uint32_t left = uint32_t(nodes_.size());+ nodes_.push_back({});+ nodes_.push_back({});+ nodes_[j.node].index = left;+ nodes_[j.node].count = 0;+ stack.push_back({left, j.first, mid - j.first});+ stack.push_back({left + 1, mid, j.first + j.count - mid});+ } else {+ nodes_[j.node].index = j.first;+ nodes_[j.node].count = j.count;+ }+ }+ tris_.resize(n);+ for (size_t i = 0; i < n; ++i) {+ const glm::uvec3& t = tris[order_[i]];+ tris_[i] = {pos[t.x], pos[t.y] - pos[t.x], pos[t.z] - pos[t.x]};+ }+ }++ // The hit with t in [tmin, tmax] nearest to `target`.+ bool nearest(const glm::vec3& o, const glm::vec3& d, float tmin, float tmax, float target, RayHitInfo& hit) const {+ if (tris_.empty()) return false;+ const glm::vec3 inv = invDir(d);+ float best = std::numeric_limits<float>::max();+ bool found = false;+ uint32_t stack[64];+ int sp = 0;+ float tn, tf;+ if (!slab(nodes_[0], o, inv, tmin, tmax, tn, tf)) return false;+ stack[sp++] = 0;+ while (sp) {+ const Node& n = nodes_[stack[--sp]];+ if (!slab(n, o, inv, tmin, tmax, tn, tf) || bound(tn, tf, target) >= best) continue;+ if (n.count) {+ for (uint32_t i = n.index; i < n.index + n.count; ++i) {+ float t, u, v;+ if (!intersect(tris_[i], o, d, t, u, v) || t < tmin || t > tmax) continue;+ const float e = std::abs(t - target);+ if (e < best) {+ best = e;+ hit = {t, u, v, order_[i]};+ found = true;+ }+ }+ continue;+ }+ float an, af, bn, bf;+ const bool ha = slab(nodes_[n.index], o, inv, tmin, tmax, an, af);+ const bool hb = slab(nodes_[n.index + 1], o, inv, tmin, tmax, bn, bf);+ const float la = ha ? bound(an, af, target) : best, lb = hb ? bound(bn, bf, target) : best;+ // Push the less promising child first so the better one is visited next.+ if (la < best && lb < best) {+ if (sp + 2 > 64) continue;+ if (la <= lb) {+ stack[sp++] = n.index + 1;+ stack[sp++] = n.index;+ } else {+ stack[sp++] = n.index;+ stack[sp++] = n.index + 1;+ }+ } else if (la < best && sp < 64) {+ stack[sp++] = n.index;+ } else if (lb < best && sp < 64) {+ stack[sp++] = n.index + 1;+ }+ }+ return found;+ }++ // Any hit with t in [tmin, tmax].+ bool occluded(const glm::vec3& o, const glm::vec3& d, float tmin, float tmax) const {+ if (tris_.empty()) return false;+ const glm::vec3 inv = invDir(d);+ uint32_t stack[64];+ int sp = 0;+ stack[sp++] = 0;+ float tn, tf;+ while (sp) {+ const Node& n = nodes_[stack[--sp]];+ if (!slab(n, o, inv, tmin, tmax, tn, tf)) continue;+ if (n.count) {+ for (uint32_t i = n.index; i < n.index + n.count; ++i) {+ float t, u, v;+ if (intersect(tris_[i], o, d, t, u, v) && t >= tmin && t <= tmax) return true;+ }+ continue;+ }+ if (sp + 2 <= 64) {+ stack[sp++] = n.index + 1;+ stack[sp++] = n.index;+ }+ }+ return false;+ }++private:+ static constexpr uint32_t kLeaf = 4;+ static constexpr int kBins = 16;+ struct Box {+ glm::vec3 lo{std::numeric_limits<float>::max()}, hi{std::numeric_limits<float>::lowest()};+ void grow(const glm::vec3& p) { lo = glm::min(lo, p), hi = glm::max(hi, p); }+ void grow(const Box& b) { lo = glm::min(lo, b.lo), hi = glm::max(hi, b.hi); }+ float area() const {+ if (lo.x > hi.x) return 0.0f;+ const glm::vec3 e = hi - lo;+ return e.x * e.y + e.y * e.z + e.z * e.x;+ }+ };+ struct Node {+ glm::vec3 lo{0.0f};+ uint32_t index = 0; // leaf: first triangle, inner: left child (right = index + 1)+ glm::vec3 hi{0.0f};+ uint32_t count = 0; // > 0 for leaves+ };+ struct Tri {+ glm::vec3 v0, e1, e2;+ };++ bool split(uint32_t first, uint32_t count, const Box& nb, const Box& cb, const std::vector<Box>& box,+ const std::vector<glm::vec3>& centroid, uint32_t& mid) {+ float bestCost = std::numeric_limits<float>::max();+ int bestAxis = -1, bestBin = 0;+ const glm::vec3 ext = cb.hi - cb.lo;+ for (int axis = 0; axis < 3; ++axis) {+ if (ext[axis] <= 0.0f) continue;+ Box bins[kBins];+ uint32_t cnt[kBins] = {};+ const float k = float(kBins) * 0.9999f / ext[axis];+ for (uint32_t i = first; i < first + count; ++i) {+ const int b = std::min(kBins - 1, int((centroid[order_[i]][axis] - cb.lo[axis]) * k));+ bins[b].grow(box[order_[i]]);+ ++cnt[b];+ }+ float rightArea[kBins];+ uint32_t rightCount[kBins];+ Box acc;+ uint32_t c = 0;+ for (int b = kBins - 1; b > 0; --b) {+ acc.grow(bins[b]);+ c += cnt[b];+ rightArea[b] = acc.area();+ rightCount[b] = c;+ }+ acc = Box();+ c = 0;+ for (int b = 0; b < kBins - 1; ++b) {+ acc.grow(bins[b]);+ c += cnt[b];+ if (!c || !rightCount[b + 1]) continue;+ const float cost = acc.area() * float(c) + rightArea[b + 1] * float(rightCount[b + 1]);+ if (cost < bestCost) {+ bestCost = cost;+ bestAxis = axis;+ bestBin = b;+ }+ }+ }+ if (bestAxis < 0) { // all centroids in one spot: split in the middle of the list+ if (count <= 16) return false;+ mid = first + count / 2;+ return true;+ }+ // A leaf costs about one intersection per triangle; stop when splitting doesn't pay.+ if (count <= 8 && bestCost >= nb.area() * float(count)) return false;+ const float k = float(kBins) * 0.9999f / ext[bestAxis];+ auto* b = order_.data() + first;+ auto* e = b + count;+ auto* m = std::partition(b, e, [&](uint32_t t) {+ return std::min(kBins - 1, int((centroid[t][bestAxis] - cb.lo[bestAxis]) * k)) <= bestBin;+ });+ mid = uint32_t(m - order_.data());+ if (mid == first || mid == first + count) mid = first + count / 2;+ return true;+ }++ static glm::vec3 invDir(const glm::vec3& d) {+ auto inv = [](float x) { return std::abs(x) > 1e-20f ? 1.0f / x : (x < 0 ? -1e20f : 1e20f); };+ return {inv(d.x), inv(d.y), inv(d.z)};+ }+ static bool slab(const Node& n, const glm::vec3& o, const glm::vec3& inv, float tmin, float tmax, float& tn, float& tf) {+ const glm::vec3 t0 = (n.lo - o) * inv, t1 = (n.hi - o) * inv;+ const glm::vec3 a = glm::min(t0, t1), b = glm::max(t0, t1);+ tn = std::max(std::max(a.x, a.y), std::max(a.z, tmin));+ tf = std::min(std::min(b.x, b.y), std::min(b.z, tmax));+ return tn <= tf;+ }+ static float bound(float tn, float tf, float target) { return target < tn ? tn - target : target > tf ? target - tf : 0.0f; }+ // Two-sided Moller-Trumbore.+ static bool intersect(const Tri& tr, const glm::vec3& o, const glm::vec3& d, float& t, float& u, float& v) {+ const glm::vec3 p = glm::cross(d, tr.e2);+ const float det = glm::dot(tr.e1, p);+ if (std::abs(det) < 1e-20f) return false;+ const float inv = 1.0f / det;+ const glm::vec3 s = o - tr.v0;+ u = glm::dot(s, p) * inv;+ if (u < 0.0f || u > 1.0f) return false;+ const glm::vec3 q = glm::cross(s, tr.e1);+ v = glm::dot(d, q) * inv;+ if (v < 0.0f || u + v > 1.0f) return false;+ t = glm::dot(tr.e2, q) * inv;+ return true;+ }++ std::vector<Node> nodes_;+ std::vector<uint32_t> order_;+ std::vector<Tri> tris_;+};++} // namespace sfdiff --git a/src/core/Texture.cpp b/src/core/Texture.cppindex 8b6f14cb..ac3c3ee9 100644--- a/src/core/Texture.cpp+++ b/src/core/Texture.cpp@@ -1999,4 +1999,29 @@ void clearTextureLayer(PaintTexture& t, int layer) {uint64_t meshUvFingerprint(const Mesh& mesh) { return uvFingerprint(mesh); }+bool texelTile(const Mesh& m, int width, int height, uint32_t tile, TexelTile& out) {+ if (m.uvs.size() != m.triangleCount() * 3 || width <= 0 || height <= 0) return false;+ const uint64_t key = paintKey(m, width, height);+ const PaintCacheEntry e = paintCache(m, width, height, key);+ if (tile >= uint32_t(e.index->tilesX) * uint32_t(e.index->tilesY)) return false;+ PaintTexture dims; // (buildTexelMap reads the size only)+ dims.width = width;+ dims.height = height;+ const std::unique_ptr<TexelMapTile> map = buildTexelMap(m, dims, *e.index, tile);+ constexpr size_t n = size_t(kTextureTile) * kTextureTile;+ out.tri.assign(map->tri.begin(), map->tri.end());+ out.bary.resize(n);+ for (size_t i = 0; i < n; ++i) out.bary[i] = glm::vec2(map->bary[i * 2], map->bary[i * 2 + 1]) / 65535.0f;+ return true;+}++bool triangleTiles(const Mesh& m, int width, int height, uint32_t tri, int& tx0, int& ty0, int& tx1, int& ty1) {+ if (m.uvs.size() != m.triangleCount() * 3 || tri >= m.triangleCount()) return false;+ const PaintCacheEntry e = paintCache(m, width, height, paintKey(m, width, height));+ const uint8_t* o = &e.index->triTiles[size_t(tri) * 4];+ if (o[0] > o[2]) return false;+ tx0 = o[0], ty0 = o[1], tx1 = o[2], ty1 = o[3];+ return true;+}+} // namespace sfdiff --git a/src/core/Texture.h b/src/core/Texture.hindex 9de11a31..6ad0e640 100644--- a/src/core/Texture.h+++ b/src/core/Texture.h@@ -66,6 +66,7 @@ struct TextureLayer {};struct UvTileIndex; // (Texture.cpp)+struct MeshMapSet; // (core/MeshMaps.h)struct TexelMapCache; // (Texture.cpp)struct PaintTexture {@@ -83,6 +84,9 @@ struct PaintTexture {std::vector<uint8_t> viewPixels;Channel viewChannel = Channel::BaseColor;uint64_t viewRevision = 0;+ // Mesh Maps (core/MeshMaps.h): the Part's AO, curvature, thickness, ... on these UVs at this size, which Fill+ // layers read. Derived data, replaced as a whole when re-baked (copies and undo steps share it); not saved.+ std::shared_ptr<const MeshMapSet> meshMaps;// The RGBA8 texels the viewport shows: the composite, or the solo channel.const std::vector<uint8_t>& shown() const {return viewChannel != Channel::BaseColor && viewPixels.size() == pixels.size() ? viewPixels : pixels;@@ -125,6 +129,19 @@ struct PaintTexture {size_t colourBytes() const;};+// --- Texel maps (Mesh Maps and fill layers, core/MeshMaps.h, core/LayerStack.h) ---+// Texture tile `tile` (kTextureTile texels square; tiles row-major, rows bottom-up): every texel's triangle+// (kNoTexelTriangle where no UV island reaches) and barycentrics (b1, b2; b0 = 1 - b1 - b2), gutter texels mapped+// to their nearest island point. Built from the mesh's UVs (thread-safe: reads the mesh, the shared UV bins).+constexpr uint32_t kNoTexelTriangle = UINT32_MAX;+struct TexelTile {+ std::vector<uint32_t> tri;+ std::vector<glm::vec2> bary;+};+bool texelTile(const Mesh& mesh, int width, int height, uint32_t tile, TexelTile& out);+// The texture tiles triangle `tri` reaches with the gutter, inclusive; false when none.+bool triangleTiles(const Mesh& mesh, int width, int height, uint32_t tri, int& tx0, int& ty0, int& tx1, int& ty1);+// A fingerprint of the mesh's UVs (sampled; changes when the layout does), for caches keyed by UV layout.uint64_t meshUvFingerprint(const Mesh& mesh);// Bytes of the texture-painting caches shared by every texture on the same UVs (UV tile bins, coverage, texeldiff --git a/tests/test_bake.cpp b/tests/test_bake.cppindex f5fd91cf..289cf1f4 100644--- a/tests/test_bake.cpp+++ b/tests/test_bake.cpp@@ -332,7 +332,7 @@ TEST(bake_errors) {uint32_t maps = 0;CHECK(parseBakeMaps("normal, AO,disp", maps, err));CHECK(maps == (bakeBit(BakeMap::Normal) | bakeBit(BakeMap::AmbientOcclusion) | bakeBit(BakeMap::Displacement)));- CHECK(parseBakeMaps("all", maps, err) && maps == 63u);+ CHECK(parseBakeMaps("all", maps, err) && maps == (1u << kBakeMapCount) - 1u);CHECK(!parseBakeMaps("normal,specular", maps, err));// Cancelling stops it.st.maps = bakeBit(BakeMap::Normal);diff --git a/tests/test_mesh_maps.cpp b/tests/test_mesh_maps.cppnew file mode 100644index 00000000..82ed76f7--- /dev/null+++ b/tests/test_mesh_maps.cpp@@ -0,0 +1,286 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Mesh Maps (core/MeshMaps.h) and the bake's new maps (core/Bake.h): the mean curvature estimate, AO in a trench,+// thickness of thin and thick shapes, position and world normal, live updates matching a full bake texel for+// texel, UDIM tiles, and baking a Part's top subdivision level onto its lowest.+#include "TestHarness.h"++#include "core/Bake.h"+#include "core/MeshMaps.h"+#include "core/Multires.h"+#include "core/Primitives.h"+#include "core/Texture.h"++#include <chrono>+#include <cmath>++using namespace sf;++namespace {++void planarUvs(Mesh& m, int axisA = 0, int axisB = 2) {+ const AABB b = m.bounds();+ const glm::vec3 e = glm::max(b.extent(), glm::vec3(1e-6f));+ m.uvs.resize(m.triangleCount() * 3);+ for (size_t t = 0; t < m.triangleCount(); ++t)+ for (int c = 0; c < 3; ++c) {+ const glm::vec3 p = m.positions[m.triangles[t][c]];+ m.uvs[t * 3 + size_t(c)] = glm::vec2((p[axisA] - b.min[axisA]) / e[axisA], (p[axisB] - b.min[axisB]) / e[axisB]) * 0.96f + 0.02f;+ }+}++// Spherical UVs with the seam column duplicated per triangle (good enough for maps on a sphere).+void sphereUvs(Mesh& m) {+ m.uvs.resize(m.triangleCount() * 3);+ for (size_t t = 0; t < m.triangleCount(); ++t) {+ glm::vec2 uv[3];+ for (int c = 0; c < 3; ++c) {+ const glm::vec3 p = glm::normalize(m.positions[m.triangles[t][c]]);+ uv[c] = glm::vec2(0.5f + std::atan2(p.z, p.x) / 6.2831853f, 0.5f + std::asin(std::clamp(p.y, -1.0f, 1.0f)) / 3.1415927f);+ }+ for (int c = 1; c < 3; ++c) // (keep a triangle on one side of the seam)+ if (uv[c].x - uv[0].x > 0.5f) uv[c].x -= 1.0f;+ else if (uv[0].x - uv[c].x > 0.5f) uv[c].x += 1.0f;+ for (int c = 0; c < 3; ++c) m.uvs[t * 3 + size_t(c)] = glm::vec2(std::clamp(uv[c].x, 0.0f, 1.0f), uv[c].y);+ }+}++// A plane with a V trench along z in the middle.+Mesh trench() {+ Mesh m = makePlane(64);+ for (glm::vec3& p : m.positions) p.y = -0.6f * std::max(0.0f, 0.3f - std::abs(p.x));+ m.recomputeAllNormals();+ planarUvs(m);+ return m;+}++// The mean value of a scalar map over texels whose texel-map triangle exists and satisfies `where`.+template <class Where>+double meanWhere(const Mesh& m, const MeshMapSet& s, MeshMapKind k, Where where) {+ double sum = 0;+ size_t n = 0;+ const int tilesX = (s.width + 63) / 64, tilesY = (s.height + 63) / 64;+ for (int ty = 0; ty < tilesY; ++ty)+ for (int tx = 0; tx < tilesX; ++tx) {+ TexelTile tt;+ if (!texelTile(m, s.width, s.height, uint32_t(ty * tilesX + tx), tt)) continue;+ for (int li = 0; li < 64 * 64; ++li) {+ const uint32_t t = tt.tri[size_t(li)];+ if (t == kNoTexelTriangle) continue;+ const glm::vec2 b = tt.bary[size_t(li)];+ const glm::uvec3 tv = m.triangles[t];+ const glm::vec3 p = m.positions[tv.x] * (1 - b.x - b.y) + m.positions[tv.y] * b.x + m.positions[tv.z] * b.y;+ if (!where(p)) continue;+ sum += s.value(k, tx * 64 + li % 64, ty * 64 + li / 64);+ ++n;+ }+ }+ return n ? sum / double(n) : -1.0;+}++} // namespace++TEST(mesh_maps_mean_curvature_is_one_over_radius) {+ for (int sub : {3, 5})+ for (float radius : {1.0f, 2.5f}) {+ const Mesh m = makeIcosphere(sub, radius);+ const std::vector<float> h = meshMeanCurvature(m);+ double mean = 0;+ for (float v : h) mean += v;+ mean /= double(h.size());+ CHECK(std::abs(mean * radius - 1.0) < 0.03); // density-independent, convex > 0+ }+ // A flat plane has none.+ const std::vector<float> flat = meshMeanCurvature(makePlane(16));+ float worst = 0;+ for (float v : flat) worst = std::max(worst, std::abs(v));+ CHECK(worst < 1e-3f);+}++TEST(mesh_maps_ao_curvature_and_normal_on_a_trench) {+ const Mesh m = trench();+ MeshMapSet s;+ std::string err;+ MeshMapSettings st;+ st.aoRays = 48;+ st.aoDistance = 0.2f;+ CHECK(bakeMeshMaps(m, 256, 256, kAllMeshMaps, st, s, err));+ CHECK(s.kinds == kAllMeshMaps && s.texelsBaked > 50000);+ const double floorAo = meanWhere(m, s, MeshMapKind::AmbientOcclusion, [](glm::vec3 p) { return std::abs(p.x) < 0.04f; });+ const double flatAo = meanWhere(m, s, MeshMapKind::AmbientOcclusion, [](glm::vec3 p) { return std::abs(p.x) > 0.8f; });+ std::printf(" trench AO %.3f, flat AO %.3f\n", floorAo, flatAo);+ CHECK(flatAo > 0.97);+ CHECK(floorAo < flatAo - 0.15);+ // The trench's floor is concave (dark curvature), its rims convex (bright), the flat mid-grey.+ const double floorCurv = meanWhere(m, s, MeshMapKind::Curvature, [](glm::vec3 p) { return std::abs(p.x) < 0.02f; });+ const double rimCurv = meanWhere(m, s, MeshMapKind::Curvature, [](glm::vec3 p) { return std::abs(std::abs(p.x) - 0.3f) < 0.02f; });+ const double flatCurv = meanWhere(m, s, MeshMapKind::Curvature, [](glm::vec3 p) { return std::abs(p.x) > 0.8f; });+ std::printf(" curvature floor %.3f rim %.3f flat %.3f\n", floorCurv, rimCurv, flatCurv);+ CHECK(std::abs(flatCurv - 0.5) < 0.01);+ CHECK(floorCurv < 0.45 && rimCurv > 0.55);+ // World normal on the flat part points up; position spans the box.+ const int x = 250, y = 128; // near +x edge+ CHECK(s.vector(MeshMapKind::WorldNormal, x, y).y > 0.99f);+ CHECK(s.vector(MeshMapKind::Position, x, y).x > 0.95f);+ CHECK(s.vector(MeshMapKind::Position, 5, y).x < 0.05f);+}++TEST(mesh_maps_thickness_tells_thin_from_thick) {+ Mesh ball = makeIcosphere(4, 1.0f);+ sphereUvs(ball);+ Mesh slab = makeCube(8, 2.0f);+ for (glm::vec3& p : slab.positions) p.y *= 0.03f;+ slab.recomputeAllNormals();+ planarUvs(slab);+ MeshMapSettings st;+ st.thicknessRays = 24;+ st.thicknessDistance = 0.1f;+ MeshMapSet a, b;+ std::string err;+ CHECK(bakeMeshMaps(ball, 128, 128, meshMapBit(MeshMapKind::Thickness), st, a, err));+ CHECK(bakeMeshMaps(slab, 128, 128, meshMapBit(MeshMapKind::Thickness), st, b, err));+ const double thick = meanWhere(ball, a, MeshMapKind::Thickness, [](glm::vec3) { return true; });+ const double thin = meanWhere(slab, b, MeshMapKind::Thickness, [](glm::vec3 p) { return std::abs(p.x) < 0.8f && std::abs(p.z) < 0.8f; });+ std::printf(" thickness sphere %.3f slab %.3f\n", thick, thin);+ CHECK(thick > 0.9 && thin < 0.5);+}++TEST(mesh_maps_live_update_matches_a_full_bake) {+ Mesh m = trench();+ MeshMapSettings st;+ st.aoRays = 16;+ st.thicknessRays = 8;+ auto set = std::make_shared<MeshMapSet>();+ std::string err;+ CHECK(bakeMeshMaps(m, 256, 256, kAllMeshMaps, st, *set, err));+ // Sculpt: a dent near one corner of the plane (inside the bounding box, which sets the maps' ray distances).+ const glm::vec3 c(-0.6f, 0.0f, -0.6f);+ for (glm::vec3& p : m.positions) {+ const float d = glm::distance(glm::vec2(p.x, p.z), glm::vec2(c.x, c.z));+ if (d < 0.15f) p.y -= 0.1f * (0.5f + 0.5f * std::cos(d / 0.15f * 3.14159265f));+ }+ m.recomputeAllNormals();+ std::vector<uint32_t> moved;+ const AABB region = changedRegion(*set, m, &moved);+ CHECK(region.valid() && !moved.empty());+ MeshMapUpdate up;+ CHECK(prepareMeshMapUpdate(m, set, region, moved, up));+ const size_t allTiles = size_t(4 * 4);+ std::printf(" update: %zu of %zu tiles, %zu local triangles of %zu\n", up.tiles.size(), allTiles, up.local.triangleCount(),+ m.triangleCount());+ CHECK(up.tiles.size() < allTiles);+ CHECK(up.local.triangleCount() < m.triangleCount());+ runMeshMapUpdate(up);+ CHECK(up.ok);+ const std::shared_ptr<MeshMapSet> updated = applyMeshMapUpdate(up);+ CHECK(updated && updated->revision == set->revision + 1);+ CHECK(!changedRegion(*updated, m).valid()); // the positions it remembers are the sculpted ones+ MeshMapSet full;+ CHECK(bakeMeshMaps(m, 256, 256, kAllMeshMaps, st, full, err));+ // (Position keeps the box of the first bake, so procedural patterns don't slide as the Part grows: compare the+ // other maps.)+ size_t differ = 0, total = 0;+ for (int k = 0; k < kMeshMapCount; ++k) {+ if (MeshMapKind(k) == MeshMapKind::Position) continue;+ size_t before = differ;+ for (int y = 0; y < 256; ++y)+ for (int x = 0; x < 256; ++x) {+ float a[4] = {}, b[4] = {};+ updated->images[size_t(k)].values(x, y, a);+ full.images[size_t(k)].values(x, y, b);+ ++total;+ for (int i = 0; i < 3; ++i)+ if (std::abs(a[i] - b[i]) > 1.0f / 255.0f) {+ ++differ;+ break;+ }+ }+ if (differ > before) std::printf(" %s: %zu texels differ\n", meshMapId(MeshMapKind(k)), differ - before);+ }+ std::printf(" %zu of %zu texels differ from a full bake\n", differ, total);+ CHECK(differ == 0);+}++TEST(mesh_maps_live_update_is_faster_than_a_full_bake) {+ // A denser Part: a 2K map of a 130k-triangle sphere, then a small local change.+ Mesh m = makeIcosphere(6, 1.0f);+ sphereUvs(m);+ MeshMapSettings st;+ auto set = std::make_shared<MeshMapSet>();+ std::string err;+ const auto t0 = std::chrono::steady_clock::now();+ CHECK(bakeMeshMaps(m, 2048, 2048, kAllMeshMaps, st, *set, err));+ const double full = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();+ for (glm::vec3& p : m.positions)+ if (glm::distance(p, glm::vec3(0, 0, 1)) < 0.08f) p *= 1.02f;+ m.recomputeAllNormals();+ std::vector<uint32_t> moved;+ const auto t1 = std::chrono::steady_clock::now();+ const AABB region = changedRegion(*set, m, &moved);+ MeshMapUpdate up;+ CHECK(prepareMeshMapUpdate(m, set, region, moved, up));+ runMeshMapUpdate(up);+ CHECK(applyMeshMapUpdate(up) != nullptr);+ const double live = std::chrono::duration<double>(std::chrono::steady_clock::now() - t1).count();+ std::printf(" 2K maps of %zu triangles: full bake %.2f s, live update of %zu tiles %.3f s\n", m.triangleCount(), full,+ up.tiles.size(), live);+ CHECK(live < full * 0.5);+}++TEST(bake_new_maps_udim_tiles_and_levels) {+ // A plane with its right half moved to UDIM tile 1002.+ Mesh low = makePlane(16);+ planarUvs(low);+ for (size_t t = 0; t < low.triangleCount(); ++t) {+ const glm::vec2 c = (low.uvs[t * 3] + low.uvs[t * 3 + 1] + low.uvs[t * 3 + 2]) / 3.0f;+ if (c.x > 0.5f)+ for (int i = 0; i < 3; ++i) low.uvs[t * 3 + size_t(i)].x += 1.0f;+ }+ CHECK(udimTiles(low) == std::vector<int>({1001, 1002}));+ Mesh high = makePlane(64);+ for (glm::vec3& p : high.positions) p.y = 0.02f * std::sin(p.x * 20.0f);+ high.recomputeAllNormals();+ BakeSettings st;+ st.size = 128;+ st.maps = bakeBit(BakeMap::Normal) | bakeBit(BakeMap::Curvature) | bakeBit(BakeMap::Thickness) | bakeBit(BakeMap::Position) |+ bakeBit(BakeMap::Id);+ std::vector<BakeResult> results;+ std::string err;+ CHECK(bakeMapsUdim(low, {&high}, st, results, err));+ CHECK(results.size() == 2 && results[0].udim == 1001 && results[1].udim == 1002);+ for (const BakeResult& r : results) {+ CHECK(r.islandTexels > 2000);+ CHECK(r.curvature.size() == 128 * 128 && r.position.size() == 128 * 128 * 3 && r.id.size() == 128 * 128 * 3);+ }+ CHECK(bakeFileName("Low", BakeMap::Curvature, ".png", 1002) == "Low_curvature.1002.png");+ std::vector<std::string> written;+ const std::string dir = tempPath("sf_bake_udim");+ CHECK(saveBakeMaps(results[1], dir, "Low", false, written, err));+ CHECK(written.size() == 5);++ // A Part's own levels: its top subdivision level (with sculpted ripples) baked onto its lowest.+ Mesh part = makeQuadSphere(6);+ sphereUvs(part);+ std::string e2;+ CHECK(subdivDivide(part, true, e2));+ CHECK(subdivDivide(part, true, e2));+ for (glm::vec3& p : part.positions) p *= 1.0f + 0.03f * std::sin(p.y * 30.0f);+ part.recomputeAllNormals();+ Mesh l, h;+ CHECK(bakeLevelSources(part, "subdivision", l, h, e2));+ CHECK(l.triangleCount() * 16 == h.triangleCount());+ BakeSettings ns;+ ns.size = 128;+ ns.maps = bakeBit(BakeMap::Normal);+ BakeResult nr;+ CHECK(bakeMaps(l, {&h}, ns, nr, e2));+ // The ripples show in the normal map: many texels lean away from flat.+ size_t leaning = 0;+ for (size_t i = 0; i < nr.normal.size(); i += 3) leaning += nr.normal[i + 2] < 245;+ std::printf(" level bake: %zu of %zu texels lean\n", leaning, nr.normal.size() / 3);+ CHECK(leaning > 1000);+ Mesh noLevels = makeIcosphere(2);+ CHECK(!bakeLevelSources(noLevels, "subdivision", l, h, e2));+ CHECK(!bakeLevelSources(noLevels, "micro", l, h, e2));+}diff --git a/tests/ui/bake_levels.sfui b/tests/ui/bake_levels.sfuinew file mode 100644index 00000000..719438cf--- /dev/null+++ b/tests/ui/bake_levels.sfui@@ -0,0 +1,52 @@+# Mesh Maps bake (Tool > Bake): a Part's own top subdivision level baked onto its lowest level, the new maps+# (curvature, thickness, position, ID), and in-texture Mesh Maps for Fill layers (mesh_maps).+# Files are written to the working directory (the build folder).+run new_sphere subdivisions=3+run uv_auto resolution=1024+expect_value uvs == 1+run polygroup_uv+run subdiv_divide+run subdiv_divide+expect_value sdiv_levels == 3+run stroke brush=Crease points="-0.6,0.35,1 0,0.55,1 0.6,0.35,1" radius=0.07 strength=1+run stroke brush=Inflate points="-0.35,-0.3,1" radius=0.3 strength=1+run stroke brush=Clay points="0.25,-0.5,1 0.55,-0.05,1" radius=0.1 strength=1++# The Bake sub-palette offers the Part's own levels as the source.+click "Bake##tool.bake"+click "Bake/##bakesource"+expect "Own top subdivision level##level"+click "Own top subdivision level##level"+expect_text "Own top subdivision level"+click "Bake/Curvature"+click "Bake/Thickness"+click "Bake/Position"+click "Bake/ID"+wait 0.2+shot bake-levels-palette+click "Bake/Bake"+expect_value bake_running == 1+wait_idle 300+expect_value bake_running == 0+expect_status "Baked normal, curvature, thickness, position, id at 2048x2048"+expect_value bake_files == 5++# The command: the same, smaller, with every map.+run bake source=subdivision maps=all size=512 out=sf_ui_bake_levels name=Levels+expect_status "Baked normal, object_normal, displacement, ao, cavity, curvature, thickness, position, id at 512x512"+run_fails bake source=micro maps=normal size=512 out=sf_ui_bake_levels++# (UDIM tiles: tests/test_mesh_maps.cpp, bake_new_maps_udim_tiles_and_levels.)++# Mesh Maps in the texture, for Fill layers: baked on the texture's UVs at its size.+run new_sphere subdivisions=4+run uv_auto resolution=512+run texture_create size=1024+run mesh_maps maps=all+expect_status "Mesh Maps ao, curvature, thickness, position, world_normal, id at 1024x1024"+expect_value mesh_maps == 63+run mesh_maps action=info+expect_status "live"+run mesh_maps action=clear+expect_value mesh_maps == 0+run_fails mesh_maps maps=shine