Skip to content

Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.

Levels: say when rebuilding tools drop them, layer detail in local frames, free inactive caches

islandmeda72d87123eef
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4d94baab..0ca0e996 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -352,6 +352,7 @@ if(SCULPTFORGE_BUILD_TESTS)
add_executable(sculptforge_tests ${SCULPTFORGE_TEST_SOURCES} src/cli/McpServer.cpp src/app/AssetLibrary.cpp
src/app/UiLayout.cpp src/app/ShellGeometry.cpp src/render/Camera.cpp)
target_include_directories(sculptforge_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/tests)
+ target_compile_definitions(sculptforge_tests PRIVATE SF_TEST_DATA_DIR="${CMAKE_CURRENT_SOURCE_DIR}/tests/data")
target_link_libraries(sculptforge_tests PRIVATE sculptforge_core sculptforge_ai)
if(SCULPTFORGE_BUILD_APP) # the action registry (key chords, shortcut overrides) needs SDL's key names
target_sources(sculptforge_tests PRIVATE src/app/Actions.cpp)
diff --git a/src/app/PanelRetopo.cpp b/src/app/PanelRetopo.cpp
index 67bb19d4..3a3090f3 100644
--- a/src/app/PanelRetopo.cpp
+++ b/src/app/PanelRetopo.cpp
@@ -125,6 +125,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)};
+ if (const std::string notice = doc_.takeNotice(); !notice.empty()) r.message += ". " + notice; // levels dropped
status_ = r.message;
lastCommandOk_ = true;
clearLods();
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index 03edd06c..462eb683 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -780,7 +780,10 @@ CommandResult CommandRegistry::execute(Document& doc, const std::string& name, c
if (!cmd) return {false, "Unknown command: " + name};
for (const auto& p : cmd->params)
if (p.required && !args.contains(p.name)) return {false, "Missing required argument: " + p.name};
- return cmd->run(doc, args);
+ doc.notice.clear();
+ CommandResult r = cmd->run(doc, args);
+ if (const std::string notice = doc.takeNotice(); !notice.empty() && r.ok) r.message += ". " + notice;
+ return r;
}
std::string CommandRegistry::toolSchemaJson() const {
diff --git a/src/core/Document.cpp b/src/core/Document.cpp
index 11c4f40b..12754545 100644
--- a/src/core/Document.cpp
+++ b/src/core/Document.cpp
@@ -2,6 +2,8 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "core/Document.h"
+#include "core/Multires.h"
+
#include <filesystem>
#include <memory>
@@ -58,6 +60,7 @@ void Document::selectSubtool(int i) {
std::swap(cleanRevision_, s.cleanRevision);
};
swapIn(subtools[size_t(activeSubtool)]);
+ subdivReleaseCache(subtools[size_t(activeSubtool)].mesh); // only the active SubTool keeps cached levels
activeSubtool = i;
swapIn(subtools[size_t(i)]);
if (bvh.nodeCount() == 0 && mesh.triangleCount()) bvhDirty = true; // built on first use
@@ -150,6 +153,13 @@ std::string Document::assetName() const {
}
void Document::replaceMeshUndoable(Mesh m, std::string label) {
+ if (m.multires && !subdivMatches(m)) m.multires.reset();
+ if (mesh.multires && !m.multires) {
+ // A tool rebuilt the mesh from the current level: the levels go, the undo step keeps them.
+ if (const std::string note = subdivDroppedNote(mesh); !note.empty())
+ notice += (notice.empty() ? "" : "; ") + note + " (Undo brings them back)";
+ subdivReleaseCache(mesh);
+ }
UndoRecord r;
r.label = std::move(label);
r.mesh = std::make_unique<Mesh>(std::move(mesh));
diff --git a/src/core/Document.h b/src/core/Document.h
index 0506751a..144279f8 100644
--- a/src/core/Document.h
+++ b/src/core/Document.h
@@ -12,6 +12,7 @@
#include "core/Undo.h"
#include <string>
+#include <utility>
namespace sf {
@@ -113,9 +114,15 @@ struct Document {
// Replaces the whole scene with one SubTool holding `m` and clears the edit history.
void setMesh(Mesh m, std::string name = "Sculpt");
- // Replaces the mesh as an undoable topology change.
+ // Replaces the mesh as an undoable topology change. A result without the old mesh's subdivision levels (a
+ // remesh, decimate, ...) leaves a `notice` saying the levels were removed; undo brings them back.
void replaceMeshUndoable(Mesh m, std::string label);
+ // A note for the status line from the last operation, e.g. that subdivision levels were removed.
+ // CommandRegistry::execute adds it to the command's message; other callers take it with takeNotice().
+ std::string notice;
+ std::string takeNotice() { return std::exchange(notice, {}); }
+
private:
uint64_t cleanRevision_ = 0, cleanSplatsVersion_ = 0;
uint32_t nextSubtoolId_ = 2;
diff --git a/src/core/Multires.cpp b/src/core/Multires.cpp
index 1a270681..7fa12285 100644
--- a/src/core/Multires.cpp
+++ b/src/core/Multires.cpp
@@ -465,12 +465,21 @@ std::vector<T> subdivideField(const SubdivTopology& tp, bool smooth, const std::
// Vertex normals of `Q` on the fine triangles (area weighted).
std::vector<glm::vec3> fineNormals(const std::vector<glm::uvec3>& tris, const std::vector<glm::vec3>& Q) {
+ // Face normals in parallel, then summed per vertex in triangle order (so the result doesn't depend on the
+ // thread count).
+ std::vector<glm::vec3> f(tris.size());
+ parallelRange(tris.size(), [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ const glm::uvec3& t = tris[i];
+ f[i] = glm::cross(Q[t.y] - Q[t.x], Q[t.z] - Q[t.x]);
+ }
+ });
std::vector<glm::vec3> n(Q.size(), glm::vec3(0.0f));
- for (const auto& t : tris) {
- const glm::vec3 f = glm::cross(Q[t.y] - Q[t.x], Q[t.z] - Q[t.x]);
- n[t.x] += f;
- n[t.y] += f;
- n[t.z] += f;
+ for (size_t i = 0; i < tris.size(); ++i) {
+ const glm::uvec3& t = tris[i];
+ n[t.x] += f[i];
+ n[t.y] += f[i];
+ n[t.z] += f[i];
}
return n;
}
@@ -496,10 +505,10 @@ inline void frameAt(glm::vec3 n, const glm::vec3& q, const glm::vec3& qref, glm:
nn = n;
}
-// P[k] = Q + Frame(Q) * D, or D = Frame(Q)^-1 (P[k] - Q), with Q = the subdivided coarse shape.
-void applyDetail(const SubdivTopology& tp, const std::vector<glm::uvec3>& tris, const std::vector<glm::vec3>& Q,
+// P[k] = Q + Frame(Q) * D, or D = Frame(Q)^-1 (P[k] - Q), with Q = the subdivided coarse shape and n its
+// normals (fineNormals).
+void applyDetail(const SubdivTopology& tp, const std::vector<glm::vec3>& n, const std::vector<glm::vec3>& Q,
const std::vector<glm::vec3>& D, std::vector<glm::vec3>& out) {
- const std::vector<glm::vec3> n = fineNormals(tris, Q);
out.resize(Q.size());
parallelRange(Q.size(), [&](size_t b0, size_t e0) {
for (size_t v = b0; v < e0; ++v) {
@@ -510,9 +519,8 @@ void applyDetail(const SubdivTopology& tp, const std::vector<glm::uvec3>& tris,
}
});
}
-void fitDetail(const SubdivTopology& tp, const std::vector<glm::uvec3>& tris, const std::vector<glm::vec3>& Q,
+void fitDetail(const SubdivTopology& tp, const std::vector<glm::vec3>& n, const std::vector<glm::vec3>& Q,
const std::vector<glm::vec3>& P, std::vector<glm::vec3>& D) {
- const std::vector<glm::vec3> n = fineNormals(tris, Q);
D.resize(Q.size());
parallelRange(Q.size(), [&](size_t b0, size_t e0) {
for (size_t v = b0; v < e0; ++v) {
@@ -525,6 +533,34 @@ void fitDetail(const SubdivTopology& tp, const std::vector<glm::uvec3>& tris, co
});
}
+// Sculpt-layer details live in the same local frames as the shape's (the frames of Q, the subdivided coarse
+// base, with normals n = fineNormals(tris, Q)), so they turn with the surface. `out` += Frame(Q) * local.
+void addLayerDetail(const SubdivTopology& tp, const std::vector<glm::vec3>& n, const std::vector<glm::vec3>& Q,
+ const std::vector<glm::vec3>& local, std::vector<glm::vec3>& out) {
+ parallelRange(Q.size(), [&](size_t b0, size_t e0) {
+ for (size_t v = b0; v < e0; ++v) {
+ glm::vec3 t, b, nn;
+ const uint32_t r = tp.frameRef[v];
+ frameAt(n[v], Q[v], r == kNone ? Q[v] : Q[r], t, b, nn);
+ out[v] += t * local[v].x + b * local[v].y + nn * local[v].z;
+ }
+ });
+}
+// local = Frame(Q)^-1 * world.
+void layerDetailToLocal(const SubdivTopology& tp, const std::vector<glm::vec3>& n, const std::vector<glm::vec3>& Q,
+ const std::vector<glm::vec3>& world, std::vector<glm::vec3>& local) {
+ local.resize(Q.size());
+ parallelRange(Q.size(), [&](size_t b0, size_t e0) {
+ for (size_t v = b0; v < e0; ++v) {
+ glm::vec3 t, b, nn;
+ const uint32_t r = tp.frameRef[v];
+ frameAt(n[v], Q[v], r == kNone ? Q[v] : Q[r], t, b, nn);
+ const glm::vec3 d = world[v];
+ local[v] = {glm::dot(d, t), glm::dot(d, b), glm::dot(d, nn)};
+ }
+ });
+}
+
// --- Moving attributes between neighbouring levels. `flags` (null = every element) say which elements
// changed; the ones written are flagged in `outFlags`. ---
@@ -691,12 +727,19 @@ void evaluateLevel(MultiresStack& s, int k) {
Mesh& fine = mutableData(L);
const std::vector<glm::vec3> Q = subdivideField(tp, tp.smooth, baseChannel(coarse));
std::vector<glm::vec3>& target = baseChannel(fine);
- if (L.detail) applyDetail(tp, fine.triangles, Q, *L.detail, target);
- else target = Q;
+ std::vector<glm::vec3> n; // normals of Q, for the frames of the details
+ if (L.detail) {
+ n = fineNormals(fine.triangles, Q);
+ applyDetail(tp, n, Q, *L.detail, target);
+ } else {
+ target = Q;
+ }
for (size_t i = 0; i < fine.layers.size() && i < coarse.layers.size(); ++i) {
std::vector<glm::vec3> d = subdivideField(tp, tp.smooth, coarse.layers[i].delta);
- if (i < L.layerDetail.size() && L.layerDetail[i])
- for (size_t v = 0; v < d.size(); ++v) d[v] += (*L.layerDetail[i])[v];
+ if (i < L.layerDetail.size() && L.layerDetail[i]) {
+ if (n.empty()) n = fineNormals(fine.triangles, Q);
+ addLayerDetail(tp, n, Q, *L.layerDetail[i], d);
+ }
fine.layers[i].delta = std::move(d);
}
evaluateLayers(fine);
@@ -977,20 +1020,27 @@ void spreadUvs(MultiresStack& s, int c, const Mesh& w, const Mesh& r) {
void spreadShape(MultiresStack& s, int c, const Mesh& w, const Mesh& r) {
const size_t channels = 1 + w.layers.size();
bool anyChange = false;
+ // Per level: the subdivided coarse base and its normals (the layer details' frames), once the base channel
+ // (channel 0, done first) is final.
+ std::vector<std::vector<glm::vec3>> frameQ(size_t(c) + 1), frameN(size_t(c) + 1);
+ bool baseChanged = false;
for (size_t ch = 0; ch < channels; ++ch) {
const std::vector<glm::vec3>& wa = ch == 0 ? baseChannel(w) : w.layers[ch - 1].delta;
const std::vector<glm::vec3>& ra = ch == 0 ? baseChannel(r) : r.layers[ch - 1].delta;
- if (sameArray(wa, ra)) continue;
+ const bool same = sameArray(wa, ra);
+ // A changed base also changes the frames the layer details are kept in, so those are re-fitted too.
+ if (same && !(ch > 0 && baseChanged)) continue;
+ if (ch == 0) baseChanged = true;
anyChange = true;
// Restrict with full weighting (the transpose of linear interpolation): each coarse vertex moves by a
// blend of the change at its own fine vertex (weight 1), the edge points around it (1/2) and, for
// Catmull-Clark, the face points (1/4). Broad changes come through unchanged; narrow strokes show up
// softened instead of as spikes.
- std::vector<glm::vec3> delta(wa.size());
- parallelRange(wa.size(), [&](size_t b, size_t e) {
+ std::vector<glm::vec3> delta(same ? 0 : wa.size());
+ parallelRange(delta.size(), [&](size_t b, size_t e) {
for (size_t v = b; v < e; ++v) delta[v] = wa[v] - ra[v];
});
- for (int j = c; j >= 1; --j) {
+ for (int j = same ? 0 : c; j >= 1; --j) {
const SubdivTopology& tp = *s.levels[size_t(j)].topo;
std::vector<glm::vec3> cd(tp.coarseVertices);
parallelRange(tp.coarseVertices, [&](size_t b, size_t e) {
@@ -1025,13 +1075,24 @@ void spreadShape(MultiresStack& s, int c, const Mesh& w, const Mesh& r) {
const Mesh& cm = *s.levels[size_t(j) - 1].data;
const Mesh& fm = j == c ? w : *L.data;
const std::vector<glm::vec3>& fineVals = ch == 0 ? baseChannel(fm) : fm.layers[ch - 1].delta;
- const std::vector<glm::vec3> Q = subdivideField(tp, tp.smooth, ch == 0 ? baseChannel(cm) : cm.layers[ch - 1].delta);
+ std::vector<glm::vec3> Q = subdivideField(tp, tp.smooth, ch == 0 ? baseChannel(cm) : cm.layers[ch - 1].delta);
if (ch == 0) {
- fitDetail(tp, fm.triangles, Q, fineVals, mutableArray(L.detail, Q.size()));
+ std::vector<glm::vec3> n = fineNormals(fm.triangles, Q);
+ fitDetail(tp, n, Q, fineVals, mutableArray(L.detail, Q.size()));
+ if (channels > 1) { // the layer channels' frames
+ frameN[size_t(j)] = std::move(n);
+ frameQ[size_t(j)] = std::move(Q);
+ }
} else {
if (L.layerDetail.size() < w.layers.size()) L.layerDetail.resize(w.layers.size());
- std::vector<glm::vec3>& d = mutableArray(L.layerDetail[ch - 1], Q.size());
- for (size_t v = 0; v < Q.size(); ++v) d[v] = fineVals[v] - Q[v];
+ std::vector<glm::vec3>& fq = frameQ[size_t(j)];
+ if (fq.empty()) {
+ fq = subdivideField(tp, tp.smooth, baseChannel(cm));
+ frameN[size_t(j)] = fineNormals(fm.triangles, fq);
+ }
+ std::vector<glm::vec3> world(Q.size());
+ for (size_t v = 0; v < Q.size(); ++v) world[v] = fineVals[v] - Q[v];
+ layerDetailToLocal(tp, frameN[size_t(j)], fq, world, mutableArray(L.layerDetail[ch - 1], Q.size()));
}
}
}
@@ -1152,6 +1213,39 @@ size_t subdivBytes(const Mesh& mesh) {
return total;
}
+size_t subdivCacheBytes(const Mesh& mesh) {
+ if (!mesh.multires || !mesh.multires->cache) return 0;
+ size_t total = 0;
+ for (const SubdivLevelCache::Entry& e : mesh.multires->cache->entries) {
+ const Mesh& m = e.mesh;
+ // Positions, normals and the vertex adjacency; triangles, face normals, quads and the BVH (estimated).
+ total += m.vertexCount() * 80 + m.triangleCount() * 48 + m.base.size() * 12 + m.mask.size() * 4 +
+ m.colors.size() * 12 + m.polygroups.size() * 4 + m.hidden.size() + m.uvs.size() * 8 +
+ m.paintBase.size() * 12;
+ for (const SculptLayer& l : m.layers) total += l.delta.size() * 12;
+ for (const PaintLayer& p : m.paintLayers) total += p.color.size() * 12 + p.alpha.size() * 4;
+ }
+ return total;
+}
+
+void subdivReleaseCache(Mesh& mesh) {
+ // The cache is shared by every copy of the stack (undo steps): emptying it frees it for all of them.
+ if (mesh.multires && mesh.multires->cache) std::vector<SubdivLevelCache::Entry>().swap(mesh.multires->cache->entries);
+}
+
+std::string subdivDroppedNote(const Mesh& mesh, const std::string& name) {
+ if (!mesh.multires || mesh.multires->levels.size() < 2) return {};
+ return "Subdivision levels removed: " + (name.empty() ? std::string() : name + " ") + "SDiv " +
+ std::to_string(mesh.multires->current + 1) + " of " + std::to_string(mesh.multires->levels.size()) +
+ " kept as the new base";
+}
+
+void noteSubtoolLevelsDropped(Document& doc, int index) {
+ if (index < 0 || index >= doc.subtoolCount()) return;
+ const std::string note = subdivDroppedNote(doc.subtoolMesh(index), doc.subtools[size_t(index)].name);
+ if (!note.empty()) doc.notice += (doc.notice.empty() ? "" : "; ") + note;
+}
+
// --- Operations ---
bool subdivCommit(Mesh& w) {
@@ -1401,6 +1495,28 @@ bool attachSubdivStack(Mesh& mesh, MultiresStack stack, std::string& error) {
return true;
}
+void convertWorldLayerDetail(MultiresStack& s) {
+ bool any = false;
+ for (const SubdivLevel& l : s.levels)
+ for (const auto& d : l.layerDetail) any = any || bool(d);
+ if (!any) return;
+ for (size_t k = 1; k < s.levels.size(); ++k) {
+ SubdivLevel& L = s.levels[k];
+ if (!L.topo || !L.data) return;
+ // The frames come from the level below, evaluated with its details (converted already).
+ if (k >= 2 && s.levels[k - 1].stale) evaluateLevel(s, int(k) - 1);
+ const SubdivTopology& tp = *L.topo;
+ const std::vector<glm::vec3> Q = subdivideField(tp, tp.smooth, baseChannel(*s.levels[k - 1].data));
+ const std::vector<glm::vec3> n = fineNormals(L.data->triangles, Q);
+ for (auto& d : L.layerDetail) {
+ if (!d || d->size() != Q.size()) continue;
+ auto local = std::make_shared<std::vector<glm::vec3>>();
+ layerDetailToLocal(tp, n, Q, *d, *local);
+ d = std::move(local);
+ }
+ }
+}
+
const Mesh& subdivLevelData(const Mesh& mesh, int level) { return *mesh.multires->levels[size_t(level)].data; }
bool subdivInSync(const Mesh& mesh) {
@@ -1792,24 +1908,26 @@ bool subdivReconstruct(Mesh& mesh, std::string& error, BVH* bvh) {
}
SubdivLevel fineLevel;
fineLevel.topo = tp;
+ // The coarse base is the positions so far (the layers' offsets are added below).
+ const std::vector<glm::vec3> Q = subdivideField(*tp, true, coarse.positions);
if (!mesh.layers.empty()) {
coarse.base = coarse.positions;
+ const std::vector<glm::vec3> n = fineNormals(mesh.triangles, Q);
for (const SculptLayer& l : mesh.layers) {
SculptLayer cl{l.name, std::vector<glm::vec3>(nc), l.weight};
for (uint32_t v = 0; v < nc; ++v) cl.delta[v] = l.delta[rec.vertexChild[v]];
const std::vector<glm::vec3> s = subdivideField(*tp, true, cl.delta);
- auto d = std::make_shared<std::vector<glm::vec3>>(s.size());
- for (size_t v = 0; v < s.size(); ++v) (*d)[v] = l.delta[v] - s[v];
+ std::vector<glm::vec3> world(s.size());
+ for (size_t v = 0; v < s.size(); ++v) world[v] = l.delta[v] - s[v];
+ auto d = std::make_shared<std::vector<glm::vec3>>();
+ layerDetailToLocal(*tp, n, Q, world, *d);
fineLevel.layerDetail.push_back(std::move(d));
coarse.layers.push_back(std::move(cl));
}
evaluateLayers(coarse);
}
- {
- const std::vector<glm::vec3> Q = subdivideField(*tp, true, baseChannel(coarse));
- fineLevel.detail = std::make_shared<std::vector<glm::vec3>>();
- fitDetail(*tp, mesh.triangles, Q, fineBase, *fineLevel.detail);
- }
+ fineLevel.detail = std::make_shared<std::vector<glm::vec3>>();
+ fitDetail(*tp, fineNormals(mesh.triangles, Q), Q, fineBase, *fineLevel.detail);
MultiresStack& s = ensureStack(mesh);
fineLevel.data = s.levels[0].data;
fineLevel.stale = false;
diff --git a/src/core/Multires.h b/src/core/Multires.h
index 2193bb82..a01e8f89 100644
--- a/src/core/Multires.h
+++ b/src/core/Multires.h
@@ -22,7 +22,9 @@
// - mask, polypaint and paint layers (per vertex), polygroups and hidden faces (per triangle) and UVs (per
// corner) are copied down to the parent elements and interpolated / inherited up, only where they changed,
// so detail painted at a high level survives an edit somewhere else at a low level;
-// - sculpt layers are their own displacement channels (world space), subdivided with the same stencils;
+// - sculpt layers are their own displacement channels, subdivided with the same stencils; their per-level
+// detail is stored in the same local frame as the shape's, so a sculpt layer's fine offsets turn and bend
+// with a low level that is rotated (Gizmo 3D) or reshaped (project format 5; older files are converted);
// - the painted texture lives in UV space and is shared by every level.
// Stepping between levels that weren't edited copies the stored level back, so up / down round trips are
// bit-for-bit.
@@ -83,12 +85,15 @@ struct SubdivLevel {
std::shared_ptr<Mesh> data;
std::shared_ptr<const SubdivTopology> topo; // null for level 0
std::shared_ptr<std::vector<glm::vec3>> detail; // local-frame displacement (levels >= 1)
- std::vector<std::shared_ptr<std::vector<glm::vec3>>> layerDetail; // per sculpt layer, world space
+ // Per sculpt layer: its offsets minus the subdivided offsets of the level below, in the local frame of the
+ // subdivided shape (as `detail`), so they turn with the surface.
+ std::vector<std::shared_ptr<std::vector<glm::vec3>>> layerDetail;
bool stale = false;
};
// Working meshes (with topology and normals) and BVHs of the levels most recently left, so stepping back to
-// one is a move instead of a rebuild. Keyed by the level's data, so any change to the level misses.
+// one is a move instead of a rebuild. Keyed by the level's data, so any change to the level misses. Only the
+// active SubTool keeps one: Document::selectSubtool frees the cache of the SubTool it leaves (subdivReleaseCache).
struct SubdivLevelCache;
struct MultiresStack {
@@ -109,6 +114,21 @@ size_t subdivLevelTriangles(const Mesh& mesh, int level);
bool subdivMatches(const Mesh& mesh);
// Bytes the stack holds (all levels, details and topology), for the memory readout and tests.
size_t subdivBytes(const Mesh& mesh);
+// Bytes the level cache holds (cached working meshes and their BVHs; approximate).
+size_t subdivCacheBytes(const Mesh& mesh);
+// Frees the level cache (the next step to another level rebuilds it): for SubTools that aren't active and
+// meshes kept by undo steps.
+void subdivReleaseCache(Mesh& mesh);
+
+// --- Tools that rebuild the mesh (voxel remesh, decimate, QRemesh, Subdivide, Delete Hidden, merging and
+// splitting SubTools) work on the current level, pending edits included, and leave a plain mesh: the levels
+// are dropped and the current level becomes the new base. ---
+// The status-line note for dropping `mesh`'s levels: "Subdivision levels removed: SDiv 3 of 5 kept as the new
+// base". "" when the mesh has no levels. `name` (a SubTool name, optional) prefixes the level.
+std::string subdivDroppedNote(const Mesh& mesh, const std::string& name = {});
+// Adds the note for SubTool `index` (named) to doc.notice, for operations that aren't undoable (merging and
+// splitting SubTools). Nothing when it has no levels.
+void noteSubtoolLevelsDropped(Document& doc, int index);
// --- Operations on the mesh (no undo; see the commands / Document helpers below) ---
// Each returns false with `error` set when it can't run. All of them reconcile pending edits first.
@@ -143,6 +163,9 @@ std::shared_ptr<const SubdivTopology> rebuildSubdivTopology(const Mesh& coarse,
std::vector<uint32_t> faceChild, std::string& error);
// Gives a loaded mesh (the current level) its stack; false when the stack doesn't fit it.
bool attachSubdivStack(Mesh& mesh, MultiresStack stack, std::string& error);
+// Projects before format 5 stored sculpt-layer details in world space: converts a loaded stack's (with its
+// topology) to the local frames SubdivLevel::layerDetail uses now. Evaluates stale levels on the way.
+void convertWorldLayerDetail(MultiresStack& stack);
// The level data `level` keeps (for writing projects; may be stale, see SubdivLevel).
const Mesh& subdivLevelData(const Mesh& mesh, int level);
// True when the mesh holds no edits its stack hasn't folded in yet (its current level's data is the mesh).
diff --git a/src/core/Project.cpp b/src/core/Project.cpp
index 6ae8b36f..9cb496ba 100644
--- a/src/core/Project.cpp
+++ b/src/core/Project.cpp
@@ -438,8 +438,9 @@ bool readUintList(Reader& r, const Json& desc, const char* what, std::vector<uin
return r.uints(desc, what, n, 1, out.data());
}
-// Reads "subdiv" into `m` (the SubTool's current level). Levels that don't fit are an error.
-bool readSubdiv(Reader& r, const Json& sj, Mesh& m, std::string& error) {
+// Reads "subdiv" into `m` (the SubTool's current level). Levels that don't fit are an error. Format 4 kept the
+// sculpt-layer details in world space (`worldLayerDetail`): they're converted to local frames.
+bool readSubdiv(Reader& r, const Json& sj, Mesh& m, std::string& error, bool worldLayerDetail) {
if (!sj.isObject()) return true;
const Json& list = sj["levels"];
if (!list.isArray() || list.size() < 2 || list.size() > 32) {
@@ -521,6 +522,7 @@ bool readSubdiv(Reader& r, const Json& sj, Mesh& m, std::string& error) {
}
stack.levels.push_back(std::move(level));
}
+ if (worldLayerDetail) convertWorldLayerDetail(stack);
if (!attachSubdivStack(m, std::move(stack), error)) {
error = "Project " + error;
return false;
@@ -682,7 +684,7 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {
if (!readMesh(r, sj["mesh"], sj["layers"], s.mesh, error)) return false;
if (!readPaintLayers(r, sj["paint_layers"], s.mesh, error)) return false;
if (!readTexture(r, sj["texture"], s.mesh, error)) return false;
- if (!readSubdiv(r, sj["subdiv"], s.mesh, error)) return false;
+ if (!readSubdiv(r, sj["subdiv"], s.mesh, error, version < 5)) return false;
s.activeLayer = int(sj["active_layer"].asNumber(-1));
subtools.push_back(std::move(s));
}
diff --git a/src/core/Project.h b/src/core/Project.h
index fbf0bcb5..9b0ad807 100644
--- a/src/core/Project.h
+++ b/src/core/Project.h
@@ -22,8 +22,9 @@ namespace sf {
// 1: one mesh. 2: a list of SubTools (version 1 files still load, as one SubTool). 3: SubTools may carry a
// painted texture with layers ("texture"; older files still load). 4: SubTools may carry subdivision levels
-// ("subdiv"; older files still load).
-constexpr int kProjectVersion = 4;
+// ("subdiv"; older files still load). 5: sculpt-layer details of subdivision levels are in the levels' local
+// frames, not world space (format 4 files are converted when they load).
+constexpr int kProjectVersion = 5;
constexpr const char* kProjectExtension = ".sfproj";
// True for paths ending in .sfproj (any case).
diff --git a/src/core/SubTools.cpp b/src/core/SubTools.cpp
index 7556b577..c1611f98 100644
--- a/src/core/SubTools.cpp
+++ b/src/core/SubTools.cpp
@@ -179,6 +179,7 @@ CommandResult notFound(const Args& a) {
// Replaces SubTool `index` by `pieces`, named after it ("Body 1", "Body 2", ...); the first piece is selected.
void replaceWithPieces(Document& doc, int index, std::vector<Mesh> pieces) {
+ noteSubtoolLevelsDropped(doc, index); // the pieces are cut from the current level
const std::string base = doc.subtools[size_t(index)].name;
const bool visible = doc.subtools[size_t(index)].visible;
for (size_t k = 0; k < pieces.size(); ++k) {
@@ -364,6 +365,7 @@ void registerSubToolCommands(CommandRegistry& reg) {
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)});
+ for (int k : {i, i + 1}) noteSubtoolLevelsDropped(doc, k); // merged at their current levels
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));
@@ -379,6 +381,7 @@ void registerSubToolCommands(CommandRegistry& reg) {
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);
+ for (int k : visible) noteSubtoolLevelsDropped(doc, k); // merged at their current levels
const size_t tris = merged.triangleCount();
const int at = visible.front();
doc.addSubtool(std::move(merged), "Merged", true, at);
diff --git a/tests/data/levels_layers_v4.sfproj b/tests/data/levels_layers_v4.sfproj
new file mode 100644
index 00000000..835eb9a8
Binary files /dev/null and b/tests/data/levels_layers_v4.sfproj differ
diff --git a/tests/data/levels_layers_v4_top.sfproj b/tests/data/levels_layers_v4_top.sfproj
new file mode 100644
index 00000000..212ef933
Binary files /dev/null and b/tests/data/levels_layers_v4_top.sfproj differ
diff --git a/tests/test_multires_polish.cpp b/tests/test_multires_polish.cpp
new file mode 100644
index 00000000..ce0a14d2
--- /dev/null
+++ b/tests/test_multires_polish.cpp
@@ -0,0 +1,347 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Subdivision levels, polish: tools that rebuild the mesh say they drop the levels and undo brings them back,
+// sculpt-layer detail turns with the low level, and inactive SubTools don't keep cached levels.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/MeshTransform.h"
+#include "core/Multires.h"
+#include "core/Primitives.h"
+#include "core/Project.h"
+
+#include <glm/gtc/quaternion.hpp>
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <cstdlib>
+#include <cstring>
+#include <filesystem>
+
+using namespace sf;
+
+namespace {
+
+const CommandRegistry& registry() {
+ static CommandRegistry r;
+ return r;
+}
+
+CommandResult run(Document& d, const std::string& name, const Args& a = {}) {
+ CommandResult r = registry().execute(d, name, a);
+ if (!r.ok) std::printf(" (%s: %s)\n", name.c_str(), r.message.c_str());
+ return r;
+}
+
+bool stroke(Document& d, const std::string& points, const std::string& brush = "Standard", double radius = 0.3) {
+ return run(d, "stroke", {{"points", points}, {"brush", brush}, {"radius", radius}, {"strength", 0.8}}).ok;
+}
+
+float maxDistance(const std::vector<glm::vec3>& a, const std::vector<glm::vec3>& b) {
+ if (a.size() != b.size()) return 1e30f;
+ float m = 0.0f;
+ for (size_t i = 0; i < a.size(); ++i) m = std::max(m, glm::length(a[i] - b[i]));
+ return m;
+}
+
+bool bitEqual(const std::vector<glm::vec3>& a, const std::vector<glm::vec3>& b) {
+ return a.size() == b.size() && (a.empty() || std::memcmp(a.data(), b.data(), a.size() * sizeof(glm::vec3)) == 0);
+}
+
+bool contains(const std::string& s, const std::string& part) { return s.find(part) != std::string::npos; }
+
+// A cube divided twice, detail at the top, then a pending (not yet folded in) stroke at SDiv 2 of 3.
+Document levelledCube() {
+ Document d = makeDoc(makeCube(4));
+ run(d, "subdiv_divide");
+ run(d, "subdiv_divide");
+ stroke(d, "0,0,2");
+ run(d, "subdiv_level", {{"level", 2.0}});
+ stroke(d, "0.3,0.3,2", "Inflate", 0.5);
+ return d;
+}
+
+double msSince(std::chrono::steady_clock::time_point t0) {
+ return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
+}
+
+} // namespace
+
+// Timing of selecting SubTools and stepping levels on a 1.77M-triangle top level (SF_LEVELS_BENCH=1).
+TEST(multires_bench_select_and_step) {
+ if (!std::getenv("SF_LEVELS_BENCH")) return;
+ Document d = makeDoc(makeCube(3));
+ for (int i = 0; i < 7; ++i) run(d, "subdiv_divide");
+ d.addSubtool(makeIcosphere(3), "Eye", false);
+ std::printf(" top level: %zu triangles\n", d.mesh.triangleCount());
+ // Fill the level cache: down and back up.
+ run(d, "subdiv_lower");
+ std::printf(" level cache at SDiv 7: %.0f MB (the top level), ", double(subdivCacheBytes(d.mesh)) / 1e6);
+ run(d, "subdiv_higher");
+ std::printf("at SDiv 8: %.0f MB; the levels themselves %.0f MB\n", double(subdivCacheBytes(d.mesh)) / 1e6,
+ double(subdivBytes(d.mesh)) / 1e6);
+ for (int round = 0; round < 3; ++round) {
+ auto t0 = std::chrono::steady_clock::now();
+ d.selectSubtool(1);
+ const double away = msSince(t0);
+ t0 = std::chrono::steady_clock::now();
+ d.selectSubtool(0);
+ const double back = msSince(t0);
+ t0 = std::chrono::steady_clock::now();
+ run(d, "subdiv_lower");
+ const double down = msSince(t0);
+ t0 = std::chrono::steady_clock::now();
+ run(d, "subdiv_higher");
+ const double up = msSince(t0);
+ t0 = std::chrono::steady_clock::now();
+ run(d, "subdiv_lower");
+ const double down2 = msSince(t0);
+ run(d, "subdiv_higher");
+ std::printf(" select away %.1f ms, select back %.1f ms, then step down %.1f ms, up %.1f ms, down again %.1f ms\n",
+ away, back, down, up, down2);
+ }
+ // Sculpt layers across levels: a layer stroke at the top folded in on the way down, a base stroke one level
+ // down, re-evaluating the top (with its layer) on the way up.
+ run(d, "layer_add", {{"name", "Scales"}});
+ d.activeLayer = 0;
+ stroke(d, "0,0,2", "Standard", 0.2);
+ auto t0 = std::chrono::steady_clock::now();
+ run(d, "subdiv_lower");
+ const double fold = msSince(t0);
+ d.activeLayer = -1;
+ stroke(d, "0.3,0,2", "Inflate", 0.5);
+ t0 = std::chrono::steady_clock::now();
+ run(d, "subdiv_higher");
+ const double eval = msSince(t0);
+ std::printf(" with a sculpt layer: step down folding a layer stroke in %.1f ms, step up re-evaluating %.1f ms\n", fold, eval);
+}
+
+// Every tool that rebuilds the mesh works on the current level (pending edits included), says the levels were
+// removed, and undo brings back the whole stack: every level as it was, at the level the user was on.
+TEST(multires_rebuilding_tools_drop_levels_and_undo_restores_them) {
+ struct Case {
+ const char* command;
+ Args args;
+ };
+ const Case cases[] = {
+ {"remesh", {{"resolution", 40.0}}},
+ {"decimate", {{"ratio", 0.5}}},
+ {"qremesh", {{"target", 150.0}}},
+ {"subdivide", {}},
+ {"delete_hidden", {}},
+ };
+ for (const Case& c : cases) {
+ std::printf(" %s\n", c.command);
+ Document d = levelledCube();
+ if (std::string(c.command) == "delete_hidden")
+ for (uint32_t t = 0; t < 40; ++t) d.mesh.ensureHidden()[t] = 1; // hidden at this level, pending
+ CHECK(subdivLevelText(d.mesh) == "SDiv 2/3");
+ CHECK(!subdivInSync(d.mesh)); // the stroke at SDiv 2 is still pending
+ const std::vector<glm::vec3> working = d.mesh.positions;
+ const size_t tris = d.mesh.triangleCount();
+ std::vector<std::vector<glm::vec3>> levels;
+ for (int i = 0; i < 3; ++i) levels.push_back(subdivLevelMesh(d.mesh, i).positions);
+ const AABB box = d.mesh.bounds();
+
+ const CommandResult r = run(d, c.command, c.args);
+ CHECK(r.ok);
+ CHECK(contains(r.message, "Subdivision levels removed: SDiv 2 of 3 kept as the new base"));
+ CHECK(contains(r.message, "Undo"));
+ CHECK(subdivLevelCount(d.mesh) == 0);
+ CHECK(d.notice.empty());
+ // Made from the current level, with the pending stroke.
+ const std::string cmd = c.command;
+ if (cmd == "subdivide") CHECK(d.mesh.triangleCount() == tris * 4);
+ if (cmd == "delete_hidden") {
+ CHECK(d.mesh.triangleCount() == tris - 40);
+ for (const glm::vec3& p : d.mesh.positions) CHECK(std::find(working.begin(), working.end(), p) != working.end());
+ }
+ if (cmd == "decimate") CHECK(d.mesh.triangleCount() <= tris / 2 + 2);
+ const AABB after = d.mesh.bounds();
+ CHECK(glm::length(after.min - box.min) < 0.1f && glm::length(after.max - box.max) < 0.1f);
+
+ // Undo: the whole stack, at SDiv 2 with the pending stroke, and every level as it was.
+ CHECK(run(d, "undo").ok);
+ CHECK(subdivLevelText(d.mesh) == "SDiv 2/3");
+ CHECK(bitEqual(d.mesh.positions, working));
+ for (int i : {2, 0, 1}) {
+ CHECK(run(d, "subdiv_level", {{"level", double(i + 1)}}).ok);
+ CHECK(maxDistance(d.mesh.positions, levels[size_t(i)]) < 1e-5f);
+ }
+ // Again from SDiv 2: redo drops the levels again, undo once more brings them back.
+ CHECK(run(d, c.command, c.args).ok);
+ CHECK(subdivLevelCount(d.mesh) == 0);
+ CHECK(run(d, "undo").ok);
+ CHECK(subdivLevelText(d.mesh) == "SDiv 2/3");
+ CHECK(run(d, "redo").ok);
+ CHECK(subdivLevelCount(d.mesh) == 0);
+ CHECK(run(d, "undo").ok);
+ CHECK(subdivLevelText(d.mesh) == "SDiv 2/3");
+ CHECK(maxDistance(d.mesh.positions, levels[1]) < 1e-5f);
+ }
+ // Without levels there's no note.
+ Document p = makeDoc(makeCube(4));
+ CHECK(!contains(run(p, "decimate", {{"ratio", 0.5}}).message, "Subdivision"));
+}
+
+// Merging and splitting SubTools (not undoable) use each SubTool's current level and say so.
+TEST(multires_merge_and_split_say_levels_are_removed) {
+ Document d = levelledCube();
+ d.subtools[0].name = "Body";
+ const size_t current = d.mesh.triangleCount();
+ d.addSubtool(makeIcosphere(1), "Eye", false);
+ CommandResult r = run(d, "subtool_merge_down");
+ CHECK(r.ok);
+ CHECK(contains(r.message, "Subdivision levels removed: Body SDiv 2 of 3 kept as the new base"));
+ CHECK(d.mesh.triangleCount() == current + makeIcosphere(1).triangleCount());
+ CHECK(subdivLevelCount(d.mesh) == 0);
+ // Split: pieces of the current level.
+ Document t = levelledCube();
+ for (uint32_t i = 0; i < t.mesh.triangleCount(); ++i) t.mesh.ensurePolygroups()[i] = i < 100 ? 1 : 2;
+ r = run(t, "subtool_split_groups");
+ CHECK(r.ok);
+ CHECK(contains(r.message, "Subdivision levels removed: Sculpt SDiv 2 of 3 kept as the new base"));
+ CHECK(t.mesh.triangleCount() == 100 || t.subtoolMesh(0).triangleCount() == 100);
+ // Merge visible: both SubTools with levels are named.
+ Document m = levelledCube();
+ m.addSubtool(makeCube(2), "Box", true);
+ run(m, "subdiv_divide");
+ r = run(m, "subtool_merge_visible");
+ CHECK(r.ok);
+ CHECK(contains(r.message, "Sculpt SDiv 2 of 3"));
+ CHECK(contains(r.message, "Box SDiv 2 of 2"));
+}
+
+namespace {
+
+// Each vertex's sculpt-layer offset at the top level: positions at weight 1 minus positions at weight 0.
+std::vector<glm::vec3> layerOffsets(Document& d) {
+ CHECK(run(d, "layer_set_weight", {{"index", 0.0}, {"weight", 0.0}}).ok);
+ const std::vector<glm::vec3> off = d.mesh.positions;
+ CHECK(run(d, "layer_set_weight", {{"index", 0.0}, {"weight", 1.0}}).ok);
+ std::vector<glm::vec3> o(off.size());
+ for (size_t v = 0; v < o.size(); ++v) o[v] = d.mesh.positions[v] - off[v];
+ return o;
+}
+
+float maxLength(const std::vector<glm::vec3>& a) {
+ float m = 0.0f;
+ for (const auto& v : a) m = std::max(m, glm::length(v));
+ return m;
+}
+
+} // namespace
+
+// A sculpt layer's fine detail turns with a low level rotated by the gizmo (the transform command).
+TEST(multires_layer_detail_turns_with_a_rotated_low_level) {
+ Document d = makeDoc(makeCube(3));
+ run(d, "subdiv_divide");
+ run(d, "subdiv_divide");
+ CHECK(run(d, "layer_add", {{"name", "Scales"}}).ok);
+ d.activeLayer = 0;
+ for (int i = 0; i < 4; ++i) {
+ CHECK(stroke(d, "0,0,2", "Standard", 0.25));
+ CHECK(stroke(d, "0.4,-0.2,2 0.5,0.3,2", "Standard", 0.12));
+ }
+ const std::vector<glm::vec3> before = layerOffsets(d);
+ const std::vector<glm::vec3> top = d.mesh.positions;
+ CHECK(maxLength(before) > 0.02f);
+
+ CHECK(run(d, "subdiv_level", {{"level", 1.0}}).ok);
+ CHECK(run(d, "transform", {{"rotate", "0,90,0"}, {"pivot", "origin"}}).ok);
+ CHECK(run(d, "subdiv_level", {{"level", 3.0}}).ok);
+ const glm::mat3 R = glm::mat3_cast(eulerRotation(glm::vec3(0, 90, 0)));
+ // The whole top level turned, layer included, and so did each vertex's layer offset.
+ std::vector<glm::vec3> turned(top.size()), turnedOffsets(before.size());
+ for (size_t v = 0; v < top.size(); ++v) turned[v] = R * top[v];
+ for (size_t v = 0; v < before.size(); ++v) turnedOffsets[v] = R * before[v];
+ const std::vector<glm::vec3> after = layerOffsets(d);
+ std::printf(" top level %.2g from the turned shape, layer offsets %.2g from the turned ones (largest offset %.2g)\n",
+ maxDistance(d.mesh.positions, turned), maxDistance(after, turnedOffsets), maxLength(before));
+ CHECK(maxDistance(d.mesh.positions, turned) < 1e-4f);
+ CHECK(maxDistance(after, turnedOffsets) < 1e-4f);
+ // (Kept in world space, the fine part of the offsets would still point the old way.)
+ CHECK(maxDistance(after, before) > 0.5f * maxLength(before));
+
+ // Saved and loaded (format 5), the same.
+ const std::string path = tempPath("sf_multires_layer_frames.sfproj");
+ std::string err;
+ CHECK(saveProject(path, d, err));
+ Document e;
+ CHECK(loadProject(path, e, err));
+ CHECK(run(e, "subdiv_level", {{"level", 1.0}}).ok);
+ CHECK(run(e, "subdiv_level", {{"level", 3.0}}).ok);
+ CHECK(maxDistance(e.mesh.positions, d.mesh.positions) < 1e-5f);
+ std::filesystem::remove(path);
+}
+
+// Format 4 projects kept sculpt-layer details in world space: they load converted, so the levels evaluate as
+// they did (tests/data/levels_layers_v4*.sfproj were saved by 0.4.2 + levels: a layer sculpted at SDiv 3, then a
+// stroke on the base at SDiv 1, saved there with SDiv 2 and 3 waiting to be re-evaluated; and the same at SDiv 3).
+TEST(multires_format4_layer_detail_is_converted) {
+ Document ref, d;
+ std::string err;
+ CHECK(loadProject(SF_TEST_DATA_DIR "/levels_layers_v4_top.sfproj", ref, err));
+ CHECK(loadProject(SF_TEST_DATA_DIR "/levels_layers_v4.sfproj", d, err));
+ CHECK(subdivLevelText(ref.mesh) == "SDiv 3/3" && subdivLevelText(d.mesh) == "SDiv 1/3");
+ CHECK(run(d, "subdiv_level", {{"level", 3.0}}).ok);
+ CHECK(d.mesh.layers.size() == 1 && ref.mesh.layers.size() == 1);
+ if (d.mesh.layers.size() != 1 || ref.mesh.layers.size() != 1) return;
+ std::printf(" top level %.2g from 0.4.2's, layer %.2g\n", maxDistance(d.mesh.positions, ref.mesh.positions),
+ maxDistance(d.mesh.layers[0].delta, ref.mesh.layers[0].delta));
+ CHECK(maxDistance(d.mesh.positions, ref.mesh.positions) < 1e-5f);
+ CHECK(maxDistance(d.mesh.base, ref.mesh.base) < 1e-5f);
+ CHECK(maxDistance(d.mesh.layers[0].delta, ref.mesh.layers[0].delta) < 1e-5f);
+ // And the converted details turn with the base.
+ const std::vector<glm::vec3> before = layerOffsets(d), top = d.mesh.positions;
+ CHECK(run(d, "subdiv_level", {{"level", 1.0}}).ok);
+ CHECK(run(d, "transform", {{"rotate", "0,0,90"}, {"pivot", "origin"}}).ok);
+ CHECK(run(d, "subdiv_level", {{"level", 3.0}}).ok);
+ const glm::mat3 R = glm::mat3_cast(eulerRotation(glm::vec3(0, 0, 90)));
+ std::vector<glm::vec3> turned(top.size()), turnedOffsets(before.size());
+ for (size_t v = 0; v < top.size(); ++v) turned[v] = R * top[v];
+ for (size_t v = 0; v < before.size(); ++v) turnedOffsets[v] = R * before[v];
+ CHECK(maxDistance(d.mesh.positions, turned) < 1e-4f);
+ CHECK(maxDistance(layerOffsets(d), turnedOffsets) < 1e-4f);
+ // Saved again, it's format 5.
+ const std::string path = tempPath("sf_levels_v5.sfproj");
+ CHECK(saveProject(path, d, err));
+ Document e;
+ CHECK(loadProject(path, e, err));
+ CHECK(maxDistance(e.mesh.positions, d.mesh.positions) < 1e-6f);
+ std::filesystem::remove(path);
+}
+
+// Only the active SubTool keeps cached levels: leaving a SubTool frees its cache, and stepping levels after
+// coming back still works (the level is rebuilt once).
+TEST(multires_inactive_subtools_free_their_level_cache) {
+ Document d = makeDoc(makeCube(4));
+ for (int i = 0; i < 3; ++i) run(d, "subdiv_divide");
+ stroke(d, "0,0,2");
+ CHECK(run(d, "subdiv_lower").ok);
+ CHECK(run(d, "subdiv_higher").ok);
+ const size_t cached = subdivCacheBytes(d.mesh);
+ const size_t stackBytes = subdivBytes(d.mesh);
+ std::printf(" cache %zu bytes, stack %zu bytes\n", cached, stackBytes);
+ CHECK(cached > d.mesh.triangleCount() * 12); // at least the level left
+ const std::vector<glm::vec3> top = d.mesh.positions;
+ d.addSubtool(makeIcosphere(1), "Eye", true); // selects the new SubTool
+ CHECK(subdivCacheBytes(d.subtoolMesh(0)) == 0);
+ CHECK(subdivBytes(d.subtoolMesh(0)) == stackBytes); // the levels themselves are kept
+ d.selectSubtool(0);
+ CHECK(subdivLevelText(d.mesh) == "SDiv 4/4");
+ CHECK(bitEqual(d.mesh.positions, top));
+ CHECK(run(d, "subdiv_lower").ok);
+ CHECK(run(d, "subdiv_higher").ok);
+ CHECK(bitEqual(d.mesh.positions, top));
+ CHECK(subdivCacheBytes(d.mesh) > 0);
+ // A mesh kept by an undo step after a remesh holds no cache either.
+ CHECK(run(d, "decimate", {{"ratio", 0.5}}).ok);
+ CHECK(run(d, "undo").ok);
+ CHECK(subdivCacheBytes(d.mesh) == 0);
+ CHECK(run(d, "subdiv_lower").ok);
+ CHECK(run(d, "subdiv_higher").ok);
+ CHECK(bitEqual(d.mesh.positions, top));
+}