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
Texture transfer: Auto UV moves the paint and its layers onto the new UVs; remesh, QRemesh and merge keep the texture; decimate keeps UV seams
islandmede97473b77fb0
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 4d94baab..f0100a9e 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -60,6 +60,7 @@ add_library(sculptforge_core STATICsrc/core/Multires.cppsrc/core/MultiresCommands.cppsrc/core/AutoUv.cpp+ src/core/TextureTransfer.cppsrc/core/SurfaceQuery.cppsrc/core/QRemesh.cppsrc/core/Projection.cppdiff --git a/src/app/App.h b/src/app/App.hindex 9e9316d6..44299527 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -262,6 +262,7 @@ private:std::string comfyWorkflowError_;bool remeshGenerated_ = true;int voxelResolution_ = 200;+ bool keepTexture_ = true; // Keep Texture: remeshes carry a painted texture over (core/TextureTransfer.h)int splatMeshResolution_ = 192;int remeshResolution_ = 256;std::future<ai::GeneratorResult> pendingGenerator_;@@ -429,6 +430,7 @@ private:void drawQRemeshContents();void drawProjectContents();void startQRemesh();+ void drawKeepTextureCheckbox(const char* path); // Keep Texture under Remesh and QRemesh (PanelTexture.cpp)void pollQRemesh();struct QRemeshJob {std::future<bool> done;@@ -441,6 +443,7 @@ private:size_t triangles = 0; // the mesh must still have this many triangles when it finishesbool keepOriginal = false;Args args; // the equivalent qremesh command, for the console+ std::shared_ptr<std::string> textureNote; // what happened to a painted texture (Keep Texture)};std::unique_ptr<QRemeshJob> qremesh_;struct RetopoSettings {diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex 9464d1ec..60376254 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -390,6 +390,7 @@ void App::drawPalette_Tool() {ImGui::SliderInt("##voxres", &voxelResolution_, 64, 400, "Resolution %d");ui::HelpText("Resolution", nullptr, "Voxels across the model: higher keeps more detail and makes more triangles.","Tool > Remesh");+ if (hasTexture(doc_.mesh)) drawKeepTextureCheckbox("Tool > Remesh"); // only for a painted SubTool}if (subpalette("tool.masking", "Masking")) drawMaskingSection();if (subpalette("tool.polygroups", "Polygroups")) drawPolygroupsSection();diff --git a/src/app/PanelRetopo.cpp b/src/app/PanelRetopo.cppindex 67bb19d4..7459f98b 100644--- a/src/app/PanelRetopo.cpp+++ b/src/app/PanelRetopo.cpp@@ -9,6 +9,8 @@#include "app/Demo.h"#include "app/Ui.h"+#include "core/TextureTransfer.h"+#include <algorithm>#include <thread>@@ -87,15 +89,29 @@ void App::startQRemesh() {if (o.usePolypaint) job->args["use_polypaint"] = true;if (o.symmetryAxis >= 0) job->args["symmetry"] = std::string(1, char('x' + o.symmetryAxis));if (job->keepOriginal) job->args["keep_original"] = true;+ const bool keepTexture = keepTexture_;+ if (!keepTexture && hasTexture(doc_.mesh)) job->args["keep_texture"] = false;+ job->textureNote = std::make_shared<std::string>();std::promise<bool> promise;job->done = promise.get_future();std::thread([promise = std::move(promise), source = std::make_shared<Mesh>(doc_.mesh), o, progress = job->progress,- cancel = job->cancel, result = job->result, stats = job->stats, error = job->error]() mutable {- const bool ok = qremesh(*source, o, *result, *error, [&](float f) {- progress->store(f);+ cancel = job->cancel, result = job->result, stats = job->stats, error = job->error,+ note = job->textureNote, keepTexture]() mutable {+ // With a texture to keep, QRemesh takes the first 80% of the bar and Auto UV + transfer the rest.+ const float share = hasTexture(*source) && keepTexture ? 0.8f : 1.0f;+ bool ok = qremesh(*source, o, *result, *error, [&](float f) {+ progress->store(f * share);return !cancel->load();}, stats.get());+ if (ok) *note = carryTextureNote(*source, *result, keepTexture, [&](float f) {+ progress->store(share + (1.0f - share) * f);+ return !cancel->load();+ });+ if (ok && cancel->load()) {+ ok = false;+ *error = "QRemesh cancelled";+ }promise.set_value(ok);}).detach();qremesh_ = std::move(job);@@ -124,7 +140,7 @@ void App::pollQRemesh() {}if (index != doc_.activeSubtool) doc_.selectSubtool(index);if (doc_.sculptor.strokeActive()) endStroke();- CommandResult r{true, applyQRemesh(doc_, std::move(*job->result), job->keepOriginal, *job->stats)};+ CommandResult r{true, applyQRemesh(doc_, std::move(*job->result), job->keepOriginal, *job->stats) + *job->textureNote};status_ = r.message;lastCommandOk_ = true;clearLods();@@ -204,6 +220,10 @@ void App::drawQRemeshContents() {"Keep the SubTool as it was, hidden, right below the new one (\"<name> Original\"), ready to ""ProjectAll its detail back. Off: replace it, as ZBrush does (undo brings it back).",kQRemeshPath);+ if (hasTexture(doc_.mesh)) { // only matters for a painted SubTool+ ImGui::SameLine(half + style.ItemSpacing.x);+ drawKeepTextureCheckbox(kQRemeshPath);+ }}void App::drawProjectContents() {diff --git a/src/app/PanelTexture.cpp b/src/app/PanelTexture.cppindex 3b596a66..ed3d6a19 100644--- a/src/app/PanelTexture.cpp+++ b/src/app/PanelTexture.cpp@@ -12,6 +12,7 @@#include "app/Ui.h"#include "core/Polypaint.h"+#include "core/TextureTransfer.h"#include <IconsLucide.h>@@ -146,9 +147,24 @@ void App::registerTextureUiActions() {add("texture.delete", "Delete Texture", kPath, [this] { runCommand("texture_delete"); }, nullptr,[this] { return doc_.mesh.texture != nullptr; },"Remove the SubTool's texture (undoable). Painting goes back to the vertices.", "texture_delete");+ add("geometry.keep_texture", "Keep Texture", "Tool > Remesh", [this] { keepTexture_ = !keepTexture_; },+ [this] { return keepTexture_; }, nullptr,+ "Voxel Remesh and QRemesh keep a painted texture: the new mesh gets Auto UVs and the texture (every layer) "+ "is projected onto it from the old surface, in the same undo step. Off: the texture is dropped. Merging "+ "SubTools keeps textures too. Shown under Remesh and QRemesh when the SubTool has a texture.",+ "");for (int i = 0; i < 2; ++i) g_dialogs[i] = {this, TextureFile(i)};}+void App::drawKeepTextureCheckbox(const char* path) {+ ImGui::Checkbox("Keep Texture", &keepTexture_);+ ui::HelpText("Keep Texture", nullptr,+ "Keep the painted texture: the new mesh gets Auto UVs and the texture (every layer) is projected onto "+ "it from the old surface, in the same undo step (it adds the Auto UV time). Off: the texture is "+ "dropped. Scripts: keep_texture=false.",+ path);+}+void App::startAutoUv() {if (autoUv_ || doc_.mesh.triangleCount() == 0) return;auto job = std::make_unique<AutoUvJob>();@@ -203,15 +219,14 @@ void App::pollAutoUv() {}if (index != doc_.activeSubtool) doc_.selectSubtool(index);if (doc_.sculptor.strokeActive()) endStroke();- const bool repainted = doc_.mesh.texture != nullptr;Mesh m = doc_.mesh;- m.uvs = std::move(job->result->uvs);+ // A painted texture and its layers move onto the new UVs, in the same undo step (core/TextureTransfer.h).+ const std::string note = setUvsKeepingTexture(m, std::move(job->result->uvs));doc_.replaceMeshUndoable(std::move(m), "Auto UV");uvLinesKey_ = 0;updateTitle();status_ = "Auto UV: " + std::to_string(job->result->charts) + " UV islands" +- (repainted ? " (the texture was painted on the old UVs; undo to get them back)"- : hasTexture(doc_.mesh) ? "" : ". Now make a texture: Tool > Texture Map > New Texture");+ (!note.empty() ? note : hasTexture(doc_.mesh) ? "" : ". Now make a texture: Tool > Texture Map > New Texture");}void App::drawTextureMapContents() {diff --git a/src/app/Shell.cpp b/src/app/Shell.cppindex 722d7ec6..ba749dc7 100644--- a/src/app/Shell.cpp+++ b/src/app/Shell.cpp@@ -395,7 +395,12 @@ void App::registerShellActions() {[this] { requestQuit(); }, nullptr, nullptr});add({"geometry.remesh", "Voxel Remesh", nullptr,"Rebuild as an even, watertight surface (like DynaMesh): merges parts, fixes scans and generated models.",- "Tool > Remesh", "", "remesh", [this] { runCommand("remesh", {{"resolution", double(voxelResolution_)}}); },+ "Tool > Remesh", "", "remesh",+ [this] {+ Args a{{"resolution", double(voxelResolution_)}};+ if (!keepTexture_ && hasTexture(doc_.mesh)) a["keep_texture"] = false; // Keep Texture off+ runCommand("remesh", a);+ },nullptr, nullptr});add({"geometry.to_splats", "Sculpt to Splats", nullptr, "Turn the sculpt into Gaussian splats.", "Splats", "","mesh_to_splats", [this] { runCommand("mesh_to_splats"); }, nullptr, nullptr});diff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex 03edd06c..1b9e6c36 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -19,6 +19,7 @@#include "core/Project.h"#include "core/QRemesh.h"#include "core/Splats.h"+#include "core/TextureTransfer.h"#include "core/Voxel.h"#include "io/FbxIO.h"#include "io/GltfIO.h"@@ -190,14 +191,18 @@ CommandRegistry::CommandRegistry() {add({"remesh","Voxel remesh (like DynaMesh): rebuild the sculpt as an even, watertight surface, merging overlapping "- "parts and fixing broken scans or generated models. Sculpt layers are baked in.",- {{"resolution", T::Number, "Voxels across the longest side (32-512). Default 200; higher keeps more detail.", false}},+ "parts and fixing broken scans or generated models. Sculpt layers are baked in. A painted texture is "+ "kept (new Auto UVs, colour projected from the old surface) unless keep_texture=false.",+ {{"resolution", T::Number, "Voxels across the longest side (32-512). Default 200; higher keeps more detail.", false},+ {"keep_texture", T::Bool, "Keep a painted texture: Auto UV the result and project the texture onto it. "+ "Default true.", false}},[](Document& doc, const Args& a) -> CommandResult {std::string err;Mesh m = voxelRemesh(doc.mesh, std::clamp(int(argNumber(a, "resolution", 200)), 32, 512), &err);if (m.triangleCount() == 0) return {false, err};+ const std::string texture = carryTextureNote(doc.mesh, m, argBool(a, "keep_texture", true));doc.replaceMeshUndoable(std::move(m), "Remesh");- return {true, "Remeshed to " + std::to_string(doc.mesh.triangleCount()) + " triangles"};+ return {true, "Remeshed to " + std::to_string(doc.mesh.triangleCount()) + " triangles" + texture};}});add({"image_relief",diff --git a/src/core/Decimate.cpp b/src/core/Decimate.cppindex 73408200..88274b34 100644--- a/src/core/Decimate.cpp+++ b/src/core/Decimate.cpp@@ -66,6 +66,21 @@ Mesh decimate(const Mesh& src, size_t targetTriangles) {for (uint32_t f = 0; f < nt; ++f)for (int c = 0; c < 3; ++c) vFaces[F[f][c]].push_back(f);+ // Vertices on a UV seam (corners with different UVs) stay put: collapsing one would give the corners on+ // the other side of the seam UVs from the wrong island, scrambling a painted texture there. Other vertices+ // collapse onto a kept vertex, whose UV in the collapsing faces' island the moved corners then take (exact).+ std::vector<char> uvSeam(nv, 0);+ if (!FUV.empty()) {+ std::vector<glm::vec2> firstUv(nv, glm::vec2(-1e30f));+ for (uint32_t f = 0; f < nt; ++f)+ for (int c = 0; c < 3; ++c) {+ const uint32_t v = F[f][c];+ const glm::vec2 uv = FUV[size_t(f) * 3 + size_t(c)];+ if (firstUv[v].x == -1e30f) firstUv[v] = uv;+ else if (glm::any(glm::greaterThan(glm::abs(firstUv[v] - uv), glm::vec2(1e-6f)))) uvSeam[v] = 1;+ }+ }+// Area-weighted plane quadrics.std::vector<Quadric> Q(nv);std::vector<glm::dvec3> faceN(nt);@@ -134,6 +149,7 @@ Mesh decimate(const Mesh& src, size_t targetTriangles) {heap.pop();const uint32_t u = c.from, v = c.to;if (!vAlive[u] || !vAlive[v] || version[u] != c.fromVersion || version[v] != c.toVersion) continue;+ if (uvSeam[u]) continue;shared.clear();for (uint32_t f : vFaces[u]) {@@ -171,12 +187,21 @@ Mesh decimate(const Mesh& src, size_t targetTriangles) {}if (!ok) continue;- // Corners that move from u to v take v's UV from a collapsed face- // (approximate across UV seams).+ // Corners that move from u to v take v's UV from a collapsed face (u is not on a seam, so all of its+ // faces lie in one UV island; skip the collapse if the collapsed faces disagree about v's UV).glm::vec2 uvOfV(0.0f);- if (!FUV.empty())- for (int k = 0; k < 3; ++k)- if (F[shared[0]][k] == v) uvOfV = FUV[size_t(shared[0]) * 3 + size_t(k)];+ if (!FUV.empty()) {+ bool first = true;+ for (uint32_t f : shared)+ for (int k = 0; k < 3; ++k)+ if (F[f][k] == v) {+ const glm::vec2 uv = FUV[size_t(f) * 3 + size_t(k)];+ if (!first && glm::any(glm::greaterThan(glm::abs(uv - uvOfV), glm::vec2(1e-6f)))) ok = false;+ uvOfV = uv;+ first = false;+ }+ if (!ok) continue;+ }for (uint32_t f : shared) {faceAlive[f] = 0;--liveFaces;diff --git a/src/core/RetopoCommands.cpp b/src/core/RetopoCommands.cppindex f44f0449..6a6b0321 100644--- a/src/core/RetopoCommands.cpp+++ b/src/core/RetopoCommands.cpp@@ -6,6 +6,7 @@#include "core/Commands.h"#include "core/Projection.h"#include "core/QRemesh.h"+#include "core/TextureTransfer.h"#include <algorithm>#include <cmath>@@ -62,7 +63,9 @@ void registerRetopoCommands(CommandRegistry& reg) {{"symmetry", T::String, "Mirror the topology across x, y or z (the plane through the origin). Default: none.", false},{"keep_original", T::Bool, "Keep the original as a hidden SubTool below (for project_all). Default false.", false},{"smooth", T::Number, "Relaxation passes on the surface (0-30). Default 6.", false},- {"seed", T::Number, "Random start of the direction field (results are repeatable per seed).", false}},+ {"seed", T::Number, "Random start of the direction field (results are repeatable per seed).", false},+ {"keep_texture", T::Bool, "Keep a painted texture: Auto UV the result and project the texture onto it. "+ "Default true.", false}},[](Document& doc, const Args& a) -> CommandResult {if (doc.mesh.triangleCount() == 0) return {false, "QRemesh: the SubTool is empty"};QRemeshOptions o;@@ -78,7 +81,8 @@ void registerRetopoCommands(CommandRegistry& reg) {std::string err;QRemeshStats st;if (!qremesh(doc.mesh, o, out, err, {}, &st)) return {false, err};- return {true, applyQRemesh(doc, std::move(out), argBool(a, "keep_original", false), st)};+ const std::string texture = carryTextureNote(doc.mesh, out, argBool(a, "keep_texture", true));+ return {true, applyQRemesh(doc, std::move(out), argBool(a, "keep_original", false), st) + texture};}});reg.add({"project_all",diff --git a/src/core/SubTools.cpp b/src/core/SubTools.cppindex 7556b577..23a20509 100644--- a/src/core/SubTools.cpp+++ b/src/core/SubTools.cpp@@ -6,6 +6,7 @@#include "core/Multires.h"#include "core/Polygroups.h"#include "core/Primitives.h"+#include "core/TextureTransfer.h"#include <algorithm>#include <filesystem>@@ -359,32 +360,42 @@ void registerSubToolCommands(CommandRegistry& reg) {reg.add({"subtool_merge_down","Merge the active SubTool with the one below it into one mesh (not undoable). Each keeps its own "- "polygroups, so subtool_split_groups can separate them again.", {},- [](Document& doc, const Args&) -> CommandResult {+ "polygroups, so subtool_split_groups can separate them again. Painted textures are kept in one new "+ "texture on new Auto UVs.",+ {{"keep_texture", T::Bool, "Keep painted textures (Auto UV the result and copy them in). Default true.", false}},+ [](Document& doc, const Args& a) -> CommandResult {const int i = doc.activeSubtool;if (i + 1 >= doc.subtoolCount()) return {false, "There's no SubTool below " + doc.activeSubtoolInfo().name};Mesh merged = mergeMeshes({&doc.subtoolMesh(i), &doc.subtoolMesh(i + 1)});+ const std::string texture = carryMergedTexturesNote({&doc.subtoolMesh(i), &doc.subtoolMesh(i + 1)}, merged,+ argBool(a, "keep_texture", true));const std::string name = doc.subtools[size_t(i)].name, below = doc.subtools[size_t(i + 1)].name;doc.removeSubtool(i + 1);doc.replaceActiveMesh(std::move(merged));- return {true, "Merged " + below + " into " + name + " (" + countText(doc.mesh.triangleCount()) + ")"};+ return {true, "Merged " + below + " into " + name + " (" + countText(doc.mesh.triangleCount()) + ")" + texture};}});reg.add({"subtool_merge_visible","Merge every visible SubTool into one new SubTool, replacing them (not undoable). Hidden SubTools stay "- "as they are.", {},- [](Document& doc, const Args&) -> CommandResult {+ "as they are. Painted textures are kept in one new texture on new Auto UVs.",+ {{"keep_texture", T::Bool, "Keep painted textures (Auto UV the result and copy them in). Default true.", false}},+ [](Document& doc, const Args& a) -> CommandResult {std::vector<int> visible;for (int i = 0; i < doc.subtoolCount(); ++i)if (doc.subtools[size_t(i)].visible) visible.push_back(i);if (visible.size() < 2) return {false, "Show at least two SubTools to merge"};Mesh merged = mergedVisibleMesh(doc);+ std::vector<const Mesh*> parts; // as mergedVisibleMesh gathers them+ for (int i : visible)+ if (doc.subtoolMesh(i).triangleCount()) parts.push_back(&doc.subtoolMesh(i));+ const std::string texture =+ parts.size() > 1 ? carryMergedTexturesNote(parts, merged, argBool(a, "keep_texture", true)) : std::string();const size_t tris = merged.triangleCount();const int at = visible.front();doc.addSubtool(std::move(merged), "Merged", true, at);for (auto it = visible.rbegin(); it != visible.rend(); ++it) doc.removeSubtool(*it + 1);return {true, "Merged " + std::to_string(visible.size()) + " SubTools into " +- doc.activeSubtoolInfo().name + " (" + countText(tris) + ")"};+ doc.activeSubtoolInfo().name + " (" + countText(tris) + ")" + texture};}});reg.add({"subtool_split_groups", "Split the active SubTool into one SubTool per polygroup (not undoable).", {},diff --git a/src/core/TextureCommands.cpp b/src/core/TextureCommands.cppindex ce30cffa..6edc7980 100644--- a/src/core/TextureCommands.cpp+++ b/src/core/TextureCommands.cpp@@ -6,6 +6,7 @@#include "core/AutoUv.h"#include "core/Polypaint.h"#include "core/Texture.h"+#include "core/TextureTransfer.h"#include "core/Undo.h"#include <algorithm>@@ -202,10 +203,12 @@ CommandResult textureLayerCommand(Document& doc, const std::string& verb, constvoid registerTextureCommands(CommandRegistry& reg) {reg.add({"uv_auto","Unwrap the active SubTool automatically (xatlas): cuts it into UV islands and packs them into the 0-1 "- "square, so it can carry a painted texture. Replaces any existing UVs (undoable). Can take a while on "- "millions of triangles.",+ "square, so it can carry a painted texture. Replaces any existing UVs; a painted texture and its layers "+ "are moved onto the new UVs (one undo step). Can take a while on millions of triangles.",{{"resolution", T::Number, "Texture size the islands are packed for (padding in texels). Default: the "- "texture's size, or 2048.", false}},+ "texture's size, or 2048.", false},+ {"keep_texture", T::Bool, "Move a painted texture onto the new UVs. Default true; false leaves the "+ "texels where they are (they no longer line up).", false}},[](Document& doc, const Args& a) -> CommandResult {if (doc.mesh.triangleCount() == 0) return {false, "There is no mesh to unwrap"};AutoUvResult result;@@ -214,12 +217,10 @@ void registerTextureCommands(CommandRegistry& reg) {: doc.mesh.texture ? std::max(doc.mesh.texture->width, doc.mesh.texture->height): kDefaultTextureSize;if (!computeAutoUv(doc.mesh.positions, doc.mesh.triangles, res, result, err)) return {false, err};- const bool repainted = doc.mesh.texture != nullptr;Mesh m = doc.mesh;- m.uvs = std::move(result.uvs);+ const std::string note = setUvsKeepingTexture(m, std::move(result.uvs), argBool(a, "keep_texture", true));doc.replaceMeshUndoable(std::move(m), "Auto UV");- return {true, "Auto UV: " + std::to_string(result.charts) + " UV islands" +- (repainted ? " (the texture was painted on the old UVs; undo to get them back)" : "")};+ return {true, "Auto UV: " + std::to_string(result.charts) + " UV islands" + note};}});reg.add({"texture_create",diff --git a/src/core/TextureTransfer.cpp b/src/core/TextureTransfer.cppnew file mode 100644index 00000000..49d58f32--- /dev/null+++ b/src/core/TextureTransfer.cpp@@ -0,0 +1,428 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/TextureTransfer.h"++#include "core/Parallel.h"+#include "core/SurfaceQuery.h"++#include <algorithm>+#include <atomic>+#include <chrono>+#include <cmath>+#include <cstdio>+#include <cstring>+#include <limits>++namespace sf {++namespace {++using Clock = std::chrono::steady_clock;+double secondsSince(Clock::time_point t) { return std::chrono::duration<double>(Clock::now() - t).count(); }++// One texture a texel can read from: its RGBA8 planes (same order as the destination's) and its UVs.+struct Source {+ const PaintTexture* tex = nullptr; // null: the part has no texture (its texels are white)+ const std::vector<glm::vec2>* uvs = nullptr;+ std::vector<const std::vector<uint8_t>*> planes;+};++// Bilinear RGBA at `uv` (texel centres at (x + 0.5) / w), weighted by alpha so transparent texels of a layer+// don't darken its edges. Opaque planes give plain bilinear filtering.+inline void sampleRgba(const uint8_t* plane, int w, int h, const glm::vec2& uv, uint8_t* out) {+ const float fx = std::clamp(uv.x, 0.0f, 1.0f) * float(w) - 0.5f, fy = std::clamp(uv.y, 0.0f, 1.0f) * float(h) - 0.5f;+ const float flx = std::floor(fx), fly = std::floor(fy);+ const int x0 = std::clamp(int(flx), 0, w - 1), y0 = std::clamp(int(fly), 0, h - 1);+ const int x1 = std::min(x0 + 1, w - 1), y1 = std::min(y0 + 1, h - 1);+ const float ax = std::clamp(fx - flx, 0.0f, 1.0f), ay = std::clamp(fy - fly, 0.0f, 1.0f);+ const uint8_t* p[4] = {plane + (size_t(y0) * size_t(w) + size_t(x0)) * 4, plane + (size_t(y0) * size_t(w) + size_t(x1)) * 4,+ plane + (size_t(y1) * size_t(w) + size_t(x0)) * 4, plane + (size_t(y1) * size_t(w) + size_t(x1)) * 4};+ const float wt[4] = {(1 - ax) * (1 - ay), ax * (1 - ay), (1 - ax) * ay, ax * ay};+ float r = 0, g = 0, b = 0, a = 0;+ for (int k = 0; k < 4; ++k) {+ const float wa = wt[k] * float(p[k][3]);+ r += wa * float(p[k][0]);+ g += wa * float(p[k][1]);+ b += wa * float(p[k][2]);+ a += wa;+ }+ if (a <= 0.0f) {+ std::memcpy(out, p[0], 3);+ out[3] = 0;+ return;+ }+ const float inv = 1.0f / a;+ out[0] = uint8_t(std::lround(std::clamp(r * inv, 0.0f, 255.0f)));+ out[1] = uint8_t(std::lround(std::clamp(g * inv, 0.0f, 255.0f)));+ out[2] = uint8_t(std::lround(std::clamp(b * inv, 0.0f, 255.0f)));+ out[3] = uint8_t(std::lround(std::clamp(a, 0.0f, 255.0f)));+}++// Fills `planes` (each w * h RGBA8, already holding the blank value) from the sources: every texel inside a+// triangle of `uvs` asks lookup(tri, bary, source, sourceTri, sourceBary) where to read. `ring` gets 1 for+// filled texels. Returns the texels inside islands; `missed` those whose lookup failed.+template <class Lookup>+size_t fillPlanes(std::vector<std::vector<uint8_t>*>& planes, int w, int h, const std::vector<glm::vec2>& uvs,+ size_t triangles, const std::vector<Source>& sources, std::vector<uint8_t>& ring, size_t& missed,+ Lookup&& lookup) {+ std::atomic<size_t> inside{0}, lost{0};+ ring.assign(size_t(w) * size_t(h), 0);+ parallelFor(triangles, [&](size_t b, size_t e) {+ size_t in = 0, miss = 0;+ for (size_t t = b; t < e; ++t) {+ rasterizeUvTriangle(uvs[t * 3], uvs[t * 3 + 1], uvs[t * 3 + 2], w, h, [&](int x, int y, float b0, float b1, float b2) {+ ++in;+ uint32_t s = 0, st = 0;+ glm::vec3 sb;+ if (!lookup(uint32_t(t), glm::vec3(b0, b1, b2), s, st, sb)) {+ ++miss;+ return;+ }+ const size_t i = size_t(y) * size_t(w) + size_t(x);+ const Source& src = sources[s];+ if (src.tex) {+ const glm::vec2 uv = (*src.uvs)[size_t(st) * 3] * sb.x + (*src.uvs)[size_t(st) * 3 + 1] * sb.y ++ (*src.uvs)[size_t(st) * 3 + 2] * sb.z;+ for (size_t k = 0; k < planes.size(); ++k)+ sampleRgba(src.planes[k]->data(), src.tex->width, src.tex->height, uv, &(*planes[k])[i * 4]);+ } else {+ for (size_t k = 0; k < planes.size(); ++k) std::memset(&(*planes[k])[i * 4], 255, 4);+ }+ ring[i] = 1;+ });+ }+ inside += in;+ lost += miss;+ }, 2000);+ missed = lost;+ return inside;+}++// Pads `rings` texels around the filled ones: ring by ring, each empty texel next to filled ones takes their+// alpha-weighted average (as the baker pads its maps).+void padPlanes(std::vector<std::vector<uint8_t>*>& planes, int w, int h, std::vector<uint8_t>& ring, int rings) {+ std::vector<uint8_t> next(ring.size(), 0);+ for (int k = 2; k <= rings + 1; ++k) {+ std::atomic<size_t> added{0};+ parallelFor(size_t(h), [&](size_t y0, size_t y1) {+ size_t n = 0;+ for (int y = int(y0); y < int(y1); ++y)+ for (int x = 0; x < w; ++x) {+ const size_t i = size_t(y) * size_t(w) + size_t(x);+ if (ring[i]) continue;+ int nb[8], cnt = 0;+ for (int dy = -1; dy <= 1; ++dy)+ for (int dx = -1; dx <= 1; ++dx) {+ const int nx = x + dx, ny = y + dy;+ if ((dx | dy) == 0 || nx < 0 || ny < 0 || nx >= w || ny >= h) continue;+ const size_t j = size_t(ny) * size_t(w) + size_t(nx);+ if (ring[j] && ring[j] < k) nb[cnt++] = int(j);+ }+ if (!cnt) continue;+ for (auto* plane : planes) {+ float r = 0, g = 0, b = 0, a = 0;+ for (int q = 0; q < cnt; ++q) {+ const uint8_t* p = &(*plane)[size_t(nb[q]) * 4];+ const float pa = float(p[3]) + 1e-3f; // keeps the colour of fully transparent texels+ r += pa * float(p[0]);+ g += pa * float(p[1]);+ b += pa * float(p[2]);+ a += pa;+ }+ uint8_t* o = &(*plane)[i * 4];+ o[0] = uint8_t(std::lround(r / a));+ o[1] = uint8_t(std::lround(g / a));+ o[2] = uint8_t(std::lround(b / a));+ o[3] = uint8_t(std::lround(std::clamp(a / float(cnt), 0.0f, 255.0f)));+ }+ next[i] = uint8_t(k);+ ++n;+ }+ added += n;+ }, 64);+ if (!added) break;+ parallelFor(ring.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i)+ if (next[i]) ring[i] = next[i], next[i] = 0;+ });+ }+}++// A texture of `like`'s size and layer settings, every plane blank (Base white, layers transparent).+std::shared_ptr<PaintTexture> blankLike(const PaintTexture& like, bool withLayers) {+ auto t = makeTexture(like.width, like.height);+ if (withLayers && !like.layers.empty()) {+ t->base.assign(t->texelCount() * 4, 255);+ t->layers = like.layers;+ for (auto& l : t->layers) l.rgba.assign(t->texelCount() * 4, 0);+ t->activeLayer = like.activeLayer;+ }+ return t;+}++// The destination planes of `t` and the matching source planes of `src` (Base / pixels first, then layers).+void planesOf(PaintTexture& t, std::vector<std::vector<uint8_t>*>& out) {+ out.clear();+ if (t.layers.empty()) {+ out.push_back(&t.pixels);+ return;+ }+ out.push_back(&t.base);+ for (auto& l : t.layers) out.push_back(&l.rgba);+}+void planesOf(const PaintTexture& t, bool withLayers, std::vector<const std::vector<uint8_t>*>& out) {+ out.clear();+ if (!withLayers || t.layers.empty() || t.base.size() != t.pixels.size()) {+ out.push_back(&t.pixels);+ return;+ }+ out.push_back(&t.base);+ for (const auto& l : t.layers) out.push_back(&l.rgba);+}++bool layersUsable(const PaintTexture& t) {+ if (t.layers.empty() || t.base.size() != t.pixels.size()) return false;+ for (const auto& l : t.layers)+ if (l.rgba.size() != t.pixels.size()) return false;+ return true;+}++void finish(PaintTexture& t) {+ if (!t.layers.empty()) compositeTextureAll(t);+ t.markAllDirty();+}++} // namespace++std::shared_ptr<PaintTexture> retargetTexture(const Mesh& mesh, const std::vector<glm::vec2>& newUvs,+ TextureTransferStats* stats) {+ if (!hasTexture(mesh) || newUvs.size() != mesh.triangleCount() * 3) return nullptr;+ const auto start = Clock::now();+ const PaintTexture& old = *mesh.texture;+ const bool layers = layersUsable(old);+ auto tex = blankLike(old, layers);+ std::vector<std::vector<uint8_t>*> dst;+ planesOf(*tex, dst);+ std::vector<Source> sources(1);+ sources[0].tex = &old;+ sources[0].uvs = &mesh.uvs;+ planesOf(old, layers, sources[0].planes);+ std::vector<uint8_t> ring;+ size_t missed = 0;+ const size_t texels = fillPlanes(dst, tex->width, tex->height, newUvs, mesh.triangleCount(), sources, ring, missed,+ [](uint32_t t, const glm::vec3& b, uint32_t& s, uint32_t& st, glm::vec3& sb) {+ s = 0, st = t, sb = b;+ return true;+ });+ padPlanes(dst, tex->width, tex->height, ring, kTransferPadding);+ finish(*tex);+ if (stats) {+ stats->texels = texels;+ stats->missed = missed;+ stats->transferSeconds = secondsSince(start);+ }+ return tex;+}++std::string setUvsKeepingTexture(Mesh& mesh, std::vector<glm::vec2> uvs, bool keep) {+ std::string note;+ if (hasTexture(mesh)) {+ TextureTransferStats st;+ std::shared_ptr<PaintTexture> moved = keep ? retargetTexture(mesh, uvs, &st) : nullptr;+ if (moved) {+ const size_t layers = moved->layers.size();+ mesh.texture = std::move(moved);+ char buf[160];+ std::snprintf(buf, sizeof buf, " (the texture%s moved onto the new UVs in %.1f s)",+ layers ? (" and its " + std::to_string(layers) + " layer" + (layers > 1 ? "s" : "")).c_str() : "",+ st.transferSeconds);+ note = buf;+ } else {+ note = " (the texture was painted on the old UVs, so it no longer lines up; undo to get them back)";+ }+ }+ mesh.uvs = std::move(uvs);+ mesh.facesDirty = true;+ return note;+}++bool transferTextureFromSurface(const Mesh& source, Mesh& target, std::string& error, TextureTransferStats* stats) {+ if (!hasTexture(source)) {+ error = "The source has no texture";+ return false;+ }+ if (target.uvs.size() != target.triangleCount() * 3 || target.triangleCount() == 0) {+ error = "The new mesh has no UVs";+ return false;+ }+ const auto start = Clock::now();+ const PaintTexture& old = *source.texture;+ const bool layers = layersUsable(old);+ auto tex = blankLike(old, layers);+ std::vector<std::vector<uint8_t>*> dst;+ planesOf(*tex, dst);+ std::vector<Source> sources(1);+ sources[0].tex = &old;+ sources[0].uvs = &source.uvs;+ planesOf(old, layers, sources[0].planes);++ TriangleBVH bvh;+ bvh.build(source.positions, source.triangles);+ // How far each new vertex is from the old surface bounds every texel's search: a point of a triangle is+ // within (corner distance + edge length) of the old surface, so the query stays local.+ const float inf = std::numeric_limits<float>::max();+ std::vector<float> vd(target.vertexCount(), inf);+ parallelFor(target.vertexCount(), [&](size_t b, size_t e) {+ for (size_t v = b; v < e; ++v) {+ SurfaceHit h;+ if (bvh.closestPoint(target.positions[v], inf, h)) vd[v] = h.distance;+ }+ }, 4096);+ const size_t nt = target.triangleCount();+ std::vector<float> reach(nt, inf);+ parallelFor(nt, [&](size_t b, size_t e) {+ for (size_t t = b; t < e; ++t) {+ const glm::uvec3 tv = target.triangles[t];+ const glm::vec3 &p0 = target.positions[tv.x], &p1 = target.positions[tv.y], &p2 = target.positions[tv.z];+ const float edge = std::max({glm::length(p1 - p0), glm::length(p2 - p1), glm::length(p0 - p2)});+ const float d = std::max({vd[tv.x], vd[tv.y], vd[tv.z]});+ if (d < inf) reach[t] = d + edge * 1.01f + 1e-6f;+ }+ });+ std::vector<uint8_t> ring;+ size_t missed = 0;+ const size_t texels = fillPlanes(dst, tex->width, tex->height, target.uvs, nt, sources, ring, missed,+ [&](uint32_t t, const glm::vec3& b, uint32_t& s, uint32_t& st, glm::vec3& sb) {+ const glm::uvec3 tv = target.triangles[t];+ const glm::vec3 p = target.positions[tv.x] * b.x + target.positions[tv.y] * b.y ++ target.positions[tv.z] * b.z;+ SurfaceHit h;+ if (!bvh.closestPoint(p, reach[t], h) && !bvh.closestPoint(p, inf, h)) return false;+ s = 0, st = h.prim, sb = h.bary;+ return true;+ });+ padPlanes(dst, tex->width, tex->height, ring, kTransferPadding);+ finish(*tex);+ target.texture = std::move(tex);+ target.paintToTexture = source.paintToTexture;+ target.facesDirty = true;+ if (stats) {+ stats->texels = texels;+ stats->missed = missed;+ stats->transferSeconds = secondsSince(start);+ }+ return true;+}++bool carryTexture(const Mesh& source, Mesh& target, std::string& error, TextureTransferStats* stats,+ const AutoUvProgress& progress) {+ if (!hasTexture(source)) return true;+ TextureTransferStats local;+ TextureTransferStats& st = stats ? *stats : local;+ const auto start = Clock::now();+ AutoUvResult uv;+ const int res = std::max(source.texture->width, source.texture->height);+ if (!computeAutoUv(target.positions, target.triangles, res, uv, error, progress)) return false;+ st.uvSeconds = secondsSince(start);+ st.charts = uv.charts;+ target.uvs = std::move(uv.uvs);+ if (!transferTextureFromSurface(source, target, error, &st)) {+ target.uvs.clear();+ target.texture.reset();+ return false;+ }+ if (progress) progress(1.0f);+ return true;+}++std::string carryTextureNote(const Mesh& source, Mesh& target, bool keep, const AutoUvProgress& progress) {+ if (!hasTexture(source)) return {};+ if (!keep) return "; the texture was dropped (keep_texture=false)";+ std::string err;+ TextureTransferStats st;+ if (!carryTexture(source, target, err, &st, progress))+ return "; the texture could not be kept (" + err + "): undo, export it, or bake it to polypaint first";+ char buf[160];+ std::snprintf(buf, sizeof buf, "; texture kept (Auto UV, %d islands, %.1f s)", st.charts, st.uvSeconds + st.transferSeconds);+ return buf;+}++bool carryMergedTextures(const std::vector<const Mesh*>& parts, Mesh& merged, std::string& error,+ TextureTransferStats* stats) {+ const PaintTexture* biggest = nullptr;+ bool toTexture = false;+ size_t total = 0;+ for (const Mesh* m : parts) {+ total += m->triangleCount();+ if (!hasTexture(*m)) continue;+ if (!biggest || m->texture->width > biggest->width) biggest = m->texture.get();+ toTexture = toTexture || m->paintToTexture;+ }+ if (!biggest) return true;+ if (total != merged.triangleCount()) {+ error = "The merged mesh doesn't match its parts";+ return false;+ }+ TextureTransferStats local;+ TextureTransferStats& st = stats ? *stats : local;+ const auto start = Clock::now();+ AutoUvResult uv;+ if (!computeAutoUv(merged.positions, merged.triangles, biggest->width, uv, error)) return false;+ st.uvSeconds = secondsSince(start);+ st.charts = uv.charts;+ const auto t0 = Clock::now();+ merged.uvs = std::move(uv.uvs);+ auto tex = makeTexture(biggest->width, biggest->height);+ std::vector<std::vector<uint8_t>*> dst{&tex->pixels};+ std::vector<Source> sources(parts.size());+ std::vector<uint32_t> first(parts.size() + 1, 0); // first merged triangle of each part+ for (size_t i = 0; i < parts.size(); ++i) {+ first[i + 1] = first[i] + uint32_t(parts[i]->triangleCount());+ if (!hasTexture(*parts[i])) continue;+ sources[i].tex = parts[i]->texture.get();+ sources[i].uvs = &parts[i]->uvs;+ sources[i].planes = {&parts[i]->texture->pixels};+ }+ std::vector<uint8_t> ring;+ size_t missed = 0;+ st.texels = fillPlanes(dst, tex->width, tex->height, merged.uvs, merged.triangleCount(), sources, ring, missed,+ [&](uint32_t t, const glm::vec3& b, uint32_t& s, uint32_t& lt, glm::vec3& sb) {+ s = uint32_t(std::upper_bound(first.begin(), first.end(), t) - first.begin()) - 1;+ lt = t - first[s];+ sb = b;+ return true;+ });+ st.missed = missed;+ padPlanes(dst, tex->width, tex->height, ring, kTransferPadding);+ finish(*tex);+ merged.texture = std::move(tex);+ merged.paintToTexture = toTexture;+ merged.facesDirty = true;+ st.transferSeconds = secondsSince(t0);+ return true;+}++std::string carryMergedTexturesNote(const std::vector<const Mesh*>& parts, Mesh& merged, bool keep) {+ size_t textured = 0;+ for (const Mesh* m : parts) textured += hasTexture(*m) ? 1 : 0;+ if (!textured) return {};+ const std::string what = textured > 1 ? "textures" : "texture";+ if (!keep) {+ merged.texture.reset();+ merged.paintToTexture = false;+ return "; the " + what + " were dropped (keep_texture=false)";+ }+ std::string err;+ TextureTransferStats st;+ if (!carryMergedTextures(parts, merged, err, &st)) {+ merged.texture.reset();+ merged.paintToTexture = false;+ return "; the " + what + " could not be kept (" + err + ")";+ }+ char buf[160];+ std::snprintf(buf, sizeof buf, "; %s kept in one texture (Auto UV, %d islands, %.1f s)", what.c_str(), st.charts,+ st.uvSeconds + st.transferSeconds);+ return buf;+}++} // namespace sfdiff --git a/src/core/TextureTransfer.h b/src/core/TextureTransfer.hnew file mode 100644index 00000000..4ba667d0--- /dev/null+++ b/src/core/TextureTransfer.h@@ -0,0 +1,69 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Texture transfer: keeps a SubTool's painted texture (core/Texture.h) when its UVs or its surface are rebuilt.+//+// - New UVs on the same triangles (Auto UV on a textured SubTool): every texel of the new layout is the same+// surface point as before (same triangle, same barycentrics), so it reads the old texture at the old UVs.+// Every layer is transferred, with its settings; the result is exact up to resampling (bilinear).+// - A new surface (voxel remesh, QRemesh): the result gets Auto UVs, and every texel takes the colour of the+// closest point of the old surface. Every layer is transferred too.+// - Merged SubTools: the merged mesh keeps each part's triangles in order, so each texel reads its part's+// texture exactly (layers are flattened, as the parts' stacks differ).+//+// Texels are filled triangle by triangle on all threads; then the texels around each UV island are padded+// ring by ring from the island's edge (as baking does), so seams don't show. Texels no island reaches stay+// white (transparent on layers).+#pragma once++#include "core/AutoUv.h"+#include "core/Mesh.h"+#include "core/Texture.h"++#include <memory>+#include <string>+#include <vector>++namespace sf {++constexpr int kTransferPadding = 8; // texels padded around the new islands++struct TextureTransferStats {+ size_t texels = 0; // texels inside the new UV islands+ size_t missed = 0; // of those, texels that found no source (left blank, then padded)+ int charts = 0; // UV islands made by Auto UV (0 when the UVs were given)+ double uvSeconds = 0, transferSeconds = 0;+};++// The texture of `mesh` laid out again on `newUvs` (per triangle corner, same triangles as `mesh`). Null when+// the mesh has no texture or `newUvs` doesn't fit.+std::shared_ptr<PaintTexture> retargetTexture(const Mesh& mesh, const std::vector<glm::vec2>& newUvs,+ TextureTransferStats* stats = nullptr);++// Gives `mesh` new UVs (Auto UV), moving its texture and layers onto them (retargetTexture) unless `keep` is+// false. Returns the status text to add (" (texture moved onto the new UVs)"), empty without a texture.+std::string setUvsKeepingTexture(Mesh& mesh, std::vector<glm::vec2> uvs, bool keep = true);++// Gives `target` (which must have UVs) a texture of `source`'s size whose texels take the colour of the closest+// point on `source`'s surface (all of its layers). False with `error` when `source` has no texture.+bool transferTextureFromSurface(const Mesh& source, Mesh& target, std::string& error,+ TextureTransferStats* stats = nullptr);++// After a rebuild of `source` into `target` (voxel remesh, QRemesh): Auto UVs for `target` (packed for the+// texture's size) and the texture projected from `source`. Does nothing (true) when `source` has no texture.+// False with `error` on failure or cancel (`target` keeps no UVs or texture then).+bool carryTexture(const Mesh& source, Mesh& target, std::string& error, TextureTransferStats* stats = nullptr,+ const AutoUvProgress& progress = {});++// The status text for a rebuild that had to deal with a texture: what carryTexture did (", texture kept: ..."),+// or that the texture was dropped. Empty when `source` has no texture. Runs carryTexture when `keep`.+std::string carryTextureNote(const Mesh& source, Mesh& target, bool keep, const AutoUvProgress& progress = {});++// After mergeMeshes(parts) into `merged` (same triangles, in order): Auto UVs for `merged` and one texture+// holding each textured part's paint (composited). Does nothing (true) when no part has a texture.+bool carryMergedTextures(const std::vector<const Mesh*>& parts, Mesh& merged, std::string& error,+ TextureTransferStats* stats = nullptr);+// The same as status text (", textures kept: ..." or that they were dropped); empty when no part has a texture.+std::string carryMergedTexturesNote(const std::vector<const Mesh*>& parts, Mesh& merged, bool keep);++} // namespace sfdiff --git a/tests/test_texture_transfer.cpp b/tests/test_texture_transfer.cppnew file mode 100644index 00000000..df6133d2--- /dev/null+++ b/tests/test_texture_transfer.cpp@@ -0,0 +1,342 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Texture transfer (core/TextureTransfer.h): Auto UV on a painted SubTool moves the paint (and its layers)+// onto the new UVs as one undo step; voxel remesh, QRemesh and merging SubTools keep the texture; the cost at+// 4K on a million triangles.+#include "TestHarness.h"++#include "core/AutoUv.h"+#include "core/Commands.h"+#include "core/Polypaint.h"+#include "core/Primitives.h"+#include "core/SubTools.h"+#include "core/Texture.h"+#include "core/TextureTransfer.h"++#include <algorithm>+#include <chrono>+#include <cmath>+#include <cstdio>+#include <random>++using namespace sf;++namespace {++// The test pattern: a smooth colour field over space (display values 0..1).+glm::vec3 pattern(const glm::vec3& p) {+ return glm::vec3(0.5f + 0.4f * std::sin(3.0f * p.x + 0.5f), 0.5f + 0.4f * std::cos(2.5f * p.y),+ 0.5f + 0.4f * std::sin(2.0f * p.z + 1.0f));+}+float toLinear(float c) { return c <= 0.04045f ? c / 12.92f : std::pow((c + 0.055f) / 1.055f, 2.4f); }+glm::vec3 patternLinear(const glm::vec3& p) {+ const glm::vec3 c = pattern(p);+ return {toLinear(c.x), toLinear(c.y), toLinear(c.z)};+}++uint8_t byte(float x) { return uint8_t(std::lround(std::clamp(x, 0.0f, 1.0f) * 255.0f)); }++// Paints the pattern into `plane` (RGBA8 of the mesh's texture), alpha `alpha`, gutters included.+void paintPattern(Mesh& m, std::vector<uint8_t>& plane, uint8_t alpha, float shift = 0.0f) {+ PaintTexture& tex = *m.texture;+ bakeTexels(m, tex, [&](uint32_t t, float b0, float b1, float b2, int x, int y) {+ const glm::uvec3 tv = m.triangles[t];+ const glm::vec3 p = m.positions[tv.x] * b0 + m.positions[tv.y] * b1 + m.positions[tv.z] * b2;+ const glm::vec3 c = pattern(p + glm::vec3(shift));+ uint8_t* px = &plane[(size_t(y) * size_t(tex.width) + size_t(x)) * 4];+ px[0] = byte(c.x), px[1] = byte(c.y), px[2] = byte(c.z), px[3] = alpha;+ }, false);+}++// A textured sphere (Auto UV packed for `packFor`, a size x size texture) painted with the pattern.+Document paintedSphere(int subdivisions, int size, int packFor) {+ Document doc = makeDoc(makeIcosphere(subdivisions));+ CommandRegistry reg;+ CHECK(reg.execute(doc, "uv_auto", {{"resolution", double(packFor)}}).ok);+ CHECK(reg.execute(doc, "texture_create", {{"size", std::to_string(size)}}).ok);+ paintPattern(doc.mesh, mutableTexture(doc.mesh).pixels, 255);+ doc.undo.clear();+ return doc;+}++// Random surface points (triangle + barycentrics).+struct SurfacePoint {+ uint32_t tri;+ glm::vec3 bary;+};+std::vector<SurfacePoint> randomPoints(const Mesh& m, int n, uint32_t seed = 7) {+ std::mt19937 rng(seed);+ std::uniform_real_distribution<float> u(0.0f, 1.0f);+ std::vector<SurfacePoint> out;+ for (int i = 0; i < n; ++i) {+ float a = u(rng), b = u(rng);+ if (a + b > 1.0f) a = 1.0f - a, b = 1.0f - b;+ out.push_back({uint32_t(rng() % m.triangleCount()), glm::vec3(1.0f - a - b, a, b)});+ }+ return out;+}+glm::vec3 pointOf(const Mesh& m, const SurfacePoint& s) {+ const glm::uvec3 tv = m.triangles[s.tri];+ return m.positions[tv.x] * s.bary.x + m.positions[tv.y] * s.bary.y + m.positions[tv.z] * s.bary.z;+}++struct ErrorStats {+ float mean = 0, p99 = 0, max = 0;+};+ErrorStats errorStats(std::vector<float> e) {+ ErrorStats s;+ if (e.empty()) return s;+ std::sort(e.begin(), e.end());+ for (float x : e) s.mean += x;+ s.mean /= float(e.size());+ s.p99 = e[size_t(double(e.size() - 1) * 0.99)];+ s.max = e.back();+ return s;+}+float maxDiff(const glm::vec3& a, const glm::vec3& b) {+ const glm::vec3 d = glm::abs(a - b);+ return std::max({d.x, d.y, d.z});+}++// How far the texture of `m` strays from the pattern at random surface points (linear RGB).+ErrorStats patternError(const Mesh& m, int n = 4000) {+ std::vector<float> e;+ for (const SurfacePoint& s : randomPoints(m, n)) {+ const glm::vec3 p = pointOf(m, s);+ e.push_back(maxDiff(sampleTextureAt(m, s.tri, p), patternLinear(p)));+ }+ return errorStats(e);+}++} // namespace++TEST(texture_transfer_auto_uv_keeps_the_paint) {+ Document doc = paintedSphere(4, 1024, 512);+ const std::vector<glm::vec2> oldUvs = doc.mesh.uvs;+ const auto oldTexture = doc.mesh.texture;+ const ErrorStats before = patternError(doc.mesh);+ // Samples of the texture before, at fixed surface points.+ const auto pts = randomPoints(doc.mesh, 4000, 11);+ std::vector<glm::vec3> was;+ for (const auto& s : pts) was.push_back(sampleTextureAt(doc.mesh, s.tri, pointOf(doc.mesh, s)));++ CommandRegistry reg;+ const CommandResult r = reg.execute(doc, "uv_auto", {{"resolution", 2048.0}}); // packed differently+ CHECK(r.ok);+ CHECK(r.message.find("moved onto the new UVs") != std::string::npos);+ CHECK(doc.mesh.uvs != oldUvs);+ CHECK(hasTexture(doc.mesh));+ CHECK(doc.mesh.texture != oldTexture);+ std::vector<float> e;+ for (size_t i = 0; i < pts.size(); ++i) e.push_back(maxDiff(sampleTextureAt(doc.mesh, pts[i].tri, pointOf(doc.mesh, pts[i])), was[i]));+ const ErrorStats moved = errorStats(e), after = patternError(doc.mesh);+ std::printf(" auto uv transfer: vs before mean %.4f p99 %.4f max %.4f; vs pattern %.4f -> %.4f (p99 %.4f -> %.4f)\n",+ moved.mean, moved.p99, moved.max, before.mean, after.mean, before.p99, after.p99);+ CHECK(moved.mean < 0.01f);+ CHECK(moved.p99 < 0.05f);+ CHECK(after.mean < before.mean + 0.01f);++ // Without the transfer the paint is scrambled (the old behaviour), which the check above would catch.+ {+ Document copy = paintedSphere(4, 1024, 512);+ CHECK(reg.execute(copy, "uv_auto", {{"resolution", 2048.0}, {"keep_texture", false}}).ok);+ CHECK(patternError(copy.mesh).mean > 0.05f);+ }++ // One undo step brings back the old UVs and the old texture; redo the new ones.+ CHECK(doc.undo.undoCount() == 1);+ const auto newTexture = doc.mesh.texture;+ doc.undo.undo(doc.mesh, doc.bvh);+ CHECK(doc.mesh.uvs == oldUvs);+ CHECK(doc.mesh.texture == oldTexture);+ doc.undo.redo(doc.mesh, doc.bvh);+ CHECK(doc.mesh.texture == newTexture);+}++TEST(texture_transfer_auto_uv_keeps_layers) {+ Document doc = paintedSphere(3, 1024, 512);+ PaintTexture& t = mutableTexture(doc.mesh);+ const int layer = addTextureLayer(t, "Dirt");+ t.layers[size_t(layer)].opacity = 0.5f;+ t.layers[size_t(layer)].blend = BlendMode::Multiply;+ paintPattern(doc.mesh, t.layers[size_t(layer)].rgba, 200, 0.7f);+ compositeTextureAll(t);+ const auto pts = randomPoints(doc.mesh, 3000, 5);+ std::vector<glm::vec3> was;+ for (const auto& s : pts) was.push_back(sampleTextureAt(doc.mesh, s.tri, pointOf(doc.mesh, s)));+ const uint32_t id = t.layers[0].id;++ CommandRegistry reg;+ const CommandResult r = reg.execute(doc, "uv_auto", {{"resolution", 1024.0}});+ CHECK(r.ok);+ CHECK(r.message.find("1 layer") != std::string::npos);+ const PaintTexture& n = *doc.mesh.texture;+ CHECK(n.layers.size() == 1);+ CHECK(n.layers[0].name == "Dirt" && n.layers[0].id == id);+ CHECK(n.layers[0].opacity == 0.5f && n.layers[0].blend == BlendMode::Multiply);+ CHECK(n.base.size() == n.pixels.size());+ std::vector<float> e;+ for (size_t i = 0; i < pts.size(); ++i) e.push_back(maxDiff(sampleTextureAt(doc.mesh, pts[i].tri, pointOf(doc.mesh, pts[i])), was[i]));+ const ErrorStats s = errorStats(e);+ std::printf(" auto uv transfer with a layer: mean %.4f p99 %.4f\n", s.mean, s.p99);+ CHECK(s.mean < 0.015f);+ CHECK(s.p99 < 0.08f);+}++TEST(texture_transfer_remesh_and_qremesh_keep_the_texture) {+ CommandRegistry reg;+ for (const char* cmd : {"remesh", "qremesh"}) {+ Document doc = paintedSphere(4, 1024, 1024);+ const ErrorStats before = patternError(doc.mesh);+ const auto oldTexture = doc.mesh.texture;+ const size_t oldTris = doc.mesh.triangleCount();+ Args a = std::string(cmd) == "remesh" ? Args{{"resolution", 96.0}} : Args{{"target", 2000.0}};+ const CommandResult r = reg.execute(doc, cmd, a);+ CHECK(r.ok);+ CHECK(r.message.find("texture kept") != std::string::npos);+ CHECK(doc.mesh.triangleCount() != oldTris);+ CHECK(hasTexture(doc.mesh));+ CHECK(doc.mesh.texture->width == 1024);+ CHECK(doc.mesh.paintToTexture);+ const ErrorStats after = patternError(doc.mesh);+ std::printf(" %s keeps the texture: pattern error mean %.4f -> %.4f, p99 %.4f -> %.4f (%s)\n", cmd, before.mean,+ after.mean, before.p99, after.p99, r.message.c_str());+ CHECK(after.mean < 0.02f);+ CHECK(after.p99 < 0.08f);+ // One undo step: the old mesh with its UVs and texture.+ CHECK(doc.undo.undoCount() == 1);+ doc.undo.undo(doc.mesh, doc.bvh);+ CHECK(doc.mesh.triangleCount() == oldTris);+ CHECK(doc.mesh.texture == oldTexture);++ // keep_texture=false drops it, and says so.+ a["keep_texture"] = false;+ const CommandResult d = reg.execute(doc, cmd, a);+ CHECK(d.ok);+ CHECK(d.message.find("texture was dropped") != std::string::npos);+ CHECK(!hasTexture(doc.mesh));+ }+}++TEST(texture_transfer_decimate_keeps_the_texture) {+ // Decimate keeps the UVs; vertices on UV seams stay put so the corners across a seam keep their island's UVs.+ Document doc = paintedSphere(4, 1024, 1024);+ const size_t before = doc.mesh.triangleCount();+ CommandRegistry reg;+ CHECK(reg.execute(doc, "decimate", {{"ratio", 0.3}}).ok);+ CHECK(hasTexture(doc.mesh));+ CHECK(doc.mesh.triangleCount() <= before * 35 / 100);+ const ErrorStats after = patternError(doc.mesh);+ std::printf(" decimate keeps the texture: %zu -> %zu tris, pattern error mean %.4f p99 %.4f max %.4f\n", before,+ doc.mesh.triangleCount(), after.mean, after.p99, after.max);+ CHECK(after.mean < 0.01f);+ CHECK(after.p99 < 0.03f);+}++TEST(texture_transfer_merge_keeps_both_textures) {+ Document doc = paintedSphere(3, 1024, 512);+ Mesh second = makeIcosphere(3, 0.5f);+ for (auto& p : second.positions) p += glm::vec3(2.0f, 0.0f, 0.0f);+ second.recomputeAllNormals();+ {+ AutoUvResult uv;+ std::string err;+ CHECK(computeAutoUv(second.positions, second.triangles, 512, uv, err));+ second.uvs = uv.uvs;+ second.texture = makeTexture(2048, 2048); // the bigger texture sets the merged size+ second.paintToTexture = true;+ paintPattern(second, second.texture->pixels, 255);+ }+ Mesh plain = makeIcosphere(2, 0.3f); // a part without texture comes out white+ for (auto& p : plain.positions) p += glm::vec3(-2.0f, 0.0f, 0.0f);+ doc.addSubtool(second, "Second", false);+ doc.addSubtool(plain, "Plain", false);+ CommandRegistry reg;+ const CommandResult r = reg.execute(doc, "subtool_merge_visible", {});+ CHECK(r.ok);+ CHECK(r.message.find("textures kept") != std::string::npos);+ CHECK(doc.subtoolCount() == 1);+ CHECK(hasTexture(doc.mesh));+ CHECK(doc.mesh.texture->width == 2048);+ // Points on the two painted spheres follow the pattern; the plain one is white.+ std::vector<float> painted;+ float plainError = 0.0f;+ for (const auto& s : randomPoints(doc.mesh, 4000, 3)) {+ const glm::vec3 p = pointOf(doc.mesh, s), c = sampleTextureAt(doc.mesh, s.tri, p);+ if (p.x < -1.0f) plainError = std::max(plainError, maxDiff(c, glm::vec3(1.0f)));+ else painted.push_back(maxDiff(c, patternLinear(p)));+ }+ const ErrorStats e = errorStats(painted);+ std::printf(" merged textures: pattern error mean %.4f p99 %.4f, plain part %.4f\n", e.mean, e.p99, plainError);+ CHECK(e.mean < 0.02f);+ CHECK(e.p99 < 0.08f);+ CHECK(plainError < 0.01f);+}++TEST(texture_transfer_pads_the_new_islands) {+ // Texels just outside the new islands carry the island's colour (no white seams once filtered).+ Document doc = paintedSphere(3, 1024, 512);+ CommandRegistry reg;+ CHECK(reg.execute(doc, "uv_auto", {{"resolution", 1024.0}}).ok);+ const PaintTexture& t = *doc.mesh.texture;+ ensureCoverage(doc.mesh, const_cast<PaintTexture&>(t), true);+ size_t border = 0, white = 0;+ for (int y = 1; y + 1 < t.height; ++y)+ for (int x = 1; x + 1 < t.width; ++x) {+ if (t.covered(x, y)) continue;+ bool next = false;+ for (int d = 0; d < 4 && !next; ++d) next = t.covered(x + (d == 0) - (d == 1), y + (d == 2) - (d == 3));+ if (!next) continue;+ ++border;+ const uint8_t* p = &t.pixels[(size_t(y) * size_t(t.width) + size_t(x)) * 4];+ if (p[0] == 255 && p[1] == 255 && p[2] == 255) ++white;+ }+ CHECK(border > 0);+ CHECK(white * 100 < border); // the pattern never reaches pure white+}++TEST(texture_transfer_speed_at_4k_on_a_million_triangles) {+ using Clock = std::chrono::steady_clock;+ auto ms = [](Clock::time_point a, Clock::time_point b) { return std::chrono::duration<double, std::milli>(b - a).count(); };+ // A 1M-triangle grid with planar UVs and a 4K texture with a layer; new UVs mirrored and rotated (a different+ // layout of the same triangles, as Auto UV gives).+ Mesh m = makePlane(724); // 1.05M triangles+ 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::clamp(glm::vec2(p.x, p.z) * 0.5f + 0.5f, 0.0f, 1.0f);+ }+ m.texture = makeTexture(4096, 4096);+ paintPattern(m, m.texture->pixels, 255);+ addTextureLayer(*m.texture, "Layer 1");+ std::vector<glm::vec2> uvs(m.uvs.size());+ for (size_t i = 0; i < uvs.size(); ++i) uvs[i] = glm::vec2(m.uvs[i].y, 1.0f - m.uvs[i].x);+ const auto t0 = Clock::now();+ TextureTransferStats st;+ const auto moved = retargetTexture(m, uvs, &st);+ const auto t1 = Clock::now();+ CHECK(moved != nullptr);+ CHECK(st.texels > 4096u * 4000u);++ // Surface transfer: the same texture onto a 250k-triangle grid hovering just above the source.+ Mesh target = makePlane(354);+ for (auto& p : target.positions) p.y += 0.001f;+ target.uvs.resize(target.triangleCount() * 3);+ for (size_t t = 0; t < target.triangleCount(); ++t)+ for (int c = 0; c < 3; ++c) {+ const glm::vec3 p = target.positions[target.triangles[t][c]];+ target.uvs[t * 3 + size_t(c)] = glm::clamp(glm::vec2(p.z, p.x) * 0.5f + 0.5f, 0.0f, 1.0f);+ }+ std::string err;+ TextureTransferStats ss;+ const auto t2 = Clock::now();+ CHECK(transferTextureFromSurface(m, target, err, &ss));+ const auto t3 = Clock::now();+ std::printf(" texture transfer at 4K: new UVs on %zu tris %.0f ms (2 planes); from the surface of %zu tris onto %zu tris "+ "%.0f ms (%zu texels)\n",+ m.triangleCount(), ms(t0, t1), m.triangleCount(), target.triangleCount(), ms(t2, t3), ss.texels);+ CHECK(ms(t0, t1) < 5000.0);+ CHECK(ms(t2, t3) < 20000.0);+}