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
Sculpt Timeline strip, timelapse export and proof mode (Help > Benchmark, --benchmark)
islandmed930f8141acd8
diff --git a/CMakeLists.txt b/CMakeLists.txtindex b50f484c..08e3ff46 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -251,6 +251,8 @@ if(SCULPTFORGE_BUILD_APP)src/app/PanelProject.cppsrc/app/PanelSubTools.cppsrc/app/PanelExtract.cpp+ src/app/PanelTimeline.cpp+ src/app/ProofMode.cppsrc/app/Tablet.cppsrc/app/SpaceMouse.cppsrc/app/Input.cpp@@ -263,6 +265,15 @@ if(SCULPTFORGE_BUILD_APP)target_include_directories(sculptforge PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/lucide)target_compile_definitions(sculptforge PRIVATE SCULPTFORGE_VERSION="${PROJECT_VERSION}"SF_UPDATE_CHECK=$<BOOL:${SCULPTFORGE_UPDATE_CHECK}>)+ # The commit a build came from, for proof mode's results (src/app/ProofMode.cpp); taken when CMake configures.+ find_package(Git QUIET)+ if(GIT_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git)+ execute_process(COMMAND ${GIT_EXECUTABLE} rev-parse --short HEAD WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}+ OUTPUT_VARIABLE SF_GIT_COMMIT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)+ endif()+ if(SF_GIT_COMMIT)+ set_source_files_properties(src/app/ProofMode.cpp PROPERTIES COMPILE_DEFINITIONS "SF_GIT_COMMIT=\"${SF_GIT_COMMIT}\"")+ endif()if(MSVC)target_compile_options(sculptforge PRIVATE /W4 /utf-8 /permissive-)else()diff --git a/src/app/App.cpp b/src/app/App.cppindex 20b9c572..cbb8c50b 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -83,7 +83,7 @@ App::~App() = default;bool App::init(const AppOptions& options) {options_ = options;const bool recording = !options.recordPath.empty() || !options.uiTest.empty();- const bool headless = !options.renderPath.empty() || recording;+ const bool headless = !options.renderPath.empty() || recording || !options.timelapsePath.empty();// UI tests run in a hidden window that never has focus; SDL drops joystick input without focus otherwise, and// the scripted SpaceMouse is a virtual joystick (UiTest.cpp).if (!options.uiTest.empty()) SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");@@ -111,7 +111,8 @@ bool App::init(const AppOptions& options) {const SDL_WindowFlags flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY |(headless ? SDL_WINDOW_HIDDEN : 0) |(options.fullscreen && !headless ? SDL_WINDOW_FULLSCREEN : 0);- const int winW = recording ? options.width : 1600, winH = recording ? options.height : 960;+ const bool sized = recording || options.benchmark; // proof mode: --size (1920x1080 by default)+ const int winW = sized ? options.width : 1600, winH = sized ? options.height : 960;window_ = SDL_CreateWindow("SculptForge", winW, winH, flags);if (!window_) {SDL_Log("SDL_CreateWindow failed: %s", SDL_GetError());@@ -624,6 +625,8 @@ uint64_t App::frameKey() const {int App::run() {if (!options_.renderPath.empty()) return renderHeadless();if (!options_.recordPath.empty() || !options_.uiTest.empty()) return runRecording();+ if (!options_.timelapsePath.empty()) return runTimelapseCli(); // (PanelTimeline.cpp)+ if (options_.benchmark) startProofMode(); // runs in this loop (ProofMode.cpp)if (g_wakeEvent == 0) g_wakeEvent = SDL_RegisterEvents(1);// Dabs are queued and placed within a time budget each frame (strokeTo). SF_STROKE_IMMEDIATE=1 places them all// as each pointer sample arrives, as before 0.9.6 (for comparison).@@ -809,6 +812,7 @@ int App::run() {perf_.samplesUsed = renderer_.drawView(camera_, fbW, fbH, renderSettings_, canvasViewport(fbW, fbH), samples);renderSettings_.motionProxy = false; // (other renders, e.g. project thumbnails, draw in full)ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());+ if (proof_) proofBeforeSwap(fbW, fbH); // Help > Benchmark: timing, video capture, the scripted pointerSDL_GL_SwapWindow(window_);++framesDrawn;if (sm.started && !sm.moving) { // the press is on screen: start moving round the circle@@ -1658,6 +1662,7 @@ void App::drawUi() {drawBrushGallery();if (showImageTo3D_) drawImageTo3D();drawPhoneWindow(); // File > Capture from phone (PanelPhone.cpp)+ drawTimelineUi(); // the Sculpt Timeline strip, timelapse, proof mode HUD (PanelTimeline.cpp, ProofMode.cpp)pollAlphaFile();pollVdm();if (previewLod_ >= 0) {diff --git a/src/app/App.h b/src/app/App.hindex fffafe32..59a3eaa6 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -77,6 +77,15 @@ struct AppOptions {float measureStroke = 0.0f; // --measure-stroke S: a scripted fast circle stroke, report its path and frame timesfloat measureStrokeRadius = 0.0f; // --measure-stroke S,R: the brush radius in screen pixelsfloat measureIdle = 0.0f; // --measure-idle S: after a settling pause, count the frames drawn in S idle seconds, exit+ // --timelapse out.mp4: render the opened project's history (its .sfhist) as a turntable timelapse and exit.+ std::string timelapsePath;+ float timelapseSeconds = 20.0f;+ // --benchmark: proof mode (ProofMode.cpp), then exit. Sizes in millions of triangles (empty: 5, 20, 33 and+ // 100 when memory allows); outputs default to the current folder.+ bool benchmark = false;+ std::string benchmarkSizes, benchmarkOut, benchmarkVideo;+ bool benchmarkNoVideo = false, benchmarkVsync = false;+ float benchmarkStrokeSeconds = 6.0f;};class Demo;@@ -1227,6 +1236,20 @@ private:bool spaceMouseMoving_ = false;int spaceMouseLastButton_ = -1; // for Preferences: "Button N pressed"// ---- end SpaceMouse ----+ // ---- Sculpt Timeline (PanelTimeline.cpp, core/Timeline.h) and proof mode (ProofMode.cpp) ----+ // The history strip along the bottom of the canvas, the timelapse export, and Help > Benchmark: a scripted+ // stroke through the input handlers on 5M..100M+ meshes with a live HUD, an MP4 and a JSON result.+ std::shared_ptr<struct TimelineUiState> timelineUi_;+ std::shared_ptr<struct ProofState> proof_;+ void drawTimelineUi(); // once a frame from drawUi: keeps the timeline attached and draws the strip+ void registerTimelineUiActions(); // view.timeline, timeline.timelapse, help.benchmark+ void startTimelapse(const std::string& path, int width, int height, float seconds, int fps);+ 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+ void proofBeforeSwap(int fbW, int fbH); // the interactive loop, after drawing a frame, before showing it+ void drawProofUi();+ // ---- end Sculpt Timeline ----};} // namespace sfdiff --git a/src/app/Config.cpp b/src/app/Config.cppindex ac6e7afe..6d9b7f71 100644--- a/src/app/Config.cpp+++ b/src/app/Config.cpp@@ -479,6 +479,7 @@ void App::initActions() {registerFaceUiActions(); // Tool > Facial Shapes, face_take_play / face_take_stop (PanelFace.cpp)registerPerformanceUiActions(); // Preferences > Performance (PanelPerformance.cpp)registerInputActions(); // ZBrush keys: U I O, Space, L, V, Ctrl+A / I / H / W..., the input style (Input.cpp)+ registerTimelineUiActions(); // Sculpt Timeline, timelapse, Help > Benchmark (PanelTimeline.cpp)// Every command, so the command palette finds anything scriptable.actions_.registerCommands(diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex bbe4ec8d..c0da2a4d 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -387,6 +387,7 @@ void App::drawPalette_Help() {menuAction(*this, "help.report");menuAction(*this, "help.log");menuAction(*this, "help.feedback");+ menuAction(*this, "help.benchmark");ImGui::Separator();menuAction(*this, "help.about");}diff --git a/src/app/PanelTimeline.cpp b/src/app/PanelTimeline.cppnew file mode 100644index 00000000..a8313339--- /dev/null+++ b/src/app/PanelTimeline.cpp@@ -0,0 +1,567 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// The Sculpt Timeline strip (docs/guide/timeline.md): every step of the history as a tick along the bottom of the+// canvas. Drag the scrubber to see the model at any point, click a tick to go there; sculpting from an earlier+// point starts a branch and the old continuation stays as a lane above the track (click it to switch back).+// Right-click a stroke to re-tune its strength. Timelapse renders the history as a turntable video. The data+// side is core/Timeline.h; Help > Benchmark (proof mode) is in ProofMode.cpp.+#include "app/App.h"+#include "app/Theme.h"+#include "app/Ui.h"++#include "core/Json.h"+#include "core/Timeline.h"++#include <IconsLucide.h>++#include <algorithm>+#include <chrono>+#include <cmath>+#include <cstdio>+#include <ctime>+#include <filesystem>+#include <fstream>+#include <sstream>++namespace sf {++namespace {++std::filesystem::path fsPathOf(const std::string& p) { return std::filesystem::path(std::u8string(p.begin(), p.end())); }+std::string utf8Of(const std::filesystem::path& p) {+ const auto s = p.u8string();+ return std::string(s.begin(), s.end());+}++ImU32 kindColor(Timeline::Kind k, float alpha) {+ switch (k) {+ case Timeline::Kind::Stroke: return theme::u32(theme::rgb(0xc9c9cf), alpha);+ case Timeline::Kind::Mask: return theme::u32(theme::rgb(0x6aa2e8), alpha);+ case Timeline::Kind::Paint: return theme::u32(theme::rgb(0xd77fb3), alpha);+ case Timeline::Kind::Visibility: return theme::u32(theme::rgb(0x8fc07a), alpha);+ case Timeline::Kind::Topology: return theme::u32(theme::rgb(0x4fc3c0), alpha);+ default: return theme::u32(theme::textDim, alpha);+ }+}++const char* kindLabel(Timeline::Kind k) {+ switch (k) {+ case Timeline::Kind::Start: return "Start";+ case Timeline::Kind::Stroke: return "Stroke";+ case Timeline::Kind::Mask: return "Mask";+ case Timeline::Kind::Paint: return "Paint";+ case Timeline::Kind::Visibility: return "Visibility";+ case Timeline::Kind::Topology: return "Topology";+ default: return "Edit";+ }+}++std::string ago(double unixTime) {+ const double now = std::chrono::duration<double>(std::chrono::system_clock::now().time_since_epoch()).count();+ const double s = std::max(0.0, now - unixTime);+ char buf[64];+ if (s < 60) std::snprintf(buf, sizeof buf, "%.0f s ago", s);+ else if (s < 3600) std::snprintf(buf, sizeof buf, "%.0f min ago", s / 60);+ else std::snprintf(buf, sizeof buf, "%.1f h ago", s / 3600);+ return buf;+}++} // namespace++struct TimelapseJob {+ FILE* ffmpeg = nullptr;+ std::string path;+ int width = 1920, height = 1080, fps = 30;+ int frame = 0, frames = 0, hold0 = 0, hold1 = 0;+ size_t steps = 0, restore = 0;+ Camera camera;+ float yaw0 = 0.0f;+ std::vector<uint8_t> rgba;+ std::string error;+ bool cancelled = false;+};++struct TimelineUiState {+ bool loaded = false;+ bool visible = true; // the strip is open (else only its tab shows)+ bool record = true; // keep a timeline for the history+ bool saveHistory = false; // write <name>.sfhist with the project+ bool dragging = false;+ size_t pendingSeek = SIZE_MAX; // the scrubber's target, applied once a frame+ uint32_t retuneNode = Timeline::kNone;+ float retuneValue = 1.0f;+ std::string message;+ // Timelapse dialog+ bool timelapseDialog = false;+ int timelapseRes = 0; // 0 = 1080p, 1 = 4K+ float timelapseSeconds = 20.0f;+ char timelapsePath[1024] = "";+ std::unique_ptr<TimelapseJob> job;+};++namespace {++std::string prefsFile(const std::string& configDir) { return configDir.empty() ? std::string() : configDir + "timeline.json"; }++void loadPrefs(TimelineUiState& s, const std::string& configDir, bool deterministic) {+ s.loaded = true;+ if (deterministic) return;+ std::ifstream f(fsPathOf(prefsFile(configDir)));+ if (!f) return;+ std::stringstream ss;+ ss << f.rdbuf();+ Json j;+ std::string err;+ if (!Json::parse(ss.str(), j, err) || !j.isObject()) return;+ s.visible = j["visible"].asBool(s.visible);+ s.record = j["record"].asBool(s.record);+ s.saveHistory = j["save_history"].asBool(s.saveHistory);+}++void savePrefs(const TimelineUiState& s, const std::string& configDir, bool deterministic) {+ if (deterministic || configDir.empty()) return;+ Json j = Json::object();+ j.set("visible", s.visible);+ j.set("record", s.record);+ j.set("save_history", s.saveHistory);+ std::ofstream f(fsPathOf(prefsFile(configDir)));+ f << j.dump(true);+}++} // namespace++void App::registerTimelineUiActions() {+ auto add = [this](const char* id, const char* label, const char* icon, const char* palette, const char* description,+ std::function<void()> run, std::function<bool()> checked = nullptr) {+ Action a;+ a.id = id;+ a.label = label;+ a.icon = icon;+ a.palette = palette;+ a.description = description;+ a.run = std::move(run);+ a.checked = std::move(checked);+ actions_.add(std::move(a));+ };+ auto ui = [this]() -> TimelineUiState& {+ if (!timelineUi_) timelineUi_ = std::make_shared<TimelineUiState>();+ return *timelineUi_;+ };+ // Before a file named on the command line opens: open_project reads its history into this scene.+ Timeline::historyDocument = &doc_;+ if (!ui().loaded) {+ loadPrefs(ui(), configDir_, uiConfigDeterministic_);+ Timeline::saveWithProject = ui().saveHistory;+ }+ add("view.timeline", "Sculpt Timeline", ICON_LC_HISTORY, "Edit",+ "Show or hide the history strip along the bottom of the canvas: every stroke and operation as a tick. Drag "+ "to see the model at any point, click to go there; sculpting from an earlier point keeps the old "+ "continuation as a branch. Right-click a stroke to change its strength.",+ [this, ui] {+ ui().visible = !ui().visible;+ savePrefs(ui(), configDir_, uiConfigDeterministic_);+ },+ [ui] { return ui().visible; });+ add("timeline.timelapse", "Export timelapse...", ICON_LC_FILM, "Edit",+ "Render the history of the active SubTool as a turntable timelapse video (1080p or 4K MP4, no captions).",+ [ui] { ui().timelapseDialog = true; });+ add("help.benchmark", "Benchmark (proof mode)", ICON_LC_GAUGE, "Help",+ "Measure how responsive sculpting is on this computer: a scripted stroke on 5, 20 and 33 million triangle "+ "meshes (and 100 million when there is memory for it) through the same code a pen uses, with a live "+ "display of frame times and how far the stroke trails the pointer. Writes a video and a JSON result you can "+ "share. Replaces the scene.",+ [this] { startProofMode(); });+}++void App::startTimelapse(const std::string& path, int width, int height, float seconds, int fps) {+ if (!timelineUi_) timelineUi_ = std::make_shared<TimelineUiState>();+ TimelineUiState& s = *timelineUi_;+ Timeline* t = Timeline::of(doc_.undo);+ if (!t || t->cursor() == 0) {+ s.message = "There is no history to make a timelapse of (sculpt something first, or open a project saved with its history)";+ status_ = s.message;+ return;+ }+ t->sync(doc_);+ auto job = std::make_unique<TimelapseJob>();+ job->path = path;+ job->width = width & ~1;+ job->height = height & ~1;+ job->fps = std::max(fps, 1);+ job->frames = std::max(job->fps * 2, int(std::lround(seconds * float(job->fps))));+ job->hold0 = std::min(job->frames / 6, job->fps * 6 / 10);+ job->hold1 = std::min(job->frames / 4, job->fps * 3 / 2);+ job->steps = t->cursor(); // the history up to what the view shows now+ job->restore = t->cursor();+ job->camera = camera_;+ job->camera.frame(sceneBounds()); // framed on the finished model+ job->camera.pitch = camera_.pitch;+ job->camera.distance *= 0.72f; // frame() leaves room for any view direction; a turntable can come closer+ job->camera.aspect = float(job->width) / float(std::max(job->height, 1));+ job->yaw0 = camera_.yaw;+ const std::string cmd = "ffmpeg -loglevel error -y -f rawvideo -pix_fmt rgba -s " + std::to_string(job->width) + "x" ++ std::to_string(job->height) + " -r " + std::to_string(job->fps) ++ " -i - -c:v libx264 -preset medium -crf 18 -pix_fmt yuv420p -movflags +faststart \"" + path + "\"";+#if defined(_WIN32)+ job->ffmpeg = _popen(cmd.c_str(), "wb");+#else+ job->ffmpeg = popen(cmd.c_str(), "w");+#endif+ if (!job->ffmpeg) {+ status_ = s.message = "Timelapse needs ffmpeg (it couldn't be started)";+ return;+ }+ s.job = std::move(job);+ status_ = "Rendering the timelapse...";+}++bool App::timelapseStep(double budgetSeconds) {+ if (!timelineUi_ || !timelineUi_->job) return false;+ TimelapseJob& j = *timelineUi_->job;+ Timeline* t = Timeline::of(doc_.undo);+ const auto t0 = std::chrono::steady_clock::now();+ auto finish = [&](bool ok) {+ std::string err;+ if (t) t->seek(doc_, std::min(j.restore, t->path().size() - 1), &err); // back to where the user was+#if defined(_WIN32)+ const int status = _pclose(j.ffmpeg);+#else+ const int status = pclose(j.ffmpeg);+#endif+ if (j.cancelled) {+ std::error_code ec;+ std::filesystem::remove(fsPathOf(j.path), ec);+ status_ = "Timelapse cancelled";+ } else if (!ok || status != 0) {+ status_ = "The timelapse couldn't be written" + (j.error.empty() ? std::string() : ": " + j.error);+ } else {+ status_ = "Timelapse saved: " + j.path + " (" + std::to_string(j.frames) + " frames, " ++ std::to_string(j.frames / j.fps) + " s)";+ }+ timelineUi_->message = status_;+ lastCommandOk_ = ok && status == 0 && !j.cancelled;+ timelineUi_->job.reset();+ return false;+ };+ if (!t || j.cancelled) return finish(false);+ RenderSettings settings = renderSettings_;+ settings.dimInactive = false;+ settings.motionProxy = false;+ while (j.frame < j.frames) {+ // The history plays between the two holds; the camera turns once around the model over the whole video.+ const int sweep = std::max(1, j.frames - j.hold0 - j.hold1);+ const double u = std::clamp(double(j.frame - j.hold0) / double(sweep), 0.0, 1.0);+ const size_t step = std::min(j.steps, size_t(std::lround(u * double(j.steps))));+ std::string err;+ if (step != t->cursor() && !t->seek(doc_, step, &err)) {+ j.error = err;+ return finish(false);+ }+ Camera cam = j.camera;+ cam.yaw = j.yaw0 + 6.2831853f * float(j.frame) / float(j.frames);+ syncScene();+ if (!renderer_.renderToImage(cam, j.width, j.height, settings, j.rgba, err)) {+ j.error = err;+ return finish(false);+ }+ for (size_t i = 3; i < j.rgba.size(); i += 4) j.rgba[i] = 255;+ if (std::fwrite(j.rgba.data(), 1, j.rgba.size(), j.ffmpeg) != j.rgba.size()) {+ j.error = "ffmpeg stopped";+ return finish(false);+ }+ ++j.frame;+ if (budgetSeconds > 0 && std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count() > budgetSeconds)+ return true;+ }+ return finish(true);+}++int App::runTimelapseCli() {+ Timeline* t = Timeline::of(doc_.undo);+ if (!t) t = Timeline::attach(doc_).get();+ if (t->cursor() == 0 && t->path().size() > 1) t->seek(doc_, t->path().size() - 1);+ if (t->cursor() == 0) {+ std::fprintf(stderr, "No history to render: open a project saved with its history (<name>.sfhist beside it)\n");+ return 1;+ }+ std::printf("Timelapse: %zu steps, %dx%d, %.0f s\n", t->cursor(), options_.width, options_.height, double(options_.timelapseSeconds));+ std::fflush(stdout);+ startTimelapse(options_.timelapsePath, options_.width, options_.height, options_.timelapseSeconds, std::max(options_.fps, 1));+ if (!timelineUi_ || !timelineUi_->job) {+ std::fprintf(stderr, "%s\n", status_.c_str());+ return 1;+ }+ while (timelapseStep(0.0)) {+ }+ std::printf("%s\n", status_.c_str());+ return lastCommandOk_ ? 0 : 1;+}++void App::drawTimelineUi() {+ if (!timelineUi_) timelineUi_ = std::make_shared<TimelineUiState>();+ TimelineUiState& s = *timelineUi_;+ if (!s.loaded) {+ loadPrefs(s, configDir_, uiConfigDeterministic_);+ Timeline::saveWithProject = s.saveHistory;+ Timeline::historyDocument = &doc_;+ }+ if (proof_) drawProofUi();+ // Keep a timeline on the active SubTool's history (each SubTool's travels with its undo stack).+ Timeline* t = Timeline::of(doc_.undo);+ if (!t && s.record) t = Timeline::attach(doc_).get();+ if (!t) return;+ const bool stroking = doc_.sculptor.strokeActive() || drag_ == Drag::Stroke || !dabQueue_.empty();+ if (!stroking) t->sync(doc_);++ // A running timelapse: a few frames each app frame, under a modal with a progress bar.+ if (s.job) {+ ImGui::OpenPopup("Rendering timelapse");+ if (ImGui::BeginPopupModal("Rendering timelapse", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {+ ImGui::Text("%s", s.job->path.c_str());+ ImGui::ProgressBar(float(s.job->frame) / float(std::max(1, s.job->frames)), ImVec2(360 * uiScale_, 0));+ if (ImGui::Button("Cancel")) s.job->cancelled = true;+ ImGui::EndPopup();+ }+ activeUntil_ = std::max(activeUntil_, double(SDL_GetTicksNS()) * 1e-9 + 0.2);+ if (!timelapseStep(0.05)) t = Timeline::of(doc_.undo);+ if (!t) return;+ }+ if (s.timelapseDialog) {+ if (!s.timelapsePath[0]) {+ std::filesystem::path p;+ if (!doc_.path.empty()) p = fsPathOf(doc_.path).replace_extension().string() + "-timelapse.mp4";+ else if (const char* v = SDL_GetUserFolder(SDL_FOLDER_VIDEOS)) p = fsPathOf(v) / "sculptforge-timelapse.mp4";+ else p = "sculptforge-timelapse.mp4";+ std::snprintf(s.timelapsePath, sizeof s.timelapsePath, "%s", utf8Of(p).c_str());+ }+ ImGui::OpenPopup("Export timelapse");+ s.timelapseDialog = false;+ }+ if (ImGui::BeginPopupModal("Export timelapse", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {+ ImGui::TextWrapped("The history of the active SubTool (%zu steps up to the cursor) played as a turntable.", t->cursor());+ ImGui::RadioButton("1080p", &s.timelapseRes, 0);+ ImGui::SameLine();+ ImGui::RadioButton("4K", &s.timelapseRes, 1);+ ImGui::SetNextItemWidth(200 * uiScale_);+ ImGui::SliderFloat("Length", &s.timelapseSeconds, 5.0f, 90.0f, "%.0f s");+ ImGui::SetNextItemWidth(420 * uiScale_);+ ImGui::InputText("File", s.timelapsePath, sizeof s.timelapsePath);+ if (ImGui::Button("Export")) {+ const bool k4 = s.timelapseRes == 1;+ startTimelapse(s.timelapsePath, k4 ? 3840 : 1920, k4 ? 2160 : 1080, s.timelapseSeconds, 30);+ ImGui::CloseCurrentPopup();+ }+ ImGui::SameLine();+ if (ImGui::Button("Close")) ImGui::CloseCurrentPopup();+ ImGui::EndPopup();+ }++ // The strip: along the bottom of the canvas.+ const CanvasRect c = canvasRect();+ const float sc = uiScale_;+ if (c.w < 200 || c.h < 150 || hideUi_) return;+ const float margin = 10 * sc;+ if (!s.visible) {+ ImGui::SetNextWindowPos(ImVec2(c.x + c.w * 0.5f, c.y + c.h - 4 * sc), ImGuiCond_Always, ImVec2(0.5f, 1.0f));+ ImGui::SetNextWindowBgAlpha(0.85f);+ if (ImGui::Begin("##timeline_tab", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize |+ ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing |+ ImGuiWindowFlags_NoNav)) {+ const std::string label = std::string(ICON_LC_HISTORY " Timeline ") + std::to_string(t->cursor()) + "/" ++ std::to_string(t->path().size() - 1);+ if (ImGui::SmallButton(label.c_str())) {+ s.visible = true;+ savePrefs(s, configDir_, uiConfigDeterministic_);+ }+ ui::HelpText("Sculpt Timeline", nullptr, "Open the history strip.", "Edit");+ }+ ImGui::End();+ return;+ }+ const auto branches = t->branches();+ const int lanes = std::min<int>(3, int(branches.size()));+ const float laneH = 7 * sc, trackH = 26 * sc;+ const float height = 30 * sc + trackH + float(lanes) * (laneH + 3 * sc);+ ImGui::SetNextWindowPos(ImVec2(c.x + margin, c.y + c.h - margin - height), ImGuiCond_Always);+ ImGui::SetNextWindowSize(ImVec2(c.w - 2 * margin, height), ImGuiCond_Always);+ ImGui::SetNextWindowBgAlpha(0.88f);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8 * sc, 5 * sc));+ const bool open = ImGui::Begin("##timeline", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoSavedSettings |+ ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav |+ ImGuiWindowFlags_NoScrollWithMouse);+ ImGui::PopStyleVar();+ if (!open) {+ ImGui::End();+ return;+ }+ const auto& path = t->path();+ const size_t n = path.size();+ // Header row: what it is, where the cursor is, the controls.+ ImGui::AlignTextToFramePadding();+ ImGui::TextUnformatted(ICON_LC_HISTORY);+ ImGui::SameLine();+ ImGui::Text("Step %zu of %zu", t->cursor(), n - 1);+ if (!branches.empty()) {+ ImGui::SameLine();+ ImGui::TextDisabled("%s %zu branch%s", ICON_LC_GIT_BRANCH, branches.size(), branches.size() == 1 ? "" : "es");+ }+ if (const Timeline::Node& cur = t->node(t->cursorNode()); t->cursor() > 0) {+ ImGui::SameLine();+ ImGui::TextDisabled(" %s", cur.label.c_str());+ }+ if (!s.message.empty()) {+ ImGui::SameLine();+ ImGui::TextColored(theme::textDim, " %s", s.message.c_str());+ }+ const float buttons = 250 * sc;+ ImGui::SameLine(ImGui::GetWindowWidth() - buttons);+ if (ImGui::Checkbox("Save with project", &s.saveHistory)) {+ Timeline::saveWithProject = s.saveHistory;+ savePrefs(s, configDir_, uiConfigDeterministic_);+ }+ ui::HelpText("Save with project", nullptr,+ "Also save the history beside the project as <name>.sfhist (strokes, masks, polypaint, visibility; "+ "a topology change cuts it). Opening the project brings it back.",+ "Edit > Sculpt Timeline");+ ImGui::SameLine();+ if (ImGui::SmallButton(ICON_LC_FILM)) s.timelapseDialog = true;+ ui::HelpText("Export timelapse", nullptr, "Render this history as a turntable timelapse video.", "Edit > Sculpt Timeline");+ ImGui::SameLine();+ if (ImGui::SmallButton(ICON_LC_CHEVRON_DOWN)) {+ s.visible = false;+ savePrefs(s, configDir_, uiConfigDeterministic_);+ }+ ui::HelpText("Hide", nullptr, "Fold the timeline into a tab.", "Edit > Sculpt Timeline");++ // Branch lanes, then the track.+ ImDrawList* dl = ImGui::GetWindowDrawList();+ const ImVec2 origin = ImGui::GetCursorScreenPos();+ const float x0 = origin.x + 6 * sc, x1 = origin.x + ImGui::GetContentRegionAvail().x - 6 * sc;+ size_t span = n > 1 ? n - 1 : 1; // steps the track shows: the active branch, or a longer other branch+ for (const Timeline::Branch& b : branches) span = std::max(span, b.from + b.length);+ const float step = (x1 - x0) / float(span);+ auto xOf = [&](double i) { return x0 + float(i) * step; };+ const ImVec2 mouse = ImGui::GetIO().MousePos;+ float y = origin.y;+ uint32_t hovered = Timeline::kNone;+ for (int l = 0; l < lanes; ++l) {+ const Timeline::Branch& b = branches[branches.size() - 1 - size_t(l)]; // the newest on top+ const float ly = y + laneH * 0.5f;+ const float bx0 = xOf(double(b.from)), bx1 = std::min(x1, xOf(double(b.from + b.length)));+ dl->AddLine(ImVec2(bx0, y + laneH), ImVec2(bx0, ly), theme::u32(theme::textDim, 0.6f), 1.0f * sc);+ dl->AddLine(ImVec2(bx0, ly), ImVec2(bx1, ly), theme::u32(theme::textDim, 0.6f), 2.0f * sc);+ dl->AddCircleFilled(ImVec2(bx1, ly), 3.0f * sc, theme::u32(theme::textBright, 0.9f));+ ImGui::SetCursorScreenPos(ImVec2(bx0, y));+ ImGui::PushID(int(b.first));+ if (ImGui::InvisibleButton("##lane", ImVec2(std::max(8 * sc, bx1 - bx0 + 4 * sc), laneH))) {+ std::string e;+ if (!t->select(doc_, b.tip, &e)) s.message = e;+ else s.message = "Switched to the other branch (the one you left is a lane now)";+ }+ if (ImGui::IsItemHovered())+ ImGui::SetTooltip("Branch from step %zu: %zu step%s, ending with \"%s\"\nClick to make it the active branch", b.from,+ b.length, b.length == 1 ? "" : "s", t->node(b.tip).label.c_str());+ ImGui::PopID();+ y += laneH + 3 * sc;+ }+ if (branches.size() > size_t(lanes)) {+ dl->AddText(ImVec2(x1 - 30 * sc, origin.y), theme::u32(theme::textDim), ("+" + std::to_string(branches.size() - size_t(lanes))).c_str());+ }+ const float ty0 = y, ty1 = y + trackH;+ dl->AddRectFilled(ImVec2(x0 - 4 * sc, ty0), ImVec2(x1 + 4 * sc, ty1), theme::u32(theme::frame, 0.5f), 3 * sc);+ dl->AddRectFilled(ImVec2(x0 - 4 * sc, ty0), ImVec2(xOf(double(n - 1)) + 4 * sc, ty1), theme::u32(theme::frame), 3 * sc);+ // Ticks: one per step (several per pixel collapse into one line), dimmer after the cursor.+ const size_t cursor = s.dragging && s.pendingSeek != SIZE_MAX ? s.pendingSeek : t->cursor();+ const size_t every = step >= 1.0f || n < 2 ? 1 : size_t(std::ceil(1.0f / step));+ for (size_t i = 1; i < n; i += every) {+ const Timeline::Node& node = t->node(path[i]);+ const float x = xOf(double(i));+ const float h = node.kind == Timeline::Kind::Topology ? 1.0f : node.kind == Timeline::Kind::Stroke ? 0.62f : 0.45f;+ const float alpha = i <= cursor ? 1.0f : 0.35f;+ dl->AddLine(ImVec2(x, ty1 - 3 * sc), ImVec2(x, ty1 - 3 * sc - (trackH - 6 * sc) * h), kindColor(node.kind, alpha),+ std::clamp(step * 0.6f, 1.0f, 3.0f * sc));+ if (node.strength != 1.0f) dl->AddCircleFilled(ImVec2(x, ty0 + 3 * sc), 2.0f * sc, theme::u32(theme::accent, alpha));+ if (path[i] == s.retuneNode) dl->AddRect(ImVec2(x - 3 * sc, ty0 + 1), ImVec2(x + 3 * sc, ty1 - 1), theme::u32(theme::textBright), 2 * sc);+ if (t->hasCheckpoint(path[i])) dl->AddLine(ImVec2(x, ty1 - 2 * sc), ImVec2(x, ty1), theme::u32(theme::textDim, 0.7f), 1.0f);+ }+ // The scrubber.+ const float cx = xOf(double(cursor));+ dl->AddLine(ImVec2(cx, ty0 - 2 * sc), ImVec2(cx, ty1 + 2 * sc), theme::u32(theme::accent), 2.0f * sc);+ dl->AddTriangleFilled(ImVec2(cx - 5 * sc, ty0 - 3 * sc), ImVec2(cx + 5 * sc, ty0 - 3 * sc), ImVec2(cx, ty0 + 3 * sc), theme::u32(theme::accent));+ ImGui::SetCursorScreenPos(ImVec2(x0 - 4 * sc, ty0));+ ImGui::InvisibleButton("##track", ImVec2(std::max(8 * sc, xOf(double(n - 1)) - x0 + 8 * sc), trackH),+ ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight);+ const bool trackHovered = ImGui::IsItemHovered();+ auto indexAt = [&](float mx) { return n > 1 ? size_t(std::clamp(std::lround((mx - x0) / std::max(step, 1e-6f)), 0L, long(n - 1))) : size_t(0); };+ if (trackHovered || ImGui::IsItemActive()) hovered = path[indexAt(mouse.x)];+ if (ImGui::IsItemActive() && ImGui::IsMouseDown(ImGuiMouseButton_Left)) {+ s.dragging = true;+ s.pendingSeek = indexAt(mouse.x);+ }+ if (s.dragging && !ImGui::IsMouseDown(ImGuiMouseButton_Left)) s.dragging = false;+ if (ImGui::IsItemClicked(ImGuiMouseButton_Right) && hovered != Timeline::kNone) {+ s.retuneNode = hovered;+ s.retuneValue = t->node(hovered).strength;+ ImGui::OpenPopup("##retune");+ }+ if (trackHovered && hovered != Timeline::kNone && !ImGui::IsPopupOpen("##retune")) {+ const Timeline::Node& node = t->node(hovered);+ const int d = t->depth(hovered);+ if (node.parent == Timeline::kNone) ImGui::SetTooltip("Start of the history");+ else+ ImGui::SetTooltip("Step %d: %s (%s)\n%u %s, %s%s\nClick or drag to show the model here; right-click to re-tune", d,+ node.label.c_str(), kindLabel(node.kind), node.touched,+ node.kind == Timeline::Kind::Visibility ? "triangles" : "vertices", ago(node.time).c_str(),+ node.strength != 1.0f ? ("\nStrength " + std::to_string(int(std::lround(node.strength * 100))) + "%").c_str() : "");+ }+ // Apply the scrubber's target once a frame (coalesced while dragging).+ if (s.pendingSeek != SIZE_MAX && s.pendingSeek != t->cursor() && !stroking) {+ std::string e;+ if (!t->seek(doc_, s.pendingSeek, &e)) s.message = e;+ else s.message.clear();+ doc_.modified = true;+ updateTitle();+ }+ if (!s.dragging) s.pendingSeek = SIZE_MAX;+ // Re-tune pop-up.+ if (ImGui::BeginPopup("##retune")) {+ const uint32_t id = s.retuneNode;+ if (id < t->nodeCount() && t->node(id).alive) {+ const Timeline::Node& node = t->node(id);+ ImGui::Text("Step %d: %s", t->depth(id), node.label.c_str());+ std::string why;+ if (t->canRetune(id, &why)) {+ ImGui::SetNextItemWidth(220 * sc);+ if (ImGui::SliderFloat("Strength", &s.retuneValue, 0.0f, 2.0f, "%.2f")) {+ std::string e;+ if (!t->retune(doc_, id, s.retuneValue, &e)) s.message = e;+ doc_.modified = true;+ }+ ui::HelpText("Strength", nullptr,+ "How strongly this stroke shows: 1 = as sculpted, 0 = gone, 2 = twice as strong. Later strokes "+ "are not redone: where they overlap this one they keep their own displacement on top.",+ "Edit > Sculpt Timeline");+ if (ImGui::SmallButton("Reset to 1")) {+ s.retuneValue = 1.0f;+ t->retune(doc_, id, 1.0f);+ }+ ImGui::SameLine();+ } else {+ ImGui::TextDisabled("%s", why.c_str());+ }+ if (ImGui::SmallButton("Show the model here")) {+ std::string e;+ if (!t->select(doc_, id, &e)) s.message = e;+ ImGui::CloseCurrentPopup();+ }+ ImGui::TextDisabled("Sculpting from an earlier step starts a branch;\nthe later steps stay as a lane above.");+ }+ ImGui::EndPopup();+ } else if (s.retuneNode != Timeline::kNone && !ImGui::IsPopupOpen("##retune")) {+ s.retuneNode = Timeline::kNone;+ }+ ImGui::End();+}++} // namespace sfdiff --git a/src/app/ProofMode.cpp b/src/app/ProofMode.cppnew file mode 100644index 00000000..d0dbadc0--- /dev/null+++ b/src/app/ProofMode.cpp@@ -0,0 +1,867 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Proof mode (Help > Benchmark, sculptforge --benchmark; docs/benchmark.md).+//+// For each mesh size it builds a sphere with subdivision levels the way a sculptor gets one, then, in the+// app's own interactive loop, plays a scripted pen stroke into the same handlers mouse and pen events call+// (App::onMouseDown / onMouseMove / onMouseUp: the dab queue, the time budget, the renderer, all as when you+// sculpt), at 240 pointer samples a second, with a normal and a large brush, and turns the view. Every frame it+// records the frame time and how far the stroke on screen trails the pointer: in pixels along the path, and+// in milliseconds from the pointer sample the newest drawn dab belongs to until the frame showing it is handed+// to the display (SwapWindow; the display's own scan-out and the compositor come on top). A HUD shows the+// numbers live; the frames go, HUD included, to an MP4 (read back through pixel buffers, encoded by ffmpeg on+// its own thread), and a JSON result with the hardware and version is written at the end.+#include "app/ProofMode.h"++#include "app/App.h"+#include "app/Theme.h"++#include "core/Benchmark.h"+#include "core/Primitives.h"+#include "core/Timeline.h"++#include "render/GL.h"++#include <algorithm>+#include <chrono>+#include <cmath>+#include <condition_variable>+#include <cstdio>+#include <cstring>+#include <ctime>+#include <deque>+#include <filesystem>+#include <fstream>+#include <mutex>+#include <sstream>+#include <thread>++#if defined(_WIN32)+#include <windows.h>+#elif defined(__APPLE__)+#include <sys/sysctl.h>+#include <sys/utsname.h>+#include <mach/mach.h>+#else+#include <sys/utsname.h>+#include <unistd.h>+#endif++#ifndef SF_GIT_COMMIT+#define SF_GIT_COMMIT "unknown"+#endif++namespace sf {++// ---------------------------------------------------------------------------------------------------------------+// Sizes and hardware++std::vector<ProofMeshSize>& proofExtraSizes() {+ static std::vector<ProofMeshSize> extra;+ return extra;+}++std::vector<ProofMeshSize> proofDefaultSizes(size_t available) {+ std::vector<ProofMeshSize> sizes{{5, "5M", nullptr, 150}, {20, "20M", nullptr, 150}, {33, "33M", nullptr, 150}};+ auto fits = [&](const ProofMeshSize& s) {+ return available > 0 && s.millions * 1e6 * s.bytesPerTriangle * 1.25 < double(available);+ };+ if (ProofMeshSize big{100, "100M", nullptr, 150}; fits(big)) sizes.push_back(big);+ for (const ProofMeshSize& s : proofExtraSizes())+ if (fits(s)) sizes.push_back(s);+ return sizes;+}++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{};+ m.dwLength = sizeof m;+ return GlobalMemoryStatusEx(&m) ? size_t(m.ullTotalPhys) : 0;+#elif defined(__APPLE__)+ uint64_t bytes = 0;+ size_t len = sizeof bytes;+ return sysctlbyname("hw.memsize", &bytes, &len, nullptr, 0) == 0 ? size_t(bytes) : 0;+#else+ const long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGE_SIZE);+ return pages > 0 && page > 0 ? size_t(pages) * size_t(page) : 0;+#endif+}++namespace {++std::string trim(std::string s) {+ while (!s.empty() && (s.back() == '\n' || s.back() == ' ' || s.back() == '\0' || s.back() == '\r')) s.pop_back();+ size_t i = 0;+ while (i < s.size() && (s[i] == ' ' || s[i] == '\t')) ++i;+ return s.substr(i);+}++std::string cpuModel() {+#if defined(_WIN32)+ char buf[256] = {};+ DWORD size = sizeof buf;+ if (RegGetValueA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", "ProcessorNameString",+ RRF_RT_REG_SZ, nullptr, buf, &size) == ERROR_SUCCESS)+ return trim(buf);+ return "unknown";+#elif defined(__APPLE__)+ char buf[256] = {};+ size_t len = sizeof buf;+ if (sysctlbyname("machdep.cpu.brand_string", buf, &len, nullptr, 0) == 0) return trim(buf);+ return "unknown";+#else+ std::ifstream f("/proc/cpuinfo");+ for (std::string line; std::getline(f, line);) {+ if (line.rfind("model name", 0) == 0 || line.rfind("Hardware", 0) == 0) {+ const size_t colon = line.find(':');+ if (colon != std::string::npos) return trim(line.substr(colon + 1));+ }+ }+ // ARM boards (Apple silicon under Asahi, Raspberry Pi...): the device tree names the machine.+ std::ifstream dt("/proc/device-tree/model");+ std::string model((std::istreambuf_iterator<char>(dt)), std::istreambuf_iterator<char>());+ return model.empty() ? "unknown" : trim(model);+#endif+}++std::string osName() {+#if defined(_WIN32)+ return "Windows";+#else+ utsname u{};+ if (uname(&u) != 0) return "unknown";+ std::string s = std::string(u.sysname) + " " + u.release + " " + u.machine;+#if !defined(__APPLE__)+ std::ifstream f("/etc/os-release");+ for (std::string line; std::getline(f, line);)+ if (line.rfind("PRETTY_NAME=", 0) == 0) {+ std::string v = line.substr(12);+ v.erase(std::remove(v.begin(), v.end(), '"'), v.end());+ s = v + " (" + s + ")";+ }+#endif+ return s;+#endif+}++} // namespace++Json describeHardware() {+ Json h = Json::object();+ h.set("cpu", cpuModel());+ h.set("logical_cores", int(std::thread::hardware_concurrency()));+ h.set("ram_gb", std::round(double(totalMemoryBytes()) / double(1u << 30) * 10.0) / 10.0);+ h.set("os", osName());+ return h;+}++// ---------------------------------------------------------------------------------------------------------------+// The run++namespace {++using Clock = std::chrono::steady_clock;+double nowSeconds() { return std::chrono::duration<double>(Clock::now().time_since_epoch()).count(); }++constexpr GLenum kPixelPackBuffer = 0x88EB, kStreamRead = 0x88E1, kMapReadBit = 0x0001;+constexpr double kPointerHz = 240.0;+constexpr int kVideoFps = 30;++struct Percentiles {+ double p50 = 0, p95 = 0, p99 = 0, max = 0, mean = 0;+};+Percentiles percentiles(std::vector<double> v) {+ Percentiles p;+ if (v.empty()) return p;+ std::sort(v.begin(), v.end());+ auto at = [&](double q) { return v[std::min(v.size() - 1, size_t(q * double(v.size())))]; };+ p.p50 = at(0.5), p.p95 = at(0.95), p.p99 = at(0.99), p.max = v.back();+ for (double x : v) p.mean += x;+ p.mean /= double(v.size());+ return p;+}+Json percentilesJson(const Percentiles& p) {+ Json j = Json::object();+ auto r = [](double x) { return std::round(x * 100.0) / 100.0; };+ j.set("p50", r(p.p50));+ j.set("p95", r(p.p95));+ j.set("p99", r(p.p99));+ j.set("max", r(p.max));+ j.set("mean", r(p.mean));+ return j;+}++// Frames to ffmpeg on a thread of its own, at a constant rate (frames repeat while the app is slower).+class VideoWriter {+public:+ bool start(const std::string& path, int w, int h) {+ w_ = w, h_ = h;+ // Bottom-up rows from glReadPixels: flipped; scaled to at most 1920 wide to keep the encoder light.+ const std::string cmd = "ffmpeg -loglevel error -y -f rawvideo -pix_fmt rgba -s " + std::to_string(w) + "x" ++ std::to_string(h) + " -r " + std::to_string(kVideoFps) ++ " -i - -vf \"vflip,scale='min(1920,iw)':-2\" -c:v libx264 -preset veryfast -crf 20 "+ "-pix_fmt yuv420p -movflags +faststart \"" + path + "\"";+#if defined(_WIN32)+ ff_ = _popen(cmd.c_str(), "wb");+#else+ ff_ = popen(cmd.c_str(), "w");+#endif+ if (!ff_) return false;+ thread_ = std::thread([this] { loop(); });+ return true;+ }+ // Takes the frame shown at `t` (seconds); drops it when the encoder is behind.+ void push(double t, std::vector<uint8_t>&& rgba) {+ std::lock_guard<std::mutex> lock(m_);+ if (queue_.size() >= 4) return;+ queue_.push_back({t, std::move(rgba)});+ cv_.notify_one();+ }+ bool finish() {+ if (!ff_) return false;+ {+ std::lock_guard<std::mutex> lock(m_);+ stop_ = true;+ cv_.notify_one();+ }+ thread_.join();+#if defined(_WIN32)+ const int status = _pclose(ff_);+#else+ const int status = pclose(ff_);+#endif+ ff_ = nullptr;+ return status == 0 && written_ > 0;+ }+ int width() const { return w_; }+ int height() const { return h_; }+ bool running() const { return ff_ != nullptr; }+ ~VideoWriter() {+ if (ff_) finish();+ }++private:+ void loop() {+ std::vector<uint8_t> last;+ double next = -1.0;+ for (;;) {+ std::pair<double, std::vector<uint8_t>> f;+ {+ std::unique_lock<std::mutex> lock(m_);+ cv_.wait(lock, [&] { return stop_ || !queue_.empty(); });+ if (queue_.empty()) break;+ f = std::move(queue_.front());+ queue_.pop_front();+ }+ if (next < 0) next = f.first;+ // Slots up to this frame's time show the previous frame; then this one.+ while (!last.empty() && next + 1.0 / kVideoFps <= f.first) {+ std::fwrite(last.data(), 1, last.size(), ff_);+ ++written_;+ next += 1.0 / kVideoFps;+ }+ if (next <= f.first + 1e-9 || last.empty()) {+ std::fwrite(f.second.data(), 1, f.second.size(), ff_);+ ++written_;+ next += 1.0 / kVideoFps;+ }+ last = std::move(f.second);+ }+ }+ FILE* ff_ = nullptr;+ int w_ = 0, h_ = 0;+ std::thread thread_;+ std::mutex m_;+ std::condition_variable cv_;+ std::deque<std::pair<double, std::vector<uint8_t>>> queue_;+ bool stop_ = false;+ long written_ = 0;+};++struct PhaseSpec {+ const char* name;+ float radiusPx; // 0 = an orbit, no stroke+ double seconds;+};++struct PhaseResult {+ std::string name;+ float radiusPx = 0;+ double seconds = 0, pathPx = 0;+ size_t dabs = 0, samples = 0;+ std::vector<double> frameMs, lagMs, lagPx;+};++struct SizeResult {+ std::string label;+ size_t triangles = 0, vertices = 0;+ double buildSeconds = 0;+ size_t ramBytes = 0, peakRamBytes = 0;+ std::vector<PhaseResult> phases;+};++} // namespace++struct ProofState {+ enum class Stage { Intro, Announce, Build, Settle, Phase, Finish, Results };+ Stage stage = Stage::Intro;+ bool cli = false, video = true, vsync = false;+ double strokeSeconds = 6.0;+ std::string jsonPath, videoPath;+ std::vector<ProofMeshSize> sizes;+ size_t sizeIndex = 0, phaseIndex = 0;+ std::vector<PhaseSpec> phases;+ std::vector<SizeResult> results;+ double stageStart = 0, lastFrame = 0, lastSample = 0;+ // The stroke+ float cx = 0, cy = 0, R = 0;+ struct Sample {+ double t;+ glm::vec2 p;+ double s; // path length so far+ };+ std::vector<Sample> samples;+ std::vector<glm::vec2> dabs;+ size_t sent = 1; // samples handed to onMouseMove (the first went to onMouseDown)+ bool pressed = false;+ // Live HUD values+ std::string hudTitle, hudLine2, hudLine3;+ std::string error;+ // Video+ VideoWriter writer;+ GLuint pbo[3] = {0, 0, 0};+ double pboTime[3] = {0, 0, 0};+ int pboW = 0, pboH = 0, pboNext = 0, pboFilled = 0;+ Json hardware;+ std::string gpu;+ bool written = false;+ // The scene before, restored by the results window's Close.+ float radiusBefore = 60, strengthBefore = 0.5f;+ BrushType brushBefore = BrushType::Standard;+};++namespace {++glm::vec2 strokePoint(const ProofState& p, double u) {+ // A figure eight across the front of the model, three times round.+ const double phi = 2.0 * 3.14159265358979 * 3.0 * u;+ return {p.cx + p.R * 1.25f * float(std::sin(phi)), p.cy + p.R * 0.75f * float(std::sin(2.0 * phi))};+}++std::string isoDate() {+ const std::time_t t = std::time(nullptr);+ char buf[32];+ std::strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%SZ", std::gmtime(&t));+ return buf;+}++std::string fileStamp() {+ const std::time_t t = std::time(nullptr);+ char buf[32];+ std::strftime(buf, sizeof buf, "%Y%m%d-%H%M%S", std::localtime(&t));+ return buf;+}++std::vector<ProofMeshSize> parseSizes(const std::string& list) {+ std::vector<ProofMeshSize> out;+ std::stringstream ss(list);+ for (std::string item; std::getline(ss, item, ',');) {+ const double m = std::atof(item.c_str());+ if (m <= 0) continue;+ char label[32];+ std::snprintf(label, sizeof label, "%gM", m);+ out.push_back({m, label, nullptr, 150});+ }+ return out;+}++} // namespace++void App::startProofMode() {+ if (proof_ && proof_->stage != ProofState::Stage::Results && proof_->stage != ProofState::Stage::Intro) return;+ auto p = std::make_shared<ProofState>();+ p->cli = options_.benchmark;+ p->video = !options_.benchmarkNoVideo;+ p->vsync = options_.benchmarkVsync;+ p->strokeSeconds = std::max(1.0f, options_.benchmarkStrokeSeconds);+ p->sizes = options_.benchmarkSizes.empty() ? proofDefaultSizes(availableMemoryBytes()) : parseSizes(options_.benchmarkSizes);+ if (p->sizes.empty()) p->sizes = proofDefaultSizes(availableMemoryBytes());+ const std::string stamp = fileStamp();+ std::filesystem::path dir = std::filesystem::current_path();+ if (!p->cli && !configDir_.empty()) dir = std::filesystem::path(std::u8string(configDir_.begin(), configDir_.end())) / "benchmarks";+ std::error_code ec;+ std::filesystem::create_directories(dir, ec);+ auto u8 = [](const std::filesystem::path& x) {+ const auto s = x.u8string();+ return std::string(s.begin(), s.end());+ };+ p->jsonPath = !options_.benchmarkOut.empty() ? options_.benchmarkOut : u8(dir / ("sculptforge-benchmark-" + stamp + ".json"));+ p->videoPath = !options_.benchmarkVideo.empty() ? options_.benchmarkVideo : u8(dir / ("sculptforge-benchmark-" + stamp + ".mp4"));+ p->phases = {{"stroke", 60.0f, p->strokeSeconds}, {"large brush stroke", 240.0f, p->strokeSeconds}, {"orbit", 0.0f, 3.0}};+ p->stage = p->cli ? ProofState::Stage::Announce : ProofState::Stage::Intro;+ p->radiusBefore = radiusPx_;+ p->strengthBefore = strength_;+ p->brushBefore = brush_;+ proof_ = p;+}++void App::drawProofUi() {+ ProofState& p = *proof_;+ const float sc = uiScale_;+ if (p.stage == ProofState::Stage::Intro) {+ ImGui::OpenPopup("Benchmark (proof mode)");+ if (ImGui::BeginPopupModal("Benchmark (proof mode)", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {+ ImGui::PushTextWrapPos(520 * sc);+ ImGui::TextWrapped("Proof mode measures how responsive sculpting is on this computer. For each mesh size it "+ "builds a sphere with subdivision levels, then plays a scripted pen stroke through the "+ "same code your pen goes through (240 samples a second), with a normal and a large brush, "+ "and turns the view.");+ ImGui::Spacing();+ std::string sizes;+ for (const auto& s : p.sizes) sizes += (sizes.empty() ? "" : ", ") + s.label;+ ImGui::Text("Meshes: %s triangles", sizes.c_str());+ ImGui::TextDisabled("(100M runs when free memory allows: %.1f GB free now)", double(availableMemoryBytes()) / double(1u << 30));+ 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 "+ "of the run:");+ ImGui::TextDisabled("%s", p.jsonPath.c_str());+ ImGui::Checkbox("Record a video of the run (needs ffmpeg)", &p.video);+ ImGui::Checkbox("Keep vertical sync on (frame rate capped at the display's)", &p.vsync);+ ImGui::Spacing();+ ImGui::TextColored(theme::accent, "The current scene is replaced. Save your work first.");+ ImGui::TextDisabled("Press Esc to stop the run.");+ ImGui::PopTextWrapPos();+ if (ImGui::Button("Start")) {+ p.stage = ProofState::Stage::Announce;+ ImGui::CloseCurrentPopup();+ }+ ImGui::SameLine();+ if (ImGui::Button("Cancel")) {+ ImGui::CloseCurrentPopup();+ proof_.reset();+ }+ ImGui::EndPopup();+ }+ return;+ }+ if (p.stage == ProofState::Stage::Results) {+ ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));+ bool open = true;+ if (ImGui::Begin("Benchmark results", &open, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse)) {+ if (!p.error.empty()) ImGui::TextColored(theme::danger, "%s", p.error.c_str());+ if (ImGui::BeginTable("##proof", 7, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg)) {+ for (const char* h : {"Mesh", "Phase", "fps", "frame p50", "frame p95", "frame p99", "trails pointer p50 / p95"})+ ImGui::TableSetupColumn(h);+ ImGui::TableHeadersRow();+ for (const SizeResult& r : p.results)+ for (const PhaseResult& ph : r.phases) {+ const Percentiles f = percentiles(ph.frameMs), l = percentiles(ph.lagMs), lp = percentiles(ph.lagPx);+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::Text("%s", r.label.c_str());+ ImGui::TableNextColumn();+ ImGui::Text("%s", ph.name.c_str());+ ImGui::TableNextColumn();+ ImGui::Text("%.0f", ph.seconds > 0 ? double(ph.frameMs.size()) / ph.seconds : 0.0);+ ImGui::TableNextColumn();+ ImGui::Text("%.1f ms", f.p50);+ ImGui::TableNextColumn();+ ImGui::Text("%.1f ms", f.p95);+ ImGui::TableNextColumn();+ ImGui::Text("%.1f ms", f.p99);+ ImGui::TableNextColumn();+ if (ph.lagMs.empty()) ImGui::TextDisabled("-");+ else ImGui::Text("%.0f / %.0f ms, %.0f / %.0f px", l.p50, l.p95, lp.p50, lp.p95);+ }+ ImGui::EndTable();+ }+ ImGui::TextDisabled("Result: %s", p.jsonPath.c_str());+ if (p.video) ImGui::TextDisabled("Video: %s", p.videoPath.c_str());+ if (ImGui::Button("Open folder")) {+ const std::string dir = std::filesystem::path(p.jsonPath).parent_path().string();+ SDL_OpenURL(("file://" + dir).c_str());+ }+ ImGui::SameLine();+ if (ImGui::Button("How to share results")) SDL_OpenURL("https://sculptforge.app/benchmarks/");+ ImGui::SameLine();+ if (ImGui::Button("Close")) open = false;+ }+ ImGui::End();+ if (!open) {+ radiusPx_ = p.radiusBefore;+ strength_ = p.strengthBefore;+ brush_ = p.brushBefore;+ proof_.reset();+ }+ return;+ }+ // The HUD, top left of the canvas (burned into the video: it is part of the frame).+ const CanvasRect c = canvasRect();+ ImDrawList* dl = ImGui::GetForegroundDrawList();+ ImFont* font = ImGui::GetFont();+ const float big = ImGui::GetFontSize() * 1.35f, small = ImGui::GetFontSize() * 1.05f;+ const ImVec2 at(c.x + 14 * sc, c.y + 14 * sc);+ const std::string brand = std::string("SculptForge ") + SCULPTFORGE_VERSION + " (" + SF_GIT_COMMIT + ") - proof mode";+ const char* lines[] = {brand.c_str(), p.hudTitle.c_str(), p.hudLine2.c_str(), p.hudLine3.c_str()};+ float w = 0, h = 0;+ for (int i = 0; i < 4; ++i) {+ const ImVec2 s = font->CalcTextSizeA(i == 1 ? big : small, 1e9f, 0.0f, lines[i]);+ w = std::max(w, s.x);+ h += s.y + 3 * sc;+ }+ dl->AddRectFilled(ImVec2(at.x - 10 * sc, at.y - 8 * sc), ImVec2(at.x + w + 10 * sc, at.y + h + 6 * sc), IM_COL32(12, 12, 14, 215), 6 * sc);+ float y = at.y;+ for (int i = 0; i < 4; ++i) {+ const float size = i == 1 ? big : small;+ dl->AddText(font, size, ImVec2(at.x, y), i == 0 ? theme::u32(theme::textDim) : i == 1 ? theme::u32(theme::textBright) : theme::u32(theme::text), lines[i]);+ y += font->CalcTextSizeA(size, 1e9f, 0.0f, lines[i]).y + 3 * sc;+ }+ if (p.pressed && !p.samples.empty()) { // where the pointer is: a small cross the stroke follows+ const glm::vec2 q = p.samples.back().p;+ dl->AddLine(ImVec2(q.x - 7 * sc, q.y), ImVec2(q.x + 7 * sc, q.y), theme::u32(theme::accent), 2 * sc);+ dl->AddLine(ImVec2(q.x, q.y - 7 * sc), ImVec2(q.x, q.y + 7 * sc), theme::u32(theme::accent), 2 * sc);+ }+}++void App::proofBeforeSwap(int fbW, int fbH) {+ ProofState& p = *proof_;+ using Stage = ProofState::Stage;+ if (p.stage == Stage::Intro || p.stage == Stage::Results) return;+ const double now = nowSeconds();+ activeUntil_ = std::max(activeUntil_, double(SDL_GetTicksNS()) * 1e-9 + 0.5); // keep the loop drawing+ // Esc stops the run (the real pointer is kept out of the scripted stroke, the keyboard is not).+ if (const bool* keys = SDL_GetKeyboardState(nullptr); keys && keys[SDL_SCANCODE_ESCAPE] && p.stage != Stage::Finish) {+ p.error = "Stopped with Esc: the results are partial";+ if (p.pressed) onMouseUp();+ p.pressed = false;+ strokeProbe_ = nullptr;+ p.stage = Stage::Finish;+ }++ // The frame about to be shown: into the video (asynchronously, through a ring of pixel buffers).+ if (p.video && p.stage != Stage::Announce && p.stage != Stage::Build) {+ const int w = fbW & ~1, h = fbH & ~1;+ if (!p.writer.running() && p.error.find("video") == std::string::npos) {+ if (p.writer.start(p.videoPath, w, h)) {+ p.pboW = w, p.pboH = h;+ gl::GenBuffers(3, p.pbo);+ for (GLuint b : p.pbo) {+ gl::BindBuffer(kPixelPackBuffer, b);+ gl::BufferData(kPixelPackBuffer, GLsizeiptr(size_t(w) * size_t(h) * 4), nullptr, kStreamRead);+ }+ gl::BindBuffer(kPixelPackBuffer, 0);+ } else {+ p.error = "The video couldn't be recorded (ffmpeg missing?)";+ p.video = false;+ }+ }+ if (p.writer.running() && w == p.pboW && h == p.pboH) {+ const int slot = p.pboNext;+ if (p.pboFilled >= 3) { // the oldest read is done by now: hand it to the encoder+ gl::BindBuffer(kPixelPackBuffer, p.pbo[slot]);+ if (const void* data = gl::MapBufferRange(kPixelPackBuffer, 0, GLsizeiptr(size_t(w) * size_t(h) * 4), kMapReadBit)) {+ std::vector<uint8_t> rgba(size_t(w) * size_t(h) * 4);+ std::memcpy(rgba.data(), data, rgba.size());+ gl::UnmapBuffer(kPixelPackBuffer);+ p.writer.push(p.pboTime[slot], std::move(rgba));+ }+ }+ gl::BindFramebuffer(GL_READ_FRAMEBUFFER, 0);+ gl::BindBuffer(kPixelPackBuffer, p.pbo[slot]);+ gl::PixelStorei(GL_PACK_ALIGNMENT, 1);+ gl::ReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);+ gl::BindBuffer(kPixelPackBuffer, 0);+ p.pboTime[slot] = now;+ p.pboNext = (slot + 1) % 3;+ p.pboFilled = std::min(p.pboFilled + 1, 3);+ }+ }++ const double frameMs = (now - p.lastFrame) * 1000.0;+ p.lastFrame = now;+ const CanvasRect c = canvasRect();+ auto beginPhase = [&] {+ const PhaseSpec& spec = p.phases[p.phaseIndex];+ SizeResult& r = p.results.back();+ r.phases.push_back({});+ r.phases.back().name = spec.name;+ r.phases.back().radiusPx = spec.radiusPx;+ p.stageStart = now;+ p.samples.clear();+ p.dabs.clear();+ p.sent = 1;+ if (spec.radiusPx > 0) {+ brush_ = BrushType::Standard;+ doc_.activeBrush = -1;+ paintMode_ = false;+ radiusPx_ = spec.radiusPx;+ strength_ = 0.35f;+ p.cx = c.x + c.w * 0.5f;+ p.cy = c.y + c.h * 0.5f;+ p.R = 0.26f * std::min(c.w, c.h);+ const glm::vec2 q = strokePoint(p, 0.0);+ p.samples.push_back({now, q, 0.0});+ p.lastSample = now;+ strokeProbe_ = &p.dabs;+ onMouseDown(q.x, q.y, SDL_BUTTON_LEFT);+ p.pressed = drag_ == Drag::Stroke;+ if (!p.pressed) {+ strokeProbe_ = nullptr;+ p.error = "No stroke began on the " + r.label + " mesh (nothing under the pointer)";+ }+ }+ p.stage = Stage::Phase;+ };+ auto nextPhase = [&] {+ SizeResult& r = p.results.back();+ r.phases.back().seconds = now - p.stageStart;+ ++p.phaseIndex;+ if (p.phaseIndex < p.phases.size()) {+ beginPhase();+ return;+ }+ r.ramBytes = residentBytes();+ r.peakRamBytes = peakResidentBytes();+ ++p.sizeIndex;+ p.stage = p.sizeIndex < p.sizes.size() ? Stage::Announce : Stage::Finish;+ };++ switch (p.stage) {+ case Stage::Announce: { // show "Building ..." for one frame, then build+ if (p.sizeIndex == 0 && p.results.empty()) {+ if (lightbox_.open()) lightbox_.toggle(); // the canvas clear (it opens at start-up)+ if (!p.vsync) SDL_GL_SetSwapInterval(0);+ p.gpu = std::string(reinterpret_cast<const char*>(gl::GetString(GL_RENDERER))) + ", OpenGL " ++ reinterpret_cast<const char*>(gl::GetString(GL_VERSION));+ p.hardware = describeHardware();+ p.hardware.set("gpu", p.gpu);+ int ww = 0, wh = 0;+ SDL_GetWindowSize(window_, &ww, &wh);+ Json win = Json::array();+ win.push(fbW);+ win.push(fbH);+ p.hardware.set("framebuffer", win);+ p.hardware.set("ui_scale", double(uiScale_));+ }+ const ProofMeshSize& s = p.sizes[p.sizeIndex];+ p.hudTitle = "Building a " + s.label + " triangle mesh...";+ p.hudLine2 = "mesh " + std::to_string(p.sizeIndex + 1) + " of " + std::to_string(p.sizes.size());+ p.hudLine3 = p.gpu.empty() ? std::string() : p.gpu;+ p.stage = Stage::Build;+ break;+ }+ case Stage::Build: {+ const ProofMeshSize& s = p.sizes[p.sizeIndex];+ doc_.setMesh(makeIcosphere(1)); // free the last mesh (and its history) first+ resetPeakResidentBytes();+ const double t0 = nowSeconds();+ const size_t tris = size_t(s.millions * 1e6);+ Mesh m = s.build ? s.build(tris) : makeBenchSphere(tris);+ SizeResult r;+ r.label = s.label;+ r.triangles = m.triangleCount();+ r.vertices = m.vertexCount();+ doc_.setMesh(std::move(m), "Benchmark");+ r.buildSeconds = nowSeconds() - t0;+ p.results.push_back(r);+ camera_.frame(sceneBounds());+ camera_.yaw = 0.0f;+ camera_.pitch = 0.0f;+ p.stageStart = nowSeconds();+ p.phaseIndex = 0;+ p.stage = Stage::Settle;+ char buf[160];+ std::snprintf(buf, sizeof buf, "%s triangles (%.1fM vertices), built in %.1f s", r.label.c_str(), double(r.vertices) / 1e6, r.buildSeconds);+ p.hudTitle = buf;+ p.hudLine2 = "settling (the first upload to the GPU)";+ break;+ }+ case Stage::Settle:+ if (now - p.stageStart > 1.0 && !backgroundBusy()) beginPhase();+ break;+ case Stage::Phase: {+ const PhaseSpec& spec = p.phases[p.phaseIndex];+ PhaseResult& ph = p.results.back().phases.back();+ if (ph.frameMs.size() < 1000000 && now - p.stageStart > 0.0) ph.frameMs.push_back(frameMs);+ const double u = std::min(1.0, (now - p.stageStart) / spec.seconds);+ if (spec.radiusPx <= 0) { // orbit: the view turns, as a drag would+ camera_.yaw = float(6.2831853 * u);+ perf_.framesStill = 0;+ } else if (p.pressed) {+ // The pointer samples since the last frame (240 a second), in the order a tablet sends them.+ while (p.lastSample + 1.0 / kPointerHz <= now) {+ p.lastSample += 1.0 / kPointerHz;+ const double su = std::min(1.0, (p.lastSample - p.stageStart) / spec.seconds);+ const glm::vec2 q = strokePoint(p, su);+ p.samples.push_back({p.lastSample, q, p.samples.back().s + double(glm::length(q - p.samples.back().p))});+ ++ph.samples;+ }+ // How far the stroke on screen (the newest dab in this frame) trails the pointer (the newest sample).+ if (!p.dabs.empty()) {+ const glm::vec2 d = p.dabs.back();+ size_t best = p.samples.size() - 1;+ float bestDist = 1e30f;+ for (size_t i = p.samples.size(); i-- > 0 && p.samples.size() - i < 2000;) {+ const float dist = glm::length(p.samples[i].p - d);+ if (dist < bestDist) bestDist = dist, best = i;+ }+ ph.lagMs.push_back((now - p.samples[best].t) * 1000.0);+ ph.lagPx.push_back(p.samples.back().s - p.samples[best].s);+ }+ // ... then the new samples go to the input handler, as the next frame's events would.+ for (; p.sent < p.samples.size(); ++p.sent)+ onMouseMove(p.samples[p.sent].p.x, p.samples[p.sent].p.y, 0.0f, 0.0f, false);+ if (u >= 1.0) {+ onMouseUp(); // places the dabs still waiting, ends the stroke (undo step, timeline)+ p.pressed = false;+ strokeProbe_ = nullptr;+ ph.dabs = p.dabs.size();+ ph.pathPx = p.samples.back().s;+ nextPhase();+ break;+ }+ } else {+ nextPhase(); // a stroke that couldn't begin+ break;+ }+ if (u >= 1.0 && spec.radiusPx <= 0) {+ nextPhase();+ break;+ }+ // Live numbers over the last second.+ std::vector<double> recentF, recentL, recentP;+ double span = 0;+ for (size_t i = ph.frameMs.size(); i-- > 0 && span < 1000.0;) {+ span += ph.frameMs[i];+ recentF.push_back(ph.frameMs[i]);+ }+ for (size_t i = ph.lagMs.size(); i-- > 0 && recentL.size() < recentF.size();) {+ recentL.push_back(ph.lagMs[i]);+ recentP.push_back(ph.lagPx[i]);+ }+ const Percentiles f = percentiles(recentF), l = percentiles(recentL), lp = percentiles(recentP);+ const SizeResult& r = p.results.back();+ char buf[256];+ std::snprintf(buf, sizeof buf, "%s triangles - %s%s", r.label.c_str(), spec.name,+ spec.radiusPx > 0 ? (" (" + std::to_string(int(spec.radiusPx)) + " px brush)").c_str() : "");+ p.hudTitle = buf;+ std::snprintf(buf, sizeof buf, "%.0f fps frame %.1f / %.1f / %.1f ms (p50 / p95 / p99)", span > 0 ? 1000.0 * double(recentF.size()) / span : 0.0,+ f.p50, f.p95, f.p99);+ p.hudLine2 = buf;+ if (spec.radiusPx > 0)+ std::snprintf(buf, sizeof buf, "stroke trails pointer %.0f ms / %.0f px (p95 %.0f ms) RAM %.1f GB %s", l.p50, lp.p50, l.p95,+ double(residentBytes()) / double(1u << 30), p.vsync ? "vsync on" : "vsync off");+ else+ std::snprintf(buf, sizeof buf, "orbiting RAM %.1f GB %s", double(residentBytes()) / double(1u << 30), p.vsync ? "vsync on" : "vsync off");+ p.hudLine3 = buf;+ break;+ }+ case Stage::Finish: {+ if (!p.vsync) SDL_GL_SetSwapInterval(1);+ if (p.writer.running()) {+ if (!p.writer.finish()) p.error += (p.error.empty() ? "" : "; ") + std::string("the video couldn't be written");+ gl::DeleteBuffers(3, p.pbo);+ }+ Json root = Json::object();+ root.set("schema", "sculptforge-benchmark/1");+ Json app = Json::object();+ app.set("version", SCULPTFORGE_VERSION);+ app.set("commit", SF_GIT_COMMIT);+ root.set("sculptforge", app);+ root.set("date", isoDate());+ root.set("hardware", p.hardware);+ Json settings = Json::object();+ settings.set("vsync", p.vsync);+ settings.set("video", p.video);+ settings.set("pointer_hz", kPointerHz);+ settings.set("stroke_seconds", p.strokeSeconds);+ 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();+ for (const SizeResult& r : p.results) {+ Json run = Json::object();+ run.set("label", r.label);+ run.set("triangles", double(r.triangles));+ run.set("vertices", double(r.vertices));+ run.set("build_seconds", std::round(r.buildSeconds * 100) / 100);+ run.set("ram_mb", double(r.ramBytes >> 20));+ run.set("peak_ram_mb", double(r.peakRamBytes >> 20));+ Json phases = Json::array();+ for (const PhaseResult& ph : r.phases) {+ Json j = Json::object();+ j.set("name", ph.name);+ if (ph.radiusPx > 0) j.set("brush_radius_px", double(ph.radiusPx));+ j.set("seconds", std::round(ph.seconds * 100) / 100);+ j.set("frames", double(ph.frameMs.size()));+ j.set("fps", ph.seconds > 0 ? std::round(double(ph.frameMs.size()) / ph.seconds * 10) / 10 : 0.0);+ j.set("frame_ms", percentilesJson(percentiles(ph.frameMs)));+ if (ph.radiusPx > 0) {+ j.set("lag_ms", percentilesJson(percentiles(ph.lagMs)));+ j.set("lag_px", percentilesJson(percentiles(ph.lagPx)));+ j.set("dabs", double(ph.dabs));+ j.set("pointer_samples", double(ph.samples));+ j.set("path_px", std::round(ph.pathPx));+ j.set("pointer_speed_px_s", ph.seconds > 0 ? std::round(ph.pathPx / ph.seconds) : 0.0);+ }+ phases.push(j);+ }+ run.set("phases", phases);+ runs.push(run);+ }+ root.set("runs", runs);+ if (p.video) root.set("video", std::filesystem::path(p.videoPath).filename().string());+ if (!p.error.empty()) root.set("notes", p.error);+ {+ std::ofstream f(std::filesystem::path(std::u8string(p.jsonPath.begin(), p.jsonPath.end())));+ f << root.dump(true) << "\n";+ if (!f) p.error += (p.error.empty() ? "" : "; ") + ("couldn't write " + p.jsonPath);+ }+ // A summary on the terminal too.+ std::printf("SculptForge %s (%s) proof mode on %s | %s\n", SCULPTFORGE_VERSION, SF_GIT_COMMIT,+ root["hardware"]["cpu"].asString().c_str(), p.gpu.c_str());+ for (const SizeResult& r : p.results)+ for (const PhaseResult& ph : r.phases) {+ const Percentiles f = percentiles(ph.frameMs), l = percentiles(ph.lagMs), lp = percentiles(ph.lagPx);+ std::printf(" %-5s %-19s %6.1f fps frame p50 %5.1f p95 %5.1f p99 %5.1f ms", r.label.c_str(), ph.name.c_str(),+ ph.seconds > 0 ? double(ph.frameMs.size()) / ph.seconds : 0.0, f.p50, f.p95, f.p99);+ if (ph.radiusPx > 0) std::printf(" trails %4.0f ms / %4.0f px (p95 %4.0f ms / %4.0f px)", l.p50, lp.p50, l.p95, lp.p95);+ std::printf("\n");+ }+ std::printf("Result: %s%s%s\n", p.jsonPath.c_str(), p.video ? "\nVideo: " : "", p.video ? p.videoPath.c_str() : "");+ if (!p.error.empty()) std::printf("Note: %s\n", p.error.c_str());+ std::fflush(stdout);+ p.stage = Stage::Results;+ if (p.cli) running_ = false;+ status_ = "Benchmark finished: " + p.jsonPath;+ break;+ }+ default:+ break;+ }+}++} // namespace sfdiff --git a/src/app/ProofMode.h b/src/app/ProofMode.hnew file mode 100644index 00000000..e32efdc0--- /dev/null+++ b/src/app/ProofMode.h@@ -0,0 +1,38 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Proof mode (Help > Benchmark, sculptforge --benchmark; docs/benchmark.md): the meshes it sculpts on, and the+// hardware description written into its JSON result.+#pragma once++#include "core/Json.h"+#include "core/Mesh.h"++#include <functional>+#include <string>+#include <vector>++namespace sf {++// One mesh size proof mode can run on.+struct ProofMeshSize {+ double millions = 0; // triangles, in millions+ std::string label; // "33M", "300M micro-displaced"+ // Builds the mesh (about millions * 1e6 triangles; null = core's benchmark sphere, with subdivision levels).+ std::function<Mesh(size_t triangles)> build;+ double bytesPerTriangle = 150; // memory the run needs per triangle (mesh, BVH, levels, GPU buffers, history)+};++// The default sizes: 5M, 20M and 33M always; 100M when the free memory holds it with room to spare.+std::vector<ProofMeshSize> proofDefaultSizes(size_t availableBytes);+// Sizes added by other features (e.g. a 300M micro-displaced mesh): appended to the defaults when memory allows.+// Register at start-up: proofExtraSizes().push_back({300, "300M micro-displaced", builder, bytes});+std::vector<ProofMeshSize>& proofExtraSizes();++// Memory the system can still hand out (Linux MemAvailable, macOS / Windows free + reclaimable); 0 = unknown.+size_t availableMemoryBytes();+size_t totalMemoryBytes();+// CPU model, logical cores, RAM, OS: the "hardware" object of the result (the GPU is added by the app).+Json describeHardware();++} // namespace sfdiff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex 41adc74d..2441138c 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -165,6 +165,7 @@#include "core/Multires.h"#include "core/Script.h"#include "core/ThreadPool.h"+#include "core/Timeline.h"#include "link/HttpServer.h"#include <imgui_internal.h>@@ -455,6 +456,13 @@ double Demo::query(const std::string& name, bool& known) const {const int k = name.back() == 'x' ? 0 : name.back() == 'y' ? 1 : 2;return name[0] == 'c' ? b.center()[k] : b.extent()[k];}+ if (name == "timeline_steps" || name == "timeline_cursor" || name == "timeline_branches") { // (core/Timeline.h)+ Timeline* t = Timeline::of(app_.doc_.undo);+ if (!t) return 0.0;+ return name == "timeline_steps" ? double(t->path().size() - 1)+ : name == "timeline_cursor" ? double(t->cursor())+ : double(t->branches().size());+ }if (name == "can_undo") return app_.doc_.undo.canUndo() ? 1.0 : 0.0;if (name == "dirty") return app_.doc_.dirty() ? 1.0 : 0.0;if (name == "splats") return double(app_.doc_.splats.size());diff --git a/src/app/main.cpp b/src/app/main.cppindex 654bc888..c6c296a7 100644--- a/src/app/main.cpp+++ b/src/app/main.cpp@@ -52,6 +52,17 @@ void usage() {" --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"+ " --timelapse out.mp4 Render the opened project's history (saved beside it as .sfhist) as a\n"+ " turntable timelapse and exit (--size 3840x2160 for 4K, --fps N)\n"+ " --timelapse-seconds S Length of the timelapse (default 20)\n"+ " --benchmark Proof mode: a scripted stroke on 5M / 20M / 33M (and 100M when memory\n"+ " allows) triangle meshes through the input handlers, with a live HUD; writes a\n"+ " JSON result and an MP4 of the run and exits (docs/benchmark.md)\n"+ " --benchmark-sizes 5,20 Proof mode mesh sizes in millions of triangles\n"+ " --benchmark-out FILE Where the JSON result goes (default: sculptforge-benchmark-<time>.json here)\n"+ " --benchmark-video FILE Where the MP4 goes; --benchmark-no-video records none\n"+ " --benchmark-vsync Keep vertical sync on (default off: frame times are not capped)\n"+ " --benchmark-seconds S Length of each scripted stroke (default 6)\n"" --log-dir DIR Write sculptforge.log to DIR instead of the user data folder\n"" --crash-test KIND Crash on purpose (segv, abort or throw) to test the crash note in the log");}@@ -133,6 +144,15 @@ int main(int argc, char** argv) {if (const size_t comma = v.find(','); comma != std::string::npos)options.measureStrokeRadius = float(std::atof(v.c_str() + comma + 1));}+ else if (a == "--timelapse") options.timelapsePath = next();+ else if (a == "--timelapse-seconds") options.timelapseSeconds = std::max(2.0f, float(std::atof(next().c_str())));+ else if (a == "--benchmark") options.benchmark = true;+ else if (a == "--benchmark-sizes") options.benchmarkSizes = next();+ else if (a == "--benchmark-out") options.benchmarkOut = next();+ else if (a == "--benchmark-video") options.benchmarkVideo = next();+ else if (a == "--benchmark-no-video") options.benchmarkNoVideo = true;+ else if (a == "--benchmark-vsync") options.benchmarkVsync = true;+ else if (a == "--benchmark-seconds") options.benchmarkStrokeSeconds = std::max(1.0f, float(std::atof(next().c_str())));else if (a == "-h" || a == "--help") {usage();return 0;@@ -148,6 +168,9 @@ int main(int argc, char** argv) {if (!sizeGiven) options.width = 1600, options.height = 960;isolateSettings();}+ if (options.benchmark && !sizeGiven) options.width = 1920, options.height = 1080;+ if (options.benchmark || !options.timelapsePath.empty()) isolateSettings(); // the user's settings and files untouched+ if (!options.timelapsePath.empty() && !sizeGiven) options.width = 1920, options.height = 1080;if (options.measureIdle > 0.0f || options.measureStroke > 0.0f) isolateSettings(); // a fresh start, no restore prompt, the user's files untouchedif (!options.recordPath.empty() && options.supersample > 1) { // the app renders large; the video keeps --sizeoptions.width *= options.supersample;diff --git a/src/core/Project.cpp b/src/core/Project.cppindex 630eaefa..2506a4ef 100644--- a/src/core/Project.cpp+++ b/src/core/Project.cpp@@ -1049,7 +1049,8 @@ bool loadProjectThumbnail(const std::string& path, Image& out, std::string& erroCommandResult openProjectCommand(Document& doc, const std::string& path) {std::string err;if (!loadProject(path, doc, err)) return {false, err};- const int histories = loadHistorySidecar(doc, path); // the Sculpt Timeline saved beside it, if it matches+ // The Sculpt Timeline saved beside it, if it matches (only into the app's own scene: not thumbnails, scratch opens).+ const int histories = &doc == Timeline::historyDocument ? loadHistorySidecar(doc, path) : 0;std::string msg = "Opened project " + path + " (";if (doc.subtoolCount() > 1) msg += std::to_string(doc.subtoolCount()) + " SubTools, ";size_t tris = 0, layers = 0;@@ -1083,7 +1084,7 @@ void registerProjectCommands(CommandRegistry& registry) {doc.path = path;doc.markClean();// The Sculpt Timeline's history beside it (<name>.sfhist), when the app asks for it.- if (Timeline::saveWithProject && !saveHistorySidecar(doc, path, &err))+ if (Timeline::saveWithProject && &doc == Timeline::historyDocument && !saveHistorySidecar(doc, path, &err))return {true, "Saved project " + path + " (the history wasn't saved: " + err + ")"};return {true, "Saved project " + path};}});diff --git a/src/core/Timeline.h b/src/core/Timeline.hindex b87dc3d0..7e9411ac 100644--- a/src/core/Timeline.h+++ b/src/core/Timeline.h@@ -112,6 +112,9 @@ public:// --- settings and statistics// save_project also writes <name>.sfhist (the app's Preferences; off for the CLI and scripts).inline static bool saveWithProject = false;+ // The document open_project / save_project read and write the sidecar for (the app's scene; null = none),+ // so opening a project for a thumbnail or a scratch scene never reads a history.+ inline static const Document* historyDocument = nullptr;size_t checkpointEvery = 16; // a checkpoint every this many path steps (doubles when over budget)size_t checkpointBudget = size_t(1) << 30; // bytes of checkpointssize_t branchBudget = size_t(3) << 29; // 1.5 GiB of inactive branches and `other` copiesdiff --git a/tests/ui/timeline.sfui b/tests/ui/timeline.sfuinew file mode 100644index 00000000..359c5d2a--- /dev/null+++ b/tests/ui/timeline.sfui@@ -0,0 +1,35 @@+# Sculpt Timeline (PanelTimeline.cpp, core/Timeline.h): the strip records every stroke, the scrubber travels in the+# history, sculpting from an earlier point keeps the old continuation as a branch.+run new_sphere subdivisions=5+expect_value timeline_steps == 0+stroke 0.35 0.40 0.60 0.45+stroke 0.40 0.55 0.62 0.60+stroke 0.30 0.30 0.50 0.35+stroke 0.55 0.35 0.65 0.55+expect_value timeline_steps == 4+expect_value timeline_cursor == 4+shot strokes++# Drag the scrubber to the start of the track, then back to the middle.+view_drag 0.60 0.887 0.075 0.887+expect_value timeline_cursor == 0+view_drag 0.09 0.887 0.40 0.887+expect_value timeline_cursor < 4+expect_value timeline_cursor > 0+shot scrubbed++# Sculpting from here starts a branch: the later strokes stay as a lane above the track.+run timeline_seek index=2+stroke 0.30 0.60 0.55 0.70+expect_value timeline_steps == 3+expect_value timeline_branches == 1+shot branch++# The other branch comes back through the command (the strip's lane does the same).+run timeline_info list=true+run timeline_select node=4+expect_value timeline_steps == 4+expect_value timeline_branches == 1+# Re-tune the first stroke: half as strong.+run timeline_retune node=1 strength=0.5+expect_status "re-tuned"