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.

Tool > Geometry subdivision levels UI: Divide/Smt, Lower/Higher Res (Shift+D / D), SDiv slider, Del Lower/Higher, Reconstruct

islandmed97dda3d2d089
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 0f8ca45d..d133e502 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -162,6 +162,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/PanelPolypaint.cpp
src/app/PanelPaintLayers.cpp
src/app/PanelTexture.cpp
+ src/app/PanelGeometry.cpp
src/app/PanelGoz.cpp
src/app/PanelProject.cpp
src/app/PanelSubTools.cpp
diff --git a/docs/guide/shortcuts.md b/docs/guide/shortcuts.md
index 22c06d98..1d1f86f1 100644
--- a/docs/guide/shortcuts.md
+++ b/docs/guide/shortcuts.md
@@ -116,7 +116,9 @@ action registry, the same source as the Controls window.
| Action | Keys | What it does |
|---|---|---|
-| Subdivide | <kbd>Ctrl</kbd>+<kbd>D</kbd> | Smoothly subdivide the mesh (Loop subdivision). Each level multiplies the triangle count by 4. |
+| Divide | <kbd>Ctrl</kbd>+<kbd>D</kbd> | Add a subdivision level: four times the polygons, and the lower levels are kept, so you can step down to shape big forms and back up to the detail. Quads stay quads (Catmull-Clark). Smt off divides without smoothing. |
+| Higher Res | <kbd>D</kbd> | Step one subdivision level up (more polygons, for detail). Edits made below carry the detail along. |
+| Lower Res | <kbd>Shift</kbd>+<kbd>D</kbd> | Step one subdivision level down (fewer polygons, for big forms). The detail of the higher levels is kept. |
### Transform
diff --git a/src/app/App.h b/src/app/App.h
index 0dfc4869..86c22cc6 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -558,6 +558,10 @@ private:
float paintOpacityDrag_ = -1.0f; // opacity before the slider drag (-1 = not dragging)
void drawGameExportContents();
void drawVisibilitySection();
+ void drawGeometrySection(); // PanelGeometry.cpp: Divide, SDiv, Lower / Higher Res, Del Lower / Higher, Reconstruct
+ bool smt_ = true; // Tool > Geometry > Smt: Divide smooths
+ float sdivSlider_ = 1.0f; // the SDiv slider while dragged (1-based)
+ bool sdivHeld_ = false;
void drawSubToolsContents();
void pollAlphaFile();
ShellGeometry shell_; // this frame's regions (drawShell)
diff --git a/src/app/Config.cpp b/src/app/Config.cpp
index 9af3f796..61f287fd 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -9,6 +9,7 @@
#include "app/App.h"
#include "app/Ui.h"
+#include "core/Multires.h"
#include "core/Script.h"
#include <IconsLucide.h>
@@ -193,7 +194,29 @@ void App::initActions() {
[this] { return doc_.undo.canUndo(); });
add("edit.redo", "Redo", "Edit", "Ctrl+Shift+Z / Ctrl+Y", [this] { runCommand("redo"); }, ICON_LC_REDO_2, "redo", nullptr,
[this] { return doc_.undo.canRedo(); });
- add("geometry.subdivide", "Subdivide", "Tool > Geometry", "Ctrl+D", [this] { runCommand("subdivide"); }, nullptr, "subdivide");
+ add("geometry.subdivide", "Subdivide", "Tool > Geometry", nullptr, [this] { runCommand("subdivide"); }, nullptr, "subdivide");
+ // Subdivision levels (ZBrush Tool > Geometry; core/Multires.h).
+ add("geometry.divide", "Divide", "Tool > Geometry", "Ctrl+D", [this] { runCommand("subdiv_divide", {{"smooth", smt_}}); },
+ ICON_LC_GRID_2X2, "subdiv_divide", nullptr, nullptr,
+ "Add a subdivision level: four times the polygons, and the lower levels are kept, so you can step down to "
+ "shape big forms and back up to the detail. Quads stay quads (Catmull-Clark). Smt off divides without smoothing.");
+ add("geometry.smt", "Smt", "Tool > Geometry", nullptr, [this] { smt_ = !smt_; }, nullptr, nullptr,
+ [this] { return smt_; }, nullptr,
+ "Smooth the next Divide (on by default). Off: the new level keeps the hard edges and flat faces of the one below.");
+ add("geometry.lower_res", "Lower Res", "Tool > Geometry", "Shift+D", [this] { runCommand("subdiv_lower"); },
+ ICON_LC_CHEVRON_DOWN, "subdiv_lower", nullptr, [this] { return subdivCurrentLevel(doc_.mesh) > 0; },
+ "Step one subdivision level down (fewer polygons, for big forms). The detail of the higher levels is kept.");
+ add("geometry.higher_res", "Higher Res", "Tool > Geometry", "D", [this] { runCommand("subdiv_higher"); },
+ ICON_LC_CHEVRON_UP, "subdiv_higher", nullptr,
+ [this] { return subdivCurrentLevel(doc_.mesh) + 1 < subdivLevelCount(doc_.mesh); },
+ "Step one subdivision level up (more polygons, for detail). Edits made below carry the detail along.");
+ add("geometry.del_lower", "Del Lower", "Tool > Geometry", nullptr, [this] { runCommand("subdiv_delete_lower"); }, nullptr,
+ "subdiv_delete_lower", nullptr, [this] { return subdivCurrentLevel(doc_.mesh) > 0; });
+ add("geometry.del_higher", "Del Higher", "Tool > Geometry", nullptr, [this] { runCommand("subdiv_delete_higher"); }, nullptr,
+ "subdiv_delete_higher", nullptr,
+ [this] { return subdivCurrentLevel(doc_.mesh) + 1 < subdivLevelCount(doc_.mesh); });
+ add("geometry.reconstruct", "Reconstruct Subdiv", "Tool > Geometry", nullptr, [this] { runCommand("subdiv_reconstruct"); },
+ nullptr, "subdiv_reconstruct", nullptr, [this] { return subdivCurrentLevel(doc_.mesh) == 0; });
add("file.new_sphere", "New Sphere", "File", "Ctrl+N", [this] { confirmDiscard([this] { runCommand("new_sphere"); }); },
ICON_LC_FILE_PLUS, "new_sphere");
add("file.new_plane", "New Plane", "File", nullptr, [this] { confirmDiscard([this] { runCommand("new_plane"); }); }, nullptr,
diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cpp
index 563a96c7..dc788860 100644
--- a/src/app/Palettes.cpp
+++ b/src/app/Palettes.cpp
@@ -358,6 +358,8 @@ void App::drawPalette_Tool() {
Demo::popScope();
}
if (subpalette("tool.geometry", "Geometry")) {
+ Demo::pushScope("Geometry");
+ drawGeometrySection();
actionRow(*this, {"geometry.subdivide"});
const float half = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;
if (ImGui::Button("Decimate", ImVec2(half, 0))) runCommand("decimate", {{"ratio", double(decimateRatio_)}});
@@ -367,6 +369,7 @@ void App::drawPalette_Tool() {
ImGui::SetNextItemWidth(-1);
ui::SliderInside("##decimate", &decimateRatio_, 0.05f, 0.95f, "Keep %.2f");
ui::HelpText("Keep", nullptr, "Fraction of the triangles Decimate keeps.", "Tool > Geometry");
+ Demo::popScope();
}
if (subpalette("tool.remesh", "Remesh")) {
const float half = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;
diff --git a/src/app/PanelGeometry.cpp b/src/app/PanelGeometry.cpp
new file mode 100644
index 00000000..3b478e7f
--- /dev/null
+++ b/src/app/PanelGeometry.cpp
@@ -0,0 +1,68 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Tool > Geometry: subdivision levels, as in ZBrush (Lower Res / Higher Res, SDiv, Del Lower / Del Higher,
+// Reconstruct Subdiv, Divide with Smt). The levels themselves live in core/Multires.
+#include "app/App.h"
+#include "app/Ui.h"
+
+#include "core/Multires.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <string>
+
+namespace sf {
+
+void App::drawGeometrySection() {
+ const Mesh& m = doc_.mesh;
+ const int levels = subdivLevelCount(m), current = subdivCurrentLevel(m);
+ const ImGuiStyle& style = ImGui::GetStyle();
+ const float half = (ImGui::GetContentRegionAvail().x - style.ItemSpacing.x) * 0.5f;
+
+ ui::ActionButton(*this, "geometry.lower_res", ImVec2(half, 0));
+ ImGui::SameLine();
+ ui::ActionButton(*this, "geometry.higher_res", ImVec2(half, 0));
+
+ // SDiv: the level slider (1 = the base cage). Applied when released, as one undo step.
+ ImGui::BeginDisabled(levels < 2);
+ if (!sdivHeld_) sdivSlider_ = float(current + 1);
+ ImGui::SetNextItemWidth(-1);
+ char format[32];
+ std::snprintf(format, sizeof format, "SDiv %%.0f / %d", std::max(levels, 1));
+ ui::SliderInside("##sdiv", &sdivSlider_, 1.0f, float(std::max(levels, 1)), format, ImGuiSliderFlags_AlwaysClamp);
+ sdivHeld_ = ImGui::IsItemActive();
+ sdivSlider_ = std::round(sdivSlider_);
+ if (ImGui::IsItemDeactivatedAfterEdit() && int(sdivSlider_) - 1 != current)
+ runCommand("subdiv_level", {{"level", double(sdivSlider_)}});
+ ImGui::EndDisabled();
+ ui::HelpText("SDiv", nullptr,
+ "The subdivision level to sculpt at: 1 is the base cage, the highest has the finest detail. "
+ "D / Shift+D step up / down. Detail is kept on every level.",
+ "Tool > Geometry");
+
+ ui::ActionButton(*this, "geometry.del_lower", ImVec2(half, 0));
+ ImGui::SameLine();
+ ui::ActionButton(*this, "geometry.del_higher", ImVec2(half, 0));
+ ui::ActionButton(*this, "geometry.reconstruct", ImVec2(-1, 0));
+
+ // Divide with its Smt toggle beside it, as in ZBrush.
+ const float smtW = ImGui::CalcTextSize("Smt").x + 2.0f * style.FramePadding.x + 6.0f * uiScale_;
+ ui::ActionButton(*this, "geometry.divide", ImVec2(ImGui::GetContentRegionAvail().x - smtW - style.ItemSpacing.x, 0),
+ ui::Look::IconLabel);
+ ImGui::SameLine();
+ ui::ActionButton(*this, "geometry.smt", ImVec2(-1, 0));
+
+ if (levels) {
+ char info[96];
+ std::snprintf(info, sizeof info, "SDiv %d of %d - base %zu, top %zu triangles", current + 1, levels,
+ subdivLevelTriangles(m, 0), subdivLevelTriangles(m, levels - 1));
+ ImGui::TextDisabled("%s", info);
+ } else {
+ ImGui::TextDisabled("No subdivision levels - Divide adds them");
+ }
+ ImGui::Separator();
+}
+
+} // namespace sf
diff --git a/src/app/PanelSubTools.cpp b/src/app/PanelSubTools.cpp
index c7e4ed9e..6db1a726 100644
--- a/src/app/PanelSubTools.cpp
+++ b/src/app/PanelSubTools.cpp
@@ -6,6 +6,7 @@
// the ZBrush viewport gesture Alt+click to select a SubTool. Every action goes
// through the subtool_* commands (core/SubTools.cpp).
#include "app/App.h"
+#include "core/Multires.h"
#include <algorithm>
#include <cmath>
@@ -120,10 +121,14 @@ void App::drawSubToolsContents() {
const float rowH = ImGui::GetTextLineHeight() + 2.0f * cellPad.y;
const float listH = rowH * float(std::min(count, kListRows)) + 2.0f;
ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, cellPad);
- if (ImGui::BeginTable("##subtools", 3, ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter,
+ if (ImGui::BeginTable("##subtools", 4, ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter,
ImVec2(-1, listH))) {
const float eyeW = ImGui::GetTextLineHeight() * 1.2f;
ImGui::TableSetupColumn("name", ImGuiTableColumnFlags_WidthStretch);
+ // Subdivision levels, as ZBrush lists them ("SDiv 3/5"); empty for meshes without levels.
+ bool anyLevels = false;
+ for (int i = 0; i < count && !anyLevels; ++i) anyLevels = subdivLevelCount(doc_.subtoolMesh(i)) > 0;
+ ImGui::TableSetupColumn("sdiv", ImGuiTableColumnFlags_WidthFixed, anyLevels ? ImGui::CalcTextSize("SDiv 8/8").x : 0.0f);
ImGui::TableSetupColumn("tris", ImGuiTableColumnFlags_WidthFixed, ImGui::CalcTextSize("0.00M").x);
ImGui::TableSetupColumn("eye", ImGuiTableColumnFlags_WidthFixed, eyeW);
for (int i = 0; i < count; ++i) {
@@ -163,8 +168,10 @@ void App::drawSubToolsContents() {
std::snprintf(renameBuffer_, sizeof renameBuffer_, "%s", s.name.c_str());
}
if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal))
- ImGui::SetTooltip("%s\n%zu vertices, %zu triangles\nClick to select, double-click to rename",
- s.name.c_str(), doc_.subtoolMesh(i).vertexCount(), doc_.subtoolMesh(i).triangleCount());
+ ImGui::SetTooltip("%s\n%zu vertices, %zu triangles%s%s\nClick to select, double-click to rename",
+ s.name.c_str(), doc_.subtoolMesh(i).vertexCount(), doc_.subtoolMesh(i).triangleCount(),
+ subdivLevelCount(doc_.subtoolMesh(i)) ? ", " : "",
+ subdivLevelText(doc_.subtoolMesh(i)).c_str());
if (ImGui::BeginPopupContextItem("##row")) {
ImGui::TextDisabled("%s", s.name.c_str());
if (ImGui::MenuItem("Rename")) {
@@ -182,12 +189,18 @@ void App::drawSubToolsContents() {
}
}
ImGui::TableSetColumnIndex(1);
+ if (const std::string sdiv = subdivLevelText(doc_.subtoolMesh(i)); !sdiv.empty()) {
+ ImVec4 col = style.Colors[isActive ? ImGuiCol_Text : ImGuiCol_TextDisabled];
+ if (isActive) col.w *= 0.75f;
+ ImGui::TextColored(col, "%s", sdiv.c_str());
+ }
+ ImGui::TableSetColumnIndex(2);
const std::string tris = shortCount(doc_.subtoolMesh(i).triangleCount());
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x - ImGui::CalcTextSize(tris.c_str()).x);
ImVec4 trisCol = style.Colors[isActive ? ImGuiCol_Text : ImGuiCol_TextDisabled];
if (isActive) trisCol.w *= 0.75f; // readable on the highlight
ImGui::TextColored(trisCol, "%s", tris.c_str());
- ImGui::TableSetColumnIndex(2);
+ ImGui::TableSetColumnIndex(3);
const ImVec2 eyePos = ImGui::GetCursorScreenPos();
const ImVec2 eyeSize(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeight());
if (ImGui::InvisibleButton(("##eye " + s.name).c_str(), eyeSize)) toggleIndex = i;
diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cpp
index 1d16a240..0596ab5c 100644
--- a/src/app/UiTest.cpp
+++ b/src/app/UiTest.cpp
@@ -56,6 +56,7 @@
// texture_painted (texels of the texture composite that aren't white),
// texture_mean_r / texture_mean_g / texture_mean_b (mean composite, sRGB 0-255),
// auto_uv_running
+// sdiv (the current subdivision level, 1 = base; 0 without levels), sdiv_levels (0 = none)
// (mesh values are the active SubTool's)
// snapshot remember the active mesh's vertices (for the moved* values)
// remember VALUE NAME keep VALUE's current value as $NAME
@@ -86,6 +87,7 @@
#include "app/Ui.h"
#include "core/BrushLibrary.h"
+#include "core/Multires.h"
#include "core/Script.h"
#include <imgui_internal.h>
@@ -218,6 +220,8 @@ double Demo::query(const std::string& name, bool& known) const {
return 255.0 * sum / double(m.colors.size());
}
if (name == "uvs") return m.hasUvs() ? 1.0 : 0.0;
+ if (name == "sdiv") return subdivLevelCount(m) ? double(subdivCurrentLevel(m) + 1) : 0.0;
+ if (name == "sdiv_levels") return double(subdivLevelCount(m));
if (name == "texture_size") return hasTexture(m) ? double(m.texture->width) : 0.0;
if (name == "paint_texture") return paintsTexture(m) ? 1.0 : 0.0;
if (name == "texture_layers") return hasTexture(m) ? double(m.texture->layers.size()) : 0.0;
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index 7026c5e5..17982ce8 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -286,7 +286,8 @@ CommandRegistry::CommandRegistry() {
}});
add({"subdivide",
- "Smoothly subdivide the mesh (Loop subdivision). Each level multiplies the triangle count by 4.",
+ "Smoothly subdivide the mesh (Loop subdivision). Each level multiplies the triangle count by 4. Unlike "
+ "Divide (subdiv_divide), it keeps no lower levels to step back to.",
{{"levels", T::Number, "Number of subdivision levels to apply (1-4). Default 1.", false}},
[](Document& doc, const Args& a) -> CommandResult {
int levels = std::clamp(int(argNumber(a, "levels", 1)), 1, 4);
diff --git a/src/core/Multires.cpp b/src/core/Multires.cpp
index a7f76af9..a901a479 100644
--- a/src/core/Multires.cpp
+++ b/src/core/Multires.cpp
@@ -11,6 +11,7 @@
#include <cmath>
#include <cstring>
#include <numbers>
+#include <optional>
#include <thread>
#include <unordered_map>
@@ -44,10 +45,9 @@ bool sameArray(const std::vector<T>& a, const std::vector<T>& b) {
// The level's data without topology, normals, texture or stack: what a level stores. (Add new Mesh attributes
// here too, so they follow the levels.)
-Mesh leanCopy(const Mesh& m) {
- Mesh out;
+// Copies the level arrays of `m` (all but the triangles) over `out`.
+void assignLevelArrays(Mesh& out, const Mesh& m) {
out.positions = m.positions;
- out.triangles = m.triangles;
out.mask = m.mask;
out.colors = m.colors;
out.polygroups = m.polygroups;
@@ -59,6 +59,11 @@ Mesh leanCopy(const Mesh& m) {
out.paintBase = m.paintBase;
out.paintLayers = m.paintLayers;
out.activePaintLayer = m.activePaintLayer;
+}
+Mesh leanCopy(const Mesh& m) {
+ Mesh out;
+ out.triangles = m.triangles;
+ assignLevelArrays(out, m);
return out;
}
std::shared_ptr<Mesh> leanShared(const Mesh& m) { return std::make_shared<Mesh>(leanCopy(m)); }
@@ -698,20 +703,82 @@ void evaluateLevel(MultiresStack& s, int k) {
L.stale = false;
}
-// Makes the working mesh level `level` of its stack (levels up to it must be evaluated).
-void loadLevel(Mesh& mesh, int level) {
+} // namespace
+
+struct SubdivLevelCache {
+ struct Entry {
+ std::shared_ptr<Mesh> key; // the level data the mesh was made from (held, so it can't change in place)
+ Mesh mesh;
+ BVH bvh;
+ };
+ std::vector<Entry> entries; // most recently left last
+ static constexpr size_t kMaxEntries = 2;
+};
+
+namespace {
+
+// Makes the working mesh level `level` of its stack (levels up to it must be evaluated). `leaving` is the level
+// data the working mesh was (null: don't keep it); with a BVH, that mesh and its BVH go to the level cache and
+// a cached copy of the new level is used when there is one.
+void enterLevel(Mesh& mesh, int level, BVH* bvh, std::shared_ptr<Mesh> leaving = nullptr) {
std::shared_ptr<MultiresStack> stack = mesh.multires;
+ if (leaving && leaving == stack->levels[size_t(level)].data) return; // already that level (e.g. Del Lower)
+ if (!stack->cache) stack->cache = std::make_shared<SubdivLevelCache>();
+ SubdivLevelCache& cache = *stack->cache;
std::shared_ptr<PaintTexture> texture = mesh.texture;
const bool toTexture = mesh.paintToTexture;
- mesh = leanCopy(*stack->levels[size_t(level)].data);
+ const std::shared_ptr<Mesh> want = stack->levels[size_t(level)].data;
+ // A cached copy of this level: exact (same data), or with the same triangles (only the shape or attributes
+ // changed, so its topology and BVH are kept and refitted).
+ std::optional<SubdivLevelCache::Entry> taken;
+ bool exact = false;
+ if (bvh) {
+ auto hit = std::find_if(cache.entries.begin(), cache.entries.end(), [&](const auto& e) { return e.key == want; });
+ exact = hit != cache.entries.end();
+ if (!exact)
+ hit = std::find_if(cache.entries.begin(), cache.entries.end(),
+ [&](const auto& e) { return sameArray(e.mesh.triangles, want->triangles); });
+ if (hit != cache.entries.end()) {
+ taken = std::move(*hit);
+ cache.entries.erase(hit);
+ }
+ if (leaving) {
+ // Keep the mesh being left (it has its topology and BVH already) for stepping back.
+ SubdivLevelCache::Entry e{std::move(leaving), std::move(mesh), std::move(*bvh)};
+ e.mesh.multires.reset();
+ e.mesh.texture.reset();
+ cache.entries.push_back(std::move(e));
+ while (cache.entries.size() > SubdivLevelCache::kMaxEntries) cache.entries.erase(cache.entries.begin());
+ }
+ }
+ if (taken) {
+ mesh = std::move(taken->mesh);
+ *bvh = std::move(taken->bvh);
+ if (!exact) {
+ std::vector<uint32_t> moved;
+ for (uint32_t v = 0; v < want->positions.size(); ++v)
+ if (want->positions[v] != mesh.positions[v]) moved.push_back(v);
+ assignLevelArrays(mesh, *want);
+ mesh.sanitizeAttributes();
+ mesh.recomputeAllNormals();
+ if (hasPaintLayers(mesh)) compositePaintAll(mesh);
+ bvh->refit(mesh, moved);
+ }
+ } else {
+ mesh = leanCopy(*want);
+ }
mesh.multires = std::move(stack);
mesh.texture = std::move(texture);
mesh.paintToTexture = toTexture;
- mesh.rebuildTopology();
- mesh.recomputeAllNormals();
- if (hasPaintLayers(mesh)) compositePaintAll(mesh);
+ if (!taken) {
+ mesh.rebuildTopology();
+ mesh.recomputeAllNormals();
+ if (hasPaintLayers(mesh)) compositePaintAll(mesh);
+ if (bvh) bvh->build(mesh);
+ }
mesh.topologyDirty = true;
mesh.facesDirty = true;
+ mesh.markAllDirty();
}
bool sameLayerSet(const Mesh& a, const Mesh& b) {
@@ -1156,7 +1223,7 @@ bool subdivCommit(Mesh& w) {
return true;
}
-bool subdivSetLevel(Mesh& mesh, int level, std::string& error) {
+bool subdivSetLevel(Mesh& mesh, int level, std::string& error, BVH* bvh) {
if (!mesh.multires) {
error = "This SubTool has no subdivision levels (Divide adds them)";
return false;
@@ -1174,12 +1241,13 @@ bool subdivSetLevel(Mesh& mesh, int level, std::string& error) {
MultiresStack& s = mutableStack(mesh);
for (int k = s.current + 1; k <= level; ++k)
if (s.levels[size_t(k)].stale) evaluateLevel(s, k);
+ std::shared_ptr<Mesh> leaving = s.levels[size_t(s.current)].data;
s.current = level;
- loadLevel(mesh, level);
+ enterLevel(mesh, level, bvh, std::move(leaving));
return true;
}
-bool subdivDivide(Mesh& mesh, bool smooth, std::string& error, size_t maxTriangles) {
+bool subdivDivide(Mesh& mesh, bool smooth, std::string& error, BVH* bvh, size_t maxTriangles) {
if (mesh.triangleCount() == 0) {
error = "Nothing to divide";
return false;
@@ -1188,7 +1256,7 @@ bool subdivDivide(Mesh& mesh, bool smooth, std::string& error, size_t maxTriangl
if (!subdivCommit(mesh)) {
// fall through: the stale stack was dropped, start a new one from this mesh
} else if (mesh.multires->current != int(mesh.multires->levels.size()) - 1 &&
- !subdivSetLevel(mesh, int(mesh.multires->levels.size()) - 1, error)) {
+ !subdivSetLevel(mesh, int(mesh.multires->levels.size()) - 1, error, bvh)) {
return false;
}
}
@@ -1203,7 +1271,8 @@ bool subdivDivide(Mesh& mesh, bool smooth, std::string& error, size_t maxTriangl
return false;
}
MultiresStack& s = ensureStack(mesh);
- const Mesh& coarse = *s.levels.back().data;
+ std::shared_ptr<Mesh> leaving = s.levels.back().data;
+ const Mesh& coarse = *leaving;
std::vector<uint32_t> pairing;
if (cc) {
pairing.resize(coarse.triangleCount());
@@ -1216,7 +1285,7 @@ bool subdivDivide(Mesh& mesh, bool smooth, std::string& error, size_t maxTriangl
level.layerDetail.resize(coarse.layers.size());
s.levels.push_back(std::move(level));
s.current = int(s.levels.size()) - 1;
- loadLevel(mesh, s.current);
+ enterLevel(mesh, s.current, bvh, std::move(leaving));
return true;
}
@@ -1637,7 +1706,7 @@ bool reconstructLoop(const Mesh& m, Reconstruction& out, std::string& error) {
} // namespace
-bool subdivReconstruct(Mesh& mesh, std::string& error) {
+bool subdivReconstruct(Mesh& mesh, std::string& error, BVH* bvh) {
if (mesh.multires) {
if (!subdivCommit(mesh)) {
// dropped: reconstruct from this mesh alone
@@ -1686,13 +1755,11 @@ bool subdivReconstruct(Mesh& mesh, std::string& error) {
return false;
}
- // Coarse shape: start at the fine corners, then nudge so that subdividing passes close to them again.
+ // Coarse shape: the fine level's corner vertices, as ZBrush does (fitting the cage so its subdivision passes
+ // through them overshoots badly on sharp shapes, and compounds over several levels); the detail of the fine
+ // level keeps it exactly as it was.
const std::vector<glm::vec3>& fineBase = baseChannel(mesh);
for (uint32_t v = 0; v < nc; ++v) coarse.positions[v] = fineBase[rec.vertexChild[v]];
- for (int it = 0; it < 6; ++it) {
- const std::vector<glm::vec3> s = subdivideField(*tp, true, coarse.positions);
- for (uint32_t v = 0; v < nc; ++v) coarse.positions[v] += fineBase[rec.vertexChild[v]] - s[rec.vertexChild[v]];
- }
// Attributes: everything copied down from the fine level.
std::vector<uint8_t> f;
if (mesh.hasMask()) restrictVertices(*tp, mesh.mask, coarse.mask, 0.0f, nullptr, f);
@@ -1740,7 +1807,7 @@ bool subdivReconstruct(Mesh& mesh, std::string& error) {
s.levels[0] = std::move(fineLevel);
s.levels.insert(s.levels.begin(), SubdivLevel{std::make_shared<Mesh>(std::move(coarse)), nullptr, nullptr, {}, false});
s.current = 0;
- loadLevel(mesh, 0);
+ enterLevel(mesh, 0, bvh, s.levels[1].data);
return true;
}
@@ -1759,9 +1826,13 @@ size_t SubdivUndo::bytes() const {
void applySubdivUndo(SubdivUndo& r, Mesh& mesh, BVH& bvh) {
subdivCommit(mesh);
+ std::shared_ptr<Mesh> leaving = mesh.multires ? mesh.multires->levels[size_t(mesh.multires->current)].data : nullptr;
+ std::shared_ptr<SubdivLevelCache> cache = mesh.multires ? mesh.multires->cache : nullptr;
std::swap(mesh.multires, r.stack);
if (mesh.multires) {
- loadLevel(mesh, mesh.multires->current);
+ if (!mesh.multires->cache) mesh.multires->cache = std::move(cache);
+ enterLevel(mesh, mesh.multires->current, &bvh, std::move(leaving));
+ return;
} else if (r.plain) {
std::shared_ptr<PaintTexture> texture = mesh.texture;
const bool toTexture = mesh.paintToTexture;
@@ -1790,10 +1861,9 @@ bool runUndoable(Document& doc, const std::string& label, Op op, std::string& me
const bool hadStack = bool(rec->stack);
const int fromLevel = subdivCurrentLevel(mesh);
if (!hadStack && plainLevel < 0) return false;
- if (!op(mesh, message)) return false;
+ if (!op(mesh, message, &doc.bvh)) return false;
if (!hadStack) rec->plain = mesh.multires->levels[size_t(plainLevel)].data;
else if (!mesh.multires) rec->plain = rec->stack->levels[size_t(fromLevel)].data; // the level that remained
- doc.bvh.build(mesh);
doc.bvhDirty = false;
UndoRecord r;
r.label = label;
@@ -1811,8 +1881,8 @@ std::string levelSummary(const Mesh& m) {
} // namespace
bool divideUndoable(Document& doc, bool smooth, std::string& message) {
- return runUndoable(doc, "Divide", [&](Mesh& m, std::string& msg) {
- if (!subdivDivide(m, smooth, msg)) return false;
+ return runUndoable(doc, "Divide", [&](Mesh& m, std::string& msg, BVH* bvh) {
+ if (!subdivDivide(m, smooth, msg, bvh)) return false;
msg = "Divided: " + levelSummary(m);
return true;
}, message, doc.mesh.multires ? -1 : 0);
@@ -1827,15 +1897,15 @@ bool setSubdivLevelUndoable(Document& doc, int level, std::string& message) {
message = levelSummary(doc.mesh);
return true;
}
- return runUndoable(doc, "SDiv " + std::to_string(level + 1), [&](Mesh& m, std::string& msg) {
- if (!subdivSetLevel(m, level, msg)) return false;
+ return runUndoable(doc, "SDiv " + std::to_string(level + 1), [&](Mesh& m, std::string& msg, BVH* bvh) {
+ if (!subdivSetLevel(m, level, msg, bvh)) return false;
msg = levelSummary(m);
return true;
}, message);
}
bool deleteLowerUndoable(Document& doc, std::string& message) {
- return runUndoable(doc, "Del Lower", [&](Mesh& m, std::string& msg) {
+ return runUndoable(doc, "Del Lower", [&](Mesh& m, std::string& msg, BVH*) {
if (!subdivDeleteLower(m, msg)) return false;
msg = "Deleted the lower levels: " + levelSummary(m);
return true;
@@ -1843,7 +1913,7 @@ bool deleteLowerUndoable(Document& doc, std::string& message) {
}
bool deleteHigherUndoable(Document& doc, std::string& message) {
- return runUndoable(doc, "Del Higher", [&](Mesh& m, std::string& msg) {
+ return runUndoable(doc, "Del Higher", [&](Mesh& m, std::string& msg, BVH*) {
if (!subdivDeleteHigher(m, msg)) return false;
msg = "Deleted the higher levels: " + levelSummary(m);
return true;
@@ -1851,8 +1921,8 @@ bool deleteHigherUndoable(Document& doc, std::string& message) {
}
bool reconstructUndoable(Document& doc, std::string& message) {
- return runUndoable(doc, "Reconstruct Subdiv", [&](Mesh& m, std::string& msg) {
- if (!subdivReconstruct(m, msg)) return false;
+ return runUndoable(doc, "Reconstruct Subdiv", [&](Mesh& m, std::string& msg, BVH* bvh) {
+ if (!subdivReconstruct(m, msg, bvh)) return false;
msg = "Reconstructed a lower level: " + levelSummary(m);
return true;
}, message, doc.mesh.multires ? -1 : 1);
diff --git a/src/core/Multires.h b/src/core/Multires.h
index 4784df14..2193bb82 100644
--- a/src/core/Multires.h
+++ b/src/core/Multires.h
@@ -87,9 +87,14 @@ struct SubdivLevel {
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.
+struct SubdivLevelCache;
+
struct MultiresStack {
std::vector<SubdivLevel> levels; // at least 2 while a mesh has a stack
int current = 0;
+ std::shared_ptr<SubdivLevelCache> cache; // shared by copies of the stack
};
// --- Queries (0 levels = a plain mesh) ---
@@ -108,17 +113,20 @@ size_t subdivBytes(const Mesh& mesh);
// --- 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.
//
+// Operations that change the working mesh take an optional BVH: when given it is made valid for the new
+// mesh (rebuilt, or taken from the level cache); otherwise the caller rebuilds it.
+//
// Adds a level on top (stepping to the highest level first) and makes it current. `smooth` = Smt.
-bool subdivDivide(Mesh& mesh, bool smooth, std::string& error, size_t maxTriangles = 50'000'000);
-// Makes `level` current. Rebuilds topology and normals (the caller rebuilds the BVH).
-bool subdivSetLevel(Mesh& mesh, int level, std::string& error);
+bool subdivDivide(Mesh& mesh, bool smooth, std::string& error, BVH* bvh = nullptr, size_t maxTriangles = 50'000'000);
+// Makes `level` current, with topology and normals.
+bool subdivSetLevel(Mesh& mesh, int level, std::string& error, BVH* bvh = nullptr);
// Deletes the levels below / above the current one (the current level becomes the base / the top).
bool subdivDeleteLower(Mesh& mesh, std::string& error);
bool subdivDeleteHigher(Mesh& mesh, std::string& error);
// At the lowest level: finds the mesh this one was subdivided from (a regular Catmull-Clark subdivision of
// an all-quad mesh, or a Loop subdivision of a triangle mesh), adds it as a new lowest level and steps down
// to it. The current level keeps its exact shape and vertex order.
-bool subdivReconstruct(Mesh& mesh, std::string& error);
+bool subdivReconstruct(Mesh& mesh, std::string& error, BVH* bvh = nullptr);
// Folds edits of the current level into the stack (see the file comment). Cheap when nothing changed.
// Returns false (and drops the stack) if the mesh no longer has the current level's topology.
bool subdivCommit(Mesh& mesh);
diff --git a/tests/test_multires.cpp b/tests/test_multires.cpp
index b4ab487f..bde96b13 100644
--- a/tests/test_multires.cpp
+++ b/tests/test_multires.cpp
@@ -368,10 +368,8 @@ TEST(multires_reconstruct_finds_lower_levels) {
CHECK(subdivLevelText(d.mesh) == "SDiv 1/3");
CHECK(d.mesh.triangleCount() == makeCube(2).triangleCount());
CHECK(d.mesh.vertexCount() == makeCube(2).vertexCount());
- // The base is close to the original cube's corners (fitted, not the sculpted surface).
- float far = 0.0f;
- for (const auto& p : d.mesh.positions) far = std::max(far, std::abs(std::max({std::abs(p.x), std::abs(p.y), std::abs(p.z)}) - 1.0f));
- CHECK(far < 0.35f);
+ // The base sits on the fine level's corner vertices.
+ for (const auto& p : d.mesh.positions) CHECK(std::find(fine.begin(), fine.end(), p) != fine.end());
CHECK(run(d, "subdiv_level", {{"level", 3.0}}).ok);
CHECK(bitEqual(d.mesh.positions, fine)); // the top is exactly the mesh it started from
CHECK(!run(d, "subdiv_reconstruct").ok); // only at the lowest level
@@ -384,7 +382,7 @@ TEST(multires_reconstruct_finds_lower_levels) {
CHECK(run(r, "subdiv_reconstruct").ok);
CHECK(run(r, "subdiv_reconstruct").ok);
CHECK(r.mesh.triangleCount() == makeIcosphere(1).triangleCount());
- CHECK(maxDistance(r.mesh.positions, subdivLevelMesh(t.mesh, 0).positions) < 0.05f);
+ CHECK(maxDistance(r.mesh.positions, subdivLevelMesh(t.mesh, 0).positions) < 0.1f);
// A mesh that isn't a subdivision is refused, and undo restores the plain mesh.
Document n = makeDoc(makeIcosphere(2));
n.mesh.triangles[0] = {n.mesh.triangles[0].x, n.mesh.triangles[0].z, n.mesh.triangles[0].y};
diff --git a/tests/ui/help_console.sfui b/tests/ui/help_console.sfui
index 3af6ec7e..7d1a6e4f 100644
--- a/tests/ui/help_console.sfui
+++ b/tests/ui/help_console.sfui
@@ -6,20 +6,20 @@ expect_value triangles == 1280
# F1: the Controls sheet is generated from the action registry. Ctrl+hover explains any item,
# Ctrl+Alt+hover shows a command's scripting parameters.
key f1
-type Controls/##controls_filter subdiv
-expect Controls/Subdivide
+type Controls/##controls_filter divide
+expect Controls/Divide
hold ctrl
-hover Controls/Subdivide
-expect_help "Loop subdivision"
+hover Controls/Divide
+expect_help "subdivision level"
expect_help Ctrl+D
shot help_ctrl_hover
hold ctrl+alt
-hover Controls/Subdivide
-expect_help "Number of subdivision levels"
+hover Controls/Divide
+expect_help "Smt: smooth the new level"
shot help_ctrl_alt_hover
hold none
wait 0.2
-expect_no_text "Loop subdivision"
+expect_no_text "subdivision level"
# ZBrush-style shortcut assignment: double-click a row (or Ctrl+Alt+click a button), press the key.
type Controls/##controls_filter wire
@@ -32,12 +32,12 @@ expect_value wireframe == 1
key ctrl+k
expect_value wireframe == 0
key f1
-expect_not Controls/Subdivide
+expect_not Controls/Divide
# Command palette (F3): fuzzy search, Enter runs.
key f3
expect_value command_palette_open == 1
-type "##Command palette" subdiv
+type "##Command palette" subdivide
expect_text "Tool > Geometry"
shot command_palette
key enter
@@ -57,7 +57,7 @@ type Console/##console "remesh resolution=64"
key enter
expect_text "> remesh resolution=64"
expect_value triangles > 30000
-type Console/##console subd
+type Console/##console subdivi
key tab
key enter
expect_text "> subdivide"
diff --git a/tests/ui/multires.sfui b/tests/ui/multires.sfui
new file mode 100644
index 00000000..f2904709
--- /dev/null
+++ b/tests/ui/multires.sfui
@@ -0,0 +1,137 @@
+# Subdivision levels (Tool > Geometry): Divide adds levels and keeps the lower ones, D / Shift+D and the SDiv
+# slider step between them, detail sculpted at the top survives sculpting big forms at a low level, and undo
+# steps back through strokes and level changes. A cube divided four times becomes a rounded box of quads.
+run new_sphere subdivisions=1
+run subtool_append type=cube name=Box
+run subtool_delete index=0
+expect_value subtools == 1
+expect_value triangles == 27648
+orbit 140 -70
+key f
+click "Geometry##tool.geometry"
+expect "Geometry/Divide"
+expect "Geometry/Smt"
+expect_value sdiv_levels == 0
+expect_text "No subdivision levels"
+
+# Reconstruct Subdiv finds the lower levels of a regular quad grid: 48 cells per side -> 24 -> 12 -> 6 -> 3.
+click "Geometry/Reconstruct Subdiv"
+expect_value sdiv_levels == 2
+expect_value sdiv == 1
+click "Geometry/Reconstruct Subdiv"
+click "Geometry/Reconstruct Subdiv"
+click "Geometry/Reconstruct Subdiv"
+expect_value sdiv_levels == 5
+expect_value triangles == 108
+expect_status "Reconstructed"
+click "Display##tool.display"
+click "Wireframe##display"
+click "Geometry##tool.geometry"
+shot reconstructed-cage
+
+# Del Higher at the base leaves the plain 108-triangle cage to start from.
+click "Geometry/Del Higher"
+expect_value sdiv_levels == 0
+expect_value triangles == 108
+
+# Divide (Ctrl+D or the button): every level has four times the quads.
+click "Geometry/Divide"
+expect_value sdiv_levels == 2
+expect_value sdiv == 2
+expect_value triangles == 432
+key ctrl+d
+key ctrl+d
+key ctrl+d
+expect_value sdiv_levels == 5
+expect_value triangles == 27648
+expect_text "SDiv 5 / 5"
+expect_status "SDiv 5/5"
+shot divided-wire
+click "Display##tool.display"
+click "Wireframe##display"
+click "Geometry##tool.geometry"
+
+# Fine detail at the top level.
+key 1
+snapshot
+stroke 0.25 0.35 0.75 0.4
+stroke 0.3 0.5 0.7 0.55
+expect_value moved > 200
+shot top-detail
+
+# Step down twice (Shift+D) and sculpt a big form: few vertices move.
+key shift+d
+key shift+d
+expect_value sdiv == 3
+expect_value triangles == 1728
+expect_text "SDiv 3 / 5"
+shot level-3
+snapshot
+key ]
+key ]
+key ]
+key ]
+key ]
+key ]
+key ]
+stroke 0.2 0.7 0.75 0.75 1.0
+key [
+key [
+key [
+key [
+key [
+key [
+key [
+expect_value moved > 3
+expect_value moved < 300
+shot level-3-form
+
+# Back up (D twice): the top level shows the big form with the fine detail on it.
+key d
+key d
+expect_value sdiv == 5
+expect_value triangles == 27648
+shot top-after-low-edit
+
+# Undo goes back through the steps and strokes in order: two steps, the low stroke, two steps, the detail.
+key ctrl+z
+expect_value sdiv == 4
+key ctrl+z
+expect_value sdiv == 3
+snapshot
+key ctrl+z
+expect_value moved > 3
+key ctrl+z
+key ctrl+z
+expect_value sdiv == 5
+snapshot
+key ctrl+z
+expect_value moved > 200
+expect_value sdiv == 5
+key ctrl+shift+z
+expect_value sdiv == 5
+
+# The SDiv slider: drag it to the left end for the base cage.
+drag_item "Geometry/##sdiv" -400 0
+expect_value sdiv == 1
+expect_value triangles == 108
+shot base-level
+
+# The SubTool list shows the level.
+click "SubTool##tool.subtool"
+expect_text "SDiv 1/5"
+shot subtool-list
+
+# Del Lower at level 2 makes it the new base; Del Higher drops the top.
+click "Geometry##tool.geometry"
+key d
+click "Geometry/Del Lower"
+expect_value sdiv == 1
+expect_value sdiv_levels == 4
+expect_value triangles == 432
+click "Geometry/Higher Res"
+click "Geometry/Del Higher"
+expect_value sdiv_levels == 2
+key ctrl+z
+expect_value sdiv_levels == 4
+shot after-delete