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
Hardware profile and frame governor (core): system probe, profile mapping from measurements, cache, JSON schema, commands
islandmed89dd4e562ece
diff --git a/CMakeLists.txt b/CMakeLists.txtindex ff6dc1f0..dcc2ed8c 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -32,6 +32,8 @@ add_library(sculptforge_core STATICsrc/core/ThreadPool.cppsrc/core/UploadOrder.cppsrc/core/Benchmark.cpp+ src/core/HardwareProfile.cpp+ src/core/FrameGovernor.cppsrc/core/Sculpt.cppsrc/core/Dyntopo.cppsrc/core/DyntopoCommands.cppdiff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex 8e42df63..2b7a65ae 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -11,6 +11,7 @@#include "core/EnginePresets.h"#include "core/ExtractMirror.h"#include "core/Face.h"+#include "core/HardwareProfile.h"#include "core/ImageTo3D.h"#include "core/Masking.h"#include "core/Multires.h"@@ -774,6 +775,7 @@ CommandRegistry::CommandRegistry() {registerTransformCommands(*this); // transform (core/MeshTransform.h)registerExtractMirrorCommands(*this); // extract, mirror_and_weld, mirror (core/ExtractMirror.h)registerPerformanceCommands(*this); // perf_info, set_multithreading (core/Benchmark.cpp)+ registerHardwareProfileCommands(*this); // performance_profile, calibrate, set_performance_override (core/HardwareProfile.cpp)registerPaintCommands(*this); // core/Polypaint.cppregisterGozCommands(*this); // goz_import/export/send/receive, export_stl (io/GozCommands.cpp)registerBlenderCommands(*this); // blender_send/receive (io/BlenderCommands.cpp)diff --git a/src/core/FrameGovernor.cpp b/src/core/FrameGovernor.cppnew file mode 100644index 00000000..4cb4758a--- /dev/null+++ b/src/core/FrameGovernor.cpp@@ -0,0 +1,114 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/FrameGovernor.h"++#include <algorithm>+#include <cmath>++namespace sf {++namespace {+template <class T>+T medianOf(std::vector<T> v) {+ if (v.empty()) return T{};+ const size_t mid = v.size() / 2;+ std::nth_element(v.begin(), v.begin() + std::ptrdiff_t(mid), v.end());+ return v[mid];+}+} // namespace++void FrameGovernor::reset(const GovernorConfig& config, uint64_t budget) {+ config_ = config;+ if (config_.window < 1) config_.window = 1;+ budget_ = std::clamp(budget ? budget : config_.minBudget, config_.minBudget, std::max(config_.minBudget, config_.maxBudget));+ costs_.clear();+ drawn_.clear();+ scene_.clear();+ limitedFrames_ = 0;+ settle_ = 0;+ lastCost_ = 0.0;+ lastDrawn_ = 0;+ lastAction_ = Action::Hold;+ adjustments_ = decisions_ = 0;+}++void FrameGovernor::setTargetFps(int fps) {+ fps = std::clamp(fps, 15, 360);+ if (fps == config_.targetFps) return;+ config_.targetFps = fps;+ costs_.clear(); // measured against the old target+ drawn_.clear();+ scene_.clear();+ limitedFrames_ = 0;+}++uint64_t FrameGovernor::proxyThreshold() const { return std::max(budget_, config_.minProxyThreshold); }++bool FrameGovernor::addFrame(const FrameSample& f) {+ if (config_.movingOnly && !f.moving) return false;+ const double cost = std::max(f.cpuMs, f.gpuMs);+ if (!(cost > 0.0) || cost > config_.maxFrameMs) return false;+ if (settle_ > 0) {+ --settle_;+ return false;+ }+ costs_.push_back(cost);+ drawn_.push_back(f.drawnTriangles);+ scene_.push_back(f.sceneTriangles);+ if (f.limited) ++limitedFrames_;+ if (int(costs_.size()) < config_.window) return false;+ const uint64_t before = budget_;+ decide();+ costs_.clear();+ drawn_.clear();+ scene_.clear();+ limitedFrames_ = 0;+ if (budget_ != before) {+ settle_ = config_.settleFrames;+ ++adjustments_;+ return true;+ }+ return false;+}++void FrameGovernor::decide() {+ ++decisions_;+ const double T = targetMs();+ const double C = medianOf(costs_);+ const uint64_t D = medianOf(drawn_);+ const uint64_t S = medianOf(scene_);+ const bool limited = limitedFrames_ * 2 > int(costs_.size());+ lastCost_ = C;+ lastDrawn_ = D;+ lastAction_ = Action::Hold;+ const uint64_t lo = config_.minBudget, hi = std::max(config_.minBudget, config_.maxBudget);+ const double aim = T * config_.aimFraction;+ if (C > T * config_.highFraction) {+ // Too slow: draw less. From what was actually drawn when the scene is smaller than the budget (a budget far+ // above the scene would take several steps to have any effect).+ const double factor = std::clamp(aim / C, config_.maxStepDown, 0.9);+ const uint64_t base = D > 0 ? std::min(budget_, D) : budget_;+ const uint64_t next = std::clamp(uint64_t(double(base) * factor), lo, hi);+ if (next < budget_) {+ budget_ = next;+ lastAction_ = Action::Lowered;+ }+ } else if (C < T * config_.lowFraction) {+ // Room to spare: draw more, but only where the budget is what holds the view back.+ if (!limited && !(D > 0 && double(D) >= 0.9 * double(budget_))) return;+ const double factor = std::clamp(aim / C, 1.05, config_.maxStepUp);+ uint64_t next = std::clamp(uint64_t(double(budget_) * factor), lo, hi);+ if (limited && S > 0 && next >= S) {+ // Past the scene's size the view draws everything: predict that frame (cost grows with what's drawn)+ // and only go there if it stays well inside the target; else stay just under the scene.+ const double predicted = D > 0 ? C * double(S) / double(D) : 1e9;+ if (predicted > T * config_.highFraction * 0.9) next = std::max(budget_, S > 1 ? S - 1 : S);+ }+ if (next > budget_) {+ budget_ = next;+ lastAction_ = Action::Raised;+ }+ }+}++} // namespace sfdiff --git a/src/core/FrameGovernor.h b/src/core/FrameGovernor.hnew file mode 100644index 00000000..82474117--- /dev/null+++ b/src/core/FrameGovernor.h@@ -0,0 +1,86 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Adaptive frame governor: holds the 3D view at its target frame rate (60 fps, or 120 on a 120 Hz display) by+// adjusting how much the view draws, never what the scene holds. It reads measured frame times (CPU, and GPU+// through timer queries where the driver has them) and the triangles each frame drew, and moves the render+// triangle budget and the motion proxy threshold (core/HardwareProfile.h) with hysteresis:+//+// - decisions are made on the median of a window of frames (one slow frame changes nothing);+// - a dead band: frames between `lowFraction` and `highFraction` of the target frame time keep the budget;+// - after a change, `settleFrames` frames are ignored while the new budget takes effect;+// - raising the budget past the scene's size (which would switch the motion proxy off) needs a predicted frame+// time well inside the target, so the view doesn't flip between the proxy and full detail.+//+// Only frames where the view moves count by default (still frames draw everything in full: the governor+// can't help them, and the motion proxy is what it controls in today's renderer). Micromesh will read the+// budget every frame (renderTriangleBudget()) for its continuous level of detail; see docs/performance.md.+#pragma once++#include <cstdint>+#include <vector>++namespace sf {++struct FrameSample {+ double cpuMs = 0.0; // CPU time of the frame's work (input to swap, without waiting for vsync)+ double gpuMs = -1.0; // GPU time of the 3D view (timer query); < 0 = unknown+ uint64_t drawnTriangles = 0; // what the frame drew after culling and the proxy+ uint64_t sceneTriangles = 0; // the visible scene in full detail (0 = unknown)+ bool moving = true; // the view moved (orbit, pan, zoom, SpaceMouse...)+ bool limited = false; // the frame drew less than full detail because of the budget (the proxy)+};++struct GovernorConfig {+ int targetFps = 60;+ double lowFraction = 0.6; // below this share of the frame time: room to draw more+ double highFraction = 1.0; // above: draw less+ double aimFraction = 0.8; // where an adjustment aims+ int window = 20; // frames per decision (their median)+ int settleFrames = 5; // frames ignored after a change+ double maxStepDown = 0.5; // the most one decision may cut the budget (factor)+ double maxStepUp = 1.25; // the most one decision may raise it+ double maxFrameMs = 250.0; // longer frames are hitches (loading, a dialog), not drawing: ignored+ uint64_t minBudget = 250'000, maxBudget = 2'000'000'000;+ uint64_t minProxyThreshold = 262'144; // the renderer draws smaller meshes in full anyway+ bool movingOnly = true;+};++class FrameGovernor {+public:+ enum class Action { Hold, Lowered, Raised };++ FrameGovernor() = default;+ explicit FrameGovernor(const GovernorConfig& config, uint64_t budget = 0) { reset(config, budget); }++ void reset(const GovernorConfig& config, uint64_t budget);+ void setTargetFps(int fps);+ // Feeds one frame; returns true when the budgets changed (read budget() / proxyThreshold()).+ bool addFrame(const FrameSample& frame);++ uint64_t budget() const { return budget_; }+ uint64_t proxyThreshold() const;+ double targetMs() const { return 1000.0 / double(config_.targetFps > 0 ? config_.targetFps : 60); }+ const GovernorConfig& config() const { return config_; }+ // The last decision's window: median frame cost (max of CPU and GPU) and median drawn triangles.+ double lastCostMs() const { return lastCost_; }+ uint64_t lastDrawn() const { return lastDrawn_; }+ Action lastAction() const { return lastAction_; }+ int adjustments() const { return adjustments_; }+ int decisions() const { return decisions_; }++private:+ void decide();+ GovernorConfig config_;+ uint64_t budget_ = 0;+ std::vector<double> costs_;+ std::vector<uint64_t> drawn_, scene_;+ int limitedFrames_ = 0;+ int settle_ = 0;+ double lastCost_ = 0.0;+ uint64_t lastDrawn_ = 0;+ Action lastAction_ = Action::Hold;+ int adjustments_ = 0, decisions_ = 0;+};++} // namespace sfdiff --git a/src/core/HardwareProfile.cpp b/src/core/HardwareProfile.cppnew file mode 100644index 00000000..8cc2b0de--- /dev/null+++ b/src/core/HardwareProfile.cpp@@ -0,0 +1,1044 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/HardwareProfile.h"++#include "core/Benchmark.h"+#include "core/BrushLibrary.h"+#include "core/Commands.h"+#include "core/Document.h"+#include "core/Sculpt.h"++#include <algorithm>+#include <atomic>+#include <chrono>+#include <cmath>+#include <cstdio>+#include <cstring>+#include <filesystem>+#include <fstream>+#include <mutex>+#include <sstream>+#include <thread>++#if defined(_WIN32)+#define WIN32_LEAN_AND_MEAN+#include <windows.h>+#else+#include <sys/utsname.h>+#include <unistd.h>+#endif+#if defined(__APPLE__)+#include <sys/sysctl.h>+#endif+#if defined(__linux__) && (defined(__aarch64__) || defined(__arm__))+#include <sys/auxv.h>+#endif+#if defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || defined(_M_IX86)+#define SF_X86 1+#if defined(_MSC_VER)+#include <intrin.h>+#else+#include <cpuid.h>+#endif+#endif++#ifndef SCULPTFORGE_VERSION+#define SCULPTFORGE_VERSION "dev"+#endif++namespace sf {++namespace {++using Clock = std::chrono::steady_clock;+double msSince(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); }++std::string lower(std::string s) {+ std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); });+ return s;+}+bool has(const std::string& haystack, const char* needle) { return haystack.find(needle) != std::string::npos; }++std::string trim(std::string s) {+ while (!s.empty() && std::isspace(static_cast<unsigned char>(s.back()))) s.pop_back();+ size_t i = 0;+ while (i < s.size() && std::isspace(static_cast<unsigned char>(s[i]))) ++i;+ return s.substr(i);+}++std::string readFile(const std::string& path) {+ std::ifstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);+ if (!f) return {};+ std::stringstream ss;+ ss << f.rdbuf();+ return ss.str();+}++double median(std::vector<double> v) {+ if (v.empty()) return 0.0;+ std::sort(v.begin(), v.end());+ const size_t n = v.size();+ return n % 2 ? v[n / 2] : 0.5 * (v[n / 2 - 1] + v[n / 2]);+}++constexpr uint64_t kM = 1'000'000;++uint64_t roundDownTo(uint64_t v, uint64_t step) { return step ? v / step * step : v; }++} // namespace++// ---------------------------------------------------------------------------+// Names+// ---------------------------------------------------------------------------++const char* gpuKindName(GpuKind kind) {+ switch (kind) {+ case GpuKind::Discrete: return "discrete";+ case GpuKind::Integrated: return "integrated";+ case GpuKind::Unified: return "unified";+ case GpuKind::Software: return "software";+ case GpuKind::Unknown: break;+ }+ return "unknown";+}++GpuKind gpuKindFromName(const std::string& name) {+ for (GpuKind k : {GpuKind::Discrete, GpuKind::Integrated, GpuKind::Unified, GpuKind::Software})+ if (name == gpuKindName(k)) return k;+ return GpuKind::Unknown;+}++const char* tierName(ProfileTier tier) {+ switch (tier) {+ case ProfileTier::Software: return "Software";+ case ProfileTier::Laptop: return "Laptop";+ case ProfileTier::Workstation: return "Workstation";+ case ProfileTier::Monster: return "Monster";+ }+ return "Laptop";+}++bool tierFromName(const std::string& name, ProfileTier& out) {+ const std::string n = lower(name);+ for (ProfileTier t : {ProfileTier::Software, ProfileTier::Laptop, ProfileTier::Workstation, ProfileTier::Monster})+ if (n == lower(tierName(t))) {+ out = t;+ return true;+ }+ if (n == "llvmpipe" || n == "safe") {+ out = ProfileTier::Software;+ return true;+ }+ return false;+}++std::string formatTriangles(uint64_t t) {+ char buf[32];+ if (t >= 1'000'000'000) std::snprintf(buf, sizeof buf, "%.2fB", double(t) / 1e9);+ else if (t >= kM) std::snprintf(buf, sizeof buf, "%.1fM", double(t) / 1e6);+ else std::snprintf(buf, sizeof buf, "%.0fk", double(t) / 1e3);+ return buf;+}++std::string formatMegabytes(uint64_t mb) {+ char buf[32];+ if (mb >= 1024) std::snprintf(buf, sizeof buf, "%.1f GB", double(mb) / 1024.0);+ else std::snprintf(buf, sizeof buf, "%llu MB", static_cast<unsigned long long>(mb));+ return buf;+}++// ---------------------------------------------------------------------------+// Probes+// ---------------------------------------------------------------------------++GpuKind classifyGpu(const std::string& vendorIn, const std::string& rendererIn) {+ const std::string v = lower(vendorIn), r = lower(rendererIn);+ if (r.empty() && v.empty()) return GpuKind::Unknown;+ for (const char* s : {"llvmpipe", "softpipe", "swiftshader", "software rasterizer", "gdi generic",+ "microsoft basic render", "apple software renderer", "swrast", "lavapipe"})+ if (has(r, s)) return GpuKind::Software;+ // Apple GPUs share the system memory: macOS ("Apple M1 Pro") and Asahi Linux ("Apple M1 Pro (G13S C0)", "AGX").+ if (has(r, "apple m") || has(r, "apple a") || has(r, "agx") || (has(v, "apple") && !has(r, "radeon") && !has(r, "intel")))+ return GpuKind::Unified;+ if (has(v, "nvidia") || has(r, "geforce") || has(r, "quadro") || has(r, "rtx") || has(r, "tesla")) {+ if (has(r, "tegra") || has(r, "orin") || has(r, "xavier")) return GpuKind::Unified; // Jetson boards+ return GpuKind::Discrete;+ }+ if (has(v, "intel") || has(r, "intel")) {+ // Arc A / B series cards are discrete; "Intel(R) Arc(TM) Graphics" without a model is Meteor Lake's iGPU.+ if (has(r, "arc") && (has(r, "arc(tm) a") || has(r, "arc a") || has(r, "arc(tm) b") || has(r, "arc b") ||+ has(r, "dg2") || has(r, "bmg")))+ return GpuKind::Discrete;+ return GpuKind::Integrated;+ }+ if (has(v, "amd") || has(v, "ati") || has(r, "radeon") || has(r, "amd")) {+ if (has(r, " rx ") || has(r, "rx ") || has(r, "radeon pro") || has(r, "firepro") || has(r, "instinct") ||+ has(r, "vega 56") || has(r, "vega 64") || has(r, "radeon vii"))+ return GpuKind::Discrete;+ // APUs: "AMD Radeon Graphics", "Radeon 780M", "Vega 8", RADV/radeonsi with an APU chip name.+ if (has(r, "radeon graphics") || has(r, "radeon(tm) graphics") || has(r, "vega 3") || has(r, "vega 6") ||+ has(r, "vega 8") || has(r, "vega 10") || has(r, "vega 11") || has(r, "renoir") || has(r, "cezanne") ||+ has(r, "rembrandt") || has(r, "phoenix") || has(r, "raphael") || has(r, "strix") || has(r, "van gogh") ||+ has(r, "gfx1103") || has(r, "gfx1150") || has(r, "gfx1035") || has(r, "gfx90c") || has(r, "760m") ||+ has(r, "780m") || has(r, "880m") || has(r, "890m") || has(r, "8060s") || has(r, "8050s"))+ return GpuKind::Integrated;+ return GpuKind::Discrete;+ }+ if (has(r, "mali") || has(r, "adreno") || has(r, "powervr") || has(r, "videocore") || has(r, "v3d") ||+ has(r, "immortalis"))+ return GpuKind::Integrated;+ if (has(r, "virgl") || has(r, "vmware") || has(r, "svga3d") || has(r, "parallels") || has(r, "virtio"))+ return GpuKind::Unknown; // virtual machines: the host's GPU, through a translation layer+ return GpuKind::Unknown;+}++uint64_t sysfsVramMB(const std::string& glVendor, const std::string& sysfsRoot) {+ const std::string v = lower(glVendor);+ std::string wantVendor;+ if (has(v, "amd") || has(v, "ati")) wantVendor = "0x1002";+ else if (has(v, "nvidia")) wantVendor = "0x10de";+ else if (has(v, "intel")) wantVendor = "0x8086";+ std::error_code ec;+ uint64_t best = 0;+ for (const auto& entry : std::filesystem::directory_iterator(sysfsRoot, ec)) {+ const std::string name = entry.path().filename().string();+ if (name.rfind("card", 0) != 0 || name.find('-') != std::string::npos) continue; // cardN, not cardN-HDMI-A-1+ const std::filesystem::path dev = entry.path() / "device";+ const std::string vendor = trim(readFile((dev / "vendor").string()));+ if (!wantVendor.empty() && vendor != wantVendor) continue;+ const std::string total = trim(readFile((dev / "mem_info_vram_total").string())); // amdgpu, bytes+ if (total.empty()) continue;+ const uint64_t mb = std::strtoull(total.c_str(), nullptr, 10) >> 20;+ best = std::max(best, mb);+ }+ return best;+}++void probeSystem(HardwareInfo& info) {+ info.appVersion = SCULPTFORGE_VERSION;+ info.cpuThreads = int(std::max(1u, std::thread::hardware_concurrency()));+ // --- RAM and OS ---+#if defined(_WIN32)+ MEMORYSTATUSEX ms{};+ ms.dwLength = sizeof ms;+ if (GlobalMemoryStatusEx(&ms)) info.ramMB = uint64_t(ms.ullTotalPhys) >> 20;+ std::string os = "Windows";+ using RtlGetVersionFn = LONG(WINAPI*)(PRTL_OSVERSIONINFOW);+ if (HMODULE ntdll = GetModuleHandleW(L"ntdll.dll")) {+ auto rtlGetVersion = reinterpret_cast<RtlGetVersionFn>(reinterpret_cast<void*>(GetProcAddress(ntdll, "RtlGetVersion")));+ RTL_OSVERSIONINFOW ver{};+ ver.dwOSVersionInfoSize = sizeof ver;+ if (rtlGetVersion && rtlGetVersion(&ver) == 0)+ os += " " + std::to_string(ver.dwMajorVersion) + "." + std::to_string(ver.dwMinorVersion) + "." ++ std::to_string(ver.dwBuildNumber);+ }+ SYSTEM_INFO si{};+ GetNativeSystemInfo(&si);+ os += si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM64 ? " arm64" : " x86_64";+ info.os = os;+#else+ const long pages = sysconf(_SC_PHYS_PAGES), pageSize = sysconf(_SC_PAGE_SIZE);+ if (pages > 0 && pageSize > 0) info.ramMB = (uint64_t(pages) * uint64_t(pageSize)) >> 20;+ struct utsname u {};+ if (uname(&u) == 0) info.os = std::string(u.sysname) + " " + u.release + " " + u.machine;+#if defined(__APPLE__)+ {+ uint64_t mem = 0;+ size_t len = sizeof mem;+ if (sysctlbyname("hw.memsize", &mem, &len, nullptr, 0) == 0) info.ramMB = mem >> 20;+ char ver[64] = {};+ len = sizeof ver;+ if (sysctlbyname("kern.osproductversion", ver, &len, nullptr, 0) == 0) info.os = std::string("macOS ") + ver + " " + u.machine;+ char brand[128] = {};+ len = sizeof brand;+ if (sysctlbyname("machdep.cpu.brand_string", brand, &len, nullptr, 0) == 0) info.cpu = trim(brand);+ }+#endif+#endif+ // --- CPU name and SIMD ---+ info.simd.clear();+#if defined(SF_X86)+ {+ unsigned regs[12] = {};+ bool ok = true;+ for (unsigned i = 0; i < 3 && ok; ++i) {+#if defined(_MSC_VER)+ int r[4];+ __cpuid(r, int(0x80000002u + i));+ std::memcpy(®s[i * 4], r, sizeof r);+#else+ ok = __get_cpuid(0x80000002u + i, ®s[i * 4], ®s[i * 4 + 1], ®s[i * 4 + 2], ®s[i * 4 + 3]) != 0;+#endif+ }+ if (ok && info.cpu.empty()) {+ char brand[49] = {};+ std::memcpy(brand, regs, 48);+ info.cpu = trim(brand);+ }+ }+#if defined(_MSC_VER)+ {+ int r[4];+ __cpuid(r, 1);+ const bool sse42 = (r[2] >> 20) & 1, osxsave = (r[2] >> 27) & 1, avx = (r[2] >> 28) & 1;+ const bool ymm = osxsave && avx && ((_xgetbv(0) & 6) == 6);+ __cpuidex(r, 7, 0);+ if (sse42) info.simd.push_back("sse4.2");+ if (ymm && ((r[1] >> 5) & 1)) info.simd.push_back("avx2");+ if (ymm && ((r[1] >> 16) & 1) && ((_xgetbv(0) & 0xE6) == 0xE6)) info.simd.push_back("avx512f");+ }+#else+ __builtin_cpu_init();+ if (__builtin_cpu_supports("sse4.2")) info.simd.push_back("sse4.2");+ if (__builtin_cpu_supports("avx2")) info.simd.push_back("avx2");+ if (__builtin_cpu_supports("avx512f")) info.simd.push_back("avx512f");+#endif+#elif defined(__aarch64__) || defined(_M_ARM64)+ info.simd.push_back("neon"); // every ARM64 CPU has Advanced SIMD+#if defined(__linux__)+ if (getauxval(AT_HWCAP) & (1UL << 22)) info.simd.push_back("sve"); // HWCAP_SVE+#endif+#endif+#if defined(__linux__)+ if (info.cpu.empty()) {+ // ARM boards: the device tree names the machine ("Apple MacBook Pro (16-inch, M1 Pro, 2021)").+ std::string model = readFile("/proc/device-tree/model");+ model.erase(std::remove(model.begin(), model.end(), '\0'), model.end());+ info.cpu = trim(model);+ }+ if (info.cpu.empty()) {+ std::istringstream cpuinfo(readFile("/proc/cpuinfo"));+ for (std::string line; std::getline(cpuinfo, line);)+ if (line.rfind("model name", 0) == 0 || line.rfind("Model", 0) == 0) {+ if (const size_t colon = line.find(':'); colon != std::string::npos) info.cpu = trim(line.substr(colon + 1));+ break;+ }+ }+#endif+#if defined(__AVX512F__)+ info.simdBuild = "avx512f";+#elif defined(__AVX2__)+ info.simdBuild = "avx2";+#elif defined(__SSE4_2__)+ info.simdBuild = "sse4.2";+#elif defined(SF_X86)+ info.simdBuild = "sse2";+#elif defined(__ARM_NEON) || defined(_M_ARM64)+ info.simdBuild = "neon";+#else+ info.simdBuild = "scalar";+#endif+}++// ---------------------------------------------------------------------------+// Mapping+// ---------------------------------------------------------------------------++namespace {++// GPU memory the scene may use, in MB (0 = unknown).+uint64_t usableGpuMemoryMB(const HardwareInfo& hw) {+ switch (hw.gpuKind) {+ case GpuKind::Discrete: return hw.vramMB;+ case GpuKind::Unified:+ // Apple GPUs may use about two thirds of the memory (Metal's recommended working set); a reported figure+ // (CGL, GLX_MESA_query_renderer) already is that.+ return hw.vramMB ? hw.vramMB : hw.ramMB * 2 / 3;+ case GpuKind::Integrated: return std::max(hw.vramMB, hw.ramMB / 2); // the carve-out plus shared system memory+ case GpuKind::Software: return hw.ramMB / 4;+ case GpuKind::Unknown: break;+ }+ return hw.vramMB;+}++struct TierLimits {+ uint64_t budgetMin, budgetMax, budgetDefault; // render triangle budget+ uint64_t vramDefaultMB, uploadDefaultMB;+ int textureCap;+ uint64_t subdivCap, microCap;+};++TierLimits limits(ProfileTier t) {+ switch (t) {+ case ProfileTier::Software: return {250'000, 4 * kM, 1 * kM, 1024, 16, 4096, 20 * kM, 16 * kM};+ case ProfileTier::Laptop: return {2 * kM, 40 * kM, 8 * kM, 2048, 64, 8192, 120 * kM, 256 * kM};+ case ProfileTier::Workstation: return {8 * kM, 150 * kM, 30 * kM, 6144, 128, 16384, 500 * kM, 1024 * kM};+ case ProfileTier::Monster: return {30 * kM, 600 * kM, 100 * kM, 12288, 256, 16384, 2000 * kM, 4096 * kM};+ }+ return limits(ProfileTier::Laptop);+}++// Thresholds on measured triangle throughput (million small triangles per second, trivial shading).+constexpr double kSoftwareBelowM = 60.0, kWorkstationFromM = 1000.0, kMonsterFromM = 5000.0;++ProfileTier tierFromMeasurements(const HardwareInfo& hw, const Calibration& c, std::string& why) {+ char buf[256];+ ProfileTier t;+ if (hw.gpuKind == GpuKind::Software) {+ why = "a software renderer (" + hw.glRenderer + "): safe mode";+ return ProfileTier::Software;+ }+ if (c.trianglesPerSecondM > 0.0) {+ if (c.trianglesPerSecondM < kSoftwareBelowM) t = ProfileTier::Software;+ else if (c.trianglesPerSecondM < kWorkstationFromM) t = ProfileTier::Laptop;+ else if (c.trianglesPerSecondM < kMonsterFromM) t = ProfileTier::Workstation;+ else t = ProfileTier::Monster;+ std::snprintf(buf, sizeof buf, "%.0fM triangles/s", c.trianglesPerSecondM);+ why = buf;+ } else {+ // Nothing measured: a conservative guess from the memory sizes.+ const uint64_t gpu = usableGpuMemoryMB(hw);+ t = ProfileTier::Laptop;+ if (gpu >= 8192 && hw.ramMB >= 24 * 1024) t = ProfileTier::Workstation;+ why = "not calibrated, from memory sizes";+ }+ // Memory caps: a fast GPU with little memory, or a machine with little RAM, can't hold the big scenes.+ const uint64_t gpu = usableGpuMemoryMB(hw);+ auto cap = [&](ProfileTier most, const char* reason) {+ if (int(t) > int(most)) {+ t = most;+ why += std::string(", capped by ") + reason;+ }+ };+ if (gpu && gpu < 3072) cap(ProfileTier::Laptop, "GPU memory");+ else if (gpu && gpu < 10240) cap(ProfileTier::Workstation, "GPU memory");+ if (hw.ramMB && hw.ramMB < 8 * 1024) cap(ProfileTier::Laptop, "system memory");+ else if (hw.ramMB && hw.ramMB < 24 * 1024) cap(ProfileTier::Workstation, "system memory");+ if (c.dabMs > 3.0) cap(ProfileTier::Laptop, "brush speed");+ if (c.memoryGBps > 0.0 && c.memoryGBps < 4.0) cap(ProfileTier::Laptop, "memory bandwidth");+ if (t != ProfileTier::Software && c.trianglesPerSecondM > 0.0 && c.trianglesPerSecondM < kSoftwareBelowM)+ t = ProfileTier::Software;+ return t;+}++} // namespace++PerformanceSettings settingsForTier(ProfileTier tier, const HardwareInfo& hw, const Calibration& c) {+ const TierLimits L = limits(tier);+ PerformanceSettings s;+ s.targetFps = 60;+ // Render budget: half a 60 Hz frame of the measured throughput (the real shading, antialiasing and the UI cost+ // the rest); the frame governor refines it from real frames.+ uint64_t budget = L.budgetDefault;+ if (c.trianglesPerSecondM > 0.0) budget = uint64_t(c.trianglesPerSecondM * 1e6 / 60.0 * 0.5);+ s.renderTriangleBudget = std::clamp(budget, L.budgetMin, L.budgetMax);+ // While the view moves, scenes over the budget draw the motion proxy (a quarter of the triangles).+ s.motionProxyThreshold = std::max<uint64_t>(s.renderTriangleBudget, 262'144);+ // GPU memory budget: 80% of dedicated memory (the desktop and other programs keep the rest).+ const uint64_t gpu = usableGpuMemoryMB(hw);+ if (gpu) s.vramBudgetMB = hw.gpuKind == GpuKind::Discrete || hw.gpuKind == GpuKind::Unknown ? gpu * 4 / 5 : gpu;+ else s.vramBudgetMB = L.vramDefaultMB;+ // Uploads: a quarter of a 60 Hz frame at the measured bandwidth.+ if (c.uploadGBps > 0.0)+ s.uploadBudgetMBPerFrame = std::clamp<uint64_t>(uint64_t(c.uploadGBps * 1e9 / 60.0 * 0.25) >> 20, 4, 1024);+ else s.uploadBudgetMBPerFrame = L.uploadDefaultMB;+ s.maxTextureSize = L.textureCap;+ if (hw.maxTextureSize > 0) s.maxTextureSize = std::min(s.maxTextureSize, hw.maxTextureSize);+ if (s.vramBudgetMB < 2048) s.maxTextureSize = std::min(s.maxTextureSize, 8192);+ // Subdivision: about 100 bytes of system memory per triangle with its levels, BVH and undo (docs/performance.md),+ // half the RAM; and about 16 bytes of GPU memory per drawn triangle.+ const uint64_t byRam = hw.ramMB ? (hw.ramMB << 20) / 2 / 100 : L.subdivCap;+ const uint64_t byGpu = (s.vramBudgetMB << 20) / 16;+ s.maxSubdivisionTriangles = std::clamp<uint64_t>(roundDownTo(std::min({byRam, byGpu, L.subdivCap}), kM), 2 * kM, L.subdivCap);+ // Micro-displacement: about 8 bytes of GPU memory per micro-triangle, a quarter of the budget.+ s.microTriangleLimit = std::clamp<uint64_t>(roundDownTo((s.vramBudgetMB << 20) / 4 / 8, kM), 1 * kM, L.microCap);+ // Threads: every hardware thread (the pool's limit is 16); a software renderer draws on the same cores.+ const int threads = std::max(1, hw.cpuThreads ? hw.cpuThreads : int(std::thread::hardware_concurrency()));+ s.threads = std::clamp(tier == ProfileTier::Software ? threads / 2 : threads, 1, 16);+ return s;+}++PerformanceSettings applyOverrides(const PerformanceSettings& a, const ProfileOverrides& o) {+ PerformanceSettings s = a;+ if (o.renderTriangleBudget) s.renderTriangleBudget = o.renderTriangleBudget;+ if (o.motionProxyThreshold) s.motionProxyThreshold = o.motionProxyThreshold;+ else if (o.renderTriangleBudget) s.motionProxyThreshold = std::max<uint64_t>(o.renderTriangleBudget, 262'144);+ if (o.vramBudgetMB) s.vramBudgetMB = o.vramBudgetMB;+ if (o.uploadBudgetMBPerFrame) s.uploadBudgetMBPerFrame = o.uploadBudgetMBPerFrame;+ if (o.maxTextureSize) s.maxTextureSize = o.maxTextureSize;+ if (o.maxSubdivisionTriangles) s.maxSubdivisionTriangles = o.maxSubdivisionTriangles;+ if (o.microTriangleLimit) s.microTriangleLimit = o.microTriangleLimit;+ if (o.threads) s.threads = std::clamp(o.threads, 1, 64);+ if (o.targetFps) s.targetFps = std::clamp(o.targetFps, 15, 360);+ return s;+}++bool ProfileOverrides::any() const {+ return !tier.empty() || renderTriangleBudget || motionProxyThreshold || vramBudgetMB || uploadBudgetMBPerFrame ||+ maxTextureSize || maxSubdivisionTriangles || microTriangleLimit || threads || targetFps || !governor;+}++HardwareProfile mapProfile(const HardwareInfo& hardware, const Calibration& calibration, const ProfileOverrides& overrides) {+ HardwareProfile p;+ p.hardware = hardware;+ p.calibration = calibration;+ p.overrides = overrides;+ std::string why;+ p.tier = tierFromMeasurements(hardware, calibration, why);+ ProfileTier forced;+ if (!overrides.tier.empty() && tierFromName(overrides.tier, forced) && forced != p.tier) {+ why += std::string("; set to ") + tierName(forced) + " by hand";+ p.tier = forced;+ }+ p.automatic = settingsForTier(p.tier, hardware, calibration);+ p.settings = applyOverrides(p.automatic, overrides);+ const uint64_t gpu = usableGpuMemoryMB(hardware);+ std::string gpuName = hardware.glRenderer.empty() ? std::string("no GPU probed") : hardware.glRenderer;+ // "Detected Apple M1 Pro (G13S C0), 21.3 GB unified -> Workstation (2100M triangles/s)"+ p.reason = "Detected " + gpuName + (gpu ? ", " + formatMegabytes(gpu) + " " + gpuKindName(hardware.gpuKind) : std::string()) ++ " -> " + tierName(p.tier) + " (" + why + ")";+ return p;+}++// ---------------------------------------------------------------------------+// Cache and JSON+// ---------------------------------------------------------------------------++namespace {++Json num(uint64_t v) { return Json(double(v)); }+uint64_t u64(const Json& j, uint64_t fallback = 0) {+ const double d = j.asNumber(double(fallback));+ return d > 0 ? uint64_t(d) : 0;+}++Json hardwareJson(const HardwareInfo& h) {+ Json j = Json::object();+ j.set("gl_vendor", h.glVendor);+ j.set("gl_renderer", h.glRenderer);+ j.set("gl_version", h.glVersion);+ j.set("gpu_kind", gpuKindName(h.gpuKind));+ j.set("vram_mb", num(h.vramMB));+ j.set("vram_available_mb", num(h.vramAvailableMB));+ j.set("vram_source", h.vramSource.empty() ? std::string("none") : h.vramSource);+ j.set("max_texture_size", h.maxTextureSize);+ j.set("timer_query", h.timerQuery);+ j.set("os", h.os);+ j.set("cpu", h.cpu);+ j.set("cpu_threads", h.cpuThreads);+ j.set("ram_mb", num(h.ramMB));+ Json simd = Json::array();+ for (const auto& s : h.simd) simd.push(s);+ j.set("simd", simd);+ j.set("simd_build", h.simdBuild);+ j.set("app_version", h.appVersion);+ return j;+}++void hardwareFromJson(const Json& j, HardwareInfo& h) {+ h.glVendor = j["gl_vendor"].asString();+ h.glRenderer = j["gl_renderer"].asString();+ h.glVersion = j["gl_version"].asString();+ h.gpuKind = gpuKindFromName(j["gpu_kind"].asString());+ h.vramMB = u64(j["vram_mb"]);+ h.vramAvailableMB = u64(j["vram_available_mb"]);+ h.vramSource = j["vram_source"].asString();+ h.maxTextureSize = int(j["max_texture_size"].asNumber());+ h.timerQuery = j["timer_query"].asBool();+ h.os = j["os"].asString();+ h.cpu = j["cpu"].asString();+ h.cpuThreads = int(j["cpu_threads"].asNumber());+ h.ramMB = u64(j["ram_mb"]);+ h.simd.clear();+ for (const Json& s : j["simd"].items()) h.simd.push_back(s.asString());+ h.simdBuild = j["simd_build"].asString();+ h.appVersion = j["app_version"].asString();+}++Json calibrationToJson(const Calibration& c) {+ Json j = Json::object();+ j.set("triangles_per_second_millions", c.trianglesPerSecondM);+ j.set("upload_gb_per_second", c.uploadGBps);+ j.set("dab_ms", c.dabMs);+ j.set("dab_vertices", c.dabVertices);+ j.set("memory_gb_per_second", c.memoryGBps);+ j.set("gpu_timer", c.gpuTimer);+ j.set("runs", c.runs);+ j.set("duration_ms", c.durationMs);+ j.set("skipped", c.skipped);+ j.set("cpu_only", c.cpuOnly);+ return j;+}++void calibrationFromJson(const Json& j, Calibration& c) {+ c.trianglesPerSecondM = j["triangles_per_second_millions"].asNumber();+ c.uploadGBps = j["upload_gb_per_second"].asNumber();+ c.dabMs = j["dab_ms"].asNumber();+ c.dabVertices = j["dab_vertices"].asNumber();+ c.memoryGBps = j["memory_gb_per_second"].asNumber();+ c.gpuTimer = j["gpu_timer"].asBool();+ c.runs = int(j["runs"].asNumber());+ c.durationMs = j["duration_ms"].asNumber();+ c.skipped = j["skipped"].asBool();+ c.cpuOnly = j["cpu_only"].asBool();+}++Json settingsJson(const PerformanceSettings& s) {+ Json j = Json::object();+ j.set("render_triangle_budget", num(s.renderTriangleBudget));+ j.set("motion_proxy_threshold", num(s.motionProxyThreshold));+ j.set("vram_budget_mb", num(s.vramBudgetMB));+ j.set("upload_budget_mb_per_frame", num(s.uploadBudgetMBPerFrame));+ j.set("max_texture_size", s.maxTextureSize);+ j.set("max_subdivision_triangles", num(s.maxSubdivisionTriangles));+ j.set("micro_triangle_limit", num(s.microTriangleLimit));+ j.set("threads", s.threads);+ j.set("target_fps", s.targetFps);+ return j;+}++Json overridesJson(const ProfileOverrides& o) {+ Json j = Json::object();+ if (!o.tier.empty()) j.set("tier", o.tier);+ if (o.renderTriangleBudget) j.set("render_triangle_budget", num(o.renderTriangleBudget));+ if (o.motionProxyThreshold) j.set("motion_proxy_threshold", num(o.motionProxyThreshold));+ if (o.vramBudgetMB) j.set("vram_budget_mb", num(o.vramBudgetMB));+ if (o.uploadBudgetMBPerFrame) j.set("upload_budget_mb_per_frame", num(o.uploadBudgetMBPerFrame));+ if (o.maxTextureSize) j.set("max_texture_size", o.maxTextureSize);+ if (o.maxSubdivisionTriangles) j.set("max_subdivision_triangles", num(o.maxSubdivisionTriangles));+ if (o.microTriangleLimit) j.set("micro_triangle_limit", num(o.microTriangleLimit));+ if (o.threads) j.set("threads", o.threads);+ if (o.targetFps) j.set("target_fps", o.targetFps);+ if (!o.governor) j.set("governor", false);+ return j;+}++void overridesFromJson(const Json& j, ProfileOverrides& o) {+ o = {};+ o.tier = j["tier"].asString();+ o.renderTriangleBudget = u64(j["render_triangle_budget"]);+ o.motionProxyThreshold = u64(j["motion_proxy_threshold"]);+ o.vramBudgetMB = u64(j["vram_budget_mb"]);+ o.uploadBudgetMBPerFrame = u64(j["upload_budget_mb_per_frame"]);+ o.maxTextureSize = int(j["max_texture_size"].asNumber());+ o.maxSubdivisionTriangles = u64(j["max_subdivision_triangles"]);+ o.microTriangleLimit = u64(j["micro_triangle_limit"]);+ o.threads = int(j["threads"].asNumber());+ o.targetFps = int(j["target_fps"].asNumber());+ o.governor = j["governor"].asBool(true);+}++} // namespace++std::string hardwareProfilePath() {+ const std::string dir = appDataDir();+ if (dir.empty()) return {};+#if defined(_WIN32)+ return dir + "\\hardware_profile.json";+#else+ return dir + "/hardware_profile.json";+#endif+}++Json hardwareProfileToJson(const HardwareProfile& p) {+ Json j = Json::object();+ j.set("cache_version", kHardwareProfileCacheVersion);+ j.set("hardware", hardwareJson(p.hardware));+ j.set("calibration", calibrationToJson(p.calibration));+ j.set("tier", tierName(p.tier));+ j.set("settings", settingsJson(p.settings));+ j.set("overrides", overridesJson(p.overrides));+ return j;+}++bool hardwareProfileFromJson(const Json& j, HardwareProfile& out) {+ if (!j.isObject() || int(j["cache_version"].asNumber()) != kHardwareProfileCacheVersion) return false;+ if (!j["hardware"].isObject() || !j["calibration"].isObject()) return false;+ HardwareInfo h;+ Calibration c;+ ProfileOverrides o;+ hardwareFromJson(j["hardware"], h);+ calibrationFromJson(j["calibration"], c);+ if (j["overrides"].isObject()) overridesFromJson(j["overrides"], o);+ // The tier and settings are mapped again (not read back), so they always follow this version's mapping.+ out = mapProfile(h, c, o);+ return true;+}++bool loadHardwareProfile(const std::string& path, HardwareProfile& out) {+ if (path.empty()) return false;+ const std::string text = readFile(path);+ if (text.empty()) return false;+ Json j;+ std::string error;+ return Json::parse(text, j, error) && hardwareProfileFromJson(j, out);+}++bool saveHardwareProfile(const std::string& path, const HardwareProfile& profile, std::string& error) {+ if (path.empty()) {+ error = "no settings folder";+ return false;+ }+ const std::filesystem::path p(std::u8string(path.begin(), path.end()));+ std::error_code ec;+ if (p.has_parent_path()) std::filesystem::create_directories(p.parent_path(), ec);+ const std::filesystem::path tmp = p.string() + ".tmp";+ {+ std::ofstream f(tmp, std::ios::binary | std::ios::trunc);+ if (!f) {+ error = "cannot write " + path;+ return false;+ }+ f << hardwareProfileToJson(profile).dump(true) << "\n";+ if (!f) {+ error = "cannot write " + path;+ return false;+ }+ }+ std::filesystem::rename(tmp, p, ec);+ if (ec) {+ error = "cannot replace " + path + ": " + ec.message();+ return false;+ }+ return true;+}++std::string recalibrationReason(const HardwareProfile* cached, const HardwareInfo& cur) {+ if (!cached) return "first launch";+ const HardwareInfo& old = cached->hardware;+ if (old.glVendor != cur.glVendor || old.glRenderer != cur.glRenderer) return "GPU changed";+ if (old.glVersion != cur.glVersion) return "driver changed";+ if (old.appVersion != cur.appVersion) return "new version";+ if (cached->calibration.cpuOnly && !cur.glRenderer.empty()) return "GPU not measured yet";+ return {};+}++bool needsRecalibration(const HardwareProfile* cached, const HardwareInfo& current) {+ return !recalibrationReason(cached, current).empty();+}++Json calibrationJson(const HardwareProfile& p) {+ Json j = Json::object();+ j.set("schema", kCalibrationSchema);+ j.set("app_version", p.hardware.appVersion);+ j.set("hardware", hardwareJson(p.hardware));+ j.set("measurements", calibrationToJson(p.calibration));+ j.set("profile", tierName(p.tier));+ j.set("reason", p.reason);+ j.set("settings", settingsJson(p.settings));+ j.set("automatic", settingsJson(p.automatic));+ j.set("overrides", overridesJson(p.overrides));+ j.set("network", false); // calibration never uses the network (no telemetry)+ return j;+}++bool validateCalibrationJson(const Json& j, std::string& error) {+ auto need = [&](const Json& obj, const char* where, const char* key, Json::Type type) {+ if (!error.empty()) return false;+ const Json& v = obj[key];+ if (v.type() != type) {+ error = std::string(where) + "." + key + " is missing or has the wrong type";+ return false;+ }+ return true;+ };+ error.clear();+ if (!j.isObject()) {+ error = "not a JSON object";+ return false;+ }+ using T = Json::Type;+ need(j, "$", "schema", T::String);+ if (error.empty() && j["schema"].asString() != kCalibrationSchema) error = "$.schema is not " + std::string(kCalibrationSchema);+ need(j, "$", "app_version", T::String);+ need(j, "$", "hardware", T::Object);+ need(j, "$", "measurements", T::Object);+ need(j, "$", "profile", T::String);+ need(j, "$", "reason", T::String);+ need(j, "$", "settings", T::Object);+ need(j, "$", "automatic", T::Object);+ need(j, "$", "overrides", T::Object);+ need(j, "$", "network", T::Bool);+ if (!error.empty()) return false;+ ProfileTier tier;+ if (!tierFromName(j["profile"].asString(), tier)) {+ error = "$.profile is not a tier name";+ return false;+ }+ if (j["network"].asBool()) {+ error = "$.network must be false";+ return false;+ }+ const Json& h = j["hardware"];+ for (const char* k : {"gl_vendor", "gl_renderer", "gl_version", "gpu_kind", "vram_source", "os", "cpu", "simd_build", "app_version"})+ need(h, "hardware", k, T::String);+ for (const char* k : {"vram_mb", "vram_available_mb", "max_texture_size", "cpu_threads", "ram_mb"}) need(h, "hardware", k, T::Number);+ need(h, "hardware", "timer_query", T::Bool);+ need(h, "hardware", "simd", T::Array);+ const Json& m = j["measurements"];+ for (const char* k : {"triangles_per_second_millions", "upload_gb_per_second", "dab_ms", "dab_vertices",+ "memory_gb_per_second", "runs", "duration_ms"})+ need(m, "measurements", k, T::Number);+ for (const char* k : {"gpu_timer", "skipped", "cpu_only"}) need(m, "measurements", k, T::Bool);+ for (const char* which : {"settings", "automatic"}) {+ const Json& s = j[which];+ for (const char* k : {"render_triangle_budget", "motion_proxy_threshold", "vram_budget_mb", "upload_budget_mb_per_frame",+ "max_texture_size", "max_subdivision_triangles", "micro_triangle_limit", "threads", "target_fps"})+ need(s, which, k, T::Number);+ if (error.empty() && s["render_triangle_budget"].asNumber() <= 0) error = std::string(which) + ".render_triangle_budget must be > 0";+ if (error.empty() && s["threads"].asNumber() < 1) error = std::string(which) + ".threads must be >= 1";+ }+ return error.empty();+}++// ---------------------------------------------------------------------------+// CPU benchmarks+// ---------------------------------------------------------------------------++double measureMemoryBandwidthGBps(int runs) {+ constexpr size_t kBytes = size_t(64) << 20;+ std::vector<uint8_t> a(kBytes, 1), b(kBytes, 0); // touched: the pages exist before timing+ std::vector<double> rates;+ for (int i = 0; i < std::max(1, runs) + 1; ++i) {+ a[size_t(i) * 4099 % kBytes] = uint8_t(i); // a change the copy can't skip+ const auto t = Clock::now();+ std::memcpy(b.data(), a.data(), kBytes);+ const double ms = msSince(t);+ if (i > 0 && ms > 0.0) rates.push_back(double(kBytes) / (ms * 1e-3) / 1e9); // the first run warms up+ }+ volatile uint8_t sink = b[kBytes / 2];+ (void)sink;+ return median(rates);+}++double measureDabMs(size_t triangles, int runs, int dabsPerRun, double* verticesPerDab) {+ Document doc;+ doc.setMesh(makeBenchSphere(triangles), "Calibration");+ Mesh& m = doc.mesh;+ Sculptor& sc = doc.sculptor;+ const float radius = 0.12f, step = 0.15f * radius;+ std::vector<double> perDab;+ double verts = 0.0;+ for (int run = 0; run < std::max(1, runs) + 1; ++run) { // run 0 warms the caches and the thread pool+ sc.beginStroke(m, "Calibration");+ sc.timings = {};+ Symmetry sym;+ glm::vec3 last(0.0f);+ int done = 0;+ double ms = 0.0;+ for (int i = 0; i < dabsPerRun; ++i) {+ const float x = 0.15f + std::fmod(float(i) * step, 0.6f), y = 0.2f + 0.1f * std::sin(float(i) * 0.3f);+ RayHit hit;+ if (!doc.bvh.raycast(m, glm::vec3(x, y, 5.0f), glm::vec3(0, 0, -1), hit)) continue;+ DabParams p;+ p.center = hit.position;+ p.viewDir = glm::vec3(0, 0, -1);+ p.radius = radius;+ p.strength = 0.3f;+ p.strokeDelta = i ? hit.position - last : glm::vec3(0.0f);+ last = hit.position;+ const auto t = Clock::now();+ sc.dab(m, doc.bvh, BrushType::Standard, p, sym);+ ms += msSince(t);+ m.clearDirty();+ ++done;+ }+ if (run > 0 && done > 0) {+ perDab.push_back(ms / double(done));+ verts = double(sc.timings.vertices) / double(done);+ }+ doc.undo.push(sc.endStroke());+ doc.undo.undo(m, doc.bvh); // the next run sculpts the same surface+ m.clearDirty();+ }+ if (verticesPerDab) *verticesPerDab = verts;+ return median(perDab);+}++void calibrateCpu(Calibration& out, bool quick) {+ out.memoryGBps = measureMemoryBandwidthGBps(quick ? 3 : 5);+ out.dabMs = measureDabMs(quick ? 200'000 : 1'000'000, quick ? 3 : 5, quick ? 12 : 20, &out.dabVertices);+ out.runs = std::max(out.runs, quick ? 3 : 5);+}++// ---------------------------------------------------------------------------+// The profile in effect+// ---------------------------------------------------------------------------++namespace {++std::mutex g_mutex;+PerformanceSettings& currentSettingsLocked() {+ static PerformanceSettings s = settingsForTier(ProfileTier::Laptop, HardwareInfo{}, Calibration{});+ return s;+}+std::atomic<uint64_t> g_budget{0}, g_proxy{0};+GpuCalibrator g_gpuCalibrator;+std::atomic<uint64_t> g_revision{0};++} // namespace++PerformanceSettings currentPerformanceSettings() {+ std::lock_guard<std::mutex> lock(g_mutex);+ return currentSettingsLocked();+}++void setCurrentPerformanceSettings(const PerformanceSettings& s) {+ {+ std::lock_guard<std::mutex> lock(g_mutex);+ currentSettingsLocked() = s;+ }+ setGovernedBudgets(s.renderTriangleBudget, s.motionProxyThreshold);+ g_revision.fetch_add(1, std::memory_order_relaxed);+}++uint64_t performanceSettingsRevision() { return g_revision.load(std::memory_order_relaxed); }++uint64_t renderTriangleBudget() {+ const uint64_t b = g_budget.load(std::memory_order_relaxed);+ return b ? b : currentPerformanceSettings().renderTriangleBudget;+}++uint64_t motionProxyThreshold() {+ const uint64_t t = g_proxy.load(std::memory_order_relaxed);+ return t ? t : currentPerformanceSettings().motionProxyThreshold;+}++void setGovernedBudgets(uint64_t renderTriangles, uint64_t proxyThreshold) {+ g_budget.store(renderTriangles, std::memory_order_relaxed);+ g_proxy.store(proxyThreshold, std::memory_order_relaxed);+}++void setGpuCalibrator(GpuCalibrator calibrator) {+ std::lock_guard<std::mutex> lock(g_mutex);+ g_gpuCalibrator = std::move(calibrator);+}++// ---------------------------------------------------------------------------+// Commands+// ---------------------------------------------------------------------------++namespace {++// The profile the commands work on: the cache file (the app keeps it current).+bool loadCurrent(HardwareProfile& p) { return loadHardwareProfile(hardwareProfilePath(), p); }++HardwareProfile uncalibrated() {+ HardwareInfo h;+ probeSystem(h);+ Calibration c;+ c.cpuOnly = true;+ return mapProfile(h, c);+}++bool setOverride(ProfileOverrides& o, const std::string& name, const std::string& text, double value, std::string& error) {+ const bool clear = text == "auto" || (text.empty() && value <= 0.0);+ const uint64_t u = clear ? 0 : uint64_t(std::max(0.0, value));+ if (name == "tier") {+ ProfileTier t;+ if (clear) o.tier.clear();+ else if (tierFromName(text, t)) o.tier = tierName(t);+ else {+ error = "tier must be Software, Laptop, Workstation, Monster or auto";+ return false;+ }+ } else if (name == "render_triangle_budget") o.renderTriangleBudget = u;+ else if (name == "motion_proxy_threshold") o.motionProxyThreshold = u;+ else if (name == "vram_budget_mb") o.vramBudgetMB = u;+ else if (name == "upload_budget_mb_per_frame") o.uploadBudgetMBPerFrame = u;+ else if (name == "max_texture_size") o.maxTextureSize = int(u);+ else if (name == "max_subdivision_triangles") o.maxSubdivisionTriangles = u;+ else if (name == "micro_triangle_limit") o.microTriangleLimit = u;+ else if (name == "threads") o.threads = int(u);+ else if (name == "target_fps") o.targetFps = int(u);+ else if (name == "governor") o.governor = clear ? true : value != 0.0 || text == "on" || text == "true";+ else {+ error = "unknown setting " + name;+ return false;+ }+ return true;+}++} // namespace++void registerHardwareProfileCommands(CommandRegistry& registry) {+ registry.add({"performance_profile",+ "The hardware profile as JSON (schema sculptforge.calibration/1): the GPU, its memory, RAM, CPU threads "+ "and SIMD, what calibration measured, the tier (Software / Laptop / Workstation / Monster) and its "+ "settings (render triangle budget, motion proxy threshold, VRAM budget, ...). Nothing is sent anywhere.",+ {},+ [](Document&, const Args&) -> CommandResult {+ HardwareProfile p;+ if (!loadCurrent(p)) p = uncalibrated();+ return {true, calibrationJson(p).dump(true)};+ }});+ registry.add({"calibrate",+ "Measure this computer again (about 2-3 seconds) and pick the performance profile: triangle throughput "+ "and upload bandwidth on the GPU (in the app; sculptforge --calibrate from a shell), brush dab cost and "+ "memory bandwidth on the CPU. Prints the result as JSON and saves it. Manual overrides are kept.",+ {{"quick", ParamSpec::Type::Bool, "Fewer runs (about 1 second, less precise).", false}},+ [](Document&, const Args& a) -> CommandResult {+ const bool quick = argBool(a, "quick", false);+ GpuCalibrator gpu;+ {+ std::lock_guard<std::mutex> lock(g_mutex);+ gpu = g_gpuCalibrator;+ }+ HardwareProfile cached;+ const bool hadCache = loadCurrent(cached);+ HardwareProfile p;+ std::string error;+ if (gpu) {+ if (!gpu(p, error)) return {false, error};+ } else {+ // No OpenGL here (sculptforge-cli): measure the CPU; keep the cached GPU strings and numbers.+ const auto t = Clock::now();+ HardwareInfo h;+ probeSystem(h);+ Calibration c;+ if (hadCache) {+ h.glVendor = cached.hardware.glVendor;+ h.glRenderer = cached.hardware.glRenderer;+ h.glVersion = cached.hardware.glVersion;+ h.gpuKind = cached.hardware.gpuKind;+ h.vramMB = cached.hardware.vramMB;+ h.vramSource = cached.hardware.vramSource;+ h.maxTextureSize = cached.hardware.maxTextureSize;+ h.timerQuery = cached.hardware.timerQuery;+ c.trianglesPerSecondM = cached.calibration.trianglesPerSecondM;+ c.uploadGBps = cached.calibration.uploadGBps;+ c.gpuTimer = cached.calibration.gpuTimer;+ }+ c.cpuOnly = c.trianglesPerSecondM <= 0.0;+ calibrateCpu(c, quick);+ c.durationMs = msSince(t);+ p = mapProfile(h, c, hadCache ? cached.overrides : ProfileOverrides{});+ }+ if (hadCache && !gpu) p.overrides = cached.overrides;+ saveHardwareProfile(hardwareProfilePath(), p, error); // best effort: the JSON is the answer+ return {true, calibrationJson(p).dump(true)};+ }});+ registry.add({"set_performance_override",+ "Override one setting of the performance profile by hand (kept across re-calibrations), or give it "+ "back to the profile with value=auto. Settings: tier (Software, Laptop, Workstation, Monster), "+ "render_triangle_budget, motion_proxy_threshold, vram_budget_mb, upload_budget_mb_per_frame, "+ "max_texture_size, max_subdivision_triangles, micro_triangle_limit, threads (next start), target_fps, "+ "governor (on / off).",+ {{"name", ParamSpec::Type::String, "The setting.", true},+ {"value", ParamSpec::Type::String, "A number, a tier name, on / off, or auto.", true}},+ [](Document&, const Args& a) -> CommandResult {+ HardwareProfile p;+ if (!loadCurrent(p)) p = uncalibrated();+ const std::string name = argString(a, "name");+ std::string text = argString(a, "value");+ double value = argNumber(a, "value", 0.0);+ if (!text.empty() && text != "auto") {+ char* end = nullptr;+ const double d = std::strtod(text.c_str(), &end);+ if (end && *end == '\0') {+ value = d;+ text.clear();+ }+ }+ std::string error;+ ProfileOverrides o = p.overrides;+ if (!setOverride(o, name, text, value, error)) return {false, error};+ p = mapProfile(p.hardware, p.calibration, o);+ if (!saveHardwareProfile(hardwareProfilePath(), p, error)) return {false, error};+ setCurrentPerformanceSettings(p.settings);+ return {true, name + " = " + (text.empty() && value > 0 ? std::to_string(uint64_t(value)) : text.empty() ? "auto" : text) ++ "; " + p.reason};+ }});+}++} // namespace sfdiff --git a/src/core/HardwareProfile.h b/src/core/HardwareProfile.hnew file mode 100644index 00000000..a8c6a014--- /dev/null+++ b/src/core/HardwareProfile.h@@ -0,0 +1,190 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Automatic hardware detection and calibration (docs/performance.md, "Hardware profile").+//+// What the computer is (HardwareInfo: the GPU's OpenGL strings and memory, system RAM, CPU threads, SIMD, OS)+// and how fast it measured (Calibration: triangle throughput, buffer upload bandwidth, brush dab cost, memory+// bandwidth) map to a profile tier (Software / Laptop / Workstation / Monster) with concrete settings+// (PerformanceSettings: render triangle budget, motion proxy threshold, VRAM budget, ...). The mapping uses+// the measurements and memory sizes, never GPU names: names only tell unified from discrete memory and spot a+// software renderer (llvmpipe and friends).+//+// Everything is cached in <config dir>/hardware_profile.json and probed again when the GPU's renderer, vendor+// or driver (GL_VERSION) string or the app version changes. Nothing here uses the network.+//+// This file is the core half (no OpenGL): the types, the CPU probes and benchmarks, the mapping, the cache and+// the JSON. The app (app/Calibration.h) adds the OpenGL probe and GPU benchmarks; the frame governor+// (core/FrameGovernor.h) adjusts the render budgets at run time.+#pragma once++#include "core/Json.h"++#include <cstdint>+#include <functional>+#include <string>+#include <vector>++namespace sf {++class CommandRegistry;++enum class GpuKind { Unknown, Discrete, Integrated, Unified, Software };+const char* gpuKindName(GpuKind kind); // "discrete", "integrated", "unified", "software", "unknown"+GpuKind gpuKindFromName(const std::string& name);++enum class ProfileTier { Software, Laptop, Workstation, Monster };+const char* tierName(ProfileTier tier); // "Software", "Laptop", "Workstation", "Monster"+bool tierFromName(const std::string& name, ProfileTier& out);++// What the computer is. GPU fields stay empty / 0 where no OpenGL context was probed (sculptforge-cli).+struct HardwareInfo {+ std::string glVendor, glRenderer, glVersion;+ GpuKind gpuKind = GpuKind::Unknown;+ uint64_t vramMB = 0; // dedicated video memory; for unified memory, what the GPU may use; 0 = unknown+ uint64_t vramAvailableMB = 0; // free right now, where the driver says (NVX / ATI meminfo); 0 = unknown+ std::string vramSource; // how vramMB was found, e.g. "GL_NVX_gpu_memory_info", "sysfs amdgpu", "none"+ int maxTextureSize = 0; // GL_MAX_TEXTURE_SIZE+ bool timerQuery = false; // GL timer queries work (GL_TIME_ELAPSED)+ // The machine.+ std::string os; // e.g. "Linux 6.9.1 aarch64", "Windows 10.0.22631 x86_64", "macOS 15.1 arm64"+ std::string cpu; // brand string or board model, "" if unknown+ int cpuThreads = 0; // hardware threads+ uint64_t ramMB = 0; // physical memory+ std::vector<std::string> simd; // what the CPU supports: "sse4.2", "avx2", "avx512f", "neon", "sve"+ std::string simdBuild; // what this build was compiled to use, e.g. "sse2", "avx2", "neon"+ std::string appVersion;+};++// Fills the machine fields (os, cpu, cpuThreads, ramMB, simd, simdBuild, appVersion).+void probeSystem(HardwareInfo& info);+// Classifies the GPU from its OpenGL strings: Software (llvmpipe, softpipe, SwiftShader, Microsoft Basic Render,+// GDI Generic, Apple Software Renderer), Unified (Apple GPUs, including Asahi Linux), Integrated (Intel UHD / Iris /+// Xe, AMD APUs whose name has no model number) or Discrete (NVIDIA GeForce / Quadro / RTX, AMD Radeon RX / Pro,+// Intel Arc A / B), else Unknown. Only memory type: tiers come from measurements.+GpuKind classifyGpu(const std::string& vendor, const std::string& renderer);+// Linux: video memory from sysfs (amdgpu's mem_info_vram_total) for the card whose PCI vendor matches `glVendor`;+// 0 if none. `sysfsRoot` is for tests (default /sys/class/drm).+uint64_t sysfsVramMB(const std::string& glVendor, const std::string& sysfsRoot = "/sys/class/drm");++// What calibration measured. Numbers are medians of `runs` runs; 0 = not measured.+struct Calibration {+ double trianglesPerSecondM = 0.0; // million triangles per second, small triangles into an offscreen target+ double uploadGBps = 0.0; // glBufferSubData of a large buffer, GB/s (10^9 bytes)+ double dabMs = 0.0; // one Standard brush dab (X symmetry) on a generated 1M triangle sphere (0.2M quick)+ double dabVertices = 0.0; // vertices one dab moved (both sides)+ double memoryGBps = 0.0; // memcpy of a 64 MB buffer, bytes copied per second (GB/s)+ bool gpuTimer = false; // GPU numbers came from timer queries (else glFinish around the CPU clock)+ int runs = 0;+ double durationMs = 0.0; // the whole calibration+ bool skipped = false; // the user skipped it: the profile comes from the probe alone+ bool cpuOnly = false; // no OpenGL context (sculptforge-cli): GPU numbers are from the cache or 0+};++// The settings a profile gives. Overridable one by one (ProfileOverrides).+struct PerformanceSettings {+ uint64_t renderTriangleBudget = 0; // triangles the 3D view may draw per frame at the target frame rate+ uint64_t motionProxyThreshold = 0; // scenes with at least this many visible triangles draw the motion+ // proxy while the view moves (Fast Navigation)+ uint64_t vramBudgetMB = 0; // GPU memory the scene's buffers should stay within+ uint64_t uploadBudgetMBPerFrame = 0; // vertex data to send to the GPU per frame before deferring the rest+ int maxTextureSize = 0; // largest texture to create (paint textures, bakes)+ uint64_t maxSubdivisionTriangles = 0; // default limit for Divide (subdivision levels) on this machine+ uint64_t microTriangleLimit = 0; // micro-displacement (micromesh): most micro-triangles to generate+ int threads = 0; // worker threads for brushes and other per-dab work+ int targetFps = 60; // the governor's target (60, or 120 on a 120 Hz display)+};++// Manual overrides from Preferences > Performance (0 = automatic). Kept across re-calibrations.+struct ProfileOverrides {+ std::string tier; // "" = automatic, else a tierName()+ uint64_t renderTriangleBudget = 0;+ uint64_t motionProxyThreshold = 0;+ uint64_t vramBudgetMB = 0;+ uint64_t uploadBudgetMBPerFrame = 0;+ int maxTextureSize = 0;+ uint64_t maxSubdivisionTriangles = 0;+ uint64_t microTriangleLimit = 0;+ int threads = 0;+ int targetFps = 0;+ bool governor = true; // the adaptive frame governor (off: the budgets stay as set)+ bool any() const;+};++struct HardwareProfile {+ HardwareInfo hardware;+ Calibration calibration;+ ProfileTier tier = ProfileTier::Laptop;+ std::string reason; // why this tier, in words (Preferences > Performance)+ PerformanceSettings settings; // the tier's settings with the overrides applied+ PerformanceSettings automatic; // before the overrides+ ProfileOverrides overrides;+};++// Maps what was detected and measured to a tier and its settings. Deterministic: the same inputs give the same+// profile. With nothing measured (skipped, or no GPU numbers) it falls back to the memory sizes and the probe's+// GPU kind, conservatively.+HardwareProfile mapProfile(const HardwareInfo& hardware, const Calibration& calibration,+ const ProfileOverrides& overrides = {});+// Applies `overrides` to `automatic` (and a tier override re-maps first). Used by mapProfile.+PerformanceSettings applyOverrides(const PerformanceSettings& automatic, const ProfileOverrides& overrides);+// The settings a tier gives for this hardware and calibration (mapProfile's second half).+PerformanceSettings settingsForTier(ProfileTier tier, const HardwareInfo& hardware, const Calibration& calibration);++// --- Cache (<config dir>/hardware_profile.json) ---+constexpr int kHardwareProfileCacheVersion = 1;+std::string hardwareProfilePath(); // <app data dir>/hardware_profile.json ("" if there is none)+// The profile's file contents (JSON object with "cache_version") and back. fromJson returns false for a file of+// another cache version or a broken one.+Json hardwareProfileToJson(const HardwareProfile& profile);+bool hardwareProfileFromJson(const Json& j, HardwareProfile& out);+bool loadHardwareProfile(const std::string& path, HardwareProfile& out);+bool saveHardwareProfile(const std::string& path, const HardwareProfile& profile, std::string& error);+// The cached profile no longer fits this computer: the GPU's vendor, renderer or driver string or the app version+// changed (or nothing is cached). `current` needs only the GL strings and appVersion.+bool needsRecalibration(const HardwareProfile* cached, const HardwareInfo& current);+// Why needsRecalibration said so, for the log ("first launch", "GPU changed", "driver changed", "new version").+std::string recalibrationReason(const HardwareProfile* cached, const HardwareInfo& current);++// --- JSON output (sculptforge --calibrate, the calibrate / performance_profile commands) ---+constexpr const char* kCalibrationSchema = "sculptforge.calibration/1";+Json calibrationJson(const HardwareProfile& profile);+// Checks `j` has every field of kCalibrationSchema with the right types; `error` names the first problem.+bool validateCalibrationJson(const Json& j, std::string& error);++// --- CPU benchmarks (deterministic work, median of `runs`) ---+double measureMemoryBandwidthGBps(int runs = 5);+// Standard brush dabs on a generated sphere of about `triangles` triangles; returns ms per dab (median of runs)+// and the vertices one dab moved.+double measureDabMs(size_t triangles, int runs, int dabsPerRun, double* verticesPerDab = nullptr);+// The CPU half of calibration: memory bandwidth and dab cost into `out` (GPU fields untouched).+void calibrateCpu(Calibration& out, bool quick = false);++// --- The profile in effect (read by the renderer, the governor and micromesh) ---+// Thread-safe snapshot of the current settings. Before any profile is applied, the defaults of a Laptop with+// nothing measured.+PerformanceSettings currentPerformanceSettings();+void setCurrentPerformanceSettings(const PerformanceSettings& settings);+// Bumped by every setCurrentPerformanceSettings (e.g. the set_performance_override command): the app re-reads the+// cached profile when it changes.+uint64_t performanceSettingsRevision();+// The governed render budget (the frame governor writes it every adjustment; renderers read it every frame).+// Micromesh (feat/micromesh) amplifies displacement only up to this many triangles per frame; see+// docs/performance.md, "Render triangle budget".+uint64_t renderTriangleBudget();+uint64_t motionProxyThreshold();+void setGovernedBudgets(uint64_t renderTriangles, uint64_t proxyThreshold);++// The app installs a full calibrator (with the GPU) for the calibrate command; sculptforge-cli has none and+// calibrates the CPU only (the GPU numbers come from the cache).+using GpuCalibrator = std::function<bool(HardwareProfile& out, std::string& error)>;+void setGpuCalibrator(GpuCalibrator calibrator);++// performance_profile, calibrate, set_performance_override (Commands.cpp registers them).+void registerHardwareProfileCommands(CommandRegistry& registry);++// Numbers for people: "12.5M", "3.2 GB".+std::string formatTriangles(uint64_t triangles);+std::string formatMegabytes(uint64_t mb);++} // namespace sfdiff --git a/tests/test_hardware_profile.cpp b/tests/test_hardware_profile.cppnew file mode 100644index 00000000..7a8c52bb--- /dev/null+++ b/tests/test_hardware_profile.cpp@@ -0,0 +1,616 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Hardware profile (core/HardwareProfile.h) and the adaptive frame governor (core/FrameGovernor.h): profile+// mapping from synthetic measurements, cache invalidation, the JSON schema, governor convergence and hysteresis+// on synthetic frame-time traces. Timing checks of the real CPU benchmarks run only with SF_BENCH_LIMITS=1.+#include "TestHarness.h"++#include "core/Commands.h"+#include "core/FrameGovernor.h"+#include "core/HardwareProfile.h"++#include <cmath>+#include <cstdlib>+#include <filesystem>+#include <fstream>++using namespace sf;++namespace {++HardwareInfo machine(const std::string& vendor, const std::string& renderer, uint64_t vramMB, uint64_t ramMB, int threads = 12) {+ HardwareInfo h;+ h.glVendor = vendor;+ h.glRenderer = renderer;+ h.glVersion = "4.6.0 test";+ h.gpuKind = classifyGpu(vendor, renderer);+ h.vramMB = vramMB;+ h.ramMB = ramMB;+ h.cpuThreads = threads;+ h.maxTextureSize = 16384;+ h.appVersion = "9.9.9";+ h.os = "TestOS";+ return h;+}++Calibration measured(double triM, double uploadGBps = 10.0, double dabMs = 0.5, double memGBps = 20.0) {+ Calibration c;+ c.trianglesPerSecondM = triM;+ c.uploadGBps = uploadGBps;+ c.dabMs = dabMs;+ c.dabVertices = 4000;+ c.memoryGBps = memGBps;+ c.runs = 5;+ c.durationMs = 2000;+ return c;+}++bool sameSettings(const PerformanceSettings& a, const PerformanceSettings& b) {+ return a.renderTriangleBudget == b.renderTriangleBudget && a.motionProxyThreshold == b.motionProxyThreshold &&+ a.vramBudgetMB == b.vramBudgetMB && a.uploadBudgetMBPerFrame == b.uploadBudgetMBPerFrame &&+ a.maxTextureSize == b.maxTextureSize && a.maxSubdivisionTriangles == b.maxSubdivisionTriangles &&+ a.microTriangleLimit == b.microTriangleLimit && a.threads == b.threads && a.targetFps == b.targetFps;+}++// Points the per-user data folder (appDataDir) at a fresh temporary one while a test runs.+struct IsolatedDataDir {+ std::string dir, oldXdg, oldHome, oldAppData;+ explicit IsolatedDataDir(const char* name) {+ dir = tempPath(name);+ std::error_code ec;+ std::filesystem::remove_all(dir, ec);+ std::filesystem::create_directories(dir, ec);+ auto get = [](const char* k) { const char* v = std::getenv(k); return v ? std::string(v) : std::string(); };+ oldXdg = get("XDG_DATA_HOME");+ oldHome = get("HOME");+ oldAppData = get("APPDATA");+#if defined(_WIN32)+ _putenv_s("APPDATA", dir.c_str());+#else+ setenv("XDG_DATA_HOME", dir.c_str(), 1);+#if defined(__APPLE__)+ setenv("HOME", dir.c_str(), 1);+#endif+#endif+ }+ ~IsolatedDataDir() {+#if defined(_WIN32)+ _putenv_s("APPDATA", oldAppData.c_str());+#else+ if (oldXdg.empty()) unsetenv("XDG_DATA_HOME");+ else setenv("XDG_DATA_HOME", oldXdg.c_str(), 1);+#if defined(__APPLE__)+ setenv("HOME", oldHome.c_str(), 1);+#endif+#endif+ std::error_code ec;+ std::filesystem::remove_all(dir, ec);+ }+};++// A tiny deterministic noise source for frame-time traces.+struct Lcg {+ uint32_t s = 12345;+ double next() { // [-1, 1)+ s = s * 1664525u + 1013904223u;+ return double(s >> 8) / double(1u << 23) - 1.0;+ }+};++} // namespace++TEST(hw_classify_gpu) {+ CHECK(classifyGpu("Mesa", "llvmpipe (LLVM 19.1.0, 256 bits)") == GpuKind::Software);+ CHECK(classifyGpu("Microsoft Corporation", "GDI Generic") == GpuKind::Software);+ CHECK(classifyGpu("Google Inc.", "ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device))") == GpuKind::Software);+ CHECK(classifyGpu("Apple", "Apple M1 Pro") == GpuKind::Unified);+ CHECK(classifyGpu("Mesa", "Apple M1 Pro (G13S C0)") == GpuKind::Unified); // Asahi Linux+ CHECK(classifyGpu("NVIDIA Corporation", "NVIDIA GeForce RTX 4090/PCIe/SSE2") == GpuKind::Discrete);+ CHECK(classifyGpu("Intel", "Mesa Intel(R) UHD Graphics 620 (KBL GT2)") == GpuKind::Integrated);+ CHECK(classifyGpu("Intel", "Mesa Intel(R) Arc(tm) A770 Graphics (DG2)") == GpuKind::Discrete);+ CHECK(classifyGpu("AMD", "AMD Radeon RX 7900 XTX (radeonsi, navi31, LLVM 18.1.8, DRM 3.57)") == GpuKind::Discrete);+ CHECK(classifyGpu("AMD", "AMD Radeon 780M (radeonsi, gfx1103_r1, LLVM 18.1.8, DRM 3.57)") == GpuKind::Integrated);+ CHECK(classifyGpu("ATI Technologies Inc.", "AMD Radeon(TM) Graphics") == GpuKind::Integrated);+ CHECK(classifyGpu("", "") == GpuKind::Unknown);+}++TEST(hw_sysfs_vram) {+ const std::string root = tempPath("sf_hw_sysfs");+ std::error_code ec;+ std::filesystem::remove_all(root, ec);+ auto card = [&](const char* name, const char* vendor, const char* vram) {+ const auto dev = std::filesystem::path(root) / name / "device";+ std::filesystem::create_directories(dev, ec);+ std::ofstream(dev / "vendor") << vendor << "\n";+ if (vram) std::ofstream(dev / "mem_info_vram_total") << vram << "\n";+ };+ card("card0", "0x8086", nullptr); // Intel iGPU: no VRAM file+ card("card1", "0x1002", "17163091968"); // amdgpu, 16 GiB+ card("card1-DP-1", "0x1002", "1"); // a connector, not a card+ CHECK(sysfsVramMB("AMD", root) == 16368);+ CHECK(sysfsVramMB("Intel", root) == 0);+ CHECK(sysfsVramMB("", root) == 16368); // unknown vendor: any card that says+ CHECK(sysfsVramMB("AMD", root + "/missing") == 0);+ std::filesystem::remove_all(root, ec);+}++TEST(hw_profile_mapping) {+ // Software renderers are safe mode whatever they measure, with half the threads (llvmpipe draws on them too).+ {+ const HardwareProfile p = mapProfile(machine("Mesa", "llvmpipe (LLVM 19.1.0, 256 bits)", 0, 16384, 8), measured(40.0, 2.0));+ CHECK(p.tier == ProfileTier::Software);+ CHECK(p.settings.threads == 4);+ CHECK(p.settings.renderTriangleBudget <= 4'000'000);+ CHECK(p.settings.maxTextureSize <= 4096);+ }+ // A big discrete card on a big machine.+ {+ const HardwareProfile p = mapProfile(machine("NVIDIA Corporation", "NVIDIA GeForce RTX 4090/PCIe/SSE2", 24564, 65536, 32),+ measured(15000.0, 25.0, 0.2, 40.0));+ CHECK(p.tier == ProfileTier::Monster);+ CHECK(p.settings.renderTriangleBudget >= 100'000'000);+ CHECK(p.settings.vramBudgetMB == 24564 * 4 / 5);+ CHECK(p.settings.threads == 16); // the thread pool's limit+ CHECK(p.reason.find("Monster") != std::string::npos);+ CHECK(p.reason.find("RTX 4090") != std::string::npos);+ }+ // A mid card: measured as a workstation, its 8 GB keep it there.+ {+ const HardwareProfile p = mapProfile(machine("NVIDIA Corporation", "NVIDIA GeForce RTX 3070/PCIe/SSE2", 8192, 32768),+ measured(8000.0));+ CHECK(p.tier == ProfileTier::Workstation);+ CHECK(p.reason.find("capped by GPU memory") != std::string::npos);+ }+ // An integrated GPU on a 16 GB laptop.+ {+ const HardwareProfile p = mapProfile(machine("Intel", "Mesa Intel(R) Xe Graphics (TGL GT2)", 0, 16384, 8), measured(400.0, 4.0));+ CHECK(p.tier == ProfileTier::Laptop);+ CHECK(p.settings.vramBudgetMB == 8192); // shares half the RAM+ CHECK(p.settings.renderTriangleBudget >= 2'000'000 && p.settings.renderTriangleBudget <= 40'000'000);+ }+ // A fast GPU with little memory is capped.+ {+ const HardwareProfile p = mapProfile(machine("AMD", "AMD Radeon RX 6500 XT", 2048, 32768), measured(3000.0));+ CHECK(p.tier == ProfileTier::Laptop);+ CHECK(p.settings.maxTextureSize <= 8192);+ }+ // Unified memory: two thirds of the RAM for the GPU.+ {+ const HardwareProfile p = mapProfile(machine("Mesa", "Apple M1 Pro (G13S C0)", 0, 32768, 10), measured(2000.0));+ CHECK(p.hardware.gpuKind == GpuKind::Unified);+ CHECK(p.settings.vramBudgetMB == 32768 * 2 / 3);+ CHECK(p.tier == ProfileTier::Workstation);+ }+ // Measurements decide, not names: an unknown GPU that measures like software is safe mode.+ CHECK(mapProfile(machine("Weird", "Mystery GPU", 4096, 16384), measured(20.0)).tier == ProfileTier::Software);+ // Same measurements, a different (same-kind) name: the same profile.+ {+ const HardwareProfile a = mapProfile(machine("NVIDIA Corporation", "NVIDIA RTX A4000", 16384, 65536), measured(4000.0));+ const HardwareProfile b = mapProfile(machine("NVIDIA Corporation", "NVIDIA GeForce RTX 4070 Ti SUPER", 16384, 65536), measured(4000.0));+ CHECK(a.tier == b.tier);+ CHECK(sameSettings(a.settings, b.settings));+ }+ // Nothing measured (skipped): a guess from memory sizes, never above Workstation.+ {+ Calibration skipped;+ skipped.skipped = true;+ CHECK(mapProfile(machine("NVIDIA Corporation", "NVIDIA GeForce RTX 4090", 24564, 65536), skipped).tier == ProfileTier::Workstation);+ CHECK(mapProfile(machine("Intel", "Intel(R) UHD Graphics", 0, 8192), skipped).tier == ProfileTier::Laptop);+ }+ // Slow brushes or memory cap the tier.+ CHECK(mapProfile(machine("NVIDIA Corporation", "NVIDIA GeForce RTX 4090", 24564, 65536), measured(15000.0, 25.0, 5.0)).tier ==+ ProfileTier::Laptop);+ // Deterministic, and sane everywhere.+ for (double tri : {10.0, 100.0, 900.0, 1500.0, 4000.0, 6000.0, 30000.0}) {+ const HardwareInfo h = machine("NVIDIA Corporation", "NVIDIA GeForce RTX 4080", 16384, 65536);+ const HardwareProfile a = mapProfile(h, measured(tri)), b = mapProfile(h, measured(tri));+ CHECK(a.tier == b.tier && sameSettings(a.settings, b.settings));+ CHECK(a.settings.motionProxyThreshold >= 262'144);+ CHECK(a.settings.motionProxyThreshold >= a.settings.renderTriangleBudget);+ CHECK(a.settings.maxTextureSize <= h.maxTextureSize);+ CHECK(a.settings.maxSubdivisionTriangles >= 2'000'000);+ CHECK(a.settings.threads >= 1);+ CHECK(a.settings.targetFps == 60);+ }+ // Faster measurements never give a lower tier or budget.+ {+ const HardwareInfo h = machine("NVIDIA Corporation", "NVIDIA GeForce RTX 4090", 24564, 131072, 32);+ HardwareProfile prev = mapProfile(h, measured(30.0));+ for (double tri = 60.0; tri < 40000.0; tri *= 1.5) {+ const HardwareProfile p = mapProfile(h, measured(tri));+ CHECK(int(p.tier) >= int(prev.tier));+ CHECK(p.tier != prev.tier || p.settings.renderTriangleBudget >= prev.settings.renderTriangleBudget);+ prev = p;+ }+ }+}++TEST(hw_profile_overrides) {+ const HardwareInfo h = machine("NVIDIA Corporation", "NVIDIA GeForce RTX 3060", 12288, 32768);+ ProfileOverrides o;+ o.tier = "Laptop";+ o.renderTriangleBudget = 5'000'000;+ o.threads = 3;+ const HardwareProfile p = mapProfile(h, measured(3000.0), o);+ CHECK(p.tier == ProfileTier::Laptop);+ CHECK(p.reason.find("by hand") != std::string::npos);+ CHECK(p.settings.renderTriangleBudget == 5'000'000);+ CHECK(p.settings.motionProxyThreshold == 5'000'000); // follows the budget+ CHECK(p.settings.threads == 3);+ CHECK(p.automatic.renderTriangleBudget != 5'000'000 || p.automatic.threads != 3);+ CHECK(o.any());+ CHECK(!ProfileOverrides{}.any());+ // A tier name in any case, and the safe-mode alias.+ ProfileTier t;+ CHECK(tierFromName("monster", t) && t == ProfileTier::Monster);+ CHECK(tierFromName("llvmpipe", t) && t == ProfileTier::Software);+ CHECK(!tierFromName("fast", t));+}++TEST(hw_profile_cache_invalidation) {+ const std::string path = tempPath("sf_hw_profile_cache.json");+ std::error_code ec;+ std::filesystem::remove(path, ec);+ HardwareProfile missing;+ CHECK(!loadHardwareProfile(path, missing));++ const HardwareInfo h = machine("AMD", "AMD Radeon RX 7800 XT (radeonsi, navi32)", 16384, 32768);+ ProfileOverrides o;+ o.maxTextureSize = 4096;+ o.governor = false;+ const HardwareProfile p = mapProfile(h, measured(5000.0), o);+ std::string error;+ CHECK(saveHardwareProfile(path, p, error));+ HardwareProfile back;+ CHECK(loadHardwareProfile(path, back));+ CHECK(back.hardware.glRenderer == h.glRenderer);+ CHECK(back.tier == p.tier);+ CHECK(sameSettings(back.settings, p.settings));+ CHECK(back.overrides.maxTextureSize == 4096 && !back.overrides.governor); // overrides survive+ CHECK(back.calibration.trianglesPerSecondM == 5000.0);++ // Same GPU, driver and version: the cache holds.+ HardwareInfo now = h;+ CHECK(!needsRecalibration(&back, now));+ CHECK(recalibrationReason(&back, now).empty());+ // A different renderer string (a new GPU, or the same one on another driver stack) recalibrates.+ now.glRenderer = "AMD Radeon RX 7900 XTX (radeonsi, navi31)";+ CHECK(needsRecalibration(&back, now));+ CHECK(recalibrationReason(&back, now) == "GPU changed");+ now = h;+ now.glVendor = "NVIDIA Corporation";+ CHECK(recalibrationReason(&back, now) == "GPU changed");+ // A driver update changes GL_VERSION.+ now = h;+ now.glVersion = "4.6 (Core Profile) Mesa 26.0.1";+ CHECK(recalibrationReason(&back, now) == "driver changed");+ // A new app version.+ now = h;+ now.appVersion = "10.0.0";+ CHECK(recalibrationReason(&back, now) == "new version");+ // Nothing cached.+ CHECK(needsRecalibration(nullptr, h));+ CHECK(recalibrationReason(nullptr, h) == "first launch");+ // A CPU-only calibration (sculptforge-cli) is measured again once the app has a GPU.+ HardwareProfile cpuOnly = back;+ cpuOnly.calibration.cpuOnly = true;+ CHECK(recalibrationReason(&cpuOnly, h) == "GPU not measured yet");+ HardwareInfo headless = h;+ headless.glRenderer.clear();+ headless.glVendor.clear();+ headless.glVersion.clear();+ cpuOnly.hardware.glRenderer.clear();+ cpuOnly.hardware.glVendor.clear();+ cpuOnly.hardware.glVersion.clear();+ CHECK(!needsRecalibration(&cpuOnly, headless));++ // Another cache version, or a broken file, is not used.+ {+ Json j = hardwareProfileToJson(p);+ j.set("cache_version", kHardwareProfileCacheVersion + 1);+ std::ofstream(path, std::ios::trunc) << j.dump();+ CHECK(!loadHardwareProfile(path, back));+ std::ofstream(path, std::ios::trunc) << "{ not json";+ CHECK(!loadHardwareProfile(path, back));+ }+ std::filesystem::remove(path, ec);+}++TEST(hw_calibration_json_schema) {+ HardwareInfo h = machine("Mesa", "Apple M1 Pro (G13S C0)", 0, 32768, 10);+ h.simd = {"neon"};+ h.simdBuild = "neon";+ h.vramSource = "unified (system RAM)";+ const HardwareProfile p = mapProfile(h, measured(2500.0));+ const Json j = calibrationJson(p);+ std::string error;+ CHECK(validateCalibrationJson(j, error));+ CHECK(error.empty());+ // Round trip through text, as `sculptforge --calibrate` prints it.+ Json parsed;+ CHECK(Json::parse(j.dump(true), parsed, error));+ CHECK(validateCalibrationJson(parsed, error));+ CHECK(parsed["schema"].asString() == kCalibrationSchema);+ CHECK(parsed["profile"].asString() == "Workstation");+ CHECK(parsed["hardware"]["gpu_kind"].asString() == "unified");+ CHECK(parsed["settings"]["render_triangle_budget"].asNumber() > 0);+ CHECK(!parsed["network"].asBool());+ // Broken documents are caught, naming the field.+ {+ Json bad = Json::object();+ for (const auto& [k, v] : parsed.members())+ if (k != "settings") bad.set(k, v);+ CHECK(!validateCalibrationJson(bad, error));+ CHECK(error.find("settings") != std::string::npos);+ }+ {+ Json bad = parsed;+ bad.set("network", true);+ CHECK(!validateCalibrationJson(bad, error));+ }+ {+ Json bad = parsed;+ bad.set("profile", "Turbo");+ CHECK(!validateCalibrationJson(bad, error));+ }+ {+ Json bad = parsed;+ Json m = parsed["measurements"];+ m.set("dab_ms", "fast");+ bad.set("measurements", m);+ CHECK(!validateCalibrationJson(bad, error));+ CHECK(error.find("dab_ms") != std::string::npos);+ }+ {+ Json bad = parsed;+ bad.set("schema", "sculptforge.calibration/0");+ CHECK(!validateCalibrationJson(bad, error));+ }+ CHECK(!validateCalibrationJson(Json(1.0), error));+}++TEST(hw_profile_commands) {+ IsolatedDataDir data("sf_hw_profile_commands");+ CommandRegistry registry;+ Document doc;+ // Before any calibration: the probe alone, as JSON.+ CommandResult r = registry.execute(doc, "performance_profile");+ CHECK(r.ok);+ Json j;+ std::string error;+ CHECK(Json::parse(r.message, j, error));+ CHECK(validateCalibrationJson(j, error));+ CHECK(j["hardware"]["cpu_threads"].asNumber() >= 1);+ CHECK(j["hardware"]["ram_mb"].asNumber() > 0);+ // Overrides are saved and come back.+ r = registry.execute(doc, "set_performance_override", {{"name", std::string("render_triangle_budget")}, {"value", std::string("12000000")}});+ CHECK(r.ok);+ CHECK(currentPerformanceSettings().renderTriangleBudget == 12'000'000);+ CHECK(renderTriangleBudget() == 12'000'000);+ r = registry.execute(doc, "set_performance_override", {{"name", std::string("tier")}, {"value", std::string("Monster")}});+ CHECK(r.ok);+ r = registry.execute(doc, "performance_profile");+ CHECK(Json::parse(r.message, j, error));+ CHECK(j["profile"].asString() == "Monster");+ CHECK(j["settings"]["render_triangle_budget"].asNumber() == 12'000'000);+ CHECK(j["overrides"]["tier"].asString() == "Monster");+ r = registry.execute(doc, "set_performance_override", {{"name", std::string("tier")}, {"value", std::string("auto")}});+ CHECK(r.ok);+ r = registry.execute(doc, "set_performance_override", {{"name", std::string("warp_drive")}, {"value", std::string("1")}});+ CHECK(!r.ok);+ r = registry.execute(doc, "set_performance_override", {{"name", std::string("tier")}, {"value", std::string("Turbo")}});+ CHECK(!r.ok);+ // The file lives in the (isolated) settings folder.+ CHECK(std::filesystem::exists(hardwareProfilePath()));+ CHECK(hardwareProfilePath().find(data.dir) == 0);+ // Put the process-wide settings back for the other tests.+ setCurrentPerformanceSettings(settingsForTier(ProfileTier::Laptop, HardwareInfo{}, Calibration{}));+}++TEST(hw_cpu_benchmarks) {+ // The CPU half of calibration runs and reports something plausible (quick: about a second).+ Calibration c;+ calibrateCpu(c, true);+ CHECK(c.memoryGBps > 0.0);+ CHECK(c.dabMs > 0.0);+ CHECK(c.dabVertices > 100.0);+ HardwareInfo h;+ probeSystem(h);+ CHECK(h.cpuThreads >= 1);+ CHECK(h.ramMB > 0);+ CHECK(!h.os.empty());+ CHECK(!h.simdBuild.empty());+ CHECK(!h.appVersion.empty());+ // Timing limits only on request (machines and CI runners differ): SF_BENCH_LIMITS=1.+ if (const char* v = std::getenv("SF_BENCH_LIMITS"); v && std::string(v) == "1") {+ std::printf(" memory %.1f GB/s, dab %.3f ms (%.0f vertices)\n", c.memoryGBps, c.dabMs, c.dabVertices);+ CHECK(c.memoryGBps > 2.0);+ CHECK(c.dabMs < 5.0);+ }+}++// --- Frame governor ---++namespace {++// A renderer whose frame cost grows with what it draws: overhead + drawn / rate (+ noise).+struct SyntheticView {+ uint64_t scene = 0;+ double overheadMs = 2.0, trianglesPerMs = 2'000'000.0;+ bool proxyStep = false; // today's renderer: over the threshold it draws the proxy (a quarter); else continuous LOD+ double noise = 0.0; // relative, uniform+ Lcg rng;+ FrameSample frame(const FrameGovernor& g) {+ FrameSample f;+ f.sceneTriangles = scene;+ if (proxyStep) {+ f.limited = scene >= g.proxyThreshold();+ f.drawnTriangles = f.limited ? scene / 4 : scene;+ } else {+ f.drawnTriangles = std::min(scene, g.budget());+ f.limited = f.drawnTriangles < scene;+ }+ const double cost = (overheadMs + double(f.drawnTriangles) / trianglesPerMs) * (1.0 + noise * rng.next());+ f.cpuMs = cost * 0.4;+ f.gpuMs = cost;+ f.moving = true;+ return f;+ }+ double cost(const FrameGovernor& g) {+ const double saved = noise;+ noise = 0.0;+ const FrameSample f = frame(g);+ noise = saved;+ return std::max(f.cpuMs, f.gpuMs);+ }+};++} // namespace++TEST(governor_converges_from_above) {+ GovernorConfig cfg; // 60 fps+ FrameGovernor g(cfg, 400'000'000);+ SyntheticView v;+ v.scene = 2'000'000'000; // more than any budget: continuous level of detail+ for (int i = 0; i < 2000; ++i) g.addFrame(v.frame(g));+ const double T = g.targetMs();+ CHECK(v.cost(g) <= T * cfg.highFraction);+ CHECK(v.cost(g) >= T * cfg.lowFraction * 0.8);+ // Settled: no change over another long run.+ const int before = g.adjustments();+ for (int i = 0; i < 1000; ++i) g.addFrame(v.frame(g));+ CHECK(g.adjustments() == before);+ CHECK(g.proxyThreshold() == g.budget());+}++TEST(governor_converges_from_below) {+ GovernorConfig cfg;+ FrameGovernor g(cfg, 1'000'000);+ SyntheticView v;+ v.scene = 2'000'000'000;+ v.trianglesPerMs = 5'000'000.0;+ for (int i = 0; i < 4000; ++i) g.addFrame(v.frame(g));+ const double T = g.targetMs();+ CHECK(v.cost(g) <= T * cfg.highFraction);+ CHECK(v.cost(g) >= T * cfg.lowFraction);+ CHECK(g.lastAction() == FrameGovernor::Action::Hold);+}++TEST(governor_hysteresis_with_noise) {+ GovernorConfig cfg;+ FrameGovernor g(cfg, 30'000'000);+ SyntheticView v;+ v.scene = 2'000'000'000;+ v.noise = 0.15;+ for (int i = 0; i < 2000; ++i) g.addFrame(v.frame(g));+ const int settled = g.adjustments();+ for (int i = 0; i < 5000; ++i) g.addFrame(v.frame(g));+ CHECK(g.adjustments() - settled <= 1); // noise inside the dead band changes nothing+ CHECK(v.cost(g) <= g.targetMs());+ // Dead band: a frame cost between 60% and 100% of the target holds the budget.+ FrameGovernor h(cfg, 10'000'000);+ for (double fraction : {0.62, 0.8, 0.98}) {+ for (int i = 0; i < 200; ++i) {+ FrameSample f;+ f.gpuMs = h.targetMs() * fraction;+ f.drawnTriangles = 10'000'000;+ f.sceneTriangles = 50'000'000;+ f.limited = true;+ h.addFrame(f);+ }+ }+ CHECK(h.budget() == 10'000'000);+ CHECK(h.adjustments() == 0);+ // Just over: it lowers; well under: it raises.+ for (int i = 0; i < 25; ++i) {+ FrameSample f;+ f.gpuMs = h.targetMs() * 1.1;+ f.drawnTriangles = 10'000'000;+ h.addFrame(f);+ }+ CHECK(h.budget() < 10'000'000);+ CHECK(h.lastAction() == FrameGovernor::Action::Lowered);+}++TEST(governor_motion_proxy_no_flapping) {+ // Today's renderer: the motion proxy draws a quarter of the scene. A scene too heavy to move in full at 60 fps+ // must settle on the proxy, not flip between proxy and full detail.+ GovernorConfig cfg;+ FrameGovernor g(cfg, 200'000'000);+ SyntheticView v;+ v.proxyStep = true;+ v.scene = 80'000'000;+ v.trianglesPerMs = 4'000'000.0; // full: 22 ms (too slow); proxy: 7 ms+ int flips = 0;+ bool lastLimited = false;+ for (int i = 0; i < 6000; ++i) {+ const FrameSample f = v.frame(g);+ if (i > 500 && f.limited != lastLimited) ++flips;+ lastLimited = f.limited;+ g.addFrame(f);+ }+ CHECK(lastLimited); // on the proxy+ CHECK(flips == 0); // and stays there+ CHECK(g.budget() < v.scene);+ // A scene light enough to move in full: the budget rises past it and the proxy switches off.+ FrameGovernor h(cfg, 2'000'000);+ v.scene = 20'000'000; // full: 7 ms+ for (int i = 0; i < 6000; ++i) h.addFrame(v.frame(h));+ CHECK(h.proxyThreshold() > v.scene);+}++TEST(governor_ignores_still_frames_and_hitches) {+ GovernorConfig cfg;+ FrameGovernor g(cfg, 10'000'000);+ for (int i = 0; i < 500; ++i) {+ FrameSample still;+ still.gpuMs = 100.0; // slow, but the view isn't moving: full detail regardless+ still.moving = false;+ still.drawnTriangles = 10'000'000;+ g.addFrame(still);+ FrameSample hitch;+ hitch.cpuMs = 900.0; // a file dialog+ hitch.drawnTriangles = 10'000'000;+ g.addFrame(hitch);+ }+ CHECK(g.budget() == 10'000'000);+ CHECK(g.decisions() == 0);+ // CPU time alone (no GPU timer queries) still drives it.+ for (int i = 0; i < 25; ++i) {+ FrameSample f;+ f.cpuMs = 40.0;+ f.gpuMs = -1.0;+ f.drawnTriangles = 10'000'000;+ g.addFrame(f);+ }+ CHECK(g.budget() < 10'000'000);+ // Bounds hold.+ GovernorConfig tight;+ tight.minBudget = 5'000'000;+ tight.maxBudget = 6'000'000;+ FrameGovernor b(tight, 100'000'000);+ CHECK(b.budget() == 6'000'000);+ for (int i = 0; i < 500; ++i) {+ FrameSample f;+ f.gpuMs = 200.0;+ f.drawnTriangles = 6'000'000;+ b.addFrame(f);+ }+ CHECK(b.budget() == 5'000'000);+}++TEST(governor_target_120) {+ GovernorConfig cfg;+ cfg.targetFps = 120;+ FrameGovernor g(cfg, 100'000'000);+ SyntheticView v;+ v.scene = 2'000'000'000;+ for (int i = 0; i < 3000; ++i) g.addFrame(v.frame(g));+ CHECK(v.cost(g) <= 1000.0 / 120.0);+ FrameGovernor g60(GovernorConfig{}, 100'000'000);+ for (int i = 0; i < 3000; ++i) g60.addFrame(v.frame(g60));+ CHECK(g.budget() < g60.budget()); // half the frame time, fewer triangles+ g60.setTargetFps(120);+ CHECK(std::abs(g60.targetMs() - 1000.0 / 120.0) < 1e-9);+}