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.

Low-memory checks, Move once a frame at 33M, budgeted motion proxies, isolated agent runs (WIP: full ctest not run)

islandmedf59930057537
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 975567b0..1e2b601f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,21 @@ All notable changes to SculptForge are listed here. The format follows
included; the welcome's Support button and the ten-hour note open it too.
### Fixed
+- Help > Benchmark (and `--benchmark`) checks the memory free now before each scene instead of trusting the
+ computer's total: a scene that doesn't fit (15M needs about 2.2 GB free, 33M about 5 GB, plus a margin) is skipped
+ with a clear message ("33M skipped: needs ~5 GB free, 1.3 GB available. Close other apps and run again") rather
+ than running the system out of memory. The result lists skipped scenes; the command line exits with code 2.
+- Subdivide, Divide, Divide to a micro level and Voxel Remesh ask first ("Not enough free memory", Continue anyway or
+ Cancel) when the mesh they would build doesn't fit the memory free now.
+- Move on dense meshes no longer stalls: it worked out its whole region's normals and bounds again for every pointer
+ sample (several times a frame with a 240 Hz pen, more the slower the frame got: seconds at 33M under load). The
+ positions still follow every sample; the normals and bounds now follow once a frame, and the mesh comes out the
+ same, bit for bit.
+- The first orbit after a long stroke no longer stalls (180-300 ms at 33M): the moving view's lighter stand-ins for
+ the changed areas are rebuilt a few milliseconds a frame, the rest drawn in full detail until then.
+- Runs started by scripts and agents (`SDL_APP_ID=sculptforge-agent`, or `SF_ISOLATE=1`) use their own settings and
+ log folder for every mode (renders, `--bench`, `--calibrate` too), so they no longer write into your
+ sculptforge.log or move your session's log aside. Isolated runs remove their temporary folder when they pass.
- Custom and Community brushes (Clay Slab and other presets) show the whole alpha at Focal Shift -100, as the
built-in brushes do since #60: the stamp reaches its square's corners instead of being cut by the preset's round
tip (#75, reported by rodrigomoretto). At the default Focal Shift presets look as before; saved presets are unchanged.
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 681932b5..fa22dcd7 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -36,6 +36,7 @@ add_library(sculptforge_core STATIC
src/core/HardwareProfile.cpp
src/core/FrameGovernor.cpp
src/core/TierConfig.cpp
+ src/core/MemoryGuard.cpp
src/core/Sculpt.cpp
src/core/Dyntopo.cpp
src/core/DyntopoCommands.cpp
@@ -298,6 +299,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/PanelBrushGallery.cpp
src/app/PanelPolypaint.cpp
src/app/PanelPacks.cpp
+ src/app/MemoryConfirm.cpp
src/app/PanelPaintLayers.cpp
src/app/PanelTexture.cpp
src/app/PanelUvEditor.cpp
diff --git a/REPORT.md b/REPORT.md
index 84f219c3..708cb5b4 100644
--- a/REPORT.md
+++ b/REPORT.md
@@ -1,8 +1,7 @@
-# perf/bigbrush-p99 (0.10.8): large-brush frame spikes. NUMBERS PROVISIONAL (machine never got to load < 2)
-What: profiling showed --benchmark ran strokes in the frame loop (predictive is off); a 240 px dab at 33M moves 3-11M verts = 70-220 ms dab + 40-110 ms upload per frame, all already threaded. Fix: from 2M vertices dabs go to the solver thread (no preview; same dabs, same order), frame-sized batches, frame waits <=12.5 ms then keeps drawing; pen lift no longer blocks. SF_BACKGROUND_DABS=0/1. Also: SF_STROKE_LOG/SF_SYNC_LOG breakdowns, SF_BENCH_MESH_OUT dump, isolated runs delete their /tmp folder on success (benchmarks left 1.3 GB autosaves; /tmp filled).
-p99 / stall ms, before (bench-baseline.txt, quiet) -> after (bench-after-load3.txt, load ~3): 15M Clay large 77/136 -> 31/34, 240 px 139/172 -> 31/36; 33M Clay large 139/154 -> 31/40, 240 px 306/325 -> 33/41, Smooth 75/81 -> 31/34; worst stall 325 -> 121 (orbit); release 162 -> 0 ms. p50 within ~2 ms (11-14 ms; 33M 240 px 12.0 -> 14.3). Every 15M/33M stroke p99 < 35 ms.
-Final code at load 7.7 (bench-after.txt): strokes p99 26-31 (15M), 29-54 (33M); 33M Move 5.8 s stall + clay-small 226 ms = load (Move doesn't use this path). Re-run `build/sculptforge --benchmark standard` quiet before publishing.
-Trade-off: 33M 240 px surface trails more (p50 31 -> 69-108 px) since each dab still costs 100-200 ms; dab counts match (101 vs 99).
-Quality: same dabs through both paths are bit-identical (ui_stroke_background; --measure-stroke 3,120/3,240 SF_MEASURE_VERIFY=1). Benchmark scene meshes aren't reproducible run to run on either path (two old-path runs differ 0.26), so cross-run 1e-5 isn't measurable there.
-Tests: full ctest -j3 117/118; ui_phone_link fails (phone_ar_version 1 != 2) identically on base 60001d4: test-only, local multi-address Capture row; fixed on fix/phone-ar-reexport 40895b2 (not merged).
-SHA: code b372514, report 5207367+ on origin/perf/bigbrush-p99. CHANGELOG [Unreleased] + What's New 0.10.8 section added.
+# perf/bigbrush-p99 (0.10.8). STATUS: PAUSED (usage limit). Pushed 1aa0e20 = background dabs (green). Local commit on top = NOT pushed, full ctest NOT run.
+Done + pushed (1aa0e20): background dabs for big brushes (provisional: 33M 240 px p99 306 -> ~33 ms, stall 325 -> ~41, pen lift 162 -> 0), bit-identical (ui_stroke_background); details in the earlier report text in git history.
+Done locally (unpushed): (1) core/MemoryGuard: free-memory check; benchmark skips a scene that doesn't fit ("33M skipped: needs ~5 GB free, 1.3 GB available..."), JSON "skipped", exit 2, submit.py refuses; Subdivide/Divide/micro/remesh ask "Not enough free memory" (app/MemoryConfirm.cpp). Tests: test_memory_guard (mocked free memory), ui_memory_confirm - both pass. Verified: SF_AVAILABLE_MEMORY_MB=1240 --benchmark standard skips both scenes, rc=2.
+(2) Move at 33M: positions per pointer sample (Sculptor::grabMove), normals+BVH once a frame (grabFinish via App::flushGrab); bit-identical (test_grab_coalesce passes). 33M Move at load 8-12: p50 28, p99 53, stall 62 ms (was p50 57, multi-second stalls under load). At load 22 swap-bound (GPU contention), unconfirmed quiet.
+(3) Orbit after a stroke: motion proxies rebuilt 8 ms/frame (stale draw full); 33M orbit stall 186-317 -> 61 ms. --bench motion-setup loops until done.
+(4) Agent/script runs (SDL_APP_ID=sculptforge-agent, CLAUDECODE, SF_ISOLATE=1) isolate settings+log in every mode (--render/--bench/--calibrate too); real log untouched by my runs (checked). daily-drops fixed its renders (40c3127).
+Left / next steps to resume: 1) `pgrep -f ctest` until none, then `cd build && SDL_APP_ID=sculptforge-agent nice -n 19 ionice -c3 ctest -j3 --output-on-failure` (known unrelated: ui_phone_link, fixed on fix/phone-ar-reexport). 2) If green: `git push`. 3) Quiet (load < 2) `build/sculptforge --benchmark standard` -> bench-after.txt; confirm 33M Move p99 < 80, no stall > 150. 4) Update docs/performance.md numbers; message coordinator.
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 12c487cc..26503c9b 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -973,6 +973,7 @@ int App::run() {
continuousDabAt_ = nowS;
}
}
+ flushGrab(); // Move: the pointer's moves since the last frame, as one
if (asyncStroke_) pumpStroke();
else drainStrokeDabs(kStrokeBudgetSeconds);
mark();
@@ -1123,7 +1124,7 @@ int App::run() {
int(drag_ != Drag::None), int(backgroundBusy()), int(perf_.framesStill < 10));
}
finishProject();
- return 0;
+ return options_.benchmark && proofSkippedScenes() ? 2 : 0; // (--benchmark: a scene skipped for memory)
}
// ---------------------------------------------------------------------------
@@ -1709,6 +1710,7 @@ void App::beginStroke(float x, float y, const RayHit& hit) {
p.focal = focalShift_;
p.connectedOnly = uiPrefs_.connectedOnly;
p.viewFalloff = uiPrefs_.viewFalloff;
+ grabPending_ = false;
doc_.sculptor.beginGrab(doc_.mesh, doc_.bvh, p, symmetry_);
grabPlanePoint_ = grabLast_ = hit.position;
beginAlongNormal(hit, p.radius);
@@ -1758,7 +1760,7 @@ void App::strokeTo(float x, float y) {
const BrushRecipe* recipe = strokeRecipe();
if (strokeBrush_ == BrushType::Move && !recipe && strokeSculpt_ && strokeAlongNormal_) {
const glm::vec3 p = alongNormalTarget(x, y);
- doc_.sculptor.grab(doc_.mesh, doc_.bvh, p - grabLast_);
+ queueGrab(p - grabLast_);
grabLast_ = p;
return;
}
@@ -1770,7 +1772,7 @@ void App::strokeTo(float x, float y) {
if (std::abs(denom) < 1e-6f) return;
float t = glm::dot(grabPlanePoint_ - origin, n) / denom;
glm::vec3 p = origin + dir * t;
- doc_.sculptor.grab(doc_.mesh, doc_.bvh, p - grabLast_);
+ queueGrab(p - grabLast_);
grabLast_ = p;
return;
}
@@ -1951,7 +1953,25 @@ void App::dabAt(float x, float y, float pressure) {
doc_.sculptor.dab(doc_.mesh, doc_.bvh, st.brush, p, st.symmetry);
}
+void App::queueGrab(const glm::vec3& delta) {
+ // Move followed every pointer sample with a whole move of its region (positions, normals, BVH): at 240 samples
+ // a second on 33M triangles a frame did several, the next frame got more samples, and the view stalled for
+ // seconds. Each sample still moves the positions (the cheap part); the normals and the BVH, which depend only on
+ // where the vertices end up, follow once a frame (flushGrab): the same mesh, bit for bit. Scripts and
+ // recordings do both at once.
+ doc_.sculptor.grabMove(doc_.mesh, delta);
+ grabPending_ = true;
+ if (!interactiveStrokes_) flushGrab();
+}
+
+void App::flushGrab() {
+ if (!grabPending_) return;
+ grabPending_ = false;
+ doc_.sculptor.grabFinish(doc_.mesh, doc_.bvh);
+}
+
void App::endStroke() {
+ flushGrab(); // (Move: the last samples' move)
if (asyncStroke_) solverWait(); // (the dabs in flight; then the solver thread is idle)
drainStrokeDabs(0.0); // the dabs still waiting belong to this stroke
doc_.sculptor.flushDetailClone(doc_.mesh, doc_.bvh, symmetry_); // a Detail Clone click
@@ -1986,6 +2006,11 @@ void App::runCommand(const std::string& name, const Args& args) {
lastCommandOk_ = packs_.review != nullptr;
return;
}
+ // A big mesh (Subdivide, Divide, micro, remesh) asks first when it wouldn't fit the memory free now.
+ if (!memoryAllows(name, args, [this, name, args] { runCommand(name, args); })) {
+ lastCommandOk_ = false;
+ return;
+ }
if (doc_.sculptor.strokeActive()) endStroke();
if (name == "save_project") storeProjectSettings();
flushBrushEdits(); // commands may replace brushes: save edits first, then watch what's there afterwards
@@ -2353,6 +2378,7 @@ void App::drawUi() {
drawSupportUi(); // the first-run welcome, the one support reminder (PanelSupport.cpp)
guide_.draw(*this); // Help > User Guide
drawPacksUi(); // pack review, New Pack, macro confirmation and editor (PanelPacks.cpp)
+ drawMemoryConfirm(); // "Not enough free memory" before a big mesh (MemoryConfirm.cpp)
drawHelpConsoleUi(); // console, command palette, Controls (F1), Ctrl-hover help: last, on top
drawSupportCard(); // the support card at launch, over everything (PanelSupportCard.cpp)
}
diff --git a/src/app/App.h b/src/app/App.h
index 57830487..3519b08d 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -348,6 +348,9 @@ private:
BrushType strokeBrush_ = BrushType::Standard;
bool strokeInvert_ = false;
glm::vec3 grabPlanePoint_{0.0f}, grabLast_{0.0f};
+ bool grabPending_ = false; // Move: positions moved, normals and BVH not yet (queueGrab / flushGrab, once a frame)
+ void queueGrab(const glm::vec3& delta);
+ void flushGrab();
// Along the normal (from the discussions): Move, Tendril, Elastic Tendril and KelvinGrab strokes that began with
// the invert key held (Preferences > Input > Along the normal) slide along the average normal under the brush
// at the press instead of the view plane. alongNormalTarget: where the cursor puts the grabbed point.
@@ -1564,6 +1567,16 @@ private:
void drawPackReview();
void drawNewPack();
void drawMacroConfirm();
+ // Free memory before a big mesh (core/MemoryGuard.h): a command that would need more than is free asks first.
+ // Returns true to go on now; false: the dialog is open and `proceed` runs on Continue.
+ bool memoryAllows(const std::string& command, const Args& args, std::function<void()> proceed);
+ void drawMemoryConfirm();
+ struct MemoryConfirm {
+ bool open = false;
+ std::string what, message;
+ std::function<void()> proceed;
+ } memoryConfirm_;
+ bool memoryConfirmed_ = false; // the next memoryAllows passes (Continue was pressed)
void drawMacroEditor();
void drawPackKeymapRows(); // Preferences > Input: the enabled packs' keymaps
void pollPackDialogs();
@@ -1783,6 +1796,7 @@ private:
bool timelapseStep(double budgetSeconds); // renders frames for up to the budget; false when finished
int runTimelapseCli(); // sculptforge FILE --timelapse out.mp4
void startProofMode(); // Help > Benchmark, sculptforge --benchmark
+ bool proofSkippedScenes() const; // the benchmark skipped a scene: too little free memory
void proofBeforeSwap(int fbW, int fbH); // the interactive loop, after drawing a frame, before showing it
void drawProofUi();
// ---- end Sculpt Timeline ----
diff --git a/src/app/Bench.cpp b/src/app/Bench.cpp
index 027f5572..ddce54b8 100644
--- a/src/app/Bench.cpp
+++ b/src/app/Bench.cpp
@@ -141,6 +141,7 @@ int runAppBenchmark(BenchCommandLine cl) {
gl::Finish();
const auto t = Clock::now();
renderer.syncScene(scene(m));
+ while (renderer.proxiesPending()) renderer.syncScene(scene(m)); // (built a few ms a frame: all of them)
gl::Finish();
return msSince(t);
};
diff --git a/src/app/MemoryConfirm.cpp b/src/app/MemoryConfirm.cpp
new file mode 100644
index 00000000..5d820ac8
--- /dev/null
+++ b/src/app/MemoryConfirm.cpp
@@ -0,0 +1,79 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// "Not enough free memory": Subdivide, Divide, a micro level or a voxel remesh that would build a mesh larger than
+// the memory free now (core/MemoryGuard.h) asks before it runs. Running out takes the whole system down (other
+// programs hold memory the hardware profile, which budgets from the total, counts as ours).
+#include "app/App.h"
+
+#include "app/I18n.h"
+#include "app/Theme.h"
+#include "core/MemoryGuard.h"
+
+#include <utility>
+
+namespace sf {
+
+namespace {
+
+const char* commandTitle(const std::string& name) {
+ if (name == "subdivide") return "Subdivide";
+ if (name == "subdiv_divide") return "Divide";
+ if (name == "micro_divide") return "Divide to a micro level";
+ if (name == "remesh") return "Voxel remesh";
+ return "This step";
+}
+
+} // namespace
+
+bool App::memoryAllows(const std::string& command, const Args& args, std::function<void()> proceed) {
+ if (std::exchange(memoryConfirmed_, false)) return true; // (Continue was pressed: this is that run)
+ const size_t need = commandMemoryNeed(doc_.mesh, command, args);
+ if (need == 0) return true;
+ const MemoryCheck c = checkMemory(need);
+ if (c.enough) return true;
+ memoryConfirm_.open = true;
+ memoryConfirm_.what = commandTitle(command);
+ memoryConfirm_.message = commandShortMessage(memoryConfirm_.what, c);
+ memoryConfirm_.proceed = std::move(proceed);
+ status_ = memoryConfirm_.message + " Continue or cancel in the dialog.";
+ SDL_Log("Memory: %s", memoryConfirm_.message.c_str());
+ return false;
+}
+
+void App::drawMemoryConfirm() {
+ if (!memoryConfirm_.open) return;
+ const float s = uiScale_;
+ const ImGuiViewport* vp = ImGui::GetMainViewport();
+ ImGui::SetNextWindowPos(ImVec2(vp->WorkPos.x + vp->WorkSize.x * 0.5f, vp->WorkPos.y + vp->WorkSize.y * 0.5f),
+ ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
+ bool open = true;
+ if (!ImGui::Begin(tr("Not enough free memory"), &open,
+ ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize)) {
+ ImGui::End();
+ if (!open) memoryConfirm_ = {};
+ return;
+ }
+ ImGui::PushTextWrapPos(500 * s);
+ ImGui::TextColored(theme::danger, "%s", memoryConfirm_.message.c_str());
+ ImGui::TextWrapped("%s", tr("If the computer runs out of memory it can stop responding and SculptForge may close "
+ "without saving. Close other apps (or save first) before you go on."));
+ ImGui::PopTextWrapPos();
+ bool go = false;
+ if (ImGui::Button(tr("Continue anyway##memoryconfirm"), ImVec2(160 * s, 0))) go = true;
+ ImGui::SameLine();
+ if (ImGui::Button(tr("Cancel##memoryconfirm"), ImVec2(120 * s, 0))) open = false;
+ ImGui::End();
+ if (go) {
+ std::function<void()> proceed = std::move(memoryConfirm_.proceed);
+ memoryConfirm_ = {};
+ memoryConfirmed_ = true;
+ if (proceed) proceed();
+ memoryConfirmed_ = false; // (in case it didn't get as far as the check)
+ } else if (!open) {
+ status_ = memoryConfirm_.what + " cancelled: not enough free memory";
+ memoryConfirm_ = {};
+ }
+}
+
+} // namespace sf
diff --git a/src/app/PanelRetopo.cpp b/src/app/PanelRetopo.cpp
index b6b35366..80dd0e47 100644
--- a/src/app/PanelRetopo.cpp
+++ b/src/app/PanelRetopo.cpp
@@ -194,6 +194,8 @@ void App::startVoxelRemesh() {
if (voxelRemesh_) return;
Args args{{"resolution", double(voxelResolution_)}};
if (voxelKeepMasked_) args["keep_masked"] = true;
+ if (!memoryAllows("remesh", args, [this] { startVoxelRemesh(); })) return;
+ memoryConfirmed_ = true; // (checked: the remesh command below doesn't ask again)
if (!hasTexture(doc_.mesh) || !keepTexture_) {
if (hasTexture(doc_.mesh)) args["keep_texture"] = false; // Keep Texture off
runCommand("remesh", args);
diff --git a/src/app/ProofMode.cpp b/src/app/ProofMode.cpp
index 120a8f23..2cd4c019 100644
--- a/src/app/ProofMode.cpp
+++ b/src/app/ProofMode.cpp
@@ -19,6 +19,7 @@
#include "app/Theme.h"
#include "core/Benchmark.h"
+#include "core/MemoryGuard.h"
#include "core/Primitives.h"
#include "core/Timeline.h"
@@ -85,27 +86,6 @@ std::vector<ProofMeshSize> proofStandardScene(const std::string& name) {
return {};
}
-size_t availableMemoryBytes() {
-#if defined(_WIN32)
- MEMORYSTATUSEX m{};
- m.dwLength = sizeof m;
- return GlobalMemoryStatusEx(&m) ? size_t(m.ullAvailPhys) : 0;
-#elif defined(__APPLE__)
- vm_statistics64_data_t vm{};
- mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
- if (host_statistics64(mach_host_self(), HOST_VM_INFO64, reinterpret_cast<host_info64_t>(&vm), &count) != KERN_SUCCESS) return 0;
- return size_t(vm.free_count + vm.inactive_count + vm.purgeable_count) * size_t(vm_page_size);
-#else
- std::ifstream f("/proc/meminfo");
- std::string key;
- size_t kb = 0;
- std::string unit;
- while (f >> key >> kb >> unit)
- if (key == "MemAvailable:") return kb * 1024;
- return 0;
-#endif
-}
-
size_t totalMemoryBytes() {
#if defined(_WIN32)
MEMORYSTATUSEX m{};
@@ -382,6 +362,8 @@ struct SizeResult {
long long vramUsedKb = -1; // the most the driver's free graphics memory dropped from before the build (-1: unknown)
long long vramFreeBeforeKb = -1;
std::vector<PhaseResult> phases;
+ MemoryCheck memory; // free memory before the build
+ std::string skipped; // not built: too little free memory (benchmarkSkippedMessage)
};
} // namespace
@@ -468,6 +450,11 @@ std::vector<ProofMeshSize> parseSizes(const std::string& list) {
} // namespace
+bool App::proofSkippedScenes() const {
+ if (!proof_) return false;
+ return std::any_of(proof_->results.begin(), proof_->results.end(), [](const SizeResult& r) { return !r.skipped.empty(); });
+}
+
void App::startProofMode() {
if (proof_ && proof_->stage != ProofState::Stage::Results && proof_->stage != ProofState::Stage::Intro) return;
auto p = std::make_shared<ProofState>();
@@ -529,7 +516,21 @@ void App::drawProofUi() {
if (!p.scene.empty())
ImGui::TextDisabled("Clay at 25, 60 and 120 px, Move, Smooth, a 240 px brush, then an orbit: the scene the "
"website's table uses (same as sculptforge --benchmark %s)", p.scene.c_str());
- ImGui::TextDisabled("%.1f GB of memory free now (33M needs about 6 GB)", double(availableMemoryBytes()) / double(1u << 30));
+ { // What each scene needs free (a scene without it is skipped), against what is free now.
+ const size_t free = availableMemoryBytes();
+ std::string need, shortOf;
+ for (const ProofMeshSize& s : p.sizes) {
+ const MemoryCheck c = checkMemory(size_t(s.millions * 1e6 * s.bytesPerTriangle), free);
+ const std::string gb = formatGigabytes(c.needBytes + memoryMargin(c.needBytes));
+ need += (need.empty() ? "" : ", ") + s.label + " about " + gb;
+ if (!c.enough) shortOf += (shortOf.empty() ? "" : ", ") + s.label;
+ }
+ ImGui::TextDisabled("%s of memory free now (%s)", free ? formatGigabytes(free).c_str() : "Unknown amount",
+ need.c_str());
+ if (!shortOf.empty())
+ ImGui::TextColored(theme::danger, "Not enough free memory for %s: it will be skipped. Close other apps first.",
+ shortOf.c_str());
+ }
ImGui::Spacing();
ImGui::TextWrapped("A live display shows the frame rate, frame times (median, 95th, 99th percentile), how far "
"the stroke trails the pointer, and memory. The result is saved as JSON beside a video "
@@ -783,6 +784,22 @@ void App::proofBeforeSwap(int fbW, int fbH) {
const ProofMeshSize& s = p.sizes[p.sizeIndex];
doc_.setMesh(makeIcosphere(1)); // free the last mesh (and its history) first
gl::Finish();
+ // Free memory now, not the computer's total: with other programs holding the rest a 33M scene ran a system
+ // out of memory. Too little: this scene is skipped (and said so), the next one tried.
+ const MemoryCheck memory = checkMemory(size_t(s.millions * 1e6 * s.bytesPerTriangle));
+ if (!memory.enough) {
+ SizeResult r;
+ r.label = s.label;
+ r.memory = memory;
+ r.skipped = benchmarkSkippedMessage(s.label, memory);
+ SDL_Log("Benchmark: %s", r.skipped.c_str());
+ p.error += (p.error.empty() ? "" : "; ") + r.skipped;
+ p.results.push_back(r);
+ p.hudTitle = r.skipped;
+ ++p.sizeIndex;
+ p.stage = p.sizeIndex < p.sizes.size() ? Stage::Announce : Stage::Finish;
+ break;
+ }
const long long vramBefore = driverFreeVramKb();
resetPeakResidentBytes();
const double t0 = nowSeconds();
@@ -936,8 +953,17 @@ void App::proofBeforeSwap(int fbW, int fbH) {
settings.set("input", "scripted pointer samples into App::onMouseMove (the mouse / pen handler)");
settings.set("lag", "pointer sample time to SwapWindow of the frame showing its dab (display scan-out not included)");
root.set("settings", settings);
- Json runs = Json::array();
+ Json runs = Json::array(), skipped = Json::array();
for (const SizeResult& r : p.results) {
+ if (!r.skipped.empty()) {
+ Json k = Json::object();
+ k.set("label", r.label);
+ k.set("need_mb", double(r.memory.needBytes >> 20));
+ k.set("available_mb", double(r.memory.availableBytes >> 20));
+ k.set("message", r.skipped);
+ skipped.push(k);
+ continue;
+ }
Json run = Json::object();
run.set("label", r.label);
run.set("triangles", double(r.triangles));
@@ -980,6 +1006,7 @@ void App::proofBeforeSwap(int fbW, int fbH) {
runs.push(run);
}
root.set("runs", runs);
+ if (skipped.size() > 0) root.set("skipped", skipped); // (a result with skipped scenes isn't published)
if (p.video) root.set("video", std::filesystem::path(p.videoPath).filename().string());
if (!p.error.empty()) root.set("notes", p.error);
{
@@ -991,6 +1018,10 @@ void App::proofBeforeSwap(int fbW, int fbH) {
std::printf("SculptForge %s (%s) proof mode%s%s on %s | %s\n", SCULPTFORGE_VERSION, SF_GIT_COMMIT,
p.scene.empty() ? "" : ", scene ", p.scene.c_str(), root["hardware"]["cpu"].asString().c_str(), p.gpu.c_str());
for (const SizeResult& r : p.results) {
+ if (!r.skipped.empty()) {
+ std::printf(" %s\n", r.skipped.c_str());
+ continue;
+ }
std::printf(" %-5s peak RAM %zu MB, GPU buffers %zu MB%s, worst stall %.0f ms\n", r.label.c_str(), r.peakRamBytes >> 20,
r.gpuBufferBytes >> 20, r.vramUsedKb > 0 ? (", driver VRAM used " + std::to_string(r.vramUsedKb >> 10) + " MB").c_str() : "",
[&] { double w = 0; for (const PhaseResult& ph : r.phases) w = std::max(w, worstStallMs(ph.frameMs, ph.releaseMs)); return w; }());
diff --git a/src/app/ProofMode.h b/src/app/ProofMode.h
index 83cc58ca..06f848bf 100644
--- a/src/app/ProofMode.h
+++ b/src/app/ProofMode.h
@@ -35,8 +35,7 @@ std::vector<ProofMeshSize>& proofExtraSizes();
std::vector<ProofMeshSize> proofStandardScene(const std::string& name);
inline constexpr const char* kProofStrokeSet = "standard/1"; // bump when the standard stroke set changes
-// Memory the system can still hand out (Linux MemAvailable, macOS / Windows free + reclaimable); 0 = unknown.
-size_t availableMemoryBytes();
+// (Free memory now: availableMemoryBytes, core/MemoryGuard.h.)
size_t totalMemoryBytes();
// CPU model, logical cores, RAM, OS: the "hardware" object of the result (the GPU is added by the app).
Json describeHardware();
diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cpp
index fcef8be5..2efa053d 100644
--- a/src/app/UiTest.cpp
+++ b/src/app/UiTest.cpp
@@ -472,6 +472,7 @@ double Demo::query(const std::string& name, bool& known) const {
if (name == "radial_hover") return double(app_.radial_.hover);
if (name == "radial_ran") return double(app_.radial_.ran); // the slot run last, -1: none yet
if (name == "radial_menus") return double(app_.radialMenus_.size());
+ if (name == "memory_confirm_open") return app_.memoryConfirm_.open ? 1.0 : 0.0; // "Not enough free memory"
if (const double v = app_.packsTestValue(name); !std::isnan(v)) return v; // packs_installed, macro_recording, ...
if (name.rfind("radial_slots_", 0) == 0) { // radial_slots_N: menu N's items (1-based), -1: no such menu
const size_t i = size_t(std::max(0, std::atoi(name.c_str() + 13) - 1));
diff --git a/src/app/main.cpp b/src/app/main.cpp
index 15cf3785..e9d5b5ba 100644
--- a/src/app/main.cpp
+++ b/src/app/main.cpp
@@ -107,6 +107,28 @@ void isolateSettings() {
}
}
+// Runs by an agent or a script (SDL_APP_ID=sculptforge-agent, as ~/Work/CLAUDE.md asks for agent windows, or a
+// Claude Code shell) never touch the user's settings, log or hardware profile: a benchmark or render started there
+// wrote into the user's sculptforge.log and pushed the session's log to sculptforge-previous.log.
+// SF_ISOLATE=1 isolates any run, SF_ISOLATE=0 none of the automatic ones.
+bool automatedRun() {
+ const char* force = std::getenv("SF_ISOLATE");
+ if (force && *force) return *force != '0';
+ const char* appId = std::getenv("SDL_APP_ID");
+ const char* claude = std::getenv("CLAUDECODE");
+ return (appId && std::string(appId) == "sculptforge-agent") || (claude && *claude);
+}
+
+int finishIsolated(int code) {
+ // The isolated folder (settings, the log, autosaves: a benchmark's 33M mesh is over a gigabyte) goes with a run
+ // that passed; a failed one keeps it, log included, to look at.
+ if (code == 0 && !g_isolatedDir.empty()) {
+ std::error_code ec;
+ std::filesystem::remove_all(g_isolatedDir, ec);
+ }
+ return code;
+}
+
} // namespace
// --crash-test: crash the way real bugs do, after the log has started.
@@ -192,8 +214,9 @@ int main(int argc, char** argv) {
return 1;
}
}
- if (bench.run) return sf::runAppBenchmark(bench);
- if (calibrate) return sf::runCalibrateCommandLine(calibrateQuick, calibrateSave);
+ if (automatedRun()) isolateSettings();
+ if (bench.run) return finishIsolated(sf::runAppBenchmark(bench));
+ if (calibrate) return finishIsolated(sf::runCalibrateCommandLine(calibrateQuick, calibrateSave));
if (!options.uiTest.empty()) {
if (!sizeGiven) options.width = 1600, options.height = 960;
isolateSettings();
@@ -217,11 +240,5 @@ int main(int argc, char** argv) {
int code = app.run();
app.shutdown();
sf::crashlog::stop();
- // The isolated folder (settings, the log, autosaves: a benchmark's 33M mesh is over a gigabyte) goes with a run
- // that passed; a failed one keeps it, log included, to look at.
- if (code == 0 && !g_isolatedDir.empty()) {
- std::error_code ec;
- std::filesystem::remove_all(g_isolatedDir, ec);
- }
- return code;
+ return finishIsolated(code);
}
diff --git a/src/core/MemoryGuard.cpp b/src/core/MemoryGuard.cpp
new file mode 100644
index 00000000..a61a79d1
--- /dev/null
+++ b/src/core/MemoryGuard.cpp
@@ -0,0 +1,131 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/MemoryGuard.h"
+
+#include "core/Mesh.h"
+#include "core/Micro.h"
+#include "core/Multires.h"
+
+#include <algorithm>
+#include <atomic>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+
+#if defined(_WIN32)
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#elif defined(__APPLE__)
+#include <mach/mach.h>
+#else
+#include <fstream>
+#endif
+
+namespace sf {
+
+namespace {
+
+std::atomic<size_t> g_override{0};
+
+// A mesh in the app, per triangle: its arrays, adjacency, BVH, GPU buffers and the undo step's copy (measured: the
+// 33M benchmark head peaks at 4.7 GB, 141 bytes a triangle).
+constexpr double kMeshBytesPerTriangle = 150.0;
+// A micro level, per micro triangle: about 0.6 grid points x (2 bytes + 1 of mask + 6 on the GPU) + undo.
+constexpr double kMicroBytesPerTriangle = 6.0;
+// Voxel remesh, per grid cell: the distance field (float), the shell, wall, outside and solid masks, the smoothed
+// field (float).
+constexpr double kVoxelBytesPerCell = 11.0;
+
+size_t systemAvailable() {
+#if defined(_WIN32)
+ MEMORYSTATUSEX m{};
+ m.dwLength = sizeof m;
+ return GlobalMemoryStatusEx(&m) ? size_t(m.ullAvailPhys) : 0;
+#elif defined(__APPLE__)
+ vm_statistics64_data_t vm{};
+ mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
+ if (host_statistics64(mach_host_self(), HOST_VM_INFO64, reinterpret_cast<host_info64_t>(&vm), &count) != KERN_SUCCESS) return 0;
+ return size_t(vm.free_count + vm.inactive_count + vm.purgeable_count) * size_t(vm_page_size);
+#else
+ std::ifstream f("/proc/meminfo");
+ std::string key, unit;
+ size_t kb = 0;
+ while (f >> key >> kb >> unit)
+ if (key == "MemAvailable:") return kb * 1024;
+ return 0;
+#endif
+}
+
+size_t bytes(double b) { return b <= 0.0 ? 0 : b >= 1.8e19 ? size_t(-1) : size_t(b); }
+
+} // namespace
+
+size_t availableMemoryBytes() {
+ if (const size_t o = g_override.load(std::memory_order_relaxed)) return o;
+ if (const char* v = std::getenv("SF_AVAILABLE_MEMORY_MB"); v && *v) // (UI tests: a computer with this much free)
+ if (const double mb = std::atof(v); mb > 0.0) return size_t(mb * 1048576.0);
+ return systemAvailable();
+}
+
+void setAvailableMemoryOverride(size_t b) { g_override.store(b, std::memory_order_relaxed); }
+
+size_t memoryMargin(size_t need) { return std::max<size_t>(size_t(512) << 20, need / 10); }
+
+MemoryCheck checkMemory(size_t need, size_t available) {
+ MemoryCheck c;
+ c.needBytes = need;
+ c.availableBytes = available;
+ c.enough = available == 0 || need == 0 || need + memoryMargin(need) <= available;
+ return c;
+}
+
+std::string formatGigabytes(size_t b) {
+ const double gb = double(b) / 1e9;
+ char buf[32];
+ if (gb >= 9.95) std::snprintf(buf, sizeof buf, "%.0f GB", gb);
+ else {
+ std::snprintf(buf, sizeof buf, "%.1f GB", gb);
+ if (const std::string s = buf; s.size() > 5 && s.compare(s.size() - 5, 5, ".0 GB") == 0)
+ return s.substr(0, s.size() - 5) + " GB";
+ }
+ return buf;
+}
+
+std::string benchmarkSkippedMessage(const std::string& label, const MemoryCheck& c) {
+ return label + " skipped: needs ~" + formatGigabytes(c.needBytes) + " free, " + formatGigabytes(c.availableBytes) +
+ " available. Close other apps and run again";
+}
+
+std::string commandShortMessage(const std::string& what, const MemoryCheck& c) {
+ return what + " needs ~" + formatGigabytes(c.needBytes) + " free, " + formatGigabytes(c.availableBytes) + " available.";
+}
+
+size_t commandMemoryNeed(const Mesh& mesh, const std::string& name, const Args& args) {
+ const double nt = double(mesh.triangleCount());
+ if (nt <= 0.0) return 0;
+ if (name == "subdivide") { // Loop: 4x a level
+ const int levels = std::clamp(int(argNumber(args, "levels", 1)), 1, 4);
+ return bytes(nt * std::pow(4.0, levels) * kMeshBytesPerTriangle);
+ }
+ if (name == "subdiv_divide") { // (the projection subdivDivide makes)
+ const double quads = double(mesh.quadCount());
+ const double projected = quads > 0.0 ? quads * 8.0 + (nt - 2.0 * quads) * 6.0 : nt * 4.0;
+ return bytes(projected * double(kDivideBytesPerTriangle));
+ }
+ if (name == "micro_divide") { // (the level micro_divide picks)
+ int level = int(argNumber(args, "level", 0));
+ if (args.contains("triangles")) level = microLevelFor(mesh, size_t(std::max(1.0, argNumber(args, "triangles", 100)) * 1e6));
+ if (level <= 0) level = microLevelFor(mesh, size_t(100e6));
+ return bytes(nt * std::pow(4.0, level) * kMicroBytesPerTriangle);
+ }
+ if (name == "remesh") { // the grid across the longest side, and about 6 R^2 triangles out
+ const double r = std::clamp(argNumber(args, "resolution", 200), 32.0, 512.0);
+ return bytes(r * r * r * kVoxelBytesPerCell + 6.0 * r * r * kMeshBytesPerTriangle);
+ }
+ return 0;
+}
+
+} // namespace sf
diff --git a/src/core/MemoryGuard.h b/src/core/MemoryGuard.h
new file mode 100644
index 00000000..bce11791
--- /dev/null
+++ b/src/core/MemoryGuard.h
@@ -0,0 +1,46 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Free memory checks before work that builds a big mesh: a benchmark scene, Subdivide, Divide, a micro level, a
+// voxel remesh. The hardware profile budgets from the computer's total memory; these look at what the system can
+// hand out now (other programs hold the rest), so a 33M scene isn't built with 1.3 GB free.
+#pragma once
+
+#include "core/Commands.h"
+
+#include <cstddef>
+#include <string>
+
+namespace sf {
+
+struct Mesh;
+
+// Memory the system can still hand out now: Linux MemAvailable, macOS free + inactive + purgeable pages, Windows
+// available physical memory. 0 = unknown. The override (or SF_AVAILABLE_MEMORY_MB) replaces it, for tests.
+size_t availableMemoryBytes();
+// Tests: pretend this much memory is free; 0 goes back to asking the system.
+void setAvailableMemoryOverride(size_t bytes);
+
+// Room kept on top of a need: max(512 MB, a tenth of it).
+size_t memoryMargin(size_t needBytes);
+
+struct MemoryCheck {
+ size_t needBytes = 0; // what the work takes
+ size_t availableBytes = 0; // free now (0: unknown)
+ bool enough = true; // need + margin fits (or free memory is unknown)
+};
+MemoryCheck checkMemory(size_t needBytes, size_t availableBytes);
+inline MemoryCheck checkMemory(size_t needBytes) { return checkMemory(needBytes, availableMemoryBytes()); }
+
+// "5 GB", "2.3 GB", "0.4 GB" (decimal gigabytes, as the system's own tools show them).
+std::string formatGigabytes(size_t bytes);
+// "33M skipped: needs ~5 GB free, 1.3 GB available. Close other apps and run again"
+std::string benchmarkSkippedMessage(const std::string& label, const MemoryCheck& c);
+// "Subdivide needs ~6.2 GB free, 1.3 GB available."
+std::string commandShortMessage(const std::string& what, const MemoryCheck& c);
+
+// About what a command would take for the mesh it builds (bytes), from `mesh` and its arguments; 0 when it isn't one
+// of the big ones (subdivide, subdiv_divide, micro_divide, remesh) or can't make the mesh at all.
+size_t commandMemoryNeed(const Mesh& mesh, const std::string& name, const Args& args);
+
+} // namespace sf
diff --git a/src/core/Sculpt.cpp b/src/core/Sculpt.cpp
index 2a9a07c4..c89f46ee 100644
--- a/src/core/Sculpt.cpp
+++ b/src/core/Sculpt.cpp
@@ -1188,7 +1188,12 @@ void Sculptor::beginGrab(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym)
}
void Sculptor::grab(Mesh& mesh, BVH& bvh, const glm::vec3& delta) {
- if (micro_.active() && microMesh_ == &mesh) {
+ grabMove(mesh, delta);
+ grabFinish(mesh, bvh);
+}
+
+void Sculptor::grabMove(Mesh& mesh, const glm::vec3& delta) {
+ if (micro_.active() && microMesh_ == &mesh) { // (a micro level moves and stitches in one go)
const double k0 = micro_.kernelMs, s0 = micro_.stitchMs;
micro_.grab(mesh, delta);
timings.kernelMs += micro_.kernelMs - k0;
@@ -1210,12 +1215,17 @@ void Sculptor::grab(Mesh& mesh, BVH& bvh, const glm::vec3& delta) {
begin = end;
}
timings.kernelMs += lapMs(clock);
+ ++timings.dabs;
+ timings.vertices += grabAll_.size();
+}
+
+void Sculptor::grabFinish(Mesh& mesh, BVH& bvh) {
+ if (grabVerts_.empty() || (micro_.active() && microMesh_ == &mesh)) return;
+ auto clock = std::chrono::steady_clock::now();
mesh.updateNormals(grabAll_);
timings.normalsMs += lapMs(clock);
bvh.refitLeaves(mesh, grabLeaves_);
timings.bvhMs += lapMs(clock);
- ++timings.dabs;
- timings.vertices += grabAll_.size();
}
// Puts every vertex the current stroke moved back to its stroke-start position.
diff --git a/src/core/Sculpt.h b/src/core/Sculpt.h
index 1203f417..b07b830d 100644
--- a/src/core/Sculpt.h
+++ b/src/core/Sculpt.h
@@ -175,7 +175,11 @@ public:
// Move brush: capture the region once, then drag it by world deltas.
void beginGrab(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym);
- void grab(Mesh& mesh, BVH& bvh, const glm::vec3& delta);
+ void grab(Mesh& mesh, BVH& bvh, const glm::vec3& delta); // grabMove, then grabFinish
+ // The two halves: the positions (each pointer sample), then the normals and the BVH of what moved (once a
+ // frame: they depend only on where the vertices ended up, so the mesh is the same, bit for bit).
+ void grabMove(Mesh& mesh, const glm::vec3& delta);
+ void grabFinish(Mesh& mesh, BVH& bvh);
// Brushes that change mask or polypaint call these before writing
// mesh.mask[v] / mesh.colors[v] (after ensureMask()/ensureColors()), so
diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cpp
index 7a82b00c..89610d8c 100644
--- a/src/render/Renderer.cpp
+++ b/src/render/Renderer.cpp
@@ -1341,6 +1341,7 @@ void Renderer::syncScene(const std::vector<SceneMesh>& scene) {
it = slots_.erase(it);
}
drawList_.clear();
+ proxyPending_ = false;
for (const SceneMesh& m : scene) {
if (!m.visible || !m.mesh) continue; // hidden: keeps its dirty state until shown
MeshSlot& ms = slot(m.id);
@@ -1689,23 +1690,38 @@ void Renderer::buildProxies(MeshSlot& s, const Mesh& mesh) {
gl::BindVertexArray(0);
s.proxyAllocated = true;
}
- std::vector<std::vector<uint16_t>> built(cullScratch_.size());
- poolFor(cullScratch_.size(), [&](size_t i0, size_t i1) {
- for (size_t i = i0; i < i1; ++i) {
- const uint32_t c = cullScratch_[i];
- ClusterBounds b = s.bounds[c];
- if (!clusterProxy(mesh, s.order, c, s.order.clusterTriangles(c) / 4, built[i], b)) built[i].clear();
- s.proxyBounds[c] = b;
- }
- }, 1, 2);
+ // A few milliseconds a frame: after a long stroke most of the front is stale, and building all of it in the first
+ // moving frame stalled the view (180-300 ms at 33M). Stale clusters draw in full detail until theirs is built.
+ constexpr double kProxyBudgetMs = 8.0;
+ constexpr size_t kProxyBatch = 1024; // clusters per parallel batch
+ const auto start = std::chrono::steady_clock::now();
+ std::vector<std::vector<uint16_t>> built;
gl::BindVertexArray(s.proxyVao);
- for (size_t i = 0; i < cullScratch_.size(); ++i) {
- const uint32_t c = cullScratch_[i];
- s.proxyCount[c] = uint32_t(built[i].size());
- s.proxyStale[c] = 0;
- if (!built[i].empty())
- gl::BufferSubData(GL_ELEMENT_ARRAY_BUFFER, GLintptr(size_t(s.order.firstTriangle(c) / 4) * 3 * sizeof(uint16_t)),
- GLsizeiptr(built[i].size() * sizeof(uint16_t)), built[i].data());
+ for (size_t at = 0; at < cullScratch_.size();) {
+ const size_t n = std::min(kProxyBatch, cullScratch_.size() - at);
+ built.assign(n, {});
+ poolFor(n, [&](size_t i0, size_t i1) {
+ for (size_t i = i0; i < i1; ++i) {
+ const uint32_t c = cullScratch_[at + i];
+ ClusterBounds b = s.bounds[c];
+ if (!clusterProxy(mesh, s.order, c, s.order.clusterTriangles(c) / 4, built[i], b)) built[i].clear();
+ s.proxyBounds[c] = b;
+ }
+ }, 1, 2);
+ for (size_t i = 0; i < n; ++i) {
+ const uint32_t c = cullScratch_[at + i];
+ s.proxyCount[c] = uint32_t(built[i].size());
+ s.proxyStale[c] = 0;
+ if (!built[i].empty())
+ gl::BufferSubData(GL_ELEMENT_ARRAY_BUFFER, GLintptr(size_t(s.order.firstTriangle(c) / 4) * 3 * sizeof(uint16_t)),
+ GLsizeiptr(built[i].size() * sizeof(uint16_t)), built[i].data());
+ }
+ at += n;
+ if (at < cullScratch_.size() &&
+ std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count() > kProxyBudgetMs) {
+ proxyPending_ = true;
+ break;
+ }
}
gl::BindVertexArray(0);
}
@@ -2182,7 +2198,7 @@ void Renderer::sync(MeshSlot& s, Mesh& mesh, const NormalMapView* normalMap, boo
s.fresh = false;
uploadPatches(s, mesh, wireframe); // (may ask for a full upload next time)
mesh.clearDirty();
- if (syncLog && (full || ranged)) {
+ if (syncLog && (full || ranged || proxyMs > 1.0)) {
size_t sent = 0;
for (const auto& [b0, e0] : dirtyRuns_) sent += e0 - b0;
SDL_Log("sync: %s %zu slots in %zu runs, %.1f ms (vertices %.1f, bounds %.1f, proxy %.1f)", full ? "full" : "ranged",
diff --git a/src/render/Renderer.h b/src/render/Renderer.h
index 50a1e27c..d7a05490 100644
--- a/src/render/Renderer.h
+++ b/src/render/Renderer.h
@@ -208,6 +208,8 @@ public:
size_t gpuBytes() const;
// Triangles the last draw() sent to the GPU (after culling), for the benchmark.
size_t lastDrawnTriangles() const { return lastDrawn_; }
+ // The last syncScene left motion proxies to build (a few milliseconds of them a frame; the rest draw in full).
+ bool proxiesPending() const { return proxyPending_; }
// Texture of matcap `index` (sRGB RGBA8, rows bottom-up) for UI previews; 0 if none (or a custom one not
// uploaded yet: the next syncScene or draw does).
@@ -350,6 +352,7 @@ private:
void buildLines(MeshSlot& s, const Mesh& mesh);
void buildProxies(MeshSlot& s, const Mesh& mesh);
bool proxyUsed_ = false; // the last draw() drew motion proxies: sync keeps them current
+ bool proxyPending_ = false; // (proxiesPending)
// The ghost (setGhost), drawn on the slot ghostId_.
GhostStroke ghost_;
uint32_t ghostId_ = 0;
diff --git a/tests/test_grab_coalesce.cpp b/tests/test_grab_coalesce.cpp
new file mode 100644
index 00000000..dbf64262
--- /dev/null
+++ b/tests/test_grab_coalesce.cpp
@@ -0,0 +1,58 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Move once a frame (App::queueGrab / flushGrab): the positions move with every pointer sample (grabMove), the
+// normals and the BVH once a frame (grabFinish); the mesh comes out as a whole grab per sample left it, bit for bit.
+#include "TestHarness.h"
+
+#include "core/Primitives.h"
+#include "core/Sculpt.h"
+
+#include <cmath>
+
+using namespace sf;
+
+TEST(grab_once_a_frame_matches_per_sample) {
+ DabParams p;
+ p.center = glm::vec3(0, 0, 1);
+ p.radius = 0.6f;
+ p.strength = 0.5f;
+ const Symmetry sym{true, false, false}; // (a mirror too)
+ // A wiggly pointer path: 240 samples, applied one by one or in frames of 4-9.
+ std::vector<glm::vec3> deltas;
+ for (int i = 0; i < 240; ++i)
+ deltas.push_back(glm::vec3(0.004f * std::sin(0.11f * float(i)), 0.003f * std::cos(0.07f * float(i)), 0.002f));
+ auto run = [&](bool perSample) {
+ Document d = makeDoc(makeIcosphere(5));
+ d.sculptor.beginStroke(d.mesh, "Move");
+ d.sculptor.beginGrab(d.mesh, d.bvh, p, sym);
+ int inFrame = 0;
+ for (size_t i = 0; i < deltas.size(); ++i) {
+ if (perSample) {
+ d.sculptor.grab(d.mesh, d.bvh, deltas[i]);
+ continue;
+ }
+ d.sculptor.grabMove(d.mesh, deltas[i]);
+ if (++inFrame == 4 + int(i % 6) || i + 1 == deltas.size()) {
+ d.sculptor.grabFinish(d.mesh, d.bvh);
+ inFrame = 0;
+ }
+ }
+ d.sculptor.endStroke();
+ return d.mesh;
+ };
+ const Mesh a = run(true), b = run(false);
+ CHECK(a.positions.size() == b.positions.size());
+ float worst = 0.0f, worstNormal = 0.0f, moved = 0.0f;
+ const Mesh start = makeIcosphere(5);
+ for (size_t v = 0; v < a.positions.size(); ++v) {
+ worst = std::max(worst, glm::length(a.positions[v] - b.positions[v]));
+ worstNormal = std::max(worstNormal, glm::length(a.normals[v] - b.normals[v]));
+ moved = std::max(moved, glm::length(a.positions[v] - start.positions[v]));
+ }
+ std::printf(" grab per sample vs once a frame: positions within %.2g, normals within %.2g (moved up to %.3f)\n",
+ double(worst), double(worstNormal), double(moved));
+ CHECK(moved > 0.1f); // (the stroke did move the surface)
+ CHECK(worst == 0.0f && worstNormal == 0.0f);
+ CHECK(a.positions == b.positions && a.normals == b.normals);
+}
diff --git a/tests/test_memory_guard.cpp b/tests/test_memory_guard.cpp
new file mode 100644
index 00000000..177eeb25
--- /dev/null
+++ b/tests/test_memory_guard.cpp
@@ -0,0 +1,73 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Free memory checks (core/MemoryGuard.h) with a mocked amount of free memory: a benchmark scene that wouldn't fit
+// is skipped with a clear message, and Subdivide / Divide / micro / remesh know what they'd need.
+#include "TestHarness.h"
+
+#include "core/MemoryGuard.h"
+#include "core/Primitives.h"
+
+using namespace sf;
+
+namespace {
+
+constexpr size_t kGB = 1'000'000'000;
+
+// The standard scenes' need (ProofMode: millions x 1e6 x 150 bytes a triangle).
+size_t sceneNeed(double millions) { return size_t(millions * 1e6 * 150.0); }
+
+} // namespace
+
+TEST(memory_check_margin) {
+ CHECK(memoryMargin(100) == size_t(512) << 20); // at least 512 MB
+ CHECK(memoryMargin(10 * kGB) == kGB); // else a tenth
+ CHECK(checkMemory(kGB, 0).enough); // unknown free memory: go on
+ CHECK(checkMemory(0, 1).enough); // nothing needed
+ CHECK(checkMemory(kGB, 2 * kGB).enough);
+ CHECK(!checkMemory(kGB, kGB).enough); // fits only without the margin
+}
+
+TEST(memory_benchmark_scene_skipped) {
+ setAvailableMemoryOverride(size_t(1.3 * double(kGB))); // Tony's machine: 1.3 GB free
+ CHECK(availableMemoryBytes() == size_t(1.3 * double(kGB)));
+ const MemoryCheck c33 = checkMemory(sceneNeed(33));
+ CHECK(!c33.enough);
+ const std::string msg = benchmarkSkippedMessage("33M", c33);
+ CHECK(msg == "33M skipped: needs ~5 GB free, 1.3 GB available. Close other apps and run again");
+ CHECK(!checkMemory(sceneNeed(15)).enough); // (15M: ~2.3 GB)
+
+ setAvailableMemoryOverride(4 * kGB); // enough for 15M, not 33M
+ CHECK(checkMemory(sceneNeed(15)).enough);
+ CHECK(!checkMemory(sceneNeed(33)).enough);
+ setAvailableMemoryOverride(8 * kGB);
+ CHECK(checkMemory(sceneNeed(33)).enough);
+ setAvailableMemoryOverride(0); // (back to the system's own number)
+ CHECK(availableMemoryBytes() != size_t(8 * kGB));
+}
+
+TEST(memory_gigabytes_text) {
+ CHECK(formatGigabytes(size_t(4.95 * double(kGB))) == "5 GB");
+ CHECK(formatGigabytes(size_t(2.26 * double(kGB))) == "2.3 GB");
+ CHECK(formatGigabytes(size_t(0.4 * double(kGB))) == "0.4 GB");
+ CHECK(formatGigabytes(size_t(12.3 * double(kGB))) == "12 GB");
+}
+
+TEST(memory_command_need) {
+ const Mesh m = makeIcosphere(5); // 20480 triangles
+ const size_t nt = m.triangleCount();
+ CHECK(commandMemoryNeed(m, "subdivide", {}) == size_t(double(nt) * 4 * 150));
+ CHECK(commandMemoryNeed(m, "subdivide", {{"levels", 2.0}}) == size_t(double(nt) * 16 * 150));
+ CHECK(commandMemoryNeed(m, "subdiv_divide", {}) > 0);
+ CHECK(commandMemoryNeed(m, "micro_divide", {{"level", 3.0}}) == size_t(double(nt) * 64 * 6));
+ CHECK(commandMemoryNeed(m, "remesh", {{"resolution", 512.0}}) > commandMemoryNeed(m, "remesh", {{"resolution", 128.0}}));
+ CHECK(commandMemoryNeed(m, "smooth", {}) == 0); // not one of the big ones
+ CHECK(commandMemoryNeed(Mesh(), "subdivide", {}) == 0);
+
+ // Four levels of Subdivide on this sphere need ~0.8 GB: refused with 0.5 GB free (a dialog asks in the app).
+ setAvailableMemoryOverride(kGB / 2);
+ const MemoryCheck c = checkMemory(commandMemoryNeed(m, "subdivide", {{"levels", 4.0}}));
+ CHECK(!c.enough);
+ CHECK(commandShortMessage("Subdivide", c) == "Subdivide needs ~0.8 GB free, 0.5 GB available.");
+ setAvailableMemoryOverride(0);
+}
diff --git a/tests/ui/memory_confirm.sfui b/tests/ui/memory_confirm.sfui
new file mode 100644
index 00000000..d045efcc
--- /dev/null
+++ b/tests/ui/memory_confirm.sfui
@@ -0,0 +1,21 @@
+# Subdivide that wouldn't fit the memory free now asks first (core/MemoryGuard.h, app/MemoryConfirm.cpp): Cancel
+# leaves the mesh, Continue anyway subdivides. Free memory is mocked at 300 MB (two levels of this sphere need ~50 MB
+# plus a 512 MB margin).
+run new_sphere subdivisions=5
+expect_value triangles == 20480
+env SF_AVAILABLE_MEMORY_MB 300
+run_fails subdivide levels=2
+expect_value memory_confirm_open == 1
+expect_text "Subdivide needs"
+click "Cancel##memoryconfirm"
+expect_value memory_confirm_open == 0
+expect_value triangles == 20480
+run_fails subdivide levels=2
+click "Continue anyway##memoryconfirm"
+expect_value memory_confirm_open == 0
+expect_value triangles == 327680
+# With the memory there, no question.
+env SF_AVAILABLE_MEMORY_MB 0
+run undo
+run subdivide levels=2
+expect_value memory_confirm_open == 0
diff --git a/tools/benchmark/submit.py b/tools/benchmark/submit.py
index 23961852..558b7512 100644
--- a/tools/benchmark/submit.py
+++ b/tools/benchmark/submit.py
@@ -72,6 +72,8 @@ def validate(doc):
runs = need(doc, "runs", "list", "root") or []
if not runs:
errs.append("runs: empty")
+ for k in doc.get("skipped") or []: # a scene left out for lack of free memory: not a complete result
+ errs.append(f"skipped: {k.get('message', k.get('label', '?'))}")
for i, run in enumerate(runs):
w = f"runs[{i}]"
need(run, "label", "str", w)