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
Dynamic topology: renderer patches instead of full uploads, Dynamic toggle + Detail slider (top shelf, Draw palette), constant-detail preference, dyntopo command, benchmark rows, UI test
islandmed0f14ce9eeea2
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 1ebdf4b2..1f733593 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -34,6 +34,7 @@ add_library(sculptforge_core STATICsrc/core/Benchmark.cppsrc/core/Sculpt.cppsrc/core/Dyntopo.cpp+ src/core/DyntopoCommands.cppsrc/core/Undo.cppsrc/core/Primitives.cppsrc/core/Document.cppdiff --git a/src/app/App.cpp b/src/app/App.cppindex 51952133..a854634c 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -847,6 +847,8 @@ void App::beginStroke(float x, float y, const RayHit& hit) {playingLayer_ = -1;clearLods();beginPaintStroke();+ if (doc_.sculptor.dyntopo.enabled && strokeSculpt_ && !dyntopoBlocker(doc_.mesh).empty())+ status_ = "Dynamic is on, but this SubTool has subdivision levels: sculpting without remeshing";lastX_ = x;lastY_ = y;residual_ = 0.0f;@@ -1019,6 +1021,8 @@ void App::endStroke() {perf_.strokeFrames = 0;UndoRecord r = doc_.sculptor.endStroke();finishPaintStroke(r);+ if (r.topology && !r.topology->uvs.empty())+ status_ = "Dynamic topology removed the UVs of the remeshed SubTool (Undo brings them back)";if (!r.empty()) {doc_.undo.push(std::move(r));doc_.modified = true;diff --git a/src/app/App.h b/src/app/App.hindex 60a85ca9..93eec3cd 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -115,6 +115,10 @@ private:void strokeTo(float x, float y);void dabAt(float x, float y, float pressure = -1.0f); // pressure < 0: strokePressure()void endStroke();+ // Dynamic topology (ZBrush's Sculptris Pro, core/Dyntopo.h): turns it on or off (not on a mesh with+ // subdivision levels), saying so in the status bar; the Detail slider.+ void setDynamic(bool on);+ void drawDetailSlider(const char* id);void runCommand(const std::string& name, const Args& args = {});void openFileDialog();diff --git a/src/app/Config.cpp b/src/app/Config.cppindex 73590b9d..29eb7207 100644--- a/src/app/Config.cpp+++ b/src/app/Config.cpp@@ -51,6 +51,7 @@ Json toJson(const UiPrefs& p) {j.set("antialiasing", double(p.antialiasing));j.set("fastNavigation", p.fastNavigation);j.set("multithreading", p.multithreading);+ j.set("dyntopoConstantDetail", p.dyntopoConstantDetail);return j;}@@ -74,6 +75,7 @@ void fromJson(const Json& j, UiPrefs& p) {p.antialiasing = aa >= 8 ? 8 : aa >= 4 ? 4 : aa >= 2 ? 2 : 1;p.fastNavigation = j["fastNavigation"].asBool(p.fastNavigation);p.multithreading = j["multithreading"].asBool(p.multithreading);+ p.dyntopoConstantDetail = j["dyntopoConstantDetail"].asBool(p.dyntopoConstantDetail);}namespace {@@ -428,6 +430,7 @@ bool App::readUiConfig(const std::string& path, std::string& err) {fromJson(j["prefs"], uiPrefs_);applyPerformancePrefs();applyInputStyle();+ doc_.sculptor.dyntopo.constantDetail = uiPrefs_.dyntopoConstantDetail;return true;}diff --git a/src/app/Config.h b/src/app/Config.hindex 35a70492..9b072909 100644--- a/src/app/Config.h+++ b/src/app/Config.h@@ -35,6 +35,9 @@ struct UiPrefs {int antialiasing = 4; // samples per pixel in the 3D view: 1 (off), 2, 4 or 8bool fastNavigation = true; // big scenes draw without antialiasing while the view movesbool multithreading = true; // brushes, normals and BVH updates on every core (off: one thread)+ // Dynamic topology (Draw palette): false = the detail follows the brush size on screen (Sculptris Pro);+ // true = one detail size for the whole mesh.+ bool dyntopoConstantDetail = false;};Json toJson(const UiPrefs& prefs);diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex 94206887..569ad07c 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -188,6 +188,19 @@ void App::drawPalette_Draw() {segmented(*this, {"draw.sculpt", "draw.paint"});segmented(*this, {"draw.zadd", "draw.zsub"});actionRow(*this, {"draw.rgb", "draw.front_faces"});+ ImGui::SeparatorText("Dynamic topology");+ actionRow(*this, {"draw.dynamic"});+ ImGui::SetNextItemWidth(-1);+ drawDetailSlider("##dyntopo_detail_palette");+ if (ImGui::Checkbox("Constant detail", &uiPrefs_.dyntopoConstantDetail))+ doc_.sculptor.dyntopo.constantDetail = uiPrefs_.dyntopoConstantDetail;+ ui::HelpText("Constant detail", nullptr,+ "Off (the default): the triangle size follows the brush size on screen, as in Sculptris Pro. On: one "+ "size for the whole mesh, set by Detail. A preference (Store Config keeps it).",+ "Draw > Dynamic topology");+ if (doc_.sculptor.dyntopo.enabled && !dyntopoBlocker(doc_.mesh).empty())+ hint("This SubTool has subdivision levels, so strokes don't remesh it: delete the lower (or higher) levels "+ "first.");ImGui::SeparatorText("Tablet");ImGui::Checkbox("Pressure > strength", &pressureStrength_);ui::HelpAction(*this, "draw.pressure_strength");diff --git a/src/app/PanelBrushes.cpp b/src/app/PanelBrushes.cppindex d7631cd6..0e6d9837 100644--- a/src/app/PanelBrushes.cpp+++ b/src/app/PanelBrushes.cpp@@ -109,8 +109,15 @@ void App::snakeHookTo(float x, float y) {}}-// DragRect: undo the previous stamp and press a new one sized and rotated by the drag.+// DragRect: undo the previous stamp and press a new one sized and rotated by the drag (without remeshing:+// restoreStroke puts positions back, not topology).void App::dragRectTo(float x, float y) {+ struct NoRemesh {+ DyntopoSettings& s;+ bool was = s.enabled;+ ~NoRemesh() { s.enabled = was; }+ } noRemesh{doc_.sculptor.dyntopo};+ noRemesh.s.enabled = false;doc_.sculptor.restoreStroke(doc_.mesh, doc_.bvh);const glm::vec2 drag = glm::vec2(x, y) - dragAnchor_;const float len = glm::length(drag);diff --git a/src/app/PanelProject.cpp b/src/app/PanelProject.cppindex cf0eda16..435fabfc 100644--- a/src/app/PanelProject.cpp+++ b/src/app/PanelProject.cpp@@ -231,6 +231,8 @@ void App::storeProjectSettings() {brush.set("pressure_strength", pressureStrength_);brush.set("pressure_size", pressureSize_);brush.set("paint_color", vec3Json(doc_.paintColor));+ brush.set("dynamic", doc_.sculptor.dyntopo.enabled); // dynamic topology (core/Dyntopo.h)+ brush.set("dynamic_detail", double(doc_.sculptor.dyntopo.detail));s.set("brush", std::move(brush));Json sym = Json::object();@@ -297,6 +299,9 @@ void App::applyProjectSettings() {readBool(b, "pressure_strength", pressureStrength_);readVec3(b["paint_color"], doc_.paintColor);readBool(b, "pressure_size", pressureSize_);+ readBool(b, "dynamic", doc_.sculptor.dyntopo.enabled);+ readFloat(b, "dynamic_detail", doc_.sculptor.dyntopo.detail);+ doc_.sculptor.dyntopo.detail = std::clamp(doc_.sculptor.dyntopo.detail, 0.0f, 1.0f);}if (const Json& sym = s["symmetry"]; sym.isObject()) {readBool(sym, "x", symmetry_.x);diff --git a/src/app/Shell.cpp b/src/app/Shell.cppindex 4053a63a..d7bac407 100644--- a/src/app/Shell.cpp+++ b/src/app/Shell.cpp@@ -307,6 +307,13 @@ void App::registerShellActions() {flag("draw.rgb", "Rgb", nullptr, "Draw", "", &paintRgb_, "Sculpt brushes also paint the colour (ZBrush Rgb with Zadd).");flag("draw.front_faces", "Front", nullptr, "Brush", "", &frontFacesOnly_,"Front faces only: brushes leave the far side of thin parts alone.");+ add({"draw.dynamic", "Dynamic", nullptr,+ "Dynamic topology (ZBrush's Sculptris Pro): brushes add triangles where they need detail and remove them "+ "where they don't, so you can pull out horns or fingers without stretching. Detail sets how small the "+ "triangles get; zoom in or shrink the brush for finer ones. Needs a mesh without subdivision levels; quads "+ "under the brush become triangles and UVs are dropped (Undo brings them back).",+ "Draw", "", "dyntopo", [this] { setDynamic(!doc_.sculptor.dyntopo.enabled); },+ [this] { return doc_.sculptor.dyntopo.enabled; }, nullptr});// Masking and visibility selection shapes (Tool > Masking, Tool > Visibility), named as in ZBrush.auto shape = [this](std::string id, std::string label, std::string palette, SelectShape* target, SelectShape value,std::string description) {@@ -1163,6 +1170,7 @@ bool App::shelfItemShown(const std::string& item) const {if (layout_.customize) return true;if (item == "view.splats") return !doc_.splats.empty(); // only when there's a captureif (item == "draw.paint_vertex" || item == "draw.paint_texture") return hasTexture(doc_.mesh); // paint target+ if (item == "widget.dyntopo_detail") return doc_.sculptor.dyntopo.enabled; // with Dynamic onreturn true;}@@ -1200,6 +1208,11 @@ void App::drawShelfItem(int shelf, int index, const std::string& item, bool vertdrawZIntensitySlider("##strength");}ImGui::PopStyleVar();+ } else if (item == "widget.dyntopo_detail") {+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(8.0f * s, (rowH - ImGui::GetFontSize()) * 0.5f));+ ImGui::SetNextItemWidth((vertical ? 180.0f : 120.0f) * s);+ drawDetailSlider("##dyntopo_detail");+ ImGui::PopStyleVar();} else if (item == "widget.points") {size_t total = 0;uint64_t key = doc_.undo.revision() * 0x9E3779B97F4A7C15ull ^ uint64_t(doc_.activeSubtool) ^@@ -1333,6 +1346,30 @@ void App::drawShelfItem(int shelf, int index, const std::string& item, bool vertImGui::PopID();}+void App::setDynamic(bool on) {+ if (on) {+ const std::string why = dyntopoBlocker(doc_.mesh);+ if (!why.empty()) {+ status_ = why;+ return;+ }+ }+ doc_.sculptor.dyntopo.enabled = on;+ status_ = dyntopoSummary(doc_.sculptor.dyntopo);+}++void App::drawDetailSlider(const char* id) {+ float detail = doc_.sculptor.dyntopo.detail * 100.0f;+ if (ui::SliderInside(id, &detail, 0.0f, 100.0f, "Detail %.0f")) doc_.sculptor.dyntopo.detail = detail / 100.0f;+ ui::HelpText("Detail", nullptr,+ doc_.sculptor.dyntopo.constantDetail+ ? "Dynamic topology: how small the triangles get, one size for the whole mesh (0 coarse, 100 fine; "+ "Constant detail is on in the Draw palette). Ctrl+click to type."+ : "Dynamic topology: how small the triangles get, relative to the brush (0 coarse, 100 fine). Zoom "+ "in or shrink the brush for finer triangles, as in Sculptris Pro. Ctrl+click to type.",+ "Draw");+}+void App::finishShelfDrag() {const ImGuiPayload* payload = ImGui::GetDragDropPayload();if (payload && payload->IsDataType(ui::kUiItemPayload)) {diff --git a/src/app/UiLayout.cpp b/src/app/UiLayout.cppindex 4ffcb644..f7097da5 100644--- a/src/app/UiLayout.cpp+++ b/src/app/UiLayout.cpp@@ -2,6 +2,8 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "app/UiLayout.h"+#include <algorithm>+namespace sf {namespace {@@ -30,6 +32,7 @@ UiLayout standardLayout() {"tool.rotate", "sep", "draw.sculpt", "draw.paint", "sep","draw.zadd", "draw.zsub", "draw.rgb", "draw.paint_vertex", "draw.paint_texture", "sep", "widget.draw_size","widget.strength", "row", "ui.brush_lab", "draw.front_faces", "sep",+ "draw.dynamic", "widget.dyntopo_detail", "sep","transform.symmetry_x", "transform.symmetry_y", "transform.symmetry_z", "sep", "draw.pressure_strength","draw.pressure_size", "widget.points"};l.leftShelf = {"widget.tile.brush", "widget.tile.stroke", "widget.tile.alpha", "widget.tile.material", "widget.color"};@@ -88,6 +91,12 @@ bool fromJson(const Json& j, UiLayout& l, std::string& error) {readStrings(j["rightTray"], out.rightTray);readStrings(j["openSubpalettes"], out.openSubpalettes);readStrings(j["topShelf"], out.topShelf);+ // Version 2 (0.8) added Dynamic and its Detail slider: put them into stored top shelves, before symmetry.+ if (int(j["version"].asNumber(1)) < 2 && j["topShelf"].isArray() &&+ std::find(out.topShelf.begin(), out.topShelf.end(), "draw.dynamic") == out.topShelf.end()) {+ const auto at = std::find(out.topShelf.begin(), out.topShelf.end(), "transform.symmetry_x");+ out.topShelf.insert(at, {"draw.dynamic", "widget.dyntopo_detail", "sep"});+ }readStrings(j["leftShelf"], out.leftShelf);readStrings(j["rightShelf"], out.rightShelf);readStrings(j["bottomShelf"], out.bottomShelf);diff --git a/src/app/UiLayout.h b/src/app/UiLayout.hindex deff23df..4e7fd459 100644--- a/src/app/UiLayout.h+++ b/src/app/UiLayout.h@@ -20,7 +20,7 @@ struct CanvasRect {};struct UiLayout {- int version = 1;+ int version = 2; // 2: the top shelf has Dynamic (older stored layouts get it on load)bool shelvesVisible = true, paletteBarVisible = true, leftHanded = false;bool leftTrayOpen = false, rightTrayOpen = true;float leftTrayWidth = 300, rightTrayWidth = 300; // logical pxdiff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex 19e3146f..7ba6e3c2 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -69,6 +69,7 @@// antialiasing (Preferences > Performance: 1, 2, 4, 8), view_samples (what the interactive// view draws with now: 1 while Fast Navigation moves a big scene), multithreading (1 on),// last_stroke_dabs (dabs of the last finished stroke)+// dynamic (1 while dynamic topology is on), dynamic_detail (its Detail, 0-100)// z_intensity, smooth_intensity, rgb_intensity (0-100), focal_shift (-100..100), draw_size,// quickmenu_open, lazy_mouse, input_style (0 ZBrush, 1 SculptForge), brush_type (BrushType// index, -1 for a custom brush or Paint), last_dab_x / last_dab_y (window pixels), paint_r@@ -278,6 +279,8 @@ double Demo::query(const std::string& name, bool& known) const {if (name == "quickmenu_open") return app_.quickMenu_.open ? 1.0 : 0.0;if (name == "lazy_mouse") return app_.strokeType_ == StrokeType::LazyMouse ? 1.0 : 0.0;if (name == "input_style") return double(app_.uiPrefs_.inputStyle);+ if (name == "dynamic") return app_.doc_.sculptor.dyntopo.enabled ? 1.0 : 0.0;+ if (name == "dynamic_detail") return std::round(app_.doc_.sculptor.dyntopo.detail * 100.0f);if (name == "brush_type") return app_.doc_.activeBrush >= 0 || app_.paintMode_ ? -1.0 : double(int(app_.brush_));if (name == "last_dab_x") return app_.lastDabScreen_.x;if (name == "last_dab_y") return app_.lastDabScreen_.y;diff --git a/src/app/main.cpp b/src/app/main.cppindex 2512def6..1c757068 100644--- a/src/app/main.cpp+++ b/src/app/main.cpp@@ -43,6 +43,7 @@ void usage() {" --bench-brushes TEXT Only the benchmark brushes whose name contains TEXT (e.g. large)\n"" --bench-no-project Skip the project save / open (it needs twice the memory)\n"" --bench-view Benchmark only what the viewport costs (uploads, orbit)\n"+ " --bench-dyntopo Benchmark dynamic topology strokes (e.g. --bench-sizes 0.25,1,4)\n"" --bench-out FILE Write the benchmark report (Markdown) to FILE");}diff --git a/src/cli/main.cpp b/src/cli/main.cppindex a7eac97e..4b2d38aa 100644--- a/src/cli/main.cpp+++ b/src/cli/main.cpp@@ -37,6 +37,7 @@ void usage() {" --bench-brushes TEXT Only the benchmark brushes whose name contains TEXT (e.g. large)\n"" --bench-no-project Skip the project save / open (it needs twice the memory)\n"" --bench-view Benchmark only what the viewport costs (uploads, orbit)\n"+ " --bench-dyntopo Benchmark dynamic topology strokes (e.g. --bench-sizes 0.25,1,4)\n"" --bench-out FILE Write the benchmark report (Markdown) to FILE\n"" -h, --help Show this help\n""\n"diff --git a/src/core/Benchmark.cpp b/src/core/Benchmark.cppindex ff6fb63a..0edc2e27 100644--- a/src/core/Benchmark.cpp+++ b/src/core/Benchmark.cpp@@ -147,6 +147,8 @@ struct StrokeStats {double verts = 0, uploaded = 0, runs = 0, kernel = 0, normals = 0, bvh = 0, pick = 0, upload = 0, total = 0;double endStroke = 0, undo = 0, redo = 0;size_t undoBytes = 0;+ double remesh = 0; // dynamic topology+ size_t triangles = 0; // after the stroke};StrokeStats runStroke(Document& doc, const BenchBrush& b, int dabs, const BenchGpu* gpu, UploadOrder& order) {@@ -206,6 +208,8 @@ StrokeStats runStroke(Document& doc, const BenchBrush& b, int dabs, const BenchGst.kernel = sc.timings.kernelMs;st.normals = sc.timings.normalsMs;st.bvh = sc.timings.bvhMs;+ st.remesh = sc.timings.remeshMs;+ st.triangles = m.triangleCount();st.verts = double(sc.timings.vertices) / double(std::max(st.dabs, 1)); // per step (both mirrors)st.uploaded /= double(std::max(st.dabs, 1));st.runs /= double(std::max(st.dabs, 1));@@ -247,6 +251,9 @@ bool parseBenchArg(int argc, char** argv, int& i, BenchCommandLine& cl) {} else if (a == "--bench-view") {cl.options.viewOnly = true;cl.options.projectRoundTrip = false;+ } else if (a == "--bench-dyntopo") {+ cl.options.dyntopo = true;+ cl.options.projectRoundTrip = false;} else if (a == "--bench-out") {cl.outPath = next();} else {@@ -282,7 +289,86 @@ int runBenchCommandLine(BenchCommandLine cl, const std::string& heading, const Breturn 0;}+namespace {++// Dynamic topology (core/Dyntopo.h): strokes that remesh as they go, on spheres without subdivision levels+// (Sculptris Pro works on such meshes only). Each row starts from the same sphere.+std::string runDyntopoBenchmark(const BenchOptions& o, const BenchGpu* gpu) {+ auto log = [&](const std::string& s) {+ if (o.log) o.log(s);+ };+ std::ostringstream md;+ md << "Threads: " << ThreadPool::shared().threads();+ if (gpu && !gpu->description.empty()) md << ", GPU: " << gpu->description;+ md << ". Dynamic topology on (relative detail), X symmetry (two dabs per step), " << o.dabsPerStroke+ << " dabs per stroke on a unit sphere without subdivision levels. Times in milliseconds.\n\n";+ struct Row {+ BenchBrush brush;+ float detail;+ };+ const std::vector<Row> rows = {+ {{"Standard, Detail 50%", Kind::Brush, BrushType::Standard}, 0.5f},+ {{"Standard, Detail 100%", Kind::Brush, BrushType::Standard}, 1.0f},+ {{"Snake Hook, Detail 50%", Kind::Brush, BrushType::SnakeHook}, 0.5f},+ {{"Clay Buildup, Detail 75%", Kind::Brush, BrushType::ClayBuildup}, 0.75f},+ {{"Smooth (simplifies), Detail 50%", Kind::Brush, BrushType::Smooth}, 0.5f},+ {{"Standard (large, r 0.4), Detail 50%", Kind::Brush, BrushType::Standard, 0.4f}, 0.5f},+ };+ for (double sizeM : o.sizesMillions) {+ const size_t target = size_t(sizeM * 1e6);+ log("Building a " + millions(double(target)) + " triangle sphere...");+ Document doc;+ doc.mesh = makeBenchSphere(target);+ doc.mesh.multires.reset(); // (as after Delete Lower)+ doc.mesh.rebuildTopology();+ doc.bvh.build(doc.mesh);+ Mesh& m = doc.mesh;+ const double nt = double(m.triangleCount()), nv = double(m.vertexCount());+ if (gpu && gpu->upload) gpu->upload(m);+ UploadOrder order;+ order.build(m);+ md << "### " << millions(nt) << " triangles (" << millions(nv) << " vertices, no subdivision levels)\n\n";+ md << "| Stroke | remesh | kernel | normals | BVH | " << (gpu ? "GPU upload | " : "")+ << "**dab total** | triangles after | stroke end | undo | redo | undo step |\n";+ md << "|---|---:|---:|---:|---:|" << (gpu ? "---:|" : "") << "---:|---:|---:|---:|---:|---:|\n";+ for (const Row& row : rows) {+ if (!o.brushFilter.empty() && row.brush.name.find(o.brushFilter) == std::string::npos) continue;+ log(" " + row.brush.name);+ doc.sculptor.dyntopo.enabled = true;+ doc.sculptor.dyntopo.detail = row.detail;+ for (double& x : doc.sculptor.dynamicTopology().phaseMs) x = 0;+ const StrokeStats s = runStroke(doc, row.brush, o.dabsPerStroke, gpu, order);+ doc.sculptor.dyntopo.enabled = false;+ {+ std::string ph = " phases:";+ for (double x : doc.sculptor.dynamicTopology().phaseMs) ph += " " + fmt("%.1f", x);+ ph += " gather:";+ for (double& x : doc.sculptor.dynamicTopology().gatherMs) { ph += " " + fmt("%.1f", x); x = 0; }+ ph += " ops " + std::to_string(doc.sculptor.dynamicTopology().stats.splits) + "/" + std::to_string(doc.sculptor.dynamicTopology().stats.collapses) + "/" + std::to_string(doc.sculptor.dynamicTopology().stats.flips);+ log(ph);+ doc.sculptor.dynamicTopology().stats = {};+ }+ const double d = std::max(s.dabs, 1);+ md << "| " << row.brush.name << " | " << fmt("%.2f", s.remesh / d) << " | " << fmt("%.2f", s.kernel / d) << " | "+ << fmt("%.2f", s.normals / d) << " | " << fmt("%.2f", s.bvh / d) << " | ";+ if (gpu) md << fmt("%.2f", s.upload / d) << " | ";+ md << "**" << fmt("%.2f", s.total / d) << "** | " << millions(double(s.triangles)) << " | " << fmt("%.1f", s.endStroke)+ << " | " << fmt("%.1f", s.undo) << " | " << fmt("%.1f", s.redo) << " | " << fmt("%.2f MB", double(s.undoBytes) / 1e6)+ << " |\n";+ doc.undo.undo(m, doc.bvh); // back to the sphere for the next row+ if (gpu && gpu->upload) gpu->upload(m);+ order.build(m);+ }+ md << "\n";+ if (o.partial) o.partial(md.str());+ }+ return md.str();+}++} // namespace+std::string runBenchmark(const BenchOptions& o, const BenchGpu* gpu) {+ if (o.dyntopo) return runDyntopoBenchmark(o, gpu);auto log = [&](const std::string& s) {if (o.log) o.log(s);};diff --git a/src/core/Benchmark.h b/src/core/Benchmark.hindex d62b4d9e..985d040d 100644--- a/src/core/Benchmark.h+++ b/src/core/Benchmark.h@@ -44,13 +44,15 @@ struct BenchOptions {// Only what the viewport costs (--bench-view): setup, the first upload, the strokes whose uploads differ// (Standard, Mask, Paint), orbiting; no other brushes, subdivision levels or project round trip.bool viewOnly = false;+ // Dynamic topology instead (--bench-dyntopo): spheres without subdivision levels, strokes that remesh.+ bool dyntopo = false;std::function<void(const std::string&)> log; // progress lines (optional)std::function<void(const std::string&)> partial; // the report so far, after each size (optional)};// Command-line options shared by sculptforge-cli and the app: --bench, --bench-sizes 4,16,32 (millions of// triangles), --bench-dabs N, --bench-no-project (skip saving / opening, which needs twice the memory),-// --bench-brushes TEXT (only the rows whose name contains TEXT), --bench-view (only the viewport's costs), --bench-out FILE. parseBenchArg returns true when argv[i] was one of them+// --bench-brushes TEXT (only the rows whose name contains TEXT), --bench-view (only the viewport's costs), --bench-dyntopo (dynamic topology strokes), --bench-out FILE. parseBenchArg returns true when argv[i] was one of them// (advancing i past its value).struct BenchCommandLine {bool run = false;diff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex 473263de..c5d7ab87 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -7,6 +7,7 @@#include "core/BrushAlpha.h"#include "core/BrushLibrary.h"#include "core/Decimate.h"+#include "core/Dyntopo.h"#include "core/EnginePresets.h"#include "core/ImageTo3D.h"#include "core/Masking.h"@@ -767,6 +768,7 @@ CommandRegistry::CommandRegistry() {registerPolygroupCommands(*this);registerSubToolCommands(*this);registerSubdivCommands(*this); // subdiv_* (core/MultiresCommands.cpp)+ registerDyntopoCommands(*this); // dyntopo (core/DyntopoCommands.cpp)registerTransformCommands(*this); // transform (core/MeshTransform.h)registerPerformanceCommands(*this); // perf_info, set_multithreading (core/Benchmark.cpp)registerPaintCommands(*this); // core/Polypaint.cppdiff --git a/src/core/Dyntopo.cpp b/src/core/Dyntopo.cppindex e7ca0c59..eb9166f4 100644--- a/src/core/Dyntopo.cpp+++ b/src/core/Dyntopo.cpp@@ -108,7 +108,7 @@ float dyntopoEdgeLength(const DyntopoSettings& s, float radius, float diagonal)}std::string dyntopoBlocker(const Mesh& mesh) {- if (mesh.multires || mesh.implicitAdjacency())+ if (mesh.multires)return "Dynamic topology needs a mesh without subdivision levels: delete the lower (or higher) levels first";if (mesh.triangleCount() == 0) return "The mesh has no triangles";return {};@@ -211,12 +211,10 @@ void DynamicTopology::killVertex(uint32_t v) {mesh_->setVertexTriangles(v, {});mesh_->setNeighbors(v, {});for (size_t k = 0; k < mirrorMaps_.size(); ++k) {- auto it = mirrorMaps_[k].find(v);- if (it == mirrorMaps_[k].end()) continue;- const uint32_t w = it->second;- mirrorMaps_[k].erase(it);- auto back = mirrorMaps_[k].find(w);- if (back != mirrorMaps_[k].end() && back->second == v) mirrorMaps_[k].erase(back);+ const uint32_t w = mirrorOf(k, v);+ if (w == kNone) continue;+ if (mirrorOf(k, w) == v) mirrorMaps_[k].stamp[w] = 0;+ mirrorMaps_[k].stamp[v] = 0;}}@@ -384,7 +382,7 @@ void DynamicTopology::compact() {if (!a.empty()) a.resize(nt);});bvh_->resizeTriangles(nt);- deadT_.assign(nt, 0);+ deadT_.resize(nt); // (every slot below nt is live again)freeT_.clear();std::sort(freeV_.begin(), freeV_.end());@@ -401,7 +399,7 @@ void DynamicTopology::compact() {if (!a.empty()) a.resize(nv);});for (size_t i = nv; i < before; ++i) m.removeLastVertexSlot();- deadV_.assign(nv, 0);+ deadV_.resize(nv);freeV_.clear();}@@ -531,59 +529,83 @@ glm::vec3 DynamicTopology::faceNormalAt(uint32_t v) const {// ---------------------------------------------------------------------------uint32_t DynamicTopology::mirrorOf(size_t k, uint32_t v) const {- const auto it = mirrorMaps_[k].find(v);- return it == mirrorMaps_[k].end() ? kNone : it->second;+ const MirrorMap& map = mirrorMaps_[k];+ return v < map.to.size() && map.stamp[v] == mirrorStamp_ ? map.to[v] : kNone;}void DynamicTopology::setMirror(size_t k, uint32_t v, uint32_t w) {- mirrorMaps_[k][v] = w;- mirrorMaps_[k][w] = v;+ MirrorMap& map = mirrorMaps_[k];+ const size_t need = size_t(std::max(v, w)) + 1;+ if (map.to.size() < need) {+ map.to.resize(need + need / 4, kNone);+ map.stamp.resize(need + need / 4, 0);+ }+ map.to[v] = w;+ map.stamp[v] = mirrorStamp_;+ map.to[w] = v;+ map.stamp[w] = mirrorStamp_;}// Pairs each vertex with the vertex at its mirror image (within eps_), for every mirror; only pairs that-// find each other both ways count.+// find each other both ways count. The match is loose because overlapping mirrored dabs near the plane don't+// move both sides exactly alike, but vertices are rarely closer than half an edge.void DynamicTopology::matchMirrors(const std::vector<uint32_t>& verts) {const Mesh& m = *mesh_;- const float cell = std::max(eps_ * 4.0f, 1e-12f);- auto key = [cell](const glm::vec3& p) {- const glm::ivec3 q = glm::ivec3(glm::floor(p / cell));- return (uint64_t(uint32_t(q.x) & 0x1FFFFF) << 42) | (uint64_t(uint32_t(q.y) & 0x1FFFFF) << 21) |- uint64_t(uint32_t(q.z) & 0x1FFFFF);+ // A grid of cells twice the tolerance (an open-addressing table of the occupied cells): a point's nearest+ // vertex within the tolerance is in one of the 2 x 2 x 2 cells around it.+ const float cell = std::max(eps_ * 2.0f, 1e-12f);+ auto cellOf = [cell](const glm::vec3& p) { return glm::ivec3(glm::floor(p / cell)); };+ auto keyOf = [](const glm::ivec3& q) {+ return (uint64_t(uint32_t(q.x) & 0x1FFFFF) << 42) | (uint64_t(uint32_t(q.y) & 0x1FFFFF) << 21) | uint64_t(uint32_t(q.z) & 0x1FFFFF);+ };+ // Each occupied cell's first vertex in the table, the rest chained through gridNext_.+ size_t slots = 16;+ while (slots < verts.size() * 2) slots *= 2;+ gridKeys_.assign(slots, ~uint64_t(0));+ gridHead_.resize(slots);+ gridNext_.resize(verts.size());+ auto slotOf = [&](uint64_t key) {+ size_t h = size_t((key * 0x9E3779B97F4A7C15ull) >> 20) & (slots - 1);+ while (gridKeys_[h] != ~uint64_t(0) && gridKeys_[h] != key) h = (h + 1) & (slots - 1);+ return h;};- std::unordered_multimap<uint64_t, uint32_t> grid;- grid.reserve(verts.size() * 2);- for (uint32_t v : verts) grid.emplace(key(m.positions[v]), v);+ for (uint32_t i = 0; i < verts.size(); ++i) {+ const uint64_t key = keyOf(cellOf(m.positions[verts[i]]));+ const size_t h = slotOf(key);+ gridNext_[i] = gridKeys_[h] == key ? gridHead_[h] : kNone;+ gridKeys_[h] = key;+ gridHead_[h] = i;+ }auto nearest = [&](const glm::vec3& p) {uint32_t best = kNone;float bestD = eps_ * eps_;- const glm::ivec3 q = glm::ivec3(glm::floor(p / cell));- for (int dz = -1; dz <= 1; ++dz)- for (int dy = -1; dy <= 1; ++dy)- for (int dx = -1; dx <= 1; ++dx) {- const glm::ivec3 c = q + glm::ivec3(dx, dy, dz);- const uint64_t k = (uint64_t(uint32_t(c.x) & 0x1FFFFF) << 42) | (uint64_t(uint32_t(c.y) & 0x1FFFFF) << 21) |- uint64_t(uint32_t(c.z) & 0x1FFFFF);- auto [b, e] = grid.equal_range(k);- for (auto it = b; it != e; ++it) {- const glm::vec3 d = m.positions[it->second] - p;- const float dd = glm::dot(d, d);- if (dd <= bestD && (best == kNone || dd < bestD || it->second < best)) {- bestD = dd;- best = it->second;- }- }+ const glm::vec3 f = p / cell;+ const glm::ivec3 q = glm::ivec3(glm::floor(f));+ const glm::ivec3 step(f.x - float(q.x) < 0.5f ? -1 : 1, f.y - float(q.y) < 0.5f ? -1 : 1, f.z - float(q.z) < 0.5f ? -1 : 1);+ for (int c = 0; c < 8; ++c) {+ const glm::ivec3 at = q + glm::ivec3(c & 1 ? step.x : 0, c & 2 ? step.y : 0, c & 4 ? step.z : 0);+ const uint64_t key = keyOf(at);+ const size_t h = slotOf(key);+ if (gridKeys_[h] != key) continue;+ for (uint32_t i = gridHead_[h]; i != kNone; i = gridNext_[i]) {+ const uint32_t w = verts[i];+ const glm::vec3 d = m.positions[w] - p;+ const float dd = glm::dot(d, d);+ if (dd < bestD || (dd == bestD && best != kNone && w < best)) {+ bestD = dd;+ best = w;}+ }+ }return best;};for (size_t k = 0; k < mirrorSigns_.size(); ++k) {- auto& map = mirrorMaps_[k];- map.clear();const glm::vec3 s = mirrorSigns_[k];for (uint32_t v : verts) {+ if (mirrorOf(k, v) != kNone) continue; // (its partner found it first)const uint32_t w = nearest(m.positions[v] * s);- if (w == kNone) continue;- if (nearest(m.positions[w] * s) != v) continue;- map[v] = w;+ if (w == kNone || nearest(m.positions[w] * s) != v) continue;+ setMirror(k, v, w);}}}@@ -800,7 +822,8 @@ bool DynamicTopology::canCollapse(uint32_t keep, uint32_t drop, const glm::vec3&if (opposite[i] == kNone) return false;}if (n == 2 && opposite[0] == opposite[1]) return false;- std::vector<uint32_t> rk, rd;+ std::vector<uint32_t>& rk = ringA_;+ std::vector<uint32_t>& rd = ringB_;ring(keep, rk);ring(drop, rd);// Link condition: the ends share exactly the neighbours across the edge's triangles (else the surface@@ -814,7 +837,7 @@ bool DynamicTopology::canCollapse(uint32_t keep, uint32_t drop, const glm::vec3&if (common != size_t(n)) return false;// Nobody left with fewer than three neighbours (no flat double triangles).if (rk.size() + rd.size() - size_t(n) - 2 < 3) return false;- std::vector<uint32_t> ro;+ std::vector<uint32_t>& ro = ringC_;for (int i = 0; i < n; ++i) {ring(opposite[i], ro);if (ro.size() <= 3) return false;@@ -855,7 +878,8 @@ void DynamicTopology::collapse(uint32_t keep, uint32_t drop, const glm::vec3& p)const int n = edgeTriangles(keep, drop, tris);for (int i = 0; i < n && i < 2; ++i) killTriangle(tris[i]);const IndexRing around = m.vertexTriangles(drop);- std::vector<uint32_t> list(around.begin(), around.end());+ std::vector<uint32_t>& list = ringA_;+ list.assign(around.begin(), around.end());for (uint32_t t : list) {glm::uvec3 tri = m.triangles[t];for (int c = 0; c < 3; ++c)@@ -944,7 +968,7 @@ bool DynamicTopology::flipGain(uint32_t a, uint32_t b, uint32_t& c, uint32_t& d)if (c == kNone || d == kNone || c == d) return false;uint32_t tmp[4];if (edgeTriangles(c, d, tmp) > 0) return false;- std::vector<uint32_t> r;+ std::vector<uint32_t>& r = ringC_;auto valence = [&](uint32_t v, int& target) {ring(v, r);target = boundaryVertex(v) ? 4 : 6;@@ -1038,7 +1062,7 @@ void DynamicTopology::flipPass() {void DynamicTopology::relaxPass() {Mesh& m = *mesh_;std::vector<std::pair<uint32_t, glm::vec3>> moves;- std::vector<uint32_t> r;+ std::vector<uint32_t>& r = ringC_;uint32_t other[2];const float r2 = radius_ * radius_;for (uint32_t v : changedV_) {@@ -1068,13 +1092,28 @@ void DynamicTopology::relaxPass() {}void DynamicTopology::gatherRegion() {+ auto t0 = std::chrono::steady_clock::now();+ auto tick = [&](int i) {+ const auto now = std::chrono::steady_clock::now();+ gatherMs[i] += std::chrono::duration<double, std::milli>(now - t0).count();+ t0 = now;+ };bvh_->queryTriangles(*mesh_, center_, radius_, regionTris_);+ tick(0);if (mirrorSigns_.empty()) return;// Every vertex of the triangles under each mirror image of the brush, to pair up.- std::vector<uint32_t> verts, tris;+ std::vector<uint32_t>& verts = regionVerts_;+ std::vector<uint32_t> tris;+ verts.clear();+ if (seen_.size() < mesh_->vertexCount()) seen_.resize(mesh_->vertexCount() + mesh_->vertexCount() / 4, 0);auto addCorners = [&](const std::vector<uint32_t>& ts) {for (uint32_t t : ts)- for (int c = 0; c < 3; ++c) verts.push_back(mesh_->triangles[t][c]);+ for (int c = 0; c < 3; ++c) {+ const uint32_t v = mesh_->triangles[t][c];+ if (seen_[v] == mirrorStamp_) continue;+ seen_[v] = mirrorStamp_;+ verts.push_back(v);+ }};addCorners(regionTris_);// (A margin: the mirror images of the corners found here must be among those found there, though@@ -1084,9 +1123,25 @@ void DynamicTopology::gatherRegion() {bvh_->queryTriangles(*mesh_, center_ * s, reach, tris);addCorners(tris);}- std::sort(verts.begin(), verts.end());- verts.erase(std::unique(verts.begin(), verts.end()), verts.end());+ tick(1);+ tick(2);+ // Matched within a third of the edge length (the target, or the mesh's own where it is finer, so the+ // search grid's cells hold a vertex or two however fine the mesh is).+ std::vector<float> lengths;+ const size_t stride = std::max<size_t>(1, regionTris_.size() / 1024);+ for (size_t i = 0; i < regionTris_.size(); i += stride) {+ const glm::uvec3& tri = mesh_->triangles[regionTris_[i]];+ lengths.push_back(glm::distance(mesh_->positions[tri.x], mesh_->positions[tri.y]));+ }+ float typical = target_;+ if (!lengths.empty()) {+ std::nth_element(lengths.begin(), lengths.begin() + std::ptrdiff_t(lengths.size() / 2), lengths.end());+ typical = std::min(typical, lengths[lengths.size() / 2]);+ }+ eps_ = std::max(typical * 0.3f, 1e-7f);+ tick(3);matchMirrors(verts);+ tick(4);}bool DynamicTopology::remesh(Mesh& mesh, BVH& bvh, const glm::vec3& center, float radius, float edgeLength,@@ -1097,6 +1152,8 @@ bool DynamicTopology::remesh(Mesh& mesh, BVH& bvh, const glm::vec3& center, floaif (!dyntopoBlocker(mesh).empty() || !(edgeLength > 0.0f) || !(radius > 0.0f)) return false;if (mesh_ && mesh_ != &mesh) return false; // (another mesh mid-stroke)if (!mesh_) {+ // A former subdivision level (its levels deleted) may still derive its adjacency from them: store it.+ if (mesh.implicitAdjacency()) mesh.rebuildTopology();if (!mesh.beginDynamicAdjacency()) return false;mesh_ = &mesh;bvh_ = &bvh;@@ -1119,25 +1176,37 @@ bool DynamicTopology::remesh(Mesh& mesh, BVH& bvh, const glm::vec3& center, floatarget_ = edgeLength;splitLen2_ = (edgeLength * 4.0f / 3.0f) * (edgeLength * 4.0f / 3.0f);collapseLen2_ = (edgeLength * 0.6f) * (edgeLength * 0.6f);- // Mirror images are matched loosely: overlapping mirrored dabs near the plane don't move both sides- // exactly alike, but vertices are rarely closer than half an edge.- eps_ = std::max(edgeLength * 0.3f, 1e-7f);mirrorSigns_.assign(mirrors.size() > 1 ? mirrors.begin() + 1 : mirrors.end(), mirrors.end());mirrorMaps_.resize(mirrorSigns_.size());- for (auto& map : mirrorMaps_) map.clear();+ if (++mirrorStamp_ == 0) { // (wrapped: forget every old entry)+ for (MirrorMap& map : mirrorMaps_) std::fill(map.stamp.begin(), map.stamp.end(), 0);+ mirrorStamp_ = 1;+ }ops_ = 0;maxOps_ = 6000; // (bounds a dab's time: a big brush over fine triangles coarsens them over several dabs)+ auto lap = std::chrono::steady_clock::now();+ auto phase = [&](int i) {+ const auto now = std::chrono::steady_clock::now();+ phaseMs[i] += std::chrono::duration<double, std::milli>(now - lap).count();+ lap = now;+ };gatherRegion();+ phase(0);if (regionTris_.empty()) return false;splitPass();bvh.refitChanged(mesh);bvh.queryTriangles(mesh, center_, radius_, regionTris_);+ phase(1);collapsePass();+ phase(2);flipPass();+ phase(3);relaxPass();+ phase(4);const bool changed = !changedV_.empty() || !changedT_.empty();compact();+ phase(5);// Rings and normals of everything that changed, the BVH's boxes, and what the renderer must patch.const uint32_t nv = uint32_t(mesh.vertexCount());@@ -1167,6 +1236,7 @@ bool DynamicTopology::remesh(Mesh& mesh, BVH& bvh, const glm::vec3& center, floabvh.refitChanged(mesh);mesh.changedTriangles.insert(mesh.changedTriangles.end(), changedT_.begin(), changedT_.end());changedT_.clear();+ phase(6);lastMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - clock).count();return changed;}@@ -1185,7 +1255,12 @@ std::unique_ptr<TopologyUndo> DynamicTopology::finish(Mesh& mesh, BVH& bvh) {std::vector<uint8_t>().swap(deadV_);std::vector<uint8_t>().swap(deadT_);std::vector<uint8_t>().swap(changedVFlag_);- for (auto& map : mirrorMaps_) map.clear();+ std::vector<MirrorMap>().swap(mirrorMaps_);+ std::vector<uint64_t>().swap(gridKeys_);+ std::vector<uint32_t>().swap(gridHead_);+ std::vector<uint32_t>().swap(gridNext_);+ std::vector<uint32_t>().swap(seen_);+ std::vector<uint32_t>().swap(regionVerts_);if (undo->vertexSlots.empty() && undo->triangleSlots.empty() && undo->uvs.empty()) return nullptr;return undo;}diff --git a/src/core/Dyntopo.h b/src/core/Dyntopo.hindex 0ff5cd5e..8576c63b 100644--- a/src/core/Dyntopo.h+++ b/src/core/Dyntopo.h@@ -30,7 +30,6 @@#include <memory>#include <span>#include <string>-#include <unordered_map>#include <utility>#include <vector>@@ -49,6 +48,12 @@ float dyntopoEdgeLength(const DyntopoSettings& s, float radius, float diagonal);// Why `mesh` can't be remeshed by dynamic topology ("" when it can).std::string dyntopoBlocker(const Mesh& mesh);+// "Dynamic topology on: Detail 50 (follows the brush size)".+std::string dyntopoSummary(const DyntopoSettings& s);++class CommandRegistry;+// dyntopo: on / off, Detail, constant detail (core/DyntopoCommands.cpp).+void registerDyntopoCommands(CommandRegistry& registry);// Per-vertex and per-triangle values of a mesh at some slots (arrays the mesh doesn't have stay empty).struct TopologyVertexValues {@@ -108,6 +113,8 @@ public:DyntopoStats stats; // since the last resetdouble lastMs = 0.0; // the last remesh's time+ double phaseMs[8] = {}; // TEMP+ double gatherMs[8] = {}; // TEMPprivate:struct Edge {@@ -176,7 +183,15 @@ private:glm::vec3 center_{0.0f};float radius_ = 0.0f, target_ = 0.0f, splitLen2_ = 0.0f, collapseLen2_ = 0.0f, eps_ = 0.0f;std::vector<glm::vec3> mirrorSigns_; // without the identity- std::vector<std::unordered_map<uint32_t, uint32_t>> mirrorMaps_;+ // Per mirror: each vertex's image (valid where stamp == mirrorStamp_, so a new remesh forgets them all).+ struct MirrorMap {+ std::vector<uint32_t> to, stamp;+ };+ std::vector<MirrorMap> mirrorMaps_;+ uint32_t mirrorStamp_ = 0;+ std::vector<uint64_t> gridKeys_; // matchMirrors' search grid+ std::vector<uint32_t> gridHead_, gridNext_;+ std::vector<uint32_t> seen_, regionVerts_; // gatherRegion: vertices listed this remesh (seen_ == mirrorStamp_)std::vector<uint8_t> deadV_, deadT_;std::vector<uint32_t> freeV_, freeT_;std::vector<uint32_t> changedV_, changedT_, regionTris_;@@ -186,7 +201,7 @@ private:std::vector<uint32_t> recordedNow_;mutable bool orbitIncomplete_ = false; // the last orbit() missed a mirror imagesize_t ops_ = 0, maxOps_ = 0;- mutable std::vector<uint32_t> scratch_, scratch2_;+ mutable std::vector<uint32_t> scratch_, scratch2_, ringA_, ringB_, ringC_;};} // namespace sfdiff --git a/src/core/DyntopoCommands.cpp b/src/core/DyntopoCommands.cppnew file mode 100644index 00000000..581c2f32--- /dev/null+++ b/src/core/DyntopoCommands.cpp@@ -0,0 +1,44 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/Commands.h"+#include "core/Dyntopo.h"++#include <algorithm>+#include <cmath>++namespace sf {++std::string dyntopoSummary(const DyntopoSettings& s) {+ const int detail = int(std::lround(std::clamp(s.detail, 0.0f, 1.0f) * 100.0f));+ return std::string("Dynamic topology ") + (s.enabled ? "on" : "off") + ": Detail " + std::to_string(detail) ++ (s.constantDetail ? " (one size for the whole mesh)" : " (follows the brush size)");+}++void registerDyntopoCommands(CommandRegistry& registry) {+ using T = ParamSpec::Type;+ registry.add({"dyntopo",+ "Dynamic topology (ZBrush's Sculptris Pro): while on, brush strokes add triangles where they need "+ "detail and remove them where they don't, so shapes can be pulled out without stretching. Needs a "+ "mesh without subdivision levels; quads under the brush become triangles and UVs are dropped (undo "+ "brings them back). Without arguments, reports the settings.",+ {{"enabled", T::Bool, "true = on, false = off.", false},+ {"detail", T::Number, "Detail 0-100: how small the triangles get (default 50).", false},+ {"constant", T::Bool,+ "false (default) = the triangle size follows the brush size on screen (zoom in or shrink the brush "+ "for finer detail); true = one size for the whole mesh, set by Detail.",+ false}},+ [](Document& doc, const Args& a) -> CommandResult {+ DyntopoSettings& s = doc.sculptor.dyntopo;+ const bool enable = argBool(a, "enabled", s.enabled);+ if (enable && !s.enabled) {+ const std::string why = dyntopoBlocker(doc.mesh);+ if (!why.empty()) return {false, why};+ }+ if (a.count("detail")) s.detail = float(std::clamp(argNumber(a, "detail", 50.0), 0.0, 100.0) / 100.0);+ s.constantDetail = argBool(a, "constant", s.constantDetail);+ s.enabled = enable;+ return {true, dyntopoSummary(s)};+ }});+}++} // namespace sfdiff --git a/src/render/Renderer.cpp b/src/render/Renderer.cppindex c4ae188a..1d6fc436 100644--- a/src/render/Renderer.cpp+++ b/src/render/Renderer.cpp@@ -623,6 +623,13 @@ void Renderer::freeSlot(MeshSlot& s) {gl::DeleteVertexArrays(1, &s.vao);gl::DeleteVertexArrays(1, &s.lineVao);gl::DeleteVertexArrays(1, &s.proxyVao);+ if (s.patchVao) {+ for (GLuint* b : {&s.patchVertices, &s.patchIndices, &s.patchLines, &s.patchColors, &s.patchMask, &s.patchGroupData})+ gl::DeleteBuffers(1, b);+ gl::DeleteTextures(1, &s.patchGroupTexture);+ gl::DeleteVertexArrays(1, &s.patchVao);+ gl::DeleteVertexArrays(1, &s.patchLineVao);+ }s = MeshSlot();}@@ -630,6 +637,7 @@ size_t Renderer::gpuBytes() const {size_t total = 0;for (const MeshSlot& s : slots_) {for (size_t b : s.bytes) total += b;+ total += s.patchBytes;if (s.proxyAllocated) total += (s.order.triangleCount() / 4) * 3 * sizeof(uint16_t);if (s.paintTexture) total += size_t(s.textureW) * size_t(s.textureH) * 4 * 4 / 3; // with mipmaps}@@ -903,6 +911,7 @@ void Renderer::uploadVertices(MeshSlot& s, const Mesh& mesh, bool full) {const std::span<const uint32_t> order = s.order.fromGpu();std::atomic<bool> outside{false};const bool normals = mesh.normals.size() == mesh.vertexCount();+ const uint32_t nv = uint32_t(mesh.vertexCount());// Per block, hashes of what it last sent (positions; normals and curvature): a block a dab marked but didn't// change (paint, mask) isn't sent again, and a cluster whose positions didn't move keeps its bounds and proxy.s.blockHash.resize(nb * 2, 0);@@ -915,9 +924,10 @@ void Renderer::uploadVertices(MeshSlot& s, const Mesh& mesh, bool full) {uint64_t hp = 0, hn = 0;for (uint32_t i = b; i < e; ++i) {const uint32_t v = order[i];- PackedVertex pv; // packed here and stored once: `out` may be mapped GPU memory, slow to read back- inside &= packVertex(s.grid, mesh.positions[v], normals ? mesh.normals[v] : glm::vec3(0.0f, 0.0f, 1.0f),- curvatureAt(mesh, v), pv);+ PackedVertex pv{}; // packed here and stored once: `out` may be mapped GPU memory, slow to read back+ if (v < nv) // (else a vertex dynamic topology removed, which only patched clusters named)+ inside &= packVertex(s.grid, mesh.positions[v], normals ? mesh.normals[v] : glm::vec3(0.0f, 0.0f, 1.0f),+ curvatureAt(mesh, v), pv);out[i - b] = pv;hp = (hp ^ (uint64_t(pv.pos[0]) | uint64_t(pv.pos[1]) << 32)) * 0x100000001B3ull + i;hn = (hn ^ pv.normal) * 0x100000001B3ull + i;@@ -974,7 +984,8 @@ void Renderer::updateBounds(MeshSlot& s, const Mesh& mesh, bool all, bool computpoolFor(cullScratch_.size(), [&](size_t i0, size_t i1) {for (size_t i = i0; i < i1; ++i) {const uint32_t c = cullScratch_[i];- s.bounds[c] = clusterBounds(mesh, s.order, c);+ const bool patched = c < s.clusterPatch.size() && s.clusterPatch[c] != ~0u; // (drawn by its patch)+ s.bounds[c] = patched ? ClusterBounds() : clusterBounds(mesh, s.order, c);}}, 1, 2);s.box = AABB();@@ -1009,6 +1020,10 @@ void Renderer::uploadIndices(MeshSlot& s, const Mesh& mesh) {const size_t first = s.order.firstTriangle(c);const uint32_t count = s.order.clusterTriangles(c);uint16_t* out = staging.data() + (first - t0) * 3;+ if (c < s.clusterPatch.size() && s.clusterPatch[c] != ~0u) { // drawn by its patch+ s.drawCount[c] = 0;+ continue;+ }if (!hidden) {s.order.localTriangles(mesh, c, out);s.drawCount[c] = GLsizei(count * 3);@@ -1075,6 +1090,7 @@ void Renderer::uploadFaces(MeshSlot& s, const Mesh& mesh, bool wantUvs, bool indif (!drawnTris.empty()) poolFor(nc, [&](size_t c0, size_t c1) {for (size_t c = c0; c < c1; ++c) {uint32_t* out = drawnTris.data() + s.primBase[c];+ if (s.drawCount[c] == 0) continue; // (nothing drawn: hidden, or drawn by a patch)for (uint32_t i = 0; i < s.order.clusterTriangles(uint32_t(c)); ++i) {const uint32_t t = s.order.triangle(uint32_t(c), i);if (!hidden || !mesh.hidden[t]) *out++ = t;@@ -1148,6 +1164,7 @@ void Renderer::buildLines(MeshSlot& s, const Mesh& mesh) {poolFor(nc, [&](size_t c0, size_t c1) {thread_local std::vector<uint16_t> local;for (size_t c = c0; c < c1; ++c) {+ if (c < s.clusterPatch.size() && s.clusterPatch[c] != ~0u) continue; // drawn by its patchconst uint32_t count = s.order.clusterTriangles(uint32_t(c));local.resize(size_t(count) * 3);s.order.localTriangles(mesh, uint32_t(c), local.data());@@ -1202,8 +1219,13 @@ void Renderer::buildProxies(MeshSlot& s, const Mesh& mesh) {s.proxyCount.resize(nc, 0);s.proxyBounds.resize(nc);cullScratch_.clear();- for (uint32_t c = 0; c < nc; ++c)+ for (uint32_t c = 0; c < nc; ++c) {+ if (c < s.clusterPatch.size() && s.clusterPatch[c] != ~0u) { // drawn by its patch+ s.proxyStale[c] = 0;+ s.proxyCount[c] = 0;+ }if (s.proxyStale[c]) cullScratch_.push_back(c);+ }if (cullScratch_.empty()) return;if (!s.proxyAllocated) {gl::BindVertexArray(s.proxyVao);@@ -1232,13 +1254,328 @@ void Renderer::buildProxies(MeshSlot& s, const Mesh& mesh) {gl::BindVertexArray(0);}+// ---------------------------------------------------------------------------+// Dynamic topology patches (MeshSlot::patches)+// ---------------------------------------------------------------------------++namespace {++constexpr uint32_t kPatchTriangles = UploadOrder::kClusterTriangles; // per part: a cluster's worth+constexpr uint32_t kPatchVertices = 3 * kPatchTriangles; // (local indices stay 16-bit)+constexpr uint32_t kPatchLineIndices = 6 * kPatchTriangles; // 2 per edge, 3 edges per triangle at most+constexpr uint32_t kTailPatch = 0x80000000u;+constexpr uint32_t kNoPatch = ~0u;++} // namespace++void Renderer::resetPatches(MeshSlot& s) {+ s.patches.clear();+ s.clusterPatch.clear();+ s.tailPatch.clear();+}++bool Renderer::notePatches(MeshSlot& s, const Mesh& mesh) {+ const size_t nc = s.order.clusters().size();+ if (s.clusterPatch.size() != nc) s.clusterPatch.assign(nc, kNoPatch);+ if (s.chunkCluster.empty() && s.layoutTriangles > 0) { // which cluster each chunk of the layout went to+ s.chunkCluster.assign((size_t(s.layoutTriangles) + UploadOrder::kChunkTriangles - 1) >> UploadOrder::kChunkShift, 0);+ for (uint32_t c = 0; c < nc; ++c)+ for (uint32_t i = 0; i < s.order.clusterTriangles(c); i += UploadOrder::kChunkTriangles)+ s.chunkCluster[s.order.triangle(c, i) >> UploadOrder::kChunkShift] = c;+ }+ // More than this many and a full upload (a fresh layout) is cheaper to keep drawing.+ const size_t limit = std::max<size_t>(64, nc / 4);+ for (uint32_t t : mesh.changedTriangles) {+ uint32_t* slotOfPatch;+ uint32_t key;+ if (t < s.layoutTriangles) {+ const uint32_t chunk = t >> UploadOrder::kChunkShift;+ if (chunk >= s.chunkCluster.size()) return false;+ key = s.chunkCluster[chunk];+ slotOfPatch = &s.clusterPatch[key];+ } else {+ const uint32_t block = (t - s.layoutTriangles) / kPatchTriangles;+ if (block >= s.tailPatch.size()) s.tailPatch.resize(size_t(block) + 1, kNoPatch);+ key = kTailPatch + block;+ slotOfPatch = &s.tailPatch[block];+ }+ if (*slotOfPatch == kNoPatch) {+ if (s.patches.size() >= limit) return false;+ *slotOfPatch = uint32_t(s.patches.size());+ MeshSlot::Patch& p = s.patches.emplace_back();+ p.key = key;+ p.part = uint32_t(s.patches.size() - 1);+ if (key < kTailPatch) { // the layout no longer draws this cluster+ s.drawnTriangles -= std::min<size_t>(s.drawnTriangles, size_t(s.drawCount[key]) / 3);+ s.drawCount[key] = 0;+ if (key < s.lineCount.size()) s.lineCount[key] = 0;+ if (key < s.proxyCount.size()) s.proxyCount[key] = 0;+ if (key < s.bounds.size()) s.bounds[key] = ClusterBounds();+ }+ }+ s.patches[*slotOfPatch].stale = true;+ }+ return true;+}++bool Renderer::preparePatches(MeshSlot& s, const Mesh& mesh, bool wireframe) {+ const uint32_t nt = uint32_t(mesh.triangleCount()), nv = uint32_t(mesh.vertexCount());+ if (patchLocal_.size() < nv) {+ patchLocal_.resize(nv + nv / 4);+ patchStamp_.resize(nv + nv / 4, 0);+ }+ if (wireframe && !s.patchLinesOn)+ for (MeshSlot::Patch& p : s.patches) p.stale = true; // (their edges weren't built)+ const bool hidden = mesh.hidden.size() == nt && nt > 0;+ const bool groups = mesh.polygroups.size() == nt && nt > 0;+ for (MeshSlot::Patch& p : s.patches) {+ if (!p.stale) continue;+ if (++patchStampValue_ == 0) {+ std::fill(patchStamp_.begin(), patchStamp_.end(), 0);+ patchStampValue_ = 1;+ }+ p.verts.clear();+ p.local.clear();+ p.groups.clear();+ auto add = [&](uint32_t t) {+ if (t >= nt || (hidden && mesh.hidden[t])) return;+ const glm::uvec3& tri = mesh.triangles[t];+ for (int c = 0; c < 3; ++c) {+ const uint32_t v = tri[c];+ if (patchStamp_[v] != patchStampValue_) {+ patchStamp_[v] = patchStampValue_;+ patchLocal_[v] = uint32_t(p.verts.size());+ p.verts.push_back(v);+ }+ p.local.push_back(uint16_t(std::min<uint32_t>(patchLocal_[v], 0xFFFF)));+ }+ if (groups) p.groups.push_back(mesh.polygroups[t]);+ };+ if (p.key < kTailPatch) {+ for (uint32_t i = 0; i < s.order.clusterTriangles(p.key); ++i) add(s.order.triangle(p.key, i));+ } else {+ const uint32_t first = s.layoutTriangles + (p.key - kTailPatch) * kPatchTriangles;+ for (uint32_t t = first; t < first + kPatchTriangles && t < nt; ++t) add(t);+ }+ if (p.verts.size() > kPatchVertices) return false; // scattered triangles: time for a fresh layout+ }+ return true;+}++void Renderer::uploadPatches(MeshSlot& s, const Mesh& mesh, bool wireframe) {+ if (s.patches.empty()) return;+ const uint32_t nv = uint32_t(mesh.vertexCount());+ const bool colors = nv > 0 && mesh.colors.size() == nv, mask = nv > 0 && mesh.mask.size() == nv;+ const bool normals = mesh.normals.size() == nv;+ bool all = s.patchGrid.step != s.grid.step || s.patchGrid.origin != s.grid.origin || colors != s.patchColorsOn ||+ mask != s.patchMaskOn;+ if (!s.patchVao) {+ gl::GenVertexArrays(1, &s.patchVao);+ gl::GenVertexArrays(1, &s.patchLineVao);+ for (GLuint* b : {&s.patchVertices, &s.patchIndices, &s.patchLines, &s.patchColors, &s.patchMask, &s.patchGroupData})+ gl::GenBuffers(1, b);+ gl::GenTextures(1, &s.patchGroupTexture);+ for (GLuint vao : {s.patchVao, s.patchLineVao}) {+ gl::BindVertexArray(vao);+ gl::BindBuffer(GL_ARRAY_BUFFER, s.patchVertices);+ gl::EnableVertexAttribArray(0);+ gl::VertexAttribIPointer(0, 2, GL_UNSIGNED_INT, sizeof(PackedVertex), nullptr);+ if (vao == s.patchLineVao) {+ gl::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, s.patchLines);+ continue;+ }+ gl::EnableVertexAttribArray(1);+ gl::VertexAttribIPointer(1, 1, GL_UNSIGNED_INT, sizeof(PackedVertex), reinterpret_cast<const void*>(2 * sizeof(uint32_t)));+ gl::BindBuffer(GL_ARRAY_BUFFER, s.patchColors);+ gl::VertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, 4, nullptr);+ gl::BindBuffer(GL_ARRAY_BUFFER, s.patchMask);+ gl::VertexAttribPointer(3, 1, GL_UNSIGNED_BYTE, GL_TRUE, 1, nullptr);+ gl::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, s.patchIndices);+ }+ gl::BindVertexArray(0);+ }+ if (s.patches.size() > s.patchParts) { // room for more parts: new buffers, everything sent again+ s.patchParts = std::max<size_t>({s.patches.size(), s.patchParts * 2, 8});+ const size_t parts = s.patchParts;+ auto alloc = [](GLenum target, GLuint buffer, size_t bytes) {+ gl::BindBuffer(target, buffer);+ gl::BufferData(target, GLsizeiptr(bytes), nullptr, GL_DYNAMIC_DRAW);+ };+ alloc(GL_ARRAY_BUFFER, s.patchVertices, parts * kPatchVertices * sizeof(PackedVertex));+ alloc(GL_ARRAY_BUFFER, s.patchColors, parts * kPatchVertices * sizeof(uint32_t));+ alloc(GL_ARRAY_BUFFER, s.patchMask, parts * kPatchVertices);+ alloc(GL_TEXTURE_BUFFER, s.patchGroupData, parts * kPatchTriangles * sizeof(uint32_t));+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);+ gl::BindTexture(GL_TEXTURE_BUFFER, s.patchGroupTexture);+ gl::TexBuffer(GL_TEXTURE_BUFFER, GL_R32UI, s.patchGroupData);+ gl::BindTexture(GL_TEXTURE_BUFFER, 0);+ gl::BindVertexArray(s.patchVao);+ gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr(parts * kPatchTriangles * 3 * sizeof(uint16_t)), nullptr, GL_DYNAMIC_DRAW);+ gl::BindVertexArray(s.patchLineVao);+ gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr(parts * kPatchLineIndices * sizeof(uint16_t)), nullptr, GL_DYNAMIC_DRAW);+ gl::BindVertexArray(0);+ s.patchBytes = parts * (kPatchVertices * (sizeof(PackedVertex) + 5) + kPatchTriangles * (3 * 2 + 4) + kPatchLineIndices * 2);+ for (MeshSlot::Patch& p : s.patches) p.uploaded = false;+ all = true;+ }+ if (colors != s.patchColorsOn || mask != s.patchMaskOn) {+ gl::BindVertexArray(s.patchVao);+ if (colors) gl::EnableVertexAttribArray(2);+ else gl::DisableVertexAttribArray(2);+ if (mask) gl::EnableVertexAttribArray(3);+ else gl::DisableVertexAttribArray(3);+ gl::BindVertexArray(0);+ s.patchColorsOn = colors;+ s.patchMaskOn = mask;+ }+ std::vector<PackedVertex> packed;+ std::vector<uint32_t> packedColors;+ std::vector<uint8_t> packedMask;+ std::vector<uint16_t> lines;+ std::vector<uint64_t> edges;+ bool outside = false;+ const bool anyDirty = mesh.dirtyBegin < mesh.dirtyEnd;+ for (MeshSlot::Patch& p : s.patches) {+ const bool topology = p.stale || !p.uploaded;+ bool verts = topology || all;+ if (!verts && anyDirty)+ for (uint32_t v : p.verts)+ if (mesh.vertexDirty(v)) {+ verts = true;+ break;+ }+ if (topology) {+ if (p.stale) {+ p.indices = uint32_t(p.local.size());+ // The wireframe: each edge of the patch once, quad diagonals left out as the layout does.+ p.lines = 0;+ if (wireframe) {+ edges.clear();+ const uint32_t nt = uint32_t(mesh.triangleCount());+ size_t k = 0;+ auto addEdges = [&](uint32_t t) {+ if (t >= nt || mesh.triangleHidden(t)) return;+ const int diagonal = hiddenDiagonal(mesh, t);+ for (int e = 0; e < 3; ++e) {+ const uint64_t a = p.local[k + size_t(e)], b = p.local[k + size_t((e + 1) % 3)];+ if (e != diagonal) edges.push_back(std::min(a, b) << 16 | std::max(a, b));+ }+ k += 3;+ };+ if (p.key < kTailPatch) {+ for (uint32_t i = 0; i < s.order.clusterTriangles(p.key); ++i) addEdges(s.order.triangle(p.key, i));+ } else {+ const uint32_t first = s.layoutTriangles + (p.key - kTailPatch) * kPatchTriangles;+ for (uint32_t t = first; t < first + kPatchTriangles && t < nt; ++t) addEdges(t);+ }+ std::sort(edges.begin(), edges.end());+ edges.erase(std::unique(edges.begin(), edges.end()), edges.end());+ lines.clear();+ for (uint64_t e : edges) {+ lines.push_back(uint16_t(e >> 16));+ lines.push_back(uint16_t(e & 0xFFFF));+ }+ p.lines = uint32_t(std::min<size_t>(lines.size(), kPatchLineIndices));+ }+ }+ gl::BindVertexArray(s.patchVao);+ if (!p.local.empty())+ gl::BufferSubData(GL_ELEMENT_ARRAY_BUFFER, GLintptr(size_t(p.part) * kPatchTriangles * 3 * sizeof(uint16_t)),+ GLsizeiptr(p.local.size() * sizeof(uint16_t)), p.local.data());+ if (wireframe && p.lines > 0) {+ gl::BindVertexArray(s.patchLineVao);+ gl::BufferSubData(GL_ELEMENT_ARRAY_BUFFER, GLintptr(size_t(p.part) * kPatchLineIndices * sizeof(uint16_t)),+ GLsizeiptr(size_t(p.lines) * sizeof(uint16_t)), lines.data());+ }+ gl::BindVertexArray(0);+ if (!p.groups.empty()) {+ gl::BindBuffer(GL_TEXTURE_BUFFER, s.patchGroupData);+ gl::BufferSubData(GL_TEXTURE_BUFFER, GLintptr(size_t(p.part) * kPatchTriangles * sizeof(uint32_t)),+ GLsizeiptr(p.groups.size() * sizeof(uint32_t)), p.groups.data());+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);+ }+ if (p.stale) {+ std::vector<uint16_t>().swap(p.local);+ std::vector<uint32_t>().swap(p.groups);+ }+ p.stale = false;+ p.uploaded = true;+ }+ if (!verts || p.verts.empty()) continue;+ const size_t n = p.verts.size();+ packed.resize(n);+ glm::vec3 lo(std::numeric_limits<float>::max()), hi(std::numeric_limits<float>::lowest());+ for (size_t i = 0; i < n; ++i) {+ const uint32_t v = p.verts[i];+ const glm::vec3& pos = mesh.positions[v];+ outside |= !packVertex(s.grid, pos, normals ? mesh.normals[v] : glm::vec3(0.0f, 0.0f, 1.0f), curvatureAt(mesh, v), packed[i]);+ lo = glm::min(lo, pos);+ hi = glm::max(hi, pos);+ }+ p.bounds = ClusterBounds();+ p.bounds.center = (lo + hi) * 0.5f;+ p.bounds.radius = glm::length(hi - lo) * 0.5f;+ gl::BindBuffer(GL_ARRAY_BUFFER, s.patchVertices);+ gl::BufferSubData(GL_ARRAY_BUFFER, GLintptr(size_t(p.part) * kPatchVertices * sizeof(PackedVertex)), GLsizeiptr(n * sizeof(PackedVertex)),+ packed.data());+ if (colors) {+ packedColors.resize(n);+ for (size_t i = 0; i < n; ++i) packedColors[i] = packColor(mesh.colors[p.verts[i]]);+ gl::BindBuffer(GL_ARRAY_BUFFER, s.patchColors);+ gl::BufferSubData(GL_ARRAY_BUFFER, GLintptr(size_t(p.part) * kPatchVertices * sizeof(uint32_t)), GLsizeiptr(n * sizeof(uint32_t)),+ packedColors.data());+ }+ if (mask) {+ packedMask.resize(n);+ for (size_t i = 0; i < n; ++i) packedMask[i] = packMask(mesh.mask[p.verts[i]]);+ gl::BindBuffer(GL_ARRAY_BUFFER, s.patchMask);+ gl::BufferSubData(GL_ARRAY_BUFFER, GLintptr(size_t(p.part) * kPatchVertices), GLsizeiptr(n), packedMask.data());+ }+ }+ gl::BindBuffer(GL_ARRAY_BUFFER, 0);+ s.patchGrid = s.grid;+ s.patchLinesOn = wireframe;+ if (outside) s.fresh = true; // a vertex left the position grid: a full upload (with a new grid) next time+ // The totals the culling and drawing use: the drawn triangles, the closed mesh's volume, its box.+ size_t drawn = 0;+ for (size_t c = 0; c < s.drawCount.size(); ++c) drawn += size_t(s.drawCount[c]) / 3;+ for (const MeshSlot::Patch& p : s.patches) {+ drawn += p.indices / 3;+ if (p.bounds.radius >= 0.0f) {+ s.box.expand(p.bounds.center - glm::vec3(p.bounds.radius));+ s.box.expand(p.bounds.center + glm::vec3(p.bounds.radius));+ }+ }+ s.drawnTriangles = drawn;+}++void Renderer::drawPatches(const MeshSlot& s, GLenum mode, Part part, GLint primBaseLocation) {+ for (const MeshSlot::Patch& p : s.patches) {+ const uint32_t count = part == Part::Lines ? p.lines : p.indices;+ if (count == 0 || !insideFrustum(frameCull_, p.bounds)) continue;+ if (primBaseLocation >= 0) gl::Uniform1i(primBaseLocation, GLint(p.part * kPatchTriangles));+ const size_t first = part == Part::Lines ? size_t(p.part) * kPatchLineIndices : size_t(p.part) * kPatchTriangles * 3;+ gl::DrawElementsBaseVertex(mode, GLsizei(count), GL_UNSIGNED_SHORT, reinterpret_cast<const void*>(first * sizeof(uint16_t)),+ GLint(p.part * kPatchVertices));+ if (part != Part::Lines) lastDrawn_ += count / 3;+ }+ if (primBaseLocation >= 0) gl::Uniform1i(primBaseLocation, -1);+}+void Renderer::sync(MeshSlot& s, Mesh& mesh, const NormalMapView* normalMap, bool wireframe) {const size_t nv = mesh.vertexCount();if (normalMap && (!normalMap->rgb || !normalMap->tangents || normalMap->tangents->size() != mesh.uvs.size() ||!mesh.hasUvs() || normalMap->rgb->size() != size_t(normalMap->width) * size_t(normalMap->height) * 3))normalMap = nullptr; // made for another meshconst bool wantUvs = hasTexture(mesh) || normalMap;- const bool full = s.fresh || mesh.topologyDirty || nv != s.vertexCapacity;+ // Dynamic topology changes topology a little at a time: patches (notePatches) instead of a full upload,+ // until there are too many of them.+ const bool patched = !s.patches.empty() || !mesh.changedTriangles.empty();+ bool full = s.fresh || mesh.topologyDirty || (nv != s.vertexCapacity && !patched) || (patched && wantUvs);+ if (!full && !mesh.changedTriangles.empty() && !notePatches(s, mesh)) full = true;+ if (!full && !s.patches.empty() && mesh.facesDirty)+ for (MeshSlot::Patch& p : s.patches) p.stale = true; // (groups or hidden triangles changed)+ if (!full && !s.patches.empty() && !preparePatches(s, mesh, wireframe)) full = true;// The GPU keeps the vertices in the slot's cluster layout (core/UploadOrder.h), so a dab re-sends a few// short ranges holding what it changed, gathered from the mesh arrays.bool indicesDone = false;@@ -1270,7 +1607,10 @@ void Renderer::sync(MeshSlot& s, Mesh& mesh, const NormalMapView* normalMap, boo}s.drawCount[c] = GLsizei(drawn * 3);};+ resetPatches(s);s.order.build(mesh, write);+ s.layoutTriangles = uint32_t(nt);+ std::vector<uint32_t>().swap(s.chunkCluster); // (made when patches first need it)indicesDone = indices && gl::UnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);gl::BindVertexArray(0);s.grid = PositionGrid::around(meshBounds(mesh));@@ -1343,14 +1683,17 @@ void Renderer::sync(MeshSlot& s, Mesh& mesh, const NormalMapView* normalMap, boouploaded = present;bytes = present ? ns * elementSize : 0;};- syncAttribute(s.colorBuffer, 2, s.hasColors, gatherWith<uint32_t>(order, [&](uint32_t v) { return packColor(mesh.colors[v]); }),+ // (A slot may name a vertex dynamic topology removed since the layout was made: only patched clusters use it.)+ syncAttribute(s.colorBuffer, 2, s.hasColors,+ gatherWith<uint32_t>(order, [&](uint32_t v) { return v < nv ? packColor(mesh.colors[v]) : 0u; }),sizeof(uint32_t), nv > 0 && mesh.colors.size() == nv, s.bytes[3]);- syncAttribute(s.maskBuffer, 3, s.hasMask, gatherWith<uint8_t>(order, [&](uint32_t v) { return packMask(mesh.mask[v]); }),+ syncAttribute(s.maskBuffer, 3, s.hasMask, gatherWith<uint8_t>(order, [&](uint32_t v) { return v < nv ? packMask(mesh.mask[v]) : uint8_t(0); }),sizeof(uint8_t), nv > 0 && mesh.mask.size() == nv, s.bytes[4]);// Scratch only: don't keep a big upload's staging copy around.if (staging_.capacity() > (size_t(1) << 22)) std::vector<uint8_t>().swap(staging_);gl::BindBuffer(GL_ARRAY_BUFFER, 0);s.fresh = false;+ uploadPatches(s, mesh, wireframe); // (may ask for a full upload next time)mesh.clearDirty();}@@ -1676,6 +2019,14 @@ void Renderer::draw(const Camera& camera, int targetWidth, int targetHeight, congl::Uniform3fv(gl::GetUniformLocation(wireProgram_, "uGridOrigin"), 1, glm::value_ptr(s->grid.origin));gl::Uniform1f(gl::GetUniformLocation(wireProgram_, "uGridStep"), s->grid.step);cull(*s, frameCull_);+ if (!s->patches.empty() && s->patchVao) { // dynamic topology's patches+ const bool lines = s->patchLinesOn;+ gl::Uniform1f(gl::GetUniformLocation(wireProgram_, "uAlpha"), lines ? 0.5775f : 0.35f);+ if (!lines) gl::PolygonMode(GL_FRONT_AND_BACK, GL_LINE);+ gl::BindVertexArray(lines ? s->patchLineVao : s->patchVao);+ drawPatches(*s, lines ? GL_LINES : GL_TRIANGLES, lines ? Part::Lines : Part::Triangles, -1);+ if (!lines) gl::PolygonMode(GL_FRONT_AND_BACK, GL_FILL);+ }if (s->linesValid) {gl::Uniform1f(gl::GetUniformLocation(wireProgram_, "uAlpha"), 0.5775f); // 1 - (1 - 0.35)^2gl::BindVertexArray(s->lineVao);@@ -1708,15 +2059,23 @@ void Renderer::cull(const MeshSlot& s, const CullView& frame, bool proxy) {v.backfaces = s.closed && s.volume > 0.0 && !s.anyHidden && s.box.valid() &&(e.x < s.box.min.x || e.y < s.box.min.y || e.z < s.box.min.z || e.x > s.box.max.x || e.y > s.box.max.y ||e.z > s.box.max.z);+ auto reachesNear = [&](const ClusterBounds& b) {+ if (b.radius < 0.0f) return false;+ const float z = glm::dot(b.center - e, v.forward);+ return z - b.radius < v.nearDistance * 1.01f && z + b.radius > 0.0f;+ };if (v.backfaces)- for (const ClusterBounds& b : s.bounds) {- if (b.radius < 0.0f) continue;- const float z = glm::dot(b.center - e, v.forward);- if (z - b.radius < v.nearDistance * 1.01f && z + b.radius > 0.0f) {+ for (const ClusterBounds& b : s.bounds)+ if (reachesNear(b)) {+ v.backfaces = false;+ break;+ }+ if (v.backfaces)+ for (const MeshSlot::Patch& p : s.patches)+ if (reachesNear(p.bounds)) {v.backfaces = false;break;}- }cullBackfaces_ = v.backfaces;const size_t nc = std::min(s.bounds.size(), s.drawCount.size());for (uint32_t c = 0; c < nc; ++c) {@@ -1834,6 +2193,18 @@ void Renderer::drawSlot(const MeshSlot& s, bool active, const RenderSettings& se// The back faces left in clusters along the silhouette: the GPU skips them too when they can't show.if (cullBackfaces_) gl::Enable(GL_CULL_FACE);drawClusters(s, drawClusters_, GL_TRIANGLES, Part::Triangles, perTriangle ? p->primBase : -1);+ if (!s.patches.empty() && s.patchVao) { // dynamic topology: what changed since the layout (in full while moving)+ gl::BindVertexArray(s.patchVao);+ if (!s.patchColorsOn) gl::VertexAttrib4f(2, 1.0f, 1.0f, 1.0f, 1.0f);+ if (!s.patchMaskOn) gl::VertexAttrib1f(3, 0.0f);+ if (perTriangle) {+ gl::ActiveTexture(GL_TEXTURE1);+ gl::BindTexture(GL_TEXTURE_BUFFER, s.hasGroups ? s.patchGroupTexture : 0);+ gl::ActiveTexture(GL_TEXTURE0);+ }+ drawPatches(s, GL_TRIANGLES, Part::Triangles, perTriangle ? p->primBase : -1);+ gl::BindVertexArray(s.vao);+ }if (!proxyClusters_.empty()) {gl::BindVertexArray(s.proxyVao);if (!s.hasColors) gl::VertexAttrib4f(2, 1.0f, 1.0f, 1.0f, 1.0f);diff --git a/src/render/Renderer.h b/src/render/Renderer.hindex 0e8dfd0b..f8b52bf0 100644--- a/src/render/Renderer.h+++ b/src/render/Renderer.h@@ -175,6 +175,32 @@ private:size_t vertexCapacity = 0;std::vector<uint64_t> blockHash; // per UploadOrder block: hashes of its packed positions, and the restsize_t bytes[8] = {}; // GPU sizes: vertices, indices, lines, colours, mask, groups, prims, uvs + tangents++ // Dynamic topology (Mesh::changedTriangles, core/Dyntopo.h): the clusters whose triangles changed since+ // the layout was built, and blocks of triangles added past its end, are drawn from patches instead (the+ // layout skips them): each holds a cluster's current triangles with copies of their vertices, in a fixed+ // part of the patch buffers. A full upload starts over without patches.+ struct Patch {+ uint32_t key = 0; // layout cluster, or kTailPatch + block of triangles past layoutTriangles+ uint32_t part = 0; // its part of the patch buffers+ uint32_t indices = 0, lines = 0; // drawn+ std::vector<uint32_t> verts; // the mesh vertex of each local index+ std::vector<uint16_t> local; // triangles (local indices), while stale+ std::vector<uint32_t> groups; // their polygroups, while stale+ ClusterBounds bounds;+ bool stale = true; // triangles changed: rebuild and upload everything+ bool uploaded = false;+ };+ std::vector<Patch> patches;+ std::vector<uint32_t> clusterPatch, tailPatch; // patch per layout cluster / per block past the layout (kNone)+ std::vector<uint32_t> chunkCluster; // per layout chunk of triangles: its cluster+ uint32_t layoutTriangles = 0;+ GLuint patchVao = 0, patchLineVao = 0, patchVertices = 0, patchIndices = 0, patchLines = 0, patchColors = 0,+ patchMask = 0, patchGroupData = 0, patchGroupTexture = 0;+ size_t patchParts = 0; // parts the patch buffers have room for+ bool patchColorsOn = false, patchMaskOn = false, patchLinesOn = false;+ PositionGrid patchGrid; // the grid the patches' vertices were packed with+ size_t patchBytes = 0;};MeshSlot& slot(uint32_t id); // created on first usestatic void freeSlot(MeshSlot& s);@@ -190,6 +216,15 @@ private:// building the layout).void uploadFaces(MeshSlot& s, const Mesh& mesh, bool wantUvs, bool indicesDone = false);void uploadIndices(MeshSlot& s, const Mesh& mesh);+ // Dynamic topology patches: notePatches marks what Mesh::changedTriangles touched, preparePatches rebuilds+ // the stale ones on the CPU (each false when a full upload is due instead: too many, or a patch too big),+ // uploadPatches sends them and every patch vertex the mesh marked dirty, drawPatches draws them.+ bool notePatches(MeshSlot& s, const Mesh& mesh);+ bool preparePatches(MeshSlot& s, const Mesh& mesh, bool wireframe);+ void uploadPatches(MeshSlot& s, const Mesh& mesh, bool wireframe);+ static void resetPatches(MeshSlot& s);+ std::vector<uint32_t> patchLocal_, patchStamp_; // preparePatches: mesh vertex -> local index (this stamp)+ uint32_t patchStampValue_ = 0;std::vector<std::pair<uint32_t, uint32_t>> dirtyRuns_; // scratch for sync: UploadOrder::dirtyRunsstd::vector<uint8_t> staging_; // scratch for sync: gathered vertex datastd::vector<uint8_t> blockChanged_, blockMoved_; // scratch for uploadVertices, per block@@ -200,6 +235,7 @@ private:void cull(const MeshSlot& s, const CullView& view, bool proxy = false);void drawSlot(const MeshSlot& s, bool active, const RenderSettings& settings);enum class Part { Triangles, Lines, Proxy };+ void drawPatches(const MeshSlot& s, GLenum mode, Part part, GLint primBaseLocation);void drawClusters(const MeshSlot& s, const std::vector<uint32_t>& clusters, GLenum mode, Part part, GLint primBaseLocation);std::vector<uint32_t> proxyClusters_;std::vector<GLsizei> drawCounts_;diff --git a/tests/ui/dyntopo.sfui b/tests/ui/dyntopo.sfuinew file mode 100644index 00000000..0c7daf44--- /dev/null+++ b/tests/ui/dyntopo.sfui@@ -0,0 +1,74 @@+# Dynamic topology (ZBrush's Sculptris Pro): the top shelf's Dynamic toggle and its Detail slider, strokes that+# add triangles where they go (mirrored with X symmetry), the wireframe of the remeshed area, Undo / Redo, the+# dyntopo command, and the refusal on a mesh with subdivision levels.+run new_sphere subdivisions=3+expect_value dynamic == 0+expect "Dynamic##draw.dynamic"+expect_not "##dyntopo_detail"+hold ctrl+hover "Dynamic##draw.dynamic"+expect_help "Sculptris Pro"+expect_help "subdivision levels"+hold none++click "Dynamic##draw.dynamic"+expect_value dynamic == 1+expect_status "Dynamic topology on"+expect "##dyntopo_detail"+expect_text "Detail 50"+remember triangles before+click "Standard##brush.standard"+stroke 0.3 0.35 0.7 0.55+expect_value triangles > $before*1.3+expect_value can_undo == 1+shot stroke+click "PolyF##view.polyf"+expect_value wireframe == 1+shot wireframe++# Snake Hook pulls a horn out of the sphere, with new triangles all along it.+remember triangles pulled+click "SnakeHook##brush.snakehook"+stroke 0.62 0.3 0.95 0.05+expect_value triangles > $pulled+shot snake_hook+click "PolyF##view.polyf"+shot snake_hook_shaded++# Undo takes the strokes back exactly, Redo brings them again.+key ctrl+z+key ctrl+z+expect_value triangles == $before+key ctrl+shift+z+expect_value triangles > $before*1.3+shot redo++# Finer detail: the next stroke makes smaller triangles (more of them).+run dyntopo detail=90+expect_value dynamic_detail == 90+expect_text "Detail 90"+remember triangles fine+click "Clay##brush.clay"+stroke 0.25 0.7 0.5 0.75+expect_value triangles > $fine*1.2+click "PolyF##view.polyf"+shot fine_detail+click "PolyF##view.polyf"++# Off: strokes leave the triangles alone.+click "Dynamic##draw.dynamic"+expect_value dynamic == 0+expect_not "##dyntopo_detail"+remember triangles off+stroke 0.4 0.4 0.6 0.6+expect_value triangles == $off++# A mesh with subdivision levels can't be remeshed: Dynamic stays off and says why.+run new_sphere subdivisions=2+run subdiv_divide+click "Dynamic##draw.dynamic"+expect_value dynamic == 0+expect_status "subdivision levels"+run subdiv_delete_lower+click "Dynamic##draw.dynamic"+expect_value dynamic == 1