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
Calibration in the app: OpenGL probe and GPU benchmarks, sculptforge --calibrate, Preferences > Performance profile section, frame governor wiring
islandmed2bf58378e697
diff --git a/CMakeLists.txt b/CMakeLists.txtindex dcc2ed8c..e647baed 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -207,6 +207,8 @@ if(SCULPTFORGE_BUILD_APP)${CMAKE_CURRENT_BINARY_DIR}/EmbeddedGuide.cppsrc/app/main.cppsrc/app/Bench.cpp+ src/app/Calibration.cpp+ src/app/PanelPerformanceProfile.cppsrc/app/CrashLog.cppsrc/app/App.cppsrc/app/Demo.cppdiff --git a/src/app/App.cpp b/src/app/App.cppindex 20b9c572..642482dc 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -1,6 +1,7 @@// SculptForge - open source digital sculpting// SPDX-License-Identifier: GPL-3.0-or-later#include "app/App.h"+#include "app/Calibration.h"#include "app/CrashLog.h"#include "ai/AiCommands.h"@@ -87,6 +88,7 @@ bool App::init(const AppOptions& options) {// 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");+ if (!headless && options.demo.empty()) applyCachedThreadCount(); // the hardware profile's threads, before any brush workif (!SDL_Init(SDL_INIT_VIDEO)) {SDL_Log("SDL_Init failed: %s", SDL_GetError());return false;@@ -274,6 +276,7 @@ bool App::init(const AppOptions& options) {std::snprintf(generatorCommand_, sizeof generatorCommand_, "%s",ai::defaultGeneratorCommand(std::string(base) + cliName).c_str());}+ initHardwareProfile(); // the cached hardware profile, or calibration over the first frames (PanelPerformanceProfile.cpp)return true;}@@ -282,6 +285,7 @@ void App::shutdown() {if (blenderInitialised_) writeBridgeHeartbeat(blenderExchangeRoot(), true); // the add-on starts a new onespaceMouseClose();+ shutdownHardwareProfile(); // its timer queries need the GL contextif (refTexture_) gl::DeleteTextures(1, &refTexture_);gallery_.reset(); // its preview textures need the GL contextthumbs_.clear();@@ -794,11 +798,13 @@ int App::run() {// spaceMouseMoving() is true and a loop that waits for events when idle must keep drawing.updateSpaceMouse(dt);+ hardwareProfileFrameBegin(); // the frame governor's CPU and GPU timingImGui_ImplOpenGL3_NewFrame();ImGui_ImplSDL3_NewFrame();keepImGuiOnPen();ImGui::NewFrame();drawUi();+ drawHardwareProfileOverlay();ImGui::Render();const auto syncStart = std::chrono::steady_clock::now();@@ -809,6 +815,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());+ hardwareProfileFrameEnd();SDL_GL_SwapWindow(window_);++framesDrawn;if (sm.started && !sm.moving) { // the press is on screen: start moving round the circlediff --git a/src/app/App.h b/src/app/App.hindex fffafe32..b9f887ee 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -541,6 +541,8 @@ private:int framesStill = 0; // frames since the view last movedbool fastNow = false; // this frame draws without antialiasing (fast navigation)bool proxyNow = false; // this frame draws big meshes' motion proxy (fast navigation)+ bool movingNow = false; // the view moved in the last few frames (the frame governor counts these)+ size_t sceneTriangles = 0; // visible triangles in full detail, last frameint samplesWanted = 0; // viewSamples() for the last frameint samplesUsed = 0; // what the renderer managed last frame (fewer when out of memory)double strokeSyncMs = 0.0; // upload time summed over the open stroke's frames@@ -550,6 +552,20 @@ private:int lastStrokeFrames = 0;bool gpuOutOfMemory = false;} perf_;+ // Hardware profile (PanelPerformanceProfile.cpp; app/Calibration.h, core/HardwareProfile.h, core/FrameGovernor.h):+ // calibrates on first launch and when the GPU, driver or version changes; the profile section of Preferences >+ // Performance; the adaptive frame governor, fed every frame between FrameBegin and FrameEnd.+ void initHardwareProfile();+ void shutdownHardwareProfile();+ void hardwareProfileFrameBegin();+ void hardwareProfileFrameEnd(); // before the swap: feeds the governor, runs a calibration step+ void drawHardwareProfileOverlay(); // calibration progress over the first frames (Esc skips)+ void drawPerformanceProfileSection();+ void registerPerformanceProfileUiActions();+ bool hardwareProfileGoverns() const; // the profile's motion proxy threshold applies (else the fixed default)+ void applyHardwareProfile(const struct HardwareProfile& profile, bool announce);+ void finishCalibration();+ std::shared_ptr<struct HwProfileUi> hwProfile_;// Splats > Make sculptable (PanelSculptable.cpp, core/Sculptable.h): splat capture -> sculptable SubTool on a// worker thread; the crop box and the face landmark review in the viewport.void registerSculptableUiActions();diff --git a/src/app/Calibration.cpp b/src/app/Calibration.cppnew file mode 100644index 00000000..cf3c3ad4--- /dev/null+++ b/src/app/Calibration.cpp@@ -0,0 +1,623 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "app/Calibration.h"++#include "core/ThreadPool.h"+#include "render/GL.h"++#include <SDL3/SDL.h>++#include <algorithm>+#include <chrono>+#include <cmath>+#include <cstdio>+#include <cstring>+#include <vector>++#if defined(_WIN32)+#define WIN32_LEAN_AND_MEAN+#include <windows.h>+#include <dxgi.h>+#elif defined(__APPLE__)+#include <dlfcn.h>+#endif++namespace sf {++namespace {++using Clock = std::chrono::steady_clock;+double nowMs() { return std::chrono::duration<double, std::milli>(Clock::now().time_since_epoch()).count(); }++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]);+}++#if defined(_WIN32)+std::string lower(std::string s) {+ std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); });+ return s;+}+#endif++// --- The few GL entry points beyond render/GL.h, loaded here so this module stays self-contained ---+constexpr GLenum kGL_VENDOR = 0x1F00, kGL_EXTENSIONS = 0x1F03, kGL_NUM_EXTENSIONS = 0x821D, kGL_MAX_TEXTURE_SIZE = 0x0D33;+constexpr GLenum kGL_TIME_ELAPSED = 0x88BF, kGL_QUERY_RESULT = 0x8866;+constexpr GLenum kGL_FRAMEBUFFER_BINDING = 0x8CA6, kGL_VIEWPORT = 0x0BA2, kGL_CURRENT_PROGRAM = 0x8B8D,+ kGL_VERTEX_ARRAY_BINDING = 0x85B5, kGL_ARRAY_BUFFER_BINDING = 0x8894, kGL_DEPTH_FUNC = 0x0B74,+ kGL_DEPTH_WRITEMASK = 0x0B72, kGL_RENDERBUFFER_BINDING = 0x8CA7;+// GL_NVX_gpu_memory_info (KB), GL_ATI_meminfo (KB, 4 values: the first is the pool's free total).+constexpr GLenum kGL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX = 0x9047, kGL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX = 0x9049;+constexpr GLenum kGL_TEXTURE_FREE_MEMORY_ATI = 0x87FC;+// GLX_MESA_query_renderer.+constexpr int kGLX_RENDERER_ACCELERATED_MESA = 0x8186, kGLX_RENDERER_VIDEO_MEMORY_MESA = 0x8187,+ kGLX_RENDERER_UNIFIED_MEMORY_ARCHITECTURE_MESA = 0x8188;++struct GlExtra {+ const GLubyte*(SF_GLAPI* GetStringi)(GLenum, GLuint) = nullptr;+ void(SF_GLAPI* GenQueries)(GLsizei, GLuint*) = nullptr;+ void(SF_GLAPI* DeleteQueries)(GLsizei, const GLuint*) = nullptr;+ void(SF_GLAPI* BeginQuery)(GLenum, GLuint) = nullptr;+ void(SF_GLAPI* EndQuery)(GLenum) = nullptr;+ void(SF_GLAPI* GetQueryObjectui64v)(GLuint, GLenum, uint64_t*) = nullptr;+ void(SF_GLAPI* DrawElementsInstanced)(GLenum, GLsizei, GLenum, const void*, GLsizei) = nullptr;+ bool timer() const { return GenQueries && DeleteQueries && BeginQuery && EndQuery && GetQueryObjectui64v; }+};++GlExtra loadExtra() {+ GlExtra e;+ auto get = [](const char* name) { return reinterpret_cast<void*>(SDL_GL_GetProcAddress(name)); };+ e.GetStringi = reinterpret_cast<decltype(e.GetStringi)>(get("glGetStringi"));+ e.GenQueries = reinterpret_cast<decltype(e.GenQueries)>(get("glGenQueries"));+ e.DeleteQueries = reinterpret_cast<decltype(e.DeleteQueries)>(get("glDeleteQueries"));+ e.BeginQuery = reinterpret_cast<decltype(e.BeginQuery)>(get("glBeginQuery"));+ e.EndQuery = reinterpret_cast<decltype(e.EndQuery)>(get("glEndQuery"));+ e.GetQueryObjectui64v = reinterpret_cast<decltype(e.GetQueryObjectui64v)>(get("glGetQueryObjectui64v"));+ e.DrawElementsInstanced = reinterpret_cast<decltype(e.DrawElementsInstanced)>(get("glDrawElementsInstanced"));+ return e;+}++std::string glString(GLenum name) {+ const GLubyte* s = gl::GetString(name);+ return s ? reinterpret_cast<const char*>(s) : "";+}++bool hasExtension(const GlExtra& e, const char* name) {+ if (!e.GetStringi) return false;+ GLint n = 0;+ gl::GetIntegerv(kGL_NUM_EXTENSIONS, &n);+ for (GLint i = 0; i < n; ++i) {+ const GLubyte* s = e.GetStringi(kGL_EXTENSIONS, GLuint(i));+ if (s && std::strcmp(reinterpret_cast<const char*>(s), name) == 0) return true;+ }+ return false;+}++#if defined(_WIN32)+// The adapter DXGI lists for the GL vendor, with the most dedicated memory (MB); 0 if none.+uint64_t dxgiVramMB(const std::string& glVendor, uint64_t* sharedMB) {+ const std::string v = lower(glVendor);+ UINT want = 0;+ if (v.find("nvidia") != std::string::npos) want = 0x10DE;+ else if (v.find("amd") != std::string::npos || v.find("ati") != std::string::npos) want = 0x1002;+ else if (v.find("intel") != std::string::npos) want = 0x8086;+ else if (v.find("qualcomm") != std::string::npos) want = 0x5143;+ HMODULE dll = LoadLibraryW(L"dxgi.dll");+ if (!dll) return 0;+ using CreateFactory = HRESULT(WINAPI*)(REFIID, void**);+ auto create = reinterpret_cast<CreateFactory>(reinterpret_cast<void*>(GetProcAddress(dll, "CreateDXGIFactory1")));+ uint64_t best = 0;+ IDXGIFactory1* factory = nullptr;+ if (create && SUCCEEDED(create(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&factory))) && factory) {+ IDXGIAdapter1* adapter = nullptr;+ for (UINT i = 0; factory->EnumAdapters1(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i) {+ DXGI_ADAPTER_DESC1 d{};+ if (SUCCEEDED(adapter->GetDesc1(&d)) && !(d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && (want == 0 || d.VendorId == want)) {+ const uint64_t mb = uint64_t(d.DedicatedVideoMemory) >> 20;+ if (mb >= best) {+ best = mb;+ if (sharedMB) *sharedMB = uint64_t(d.SharedSystemMemory) >> 20;+ }+ }+ adapter->Release();+ }+ factory->Release();+ }+ FreeLibrary(dll);+ return best;+}+#endif++#if defined(__APPLE__)+// CGL's video memory for the context's current renderer (MB); 0 if CGL doesn't say. Looked up at run time+// (OpenGL.framework is loaded with the context).+uint64_t cglVramMB() {+ using GetCurrentContext = void* (*)();+ using GetParameter = int (*)(void*, int, int*);+ using QueryRendererInfo = int (*)(unsigned, void**, int*);+ using DescribeRenderer = int (*)(void*, int, int, int*);+ using DestroyRendererInfo = int (*)(void*);+ auto current = reinterpret_cast<GetCurrentContext>(dlsym(RTLD_DEFAULT, "CGLGetCurrentContext"));+ auto getParameter = reinterpret_cast<GetParameter>(dlsym(RTLD_DEFAULT, "CGLGetParameter"));+ auto query = reinterpret_cast<QueryRendererInfo>(dlsym(RTLD_DEFAULT, "CGLQueryRendererInfo"));+ auto describe = reinterpret_cast<DescribeRenderer>(dlsym(RTLD_DEFAULT, "CGLDescribeRenderer"));+ auto destroy = reinterpret_cast<DestroyRendererInfo>(dlsym(RTLD_DEFAULT, "CGLDestroyRendererInfo"));+ if (!current || !getParameter || !query || !describe || !destroy) return 0;+ constexpr int kCGLCPCurrentRendererID = 309, kCGLRPRendererID = 70, kCGLRPVideoMemoryMegabytes = 131;+ void* ctx = current();+ int rendererId = 0;+ if (!ctx || getParameter(ctx, kCGLCPCurrentRendererID, &rendererId) != 0) return 0;+ void* info = nullptr;+ int count = 0;+ if (query(0xFFFFFFFFu, &info, &count) != 0 || !info) return 0;+ uint64_t mb = 0;+ for (int i = 0; i < count; ++i) {+ int id = 0, mem = 0;+ if (describe(info, i, kCGLRPRendererID, &id) != 0) continue;+ if ((id & 0xFFFFFF00) != (rendererId & 0xFFFFFF00)) continue;+ if (describe(info, i, kCGLRPVideoMemoryMegabytes, &mem) == 0 && mem > 0) mb = std::max<uint64_t>(mb, uint64_t(mem));+ }+ destroy(info);+ return mb;+}+#endif++// Saves the GL state the benchmarks change and puts it back.+struct GlStateGuard {+ GLint fbo = 0, viewport[4] = {}, program = 0, vao = 0, arrayBuffer = 0, depthFunc = 0, depthMask = 1, rb = 0;+ GLint depthTest = 0, blend = 0, cull = 0, scissor = 0;+ GlStateGuard() {+ gl::GetIntegerv(kGL_FRAMEBUFFER_BINDING, &fbo);+ gl::GetIntegerv(kGL_VIEWPORT, viewport);+ gl::GetIntegerv(kGL_CURRENT_PROGRAM, &program);+ gl::GetIntegerv(kGL_VERTEX_ARRAY_BINDING, &vao);+ gl::GetIntegerv(kGL_ARRAY_BUFFER_BINDING, &arrayBuffer);+ gl::GetIntegerv(kGL_DEPTH_FUNC, &depthFunc);+ gl::GetIntegerv(kGL_DEPTH_WRITEMASK, &depthMask);+ gl::GetIntegerv(kGL_RENDERBUFFER_BINDING, &rb);+ gl::GetIntegerv(GL_DEPTH_TEST, &depthTest);+ gl::GetIntegerv(GL_BLEND, &blend);+ gl::GetIntegerv(GL_CULL_FACE, &cull);+ gl::GetIntegerv(GL_SCISSOR_TEST, &scissor);+ }+ ~GlStateGuard() {+ gl::BindFramebuffer(GL_FRAMEBUFFER, GLuint(fbo));+ gl::Viewport(viewport[0], viewport[1], viewport[2], viewport[3]);+ gl::UseProgram(GLuint(program));+ gl::BindVertexArray(GLuint(vao));+ gl::BindBuffer(GL_ARRAY_BUFFER, GLuint(arrayBuffer));+ gl::BindRenderbuffer(GL_RENDERBUFFER, GLuint(rb));+ gl::DepthFunc(GLenum(depthFunc));+ gl::DepthMask(GLboolean(depthMask ? GL_TRUE : GL_FALSE));+ auto set = [](GLenum cap, GLint on) { on ? gl::Enable(cap) : gl::Disable(cap); };+ set(GL_DEPTH_TEST, depthTest);+ set(GL_BLEND, blend);+ set(GL_CULL_FACE, cull);+ set(GL_SCISSOR_TEST, scissor);+ while (gl::GetError() != GL_NO_ERROR) {} // nothing the benchmarks caused should reach the app's checks+ }+};++const char* kVertexShader = R"(#version 330 core+layout(location = 0) in vec2 aPos;+uniform float uDepthStep;+out vec3 vNormal;+void main() {+ float k = float(gl_InstanceID);+ vec2 p = aPos * 2.0 - 1.0 + vec2(k * 0.0007, k * 0.0003);+ float a = aPos.x * 40.0 + k, b = aPos.y * 40.0;+ vNormal = normalize(vec3(cos(a), sin(b), 1.0));+ gl_Position = vec4(p, 0.9 - k * uDepthStep + sin(a) * cos(b) * 0.0005, 1.0);+}+)";+const char* kFragmentShader = R"(#version 330 core+in vec3 vNormal;+out vec4 color;+void main() {+ float d = max(dot(normalize(vNormal), normalize(vec3(0.3, 0.5, 0.8))), 0.0);+ color = vec4(vec3(0.2 + 0.8 * d), 1.0);+}+)";++GLuint compile(GLenum type, const char* src) {+ GLuint s = gl::CreateShader(type);+ gl::ShaderSource(s, 1, &src, nullptr);+ gl::CompileShader(s);+ GLint ok = 0;+ gl::GetShaderiv(s, GL_COMPILE_STATUS, &ok);+ if (!ok) {+ char log[512] = {};+ gl::GetShaderInfoLog(s, sizeof log, nullptr, log);+ SDL_Log("Calibration shader: %s", log);+ gl::DeleteShader(s);+ return 0;+ }+ return s;+}++// Triangle throughput: a dense grid (about 4 pixels per triangle, like a sculpt seen whole) drawn instanced into+// a 1024 x 1024 offscreen target, every instance in front of the last (all of it shaded). Million triangles/s.+double measureTriangles(const GlExtra& e, bool quick, bool& usedTimer) {+ usedTimer = false;+ if (!e.DrawElementsInstanced) return 0.0;+ GlStateGuard guard;+ constexpr int kSize = 1024, kGx = 512, kGy = 256;+ constexpr GLsizei kTriangles = kGx * kGy * 2;+ GLuint fbo = 0, rbs[2] = {}, vao = 0, buffers[2] = {}, program = 0;+ gl::GenFramebuffers(1, &fbo);+ gl::GenRenderbuffers(2, rbs);+ gl::BindRenderbuffer(GL_RENDERBUFFER, rbs[0]);+ gl::RenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, kSize, kSize);+ gl::BindRenderbuffer(GL_RENDERBUFFER, rbs[1]);+ gl::RenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, kSize, kSize);+ gl::BindFramebuffer(GL_FRAMEBUFFER, fbo);+ gl::FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbs[0]);+ gl::FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbs[1]);+ double result = 0.0;+ const GLuint vs = compile(GL_VERTEX_SHADER, kVertexShader), fs = compile(GL_FRAGMENT_SHADER, kFragmentShader);+ if (vs && fs && gl::CheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE) {+ program = gl::CreateProgram();+ gl::AttachShader(program, vs);+ gl::AttachShader(program, fs);+ gl::LinkProgram(program);+ GLint linked = 0;+ gl::GetProgramiv(program, GL_LINK_STATUS, &linked);+ std::vector<float> verts;+ verts.reserve(size_t(kGx + 1) * (kGy + 1) * 2);+ for (int y = 0; y <= kGy; ++y)+ for (int x = 0; x <= kGx; ++x) {+ verts.push_back(float(x) / kGx);+ verts.push_back(float(y) / kGy);+ }+ std::vector<uint32_t> indices;+ indices.reserve(size_t(kTriangles) * 3);+ for (int y = 0; y < kGy; ++y)+ for (int x = 0; x < kGx; ++x) {+ const uint32_t a = uint32_t(y * (kGx + 1) + x), b = a + 1, c = a + uint32_t(kGx + 1), d = c + 1;+ indices.insert(indices.end(), {a, b, d, a, d, c});+ }+ gl::GenVertexArrays(1, &vao);+ gl::BindVertexArray(vao);+ gl::GenBuffers(2, buffers);+ gl::BindBuffer(GL_ARRAY_BUFFER, buffers[0]);+ gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(verts.size() * sizeof(float)), verts.data(), GL_STATIC_DRAW);+ gl::EnableVertexAttribArray(0);+ gl::VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);+ gl::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[1]);+ gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr(indices.size() * sizeof(uint32_t)), indices.data(), GL_STATIC_DRAW);+ if (linked) {+ gl::UseProgram(program);+ gl::Viewport(0, 0, kSize, kSize);+ gl::Disable(GL_BLEND);+ gl::Disable(GL_CULL_FACE);+ gl::Disable(GL_SCISSOR_TEST);+ gl::Enable(GL_DEPTH_TEST);+ gl::DepthFunc(GL_LEQUAL);+ gl::DepthMask(GL_TRUE);+ const GLint depthStep = gl::GetUniformLocation(program, "uDepthStep");+ GLuint query = 0;+ const bool timer = e.timer();+ if (timer) e.GenQueries(1, &query);+ // One timed draw of `instances` grids: milliseconds on the GPU (timer query) or the CPU clock.+ auto run = [&](int instances, bool& gpuTimed) {+ gl::ClearColor(0.1f, 0.1f, 0.1f, 1.0f);+ gl::Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);+ gl::Uniform1f(depthStep, 0.8f / float(std::max(instances, 1)));+ gl::Finish();+ const double t0 = nowMs();+ if (timer) e.BeginQuery(kGL_TIME_ELAPSED, query);+ e.DrawElementsInstanced(GL_TRIANGLES, kTriangles * 3, GL_UNSIGNED_INT, nullptr, instances);+ if (timer) e.EndQuery(kGL_TIME_ELAPSED);+ gl::Finish();+ const double cpu = nowMs() - t0;+ gpuTimed = false;+ if (timer) {+ uint64_t ns = 0;+ e.GetQueryObjectui64v(query, kGL_QUERY_RESULT, &ns);+ if (ns > 0 && double(ns) * 1e-6 <= cpu * 1.5 + 1.0) { // a plausible GPU time+ gpuTimed = true;+ return double(ns) * 1e-6;+ }+ }+ return cpu;+ };+ bool gpuTimed = false;+ run(1, gpuTimed); // warm up: shader compilation, buffer residency+ const double one = std::max(0.05, run(1, gpuTimed));+ // Enough instances for about 25 ms a run (15 quick), so timer resolution and fixed costs don't matter.+ const int instances = std::clamp(int(std::lround((quick ? 15.0 : 25.0) / one)), 1, 256);+ std::vector<double> rates;+ int timed = 0;+ for (int i = 0; i < (quick ? 3 : 5); ++i) {+ const double ms = run(instances, gpuTimed);+ timed += gpuTimed ? 1 : 0;+ if (ms > 0.0) rates.push_back(double(kTriangles) * instances / (ms * 1e-3) / 1e6);+ }+ usedTimer = timed > 0;+ result = median(rates);+ if (query) e.DeleteQueries(1, &query);+ }+ }+ if (vs) gl::DeleteShader(vs);+ if (fs) gl::DeleteShader(fs);+ if (program) gl::DeleteProgram(program);+ gl::DeleteBuffers(2, buffers);+ gl::DeleteVertexArrays(1, &vao);+ gl::DeleteFramebuffers(1, &fbo);+ gl::DeleteRenderbuffers(2, rbs);+ return result;+}++// Upload bandwidth: glBufferSubData of a whole buffer (as the renderer sends changed vertices), waited for. GB/s.+double measureUpload(bool quick) {+ GlStateGuard guard;+ const size_t bytes = (quick ? size_t(16) : size_t(32)) << 20;+ std::vector<uint8_t> data(bytes);+ for (size_t i = 0; i < bytes; ++i) data[i] = uint8_t(i * 2654435761u >> 24);+ GLuint buffer = 0;+ gl::GenBuffers(1, &buffer);+ gl::BindBuffer(GL_ARRAY_BUFFER, buffer);+ gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(bytes), nullptr, GL_DYNAMIC_DRAW);+ gl::BufferSubData(GL_ARRAY_BUFFER, 0, GLsizeiptr(bytes), data.data()); // first touch allocates+ gl::Finish();+ std::vector<double> rates;+ for (int i = 0; i < (quick ? 3 : 5); ++i) {+ data[size_t(i) * 7919] ^= 0xFF;+ const double t0 = nowMs();+ gl::BufferSubData(GL_ARRAY_BUFFER, 0, GLsizeiptr(bytes), data.data());+ gl::Finish();+ const double ms = nowMs() - t0;+ if (ms > 0.0) rates.push_back(double(bytes) / (ms * 1e-3) / 1e9);+ }+ gl::DeleteBuffers(1, &buffer);+ return median(rates);+}++} // namespace++void probeHardware(HardwareInfo& info) {+ probeSystem(info);+ const GlExtra e = loadExtra();+ info.glVendor = glString(kGL_VENDOR);+ info.glRenderer = glString(GL_RENDERER);+ info.glVersion = glString(GL_VERSION);+ info.gpuKind = classifyGpu(info.glVendor, info.glRenderer);+ GLint maxTexture = 0;+ gl::GetIntegerv(kGL_MAX_TEXTURE_SIZE, &maxTexture);+ info.maxTextureSize = maxTexture;+ info.timerQuery = e.timer();+ info.vramMB = info.vramAvailableMB = 0;+ info.vramSource = "none";+ while (gl::GetError() != GL_NO_ERROR) {}+ // NVIDIA (and Mesa's radeonsi): dedicated and free video memory.+ if (hasExtension(e, "GL_NVX_gpu_memory_info")) {+ GLint dedicated = 0, available = 0;+ gl::GetIntegerv(kGL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &dedicated);+ gl::GetIntegerv(kGL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &available);+ if (gl::GetError() == GL_NO_ERROR && dedicated > 0) {+ info.vramMB = uint64_t(dedicated) >> 10;+ info.vramAvailableMB = uint64_t(std::max(available, 0)) >> 10;+ info.vramSource = "GL_NVX_gpu_memory_info";+ }+ }+ // AMD: free memory only (no total).+ if (hasExtension(e, "GL_ATI_meminfo")) {+ GLint free[4] = {};+ gl::GetIntegerv(kGL_TEXTURE_FREE_MEMORY_ATI, free);+ if (gl::GetError() == GL_NO_ERROR && free[0] > 0 && info.vramAvailableMB == 0) {+ info.vramAvailableMB = uint64_t(free[0]) >> 10;+ if (info.vramSource == "none") info.vramSource = "GL_ATI_meminfo (free only)";+ }+ }+#if defined(__linux__) || defined(__FreeBSD__)+ // Mesa on X11 (GLX): video memory, unified memory and whether it's accelerated. Not on Wayland (EGL).+ const char* driver = SDL_GetCurrentVideoDriver();+ if (info.vramMB == 0 && driver && std::strcmp(driver, "x11") == 0 && !SDL_GetHintBoolean(SDL_HINT_VIDEO_FORCE_EGL, false)) {+ using QueryRenderer = int (*)(int, unsigned*);+ auto query = reinterpret_cast<QueryRenderer>(reinterpret_cast<void*>(SDL_GL_GetProcAddress("glXQueryCurrentRendererIntegerMESA")));+ unsigned value = 0;+ if (query && query(kGLX_RENDERER_VIDEO_MEMORY_MESA, &value) && value > 0) {+ info.vramMB = value;+ info.vramSource = "GLX_MESA_query_renderer";+ unsigned unified = 0, accelerated = 1;+ if (query(kGLX_RENDERER_UNIFIED_MEMORY_ARCHITECTURE_MESA, &unified) && unified &&+ (info.gpuKind == GpuKind::Discrete || info.gpuKind == GpuKind::Unknown))+ info.gpuKind = GpuKind::Integrated;+ if (query(kGLX_RENDERER_ACCELERATED_MESA, &accelerated) && !accelerated) info.gpuKind = GpuKind::Software;+ }+ }+ // amdgpu exposes its VRAM size in sysfs (works on Wayland too).+ if (info.vramMB == 0 && info.gpuKind != GpuKind::Software && info.gpuKind != GpuKind::Unified) {+ if (const uint64_t mb = sysfsVramMB(info.glVendor)) {+ info.vramMB = mb;+ info.vramSource = "sysfs amdgpu mem_info_vram_total";+ if (info.gpuKind == GpuKind::Discrete && mb <= 2048 && info.vramAvailableMB == 0) info.gpuKind = GpuKind::Integrated; // an APU's carve-out+ }+ }+#endif+#if defined(_WIN32)+ if (info.vramMB == 0 && info.gpuKind != GpuKind::Software) {+ uint64_t shared = 0;+ if (const uint64_t mb = dxgiVramMB(info.glVendor, &shared)) {+ info.vramMB = mb;+ info.vramSource = "DXGI";+ if (mb < 512 && info.gpuKind != GpuKind::Discrete) info.gpuKind = GpuKind::Integrated; // a carve-out only+ }+ }+#endif+#if defined(__APPLE__)+ if (info.vramMB == 0 && info.gpuKind != GpuKind::Unified) {+ if (const uint64_t mb = cglVramMB()) {+ info.vramMB = mb;+ info.vramSource = "CGL";+ }+ }+#endif+ if (info.vramMB == 0 && info.gpuKind == GpuKind::Unified) info.vramSource = "unified (system RAM)";+ while (gl::GetError() != GL_NO_ERROR) {}+}++bool GpuFrameTimer::available() {+ if (!loaded_) {+ loaded_ = true;+ const GlExtra e = loadExtra();+ ok_ = e.timer();+ if (ok_) {+ e.GenQueries(kSlots, queries_);+ while (gl::GetError() != GL_NO_ERROR) {}+ }+ }+ return ok_;+}++void GpuFrameTimer::begin() {+ if (!available() || active_ >= 0) return;+ if (pending_[next_]) pending_[next_] = false; // never read in time: dropped+ static const GlExtra e = loadExtra();+ e.BeginQuery(kGL_TIME_ELAPSED, queries_[next_]);+ active_ = next_;+}++void GpuFrameTimer::end(uint64_t frame) {+ if (active_ < 0) return;+ static const GlExtra e = loadExtra();+ e.EndQuery(kGL_TIME_ELAPSED);+ frames_[active_] = frame;+ pending_[active_] = true;+ next_ = (active_ + 1) % kSlots;+ active_ = -1;+}++bool GpuFrameTimer::poll(uint64_t& frame, double& ms) {+ if (!ok_) return false;+ static const GlExtra e = loadExtra();+ constexpr GLenum kGL_QUERY_RESULT_AVAILABLE = 0x8867;+ // Oldest first: the slot after the next one to be written.+ for (int k = 0; k < kSlots; ++k) {+ const int i = (next_ + k) % kSlots;+ if (!pending_[i] || i == active_) continue;+ uint64_t ready = 0;+ e.GetQueryObjectui64v(queries_[i], kGL_QUERY_RESULT_AVAILABLE, &ready);+ if (!ready) return false; // later ones aren't either+ uint64_t ns = 0;+ e.GetQueryObjectui64v(queries_[i], kGL_QUERY_RESULT, &ns);+ pending_[i] = false;+ frame = frames_[i];+ ms = double(ns) * 1e-6;+ return true;+ }+ return false;+}++void GpuFrameTimer::release() {+ if (ok_) {+ static const GlExtra e = loadExtra();+ if (active_ >= 0) e.EndQuery(kGL_TIME_ELAPSED);+ e.DeleteQueries(kSlots, queries_);+ }+ ok_ = false;+ loaded_ = false;+ active_ = -1;+ for (bool& p : pending_) p = false;+}++Calibrator::~Calibrator() = default;++const char* Calibrator::stageName() const {+ switch (stage_) {+ case 0: return "Detecting the GPU";+ case 1: return "Measuring triangle throughput";+ case 2: return "Measuring upload bandwidth";+ case 3: return "Measuring memory bandwidth";+ case 4: return "Measuring brush speed";+ default: return "Done";+ }+}++bool Calibrator::step() {+ if (done()) return false;+ if (stage_ == 0) startedMs_ = nowMs();+ switch (stage_) {+ case 0: probeHardware(hw_); break;+ case 1: cal_.trianglesPerSecondM = measureTriangles(loadExtra(), quick_, cal_.gpuTimer); break;+ case 2: cal_.uploadGBps = measureUpload(quick_); break;+ case 3: cal_.memoryGBps = measureMemoryBandwidthGBps(quick_ ? 3 : 5); break;+ case 4:+ cal_.dabMs = measureDabMs(quick_ ? 200'000 : 1'000'000, quick_ ? 3 : 5, quick_ ? 12 : 20, &cal_.dabVertices);+ break;+ }+ ++stage_;+ cal_.runs = quick_ ? 3 : 5;+ cal_.durationMs = nowMs() - startedMs_;+ return !done();+}++void Calibrator::skip() {+ if (stage_ == 0) probeHardware(hw_); // what the GPU is takes no time; only the measuring is skipped+ cal_ = Calibration{};+ cal_.skipped = true;+ stage_ = kStages;+}++HardwareProfile Calibrator::profile(const ProfileOverrides& overrides) const { return mapProfile(hw_, cal_, overrides); }++void applyCachedThreadCount() {+ HardwareProfile cached;+ if (loadHardwareProfile(hardwareProfilePath(), cached) && cached.settings.threads > 0)+ ThreadPool::setSharedThreadCount(cached.settings.threads);+}++HardwareProfile calibrateNow(bool quick, const ProfileOverrides& overrides) {+ Calibrator c(quick);+ while (c.step()) {}+ return c.profile(overrides);+}++int runCalibrateCommandLine(bool quick, bool save) {+ if (!SDL_Init(SDL_INIT_VIDEO)) {+ std::fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());+ return 1;+ }+ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);+ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);+ SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);+ SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);+ SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);+ SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);+ SDL_Window* window = SDL_CreateWindow("SculptForge calibration", 320, 200, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);+ SDL_GLContext context = window ? SDL_GL_CreateContext(window) : nullptr;+ if (!context) {+ std::fprintf(stderr, "OpenGL 3.3 context creation failed: %s\n", SDL_GetError());+ if (window) SDL_DestroyWindow(window);+ SDL_Quit();+ return 1;+ }+ SDL_GL_MakeCurrent(window, context);+ int code = 1;+ if (const char* missing = gl::load([](const char* n) { return reinterpret_cast<gl::GenericProc>(SDL_GL_GetProcAddress(n)); })) {+ std::fprintf(stderr, "Missing OpenGL function: %s\n", missing);+ } else {+ HardwareProfile cached;+ const std::string path = hardwareProfilePath();+ const bool hadCache = loadHardwareProfile(path, cached);+ const HardwareProfile p = calibrateNow(quick, hadCache ? cached.overrides : ProfileOverrides{});+ const Json j = calibrationJson(p);+ std::string error;+ if (!validateCalibrationJson(j, error)) {+ std::fprintf(stderr, "calibration JSON is invalid: %s\n", error.c_str());+ } else {+ std::puts(j.dump(true).c_str());+ code = 0;+ if (save && !saveHardwareProfile(path, p, error)) std::fprintf(stderr, "not saved: %s\n", error.c_str());+ }+ }+ SDL_GL_DestroyContext(context);+ SDL_DestroyWindow(window);+ SDL_Quit();+ return code;+}++} // namespace sfdiff --git a/src/app/Calibration.h b/src/app/Calibration.hnew file mode 100644index 00000000..ff6e0c3f--- /dev/null+++ b/src/app/Calibration.h@@ -0,0 +1,76 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// The OpenGL half of hardware detection and calibration (core/HardwareProfile.h has the rest):+// - probeGl: GL_VENDOR / GL_RENDERER / GL_VERSION, GL_MAX_TEXTURE_SIZE, timer queries, and video memory through+// GL_NVX_gpu_memory_info, GL_ATI_meminfo, GLX_MESA_query_renderer (X11), amdgpu sysfs (Linux), DXGI (Windows)+// or CGL (macOS), whichever answers first;+// - Calibrator: the benchmarks in short steps (one per frame in the app, so the window stays responsive and the+// user can skip): triangle throughput (instanced dense grids into an offscreen target, timed with GL timer+// queries where available, else glFinish), buffer upload bandwidth (glBufferSubData), memory bandwidth and the+// cost of a brush dab on a generated mesh. Medians of several runs; the work per run is fixed.+// Everything restores the GL state it touched, so it can run between the app's frames. No network.+#pragma once++#include "core/HardwareProfile.h"++#include <string>++namespace sf {++// Fills the GPU fields of `info` from the current OpenGL context (and the machine's, through probeSystem).+void probeHardware(HardwareInfo& info);++class Calibrator {+public:+ explicit Calibrator(bool quick = false) : quick_(quick) {}+ ~Calibrator();+ // Runs the next step (each well under a second); false once finished.+ bool step();+ bool done() const { return stage_ >= kStages; }+ float progress() const { return float(stage_) / float(kStages); }+ const char* stageName() const; // what the next step measures, for the overlay+ // Marks calibration skipped: the profile is mapped from the probe alone.+ void skip();+ // The result (valid once done()), mapped with `overrides`.+ HardwareProfile profile(const ProfileOverrides& overrides = {}) const;++private:+ static constexpr int kStages = 5; // probe, triangles, upload, memory, dab+ bool quick_ = false;+ int stage_ = 0;+ HardwareInfo hw_;+ Calibration cal_;+ double startedMs_ = 0.0;+};++// GPU time of each frame through GL timer queries (GL_TIME_ELAPSED), read a few frames later so the CPU never+// waits for the GPU. Unavailable (available() false) where the driver has no timer queries.+class GpuFrameTimer {+public:+ bool available(); // loads the entry points on first use (needs the context)+ void begin(); // before the frame's GL work+ void end(uint64_t frame); // after it; `frame` tags the result+ bool poll(uint64_t& frame, double& ms); // an earlier frame's GPU time, if one is ready (never waits)+ void release(); // deletes the queries (needs the context)++private:+ static constexpr int kSlots = 4;+ unsigned queries_[kSlots] = {};+ uint64_t frames_[kSlots] = {};+ bool pending_[kSlots] = {};+ int next_ = 0, active_ = -1;+ bool loaded_ = false, ok_ = false;+};++// Sets the shared thread pool's size from the cached profile (call before any brush work; core/ThreadPool.h).+void applyCachedThreadCount();++// Calibrates now, blocking (about 2-3 s; quick: about 1 s). Needs a current OpenGL context.+HardwareProfile calibrateNow(bool quick, const ProfileOverrides& overrides);++// sculptforge --calibrate [--calibrate-quick] [--calibrate-no-save]: a hidden window and context, calibrate, print+// the JSON (schema sculptforge.calibration/1) to stdout, save it as the cached profile. Returns the exit code.+int runCalibrateCommandLine(bool quick, bool save);++} // namespace sfdiff --git a/src/app/PanelPerformance.cpp b/src/app/PanelPerformance.cppindex 12609854..1f886414 100644--- a/src/app/PanelPerformance.cpp+++ b/src/app/PanelPerformance.cpp@@ -8,6 +8,7 @@#include "app/Ui.h"#include "core/Benchmark.h"+#include "core/HardwareProfile.h"#include "core/ThreadPool.h"#include <chrono>@@ -19,11 +20,13 @@ namespace sf {namespace {constexpr const char* kPath = "Preferences > Performance";-// Scenes this big draw without antialiasing while the view moves (with Fast Navigation on). UI tests lower it-// with the environment variable SF_FAST_NAVIGATION_TRIANGLES, so they needn't build a huge mesh.-size_t fastNavigationTriangles() {+// Scenes this big draw without antialiasing while the view moves (with Fast Navigation on): the hardware profile's+// motion proxy threshold, which the frame governor adjusts (core/HardwareProfile.h), else 10 million. UI tests+// set it with the environment variable SF_FAST_NAVIGATION_TRIANGLES, so they needn't build a huge mesh.+size_t fastNavigationTriangles(bool governed) {const char* v = std::getenv("SF_FAST_NAVIGATION_TRIANGLES");- return v && *v ? size_t(std::strtoull(v, nullptr, 10)) : size_t(10'000'000);+ if (v && *v) return size_t(std::strtoull(v, nullptr, 10));+ return governed ? size_t(motionProxyThreshold()) : size_t(10'000'000);}std::string megabytes(size_t bytes) {@@ -84,6 +87,7 @@ void App::registerPerformanceUiActions() {[] { return !ThreadPool::shared().serial(); },"Run brushes, normal and BVH updates and project saving on every core. Turn it off only to compare speeds ""or rule it out when troubleshooting: the results are the same either way.");+ registerPerformanceProfileUiActions(); // Re-calibrate, the frame governor (PanelPerformanceProfile.cpp)}void App::applyPerformancePrefs() { ThreadPool::shared().setSerial(!uiPrefs_.multithreading); }@@ -102,7 +106,9 @@ int App::viewSamples() {size_t triangles = 0;for (int i = 0; i < doc_.subtoolCount(); ++i)if (doc_.subtools[size_t(i)].visible) triangles += doc_.subtoolMesh(i).triangleCount();- perf_.proxyNow = uiPrefs_.fastNavigation && moving && triangles >= fastNavigationTriangles();+ perf_.movingNow = moving;+ perf_.sceneTriangles = triangles;+ perf_.proxyNow = uiPrefs_.fastNavigation && moving && triangles >= fastNavigationTriangles(hardwareProfileGoverns());perf_.fastNow = aa > 1 && perf_.proxyNow;perf_.samplesWanted = perf_.fastNow ? 1 : aa;return perf_.samplesWanted;@@ -123,6 +129,7 @@ void App::notePerformanceFrame(double syncMs) {}void App::drawPerformanceSection() {+ drawPerformanceProfileSection(); // what was detected and measured, the profile, overrides (PanelPerformanceProfile.cpp)// --- The 3D view ---ImGui::TextUnformatted("Antialiasing");ui::HelpText("Antialiasing", nullptr,diff --git a/src/app/PanelPerformanceProfile.cpp b/src/app/PanelPerformanceProfile.cppnew file mode 100644index 00000000..ed702a42--- /dev/null+++ b/src/app/PanelPerformanceProfile.cpp@@ -0,0 +1,458 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// The hardware profile in the app (docs/performance.md, "Hardware profile"):+// - on first launch, and when the GPU, its driver or the app version changes, calibration runs over the first+// frames (about 2 seconds, one short step per frame under a small overlay; Esc skips) and the result is cached+// in the settings folder; later starts read the cache;+// - Preferences > Performance shows what was detected and measured, the profile and its settings, the frame+// governor's state, Re-calibrate and manual overrides;+// - the adaptive frame governor (core/FrameGovernor.h) gets every drawn frame's CPU time and GPU time (timer+// queries, read a few frames later) and moves the motion proxy threshold / render triangle budget.+// Tests, renders, recordings and the --measure-* runs never calibrate (their results must not depend on the+// machine), and keep the fixed 10 million triangle Fast Navigation threshold.+#include "app/App.h"+#include "app/Calibration.h"+#include "app/Ui.h"++#include "core/FrameGovernor.h"+#include "core/HardwareProfile.h"+#include "core/ThreadPool.h"++#include <SDL3/SDL.h>++#include <algorithm>+#include <chrono>+#include <cstdio>+#include <cstdlib>+#include <deque>++namespace sf {++struct HwProfileUi {+ HardwareProfile profile;+ bool active = false; // a profile is applied: its threshold governs Fast Navigation+ bool saved = false; // the profile came from (or went to) the cache+ std::unique_ptr<Calibrator> calibrator;+ std::string calibrationReason; // "first launch", "GPU changed", ...+ bool announce = false; // say what calibration found in the status bar+ int calibrationFrames = 0; // frames shown since calibration started (the first shows the overlay)+ FrameGovernor governor;+ GpuFrameTimer timer;+ uint64_t frame = 0;+ double frameStartMs = 0.0;+ struct Pending {+ uint64_t frame;+ FrameSample sample;+ };+ std::deque<Pending> pending; // frames waiting for their GPU time+ uint64_t revision = 0; // performanceSettingsRevision() when last applied+ int displayHz = 0;+ double lastCpuMs = 0.0, lastGpuMs = -1.0;+ bool overridesOpen = false;+};++namespace {++constexpr const char* kPath = "Preferences > Performance";++double nowMs() { return double(SDL_GetTicksNS()) * 1e-6; }++void dim(const std::string& text) {+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));+ ImGui::TextWrapped("%s", text.c_str());+ ImGui::PopStyleColor();+}++std::string fmt(const char* f, double v) {+ char buf[64];+ std::snprintf(buf, sizeof buf, f, v);+ return buf;+}++bool calibrationDisabled() {+ const char* v = std::getenv("SF_NO_CALIBRATION");+ return v && *v && *v != '0';+}++int displayRefreshHz(SDL_Window* window) {+ if (!window) return 0;+ const SDL_DisplayID display = SDL_GetDisplayForWindow(window);+ const SDL_DisplayMode* mode = display ? SDL_GetCurrentDisplayMode(display) : nullptr;+ return mode ? int(mode->refresh_rate + 0.5f) : 0;+}++} // namespace++bool App::hardwareProfileGoverns() const { return hwProfile_ && hwProfile_->active; }++void App::initHardwareProfile() {+ // Deterministic runs (UI tests, renders, recordings, demos) and the --measure-* runs keep the fixed defaults.+ if (uiConfigDeterministic_ || !options_.renderPath.empty() || !options_.recordPath.empty() || !options_.uiTest.empty() ||+ options_.measureIdle > 0.0f || options_.measureStroke > 0.0f)+ return;+ hwProfile_ = std::make_shared<HwProfileUi>();+ HwProfileUi& hw = *hwProfile_;+ hw.displayHz = displayRefreshHz(window_);+ // The calibrate command (console, MCP) measures the GPU too while the app runs.+ setGpuCalibrator([this](HardwareProfile& out, std::string&) {+ HardwareProfile cached;+ const ProfileOverrides keep = loadHardwareProfile(hardwareProfilePath(), cached) ? cached.overrides : hwProfile_->profile.overrides;+ out = calibrateNow(false, keep);+ std::string error;+ saveHardwareProfile(hardwareProfilePath(), out, error);+ // Applied on the next frame (the command saved it; the revision check reloads it).+ hwProfile_->revision = 0;+ return true;+ });+ HardwareInfo current;+ probeHardware(current);+ HardwareProfile cached;+ const bool hasCache = loadHardwareProfile(hardwareProfilePath(), cached);+ hw.calibrationReason = recalibrationReason(hasCache ? &cached : nullptr, current);+ HardwareProfile start;+ if (hw.calibrationReason.empty()) {+ // The cache fits: no measuring. Only what changes between runs (free video memory) is refreshed.+ cached.hardware.vramAvailableMB = current.vramAvailableMB;+ start = cached;+ hw.saved = true;+ } else {+ // What the probe alone suggests (overrides kept): the profile while calibrating, or for good when+ // SF_NO_CALIBRATION=1.+ Calibration none;+ none.skipped = true;+ start = mapProfile(current, none, hasCache ? cached.overrides : ProfileOverrides{});+ if (!calibrationDisabled()) {+ SDL_Log("Hardware profile: calibrating (%s)", hw.calibrationReason.c_str());+ hw.calibrator = std::make_unique<Calibrator>(false);+ hw.announce = true;+ }+ }+ applyHardwareProfile(start, false);+ if (!hw.calibrator) SDL_Log("Hardware profile: %s", start.reason.c_str());+}++// Makes `p` the profile in effect: the process-wide settings and the governor's starting point; `announce` (after a+// calibration that wasn't asked for) says so in the status bar and adapts the preferences a profile implies.+void App::applyHardwareProfile(const HardwareProfile& p, bool announce) {+ HwProfileUi& hw = *hwProfile_;+ hw.profile = p;+ hw.active = true;+ PerformanceSettings s = p.settings;+ if (!p.overrides.targetFps) s.targetFps = hw.displayHz >= 119 ? 120 : 60; // 120 where the display can show it+ hw.profile.settings.targetFps = s.targetFps;+ setCurrentPerformanceSettings(s);+ GovernorConfig cfg;+ cfg.targetFps = s.targetFps;+ cfg.minBudget = std::max<uint64_t>(250'000, s.renderTriangleBudget / 8);+ cfg.maxBudget = std::min<uint64_t>(2'000'000'000, std::max<uint64_t>(s.renderTriangleBudget * 4, cfg.minBudget));+ hw.governor.reset(cfg, s.renderTriangleBudget);+ hw.revision = performanceSettingsRevision();+ if (!announce) return;+ // A software renderer draws every sample on the CPU: no antialiasing.+ if (p.tier == ProfileTier::Software && uiPrefs_.antialiasing > 1) uiPrefs_.antialiasing = 1;+ const std::string gpu = p.hardware.glRenderer.empty() ? std::string("this computer") : p.hardware.glRenderer;+ status_ = std::string(p.calibration.skipped ? "Calibration skipped: " : "Calibrated for this computer: ") + gpu + " -> " ++ tierName(p.tier) + " profile (Preferences > Performance)";+}++void App::finishCalibration() {+ HwProfileUi& hw = *hwProfile_;+ HardwareProfile cached;+ const ProfileOverrides keep = loadHardwareProfile(hardwareProfilePath(), cached) ? cached.overrides : hw.profile.overrides;+ const HardwareProfile p = hw.calibrator->profile(keep);+ hw.calibrator.reset();+ std::string error;+ hw.saved = saveHardwareProfile(hardwareProfilePath(), p, error);+ if (!hw.saved) SDL_Log("Hardware profile not saved: %s", error.c_str());+ SDL_Log("Hardware profile: %s (%.0f ms)", p.reason.c_str(), p.calibration.durationMs);+ applyHardwareProfile(p, hw.announce);+ hw.announce = false;+}++void App::shutdownHardwareProfile() {+ setGpuCalibrator(nullptr);+ if (hwProfile_) hwProfile_->timer.release();+ hwProfile_.reset();+}++void App::hardwareProfileFrameBegin() {+ if (!hwProfile_) return;+ HwProfileUi& hw = *hwProfile_;+ if (hw.calibrator) {+ // One step per frame, after the overlay has been on screen once.+ if (hw.calibrationFrames++ > 0 && !hw.calibrator->step()) finishCalibration();+ activeUntil_ = std::max(activeUntil_, double(SDL_GetTicksNS()) * 1e-9 + 0.3); // keep the frames coming+ }+ hw.frameStartMs = nowMs();+ if (!hw.calibrator) hw.timer.begin();+}++void App::hardwareProfileFrameEnd() {+ if (!hwProfile_) return;+ HwProfileUi& hw = *hwProfile_;+ const uint64_t frame = hw.frame++;+ if (hw.calibrator) return;+ hw.timer.end(frame);+ FrameSample sample;+ sample.cpuMs = nowMs() - hw.frameStartMs;+ sample.drawnTriangles = renderer_.lastDrawnTriangles();+ sample.sceneTriangles = perf_.sceneTriangles;+ sample.moving = perf_.movingNow;+ sample.limited = perf_.proxyNow;+ hw.lastCpuMs = sample.cpuMs;+ bool changed = false;+ if (hw.timer.available()) {+ hw.pending.push_back({frame, sample});+ uint64_t doneFrame = 0;+ double gpuMs = 0.0;+ while (hw.timer.poll(doneFrame, gpuMs)) {+ while (!hw.pending.empty() && hw.pending.front().frame < doneFrame) hw.pending.pop_front(); // lost+ if (!hw.pending.empty() && hw.pending.front().frame == doneFrame) {+ FrameSample s = hw.pending.front().sample;+ hw.pending.pop_front();+ s.gpuMs = gpuMs;+ hw.lastGpuMs = gpuMs;+ changed = hw.governor.addFrame(s) || changed;+ }+ }+ while (hw.pending.size() > 8) { // the GPU time never came: count the CPU time alone+ changed = hw.governor.addFrame(hw.pending.front().sample) || changed;+ hw.pending.pop_front();+ }+ } else {+ changed = hw.governor.addFrame(sample);+ }+ if (changed && hw.profile.overrides.governor && !hw.profile.overrides.motionProxyThreshold)+ setGovernedBudgets(hw.governor.budget(), hw.governor.proxyThreshold());+ // The display may change (the window moved to a 120 Hz screen): follow it.+ if (frame % 600 == 0) {+ const int hz = displayRefreshHz(window_);+ if (hz != hw.displayHz) {+ hw.displayHz = hz;+ if (!hw.profile.overrides.targetFps) hw.governor.setTargetFps(hz >= 119 ? 120 : 60);+ }+ }+ // The set_performance_override or calibrate command changed the profile: take it up.+ if (performanceSettingsRevision() != hw.revision) {+ HardwareProfile cached;+ if (loadHardwareProfile(hardwareProfilePath(), cached)) applyHardwareProfile(cached, false);+ else hw.revision = performanceSettingsRevision();+ }+}++void App::drawHardwareProfileOverlay() {+ if (!hwProfile_ || !hwProfile_->calibrator) return;+ HwProfileUi& hw = *hwProfile_;+ const ImGuiViewport* vp = ImGui::GetMainViewport();+ ImGui::SetNextWindowPos(ImVec2(vp->WorkPos.x + vp->WorkSize.x * 0.5f, vp->WorkPos.y + vp->WorkSize.y * 0.5f), ImGuiCond_Always,+ ImVec2(0.5f, 0.5f));+ ImGui::SetNextWindowSize(ImVec2(380.0f * uiScale_, 0.0f));+ ImGui::SetNextWindowFocus();+ if (ImGui::Begin("##calibration", nullptr,+ ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |+ ImGuiWindowFlags_AlwaysAutoResize)) {+ if (fontBold_) ImGui::PushFont(fontBold_);+ ImGui::TextUnformatted("Getting to know this computer");+ if (fontBold_) ImGui::PopFont();+ dim("A two-second check of the GPU, the CPU and memory, so big scenes stay smooth. Once, then again only when "+ "the graphics card, its driver or SculptForge changes. Nothing leaves this computer.");+ ImGui::ProgressBar(hw.calibrator->progress(), ImVec2(-1.0f, 0.0f), hw.calibrator->stageName());+ const bool esc = ImGui::IsKeyPressed(ImGuiKey_Escape, false);+ if (ImGui::Button("Skip") || esc) {+ hw.calibrator->skip();+ finishCalibration();+ }+ ImGui::SameLine();+ ImGui::TextDisabled("Esc");+ }+ ImGui::End();+}++void App::registerPerformanceProfileUiActions() {+ {+ Action a;+ a.id = "perf.recalibrate";+ a.label = "Re-calibrate";+ a.palette = kPath;+ a.run = [this] {+ if (!hwProfile_) {+ status_ = "Calibration is off in this run (tests, renders and recordings use fixed settings)";+ return;+ }+ hwProfile_->calibrator = std::make_unique<Calibrator>(false);+ hwProfile_->calibrationFrames = 0;+ hwProfile_->announce = true;+ status_ = "Calibrating...";+ };+ a.description = "Measure this computer again (about 2 seconds): the GPU's triangle throughput and upload speed, "+ "brush speed and memory bandwidth, then pick the performance profile. Your overrides are kept.";+ actions_.add(std::move(a));+ }+ {+ Action a;+ a.id = "perf.governor";+ a.label = "Frame Governor";+ a.palette = kPath;+ a.run = [this] {+ if (!hwProfile_) return;+ ProfileOverrides o = hwProfile_->profile.overrides;+ o.governor = !o.governor;+ const HardwareProfile p = mapProfile(hwProfile_->profile.hardware, hwProfile_->profile.calibration, o);+ std::string error;+ saveHardwareProfile(hardwareProfilePath(), p, error);+ applyHardwareProfile(p, false);+ status_ = o.governor ? "Frame governor on" : "Frame governor off (the profile's budgets stay as set)";+ };+ a.checked = [this] { return hwProfile_ && hwProfile_->profile.overrides.governor; };+ a.description = "Hold the view at the target frame rate (60 fps, or 120 on a 120 Hz display) by drawing big "+ "scenes' lighter motion proxy sooner or later while the view moves. Only what you see changes, "+ "never the model.";+ actions_.add(std::move(a));+ }+}++void App::drawPerformanceProfileSection() {+ ImGui::TextUnformatted("Hardware profile");+ ui::HelpText("Hardware profile", nullptr,+ "SculptForge measures this computer on first launch (and when the graphics card, its driver or the "+ "version changes) and picks settings to match: how many triangles the view draws per frame, when big "+ "scenes switch to their lighter motion proxy, GPU memory and upload budgets, texture and subdivision "+ "limits, threads. Nothing is sent anywhere.",+ kPath);+ if (!hwProfile_) {+ dim("Off in this run: tests, renders and recordings use fixed settings.");+ ImGui::Spacing();+ return;+ }+ HwProfileUi& hw = *hwProfile_;+ if (hw.calibrator) {+ ImGui::ProgressBar(hw.calibrator->progress(), ImVec2(-1.0f, 0.0f), hw.calibrator->stageName());+ ImGui::Spacing();+ return;+ }+ const HardwareProfile& p = hw.profile;+ const HardwareInfo& h = p.hardware;+ const Calibration& c = p.calibration;+ const PerformanceSettings& s = p.settings;+ // "Detected Apple M1 Pro, 21.3 GB unified -> Workstation"+ std::string vram = h.vramMB ? formatMegabytes(h.vramMB) : h.gpuKind == GpuKind::Unified || h.gpuKind == GpuKind::Integrated+ ? formatMegabytes(s.vramBudgetMB) + " shared"+ : std::string("memory unknown");+ if (fontBold_) ImGui::PushFont(fontBold_);+ ImGui::TextWrapped("Detected %s, %s -> %s", h.glRenderer.empty() ? "an unknown GPU" : h.glRenderer.c_str(), vram.c_str(),+ tierName(p.tier));+ if (fontBold_) ImGui::PopFont();+ dim(p.reason);+ std::string measured;+ if (c.skipped) measured = "Not measured (skipped): settings from the GPU type and memory sizes.\n";+ else {+ measured += "Triangles " + fmt("%.0fM/s", c.trianglesPerSecondM) + (c.gpuTimer ? " (GPU timer)" : " (glFinish)") ++ " Upload " + fmt("%.1f GB/s", c.uploadGBps) + "\n";+ measured += "Brush dab " + fmt("%.2f ms", c.dabMs) + " (" + fmt("%.1fk", c.dabVertices / 1000.0) + " vertices) Memory " ++ fmt("%.1f GB/s", c.memoryGBps) + "\n";+ }+ std::string simd;+ for (const auto& x : h.simd) simd += (simd.empty() ? "" : ", ") + x;+ measured += h.cpu + (h.cpu.empty() ? "" : ", ") + std::to_string(h.cpuThreads) + " threads" + (simd.empty() ? "" : " (" + simd + ")") ++ ", " + formatMegabytes(h.ramMB) + " RAM\nVideo memory: " + (h.vramSource.empty() ? std::string("none") : h.vramSource) ++ (h.vramAvailableMB ? ", " + formatMegabytes(h.vramAvailableMB) + " free" : std::string()) + "\n" + h.os + ", OpenGL " ++ h.glVersion;+ ImGui::TextWrapped("%s", measured.c_str());+ ImGui::LogText("%s", measured.c_str());++ ImGui::Spacing();+ const uint64_t governed = renderTriangleBudget();+ std::string set = "View budget " + formatTriangles(s.renderTriangleBudget) + " triangles" ++ (governed != s.renderTriangleBudget ? " (governed: " + formatTriangles(governed) + ")" : std::string()) ++ "\nMotion proxy from " + formatTriangles(motionProxyThreshold()) + " triangles\nGPU memory budget " ++ formatMegabytes(s.vramBudgetMB) + ", uploads " + std::to_string(s.uploadBudgetMBPerFrame) ++ " MB per frame\nTextures up to " + std::to_string(s.maxTextureSize) + ", subdivision up to " ++ formatTriangles(s.maxSubdivisionTriangles) + ", micro-triangles up to " + formatTriangles(s.microTriangleLimit) ++ "\n" + std::to_string(s.threads) + " threads" ++ (s.threads != ThreadPool::shared().threads() ? " (after a restart; now " + std::to_string(ThreadPool::shared().threads()) + ")" : std::string()) ++ ", target " + std::to_string(s.targetFps) + " fps";+ ImGui::TextWrapped("%s", set.c_str());+ ImGui::LogText("%s", set.c_str());++ bool governor = p.overrides.governor;+ if (ImGui::Checkbox("Frame Governor", &governor)) actions_.find("perf.governor")->run();+ ui::HelpAction(*this, "perf.governor");+ if (governor && hw.governor.decisions() > 0) {+ const char* action = hw.governor.lastAction() == FrameGovernor::Action::Lowered ? "drawing less"+ : hw.governor.lastAction() == FrameGovernor::Action::Raised ? "drawing more"+ : "holding";+ dim("Moving view: " + fmt("%.1f ms", hw.governor.lastCostMs()) + " of " + fmt("%.1f ms", hw.governor.targetMs()) + " per frame (" ++ (hw.lastGpuMs >= 0.0 ? "GPU timer" : "CPU time") + "), " + action);+ } else if (governor) {+ dim("Learns from frames while the view moves.");+ }+ if (ImGui::Button("Re-calibrate")) actions_.find("perf.recalibrate")->run();+ ui::HelpAction(*this, "perf.recalibrate");++ // --- Manual overrides ---+ if (ImGui::TreeNode("Manual overrides")) {+ ProfileOverrides o = p.overrides;+ bool edited = false;+ const char* tiers[] = {"Automatic", "Software (safe mode)", "Laptop", "Workstation", "Monster"};+ int tierIndex = 0;+ ProfileTier forced;+ if (!o.tier.empty() && tierFromName(o.tier, forced)) tierIndex = int(forced) + 1;+ ImGui::SetNextItemWidth(-1.0f);+ if (ImGui::Combo("##perf.tier", &tierIndex, tiers, 5)) {+ o.tier = tierIndex == 0 ? std::string() : std::string(tierName(ProfileTier(tierIndex - 1)));+ edited = true;+ }+ // Numbers: 0 = automatic (shown as the profile's value, dimmed hint).+ auto number = [&](const char* label, uint64_t& value, uint64_t automatic, double scale, const char* unit) {+ float v = float(double(value ? value : 0) / scale);+ ImGui::SetNextItemWidth(120.0f * uiScale_);+ const std::string hint = fmt("%.1f", double(automatic) / scale) + " " + unit + " (auto)";+ ImGui::PushID(label);+ if (ImGui::InputFloat("##v", &v, 0.0f, 0.0f, value ? "%.1f" : hint.c_str(), ImGuiInputTextFlags_EnterReturnsTrue)) {+ value = v > 0.0f ? uint64_t(double(v) * scale) : 0;+ edited = true;+ }+ ImGui::SameLine();+ ImGui::TextUnformatted(label);+ ImGui::PopID();+ };+ number("View budget (M triangles)", o.renderTriangleBudget, p.automatic.renderTriangleBudget, 1e6, "M");+ number("Motion proxy from (M triangles)", o.motionProxyThreshold, p.automatic.motionProxyThreshold, 1e6, "M");+ number("GPU memory budget (GB)", o.vramBudgetMB, p.automatic.vramBudgetMB, 1024.0, "GB");+ number("Uploads per frame (MB)", o.uploadBudgetMBPerFrame, p.automatic.uploadBudgetMBPerFrame, 1.0, "MB");+ number("Subdivision limit (M triangles)", o.maxSubdivisionTriangles, p.automatic.maxSubdivisionTriangles, 1e6, "M");+ {+ uint64_t threads = uint64_t(o.threads);+ number("Threads (next start)", threads, uint64_t(p.automatic.threads), 1.0, "");+ o.threads = int(threads);+ }+ const char* fpsNames[] = {"Target: automatic", "30 fps", "60 fps", "120 fps", "144 fps"};+ const int fpsValues[] = {0, 30, 60, 120, 144};+ int fpsIndex = 0;+ for (int i = 0; i < 5; ++i)+ if (o.targetFps == fpsValues[i]) fpsIndex = i;+ ImGui::SetNextItemWidth(-1.0f);+ if (ImGui::Combo("##perf.fps", &fpsIndex, fpsNames, 5)) {+ o.targetFps = fpsValues[fpsIndex];+ edited = true;+ }+ if (o.any() && ImGui::Button("Back to automatic")) {+ const bool governorWas = o.governor;+ o = ProfileOverrides{};+ o.governor = governorWas;+ edited = true;+ }+ if (edited) {+ const HardwareProfile next = mapProfile(h, c, o);+ std::string error;+ if (!saveHardwareProfile(hardwareProfilePath(), next, error)) status_ = "Not saved: " + error;+ applyHardwareProfile(next, false);+ }+ ImGui::TreePop();+ }+ ImGui::Separator();+ ImGui::Spacing();+}++} // namespace sfdiff --git a/src/app/main.cpp b/src/app/main.cppindex 654bc888..6f291b31 100644--- a/src/app/main.cpp+++ b/src/app/main.cpp@@ -2,6 +2,7 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "app/App.h"#include "app/Bench.h"+#include "app/Calibration.h"#include "app/CrashLog.h"#include <SDL3/SDL_main.h>@@ -52,6 +53,8 @@ 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"+ " --calibrate Measure this computer (GPU, CPU, memory; about 2-3 s), print the hardware\n"+ " profile as JSON and save it (add --calibrate-quick, --calibrate-no-save)\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");}@@ -101,11 +104,15 @@ int main(int argc, char** argv) {std::string logDir, crashTest;bool sizeGiven = false;sf::BenchCommandLine bench;+ bool calibrate = false, calibrateQuick = false, calibrateSave = true;for (int i = 1; i < argc; ++i) {std::string a = argv[i];auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : std::string(); };if (sf::parseBenchArg(argc, argv, i, bench)) continue;- if (a == "--run") options.script += next() + "\n";+ if (a == "--calibrate") calibrate = true;+ else if (a == "--calibrate-quick") calibrate = calibrateQuick = true;+ else if (a == "--calibrate-no-save") calibrateSave = false;+ else if (a == "--run") options.script += next() + "\n";else if (a == "--render") options.renderPath = next();else if (a == "--turntable") options.turntable = std::atoi(next().c_str());else if (a == "--size") sizeGiven = std::sscanf(next().c_str(), "%dx%d", &options.width, &options.height) == 2;@@ -144,6 +151,7 @@ int main(int argc, char** argv) {}}if (bench.run) return sf::runAppBenchmark(bench);+ if (calibrate) return sf::runCalibrateCommandLine(calibrateQuick, calibrateSave);if (!options.uiTest.empty()) {if (!sizeGiven) options.width = 1600, options.height = 960;isolateSettings();diff --git a/src/core/HardwareProfile.cpp b/src/core/HardwareProfile.cppindex 8cc2b0de..b3c868de 100644--- a/src/core/HardwareProfile.cpp+++ b/src/core/HardwareProfile.cpp@@ -341,9 +341,10 @@ 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;+ // Apple GPUs may use about two thirds of the memory (Metal's recommended working set). Drivers report+ // anything from that to all of the RAM (Asahi's GL_NVX_gpu_memory_info): never more than two thirds.+ if (hw.ramMB == 0) return hw.vramMB;+ return hw.vramMB ? std::min(hw.vramMB, hw.ramMB * 2 / 3) : hw.ramMB * 2 / 3;case GpuKind::Integrated: return std::max(hw.vramMB, hw.ramMB / 2); // the carve-out plus shared system memorycase GpuKind::Software: return hw.ramMB / 4;case GpuKind::Unknown: break;@@ -371,7 +372,11 @@ TierLimits limits(ProfileTier t) {// 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) {+// A re-calibration of the same GPU keeps its previous tier when the new measurement lands within this factor of+// the boundary between the two (measurements vary a little from run to run, more on a busy machine).+constexpr double kStickyBand = 1.15;++ProfileTier tierFromMeasurements(const HardwareInfo& hw, const Calibration& c, const ProfileTier* previous, std::string& why) {char buf[256];ProfileTier t;if (hw.gpuKind == GpuKind::Software) {@@ -385,6 +390,16 @@ ProfileTier tierFromMeasurements(const HardwareInfo& hw, const Calibration& c, selse t = ProfileTier::Monster;std::snprintf(buf, sizeof buf, "%.0fM triangles/s", c.trianglesPerSecondM);why = buf;+ if (previous && std::abs(int(*previous) - int(t)) == 1) {+ const ProfileTier upper = int(*previous) > int(t) ? *previous : t;+ const double boundary = upper == ProfileTier::Laptop ? kSoftwareBelowM+ : upper == ProfileTier::Workstation ? kWorkstationFromM+ : kMonsterFromM;+ if (c.trianglesPerSecondM >= boundary / kStickyBand && c.trianglesPerSecondM <= boundary * kStickyBand) {+ t = *previous;+ why += ", kept " + std::string(tierName(t)) + " (close to the boundary)";+ }+ }} else {// Nothing measured: a conservative guess from the memory sizes.const uint64_t gpu = usableGpuMemoryMB(hw);@@ -468,13 +483,15 @@ bool ProfileOverrides::any() const {maxTextureSize || maxSubdivisionTriangles || microTriangleLimit || threads || targetFps || !governor;}-HardwareProfile mapProfile(const HardwareInfo& hardware, const Calibration& calibration, const ProfileOverrides& overrides) {+HardwareProfile mapProfile(const HardwareInfo& hardware, const Calibration& calibration, const ProfileOverrides& overrides,+ const ProfileTier* previousTier) {HardwareProfile p;p.hardware = hardware;p.calibration = calibration;p.overrides = overrides;std::string why;- p.tier = tierFromMeasurements(hardware, calibration, why);+ p.tier = tierFromMeasurements(hardware, calibration, previousTier, why);+ p.measuredTier = p.tier;ProfileTier forced;if (!overrides.tier.empty() && tierFromName(overrides.tier, forced) && forced != p.tier) {why += std::string("; set to ") + tierName(forced) + " by hand";@@ -636,6 +653,7 @@ Json hardwareProfileToJson(const HardwareProfile& p) {j.set("hardware", hardwareJson(p.hardware));j.set("calibration", calibrationToJson(p.calibration));j.set("tier", tierName(p.tier));+ j.set("measured_tier", tierName(p.measuredTier));j.set("settings", settingsJson(p.settings));j.set("overrides", overridesJson(p.overrides));return j;@@ -650,8 +668,11 @@ bool hardwareProfileFromJson(const Json& j, HardwareProfile& out) {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);+ // The tier and settings are mapped again (not read back), so they always follow this version's mapping; the+ // stored tier only settles a measurement close to a boundary, as when it was saved.+ ProfileTier stored;+ const bool hasStored = tierFromName(j["measured_tier"].asString(), stored);+ out = mapProfile(h, c, o, hasStored ? &stored : nullptr);return true;}@@ -1002,7 +1023,8 @@ void registerHardwareProfileCommands(CommandRegistry& registry) {c.cpuOnly = c.trianglesPerSecondM <= 0.0;calibrateCpu(c, quick);c.durationMs = msSince(t);- p = mapProfile(h, c, hadCache ? cached.overrides : ProfileOverrides{});+ const bool sameGpu = hadCache && !h.glRenderer.empty();+ p = mapProfile(h, c, hadCache ? cached.overrides : ProfileOverrides{}, sameGpu ? &cached.measuredTier : nullptr);}if (hadCache && !gpu) p.overrides = cached.overrides;saveHardwareProfile(hardwareProfilePath(), p, error); // best effort: the JSON is the answerdiff --git a/src/core/HardwareProfile.h b/src/core/HardwareProfile.hindex a8c6a014..f005deb7 100644--- a/src/core/HardwareProfile.h+++ b/src/core/HardwareProfile.h@@ -115,6 +115,7 @@ struct HardwareProfile {HardwareInfo hardware;Calibration calibration;ProfileTier tier = ProfileTier::Laptop;+ ProfileTier measuredTier = ProfileTier::Laptop; // before a tier override (what re-calibration sticks to)std::string reason; // why this tier, in words (Preferences > Performance)PerformanceSettings settings; // the tier's settings with the overrides appliedPerformanceSettings automatic; // before the overrides@@ -123,9 +124,10 @@ struct HardwareProfile {// 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.+// GPU kind, conservatively. `previousTier` (a re-calibration of the same GPU): a measurement within 15% of the+// boundary between that tier and its neighbour keeps that tier, so the profile doesn't flip between runs.HardwareProfile mapProfile(const HardwareInfo& hardware, const Calibration& calibration,- const ProfileOverrides& overrides = {});+ const ProfileOverrides& overrides = {}, const ProfileTier* previousTier = nullptr);// 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).diff --git a/src/core/ThreadPool.cpp b/src/core/ThreadPool.cppindex 70443d7c..92e6f31d 100644--- a/src/core/ThreadPool.cpp+++ b/src/core/ThreadPool.cpp@@ -21,8 +21,22 @@ ThreadPool::~ThreadPool() {for (auto& t : workers_) t.join();}+namespace {+std::atomic<int> g_sharedThreads{0};+std::atomic<bool> g_sharedMade{false};+} // namespace++bool ThreadPool::setSharedThreadCount(int threads) {+ g_sharedThreads.store(std::clamp(threads, 0, 64));+ return !g_sharedMade.load();+}+ThreadPool& ThreadPool::shared() {- static ThreadPool pool(int(std::clamp(std::thread::hardware_concurrency(), 1u, 16u)));+ static ThreadPool pool([] {+ g_sharedMade.store(true);+ const int wanted = g_sharedThreads.load();+ return wanted > 0 ? wanted : int(std::clamp(std::thread::hardware_concurrency(), 1u, 16u));+ }());return pool;}diff --git a/src/core/ThreadPool.h b/src/core/ThreadPool.hindex 8aaa199d..b178b0f1 100644--- a/src/core/ThreadPool.h+++ b/src/core/ThreadPool.h@@ -29,6 +29,9 @@ public:// The pool brushes use: one thread per hardware thread (up to 16), the caller included.static ThreadPool& shared();+ // Threads for shared() (the hardware profile's, core/HardwareProfile.h), honoured if called before its first+ // use; 0 = automatic. Returns false when the pool already exists (the count applies at the next start).+ static bool setSharedThreadCount(int threads);int threads() const { return int(workers_.size()) + 1; }// Serial: every run() executes inline on the calling thread (tests compare results against this).