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
Voxel Remesh 3-4x faster, same output, always in the background
islandmedc5250ff6f5ef
diff --git a/changes/fix-0.10.11-voxel.md b/changes/fix-0.10.11-voxel.mdnew file mode 100644index 00000000..26436a62--- /dev/null+++ b/changes/fix-0.10.11-voxel.md@@ -0,0 +1,20 @@+---+whats_new: **Faster Voxel Remesh**: **Tool > Remesh > Voxel Remesh** is about 3-4 times faster (a 500,000-triangle+ sculpt at the default resolution in about a third of a second) and runs in the background with a progress bar and+ Cancel, so the app never freezes while it works.+highlight: Voxel Remesh 3-4x faster, never freezes the app+changed: **Voxel Remesh** is 3-4 times faster with the same result (Discord, ThinkingPolygons and GABO): every stage+ runs on all cores, the distance to the old surface is only computed in a narrow band around it, and the flood fills+ work a run at a time. A 500,000-triangle sculpt at the default resolution 200 takes about 0.3 s instead of 1.1 s;+ 2 million triangles about 0.6 s instead of 2 s; resolution 400 about 1.1 s instead of 6 s (10-core laptop).+fixed: Voxel Remesh no longer freezes the app: it always runs in the background with a progress bar and Cancel (before,+ only when keeping a painted texture). Smoothing a remeshed surface and carrying mask and colour over also run in+ parallel.+testers:+ - Windows: Tool > Remesh > Voxel Remesh on a sculpt of 500k triangles or more at resolution 200; it finishes in+ about a second or less, the viewport keeps turning while it runs, and Undo brings the old mesh back.+ - Any OS: resolution 400 on a dense sculpt, press Cancel while the bar moves; the Part stays as it was.+ - Two overlapping spheres (Append), Voxel Remesh: one closed surface, the same look as in 0.10.10.+---+Branch fix/0.10.11-voxel. Output is bit-identical to 0.10.10 (positions, triangles and mask compared on 100k and 500k+triangles at resolutions 200 and 400); numbers and method in REPORT.md.diff --git a/src/app/App.h b/src/app/App.hindex a4a5ed30..d0f647e3 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -1008,7 +1008,7 @@ private:uint32_t subtool = 0;size_t triangles = 0;int resolution = 200;- bool keepMasked = false;+ bool keepMasked = false, keepTexture = true;};std::unique_ptr<VoxelRemeshJob> voxelRemesh_;void pollQRemesh();diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex c5cd379f..af5d4e8b 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -793,10 +793,10 @@ void App::drawPalette_Tool() {ImGui::PopID();tray::GroupLabel(*this, "Voxel Remesh");const float half = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;- if (voxelRemesh_) { // remeshing a painted SubTool in the background (PanelRetopo.cpp)+ if (voxelRemesh_) { // remeshing in the background (PanelRetopo.cpp)ImGui::ProgressBar(voxelRemesh_->progress->load(), ImVec2(half, 0), "Remeshing...");ui::HelpText("Voxel Remesh", nullptr,- "Remeshing and keeping the texture in the background (Auto UV of the new surface, then the "+ "Remeshing in the background (with a painted texture: Auto UV of the new surface, then the ""texture projected onto it). The result replaces the Part when it's done.","Tool > Remesh");} else {diff --git a/src/app/PanelRetopo.cpp b/src/app/PanelRetopo.cppindex 95a2168e..18b41fc1 100644--- a/src/app/PanelRetopo.cpp+++ b/src/app/PanelRetopo.cpp@@ -195,13 +195,8 @@ void App::startVoxelRemesh() {Args args{{"resolution", double(voxelResolution_)}};if (voxelKeepMasked_) args["keep_masked"] = true;if (!memoryAllows("remesh", args, [this] { startVoxelRemesh(); })) return;- memoryConfirmed_ = true; // (checked: the remesh command below doesn't ask again)- if (!hasTexture(doc_.mesh) || !keepTexture_) {- if (hasTexture(doc_.mesh)) args["keep_texture"] = false; // Keep Texture off- runCommand("remesh", args);- return;- }- // Keeping a texture adds Auto UV of the result, which takes seconds to minutes: run it all in the background.+ // Always in the background with progress, so the UI never freezes (keeping a texture adds Auto UV of the+ // result, seconds to minutes); the result lands as the remesh command's would (pollVoxelRemesh).if (doc_.sculptor.strokeActive()) endStroke();auto job = std::make_unique<VoxelRemeshJob>();job->progress = std::make_shared<std::atomic<float>>(0.0f);@@ -219,25 +214,33 @@ void App::startVoxelRemesh() {return;}job->keepMasked = !keep.empty();+ job->keepTexture = keepTexture_;+ const bool texture = hasTexture(doc_.mesh) && keepTexture_;std::promise<bool> promise;job->done = promise.get_future();std::thread([promise = std::move(promise), source = std::make_shared<Mesh>(doc_.mesh), res = job->resolution,progress = job->progress, cancel = job->cancel, result = job->result, error = job->error,- note = job->note, keep = std::move(keep)]() mutable {+ note = job->note, keep = std::move(keep), texture, keepTexture = keepTexture_]() mutable {progress->store(0.02f);- *result = voxelRemesh(*source, res, error.get());+ const float remeshShare = texture ? 0.13f : 0.9f; // the rest: Keep Masked, then the texture's Auto UV+ *result = voxelRemesh(*source, res, error.get(), [&](float f) {+ progress->store(0.02f + remeshShare * f);+ return !cancel->load();+ });bool ok = result->triangleCount() > 0;if (ok && !keep.empty()) { // Keep Masked: the masked part goes back in, joined to the new surfaceMesh stitched;- ok = stitchKeptTriangles(*source, keep, *result, stitched, *error);+ std::string keepNote;+ ok = stitchKeptTriangles(*source, keep, *result, stitched, *error, &keepNote);if (ok) *result = std::move(stitched);else *error = "Remesh (Keep Masked): " + *error;+ if (ok && !keepNote.empty()) *note = "; Keep masked: " + keepNote;}- progress->store(0.15f);- if (ok) *note = carryTextureNote(*source, *result, true, [&](float f) {+ progress->store(texture ? 0.15f : 0.98f);+ if (ok) *note = carryTextureNote(*source, *result, keepTexture, [&](float f) {progress->store(0.15f + 0.85f * f);return !cancel->load();- });+ }) + *note;if (ok && cancel->load()) {ok = false;*error = "Voxel Remesh cancelled";@@ -245,13 +248,13 @@ void App::startVoxelRemesh() {promise.set_value(ok);}).detach();voxelRemesh_ = std::move(job);- status_ = "Voxel Remesh: remeshing and keeping the texture...";+ status_ = texture ? "Voxel Remesh: remeshing and keeping the texture..." : "Voxel Remesh: remeshing...";}void App::pollVoxelRemesh() {if (!voxelRemesh_) return;if (voxelRemesh_->done.wait_for(std::chrono::seconds(0)) != std::future_status::ready) {- status_ = "Voxel Remesh (keeping the texture): " + std::to_string(int(voxelRemesh_->progress->load() * 100.0f)) + "%";+ status_ = "Voxel Remesh: " + std::to_string(int(voxelRemesh_->progress->load() * 100.0f)) + "%";return;}if (jobWaitsForStroke()) return; // (the result lands when the stroke ends)@@ -279,6 +282,7 @@ void App::pollVoxelRemesh() {updateTitle();Args echo{{"resolution", double(job->resolution)}};if (job->keepMasked) echo["keep_masked"] = true;+ if (!job->keepTexture && job->note->find("texture") != std::string::npos) echo["keep_texture"] = false;consoleEcho("remesh", echo, r);}diff --git a/src/core/Mesh.cpp b/src/core/Mesh.cppindex 7dce3135..d8934f2e 100644--- a/src/core/Mesh.cpp+++ b/src/core/Mesh.cpp@@ -832,17 +832,19 @@ size_t Mesh::memoryBytes() const {static void laplacianStep(Mesh& m, float lambda, std::vector<glm::vec3>& next) {next.resize(m.vertexCount());- for (uint32_t v = 0; v < m.vertexCount(); ++v) {- auto ring = m.neighbors(v);- if (ring.empty()) {- next[v] = m.positions[v];- continue;+ poolFor(m.vertexCount(), [&](size_t b, size_t e) {+ for (uint32_t v = uint32_t(b); v < uint32_t(e); ++v) {+ auto ring = m.neighbors(v);+ if (ring.empty()) {+ next[v] = m.positions[v];+ continue;+ }+ glm::vec3 avg(0.0f);+ for (uint32_t n : ring) avg += m.positions[n];+ avg /= float(ring.size());+ next[v] = glm::mix(m.positions[v], avg, lambda);}- glm::vec3 avg(0.0f);- for (uint32_t n : ring) avg += m.positions[n];- avg /= float(ring.size());- next[v] = glm::mix(m.positions[v], avg, lambda);- }+ }, 1 << 14);m.positions.swap(next);}@@ -987,35 +989,38 @@ void transferVertexAttributes(const Mesh& src, Mesh& dst) {if (wantMask) dst.mask.assign(dst.positions.size(), 0.0f);if (wantColors) dst.colors.assign(dst.positions.size(), glm::vec3(1.0f));- for (size_t i = 0; i < dst.positions.size(); ++i) {- const glm::vec3 p = dst.positions[i];- const glm::ivec3 c = cellOf(p);- const glm::vec3 outside = glm::max(glm::max(box.min - p, p - box.max), glm::vec3(0.0f));- const int maxRing = gridCells + int(std::ceil(glm::length(outside) / cell));- float best = std::numeric_limits<float>::max();- uint32_t bestV = 0;- // Search shells of growing Chebyshev radius; stop once nothing closer can remain.- for (int r = 0; r <= maxRing; ++r) {- for (int dz = -r; dz <= r; ++dz)- for (int dy = -r; dy <= r; ++dy)- for (int dx = -r; dx <= r; ++dx) {- if (std::max({std::abs(dx), std::abs(dy), std::abs(dz)}) != r) continue;- auto it = grid.find(key(c + glm::ivec3(dx, dy, dz)));- if (it == grid.end()) continue;- for (uint32_t v : it->second) {- const glm::vec3 d = src.positions[v] - p;- const float d2 = glm::dot(d, d);- if (d2 < best) {- best = d2;- bestV = v;+ // Each new vertex searches on its own: blocks in parallel.+ poolFor(dst.positions.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) {+ const glm::vec3 p = dst.positions[i];+ const glm::ivec3 c = cellOf(p);+ const glm::vec3 outside = glm::max(glm::max(box.min - p, p - box.max), glm::vec3(0.0f));+ const int maxRing = gridCells + int(std::ceil(glm::length(outside) / cell));+ float best = std::numeric_limits<float>::max();+ uint32_t bestV = 0;+ // Search shells of growing Chebyshev radius; stop once nothing closer can remain.+ for (int r = 0; r <= maxRing; ++r) {+ for (int dz = -r; dz <= r; ++dz)+ for (int dy = -r; dy <= r; ++dy)+ for (int dx = -r; dx <= r; ++dx) {+ if (std::max({std::abs(dx), std::abs(dy), std::abs(dz)}) != r) continue;+ auto it = grid.find(key(c + glm::ivec3(dx, dy, dz)));+ if (it == grid.end()) continue;+ for (uint32_t v : it->second) {+ const glm::vec3 d = src.positions[v] - p;+ const float d2 = glm::dot(d, d);+ if (d2 < best) {+ best = d2;+ bestV = v;+ }}}- }- if (best < std::numeric_limits<float>::max() && std::sqrt(best) <= float(r) * cell) break;+ if (best < std::numeric_limits<float>::max() && std::sqrt(best) <= float(r) * cell) break;+ }+ if (wantMask) dst.mask[i] = src.mask[bestV];+ if (wantColors) dst.colors[i] = src.colors[bestV];}- if (wantMask) dst.mask[i] = src.mask[bestV];- if (wantColors) dst.colors[i] = src.colors[bestV];- }+ }, 1 << 13);dst.markAllDirty();}diff --git a/src/core/Voxel.cpp b/src/core/Voxel.cppindex cbabb3fc..5e200d43 100644--- a/src/core/Voxel.cpp+++ b/src/core/Voxel.cpp@@ -5,61 +5,84 @@#include <algorithm>#include <array>#include <cmath>-#include <thread>++#include "core/ThreadPool.h"namespace sf {namespace {-// Running max (dilate) or min (erode) over a window of +-radius along one axis.-void filterAxis(std::vector<uint8_t>& data, const glm::ivec3& dims, int axis, int radius, bool dilate) {- const glm::ivec3 step(1, dims.x, dims.x * dims.y);- const int n = dims[axis];- const int u = (axis + 1) % 3, v = (axis + 2) % 3;- std::vector<uint8_t> line(static_cast<size_t>(n)), out(static_cast<size_t>(n));- for (int b = 0; b < dims[v]; ++b)- for (int a = 0; a < dims[u]; ++a) {- const size_t start = size_t(a) * size_t(step[u]) + size_t(b) * size_t(step[v]);- for (int i = 0; i < n; ++i) line[size_t(i)] = data[start + size_t(i) * size_t(step[axis])];- for (int i = 0; i < n; ++i) {- uint8_t r = line[size_t(i)];- for (int k = std::max(0, i - radius); k <= std::min(n - 1, i + radius); ++k)- r = dilate ? std::max(r, line[size_t(k)]) : std::min(r, line[size_t(k)]);- out[size_t(i)] = r;- }- for (int i = 0; i < n; ++i) data[start + size_t(i) * size_t(step[axis])] = out[size_t(i)];- }-}-+// Running max (dilate) or min (erode) over a box of +-radius cells, one axis at a time (separable). Rows along x,+// whole rows for y and whole slices for z, so every pass reads memory in order; the slices run in parallel.void morph(std::vector<uint8_t>& data, const glm::ivec3& dims, int radius, bool dilate) {if (radius <= 0) return;- for (int axis = 0; axis < 3; ++axis) filterAxis(data, dims, axis, radius, dilate);+ const size_t X = size_t(dims.x), Y = size_t(dims.y), Z = size_t(dims.z), S = X * Y;+ std::vector<uint8_t> tmp(data.size());+ auto combine = [dilate](uint8_t* out, const uint8_t* in, size_t count) {+ for (size_t i = 0; i < count; ++i) out[i] = dilate ? std::max(out[i], in[i]) : std::min(out[i], in[i]);+ };+ poolFor(Y * Z, [&](size_t b, size_t e) { // x: data -> tmp+ for (size_t row = b; row < e; ++row) {+ const uint8_t* in = &data[row * X];+ uint8_t* out = &tmp[row * X];+ for (int x = 0; x < dims.x; ++x) {+ uint8_t r = in[x];+ for (int k = std::max(0, x - radius); k <= std::min(dims.x - 1, x + radius); ++k)+ r = dilate ? std::max(r, in[k]) : std::min(r, in[k]);+ out[x] = r;+ }+ }+ }, 64);+ poolFor(Z, [&](size_t b, size_t e) { // y: tmp -> data+ for (size_t z = b; z < e; ++z)+ for (int y = 0; y < dims.y; ++y) {+ uint8_t* out = &data[z * S + size_t(y) * X];+ std::copy_n(&tmp[z * S + size_t(y) * X], X, out);+ for (int k = std::max(0, y - radius); k <= std::min(dims.y - 1, y + radius); ++k)+ if (k != y) combine(out, &tmp[z * S + size_t(k) * X], X);+ }+ }, 1);+ poolFor(Z, [&](size_t b, size_t e) { // z: data -> tmp+ for (size_t z = b; z < e; ++z) {+ std::copy_n(&data[z * S], S, &tmp[z * S]);+ for (int k = std::max(0, int(z) - radius); k <= std::min(dims.z - 1, int(z) + radius); ++k)+ if (k != int(z)) combine(&tmp[z * S], &data[size_t(k) * S], S);+ }+ }, 1);+ data.swap(tmp);}-// Labels 6-connected regions where data[i] == value, starting from `seeds`.+// Labels 6-connected regions where data[i] == value, starting from `seeds` (already marked in `reached`). Span fill:+// each popped sample claims its whole x run, and only the first sample of each run beside it is pushed.void floodFill(const std::vector<uint8_t>& data, uint8_t value, const glm::ivec3& dims, std::vector<uint32_t>& stack,std::vector<uint8_t>& reached) {- const int64_t sx = 1, sy = dims.x, sz = int64_t(dims.x) * dims.y;+ const size_t X = size_t(dims.x), S = X * size_t(dims.y);+ auto open = [&](size_t j) { return !reached[j] && data[j] == value; };while (!stack.empty()) {- const uint32_t i = stack.back();+ const size_t i = stack.back();stack.pop_back();- const int x = int(i % uint32_t(dims.x));- const int y = int((i / uint32_t(dims.x)) % uint32_t(dims.y));- const int z = int(i / uint32_t(sz));- auto visit = [&](bool inRange, int64_t offset) {+ const size_t row = i - i % X; // the row's first sample+ size_t lo = i, hi = i;+ while (lo > row && open(lo - 1)) reached[--lo] = 1;+ while (hi + 1 < row + X && open(hi + 1)) reached[++hi] = 1;+ const size_t y = (i / X) % size_t(dims.y), z = i / S;+ auto scan = [&](bool inRange, size_t offset, bool up) {if (!inRange) return;- const uint32_t j = uint32_t(int64_t(i) + offset);- if (!reached[j] && data[j] == value) {- reached[j] = 1;- stack.push_back(j);+ bool inRun = false;+ for (size_t k = lo; k <= hi; ++k) {+ const size_t j = up ? k + offset : k - offset;+ const bool o = open(j);+ if (o && !inRun) {+ reached[j] = 1;+ stack.push_back(uint32_t(j));+ }+ inRun = o;}};- visit(x > 0, -sx);- visit(x + 1 < dims.x, sx);- visit(y > 0, -sy);- visit(y + 1 < dims.y, sy);- visit(z > 0, -sz);- visit(z + 1 < dims.z, sz);+ scan(y > 0, X, false);+ scan(y + 1 < size_t(dims.y), X, true);+ scan(z > 0, S, false);+ scan(z + 1 < size_t(dims.z), S, true);}}@@ -128,7 +151,9 @@ std::vector<uint8_t> solidifyShell(const VoxelGrid& shell, float threshold, intconst glm::ivec3 dims = shell.dims;const size_t n = shell.size();std::vector<uint8_t> wall(n);- for (size_t i = 0; i < n; ++i) wall[i] = shell.values[i] > threshold ? 1 : 0;+ poolFor(n, [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) wall[i] = shell.values[i] > threshold ? 1 : 0;+ }, 1 << 16);morph(wall, dims, closeRadius, true);// Flood the empty space from the grid border; whatever it can't reach is inside.@@ -147,7 +172,9 @@ std::vector<uint8_t> solidifyShell(const VoxelGrid& shell, float threshold, intfloodFill(wall, 0, dims, stack, outside);std::vector<uint8_t> solid(n);- for (size_t i = 0; i < n; ++i) solid[i] = outside[i] ? 0 : 1;+ poolFor(n, [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) solid[i] = outside[i] ? 0 : 1;+ }, 1 << 16);morph(solid, dims, closeRadius, false); // undo the gap-closing dilationif (!keepAllParts) {@@ -197,82 +224,114 @@ Mesh meshFromSolid(const VoxelGrid& grid, const std::vector<uint8_t>& solid, intMesh meshFromField(const VoxelGrid& grid, const std::vector<float>& f, float iso, int smoothIterations) {const glm::ivec3 dims = grid.dims;-- // One vertex per cell that the surface passes through (surface nets).const glm::ivec3 cells = dims - 1;- std::vector<int32_t> cellVertex(size_t(cells.x) * size_t(cells.y) * size_t(cells.z), -1);+ if (glm::any(glm::lessThan(cells, glm::ivec3(1)))) return {};+ const size_t cellSlice = size_t(cells.x) * size_t(cells.y);+ std::vector<int32_t> cellVertex(cellSlice * size_t(cells.z), -1);auto cellIndex = [&](int x, int y, int z) { return (size_t(z) * size_t(cells.y) + size_t(y)) * size_t(cells.x) + size_t(x); };- Mesh m;- for (int z = 0; z < cells.z; ++z)- for (int y = 0; y < cells.y; ++y)- for (int x = 0; x < cells.x; ++x) {- std::array<float, 8> c;- int inside = 0;- for (int k = 0; k < 8; ++k) {- c[size_t(k)] = f[grid.index(x + (k & 1), y + ((k >> 1) & 1), z + ((k >> 2) & 1))];- inside += c[size_t(k)] > iso;- }- if (inside == 0 || inside == 8) continue;- glm::vec3 sum(0.0f);- int crossings = 0;- for (int a = 0; a < 8; ++a)- for (int bit = 1; bit < 8; bit <<= 1) {- if (a & bit) continue;- const int b = a | bit;- const float fa = c[size_t(a)], fb = c[size_t(b)];- if ((fa > iso) == (fb > iso)) continue;- const float t = (iso - fa) / (fb - fa);- const glm::vec3 pa(a & 1, (a >> 1) & 1, (a >> 2) & 1);- const glm::vec3 pb(b & 1, (b >> 1) & 1, (b >> 2) & 1);- sum += glm::mix(pa, pb, t);- ++crossings;- }- cellVertex[cellIndex(x, y, z)] = int32_t(m.positions.size());- m.positions.push_back(grid.position(x, y, z) + sum / float(crossings) * grid.cell);- }- // One quad per grid edge with a sign change, joining the four cells around it.- for (int z = 0; z < dims.z; ++z)- for (int y = 0; y < dims.y; ++y)- for (int x = 0; x < dims.x; ++x) {- const glm::ivec3 p(x, y, z);- const bool in0 = f[grid.index(x, y, z)] > iso;- for (int axis = 0; axis < 3; ++axis) {- glm::ivec3 q = p;- q[axis] += 1;- if (q[axis] >= dims[axis]) continue;- const bool in1 = f[grid.index(q.x, q.y, q.z)] > iso;- if (in0 == in1) continue;- const int u = (axis + 1) % 3, v = (axis + 2) % 3;- if (p[u] < 1 || p[v] < 1 || p[u] > cells[u] - 1 || p[v] > cells[v] - 1 || p[axis] > cells[axis] - 1)- continue;- std::array<int32_t, 4> quad;- const int du[4] = {-1, 0, 0, -1}, dv[4] = {-1, -1, 0, 0};- bool ok = true;- for (int k = 0; k < 4; ++k) {- glm::ivec3 c = p;- c[u] += du[k];- c[v] += dv[k];- quad[size_t(k)] = cellVertex[cellIndex(c.x, c.y, c.z)];- ok &= quad[size_t(k)] >= 0;+ // One vertex per cell that the surface passes through (surface nets). Slices run in parallel, each numbering its+ // own vertices; the slices' counts then give the global numbers, in the same z, y, x order as a serial scan.+ std::vector<std::vector<glm::vec3>> slicePositions(size_t(cells.z));+ poolFor(size_t(cells.z), [&](size_t zb, size_t ze) {+ for (int z = int(zb); z < int(ze); ++z) {+ std::vector<glm::vec3>& out = slicePositions[size_t(z)];+ for (int y = 0; y < cells.y; ++y)+ for (int x = 0; x < cells.x; ++x) {+ std::array<float, 8> c;+ int inside = 0;+ for (int k = 0; k < 8; ++k) {+ c[size_t(k)] = f[grid.index(x + (k & 1), y + ((k >> 1) & 1), z + ((k >> 2) & 1))];+ inside += c[size_t(k)] > iso;}- if (!ok) continue;- if (!in0) std::swap(quad[1], quad[3]); // outward normal must point to the outside sample- const auto& P = m.positions;- const bool diag02 = glm::distance(P[size_t(quad[0])], P[size_t(quad[2])]) <=- glm::distance(P[size_t(quad[1])], P[size_t(quad[3])]);- const glm::uvec4 qq(quad[0], quad[1], quad[2], quad[3]);- if (diag02) {- m.triangles.push_back({qq.x, qq.y, qq.z});- m.triangles.push_back({qq.x, qq.z, qq.w});- } else {- m.triangles.push_back({qq.x, qq.y, qq.w});- m.triangles.push_back({qq.y, qq.z, qq.w});+ if (inside == 0 || inside == 8) continue;+ glm::vec3 sum(0.0f);+ int crossings = 0;+ for (int a = 0; a < 8; ++a)+ for (int bit = 1; bit < 8; bit <<= 1) {+ if (a & bit) continue;+ const int b = a | bit;+ const float fa = c[size_t(a)], fb = c[size_t(b)];+ if ((fa > iso) == (fb > iso)) continue;+ const float t = (iso - fa) / (fb - fa);+ const glm::vec3 pa(a & 1, (a >> 1) & 1, (a >> 2) & 1);+ const glm::vec3 pb(b & 1, (b >> 1) & 1, (b >> 2) & 1);+ sum += glm::mix(pa, pb, t);+ ++crossings;+ }+ cellVertex[cellIndex(x, y, z)] = int32_t(out.size());+ out.push_back(grid.position(x, y, z) + sum / float(crossings) * grid.cell);+ }+ }+ }, 1);+ std::vector<size_t> firstVertex(size_t(cells.z) + 1, 0);+ for (size_t z = 0; z < size_t(cells.z); ++z) firstVertex[z + 1] = firstVertex[z] + slicePositions[z].size();+ Mesh m;+ m.positions.resize(firstVertex.back());+ poolFor(size_t(cells.z), [&](size_t zb, size_t ze) {+ for (size_t z = zb; z < ze; ++z) {+ std::copy(slicePositions[z].begin(), slicePositions[z].end(), m.positions.begin() + ptrdiff_t(firstVertex[z]));+ std::vector<glm::vec3>().swap(slicePositions[z]);+ if (firstVertex[z] == 0) continue;+ for (size_t i = z * cellSlice; i < (z + 1) * cellSlice; ++i)+ if (cellVertex[i] >= 0) cellVertex[i] += int32_t(firstVertex[z]);+ }+ }, 1);++ // One quad per grid edge with a sign change, joining the four cells around it; slices in parallel, joined in order.+ std::vector<std::vector<glm::uvec3>> sliceTriangles(size_t(dims.z));+ poolFor(size_t(dims.z), [&](size_t zb, size_t ze) {+ for (int z = int(zb); z < int(ze); ++z) {+ std::vector<glm::uvec3>& out = sliceTriangles[size_t(z)];+ for (int y = 0; y < dims.y; ++y)+ for (int x = 0; x < dims.x; ++x) {+ const glm::ivec3 p(x, y, z);+ const bool in0 = f[grid.index(x, y, z)] > iso;+ for (int axis = 0; axis < 3; ++axis) {+ glm::ivec3 q = p;+ q[axis] += 1;+ if (q[axis] >= dims[axis]) continue;+ const bool in1 = f[grid.index(q.x, q.y, q.z)] > iso;+ if (in0 == in1) continue;+ const int u = (axis + 1) % 3, v = (axis + 2) % 3;+ if (p[u] < 1 || p[v] < 1 || p[u] > cells[u] - 1 || p[v] > cells[v] - 1 || p[axis] > cells[axis] - 1)+ continue;+ std::array<int32_t, 4> quad;+ const int du[4] = {-1, 0, 0, -1}, dv[4] = {-1, -1, 0, 0};+ bool ok = true;+ for (int k = 0; k < 4; ++k) {+ glm::ivec3 c = p;+ c[u] += du[k];+ c[v] += dv[k];+ quad[size_t(k)] = cellVertex[cellIndex(c.x, c.y, c.z)];+ ok &= quad[size_t(k)] >= 0;+ }+ if (!ok) continue;+ if (!in0) std::swap(quad[1], quad[3]); // outward normal must point to the outside sample+ const auto& P = m.positions;+ const bool diag02 = glm::distance(P[size_t(quad[0])], P[size_t(quad[2])]) <=+ glm::distance(P[size_t(quad[1])], P[size_t(quad[3])]);+ const glm::uvec4 qq(quad[0], quad[1], quad[2], quad[3]);+ if (diag02) {+ out.push_back({qq.x, qq.y, qq.z});+ out.push_back({qq.x, qq.z, qq.w});+ } else {+ out.push_back({qq.x, qq.y, qq.w});+ out.push_back({qq.y, qq.z, qq.w});+ }}- // Surface nets makes quads: keep each one (Mesh::quadPartners), like ZBrush's DynaMesh.- m.pairQuad(uint32_t(m.triangles.size() - 2), uint32_t(m.triangles.size() - 1));}- }+ }+ }, 1);+ size_t triangleTotal = 0;+ for (const auto& t : sliceTriangles) triangleTotal += t.size();+ m.triangles.reserve(triangleTotal);+ for (auto& t : sliceTriangles) {+ m.triangles.insert(m.triangles.end(), t.begin(), t.end());+ std::vector<glm::uvec3>().swap(t);+ }+ // Surface nets makes quads: keep each one (Mesh::quadPartners): an even all-quad surface.+ for (uint32_t t = 0; t + 1 < m.triangles.size(); t += 2) m.pairQuad(t, t + 1);m.rebuildTopology();taubinSmooth(m, smoothIterations);m.recomputeAllNormals();@@ -299,113 +358,182 @@ void rasterizeMeshShell(const Mesh& mesh, VoxelGrid& grid) {std::vector<float> insideDistanceField(const Mesh& mesh, const VoxelGrid& grid, const std::vector<uint8_t>& solid, float band) {// Exact distance (in cells) to the nearest triangle for every sample within `band` cells of the surface, found by- // visiting the samples around each triangle. z-slabs run on separate threads, so no two threads write a sample.+ // visiting the samples around each triangle (a narrow band: nothing else is touched). Triangles are binned into+ // z-slabs that run in parallel, each writing only its own samples and visiting its triangles in index order, so+ // ties go to the same triangle as a serial pass.const glm::ivec3 dims = grid.dims;const size_t n = grid.size();std::vector<float> dist2(n, band * band);std::vector<int32_t> nearest(n, -1);const auto& P = mesh.positions;const float inv = 1.0f / grid.cell;- auto work = [&](int z0, int z1) {- for (uint32_t t = 0; t < mesh.triangleCount(); ++t) {- const glm::uvec3 tri = mesh.triangles[t];- const glm::vec3 a = (P[tri.x] - grid.origin) * inv, b = (P[tri.y] - grid.origin) * inv,- c = (P[tri.z] - grid.origin) * inv;- const glm::ivec3 lo = glm::max(glm::ivec3(glm::floor(glm::min(a, glm::min(b, c)) - band)), glm::ivec3(0));- const glm::ivec3 hi = glm::min(glm::ivec3(glm::ceil(glm::max(a, glm::max(b, c)) + band)), dims - 1);- const int za = std::max(lo.z, z0), zb = std::min(hi.z, z1 - 1);- for (int z = za; z <= zb; ++z)- for (int y = lo.y; y <= hi.y; ++y)- for (int x = lo.x; x <= hi.x; ++x) {- const glm::vec3 p(x, y, z);- const glm::vec3 d = p - closestOnTriangle(p, a, b, c);- const float d2 = glm::dot(d, d);- const size_t i = grid.index(x, y, z);- if (d2 < dist2[i]) {- dist2[i] = d2;- nearest[i] = int32_t(t);+ const uint32_t triangles = uint32_t(mesh.triangleCount());+ auto local = [&](uint32_t t, glm::vec3& a, glm::vec3& b, glm::vec3& c, glm::ivec3& lo, glm::ivec3& hi) {+ const glm::uvec3 tri = mesh.triangles[t];+ a = (P[tri.x] - grid.origin) * inv, b = (P[tri.y] - grid.origin) * inv, c = (P[tri.z] - grid.origin) * inv;+ lo = glm::max(glm::ivec3(glm::floor(glm::min(a, glm::min(b, c)) - band)), glm::ivec3(0));+ hi = glm::min(glm::ivec3(glm::ceil(glm::max(a, glm::max(b, c)) + band)), dims - 1);+ };+ constexpr int kSlab = 4;+ const size_t slabs = size_t((dims.z + kSlab - 1) / kSlab);+ std::vector<glm::ivec2> slabRange(triangles);+ poolFor(triangles, [&](size_t b0, size_t e0) {+ for (size_t t = b0; t < e0; ++t) {+ glm::vec3 a, b, c;+ glm::ivec3 lo, hi;+ local(uint32_t(t), a, b, c, lo, hi);+ slabRange[t] = lo.z <= hi.z ? glm::ivec2(lo.z / kSlab, hi.z / kSlab) : glm::ivec2(1, 0); // (NaN: none)+ }+ }, 1 << 16);+ std::vector<uint32_t> slabStart(slabs + 1, 0);+ for (const glm::ivec2& r : slabRange)+ for (int s = r.x; s <= r.y; ++s) ++slabStart[size_t(s) + 1];+ for (size_t s = 0; s < slabs; ++s) slabStart[s + 1] += slabStart[s];+ std::vector<uint32_t> slabTriangles(slabStart.back());+ {+ std::vector<uint32_t> cursor(slabStart.begin(), slabStart.end() - 1);+ for (uint32_t t = 0; t < triangles; ++t)+ for (int s = slabRange[t].x; s <= slabRange[t].y; ++s) slabTriangles[cursor[size_t(s)]++] = t;+ }+ std::vector<glm::ivec2>().swap(slabRange);+ poolFor(slabs, [&](size_t sb, size_t se) {+ for (size_t s = sb; s < se; ++s) {+ const int z0 = int(s) * kSlab, z1 = std::min(dims.z, z0 + kSlab);+ for (uint32_t k = slabStart[s]; k < slabStart[s + 1]; ++k) {+ const uint32_t t = slabTriangles[k];+ glm::vec3 a, b, c;+ glm::ivec3 lo, hi;+ local(t, a, b, c, lo, hi);+ // Only samples within band of the triangle's bounding sphere can be within band of the triangle.+ const glm::vec3 centre = (a + b + c) / 3.0f;+ const float radius = std::sqrt(std::max({glm::dot(a - centre, a - centre), glm::dot(b - centre, b - centre),+ glm::dot(c - centre, c - centre)})) + 1e-3f;+ const float reach = radius + band;+ const float reach2 = reach * reach;+ for (int z = std::max(lo.z, z0); z <= std::min(hi.z, z1 - 1); ++z) {+ const float dz = float(z) - centre.z, rz = reach2 - dz * dz;+ if (rz < 0.0f) continue;+ for (int y = lo.y; y <= hi.y; ++y) {+ const float dy = float(y) - centre.y, ry = rz - dy * dy;+ if (ry < 0.0f) continue;+ const float half = std::sqrt(ry);+ const int x0 = std::max(lo.x, int(std::ceil(centre.x - half)));+ const int x1 = std::min(hi.x, int(std::floor(centre.x + half)));+ for (int x = x0; x <= x1; ++x) {+ const glm::vec3 p(x, y, z);+ const size_t i = grid.index(x, y, z);+ // Skip when even the sphere's near side is no closer than the best so far (most samples+ // once a slab's first triangles are in: small triangles overlap many times).+ const float far = std::sqrt(dist2[i]) + radius;+ if (glm::dot(p - centre, p - centre) > far * far) continue;+ const glm::vec3 d = p - closestOnTriangle(p, a, b, c);+ const float d2 = glm::dot(d, d);+ if (d2 < dist2[i]) {+ dist2[i] = d2;+ nearest[i] = int32_t(t);+ }}}+ }+ }}- };- const int threads = int(std::clamp(std::thread::hardware_concurrency(), 1u, 16u));- const int slab = (dims.z + threads - 1) / threads;- std::vector<std::thread> pool;- for (int k = 1; k < threads; ++k)- if (k * slab < dims.z) pool.emplace_back(work, k * slab, std::min(dims.z, (k + 1) * slab));- work(0, std::min(dims.z, slab));- for (auto& th : pool) th.join();+ }, 1);+ std::vector<uint32_t>().swap(slabTriangles);// Sign: the flood fill is certain about the outside and about the deep inside; next to the surface the// nearest triangle's side decides, which keeps sub-voxel detail instead of voxel stair-steps.- std::vector<uint8_t> nearOutside(n, 0);- for (int z = 0; z < dims.z; ++z)- for (int y = 0; y < dims.y; ++y)- for (int x = 0; x < dims.x; ++x) {- if (solid[grid.index(x, y, z)]) continue;- for (int dz = -2; dz <= 2; ++dz)- for (int dy = -2; dy <= 2; ++dy)- for (int dx = -2; dx <= 2; ++dx) {- const glm::ivec3 q(x + dx, y + dy, z + dz);- if (glm::all(glm::greaterThanEqual(q, glm::ivec3(0))) && glm::all(glm::lessThan(q, dims)))- nearOutside[grid.index(q.x, q.y, q.z)] = 1;- }- }+ std::vector<uint8_t> nearOutside(n);+ poolFor(n, [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) nearOutside[i] = solid[i] ? 0 : 1;+ }, 1 << 16);+ morph(nearOutside, dims, 2, true); // within 2 samples (any axis) of an outside samplestd::vector<uint8_t> inside(n);- for (int z = 0; z < dims.z; ++z)- for (int y = 0; y < dims.y; ++y)- for (int x = 0; x < dims.x; ++x) {- const size_t i = grid.index(x, y, z);- if (!solid[i]) inside[i] = 0;- else if (!nearOutside[i] || nearest[i] < 0) inside[i] = 1;- else {- const glm::uvec3 tri = mesh.triangles[size_t(nearest[i])];- const glm::vec3 nrm = glm::cross(P[tri.y] - P[tri.x], P[tri.z] - P[tri.x]);- const glm::vec3 p = grid.position(x, y, z);- const glm::vec3 onSurface = closestOnTriangle(p, P[tri.x], P[tri.y], P[tri.z]);- // A surface buried inside another part (solid just outside it too) doesn't bound the solid.- const float len = glm::length(nrm);- const glm::ivec3 probe(glm::round((onSurface + nrm * (2.5f * grid.cell / std::max(len, 1e-20f)) -- grid.origin) / grid.cell));- const bool buried = len > 0.0f && glm::all(glm::greaterThanEqual(probe, glm::ivec3(0))) &&- glm::all(glm::lessThan(probe, dims)) && solid[grid.index(probe.x, probe.y, probe.z)];- inside[i] = buried || glm::dot(p - onSurface, nrm) < 0.0f;+ poolFor(size_t(dims.z), [&](size_t zb, size_t ze) {+ for (int z = int(zb); z < int(ze); ++z)+ for (int y = 0; y < dims.y; ++y)+ for (int x = 0; x < dims.x; ++x) {+ const size_t i = grid.index(x, y, z);+ if (!solid[i]) inside[i] = 0;+ else if (!nearOutside[i] || nearest[i] < 0) inside[i] = 1;+ else {+ const glm::uvec3 tri = mesh.triangles[size_t(nearest[i])];+ const glm::vec3 nrm = glm::cross(P[tri.y] - P[tri.x], P[tri.z] - P[tri.x]);+ const glm::vec3 p = grid.position(x, y, z);+ const glm::vec3 onSurface = closestOnTriangle(p, P[tri.x], P[tri.y], P[tri.z]);+ // A surface buried inside another part (solid just outside it too) doesn't bound the solid.+ const float len = glm::length(nrm);+ const glm::ivec3 probe(glm::round((onSurface + nrm * (2.5f * grid.cell / std::max(len, 1e-20f)) -+ grid.origin) / grid.cell));+ const bool buried = len > 0.0f && glm::all(glm::greaterThanEqual(probe, glm::ivec3(0))) &&+ glm::all(glm::lessThan(probe, dims)) && solid[grid.index(probe.x, probe.y, probe.z)];+ inside[i] = buried || glm::dot(p - onSurface, nrm) < 0.0f;+ }}- }+ }, 1);+ std::vector<uint8_t>().swap(nearOutside);// Surfaces buried inside the solid (overlapping parts) make small "outside" pockets: anything outside that- // can't reach the real outside is inside, so merged parts stay one closed surface.- std::vector<uint8_t> reached(n, 0);+ // can't reach the real outside is inside, so merged parts stay one closed surface. The flood starts from the+ // outside samples that touch an outside-signed solid sample (the rest of the outside has nowhere to go).+ std::vector<uint8_t> reached(n);+ poolFor(n, [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) reached[i] = solid[i] ? 0 : 1;+ }, 1 << 16);+ const size_t X = size_t(dims.x), S = X * size_t(dims.y);+ std::vector<std::vector<uint32_t>> sliceSeeds(size_t(dims.z));+ poolFor(size_t(dims.z), [&](size_t zb, size_t ze) {+ for (int z = int(zb); z < int(ze); ++z)+ for (int y = 0; y < dims.y; ++y)+ for (int x = 0; x < dims.x; ++x) {+ const size_t i = grid.index(x, y, z);+ if (solid[i]) continue;+ auto pocket = [&](bool inRange, size_t j) { return inRange && solid[j] && !inside[j]; };+ if (pocket(x > 0, i - 1) || pocket(x + 1 < dims.x, i + 1) || pocket(y > 0, i - X) ||+ pocket(y + 1 < dims.y, i + X) || pocket(z > 0, i - S) || pocket(z + 1 < dims.z, i + S))+ sliceSeeds[size_t(z)].push_back(uint32_t(i));+ }+ }, 1);std::vector<uint32_t> stack;- for (size_t i = 0; i < n; ++i)- if (!solid[i]) {- reached[i] = 1;- stack.push_back(uint32_t(i));- }+ for (const auto& seeds : sliceSeeds) stack.insert(stack.end(), seeds.begin(), seeds.end());floodFill(inside, 0, dims, stack, reached);std::vector<float> f(n);- for (size_t i = 0; i < n; ++i) {- const float d = std::sqrt(dist2[i]);- f[i] = inside[i] || !reached[i] ? d : -d;- }+ poolFor(n, [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) {+ const float d = std::sqrt(dist2[i]);+ f[i] = inside[i] || !reached[i] ? d : -d;+ }+ }, 1 << 16);return f;}-Mesh voxelRemesh(const Mesh& mesh, int resolution, std::string* error) {+Mesh voxelRemesh(const Mesh& mesh, int resolution, std::string* error, const std::function<bool(float)>& progress) {VoxelGrid grid;if (mesh.triangleCount() == 0 || !makeVoxelGrid(mesh.bounds(), resolution, 4, grid)) {if (error) *error = mesh.triangleCount() == 0 ? "The mesh is empty" : "Resolution too high for this mesh";return {};}+ auto step = [&](float f) {+ if (!progress || progress(f)) return true;+ if (error) *error = "Voxel Remesh cancelled";+ return false;+ };rasterizeMeshShell(mesh, grid);+ if (!step(0.1f)) return {};std::vector<uint8_t> solid = solidifyShell(grid, 0.5f, 1, true);+ std::vector<float>().swap(grid.values);+ if (!step(0.25f)) return {};// Mesh the signed distance to the original surface (positive inside), not the blocky occupancy: the result// lands on the original surface with no voxel terracing.- Mesh out = meshFromField(grid, insideDistanceField(mesh, grid, solid, 3.0f), 0.0f, 2);+ const std::vector<float> field = insideDistanceField(mesh, grid, solid, 3.0f);+ std::vector<uint8_t>().swap(solid);+ if (!step(0.6f)) return {};+ Mesh out = meshFromField(grid, field, 0.0f, 2);if (out.triangleCount() == 0 && error) *error = "Remesh produced no surface";- // Mask and polypaint follow the nearest original vertex; polygroups, hidden+ if (!step(0.9f)) return {};+ // Mask and vertex paint follow the nearest original vertex; face groups, hidden// flags and UVs don't survive a rebuild (everything becomes visible group 0).// The original's quads don't either: the new surface is all quads of its own.transferVertexAttributes(mesh, out);+ step(1.0f);return out;}diff --git a/src/core/Voxel.h b/src/core/Voxel.hindex 6d31118c..3ff8cd41 100644--- a/src/core/Voxel.h+++ b/src/core/Voxel.h@@ -1,7 +1,7 @@// SculptForge - open source digital sculpting// SPDX-License-Identifier: GPL-3.0-or-later//-// Voxel toolkit shared by the voxel remesher (DynaMesh-style: merge parts and+// Voxel toolkit shared by the voxel remesher (merge parts and// even out topology), splat-to-mesh conversion and future boolean tools:// rasterise a surface "shell" into a grid, close small gaps, flood-fill the// outside to get a watertight solid, then extract a smooth surface with@@ -11,6 +11,7 @@#include "core/Mesh.h"#include <cstdint>+#include <functional>#include <string>#include <vector>@@ -55,9 +56,11 @@ void rasterizeMeshShell(const Mesh& mesh, VoxelGrid& grid);// Rebuilds the mesh as an even, watertight surface (`resolution` cells across// its longest side). Overlapping parts are merged. Sculpt layers are baked.-// Mask and colours transfer from the nearest original vertex; polygroups,+// Mask and colours transfer from the nearest original vertex; face groups,// hidden flags and UVs reset (all visible, group 0, no UVs); the original's-// quads are dropped and the result is all quads of its own.-Mesh voxelRemesh(const Mesh& mesh, int resolution, std::string* error = nullptr);+// quads are dropped and the result is all quads of its own. `progress` (0..1) returning false cancels (empty result).+// Parallel and narrow-band throughout: well under a second at the default resolution; run it off the UI thread.+Mesh voxelRemesh(const Mesh& mesh, int resolution, std::string* error = nullptr,+ const std::function<bool(float)>& progress = {});} // namespace sfdiff --git a/tests/test_core.cpp b/tests/test_core.cppindex 5a58e933..1be4bdcf 100644--- a/tests/test_core.cpp+++ b/tests/test_core.cpp@@ -812,6 +812,14 @@ TEST(voxel_remesh) {CHECK(reg.execute(d, "remesh", {{"resolution", 48.0}}).ok);CHECK(reg.execute(d, "undo").ok && d.mesh.triangleCount() == 1280);CHECK(!voxelRemesh(Mesh(), 64, &err).triangleCount() && !err.empty());++ // Progress rises to 1; returning false cancels with an empty result (the app's background job).+ std::vector<float> steps;+ CHECK(voxelRemesh(sphere, 48, &err, [&](float f) { steps.push_back(f); return true; }).triangleCount() > 0);+ CHECK(steps.size() >= 3 && std::is_sorted(steps.begin(), steps.end()) && steps.back() == 1.0f);+ err.clear();+ CHECK(voxelRemesh(sphere, 48, &err, [](float) { return false; }).triangleCount() == 0);+ CHECK(err.find("cancelled") != std::string::npos);}TEST(splats_mesh_conversions) {