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
Help > Record a performance trace (#127): long frames with their breakdown, strokes, long commands, background jobs, mesh size and levels, GPU and driver, to sculptforge-trace.log (2 x 2 MB, local only)
islandmed2eee2e0bc78c
diff --git a/CMakeLists.txt b/CMakeLists.txtindex bffd2d19..f7ba40ee 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -47,6 +47,7 @@ add_library(sculptforge_core STATICsrc/core/Benchmark.cppsrc/core/HardwareProfile.cppsrc/core/FrameGovernor.cpp+ src/core/PerfTrace.cppsrc/core/TierConfig.cppsrc/core/MemoryGuard.cppsrc/core/Sculpt.cppdiff --git a/changes/feat-perf-trace.md b/changes/feat-perf-trace.mdnew file mode 100644index 00000000..c67ef20e--- /dev/null+++ b/changes/feat-perf-trace.md@@ -0,0 +1,12 @@+---+whats_new: **Record a performance trace** (Help menu, #127): turn it on, do what feels slow, turn it off and attach sculptforge-trace.log (Help > Open log folder) to your report.+added: **Help > Record a performance trace** (#127, thanks RodTDai): while on, `sculptforge-trace.log` beside+ `sculptforge.log` records every frame over 33 ms with where its time went (events, dabs, UI, GPU uploads, drawing,+ GPU time), each stroke's timings, commands that held up the frames, background jobs starting and ending, the mesh+ size, subdivision and micro level, and the GPU, driver and CPU. Off by default and costs nothing when off; two files+ of 2 MB at most (`sculptforge-trace-previous.log`); a local file only, nothing is sent anywhere.+testers:+ - Windows: Help > Record a performance trace, sculpt on a big mesh and orbit, run Voxel Remesh, turn it off; Help > Open log folder shows sculptforge-trace.log with "long frame", "stroke", "command" and "jobs" lines and your GPU on the first line.+ - Any OS: restart; the trace is off again.+---+Reuses the main loop's phase marks (SF_FRAME_LOG), the stroke's SculptTimings and the frame governor's GPU timer.diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.mdindex 83438f47..30533010 100644--- a/docs/guide/troubleshooting.md+++ b/docs/guide/troubleshooting.md@@ -240,6 +240,16 @@ last. Every start keeps the previous session's log as `sculptforge-previous.log`**attach `sculptforge-previous.log` to your report** (the new `sculptforge.log` is the session after it). It holdsno models and no keys, only command names and messages, which may include file names.+### A performance trace++When SculptForge gets slow, **Help > Record a performance trace** shows where the time goes. Turn it on, do what+feels slow (the stroke, the orbit, the remesh), then choose it again to stop. `sculptforge-trace.log` beside the+log then lists every frame that took longer than 33 ms with its parts (events, dabs, interface, GPU uploads,+drawing, GPU time), each stroke's timings, commands that held up the frames, background jobs starting and+ending, the mesh size and levels, and on its first line your GPU, driver and CPU. **Attach it to your report.**+It is off by default and costs nothing when off; it stays small (2 MB, then the older lines move to+`sculptforge-trace-previous.log`) and never leaves your computer.+## Recovering work after a crashSculptForge autosaves unsaved work every 5 minutes by default (**Edit > Preferences > Autosave**, 0 turns it off).@@ -287,6 +297,7 @@ good report includes:as script** and paste it into the report. It often reproduces the problem exactly.5. **After a crash, the log**: `sculptforge-previous.log` from **Help > Open log folder** (see[The log file](#the-log-file)).+ **When it is slow**, a [performance trace](#a-performance-trace) of the slowdown.6. **A file** if the problem is with a particular model (a small `.sfproj` or the original file), and ascreenshot for display problems.diff --git a/src/app/App.cpp b/src/app/App.cppindex fc031144..3acd3a9a 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -10,6 +10,7 @@#include "app/AsyncStroke.h"#include "app/Calibration.h"#include "app/CrashLog.h"+#include "core/PerfTrace.h"#include "ai/AiCommands.h"#include "app/Demo.h"@@ -432,6 +433,10 @@ int App::runUiTest(int w, int h, int fps) {touchTick(); // a finger's press that waited for a second finger long enough goes throughhardwareProfileFrameBegin(); // (only with SF_HW_PROFILE_IN_TESTS=1: tests use fixed settings)+ // Help > Record a performance trace: run()'s phases, roughly (no events, dabs or 3D view drawn here).+ double tracePhase[7] = {};+ const bool tracing = perftrace::on();+ if (tracing) tracePhase[0] = tracePhase[1] = tracePhase[2] = double(SDL_GetTicksNS()) * 1e-6;Demo::beginFrame();if (uiScaleDirty_) applyUiScale(); // (Preferences, a display-scale change: #87)lap(frameMs[0]);@@ -451,6 +456,7 @@ int App::runUiTest(int w, int h, int fps) {ImGui::LogFinish();ImGui::Render();lap(frameMs[2]);+ if (tracing) tracePhase[3] = double(SDL_GetTicksNS()) * 1e-6;updateMouseCursor();buildGhost(); // (the stroke preview, as run() draws it)@@ -461,6 +467,10 @@ int App::runUiTest(int w, int h, int fps) {notePerformanceFrame(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - syncStart).count());viewSamples(); // keeps Fast Navigation's view of the camera current (UI tests read view_samples)hardwareProfileFrameEnd();+ if (tracing) {+ tracePhase[4] = tracePhase[5] = tracePhase[6] = double(SDL_GetTicksNS()) * 1e-6;+ tracePerfFrame(tracePhase);+ }++frames;const std::string shot = demo_->takeShotRequest();if (shot.empty()) continue;@@ -754,7 +764,7 @@ int App::run() {double phase[10] = {};int phases = 0;const auto mark = [&] {- if ((frameLogMs >= 0.0 || proof_) && phases < 10) phase[phases++] = double(SDL_GetTicksNS()) * 1e-6;+ if ((frameLogMs >= 0.0 || proof_ || perftrace::on()) && phases < 10) phase[phases++] = double(SDL_GetTicksNS()) * 1e-6;};auto seconds = [] { return double(SDL_GetTicksNS()) * 1e-9; };// --measure-idle: let start-up settle (first frames, the Library's thumbnails), then count.@@ -1116,6 +1126,7 @@ int App::run() {SDL_Log("frame %.1f ms: events %.1f, dabs %.1f, UI %.1f, ghost + sync %.1f, draw %.1f, UI draw + swap %.1f",phase[6] - phase[0], phase[1] - phase[0], phase[2] - phase[1], phase[3] - phase[2], phase[4] - phase[3],phase[5] - phase[4], phase[6] - phase[5]);+ if (phases == 7 && perftrace::on()) tracePerfFrame(phase); // Help > Record a performance trace++framesDrawn;{const double frameNow = seconds();@@ -2365,7 +2376,16 @@ void App::runCommand(const std::string& name, const Args& args) {if (name == "save_project") storeProjectSettings();flushBrushEdits(); // commands may replace brushes: save edits first, then watch what's there afterwardscrashlog::action(name); // (failures reach the log through SDL_Log below)+ const auto commandStart = std::chrono::steady_clock::now();CommandResult r = commands_.execute(doc_, name, args);+ if (perftrace::on()) { // a command that held up the frames (remesh, Divide, micro, open...)+ const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - commandStart).count();+ if (ms > perf_.traceLongMs) {+ char took[48];+ std::snprintf(took, sizeof took, " took %.1f ms%s | ", ms, r.ok ? "" : " (failed)");+ perftrace::line("command " + name + took + perfTraceScene());+ }+ }status_ = r.message;if (name.rfind("uv_", 0) == 0 || name == "texture_create" || name == "texture_delete") uvEditorChanged();lastCommandOk_ = r.ok;diff --git a/src/app/App.h b/src/app/App.hindex 01277bcc..2f7012bc 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -1045,7 +1045,18 @@ private:double lastStrokeSyncMs = 0.0;int lastStrokeFrames = 0;bool gpuOutOfMemory = false;+ double lastSyncMs = 0.0; // the last frame's scene sync (GPU uploads)+ std::string traceJobs; // the background jobs running at the last traced frame+ double traceJobsSince = 0.0; // (seconds) when they last changed+ double traceLongMs = 33.0; // perftrace::kLongFrameMs (SF_PERF_TRACE_MS: UI tests write every frame)} perf_;+ // Help > Record a performance trace (core/PerfTrace.h, #127; PanelPerformanceProfile.cpp): the toggle, and the+ // lines it writes: long frames (with the loop's phase times), strokes, long commands, background jobs.+ void togglePerfTrace();+ void tracePerfFrame(const double* phase); // phase[0..6]: the main loop's marks (App::run)+ void tracePerfStroke(const std::string& label);+ std::string perfTraceScene() const; // mesh size, levels, view state+ std::string perfTraceJobs() const; // the background jobs running now, by name// Hardware profile (PanelPerformanceProfile.cpp; app/Calibration.h, core/HardwareProfile.h, core/FrameGovernor.h):// calibrates on first launch and when the GPU, driver or version changes; the profile section of Preferences >// Performance; the adaptive frame governor, fed every frame between FrameBegin and FrameEnd.diff --git a/src/app/AsyncStroke.cpp b/src/app/AsyncStroke.cppindex d50172b1..8669cdcf 100644--- a/src/app/AsyncStroke.cpp+++ b/src/app/AsyncStroke.cpp@@ -12,6 +12,7 @@#include "app/AsyncStroke.h"#include "core/Micro.h"+#include "core/PerfTrace.h"#include "core/Sculpt.h"#include "core/TierConfig.h"@@ -385,7 +386,8 @@ void App::finishStrokeNow() {strokeMask_ = false;maskClickPending_ = false;firstDabPending_ = false;- // Preferences > Performance shows what the stroke cost.+ // Preferences > Performance shows what the stroke cost (and Help > Record a performance trace writes it).+ const bool traceStroke = doc_.sculptor.timings.dabs > 0 && perftrace::on();if (doc_.sculptor.timings.dabs > 0) {perf_.lastStroke = doc_.sculptor.timings;perf_.lastStrokeSyncMs = perf_.strokeSyncMs;@@ -395,6 +397,7 @@ void App::finishStrokeNow() {perf_.strokeSyncMs = 0.0;perf_.strokeFrames = 0;UndoRecord r = doc_.sculptor.endStroke();+ if (traceStroke) tracePerfStroke(r.label);finishPaintStroke(r);if (r.topology && !r.topology->uvs.empty())status_ = "Dynamic topology removed the UVs of the remeshed Part (Undo brings them back)";diff --git a/src/app/Config.cpp b/src/app/Config.cppindex 908f63f4..88c8874e 100644--- a/src/app/Config.cpp+++ b/src/app/Config.cpp@@ -11,6 +11,7 @@#include "app/App.h"#include "app/UiServe.h"#include "app/CrashLog.h"+#include "core/PerfTrace.h"#include "app/LookSchemes.h"#include "app/Palettes.h"#include "app/Ui.h"@@ -671,6 +672,12 @@ void App::initActions() {ICON_LC_FILE_TEXT, nullptr, nullptr, nullptr,"Open the folder with sculptforge.log: what SculptForge did and, after a crash, what crashed. ""sculptforge-previous.log beside it is the last session's. Attach both to a problem report.");+ add("help.perf_trace", "Record a performance trace", "Help", nullptr, [this] { togglePerfTrace(); }, ICON_LC_ACTIVITY,+ nullptr, [] { return perftrace::on(); }, nullptr,+ "While on, sculptforge-trace.log in the log folder records what makes SculptForge slow: every frame over 33 ms "+ "with where its time went, strokes, uploads to the GPU, remeshes and other background jobs, the mesh size and "+ "levels, and the GPU and driver. Turn it on, do what is slow, turn it off and attach the file to your report. "+ "A small file on this computer only; off by default and costs nothing when off.");add("help.feedback", "Fixes & suggestions", "Help", nullptr,[] { SDL_OpenURL("https://github.com/islandmed/SculptForge/issues/new/choose"); }, ICON_LC_MESSAGE_SQUARE_PLUS,nullptr, nullptr, nullptr,diff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cppindex 08ff8c4c..2b2d0162 100644--- a/src/app/I18nSpanish.cpp+++ b/src/app/I18nSpanish.cpp@@ -270,6 +270,7 @@ constexpr Entry kSpanish[] = {{"Join the community on Discord", "Únete a la comunidad en Discord"},{"Report a problem", "Informar de un problema"},{"Open log folder", "Abrir la carpeta de registros"},+ {"Record a performance trace", "Grabar una traza de rendimiento"},{"Fixes & suggestions", "Correcciones y sugerencias"},{"Benchmark (proof mode)", "Prueba de rendimiento (modo prueba)"},{"Support SculptForge", "Apoya a SculptForge"},diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex 85cd25a9..22dfa571 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -580,6 +580,7 @@ void App::drawPalette_Help() {menuAction(*this, "help.discord");menuAction(*this, "help.report");menuAction(*this, "help.log");+ menuAction(*this, "help.perf_trace");menuAction(*this, "help.feedback");menuAction(*this, "help.benchmark");ImGui::Separator();diff --git a/src/app/PanelPerformance.cpp b/src/app/PanelPerformance.cppindex d97e04c5..52c88930 100644--- a/src/app/PanelPerformance.cpp+++ b/src/app/PanelPerformance.cpp@@ -203,6 +203,7 @@ int App::viewSamples() {}void App::notePerformanceFrame(double syncMs) {+ perf_.lastSyncMs = syncMs;if (doc_.sculptor.strokeActive()) {perf_.strokeSyncMs += syncMs;++perf_.strokeFrames;diff --git a/src/app/PanelPerformanceProfile.cpp b/src/app/PanelPerformanceProfile.cppindex 352e4b89..8f852219 100644--- a/src/app/PanelPerformanceProfile.cpp+++ b/src/app/PanelPerformanceProfile.cpp@@ -13,10 +13,14 @@// machine), and keep the fixed 10 million triangle Fast Navigation threshold.#include "app/App.h"#include "app/Calibration.h"+#include "app/CrashLog.h"#include "app/Ui.h"#include "core/FrameGovernor.h"#include "core/HardwareProfile.h"+#include "core/Micro.h"+#include "core/Multires.h"+#include "core/PerfTrace.h"#include "core/ThreadPool.h"#include "core/TierConfig.h"@@ -27,6 +31,7 @@#include <cstdio>#include <cstdlib>#include <deque>+#include <future>namespace sf {@@ -535,3 +540,130 @@ void App::drawPerformanceProfileSection() {}} // namespace sf++// --- Help > Record a performance trace (core/PerfTrace.h, #127) ---++namespace sf {++namespace {++std::string millions(size_t n) { return n < 1000000 ? std::to_string(n) : fmt("%.2fM", double(n) * 1e-6); }++} // namespace++void App::togglePerfTrace() {+ if (perftrace::on()) {+ perftrace::stop();+ status_ = "Performance trace stopped: sculptforge-trace.log is in the log folder (Help > Open log folder)";+ return;+ }+ std::string folder = crashlog::path();+ if (const size_t slash = folder.find_last_of("/\\"); slash != std::string::npos) folder.resize(slash + 1);+ else folder.clear();+ if (folder.empty()) {+ if (char* pref = SDL_GetPrefPath("SculptForge", "SculptForge")) {+ folder = pref;+ SDL_free(pref);+ }+ }+ HardwareInfo hw;+ if (hwProfile_) hw = hwProfile_->profile.hardware;+ else probeHardware(hw);+ std::string header = std::string("SculptForge ") + SCULPTFORGE_VERSION + " performance trace | GPU " + hw.glRenderer ++ " (" + hw.glVendor + ", " + gpuKindName(hw.gpuKind) + ", " + std::to_string(hw.vramMB) ++ " MB) | OpenGL " + hw.glVersion + " | " + hw.cpu + ", " + std::to_string(hw.cpuThreads) ++ " threads, " + std::to_string(hw.ramMB) + " MB RAM, " + hw.simdBuild + " | " + hw.os;+ if (hwProfile_)+ header += std::string(" | profile ") + tierName(hwProfile_->profile.tier) + ", " ++ std::to_string(hwProfile_->tier.targetHz) + " Hz target, display " + std::to_string(hwProfile_->displayHz) + " Hz";+ perf_.traceLongMs = perftrace::kLongFrameMs;+ if (const char* ms = std::getenv("SF_PERF_TRACE_MS"); ms && *ms) perf_.traceLongMs = std::atof(ms);+ header += fmt(" | frames over %.0f ms are written", perf_.traceLongMs);+ if (folder.empty() || !perftrace::start(folder, header)) {+ status_ = "Couldn't write the performance trace (the user data folder couldn't be written)";+ return;+ }+ perf_.traceJobs = perfTraceJobs();+ perf_.traceJobsSince = double(SDL_GetTicksNS()) * 1e-9;+ perftrace::line("recording | " + perfTraceScene() + (perf_.traceJobs.empty() ? "" : " | running: " + perf_.traceJobs));+ status_ = "Recording a performance trace: do what is slow, then Help > Record a performance trace again to stop";+}++std::string App::perfTraceScene() const {+ const Mesh& m = doc_.mesh;+ std::string s = "Part " + std::to_string(doc_.activePart + 1) + "/" + std::to_string(doc_.partCount()) + " " ++ millions(m.triangleCount()) + " tris " + millions(m.vertexCount()) + " verts";+ if (const int levels = subdivLevelCount(m); levels > 0)+ s += ", level " + std::to_string(subdivCurrentLevel(m) + 1) + "/" + std::to_string(levels);+ if (m.micro) s += ", micro level " + std::to_string(m.micro->level) + " (" + millions(m.micro->microTriangles()) + " tris)";+ s += " | scene " + millions(perf_.sceneTriangles) + " tris, drawn " + millions(renderer_.lastDrawnTriangles());+ s += ", AA " + std::to_string(perf_.samplesUsed) + fmt(", view %.0f%%", double(uiPrefs_.viewResolution));+ if (perf_.movingNow) s += ", moving";+ if (perf_.proxyNow) s += ", proxy";+ if (doc_.sculptor.strokeActive()) s += ", stroke";+ if (perf_.gpuOutOfMemory) s += ", GPU out of memory";+ return s;+}++std::string App::perfTraceJobs() const {+ auto running = [](const auto& f) { return f.valid() && f.wait_for(std::chrono::seconds(0)) != std::future_status::ready; };+ std::string s;+ auto add = [&](bool busy, const char* name) {+ if (!busy) return;+ if (!s.empty()) s += ", ";+ s += name;+ };+ add(bool(voxelRemesh_), "remesh");+ add(bool(qremesh_), "QRemesh");+ add(bool(autoUv_), "Auto UV");+ add(bakeBusy(), "bake");+ add(meshMapsBusy(), "mesh maps");+ add(uvEditorBusy(), "UV editor");+ add(thumbs_.busy(), "thumbnails");+ add(libraryScanner_.busy(), "library scan");+ add(galleryBusy(), "brush gallery");+ add(renderer_.environmentPending(), "environment");+ add(splatTrainBusy(), "splat training");+ add(sculptableBusy(), "make sculptable");+ add(phoneBusy(), "phone");+ add(bool(updateJob_), "update check");+ add(running(pendingBrush_) || running(pendingGenerator_) || running(pendingModels_) || running(pendingUnreal_) ||+ running(pendingComfyCheck_),+ "AI / bridge request");+ add(solverBusy(), "stroke solver");+ return s;+}++void App::tracePerfFrame(const double* phase) {+ // Background jobs that started or ended since the last frame.+ const double now = double(SDL_GetTicksNS()) * 1e-9;+ if (std::string jobs = perfTraceJobs(); jobs != perf_.traceJobs) {+ perftrace::line(fmt("jobs after %.2f s: ", now - perf_.traceJobsSince) + (perf_.traceJobs.empty() ? "none" : perf_.traceJobs) ++ " -> " + (jobs.empty() ? "none" : jobs));+ perf_.traceJobs = std::move(jobs);+ perf_.traceJobsSince = now;+ }+ const double total = phase[6] - phase[0];+ if (total <= perf_.traceLongMs) return;+ char buf[320];+ std::snprintf(buf, sizeof buf,+ "long frame %.1f ms: events %.1f, dabs %.1f, UI %.1f, ghost + sync %.1f (uploads %.1f), draw %.1f, "+ "UI draw + swap %.1f | GPU %s ms (a frame before) | ",+ total, phase[1] - phase[0], phase[2] - phase[1], phase[3] - phase[2], phase[4] - phase[3], perf_.lastSyncMs,+ phase[5] - phase[4], phase[6] - phase[5],+ hwProfile_ && hwProfile_->lastGpuMs >= 0.0 ? fmt("%.1f", hwProfile_->lastGpuMs).c_str() : "?");+ perftrace::line(buf + perfTraceScene() + (perf_.traceJobs.empty() ? "" : " | running: " + perf_.traceJobs));+}++void App::tracePerfStroke(const std::string& label) {+ const SculptTimings& t = perf_.lastStroke;+ char buf[256];+ std::snprintf(buf, sizeof buf,+ "stroke %s: %llu dabs, %s verts moved, kernel %.1f ms, normals %.1f, BVH %.1f, dynamic topology %.1f, "+ "uploads %.1f over %d frames | ",+ label.c_str(), (unsigned long long)t.dabs, millions(size_t(t.vertices)).c_str(), t.kernelMs, t.normalsMs,+ t.bvhMs, t.remeshMs, perf_.lastStrokeSyncMs, perf_.lastStrokeFrames);+ perftrace::line(buf + perfTraceScene());+}++} // namespace sfdiff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex ddd19380..249ea793 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -273,6 +273,7 @@#include "core/ListSort.h"#include "core/LitSphere.h"#include "core/Multires.h"+#include "core/PerfTrace.h"#include "core/Script.h"#include "core/SelectionSets.h"#include "core/ThreadPool.h"@@ -913,6 +914,15 @@ double Demo::query(const std::string& name, bool& known) const {if (name == "brush_pressure") return app_.strokePressure();if (name == "stroking") return app_.drag_ == App::Drag::Stroke ? 1.0 : 0.0;if (name == "tablet_mouse_mode") return app_.uiPrefs_.tablet.mouseMode ? 1.0 : 0.0;+ if (name == "perf_trace") return perftrace::on() ? 1.0 : 0.0; // Help > Record a performance trace+ if (name == "perf_trace_long_frames" || name == "perf_trace_strokes" || name == "perf_trace_commands") {+ std::ifstream in(std::filesystem::path(std::u8string(reinterpret_cast<const char8_t*>(perftrace::path().data()),+ perftrace::path().size())));+ const std::string what = name == "perf_trace_long_frames" ? " long frame " : name == "perf_trace_strokes" ? " stroke " : " command ";+ double n = 0.0;+ for (std::string row; std::getline(in, row);) n += row.find(what) != std::string::npos ? 1.0 : 0.0;+ return n;+ }if (name == "backface_culling") return app_.renderSettings_.backfaceCulling ? 1.0 : 0.0;if (name == "xray") return app_.renderSettings_.xray ? 1.0 : 0.0;if (name == "view_resolution") return double(app_.uiPrefs_.viewResolution);diff --git a/src/core/PerfTrace.cpp b/src/core/PerfTrace.cppnew file mode 100644index 00000000..4008c184--- /dev/null+++ b/src/core/PerfTrace.cpp@@ -0,0 +1,102 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/PerfTrace.h"++#include <chrono>+#include <cstdio>+#include <filesystem>+#include <fstream>+#include <mutex>++namespace sf::perftrace {++namespace detail {+std::atomic<bool> recording{false};+}++namespace {++std::mutex g_mutex;+std::ofstream g_file;+std::string g_path, g_previous, g_header;+size_t g_bytes = 0;+std::chrono::steady_clock::time_point g_start;++std::filesystem::path fsPath(const std::string& utf8) {+ return std::filesystem::path(std::u8string(utf8.begin(), utf8.end()));+}++void writeLocked(const std::string& text) {+ g_file << text << '\n';+ g_file.flush(); // (a crash or a kill keeps what was written)+ g_bytes += text.size() + 1;+}++// The file is full: it becomes the previous one and a new one starts with the header.+void rotateLocked() {+ g_file.close();+ std::error_code ec;+ std::filesystem::remove(fsPath(g_previous), ec);+ std::filesystem::rename(fsPath(g_path), fsPath(g_previous), ec);+ g_file.open(fsPath(g_path), std::ios::binary | std::ios::trunc);+ g_bytes = 0;+ if (g_file) writeLocked(g_header + " (continued: the earlier lines are in sculptforge-trace-previous.log)");+}++} // namespace++bool start(const std::string& folder, const std::string& header) {+ std::lock_guard lock(g_mutex);+ if (detail::recording) return true;+ std::string dir = folder;+ if (!dir.empty() && dir.back() != '/' && dir.back() != '\\') dir += '/';+ g_path = dir + "sculptforge-trace.log";+ g_previous = dir + "sculptforge-trace-previous.log";+ g_header = header;+ std::error_code ec;+ if (!dir.empty()) std::filesystem::create_directories(fsPath(dir), ec);+ const auto size = std::filesystem::file_size(fsPath(g_path), ec);+ g_bytes = ec ? 0 : size_t(size);+ g_file.open(fsPath(g_path), std::ios::binary | std::ios::app);+ if (!g_file) {+ g_path.clear();+ return false;+ }+ g_start = std::chrono::steady_clock::now();+ if (g_bytes >= kMaxBytes) rotateLocked();+ else writeLocked(g_header);+ detail::recording = true;+ return true;+}++void stop() {+ std::lock_guard lock(g_mutex);+ if (!detail::recording) return;+ detail::recording = false;+ writeLocked("recording stopped");+ g_file.close();+ g_path.clear();+}++void line(const std::string& text) {+ if (!on()) return;+ std::lock_guard lock(g_mutex);+ if (!detail::recording) return;+ char at[32];+ std::snprintf(at, sizeof at, "%9.3f ",+ std::chrono::duration<double>(std::chrono::steady_clock::now() - g_start).count());+ writeLocked(at + text);+ if (g_bytes >= kMaxBytes) rotateLocked();+}++std::string path() {+ std::lock_guard lock(g_mutex);+ return g_path;+}++std::string previousPath() {+ std::lock_guard lock(g_mutex);+ return g_previous;+}++} // namespace sf::perftracediff --git a/src/core/PerfTrace.h b/src/core/PerfTrace.hnew file mode 100644index 00000000..8f0da1ff--- /dev/null+++ b/src/core/PerfTrace.h@@ -0,0 +1,35 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Help > Record a performance trace (#127): while on, the app writes what makes it slow to+// sculptforge-trace.log next to sculptforge.log (Help > Open log folder): every frame longer than kLongFrameMs+// with its breakdown, each stroke's timings, the commands that took long, background jobs starting and ending,+// with the mesh size, levels and the GPU. Off by default, and off it costs one relaxed atomic load per frame.+// The file stays small: past kMaxBytes it moves to sculptforge-trace-previous.log and a new one starts (with the+// header again). A local file only: nothing here uses the network.+#pragma once++#include <atomic>+#include <cstddef>+#include <string>++namespace sf::perftrace {++constexpr double kLongFrameMs = 33.0; // longer than two frames at 60 Hz+constexpr size_t kMaxBytes = 2 * 1024 * 1024; // per file (two files at most)++namespace detail {+extern std::atomic<bool> recording;+}+inline bool on() { return detail::recording.load(std::memory_order_relaxed); }++// Starts recording into `folder`/sculptforge-trace.log (appending to an earlier recording there); `header` (the+// app version, GPU, driver, CPU...) starts the recording and every new file. False if the file can't be written.+bool start(const std::string& folder, const std::string& header);+void stop();+// A line in the trace, after the seconds since the recording started. Does nothing when off. Thread-safe.+void line(const std::string& text);+std::string path(); // "" when not recording+std::string previousPath(); // the file the last full one moved to++} // namespace sf::perftracediff --git a/tests/test_perf_trace.cpp b/tests/test_perf_trace.cppnew file mode 100644index 00000000..17f6f480--- /dev/null+++ b/tests/test_perf_trace.cpp@@ -0,0 +1,70 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Help > Record a performance trace (core/PerfTrace.h, #127): nothing written when off, lines after the header+// when on, appending to an earlier recording, and two small files at most.+#include "TestHarness.h"++#include "core/PerfTrace.h"++#include <filesystem>+#include <fstream>+#include <iterator>++using namespace sf;+namespace fs = std::filesystem;++namespace {++fs::path freshFolder(const char* name) {+ const fs::path dir = fs::temp_directory_path() / (std::string("sculptforge_perftrace_") + name);+ fs::remove_all(dir);+ return dir;+}++std::string readFile(const fs::path& p) {+ std::ifstream in(p, std::ios::binary);+ return std::string((std::istreambuf_iterator<char>(in)), {});+}++} // namespace++TEST(perf_trace_off_writes_nothing_on_writes_lines) {+ const fs::path dir = freshFolder("onoff");+ CHECK(!perftrace::on());+ perftrace::line("before"); // off: no file, no cost+ CHECK(!fs::exists(dir / "sculptforge-trace.log"));+ CHECK(perftrace::start(dir.string(), "HEADER gpu"));+ CHECK(perftrace::on());+ CHECK(perftrace::path() == (dir / "sculptforge-trace.log").string());+ perftrace::line("long frame 48.0 ms");+ perftrace::stop();+ CHECK(!perftrace::on());+ perftrace::line("after");+ std::string text = readFile(dir / "sculptforge-trace.log");+ CHECK(text.rfind("HEADER gpu\n", 0) == 0);+ CHECK(text.find("long frame 48.0 ms") != std::string::npos);+ CHECK(text.find("recording stopped") != std::string::npos);+ CHECK(text.find("before") == std::string::npos && text.find("after") == std::string::npos);+ // A second recording appends (one file for the whole report).+ CHECK(perftrace::start(dir.string(), "HEADER again"));+ perftrace::line("second");+ perftrace::stop();+ text = readFile(dir / "sculptforge-trace.log");+ CHECK(text.find("long frame 48.0 ms") != std::string::npos && text.find("second") != std::string::npos);+ fs::remove_all(dir);+}++TEST(perf_trace_rotates_at_the_size_limit) {+ const fs::path dir = freshFolder("rotate");+ CHECK(perftrace::start(dir.string(), "HEADER"));+ const std::string row(200, 'x');+ for (size_t written = 0; written < perftrace::kMaxBytes * 3; written += row.size()) perftrace::line(row);+ perftrace::stop();+ const fs::path current = dir / "sculptforge-trace.log", previous = dir / "sculptforge-trace-previous.log";+ CHECK(fs::exists(previous));+ CHECK(fs::file_size(current) <= perftrace::kMaxBytes + 512);+ CHECK(fs::file_size(previous) <= perftrace::kMaxBytes + 512);+ CHECK(readFile(current).rfind("HEADER (continued", 0) == 0); // every file starts with the GPU and driver+ fs::remove_all(dir);+}diff --git a/tests/ui/perf_trace.sfui b/tests/ui/perf_trace.sfuinew file mode 100644index 00000000..e64bed12--- /dev/null+++ b/tests/ui/perf_trace.sfui@@ -0,0 +1,22 @@+# Help > Record a performance trace (#127): off by default; on, sculptforge-trace.log beside sculptforge.log gets the+# long frames with their breakdown, strokes and long commands; off again stops it. SF_PERF_TRACE_MS 0 writes every+# frame here (a fast GPU has no frame over 33 ms to write).+run ui_look look=classic layout=classic+run new_sphere subdivisions=4+expect_value perf_trace == 0+env SF_PERF_TRACE_MS 0+click "Help##palette.help"+click "Record a performance trace##help.perf_trace"+expect_value perf_trace == 1+expect_status "Recording a performance trace"+stroke 0.45 0.45 0.55 0.55+wait_idle 10+run subdivide+wait_idle 10+expect_value perf_trace_long_frames > 0+expect_value perf_trace_strokes > 0+expect_value perf_trace_commands > 0+click "Help##palette.help"+click "Record a performance trace##help.perf_trace"+expect_value perf_trace == 0+expect_status "Performance trace stopped"