Skip to content

Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.

Hardware tiers: Essential / Standard / High / Extreme with per-tier budgets, first-run card, tier chip, Turbo, graphics card picker, Compute choice, memory guard, memory in the top bar

islandmedfd2be55849f7
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 0818f1f0..b9096dea 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -49,6 +49,7 @@ add_library(sculptforge_core STATIC
src/core/FrameGovernor.cpp
src/core/PerfTrace.cpp
src/core/TierConfig.cpp
+ src/core/HardwareTier.cpp
src/core/MemoryGuard.cpp
src/core/Sculpt.cpp
src/core/SculptBatch.cpp
@@ -237,6 +238,7 @@ target_sources(sculptforge_core PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/EmbeddedInse
target_include_directories(sculptforge_core PUBLIC src PRIVATE third_party/stb third_party/ufbx third_party/xatlas third_party/mikktspace third_party/tinyexr)
if(WIN32)
target_link_libraries(sculptforge_core PRIVATE shell32 advapi32) # core/Trash.cpp: the Recycle Bin; core/DiscordPresence.cpp: the pipe server's user
+ target_link_libraries(sculptforge_core PRIVATE dxgi) # core/HardwareTier.cpp: the graphics cards (GPU picker)
endif()
# Third-party C code: compile quietly.
if(MSVC)
@@ -393,6 +395,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/Calibration.cpp
src/app/OptimisticBench.cpp
src/app/PanelPerformanceProfile.cpp
+ src/app/PanelHardwareTier.cpp
src/app/CrashLog.cpp
src/app/App.cpp
src/app/Precision.cpp
@@ -943,6 +946,12 @@ if(SCULPTFORGE_BUILD_TESTS)
if(TEST ui_hardware_profile)
set_tests_properties(ui_hardware_profile PROPERTIES ENVIRONMENT "SF_HW_PROFILE_IN_TESTS=1")
endif()
+ # Hardware tiers: the first-run card, the tier chip, Turbo, the panel (tests/ui/hardware_tier.sfui).
+ # Also at 2880 px wide, so the 200 % top bar has room for the chip and the bolt (the shots show them).
+ sculptforge_ui_test(hardware_tier_2880 hardware_tier --size 2880x1620)
+ if(TEST ui_hardware_tier)
+ set_tests_properties(ui_hardware_tier ui_hardware_tier_2880 PROPERTIES ENVIRONMENT "SF_HW_PROFILE_IN_TESTS=1;SF_NO_CALIBRATION=1;SF_HW_SIMULATE=high")
+ endif()
# The shell layout again on a 1920x1080 window (docs/ui-design.md §2.3).
# Studio mode: About shows the studio (tests/data/studio; core/StudioProfile.h).
sculptforge_ui_test(studio_mode studio/studio_mode --studio ${CMAKE_CURRENT_SOURCE_DIR}/tests/data/studio/studio.json)
diff --git a/changes/feat-hw-tiers.md b/changes/feat-hw-tiers.md
new file mode 100644
index 00000000..15776a4e
--- /dev/null
+++ b/changes/feat-hw-tiers.md
@@ -0,0 +1,30 @@
+---
+whats_new: **Hardware tiers and Turbo**: SculptForge sorts your computer into a tier (Essential, Standard, High, Extreme) and switches on what it can carry: more Focus Detail memory, 16K textures. A card on first launch says what it found; the tier sits in the top bar. The new bolt (**View > Turbo**, Ctrl+Alt+T) trades antialiasing and detail while you sculpt and orbit for speed, and puts everything back the moment you stop.
+highlight: Hardware tiers and a Turbo button
+added: **Hardware tiers** (Edit > Preferences > Performance): the detected tier and why ("RTX 3060, 12 GB VRAM, 32 GB
+ RAM: High"), what it turns on, Auto or any tier by hand. The Essential tier works exactly as before; Standard and up
+ keep more Focus Detail in memory, and High and up allow 16K paint and bake textures. A small card on first launch
+ (and after a hardware change) shows the tier once; the chip in the top bar opens the panel. A memory guard steps
+ the tier down a level when free memory runs low, and back up when there is room.
+ **Turbo** (the bolt in the top bar, View > Turbo, Ctrl+Alt+T): antialiasing off and a lighter view while you
+ sculpt and orbit, the detected tier's top budgets; full quality when the view stops, and Off changes nothing you
+ set. Remembered per computer.
+ **Graphics card** picker on computers with two (applies on the next start, through the system's own setting; a
+ card that fails to start falls back to the system's choice). **Compute: Auto / CPU / GPU**, with each task's path
+ shown (all CPU for now). SF_HW_SIMULATE=floor|standard|high|extreme, SF_TIER_<NAME>, SF_COMPUTE=cpu|gpu, SF_TURBO=1
+ for benches.
+ **Memory in the top bar**, beside the triangles and frame rate: SculptForge's RAM and the system's free RAM, and
+ the graphics card's memory in use where its driver reports it (NVIDIA; AMD shows what's free), updated once a
+ second; hover for the detail. Thanks, Oslen on Discord.
+testers:
+ - Top bar: the memory figure changes as you subdivide; the tooltip shows RAM used, free and total, and the graphics
+ card's memory (or says the card doesn't report it).
+ - Any OS, fresh settings folder: the tier card appears in the 3D view's corner with your GPU, memory and tier; Got
+ it hides it; it stays hidden after a restart.
+ - Windows laptop with two GPUs: Preferences > Performance > Graphics card lists both; pick the integrated one,
+ restart, the panel says "Drawing now on" it; Auto, restart, back on the discrete one.
+ - Click the bolt: it turns orange and the status bar says what changed; orbit a big sculpt; click again: AA and
+ everything as before.
+---
+Reviewers: core/HardwareTier.h is the contract focusdetail, core200m, microlod and billion-ideas read
+(currentTierConfig().budgets). Floor values are today's constants (tests/test_hardware_tier.cpp pins them).
diff --git a/docs/guide/performance.md b/docs/guide/performance.md
index fad0a2da..59ed479a 100644
--- a/docs/guide/performance.md
+++ b/docs/guide/performance.md
@@ -50,6 +50,48 @@ Open **Preferences** and click **Performance**.
| **Last stroke** | What your last stroke cost per dab: **Brush** (finding and moving the vertices), **Normals** (shading), **BVH** (the structure that finds the surface under the cursor), and the **GPU upload** per frame |
| **Memory** | What the scene holds: the meshes, the BVHs, the subdivision levels kept for stepping between them, the undo history (up to 1 GB; the oldest steps are dropped beyond that) and, roughly, the graphics card's buffers |
+## Your hardware tier
+
+On top of the profile below, SculptForge sorts your computer into a **tier**, so the bigger features switch on by
+themselves where your machine can carry them, and never where it can't. Every tier sculpts smoothly: the higher
+ones give more room for detail.
+
+| Tier | For | What it adds |
+|---|---|---|
+| **Essential** | every computer SculptForge runs on | settings tuned for the machine; Focus Detail keeps 512 MB of full-resolution detail close by |
+| **Standard** | 16 GB of memory, 6 or more threads and a 4 GB graphics card (or graphics that share the memory) | twice the Focus Detail memory, streamed in faster |
+| **High** | 32 GB, 8 or more threads and an 8 GB graphics card (or 32 GB shared, such as an Apple Pro or Max) | 2 GB of Focus Detail, 16K paint and bake textures |
+| **Extreme** | 64 GB, 16 or more threads and a 16 GB graphics card (or 64 GB shared) | 4 GB of Focus Detail, the most of everything |
+
+A graphics card or processor that measures slow keeps a lower tier, whatever its memory says.
+
+The first time SculptForge starts (and when you change the graphics card or the memory), a small card in the
+corner of the 3D view says what it found, for example *Your machine: RTX 3060, 12 GB VRAM, 32 GB RAM. Tier:
+High*, and what that turns on. Click **Got it**; it doesn't show again on this computer. The tier is also in the
+top bar, next to the bolt: click it to open **Edit > Preferences > Performance**.
+
+There, at the top:
+
+| Control | What it does |
+|---|---|
+| **Tier** | your machine, its tier, what the next tier would need, and **What this turns on** |
+| Auto / each tier | choose the tier yourself. A tier above the detected one is allowed; the memory guard still watches it |
+| **Turbo** | the same switch as the bolt (below) |
+| **Graphics card** | on a computer with two (a laptop's built-in and gaming graphics, or two cards): which one draws SculptForge. **Auto** takes the fastest one. It applies the next time SculptForge starts; if that card can't start, SculptForge goes back to the system's choice and says so |
+| **Compute** | **Auto**, **CPU** or **GPU** for the heavy work. Each task shows where it runs; the ones that have no graphics card version yet say *CPU only for now*. Auto uses the graphics card only where it measured faster, and never on the Essential tier |
+
+**Free memory is watched.** If your computer runs low on memory while you work (another program, a huge scene),
+SculptForge steps the tier down one level and says so in the status bar; detail streams in a little later and
+nothing is lost. When there is room again for a minute, it steps back up.
+
+### Turbo
+
+The small bolt in the top bar (also **View > Turbo**, <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>T</kbd>) gives everything
+your computer can safely spare to sculpting speed: while you sculpt or orbit, the view draws without
+antialiasing and with a lighter version of big scenes, and the tier's top budgets apply. The moment you stop, the
+view is back at full quality. It turns orange while on, and a line in the status bar says what it changed. Turn
+it off and every setting is exactly as you left it. SculptForge remembers it on this computer.
+
## The hardware profile
The first time you start SculptForge, a small window says **Getting to know this computer** for a second or two:
diff --git a/docs/guide/shortcuts.md b/docs/guide/shortcuts.md
index c9366530..93b1ab11 100644
--- a/docs/guide/shortcuts.md
+++ b/docs/guide/shortcuts.md
@@ -197,6 +197,7 @@ generated from SculptForge's action registry, the same source as the Controls wi
|---|---|---|
| Free | <kbd>Alt</kbd>+<kbd>Shift</kbd>+<kbd>F</kbd> | Rotation drags turn the view about the screen's axes and can roll it over the top (the default). Saved with the preferences. |
| Lock camera | <kbd>Shift</kbd>+<kbd>L</kbd> | Lock the camera for left-drags: a drag that starts on the background sculpts once it reaches the model instead of turning the view (Preferences > Input > Start strokes off the model, #62). The status bar shows CAMERA LOCKED while it is on. Right-drag or Alt+drag still move the view. Shift+L turns it on and off. |
+| Turbo | <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>T</kbd> | Everything this computer can safely give to sculpting speed, in one click: antialiasing off and a lighter view while you sculpt and orbit (full quality the moment you stop), and the top budgets of the tier this machine carries. It never goes past what the memory holds. Off puts everything back as you set it. Remembered on this computer. |
| X | <kbd>Alt</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd> | Rotation drags turn the view about the world X axis only (red): from the front, an up or down drag tips the model towards you or away. Shift still snaps to a side view; the axis gizmo shows the lock. Saved with the preferences. |
| Y (turntable) | <kbd>Alt</kbd>+<kbd>Shift</kbd>+<kbd>Y</kbd> | Rotation drags turn the view like a turntable: the model stays upright and turns about its vertical (Y) axis. Saved with the preferences. |
| Z | <kbd>Alt</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd> | Rotation drags turn the view about the world Z axis only (blue): from the front, a drag around the middle turns the model like a wheel. Shift still snaps to a side view; the axis gizmo shows the lock. Saved with the preferences. |
diff --git a/docs/performance.md b/docs/performance.md
index 526d2f32..50d6cb47 100644
--- a/docs/performance.md
+++ b/docs/performance.md
@@ -333,6 +333,27 @@ The app reads the power source with `SDL_GetPowerInfo` at start and every 5 seco
half the upload budget and 60 Hz (unless set by hand), and the status bar says so. The `draft_brush` override
(on / off) wins over both. `draftBrushMode` is a flag for the brush engine; the brushes don't read it yet.
+### Hardware tiers (core/HardwareTier.h, feat/hw-tiers)
+
+A second axis beside the render profile: **Floor** (shown as Essential) / **Standard** / **High** / **Extreme**, from
+the probed memory sizes, GPU type and threads, capped by the calibration (Standard needs 120M triangles/s, High 300M,
+Extreme 1000M; a dab over 2 ms stops at Standard). The render profile still sets the view's budgets from measured
+speed, unchanged. The tier sets `TierConfig::budgets` (TierBudgets), which the advanced levels read: Focus Detail
+(resident MB, GPU pool, ms per frame, streaming threshold), coarse LOD, micro and 1B-scene ceilings, the dense
+stroke knobs, 16K textures. **Floor's budgets are the constants every machine used before tiers**
+(tests/test_hardware_tier.cpp pins them), so the floor tier can't regress; the readers set higher tiers' values as
+they measure them.
+
+- `SF_HW_SIMULATE=floor|standard|high|extreme` forces a tier (floor keeps the integrated-GPU render budgets and 4
+ threads as before); `SF_TIER_<NAME>=<value>` pins one budget (`SF_TIER_FOCUS_RESIDENT_MB=1024`); `SF_COMPUTE=cpu|gpu`;
+ `SF_TURBO=1`.
+- Memory guard: once a second, free RAM (MemAvailable etc.) and free VRAM (NVX / ATI meminfo); under max(1 GB, RAM/10)
+ (or 256 MB VRAM) for 2 s steps the tier in effect down one level; over max(3 GB, RAM/4) for 60 s steps back up; at
+ most one change per 10 s.
+- Turbo: AA off while the view moves or a stroke runs, the motion proxy from half the threshold (even with Fast
+ Navigation off), 75 % resolution while moving, the detected tier's budgets if a lower one was set by hand. It
+ changes no saved setting.
+
### Render triangle budget and the frame governor
`renderTriangleBudget()` (core/HardwareProfile.h) is the number of triangles the 3D view may draw per frame to
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 835c0fdf..7ec106a3 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -144,6 +144,9 @@ bool App::init(const AppOptions& options) {
// Full screen on one monitor stays up when the pointer clicks on another (Windows multi-monitor, Discord).
SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0");
if (!headless && options.demo.empty()) applyCachedThreadCount(); // the hardware profile's threads, before any brush work
+ // The graphics card chosen in Preferences > Performance, before the GL context (a failed start falls back).
+ std::string gpuNotice;
+ if (!headless && options.demo.empty() && !sharedWindow_) gpuNotice = applyCachedGpuChoice();
if (sharedWindow_) syncSdlEnvironment(); // (what SDL_Init would have read)
else if (!SDL_Init(SDL_INIT_VIDEO)) {
startError_ = std::string("The window system did not start: ") + SDL_GetError();
@@ -230,6 +233,8 @@ bool App::init(const AppOptions& options) {
SDL_Log("%s", err.c_str());
return false;
}
+ if (!headless && options.demo.empty() && !sharedWindow_) gpuChoiceStarted(); // (the chosen card works)
+ if (!gpuNotice.empty()) status_ = gpuNotice;
timer.step("renderer");
renderer_.setEnvironmentWake([] { wakeMainLoop(); }); // (PBR view: a new environment's lighting is ready)
// Fill layers ask for Mesh Maps: the app bakes them on a worker thread (PanelFill.cpp, updateMeshMaps).
@@ -1225,7 +1230,7 @@ int App::run() {
renderSettings_.materialTint = materialTintFor(doc_.paintColor); // (Color > Colour tints the material)
renderSettings_.resolutionScale = float(uiPrefs_.viewResolution) / 100.0f; // (#80; only the window's view)
if (perf_.movingNow) // while the view moves, the floor tier draws fewer pixels; full resolution when it stops
- renderSettings_.resolutionScale = std::min(renderSettings_.resolutionScale, motionResolution());
+ renderSettings_.resolutionScale = std::min(renderSettings_.resolutionScale, turbo_ ? std::min(motionResolution(), 0.75f) : motionResolution());
hardwareProfileDrawStart();
perf_.samplesUsed = renderer_.drawView(camera_, fbW, fbH, renderSettings_, canvasViewport(fbW, fbH), samples);
if (snapshotEnv && *snapshotEnv && (sm.moving || sm.releasing)) {
diff --git a/src/app/App.h b/src/app/App.h
index 5f6f1721..b1b2e18b 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -1247,6 +1247,18 @@ private:
void applyHardwareProfile(const struct HardwareProfile& profile, bool announce);
void finishCalibration();
std::shared_ptr<struct HwProfileUi> hwProfile_;
+ // Hardware tiers (PanelHardwareTier.cpp, core/HardwareTier.h): the tier, GPU and Compute part of Preferences >
+ // Performance, the first-run tier card, the tier chip and Turbo in the top bar, the memory guard.
+ void drawHardwareTierSection();
+ void drawTierCard(); // once per machine, after calibration (or a hardware change); never blocks
+ void updateTierMemoryGuard(); // every frame (cheap: looks once a second)
+ void registerHardwareTierUiActions();
+ void saveProfileOverrides(const struct ProfileOverrides& o); // map, save, apply
+ std::string tierChipLabel() const; // "HIGH" / "" (no profile in this run)
+ void setTurbo(bool on);
+ bool turboOn() const;
+ bool turbo_ = false; // (mirrors the profile's overrides.turbo; SF_TURBO=1 for benches)
+ double turboToggledAt_ = -10.0; // the bolt's little animation
// Splats > Make sculptable (PanelSculptable.cpp, core/Sculptable.h): splat capture -> sculptable Part on a
// worker thread; the crop box and the face landmark review in the viewport.
void registerSculptableUiActions();
@@ -1687,6 +1699,13 @@ private:
bool hideBrushCursor_ = false; // demos: camera moves while the cursor is off screen
float fpsShown_ = -1.0f; // title-strip frame rate, refreshed twice a second
double fpsShownAt_ = 0.0;
+ // Title-strip memory (sfmonitor's request): sampled once a second, cheap (statm, meminfo, one GL query).
+ struct MemoryShown {
+ size_t appBytes = 0, freeBytes = 0, totalBytes = 0; // this process's resident RAM; the system's free and total
+ uint64_t gpuTotalMB = 0, gpuFreeMB = 0; // the graphics card, all programs; 0 = it doesn't say
+ double at = -1.0;
+ } memShown_;
+ void sampleMemoryShown();
public:
// The part of the window the 3D view uses (logical px); the whole window while the UI is hidden.
CanvasRect canvasRect() const;
diff --git a/src/app/Calibration.cpp b/src/app/Calibration.cpp
index ef69641a..1b24bee7 100644
--- a/src/app/Calibration.cpp
+++ b/src/app/Calibration.cpp
@@ -9,6 +9,8 @@
#include <SDL3/SDL.h>
#include <algorithm>
+#include <fstream>
+#include <filesystem>
#include <chrono>
#include <cmath>
#include <cstdio>
@@ -381,6 +383,15 @@ double measureUpload(bool quick) {
} // namespace
+uint64_t queryFreeVideoMemoryMB(const std::string& source) {
+ const bool nvx = source.rfind("GL_NVX", 0) == 0, ati = source.rfind("GL_ATI", 0) == 0;
+ if (!nvx && !ati) return 0;
+ while (gl::GetError() != GL_NO_ERROR) {}
+ GLint v[4] = {};
+ gl::GetIntegerv(nvx ? kGL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX : kGL_TEXTURE_FREE_MEMORY_ATI, v);
+ return gl::GetError() == GL_NO_ERROR && v[0] > 0 ? uint64_t(v[0]) >> 10 : 0;
+}
+
void probeHardware(HardwareInfo& info) {
probeSystem(info);
const GlExtra e = loadExtra();
@@ -595,6 +606,42 @@ void applyCachedThreadCount() {
ThreadPool::setSharedThreadCount(cached.settings.threads);
}
+namespace {
+std::string gpuMarkerPath() {
+ const std::string profile = hardwareProfilePath();
+ return profile.empty() ? std::string() : profile + ".gpu-starting";
+}
+} // namespace
+
+std::string applyCachedGpuChoice() {
+ const std::string marker = gpuMarkerPath();
+ if (marker.empty()) return {};
+ std::error_code ec;
+ const std::filesystem::path m(std::u8string(marker.begin(), marker.end()));
+ if (std::filesystem::exists(m, ec)) {
+ // The last start with a chosen card never reached its GL context: the system's choice this time.
+ std::filesystem::remove(m, ec);
+ clearGpuChoice();
+ SDL_Log("Graphics card: the last start on the chosen card failed; using the system's choice");
+ return "The chosen graphics card didn't start last time, so SculptForge uses the system's choice "
+ "(Preferences > Performance > Graphics card)";
+ }
+ HardwareProfile cached;
+ const std::string choice = loadHardwareProfile(hardwareProfilePath(), cached) ? cached.overrides.gpu : std::string();
+ const std::string did = applyGpuChoice(choice, listGpus());
+ if (did.empty()) return {};
+ SDL_Log("Graphics card: %s", did.c_str());
+ std::ofstream(m) << did << "\n";
+ return {};
+}
+
+void gpuChoiceStarted() {
+ const std::string marker = gpuMarkerPath();
+ if (marker.empty()) return;
+ std::error_code ec;
+ std::filesystem::remove(std::filesystem::path(std::u8string(marker.begin(), marker.end())), ec);
+}
+
HardwareProfile calibrateNow(bool quick, const ProfileOverrides& overrides, const ProfileTier* previous) {
Calibrator c(quick);
while (c.step()) {}
diff --git a/src/app/Calibration.h b/src/app/Calibration.h
index ef743d51..a9fa53e5 100644
--- a/src/app/Calibration.h
+++ b/src/app/Calibration.h
@@ -21,6 +21,9 @@ namespace sf {
// Fills the GPU fields of `info` from the current OpenGL context (and the machine's, through probeSystem).
void probeHardware(HardwareInfo& info);
+// Free video memory now (MB), with the extension probeHardware found (`vramSource`: GL_NVX_gpu_memory_info or
+// GL_ATI_meminfo); 0 = unknown. One glGetIntegerv: cheap enough for the memory guard's once-a-second look.
+uint64_t queryFreeVideoMemoryMB(const std::string& vramSource);
class Calibrator {
public:
@@ -70,6 +73,12 @@ private:
// Sets the shared thread pool's size from the cached profile (call before any brush work; core/ThreadPool.h).
void applyCachedThreadCount();
+// Before SDL_Init: the graphics card chosen in Preferences > Performance (Auto = the fastest discrete one), through the
+// platform's mechanism (core/HardwareTier.h applyGpuChoice). If the last start with a choice never got its GL context
+// (a marker file is left), this start uses the system's choice and returns a message saying so; else "".
+std::string applyCachedGpuChoice();
+// The GL context and renderer started: the choice worked (the marker goes).
+void gpuChoiceStarted();
// Calibrates now, blocking (about 2-3 s; quick: about 1 s). Needs a current OpenGL context.
HardwareProfile calibrateNow(bool quick, const ProfileOverrides& overrides, const ProfileTier* previous = nullptr);
diff --git a/src/app/FocusDetailApp.cpp b/src/app/FocusDetailApp.cpp
index 0f1fdeba..996dc89b 100644
--- a/src/app/FocusDetailApp.cpp
+++ b/src/app/FocusDetailApp.cpp
@@ -4,6 +4,7 @@
// Focus Detail in the app (prototype; core/FocusDetail.h): opening a .sfdetail file (or `--focus-detail FILE`,
// or the `standard-1b` benchmark scene) and, once a frame, telling the focus where the camera and brush are.
#include "app/App.h"
+#include "core/TierConfig.h"
#include "core/FocusDetail.h"
#include "core/Micro.h"
@@ -64,7 +65,10 @@ void App::updateFocusDetail() {
brush.radius = focusBrushRadius_;
brush.mirrorX = symmetry_.x;
}
- fd.update(m, view, brush, 3.0);
+ // The hardware tier's budgets (core/HardwareTier.h; Floor: 512 MB, 3 ms, as before tiers).
+ const TierBudgets& tb = currentTierConfig().budgets;
+ fd.budgetBytes = size_t(tb.focusResidentMB) << 20;
+ fd.update(m, view, brush, tb.focusUpdateMs);
}
} // namespace sf
diff --git a/src/app/HwProfileUi.h b/src/app/HwProfileUi.h
new file mode 100644
index 00000000..20b1be0c
--- /dev/null
+++ b/src/app/HwProfileUi.h
@@ -0,0 +1,55 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// The app's hardware profile state (PanelPerformanceProfile.cpp, PanelHardwareTier.cpp): the profile in effect,
+// calibration, the frame governor, the hardware tier's memory guard and first-run card.
+#pragma once
+
+#include "app/Calibration.h"
+
+#include "core/FrameGovernor.h"
+#include "core/HardwareProfile.h"
+#include "core/HardwareTier.h"
+#include "core/TierConfig.h"
+
+#include <deque>
+#include <memory>
+#include <string>
+#include <vector>
+
+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, drawStartMs = -1.0; // (drawStartMs: the 3D view's draw began; -1: not this frame)
+ struct Pending {
+ uint64_t frame;
+ FrameSample sample;
+ double cpuBeforeDrawMs; // the GPU waited through it inside the frame's timer query
+ };
+ std::deque<Pending> pending; // frames waiting for their GPU time
+ uint64_t revision = 0; // performanceSettingsRevision() when last applied
+ int displayHz = 0;
+ PowerSource power = PowerSource::Unknown;
+ double nextPowerCheck = 0.0; // seconds (SDL ticks)
+ TierConfig tier; // what currentTierConfig() holds
+ double lastCpuMs = 0.0, lastGpuMs = -1.0;
+ bool overridesOpen = false;
+ // Hardware tiers (PanelHardwareTier.cpp)
+ TierMemoryGuard memoryGuard; // steps the tier in effect down when free memory runs low
+ double nextMemoryCheck = 0.0; // seconds (SDL ticks)
+ bool tierCard = false; // the first-run tier card is showing
+ std::vector<GpuAdapter> gpus; // the graphics cards (listed when the panel first opens)
+ bool gpusListed = false;
+};
+
+} // namespace sf
diff --git a/src/app/I18nSimplifiedChinese.cpp b/src/app/I18nSimplifiedChinese.cpp
index 2e024c4c..f09c7772 100644
--- a/src/app/I18nSimplifiedChinese.cpp
+++ b/src/app/I18nSimplifiedChinese.cpp
@@ -4464,6 +4464,54 @@ constexpr Entry kSimplifiedChinese[] = {
"感谢你成为会员:你让 SculptForge 保持免费并持续成长。"},
{"SculptForge is free and open source. Members keep it free and growing (Help > Support SculptForge).",
"SculptForge 是免费的开源软件。会员让它保持免费并持续成长(帮助 > 支持 SculptForge)。"},
+ {"%s, %s: %s render profile",
+ "%s、%s:%s 渲染配置"},
+ {"Change it any time in",
+ "随时可以在这里更改:"},
+ {"Compute",
+ "计算"},
+ {"Everything this computer can safely give to sculpting speed, in one click: antialiasing off and a lighter view while you sculpt and orbit (full quality the moment you stop), and the top budgets of the tier this machine carries. It never goes past what the memory holds. Off puts everything back as you set it. Remembered on this computer.",
+ "一键把这台电脑能安全提供的资源都用在雕刻速度上:雕刻和旋转视图时关闭抗锯齿并使用较轻的视图(一停下就恢复完整质量),并使用这台电脑所属等级的最高预算。绝不超过内存能容纳的量。关闭后一切恢复成你的设置。在这台电脑上会记住。"},
+ {"Graphics card",
+ "显卡"},
+ {"Performance tier",
+ "性能等级"},
+ {"Preferences > Performance",
+ "偏好设置 > 性能"},
+ {"Render profile",
+ "渲染配置"},
+ {"Render profile: automatic",
+ "渲染配置:自动"},
+ {"The hardware tier SculptForge runs at on this computer. Click for what it turns on and to change it (Preferences > Performance).",
+ "SculptForge 在这台电脑上运行的硬件等级。单击可查看它开启了什么并更改(偏好设置 > 性能)。"},
+ {"The hardware tier this computer runs at, why, and what it turns on (Preferences > Performance).",
+ "这台电脑的硬件等级、原因,以及它开启了什么(偏好设置 > 性能)。"},
+ {"Tuned for your machine",
+ "已为你的电脑调校"},
+ {"Turned on:",
+ "已开启:"},
+ {"What this computer can carry beyond the essentials: bigger Focus Detail caches, 16K textures and the levels to come switch on by themselves where they fit, never where they don't. Every tier sculpts smoothly; nothing is sent anywhere.",
+ "这台电脑在基本功能之外还能负担的东西:更大的 Focus Detail 缓存、16K 纹理以及之后的等级,会在容纳得下的地方自动开启,容纳不下就不开。每个等级都能流畅雕刻;不会发送任何数据。"},
+ {"What this turns on:",
+ "这会开启:"},
+ {"Where the heavy work runs: on the processor (CPU) or the graphics card (GPU). Auto takes the GPU only where it measured faster on this computer, and never on the Essential tier. If a GPU path fails, that task switches to the CPU and says so once. Tasks without a GPU path yet stay on the CPU.",
+ "耗时的工作在哪里运行:处理器(CPU)或显卡(GPU)。Auto 只在这台电脑上测得 GPU 更快的地方使用 GPU,Essential 等级则都不用。若 GPU 路径失败,该任务会改用 CPU 并提示一次。尚无 GPU 路径的任务留在 CPU 上。"},
+ {"Which graphics card draws SculptForge, on computers with two (a laptop's integrated and discrete GPU, or two cards). Auto takes the fastest discrete one. It applies the next time SculptForge starts, through the system's own setting (Windows' graphics preference; on Linux, Mesa's DRI_PRIME or NVIDIA's render offload). If that card can't start, SculptForge falls back to the system's choice and says so.",
+ "在有两张显卡的电脑上(笔记本的集成与独立 GPU,或两张卡)由哪张显卡绘制 SculptForge。Auto 会选最快的独立显卡。下次启动 SculptForge 时生效,使用系统本身的设置(Windows 的图形偏好设置;Linux 上为 Mesa 的 DRI_PRIME 或 NVIDIA 的 render offload)。若该显卡无法启动,SculptForge 会改回系统的选择并提示。"},
+ {"free",
+ "可用"},
+ {"RAM used by SculptForge",
+ "SculptForge 使用的 RAM"},
+ {"RAM free",
+ "可用 RAM"},
+ {"Graphics card memory in use (all programs)",
+ "显卡内存使用量(所有程序)"},
+ {"Graphics card memory free",
+ "显卡可用内存"},
+ {"This graphics card doesn't report its memory use",
+ "这张显卡不报告内存使用量"},
+ {"Updated every second",
+ "每秒更新"},
};
} // namespace
diff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cpp
index 3cbb366c..7d9ba93b 100644
--- a/src/app/I18nSpanish.cpp
+++ b/src/app/I18nSpanish.cpp
@@ -4942,6 +4942,54 @@ constexpr Entry kSpanish[] = {
"Gracias por ser miembro: mantienes SculptForge gratis y en crecimiento."},
{"SculptForge is free and open source. Members keep it free and growing (Help > Support SculptForge).",
"SculptForge es libre y de código abierto. Los miembros lo mantienen gratis y en crecimiento (Ayuda > Apoya a SculptForge)."},
+ {"%s, %s: %s render profile",
+ "%s, %s: perfil de render %s"},
+ {"Change it any time in",
+ "Cámbialo cuando quieras en"},
+ {"Compute",
+ "Cálculo"},
+ {"Everything this computer can safely give to sculpting speed, in one click: antialiasing off and a lighter view while you sculpt and orbit (full quality the moment you stop), and the top budgets of the tier this machine carries. It never goes past what the memory holds. Off puts everything back as you set it. Remembered on this computer.",
+ "Todo lo que este equipo puede dar con seguridad a la velocidad de esculpido, con un clic: sin antialiasing y una vista más ligera mientras esculpes y orbitas (calidad completa en cuanto paras), y los presupuestos máximos del nivel que soporta esta máquina. Nunca pasa de lo que cabe en memoria. Al apagarlo todo vuelve a como lo tenías. Se recuerda en este equipo."},
+ {"Graphics card",
+ "Tarjeta gráfica"},
+ {"Performance tier",
+ "Nivel de rendimiento"},
+ {"Preferences > Performance",
+ "Preferencias > Rendimiento"},
+ {"Render profile",
+ "Perfil de render"},
+ {"Render profile: automatic",
+ "Perfil de render: automático"},
+ {"The hardware tier SculptForge runs at on this computer. Click for what it turns on and to change it (Preferences > Performance).",
+ "El nivel de hardware con el que SculptForge funciona en este equipo. Haz clic para ver qué activa y cambiarlo (Preferencias > Rendimiento)."},
+ {"The hardware tier this computer runs at, why, and what it turns on (Preferences > Performance).",
+ "El nivel de hardware de este equipo, por qué y qué activa (Preferencias > Rendimiento)."},
+ {"Tuned for your machine",
+ "Ajustado para tu equipo"},
+ {"Turned on:",
+ "Activado:"},
+ {"What this computer can carry beyond the essentials: bigger Focus Detail caches, 16K textures and the levels to come switch on by themselves where they fit, never where they don't. Every tier sculpts smoothly; nothing is sent anywhere.",
+ "Lo que este equipo puede llevar más allá de lo esencial: cachés de Focus Detail más grandes, texturas de 16K y los niveles que vendrán se activan solos donde caben, nunca donde no. Todos los niveles esculpen con fluidez; no se envía nada a ningún sitio."},
+ {"What this turns on:",
+ "Qué activa:"},
+ {"Where the heavy work runs: on the processor (CPU) or the graphics card (GPU). Auto takes the GPU only where it measured faster on this computer, and never on the Essential tier. If a GPU path fails, that task switches to the CPU and says so once. Tasks without a GPU path yet stay on the CPU.",
+ "Dónde se hace el trabajo pesado: en el procesador (CPU) o en la tarjeta gráfica (GPU). Auto usa la GPU solo donde midió que es más rápida en este equipo, y nunca en el nivel Essential. Si una ruta de GPU falla, esa tarea pasa a la CPU y lo dice una vez. Las tareas que aún no tienen ruta de GPU se quedan en la CPU."},
+ {"Which graphics card draws SculptForge, on computers with two (a laptop's integrated and discrete GPU, or two cards). Auto takes the fastest discrete one. It applies the next time SculptForge starts, through the system's own setting (Windows' graphics preference; on Linux, Mesa's DRI_PRIME or NVIDIA's render offload). If that card can't start, SculptForge falls back to the system's choice and says so.",
+ "Qué tarjeta gráfica dibuja SculptForge en equipos con dos (la GPU integrada y la dedicada de un portátil, o dos tarjetas). Auto elige la dedicada más rápida. Se aplica la próxima vez que SculptForge arranca, mediante el ajuste del propio sistema (la preferencia de gráficos de Windows; en Linux, DRI_PRIME de Mesa o el render offload de NVIDIA). Si esa tarjeta no puede arrancar, SculptForge vuelve a la elección del sistema y lo dice."},
+ {"free",
+ "libre"},
+ {"RAM used by SculptForge",
+ "RAM que usa SculptForge"},
+ {"RAM free",
+ "RAM libre"},
+ {"Graphics card memory in use (all programs)",
+ "Memoria de la tarjeta gráfica en uso (todos los programas)"},
+ {"Graphics card memory free",
+ "Memoria libre de la tarjeta gráfica"},
+ {"This graphics card doesn't report its memory use",
+ "Esta tarjeta gráfica no informa de su uso de memoria"},
+ {"Updated every second",
+ "Se actualiza cada segundo"},
};
} // namespace
diff --git a/src/app/I18nTraditionalChinese.cpp b/src/app/I18nTraditionalChinese.cpp
index b33f8707..f5fac74f 100644
--- a/src/app/I18nTraditionalChinese.cpp
+++ b/src/app/I18nTraditionalChinese.cpp
@@ -4462,6 +4462,54 @@ constexpr Entry kTraditionalChinese[] = {
"感謝你成為會員:你讓 SculptForge 保持免費並持續成長。"},
{"SculptForge is free and open source. Members keep it free and growing (Help > Support SculptForge).",
"SculptForge 是免費的開源軟體。會員讓它保持免費並持續成長(說明 > 支持 SculptForge)。"},
+ {"%s, %s: %s render profile",
+ "%s、%s:%s 算繪設定檔"},
+ {"Change it any time in",
+ "隨時可以在這裡變更:"},
+ {"Compute",
+ "運算"},
+ {"Everything this computer can safely give to sculpting speed, in one click: antialiasing off and a lighter view while you sculpt and orbit (full quality the moment you stop), and the top budgets of the tier this machine carries. It never goes past what the memory holds. Off puts everything back as you set it. Remembered on this computer.",
+ "一鍵把這台電腦能安全提供的資源都用在雕刻速度上:雕刻和旋轉視圖時關閉反鋸齒並使用較輕的檢視(一停下就恢復完整品質),並使用這台電腦所屬等級的最高預算。絕不超過記憶體能容納的量。關閉後一切恢復成你的設定。在這台電腦上會記住。"},
+ {"Graphics card",
+ "顯示卡"},
+ {"Performance tier",
+ "效能等級"},
+ {"Preferences > Performance",
+ "偏好設定 > 效能"},
+ {"Render profile",
+ "算繪設定檔"},
+ {"Render profile: automatic",
+ "算繪設定檔:自動"},
+ {"The hardware tier SculptForge runs at on this computer. Click for what it turns on and to change it (Preferences > Performance).",
+ "SculptForge 在這台電腦上執行的硬體等級。按一下可查看它開啟了什麼並變更(偏好設定 > 效能)。"},
+ {"The hardware tier this computer runs at, why, and what it turns on (Preferences > Performance).",
+ "這台電腦的硬體等級、原因,以及它開啟了什麼(偏好設定 > 效能)。"},
+ {"Tuned for your machine",
+ "已為你的電腦調校"},
+ {"Turned on:",
+ "已開啟:"},
+ {"What this computer can carry beyond the essentials: bigger Focus Detail caches, 16K textures and the levels to come switch on by themselves where they fit, never where they don't. Every tier sculpts smoothly; nothing is sent anywhere.",
+ "這台電腦在基本功能之外還能負擔的東西:更大的 Focus Detail 快取、16K 紋理以及之後的等級,會在容納得下的地方自動開啟,容納不下就不開。每個等級都能流暢雕刻;不會傳送任何資料。"},
+ {"What this turns on:",
+ "這會開啟:"},
+ {"Where the heavy work runs: on the processor (CPU) or the graphics card (GPU). Auto takes the GPU only where it measured faster on this computer, and never on the Essential tier. If a GPU path fails, that task switches to the CPU and says so once. Tasks without a GPU path yet stay on the CPU.",
+ "繁重工作在哪裡執行:處理器(CPU)或顯示卡(GPU)。Auto 只在這台電腦上量測到 GPU 較快的地方使用 GPU,Essential 等級則一律不用。若 GPU 路徑失敗,該工作會改用 CPU 並提示一次。尚無 GPU 路徑的工作留在 CPU 上。"},
+ {"Which graphics card draws SculptForge, on computers with two (a laptop's integrated and discrete GPU, or two cards). Auto takes the fastest discrete one. It applies the next time SculptForge starts, through the system's own setting (Windows' graphics preference; on Linux, Mesa's DRI_PRIME or NVIDIA's render offload). If that card can't start, SculptForge falls back to the system's choice and says so.",
+ "在有兩張顯示卡的電腦上(筆電的內建與獨立 GPU,或兩張卡)由哪張顯示卡繪製 SculptForge。Auto 會選最快的獨立顯示卡。下次啟動 SculptForge 時生效,使用系統本身的設定(Windows 的圖形設定;Linux 上為 Mesa 的 DRI_PRIME 或 NVIDIA 的 render offload)。若該顯示卡無法啟動,SculptForge 會改回系統的選擇並提示。"},
+ {"free",
+ "可用"},
+ {"RAM used by SculptForge",
+ "SculptForge 使用的 RAM"},
+ {"RAM free",
+ "可用 RAM"},
+ {"Graphics card memory in use (all programs)",
+ "顯示卡記憶體使用量(所有程式)"},
+ {"Graphics card memory free",
+ "顯示卡可用記憶體"},
+ {"This graphics card doesn't report its memory use",
+ "這張顯示卡不會回報記憶體使用量"},
+ {"Updated every second",
+ "每秒更新"},
};
} // namespace
diff --git a/src/app/PanelHardwareTier.cpp b/src/app/PanelHardwareTier.cpp
new file mode 100644
index 00000000..864bd428
--- /dev/null
+++ b/src/app/PanelHardwareTier.cpp
@@ -0,0 +1,378 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Hardware tiers in the app (core/HardwareTier.h, docs/performance.md "Hardware tiers"):
+// - Preferences > Performance, at the top: the tier and why ("RTX 3060, 12 GB VRAM, 32 GB RAM: High"), what it turns
+// on, Auto / each tier; the graphics card (on machines with two); Compute: Auto / CPU / GPU and each task's path;
+// - the first-run card: once per machine (after the first calibration, or a new GPU / memory size), never blocking;
+// - the tier chip in the top bar (Shell.cpp) opens the panel; Turbo (View > Turbo, Ctrl+Alt+T, the bolt in the top
+// bar): antialiasing off and a lighter view while you sculpt and orbit, the detected tier's top budgets;
+// everything comes back as it was when the view stops, and Off changes nothing the user set;
+// - the memory guard: once a second, free RAM (and video memory where the driver says); tight -> the tier in effect
+// steps down a level (with a status message), roomy again for a minute -> back up.
+#include "app/App.h"
+#include "app/Calibration.h"
+#include "app/HwProfileUi.h"
+#include "app/I18n.h"
+#include "app/ShellGeometry.h"
+#include "app/Theme.h"
+#include "app/Ui.h"
+
+#include "core/Benchmark.h"
+#include "core/HardwareTier.h"
+#include "core/MemoryGuard.h"
+#include "core/ThreadPool.h"
+
+#include <SDL3/SDL.h>
+#include <imgui.h>
+
+#include <algorithm>
+#include <cmath>
+#include <cstdlib>
+
+namespace sf {
+
+namespace {
+
+constexpr const char* kPath = "Preferences > Performance";
+
+void dimWrapped(const std::string& text) {
+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
+ ImGui::TextWrapped("%s", text.c_str());
+ ImGui::PopStyleColor();
+}
+
+void bullet(const std::string& text) {
+ ImGui::Bullet();
+ ImGui::SameLine();
+ ImGui::TextWrapped("%s", text.c_str());
+}
+
+std::string upperCase(std::string s) {
+ for (char& c : s) c = char(std::toupper(static_cast<unsigned char>(c)));
+ return s;
+}
+
+bool envTurbo() {
+ const char* v = std::getenv("SF_TURBO");
+ return v && *v == '1';
+}
+
+} // namespace
+
+bool App::turboOn() const { return turbo_; }
+
+std::string App::tierChipLabel() const {
+ if (!hwProfile_ || !hwProfile_->active) return {};
+ return hwTierDisplayName(hwProfile_->tier.hwTier);
+}
+
+void App::saveProfileOverrides(const ProfileOverrides& o) {
+ if (!hwProfile_) return;
+ const HardwareProfile& cur = hwProfile_->profile;
+ const HardwareProfile next = mapProfile(cur.hardware, cur.calibration, o, &cur.measuredTier);
+ std::string error;
+ if (!saveHardwareProfile(hardwareProfilePath(), next, error)) SDL_Log("Hardware profile not saved: %s", error.c_str());
+ applyHardwareProfile(next, false);
+}
+
+void App::setTurbo(bool on) {
+ turbo_ = on;
+ turboToggledAt_ = ImGui::GetCurrentContext() ? ImGui::GetTime() : 0.0;
+ if (hwProfile_) {
+ ProfileOverrides o = hwProfile_->profile.overrides;
+ o.turbo = on; // remembered per machine (hardware_profile.json)
+ saveProfileOverrides(o);
+ }
+ if (!on) {
+ status_ = "Turbo off: everything is as you set it";
+ return;
+ }
+ // One line, what it changed (only what this machine and these settings get).
+ std::string what;
+ auto add = [&](const std::string& s) { what += (what.empty() ? "" : ", ") + s; };
+ if (uiPrefs_.antialiasing > 1) add("antialiasing off while you sculpt and orbit");
+ add("a lighter view while the view moves");
+ if (hwProfile_) {
+ const HardwareProfile& p = hwProfile_->profile;
+ if (p.detected.tier > p.hwTier) add(std::string("the full ") + hwTierDisplayName(p.detected.tier) + " budgets");
+ if (hwProfile_->tier.memoryStepDown > 0) add("within the memory free now");
+ }
+ status_ = "Turbo on: " + what + ". Full quality the moment you stop";
+}
+
+void App::registerHardwareTierUiActions() {
+ if (envTurbo()) turbo_ = true; // (benches: SF_TURBO=1)
+ Action a;
+ a.id = "view.turbo";
+ a.label = "Turbo";
+ a.palette = "View";
+ a.shortcut = "Ctrl+Alt+T";
+ a.run = [this] { setTurbo(!turbo_); };
+ a.checked = [this] { return turbo_; };
+ a.description = "Everything this computer can safely give to sculpting speed, in one click: antialiasing off and a "
+ "lighter view while you sculpt and orbit (full quality the moment you stop), and the top budgets of "
+ "the tier this machine carries. It never goes past what the memory holds. Off puts everything back "
+ "as you set it. Remembered on this computer.";
+ actions_.add(std::move(a));
+ Action t;
+ t.id = "perf.open_tier";
+ t.label = "Performance tier";
+ t.palette = kPath;
+ t.run = [this] { openPerformancePrefs(); };
+ t.description = "The hardware tier this computer runs at, why, and what it turns on (Preferences > Performance).";
+ actions_.add(std::move(t));
+}
+
+void App::updateTierMemoryGuard() {
+ if (!hwProfile_) return;
+ // UI tests share the PC with other jobs, whose memory use would step the tier and change the status line
+ // (ui_hardware_profile saw 52 MB of video memory free during a bench); SF_TIER_GUARD_IN_TESTS=1 turns it on.
+ static const bool offInTests = !options_.uiTest.empty() && !std::getenv("SF_TIER_GUARD_IN_TESTS");
+ if (offInTests) return;
+ HwProfileUi& hw = *hwProfile_;
+ const double now = double(SDL_GetTicksNS()) * 1e-9;
+ if (now < hw.nextMemoryCheck) return;
+ hw.nextMemoryCheck = now + 1.0;
+ const uint64_t freeMB = uint64_t(availableMemoryBytes() >> 20);
+ const uint64_t gpuFreeMB = hw.profile.hardware.gpuKind == GpuKind::Discrete ? queryFreeVideoMemoryMB(hw.profile.hardware.vramSource) : 0;
+ const HwTier chosen = hw.tier.chosenHwTier;
+ const int change = hw.memoryGuard.update(now, freeMB, hw.profile.hardware.ramMB, gpuFreeMB, int(chosen));
+ if (!change) return;
+ const HwTier was = hw.tier.hwTier;
+ const HardwareProfile p = hw.profile;
+ applyHardwareProfile(p, false);
+ SDL_Log("Hardware tier: memory guard %s (%llu MB free, GPU %llu MB): %s -> %s", change > 0 ? "stepped down" : "stepped back up",
+ (unsigned long long)freeMB, (unsigned long long)gpuFreeMB, hwTierName(was), hwTierName(hw.tier.hwTier));
+ status_ = change > 0 ? std::string("Memory is tight: ") + hwTierDisplayName(hw.tier.hwTier) +
+ " budgets for now (detail streams in a little later; nothing is lost)"
+ : std::string("Memory freed up: back to ") + hwTierDisplayName(hw.tier.hwTier) + " budgets";
+}
+
+void App::sampleMemoryShown() {
+ const double now = ImGui::GetTime();
+ if (memShown_.at >= 0.0 && now - memShown_.at < 1.0) return;
+ memShown_.at = now;
+ memShown_.appBytes = residentBytes();
+ memShown_.freeBytes = availableMemoryBytes();
+ memShown_.totalBytes = size_t(std::max(SDL_GetSystemRAM(), 0)) << 20;
+ // Video memory where the driver reports it (NVIDIA; AMD gives free only); integrated graphics share the RAM above.
+ memShown_.gpuTotalMB = memShown_.gpuFreeMB = 0;
+ if (hwProfile_ && !hwProfile_->calibrator) {
+ const HardwareInfo& h = hwProfile_->profile.hardware;
+ memShown_.gpuFreeMB = queryFreeVideoMemoryMB(h.vramSource);
+ if (h.gpuKind == GpuKind::Discrete && h.vramSource.rfind("GL_NVX", 0) == 0) memShown_.gpuTotalMB = h.vramMB;
+ }
+}
+
+void App::drawHardwareTierSection() {
+ if (!hwProfile_ || hwProfile_->calibrator) return; // (the profile section says why, or shows the progress)
+ HwProfileUi& hw = *hwProfile_;
+ const HardwareProfile& p = hw.profile;
+ const TierConfig& tc = hw.tier;
+ ImGui::TextUnformatted(tr("Tier"));
+ ui::HelpText("Tier", nullptr,
+ "What this computer can carry beyond the essentials: bigger Focus Detail caches, 16K textures and "
+ "the levels to come switch on by themselves where they fit, never where they don't. Every tier "
+ "sculpts smoothly; nothing is sent anywhere.",
+ kPath);
+ if (fontBold_) ImGui::PushFont(fontBold_);
+ ImGui::TextWrapped("%s", tierSummary(p.detected, tc.hwTier).c_str());
+ if (fontBold_) ImGui::PopFont();
+ ImGui::LogText("%s", tierSummary(p.detected, tc.hwTier).c_str());
+ if (tc.memoryStepDown > 0)
+ ImGui::TextColored(theme::accent, "%s", (std::string("Stepped down from ") + hwTierDisplayName(tc.chosenHwTier) +
+ " while memory is tight; it steps back up when there is room")
+ .c_str());
+ HwTier simulated;
+ if (simulatedHwTier(simulated)) dimWrapped(std::string("Forced by SF_HW_SIMULATE=") + std::getenv("SF_HW_SIMULATE"));
+ else if (p.hwTier != p.detected.tier) dimWrapped(std::string("Set by hand; this computer was detected as ") + hwTierDisplayName(p.detected.tier));
+ if (!p.detected.limit.empty()) dimWrapped(p.detected.limit);
+ ImGui::TextUnformatted(tr("What this turns on:"));
+ for (const std::string& line : tierTurnsOn(tc.hwTier, tc.budgets)) {
+ bullet(line);
+ ImGui::LogText("%s", line.c_str());
+ }
+
+ // Auto / each tier.
+ {
+ std::vector<std::string> names;
+ names.push_back(std::string("Auto (") + hwTierDisplayName(p.detected.tier) + ")");
+ for (int i = 0; i < kHwTierCount; ++i)
+ names.push_back(hwTierDisplayName(HwTier(i)) + std::string(i > int(p.detected.tier) ? " (more than detected)" : ""));
+ int index = 0;
+ HwTier set;
+ if (!p.overrides.level.empty() && hwTierFromName(p.overrides.level, set)) index = int(set) + 1;
+ ImGui::SetNextItemWidth(-1.0f);
+ if (ImGui::BeginCombo("##perf.level", names[size_t(index)].c_str())) {
+ for (int i = 0; i < int(names.size()); ++i)
+ if (ImGui::Selectable(names[size_t(i)].c_str(), i == index) && i != index) {
+ ProfileOverrides o = p.overrides;
+ o.level = i == 0 ? std::string() : std::string(hwTierName(HwTier(i - 1)));
+ saveProfileOverrides(o);
+ status_ = i == 0 ? std::string("Tier: automatic (") + hwTierDisplayName(p.detected.tier) + ")"
+ : std::string("Tier: ") + hwTierDisplayName(HwTier(i - 1)) +
+ (i - 1 > int(p.detected.tier) ? " (the memory guard still steps down if it runs low)" : "");
+ }
+ ImGui::EndCombo();
+ }
+ }
+ bool turbo = turbo_;
+ if (ImGui::Checkbox(tr("Turbo"), &turbo)) setTurbo(turbo);
+ ui::HelpAction(*this, "view.turbo");
+
+ // The graphics card.
+ ImGui::Spacing();
+ if (!hw.gpusListed) {
+ hw.gpus = listGpus();
+ hw.gpusListed = true;
+ }
+ const std::string current = p.hardware.glRenderer.empty() ? std::string("unknown") : shortGpuName(p.hardware.glRenderer);
+ if (hw.gpus.size() >= 2) {
+ ImGui::TextUnformatted(tr("Graphics card"));
+ ui::HelpText("Graphics card", nullptr,
+ "Which graphics card draws SculptForge, on computers with two (a laptop's integrated and discrete "
+ "GPU, or two cards). Auto takes the fastest discrete one. It applies the next time SculptForge "
+ "starts, through the system's own setting (Windows' graphics preference; on Linux, Mesa's "
+ "DRI_PRIME or NVIDIA's render offload). If that card can't start, SculptForge falls back to the "
+ "system's choice and says so.",
+ kPath);
+ const std::string autoId = autoGpuId(hw.gpus);
+ std::string autoName = "the system's choice";
+ for (const GpuAdapter& g : hw.gpus)
+ if (g.id == autoId) autoName = g.name;
+ std::vector<std::pair<std::string, std::string>> items = {{"", "Auto (" + autoName + ")"}};
+ for (const GpuAdapter& g : hw.gpus) items.push_back({g.id, g.name + (g.discrete ? "" : " (integrated)")});
+ int index = 0;
+ for (int i = 1; i < int(items.size()); ++i)
+ if (items[size_t(i)].first == p.overrides.gpu) index = i;
+ ImGui::SetNextItemWidth(-1.0f);
+ if (ImGui::BeginCombo("##perf.gpu", items[size_t(index)].second.c_str())) {
+ for (int i = 0; i < int(items.size()); ++i)
+ if (ImGui::Selectable(items[size_t(i)].second.c_str(), i == index) && i != index) {
+ ProfileOverrides o = p.overrides;
+ o.gpu = items[size_t(i)].first;
+ saveProfileOverrides(o);
+ status_ = "Graphics card: " + items[size_t(i)].second + ". Applies when SculptForge starts again";
+ }
+ ImGui::EndCombo();
+ }
+ dimWrapped("Drawing now on " + current + (hw.gpus.size() >= 2 ? ". A change applies after a restart." : ""));
+ } else {
+#if defined(__APPLE__)
+ dimWrapped("Graphics card: " + current + " (macOS picks the graphics card)");
+#else
+ dimWrapped("Graphics card: " + current);
+#endif
+ }
+
+ // Compute: Auto / CPU / GPU, and the path each task takes.
+ ImGui::Spacing();
+ ImGui::TextUnformatted(tr("Compute"));
+ ui::HelpText("Compute", nullptr,
+ "Where the heavy work runs: on the processor (CPU) or the graphics card (GPU). Auto takes the GPU "
+ "only where it measured faster on this computer, and never on the Essential tier. If a GPU path "
+ "fails, that task switches to the CPU and says so once. Tasks without a GPU path yet stay on the "
+ "CPU.",
+ kPath);
+ {
+ ComputeChoice saved = ComputeChoice::Auto;
+ computeChoiceFromName(p.overrides.compute, saved);
+ int index = int(saved);
+ const char* names[] = {tr("Auto"), tr("CPU"), tr("GPU")};
+ ImGui::SetNextItemWidth(-1.0f);
+ if (ImGui::Combo("##perf.compute", &index, names, 3) && index != int(saved)) {
+ ProfileOverrides o = p.overrides;
+ o.compute = index == 0 ? std::string() : std::string(computeChoiceName(ComputeChoice(index)));
+ saveProfileOverrides(o);
+ }
+ if (tc.compute != saved) dimWrapped(std::string("SF_COMPUTE=") + computeChoiceName(tc.compute) + " (set for this run)");
+ for (int i = 0; i < kComputeTaskCount; ++i) {
+ const ComputeTaskInfo& info = computeTaskInfo(ComputeTask(i));
+ const ComputePath path = resolveCompute(info.task, tc.compute, tc.hwTier, 0.0, 0.0);
+ const std::string line = std::string(info.name) + ": " + (path == ComputePath::Gpu ? "GPU" : "CPU") +
+ (!info.gpuPath ? " (CPU only for now)" : gpuComputeFailed(info.task) ? " (GPU failed: CPU)" : "");
+ if (!info.gpuPath) ImGui::BeginDisabled();
+ bullet(line);
+ if (!info.gpuPath) ImGui::EndDisabled();
+ ImGui::LogText("%s", line.c_str());
+ }
+ }
+ ImGui::Separator();
+ ImGui::Spacing();
+}
+
+void App::drawTierCard() {
+ HwProfileUi& hw = *hwProfile_;
+ const HardwareProfile& p = hw.profile;
+ const float s = uiScale_;
+ const ImGuiViewport* vp = ImGui::GetMainViewport();
+ // Bottom right, over the canvas; it takes no focus and nothing waits for it.
+ const float w = 400.0f * s;
+ // (Inside the 3D view when there is one, so it never covers the trays and shelves.)
+ const CanvasRect& cv = shell_.canvas;
+ const ImVec2 corner = cv.w > 0.0f && cv.h > 0.0f ? ImVec2(cv.x + cv.w - 16.0f * s, cv.y + cv.h - 16.0f * s)
+ : ImVec2(vp->WorkPos.x + vp->WorkSize.x - 24.0f * s, vp->WorkPos.y + vp->WorkSize.y - 48.0f * s);
+ ImGui::SetNextWindowPos(corner, ImGuiCond_Always, ImVec2(1.0f, 1.0f));
+ ImGui::SetNextWindowSize(ImVec2(w, 0.0f));
+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(18.0f * s, 16.0f * s));
+ ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 8.0f * s);
+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1.0f);
+ ImGui::PushStyleColor(ImGuiCol_Border, theme::accent);
+ const bool open = ImGui::Begin("##tiercard", nullptr,
+ ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
+ ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoFocusOnAppearing |
+ ImGuiWindowFlags_NoNav);
+ ImGui::PopStyleColor();
+ ImGui::PopStyleVar(3);
+ if (open) {
+ // The gauge, ours: a half dial and its needle in the accent.
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ const float r = 11.0f * s;
+ const ImVec2 at = ImGui::GetCursorScreenPos();
+ const ImVec2 c(at.x + r, at.y + r * 1.25f);
+ dl->PathArcTo(c, r, 3.14159f, 6.28318f, 20);
+ dl->PathStroke(theme::u32(theme::accent), 0, 2.0f * s);
+ const float angle = 3.14159f * (1.0f + (float(int(hw.tier.hwTier)) + 1.0f) / float(kHwTierCount + 1));
+ dl->AddLine(c, ImVec2(c.x + std::cos(angle) * r * 0.8f, c.y + std::sin(angle) * r * 0.8f), theme::u32(theme::textBright), 2.0f * s);
+ dl->AddCircleFilled(c, 2.0f * s, theme::u32(theme::textBright));
+ ImGui::Dummy(ImVec2(2.0f * r + 8.0f * s, 2.0f * r));
+ ImGui::SameLine();
+ if (fontBold_) ImGui::PushFont(fontBold_);
+ ImGui::AlignTextToFramePadding();
+ ImGui::TextUnformatted(tr("Tuned for your machine"));
+ if (fontBold_) ImGui::PopFont();
+ ImGui::TextWrapped("%s", ("Your machine: " + p.detected.machine + ".").c_str());
+ if (fontBold_) ImGui::PushFont(fontBold_);
+ ImGui::TextColored(theme::accent, "%s", (std::string("Tier: ") + hwTierDisplayName(hw.tier.hwTier)).c_str());
+ if (fontBold_) ImGui::PopFont();
+ ImGui::LogText("Your machine: %s. Tier: %s", p.detected.machine.c_str(), hwTierDisplayName(hw.tier.hwTier));
+ ImGui::Spacing();
+ ImGui::TextDisabled("%s", tr("Turned on:"));
+ for (const std::string& line : tierTurnsOn(hw.tier.hwTier, hw.tier.budgets)) bullet(line);
+ ImGui::Spacing();
+ ImGui::TextDisabled("%s", tr("Change it any time in"));
+ ImGui::SameLine(0.0f, 4.0f * s);
+ ImGui::PushStyleColor(ImGuiCol_Text, theme::accent);
+ if (ImGui::Selectable(tr("Preferences > Performance"), false, 0, ImGui::CalcTextSize(tr("Preferences > Performance"))))
+ openPerformancePrefs();
+ ImGui::PopStyleColor();
+ ImGui::Spacing();
+ const float bw = ImGui::CalcTextSize(tr("Got it")).x + 28.0f * s;
+ ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - bw);
+ ImGui::PushStyleColor(ImGuiCol_Button, theme::accent);
+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, theme::accentHover);
+ ImGui::PushStyleColor(ImGuiCol_Text, theme::textOnAccent);
+ const bool gotIt = ImGui::Button(tr("Got it"), ImVec2(bw, 0.0f));
+ ImGui::PopStyleColor(3);
+ if (gotIt) {
+ hw.tierCard = false;
+ ProfileOverrides o = p.overrides;
+ o.tierCardFor = tierCardKey(p.hardware); // not again on this machine
+ saveProfileOverrides(o);
+ }
+ }
+ ImGui::End();
+}
+
+} // namespace sf
diff --git a/src/app/PanelPerformance.cpp b/src/app/PanelPerformance.cpp
index 313f1eb6..9aa5fed1 100644
--- a/src/app/PanelPerformance.cpp
+++ b/src/app/PanelPerformance.cpp
@@ -197,8 +197,12 @@ int App::viewSamples() {
if (doc_.parts[size_t(i)].visible) triangles += doc_.partMesh(i).triangleCount();
perf_.movingNow = moving;
perf_.sceneTriangles = triangles;
- perf_.proxyNow = uiPrefs_.fastNavigation && moving && triangles >= fastNavigationTriangles(hardwareProfileGoverns());
- perf_.fastNow = aa > 1 && perf_.proxyNow;
+ // Turbo (View > Turbo): the lighter proxy from half the threshold, and no antialiasing while the view moves or a
+ // stroke runs, whatever the scene's size; still frames are drawn as set.
+ const size_t proxyFrom = fastNavigationTriangles(hardwareProfileGoverns());
+ perf_.proxyNow = (uiPrefs_.fastNavigation || turbo_) && moving && triangles >= (turbo_ ? proxyFrom / 2 : proxyFrom);
+ const bool working = moving || doc_.sculptor.strokeActive() || !dabQueue_.empty();
+ perf_.fastNow = aa > 1 && (perf_.proxyNow || (turbo_ && working));
perf_.samplesWanted = perf_.fastNow ? 1 : aa;
return perf_.samplesWanted;
}
diff --git a/src/app/PanelPerformanceProfile.cpp b/src/app/PanelPerformanceProfile.cpp
index d0d5b02d..a6d61b69 100644
--- a/src/app/PanelPerformanceProfile.cpp
+++ b/src/app/PanelPerformanceProfile.cpp
@@ -13,6 +13,7 @@
// machine), and keep the fixed 10 million triangle Fast Navigation threshold.
#include "app/App.h"
#include "app/Calibration.h"
+#include "app/HwProfileUi.h"
#include "app/CrashLog.h"
#include "app/Ui.h"
#include "app/UserData.h"
@@ -36,32 +37,6 @@
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, drawStartMs = -1.0; // (drawStartMs: the 3D view's draw began; -1: not this frame)
- struct Pending {
- uint64_t frame;
- FrameSample sample;
- double cpuBeforeDrawMs; // the GPU waited through it inside the frame's timer query
- };
- std::deque<Pending> pending; // frames waiting for their GPU time
- uint64_t revision = 0; // performanceSettingsRevision() when last applied
- int displayHz = 0;
- PowerSource power = PowerSource::Unknown;
- double nextPowerCheck = 0.0; // seconds (SDL ticks)
- TierConfig tier; // what currentTierConfig() holds
- double lastCpuMs = 0.0, lastGpuMs = -1.0;
- bool overridesOpen = false;
-};
namespace {
@@ -165,6 +140,10 @@ void App::initHardwareProfile() {
}
applyHardwareProfile(start, false);
if (!hw.calibrator) SDL_Log("Hardware profile: %s", start.reason.c_str());
+ SDL_Log("Hardware tier: %s (%s%s%s)", hwTierName(start.hwTier), start.detected.machine.c_str(),
+ start.detected.limit.empty() ? "" : "; ", start.detected.limit.c_str());
+ // The tier card: after calibration (finishCalibration), or now for a machine it wasn't shown on (SF_NO_CALIBRATION).
+ if (!hw.calibrator) hw.tierCard = start.overrides.tierCardFor != tierCardKey(start.hardware);
}
// Makes `p` the profile in effect: the process-wide settings and the governor's starting point; `announce` (after a
@@ -173,8 +152,15 @@ void App::applyHardwareProfile(const HardwareProfile& p, bool announce) {
HwProfileUi& hw = *hwProfile_;
hw.profile = p;
hw.active = true;
- // The tier's knobs for this power source and display; its target Hz is the governor's (60 / 120 / 144).
- hw.tier = tierConfigFor(p, hw.power, hw.displayHz);
+ turbo_ = p.overrides.turbo || turbo_;
+ // The tier's knobs for this power source and display; its target Hz is the governor's (60 / 120 / 144). Turbo
+ // takes the detected tier's budgets when a lower one was set by hand (never past what the machine carries, and
+ // the memory guard's steps still apply).
+ HardwareProfile forTier = p;
+ HwTier simulated;
+ if (turbo_ && !simulatedHwTier(simulated) && p.detected.tier > p.hwTier) forTier.hwTier = p.detected.tier;
+ forTier.overrides.turbo = turbo_;
+ hw.tier = tierConfigFor(forTier, hw.power, hw.displayHz, hw.memoryGuard.stepDown);
setCurrentTierConfig(hw.tier);
PerformanceSettings s = p.settings;
s.targetFps = hw.tier.targetHz;
@@ -189,6 +175,7 @@ void App::applyHardwareProfile(const HardwareProfile& p, bool announce) {
hw.tier.uploadBudgetMBPerFrame = s.uploadBudgetMBPerFrame;
hw.tier.residentCacheCapMB = std::min<uint64_t>(hw.tier.residentCacheCapMB, 1024);
hw.tier.zeroCopyUMA = false;
+ hw.tier.budgets.threads = 4;
setCurrentTierConfig(hw.tier);
SDL_Log("Hardware profile: simulating the floor tier (SF_HW_SIMULATE=floor): budget 2M triangles, 4 threads");
}
@@ -224,6 +211,8 @@ void App::finishCalibration() {
SDL_Log("Hardware profile: %s (%.0f ms)", p.reason.c_str(), p.calibration.durationMs);
applyHardwareProfile(p, hw.announce);
hw.announce = false;
+ // First launch, or another machine: the tier card says what it found (once per machine).
+ hw.tierCard = p.overrides.tierCardFor != tierCardKey(p.hardware);
}
void App::shutdownHardwareProfile() {
@@ -311,6 +300,7 @@ void App::hardwareProfileFrameEnd() {
std::to_string(hw.tier.targetHz) + " Hz";
}
}
+ updateTierMemoryGuard();
// The set_performance_override or calibrate command changed the profile: take it up.
if (performanceSettingsRevision() != hw.revision) {
HardwareProfile cached;
@@ -322,6 +312,9 @@ void App::hardwareProfileFrameEnd() {
bool App::hardwareCalibrating() const { return hwProfile_ && hwProfile_->calibrator; }
void App::drawHardwareProfileOverlay() {
+ // The first-run card is for people: benchmarks, takes and demos run without it (a take's stroke would land on it).
+ const bool scripted = options_.benchmark || !options_.benchmarkScript.empty() || !options_.demo.empty();
+ if (hwProfile_ && !hwProfile_->calibrator && hwProfile_->tierCard && !scripted) drawTierCard();
if (!hwProfile_ || !hwProfile_->calibrator) return;
HwProfileUi& hw = *hwProfile_;
const ImGuiViewport* vp = ImGui::GetMainViewport();
@@ -350,6 +343,7 @@ void App::drawHardwareProfileOverlay() {
}
void App::registerPerformanceProfileUiActions() {
+ registerHardwareTierUiActions(); // the tier, Compute, the graphics card, Turbo (PanelHardwareTier.cpp)
{
Action a;
a.id = "perf.recalibrate";
@@ -393,7 +387,8 @@ void App::registerPerformanceProfileUiActions() {
}
void App::drawPerformanceProfileSection() {
- ImGui::TextUnformatted(tr("Hardware profile"));
+ drawHardwareTierSection(); // the tier, why, what it turns on; graphics card; Compute (PanelHardwareTier.cpp)
+ ImGui::TextUnformatted(tr("Render 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 "
@@ -422,7 +417,7 @@ void App::drawPerformanceProfileSection() {
: h.vramMB ? formatMegabytes(h.vramMB)
: std::string("memory unknown");
if (fontBold_) ImGui::PushFont(fontBold_);
- ImGui::TextWrapped(tr("Detected %s, %s -> %s"), h.glRenderer.empty() ? "an unknown GPU" : h.glRenderer.c_str(), vram.c_str(),
+ ImGui::TextWrapped(tr("%s, %s: %s render profile"), h.glRenderer.empty() ? "An unknown GPU" : h.glRenderer.c_str(), vram.c_str(),
tierName(p.tier));
if (fontBold_) ImGui::PopFont();
// Why (the reason without the "Detected ... -> tier" the line above already says).
@@ -486,7 +481,7 @@ void App::drawPerformanceProfileSection() {
if (ImGui::TreeNode(tr("Manual overrides"))) {
ProfileOverrides o = p.overrides;
bool edited = false;
- const char* tiers[] = {tr("Tier: automatic"), tr("Software (safe mode)"), tr("Laptop / Budget"), tr("Workstation")};
+ const char* tiers[] = {tr("Render profile: automatic"), tr("Software (safe mode)"), tr("Laptop / Budget"), tr("Workstation")};
int tierIndex = 0;
ProfileTier forced;
if (!o.tier.empty() && tierFromName(o.tier, forced)) tierIndex = int(forced) + 1;
@@ -533,9 +528,13 @@ void App::drawPerformanceProfileSection() {
edited = true;
}
if (o.any() && ImGui::Button(tr("Back to automatic"))) {
- const bool governorWas = o.governor;
+ const ProfileOverrides was = o;
o = ProfileOverrides{};
- o.governor = governorWas;
+ o.governor = was.governor;
+ o.compute = was.compute; // (choices, not tuning: kept)
+ o.gpu = was.gpu;
+ o.turbo = was.turbo;
+ o.tierCardFor = was.tierCardFor;
edited = true;
}
if (edited) {
diff --git a/src/app/Shell.cpp b/src/app/Shell.cpp
index 5cfe4a38..e1966c9a 100644
--- a/src/app/Shell.cpp
+++ b/src/app/Shell.cpp
@@ -16,6 +16,7 @@
#include "app/Ui.h"
#include "app/I18n.h"
#include "core/LitSphere.h"
+#include "core/MemoryGuard.h"
#include "core/Micro.h"
#include "core/Multires.h"
#include "core/VertexPaint.h"
@@ -33,6 +34,7 @@
#include <filesystem>
#include <fstream>
#include <iterator>
+#include <tuple>
namespace sf {
@@ -1545,8 +1547,16 @@ void App::drawStatusBar(const ShellGeometry& g) {
// version, the workspaces, the search field (to its icon), then the last menus (into a >> button).
float searchW = 150.0f * s;
const float moreW = buttonH;
- auto menusRight = [&](bool presets) { // where the menus must end
+ // Turbo's bolt (View > Turbo, our own drawing, orange when on) and the hardware tier chip (opens Preferences >
+ // Performance), left of the layout presets. A narrow window drops the chip after the version, then the bolt, then
+ // the presets (View > Turbo and the Performance panel stay).
+ const float boltW = buttonH;
+ const std::string tierText = tierChipLabel();
+ const std::string tierLabel = tierText.empty() ? std::string() : std::string(ICON_LC_GAUGE) + " " + (caps ? upper(tr(tierText.c_str())) : std::string(tr(tierText.c_str())));
+ const float tierW = tierLabel.empty() ? 0.0f : textW(monoSmall, tierLabel) + 16.0f * s;
+ auto menusRight = [&](bool presets, bool chip = false, bool bolt = false) { // where the menus must end
return right - searchW - 10.0f * s - (presets ? 3.0f * wsW + 2.0f * s + 14.0f * s : 0.0f) -
+ (chip && tierW > 0.0f ? tierW + 8.0f * s : 0.0f) - (bolt ? boltW + 6.0f * s : 0.0f) -
(mayaLink ? linkW + 10.0f * s : 0.0f) - 12.0f * s;
};
auto menusWidth = [&](int n) {
@@ -1554,9 +1564,11 @@ void App::drawStatusBar(const ShellGeometry& g) {
for (int i = 0; i < n; ++i) w += menuWs[size_t(i)];
return w;
};
- const bool showVersion = brandEnd + versionW + menusGap + menusWidth(menuCount) <= menusRight(true); // (the modules give way)
+ const bool showVersion = brandEnd + versionW + menusGap + menusWidth(menuCount) <= menusRight(true, true, true); // (the modules give way)
const float menusX = brandEnd + (showVersion ? versionW : 0.0f) + menusGap;
- const bool showPresets = menusX + menusWidth(menuCount) <= menusRight(true);
+ const bool tierChip = tierW > 0.0f && menusX + menusWidth(menuCount) <= menusRight(true, true, true);
+ const bool boltShown = menusX + menusWidth(menuCount) <= menusRight(true, tierChip, true);
+ const bool showPresets = menusX + menusWidth(menuCount) <= menusRight(true, tierChip, boltShown);
if (!showPresets && menusX + menusWidth(menuCount) > menusRight(false)) searchW = buttonH + 4.0f * s; // just the icon
int shownMenus = menuCount;
while (shownMenus > 1 && menusX + menusWidth(shownMenus) > menusRight(false)) --shownMenus;
@@ -1569,6 +1581,16 @@ void App::drawStatusBar(const ShellGeometry& g) {
barSpans_.push_back({closeX, closeX + 2.0f * winW + 2.0f * s});
barSpans_.push_back({searchX, searchX + searchW});
if (showPresets) barSpans_.push_back({presetsX, presetsX + 3.0f * wsW + 2.0f * s});
+ const float boltX = right - boltW;
+ if (boltShown) {
+ right = boltX - 6.0f * s;
+ barSpans_.push_back({boltX, boltX + boltW});
+ }
+ const float tierX = right - tierW;
+ if (tierChip) {
+ right = tierX - 8.0f * s;
+ barSpans_.push_back({tierX, tierX + tierW});
+ }
if (showVersion) {
const float vx = textAt(monoSmall, brandEnd + 6.0f * s, theme::textDim, version.number);
@@ -1703,6 +1725,20 @@ void App::drawStatusBar(const ShellGeometry& g) {
// View > Lock camera (#62, Shift+L): left-drags on the background start strokes instead of turning the view.
if (uiPrefs_.airStrokes) mods.push_back({ICON_LC_LOCK, "camera", upper(tr("Camera locked")), true});
}
+ // Memory beside them (sfmonitor, Oslen on Discord): this app's RAM and the system's free RAM, then the graphics
+ // card's memory in use where its driver says. Once a second; the tooltip has the detail.
+ sampleMemoryShown();
+ const MemoryShown& mem = memShown_;
+ int ramMod = -1, gpuMod = -1;
+ if (mem.appBytes) {
+ ramMod = int(mods.size());
+ mods.push_back({ICON_LC_MEMORY_STICK, "ram", compactBytes(mem.appBytes) + (mem.freeBytes ? " / " + compactBytes(mem.freeBytes) + " " + tr("free") : std::string())});
+ }
+ if (mem.gpuTotalMB > mem.gpuFreeMB || mem.gpuFreeMB) {
+ gpuMod = int(mods.size());
+ mods.push_back({ICON_LC_GPU, "gpu", mem.gpuTotalMB > mem.gpuFreeMB ? compactBytes(size_t(mem.gpuTotalMB - mem.gpuFreeMB) << 20)
+ : compactBytes(size_t(mem.gpuFreeMB) << 20) + " " + tr("free")});
+ }
ImFont* labelFont = theme::look.id != 0 && fontMonoTiny_ ? fontMonoTiny_ : fontTiny_ ? fontTiny_ : monoSmall;
auto moduleW = [&](const StatusModule& m) {
switch (style) {
@@ -1717,19 +1753,25 @@ void App::drawStatusBar(const ShellGeometry& g) {
const float sepW = style == Status::Terminal ? textW(monoSmall, " | ") : style == Status::TitleBlock ? 0.0f : 16.0f * s;
// Drop the least important modules (from the file name inwards) until they fit beside the menus.
std::vector<int> shown = {0, 1, 2, 3, 4};
- if (mods.size() > 5) shown.insert(shown.begin() + 1, 5); // Camera locked, beside the mode (never dropped)
+ if (uiPrefs_.airStrokes) shown.insert(shown.begin() + 1, 5); // Camera locked, beside the mode (never dropped)
+ for (int m : {ramMod, gpuMod}) // after the triangles, before the frame rate
+ if (m >= 0) shown.insert(std::find(shown.begin(), shown.end(), 4), m);
auto total = [&] {
float w = 0.0f;
for (size_t k = 0; k < shown.size(); ++k) w += moduleW(mods[size_t(shown[k])]) + (k ? sepW : 0.0f);
return w;
};
- for (int drop : {2, 4, 1})
+ for (int drop : {gpuMod, 2, ramMod, 4, 1}) { // (RAM outlasts the file name, and shrinks to the app's own before it goes)
+ if (drop >= 0 && drop == ramMod && total() > right - menusEnd - 120.0f * s) mods[size_t(ramMod)].value = compactBytes(mem.appBytes);
if (total() > right - menusEnd - 120.0f * s) shown.erase(std::remove(shown.begin(), shown.end(), drop), shown.end());
+ }
// A narrow window (#105: 800 logical px at Windows' 200 %): never over the menus; the triangles go, then the mode.
- for (int drop : {3, 5, 0})
+ for (int drop : {gpuMod, ramMod, 3, 5, 0})
if (total() > right - menusEnd) shown.erase(std::remove(shown.begin(), shown.end(), drop), shown.end());
float mx = right - total();
const float modulesX = mx;
+ std::vector<std::tuple<int, float, float>> memSpans; // (module, x0, x1): the memory modules' tooltip
+
for (size_t k = 0; k < shown.size(); ++k) {
const StatusModule& m = mods[size_t(shown[k])];
const float w = moduleW(m);
@@ -1764,9 +1806,29 @@ void App::drawStatusBar(const ShellGeometry& g) {
textAt(monoSmall, ix + textW(monoSmall, " "), theme::text, m.value);
}
}
+ if (shown[k] == ramMod || shown[k] == gpuMod) memSpans.push_back({shown[k], mx, mx + w});
mx += w;
}
if (!shown.empty()) barSpans_.push_back({modulesX, mx});
+ for (const auto& [m, x0, x1] : memSpans) {
+ ImGui::SetCursorScreenPos(ImVec2(x0, o.y + (h - buttonH) * 0.5f));
+ ImGui::InvisibleButton(m == ramMod ? "##status.ram" : "##status.gpu", ImVec2(std::max(x1 - x0, 1.0f), buttonH));
+ if (ImGui::IsItemHovered()) {
+ std::string tip = std::string(tr("RAM used by SculptForge")) + ": " + memoryText(mem.appBytes);
+ if (mem.freeBytes)
+ tip += "\n" + std::string(tr("RAM free")) + ": " + memoryText(mem.freeBytes) +
+ (mem.totalBytes ? " / " + memoryText(mem.totalBytes) : std::string());
+ if (mem.gpuTotalMB > mem.gpuFreeMB)
+ tip += "\n" + std::string(tr("Graphics card memory in use (all programs)")) + ": " +
+ memoryText(size_t(mem.gpuTotalMB - mem.gpuFreeMB) << 20) + " / " + memoryText(size_t(mem.gpuTotalMB) << 20);
+ else if (mem.gpuFreeMB)
+ tip += "\n" + std::string(tr("Graphics card memory free")) + ": " + memoryText(size_t(mem.gpuFreeMB) << 20);
+ else
+ tip += "\n" + std::string(tr("This graphics card doesn't report its memory use"));
+ tip += "\n" + std::string(tr("Updated every second"));
+ ImGui::SetTooltip("%s", tip.c_str());
+ }
+ }
if (style == Status::TitleBlock)
dl->AddLine(ImVec2(std::floor(mx + 10.0f * s) + 0.5f, o.y + inset), ImVec2(std::floor(mx + 10.0f * s) + 0.5f, o.y + h - inset),
theme::u32(theme::tileBorder));
@@ -1782,6 +1844,48 @@ void App::drawStatusBar(const ShellGeometry& g) {
}
}
+ if (tierChip) {
+ ImGui::SetCursorScreenPos(ImVec2(tierX, o.y + (h - buttonH) * 0.5f));
+ const bool clicked = ImGui::InvisibleButton((std::string(tr("Performance tier")) + "##perf.tier_chip").c_str(), ImVec2(tierW, buttonH));
+ const bool hovered = ImGui::IsItemHovered();
+ const ImVec2 p = ImGui::GetItemRectMin();
+ dl->AddRect(p, ImVec2(p.x + tierW, p.y + buttonH), theme::u32(hovered ? theme::accent : theme::tileBorder), 3.0f * s);
+ if (hovered) dl->AddRectFilled(p, ImVec2(p.x + tierW, p.y + buttonH), theme::u32(theme::frameHover, 0.6f), 3.0f * s);
+ textAt(monoSmall, p.x + 8.0f * s, hovered ? theme::textBright : theme::textDim, tierLabel);
+ ImGui::LogText("%s", tierLabel.c_str());
+ if (clicked) openPerformancePrefs();
+ ui::HelpText("Performance tier", nullptr,
+ "The hardware tier SculptForge runs at on this computer. Click for what it turns on and to change it "
+ "(Preferences > Performance).",
+ "Status bar");
+ }
+ if (boltShown) {
+ // The bolt: two triangles of our own; orange when on; a short pop when it is switched.
+ ImGui::SetCursorScreenPos(ImVec2(boltX, o.y + (h - buttonH) * 0.5f));
+ const bool clicked = ImGui::InvisibleButton((std::string(tr("Turbo")) + "##view.turbo").c_str(), ImVec2(boltW, buttonH));
+ const bool hovered = ImGui::IsItemHovered();
+ const ImVec2 p = ImGui::GetItemRectMin();
+ const bool on = turboOn();
+ if (hovered) dl->AddRectFilled(p, ImVec2(p.x + boltW, p.y + buttonH), theme::u32(theme::frameHover, 0.7f), 3.0f * s);
+ const float since = float(ImGui::GetTime() - turboToggledAt_);
+ const float pop = since >= 0.0f && since < 0.3f ? 1.0f + 0.12f * std::sin(since / 0.3f * 3.14159f) : 1.0f;
+ const float u = buttonH * 0.30f * pop; // half height of the bolt
+ const ImVec2 c(p.x + boltW * 0.5f, p.y + buttonH * 0.5f);
+ const ImU32 col = theme::u32(on ? theme::accent : hovered ? theme::textBright : theme::textDim);
+ const float bx[6] = {0.30f, -0.50f, -0.04f, -0.30f, 0.50f, 0.04f}, by[6] = {-1.0f, 0.14f, 0.14f, 1.0f, -0.14f, -0.14f};
+ ImVec2 bolt[6];
+ for (int k = 0; k < 6; ++k) bolt[k] = ImVec2(c.x + bx[k] * u, c.y + by[k] * u);
+ if (on) dl->AddConcavePolyFilled(bolt, 6, col);
+ else dl->AddPolyline(bolt, 6, col, ImDrawFlags_Closed, std::max(1.0f, 1.25f * s));
+ ImGui::LogText("%s", on ? "Turbo on" : "Turbo off");
+ if (clicked) {
+ if (const Action* a = actions_.find("view.turbo"); a && a->run) {
+ actions_.touch(a->id);
+ a->run();
+ }
+ }
+ ui::HelpAction(*this, "view.turbo");
+ }
if (mayaLink) {
ImGui::SetCursorScreenPos(ImVec2(linkX, o.y + (h - buttonH) * 0.5f));
const bool clicked = ImGui::InvisibleButton((std::string(tr("Live link on")) + "##mayalink.chip").c_str(), ImVec2(linkW, buttonH));
diff --git a/src/core/HardwareProfile.cpp b/src/core/HardwareProfile.cpp
index 549e1913..079d010c 100644
--- a/src/core/HardwareProfile.cpp
+++ b/src/core/HardwareProfile.cpp
@@ -122,7 +122,8 @@ const char* tierName(ProfileTier tier) {
bool simulatedFloorTier() {
static const bool on = [] {
const char* v = std::getenv("SF_HW_SIMULATE");
- return v && std::string(v) == "floor";
+ HwTier t;
+ return v && hwTierFromName(v, t) && t == HwTier::Floor;
}();
return on;
}
@@ -512,7 +513,7 @@ PerformanceSettings applyOverrides(const PerformanceSettings& a, const ProfileOv
bool ProfileOverrides::any() const {
return !tier.empty() || renderTriangleBudget || motionProxyThreshold || vramBudgetMB || uploadBudgetMBPerFrame ||
maxTextureSize || maxSubdivisionTriangles || microTriangleLimit || threads || targetFps || !governor ||
- draftBrush;
+ draftBrush || !level.empty();
}
HardwareProfile mapProfile(const HardwareInfo& hardware, const Calibration& calibration, const ProfileOverrides& overrides,
@@ -530,6 +531,15 @@ HardwareProfile mapProfile(const HardwareInfo& hardware, const Calibration& cali
p.tier = forced;
}
p.automatic = settingsForTier(p.tier, hardware, calibration);
+ // The hardware tier: what the machine carries (core/HardwareTier.h), set by hand, or forced by SF_HW_SIMULATE.
+ p.detected = detectHwTier(hardware, calibration, p.tier);
+ p.hwTier = p.detected.tier;
+ HwTier level;
+ if (simulatedHwTier(level)) p.hwTier = level;
+ else if (!overrides.level.empty() && hwTierFromName(overrides.level, level)) p.hwTier = level;
+ // High and up: 16K textures where the GPU allows them and has the memory.
+ if (const int cap = budgetsForTier(p.hwTier).maxTextureSize; cap > p.automatic.maxTextureSize && p.automatic.vramBudgetMB >= 6144)
+ p.automatic.maxTextureSize = hardware.maxTextureSize > 0 ? std::min(cap, hardware.maxTextureSize) : p.automatic.maxTextureSize;
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;
@@ -539,6 +549,11 @@ HardwareProfile mapProfile(const HardwareInfo& hardware, const Calibration& cali
return p;
}
+std::string tierCardKey(const HardwareInfo& hw) {
+ // Rounded to GB: what the driver reports moves a little between runs.
+ return hw.glRenderer + "|" + std::to_string((hw.vramMB + 512) / 1024) + "|" + std::to_string((hw.ramMB + 512) / 1024);
+}
+
// ---------------------------------------------------------------------------
// Cache and JSON
// ---------------------------------------------------------------------------
@@ -650,6 +665,11 @@ Json overridesJson(const ProfileOverrides& o) {
if (o.targetFps) j.set("target_fps", o.targetFps);
if (!o.governor) j.set("governor", false);
if (o.draftBrush) j.set("draft_brush", o.draftBrush == 1 ? "on" : "off");
+ if (!o.level.empty()) j.set("level", o.level);
+ if (!o.compute.empty()) j.set("compute", o.compute);
+ if (!o.gpu.empty()) j.set("gpu", o.gpu);
+ if (o.turbo) j.set("turbo", true);
+ if (!o.tierCardFor.empty()) j.set("tier_card_for", o.tierCardFor);
return j;
}
@@ -667,6 +687,11 @@ void overridesFromJson(const Json& j, ProfileOverrides& o) {
o.targetFps = int(j["target_fps"].asNumber());
o.governor = j["governor"].asBool(true);
o.draftBrush = j["draft_brush"].asString() == "on" ? 1 : j["draft_brush"].asString() == "off" ? 2 : 0;
+ o.level = j["level"].asString();
+ o.compute = j["compute"].asString();
+ o.gpu = j["gpu"].asString();
+ o.turbo = j["turbo"].asBool(false);
+ o.tierCardFor = j["tier_card_for"].asString();
}
} // namespace
@@ -690,6 +715,7 @@ Json hardwareProfileToJson(const HardwareProfile& p) {
j.set("measured_tier", tierName(p.measuredTier));
j.set("settings", settingsJson(p.settings));
j.set("overrides", overridesJson(p.overrides));
+ j.set("hw_tier", hwTierName(p.hwTier)); // (informational: mapped again on load)
return j;
}
@@ -773,6 +799,16 @@ Json calibrationJson(const HardwareProfile& p, const TierConfig* tier) {
j.set("settings", settingsJson(p.settings));
j.set("automatic", settingsJson(p.automatic));
j.set("overrides", overridesJson(p.overrides));
+ {
+ Json t = Json::object();
+ t.set("tier", hwTierName(p.hwTier));
+ t.set("shown_as", hwTierDisplayName(p.hwTier));
+ t.set("detected", hwTierName(p.detected.tier));
+ t.set("machine", p.detected.machine);
+ t.set("limit", p.detected.limit);
+ t.set("budgets", tierBudgetsJson(budgetsForTier(p.hwTier)));
+ j.set("hardware_tier", t);
+ }
j.set("tier_config", tierConfigJson(tier ? *tier : tierConfigFor(p, PowerSource::Unknown, 0)));
j.set("network", false); // calibration never uses the network (no telemetry)
return j;
@@ -806,6 +842,7 @@ bool validateCalibrationJson(const Json& j, std::string& error) {
need(j, "$", "overrides", T::Object);
need(j, "$", "network", T::Bool);
need(j, "$", "tier_config", T::Object);
+ need(j, "$", "hardware_tier", T::Object);
if (!error.empty()) return false;
ProfileTier tier;
if (!tierFromName(j["profile"].asString(), tier)) {
@@ -995,7 +1032,24 @@ bool setOverride(ProfileOverrides& o, const std::string& name, const std::string
error = "tier must be Software, Laptop (or Budget), Workstation or auto";
return false;
}
- } else if (name == "render_triangle_budget") o.renderTriangleBudget = u;
+ } else if (name == "level" || name == "hardware_tier") {
+ HwTier t;
+ if (clear) o.level.clear();
+ else if (hwTierFromName(text, t)) o.level = hwTierName(t);
+ else {
+ error = "level must be Floor (Essential), Standard, High, Extreme or auto";
+ return false;
+ }
+ } else if (name == "compute") {
+ ComputeChoice c;
+ if (!computeChoiceFromName(clear ? "auto" : text, c)) {
+ error = "compute must be auto, cpu or gpu";
+ return false;
+ }
+ o.compute = c == ComputeChoice::Auto ? std::string() : computeChoiceName(c);
+ } else if (name == "gpu") o.gpu = clear ? std::string() : text;
+ else if (name == "turbo") o.turbo = !clear && (value != 0.0 || text == "on" || text == "true");
+ 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;
@@ -1082,7 +1136,9 @@ void registerHardwareProfileCommands(CommandRegistry& registry) {
}});
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), "
+ "back to the profile with value=auto. Settings: level (the hardware tier: Floor / Essential, Standard, High, "
+ "Extreme), compute (auto, cpu, gpu), gpu (a graphics card id, next start), turbo (on / off), tier (the "
+ "render profile: Software, Laptop, Workstation), "
"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, "
"draft_brush (on / off: normals and cavity at pen release), governor (on / off).",
diff --git a/src/core/HardwareProfile.h b/src/core/HardwareProfile.h
index 97259cab..d123cfe8 100644
--- a/src/core/HardwareProfile.h
+++ b/src/core/HardwareProfile.h
@@ -22,6 +22,7 @@
// (core/FrameGovernor.h) adjusts the render budgets at run time.
#pragma once
+#include "core/HardwareTier.h"
#include "core/Json.h"
#include <cstdint>
@@ -120,6 +121,12 @@ struct ProfileOverrides {
int targetFps = 0;
bool governor = true; // the adaptive frame governor (off: the budgets stay as set)
int draftBrush = 0; // TierConfig::draftBrushMode: 0 automatic, 1 always, 2 never
+ std::string level; // hardware tier (core/HardwareTier.h): "" = automatic, else a hwTierName()
+ // Kept by "Back to automatic" (choices, not tuning): not counted by any().
+ std::string compute; // "" / "auto", "cpu", "gpu" (Preferences > Performance > Compute)
+ std::string gpu; // the graphics card: "" = Auto, else a GpuAdapter::id (next start)
+ bool turbo = false; // Turbo (View > Turbo): remembered per machine
+ std::string tierCardFor; // the machine the first-run tier card was shown for (tierCardKey)
bool any() const;
};
@@ -132,8 +139,13 @@ struct HardwareProfile {
PerformanceSettings settings; // the tier's settings with the overrides applied
PerformanceSettings automatic; // before the overrides
ProfileOverrides overrides;
+ HwTierDetection detected; // the hardware tier the machine carries, and why
+ HwTier hwTier = HwTier::Floor; // the tier in effect (detected, or set by hand / SF_HW_SIMULATE)
};
+// The machine, for the first-run tier card: the GPU, its memory and the RAM (a driver update doesn't count).
+std::string tierCardKey(const HardwareInfo& hw);
+
// 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. `previousTier` (a re-calibration of the same GPU): a measurement within 15% of the
diff --git a/src/core/HardwareTier.cpp b/src/core/HardwareTier.cpp
new file mode 100644
index 00000000..70198c8b
--- /dev/null
+++ b/src/core/HardwareTier.cpp
@@ -0,0 +1,714 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/HardwareTier.h"
+
+#include "core/HardwareProfile.h"
+
+#include <algorithm>
+#include <cctype>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <mutex>
+#include <sstream>
+
+#if defined(_WIN32)
+#define WIN32_LEAN_AND_MEAN
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include <windows.h>
+#include <dxgi.h>
+#endif
+
+namespace sf {
+
+namespace {
+
+std::string lower(std::string s) {
+ std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+ return s;
+}
+
+std::string readText(const std::string& path) {
+ std::ifstream f(path, std::ios::binary);
+ if (!f) return {};
+ std::stringstream ss;
+ ss << f.rdbuf();
+ return ss.str();
+}
+
+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);
+}
+
+bool has(const std::string& haystack, const char* needle) { return haystack.find(needle) != std::string::npos; }
+
+void eraseAll(std::string& s, const char* what) {
+ for (size_t at; (at = s.find(what)) != std::string::npos;) s.erase(at, std::strlen(what));
+}
+
+constexpr uint64_t kM = 1'000'000;
+
+// What the OS reports is a little under the label: a 16 GB machine says about 15.5 GB, a 12 GB card 11.8 GB.
+constexpr uint64_t gb(double label) { return uint64_t(label * 1024.0 * 0.94); }
+
+} // namespace
+
+// ---------------------------------------------------------------------------
+// Names
+// ---------------------------------------------------------------------------
+
+const char* hwTierName(HwTier t) {
+ switch (t) {
+ case HwTier::Floor: return "Floor";
+ case HwTier::Standard: return "Standard";
+ case HwTier::High: return "High";
+ case HwTier::Extreme: return "Extreme";
+ }
+ return "Floor";
+}
+
+const char* hwTierDisplayName(HwTier t) {
+ // The base tier is named for what it is, the experience tuned for the machine; never "low".
+ return t == HwTier::Floor ? "Essential" : hwTierName(t);
+}
+
+bool hwTierFromName(const std::string& name, HwTier& out) {
+ const std::string n = lower(trim(name));
+ for (int i = 0; i < kHwTierCount; ++i)
+ if (n == lower(hwTierName(HwTier(i))) || n == lower(hwTierDisplayName(HwTier(i)))) {
+ out = HwTier(i);
+ return true;
+ }
+ return false;
+}
+
+bool simulatedHwTier(HwTier& out) {
+ const char* v = std::getenv("SF_HW_SIMULATE");
+ return v && *v && hwTierFromName(v, out);
+}
+
+// ---------------------------------------------------------------------------
+// Budgets
+// ---------------------------------------------------------------------------
+
+TierBudgets budgetsForTier(HwTier t) {
+ TierBudgets b; // Floor: the values before tiers
+ switch (t) {
+ case HwTier::Floor: break;
+ case HwTier::Standard:
+ b.residentTriangles = 500 * kM;
+ b.maxMicroTriangles = 500 * kM;
+ b.optInMicroTriangles = 2000 * kM;
+ b.maxDenseTriangles = 60 * kM;
+ b.microResidentMB = 1024;
+ b.focusTriangles = 400 * kM;
+ b.focusResidentMB = 1024;
+ b.focusGpuPoolMB = 512;
+ b.focusUpdateMs = 4.0;
+ break;
+ case HwTier::High:
+ b.residentTriangles = 1000 * kM;
+ b.maxMicroTriangles = 1000 * kM;
+ b.billionScenes = true;
+ b.optInMicroTriangles = 8000 * kM;
+ b.maxDenseTriangles = 120 * kM;
+ b.microResidentMB = 3072;
+ b.derivNormalPx = 1.5;
+ b.waveletDabSamples = 96;
+ b.gpuDabs = 1;
+ b.focusTriangles = 600 * kM;
+ b.focusResidentMB = 2048;
+ b.focusGpuPoolMB = 1024;
+ b.focusUpdateMs = 4.0;
+ b.maxTextureSize = 16384;
+ break;
+ case HwTier::Extreme:
+ b.residentTriangles = 2000 * kM;
+ b.maxMicroTriangles = 2000 * kM;
+ b.billionScenes = true;
+ b.optInMicroTriangles = 16000 * kM;
+ b.maxDenseTriangles = 250 * kM;
+ b.microResidentMB = 8192;
+ b.derivNormalPx = 1.0;
+ b.waveletDabSamples = 128;
+ b.gpuDabs = 1;
+ b.focusTriangles = 1000 * kM;
+ b.focusResidentMB = 4096;
+ b.focusGpuPoolMB = 2048;
+ b.focusUpdateMs = 6.0;
+ b.maxTextureSize = 16384;
+ break;
+ }
+ return b;
+}
+
+#define SF_FIELD(member, kind, what) {#member, what, TierBudgetField::Kind::kind, offsetof(TierBudgets, member)}
+
+const std::vector<TierBudgetField>& tierBudgetFields() {
+ // Snake-case names are made from the members below at first use (focusResidentMB -> focus_resident_mb).
+ static const std::vector<TierBudgetField> fields = [] {
+ std::vector<TierBudgetField> f = {
+ SF_FIELD(residentTriangles, U64, "triangles held in full detail"),
+ SF_FIELD(maxMicroTriangles, U64, "micro triangles held without asking"),
+ SF_FIELD(billionScenes, Bool, "1B-triangle scenes without asking"),
+ SF_FIELD(optInMicroTriangles, U64, "micro triangles when you opt in"),
+ SF_FIELD(maxDenseTriangles, U64, "one dense mesh before a hint"),
+ SF_FIELD(microResidentMB, U64, "GPU memory for resident micro detail (MB)"),
+ SF_FIELD(derivNormalPx, Double, "pixel size for derivative shading"),
+ SF_FIELD(waveletDabSamples, U64, "dab samples before coarse-level edits"),
+ SF_FIELD(gpuDabs, Int, "GPU dabs (0 off, 1 opt-in, 2 on)"),
+ SF_FIELD(focusTriangles, U64, "micro triangles before Focus Detail streams"),
+ SF_FIELD(focusResidentMB, U64, "Focus Detail tiles in memory (MB)"),
+ SF_FIELD(focusGpuPoolMB, U64, "Focus Detail GPU pool (MB)"),
+ SF_FIELD(focusUpdateMs, Double, "Focus Detail work per frame (ms)"),
+ SF_FIELD(focusLookaheadSeconds, Double, "Focus Detail brush look-ahead (s)"),
+ SF_FIELD(stillFrameMs, Double, "still frame GPU time before preview detail (ms)"),
+ SF_FIELD(stillDelaySeconds, Double, "rest before full detail (s)"),
+ SF_FIELD(motionBudgetFraction, Double, "triangle budget share while moving"),
+ SF_FIELD(coarseLevels, Bool, "coarse levels for dense bases"),
+ SF_FIELD(draftDabVertices, U64, "vertices per dab before draft dabs (0 never)"),
+ SF_FIELD(strokeBacklogMs, Double, "queued stroke work (ms)"),
+ SF_FIELD(normalsCatchUpMs, Double, "normal catch-up per frame (ms, 0 no cap)"),
+ SF_FIELD(maxTextureSize, Int, "largest texture"),
+ SF_FIELD(threads, Int, "worker threads (0 all)"),
+ };
+ static std::vector<std::string> names; // (stable storage for the converted names)
+ names.reserve(f.size());
+ for (auto& x : f) {
+ std::string s;
+ const std::string in = x.name;
+ for (size_t i = 0; i < in.size(); ++i) {
+ const char c = in[i];
+ const bool upper = std::isupper(static_cast<unsigned char>(c));
+ const bool prevLower = i > 0 && !std::isupper(static_cast<unsigned char>(in[i - 1]));
+ if (upper && i > 0 && (prevLower || (i + 1 < in.size() && std::islower(static_cast<unsigned char>(in[i + 1])))))
+ s += '_';
+ s += char(std::tolower(static_cast<unsigned char>(c)));
+ }
+ names.push_back(s);
+ x.name = names.back().c_str();
+ }
+ return f;
+ }();
+ return fields;
+}
+
+#undef SF_FIELD
+
+double tierBudgetValue(const TierBudgets& b, const TierBudgetField& f) {
+ const char* p = reinterpret_cast<const char*>(&b) + f.offset;
+ switch (f.kind) {
+ case TierBudgetField::Kind::U64: return double(*reinterpret_cast<const uint64_t*>(p));
+ case TierBudgetField::Kind::Double: return *reinterpret_cast<const double*>(p);
+ case TierBudgetField::Kind::Int: return double(*reinterpret_cast<const int*>(p));
+ case TierBudgetField::Kind::Bool: return *reinterpret_cast<const bool*>(p) ? 1.0 : 0.0;
+ }
+ return 0.0;
+}
+
+void setTierBudgetValue(TierBudgets& b, const TierBudgetField& f, double v) {
+ char* p = reinterpret_cast<char*>(&b) + f.offset;
+ switch (f.kind) {
+ case TierBudgetField::Kind::U64: *reinterpret_cast<uint64_t*>(p) = v > 0.0 ? uint64_t(v) : 0; break;
+ case TierBudgetField::Kind::Double: *reinterpret_cast<double*>(p) = std::max(0.0, v); break;
+ case TierBudgetField::Kind::Int: *reinterpret_cast<int*>(p) = std::max(0, int(v)); break;
+ case TierBudgetField::Kind::Bool: *reinterpret_cast<bool*>(p) = v != 0.0; break;
+ }
+}
+
+void applyTierBudgetEnv(TierBudgets& b) {
+ for (const TierBudgetField& f : tierBudgetFields()) {
+ std::string env = "SF_TIER_";
+ for (const char* c = f.name; *c; ++c) env += char(std::toupper(static_cast<unsigned char>(*c)));
+ const char* v = std::getenv(env.c_str());
+ if (!v || !*v) continue;
+ char* end = nullptr;
+ const double d = std::strtod(v, &end);
+ if (end != v) setTierBudgetValue(b, f, d);
+ else if (f.kind == TierBudgetField::Kind::Bool) setTierBudgetValue(b, f, lower(v) == "on" || lower(v) == "true" ? 1.0 : 0.0);
+ }
+}
+
+Json tierBudgetsJson(const TierBudgets& b) {
+ Json j = Json::object();
+ for (const TierBudgetField& f : tierBudgetFields()) {
+ if (f.kind == TierBudgetField::Kind::Bool) j.set(f.name, tierBudgetValue(b, f) != 0.0);
+ else j.set(f.name, tierBudgetValue(b, f));
+ }
+ return j;
+}
+
+// ---------------------------------------------------------------------------
+// Detection
+// ---------------------------------------------------------------------------
+
+std::string shortGpuName(const std::string& renderer) {
+ std::string s = renderer;
+ // Mesa's layered drivers name the real GPU in brackets: "D3D12 (NVIDIA GeForce RTX 3060)" (WSL),
+ // "zink Vulkan 1.3(NVIDIA GeForce RTX 3060 (NVIDIA_PROPRIETARY))".
+ if (s.rfind("D3D12 (", 0) == 0 || s.rfind("zink ", 0) == 0) {
+ const size_t open = s.find('(');
+ if (open != std::string::npos && open + 1 < s.size()) {
+ s.erase(0, open + 1);
+ if (!s.empty() && s.back() == ')') s.pop_back();
+ }
+ }
+ // Driver suffixes: "/PCIe/SSE2", Mesa's " (radeonsi, navi23, LLVM 15.0.7, DRM 3.54, 6.5.0)", "(KBL GT2)".
+ if (const size_t slash = s.find('/'); slash != std::string::npos) s.resize(slash);
+ if (const size_t paren = s.find(" ("); paren != std::string::npos) s.resize(paren);
+ eraseAll(s, "(R)");
+ eraseAll(s, "(TM)");
+ eraseAll(s, "(tm)");
+ if (s.rfind("Mesa ", 0) == 0) s.erase(0, 5);
+ if (s.rfind("NVIDIA GeForce ", 0) == 0) s.erase(0, 15);
+ else if (s.rfind("NVIDIA ", 0) == 0) s.erase(0, 7);
+ if (s.rfind("AMD Radeon RX", 0) == 0) s.erase(0, 4);
+ std::string out;
+ for (char c : s)
+ if (!(c == ' ' && (out.empty() || out.back() == ' '))) out += c;
+ out = trim(out);
+ return out.empty() ? trim(renderer) : out;
+}
+
+GlFeatures glFeatures(const std::string& v) {
+ GlFeatures f;
+ size_t i = 0;
+ while (i < v.size() && !std::isdigit(static_cast<unsigned char>(v[i]))) ++i;
+ if (i < v.size() && std::sscanf(v.c_str() + i, "%d.%d", &f.major, &f.minor) == 2) {
+ const int n = f.major * 10 + f.minor;
+ f.compute = n >= 43;
+ f.bufferStorage = n >= 44;
+ } else {
+ f.major = f.minor = 0;
+ }
+ return f;
+}
+
+namespace {
+
+struct TierNeed {
+ uint64_t ramMB;
+ int threads;
+ uint64_t discreteMB; // a graphics card with this much memory, or ...
+ uint64_t sharedRamMB; // ... a GPU sharing this much RAM (Apple, Asahi, big APUs)
+ double triangles; // measured million triangles / s (when measured)
+ const char* words; // what the tier needs, for "needs ..."
+};
+
+// Standard, High, Extreme (Floor needs nothing).
+const TierNeed kNeeds[3] = {
+ {gb(16), 6, gb(4), gb(16), 120.0, "16 GB RAM, 6 threads and a 4 GB graphics card"},
+ {gb(32), 8, gb(8), gb(32), 300.0, "32 GB RAM, 8 threads and an 8 GB graphics card (or 32 GB shared)"},
+ {gb(64), 16, gb(16), gb(64), 1000.0, "64 GB RAM, 16 threads and a 16 GB graphics card (or 64 GB shared)"},
+};
+
+// Why `hw` falls short of `need` ("" = it doesn't).
+std::string shortOf(const HardwareInfo& hw, const Calibration& c, const TierNeed& need, int level) {
+ if (hw.ramMB && hw.ramMB < need.ramMB) return "RAM";
+ if (hw.cpuThreads && hw.cpuThreads < need.threads) return "threads";
+ switch (hw.gpuKind) {
+ case GpuKind::Discrete:
+ if (hw.vramMB && hw.vramMB < need.discreteMB) return "video memory";
+ break;
+ case GpuKind::Unified:
+ if (hw.ramMB < need.sharedRamMB) return "shared memory";
+ break;
+ case GpuKind::Integrated:
+ // Integrated GPUs (Intel, AMD APUs) share the RAM but draw slower: up to Standard, or High for a big APU with
+ // 64 GB or more (Strix Halo, measured fast).
+ if (level >= 1 && hw.ramMB < kNeeds[2].sharedRamMB) return "integrated graphics";
+ if (level >= 2) return "integrated graphics";
+ break;
+ case GpuKind::Unknown: return "unknown graphics"; // (no GPU probed: stay on the base tier)
+ case GpuKind::Software: return "software rendering";
+ }
+ if (c.trianglesPerSecondM > 0.0 && c.trianglesPerSecondM < need.triangles) return "measured GPU speed";
+ if (c.dabMs > 0.0 && c.dabMs > (level >= 1 ? 2.0 : 4.0)) return "measured brush speed";
+ return {};
+}
+
+// "RAM" -> "this computer has less RAM", for the panel's limit line.
+std::string shortfallWords(const std::string& why) {
+ if (why == "threads") return "this computer has fewer threads";
+ if (why == "RAM" || why == "video memory" || why == "shared memory") return "this computer has less " + why;
+ if (why == "integrated graphics") return "this computer draws with integrated graphics";
+ if (why == "unknown graphics") return "the graphics card could not be identified";
+ if (why == "measured GPU speed") return "the graphics card measured slower";
+ if (why == "measured brush speed") return "brushes measured slower";
+ return why;
+}
+
+} // namespace
+
+HwTierDetection detectHwTier(const HardwareInfo& hw, const Calibration& c, ProfileTier renderTier) {
+ HwTierDetection d;
+ char buf[160];
+ const std::string gpu = hw.glRenderer.empty() ? std::string() : shortGpuName(hw.glRenderer);
+ std::string mem;
+ if (hw.gpuKind == GpuKind::Discrete && hw.vramMB) {
+ std::snprintf(buf, sizeof buf, "%.0f GB VRAM", double(hw.vramMB) / 1024.0 + 0.3);
+ mem = buf;
+ } else if (hw.gpuKind == GpuKind::Unified || hw.gpuKind == GpuKind::Integrated) {
+ mem = "shared memory";
+ }
+ std::snprintf(buf, sizeof buf, "%.0f GB RAM", double(hw.ramMB) / 1024.0 + 0.3);
+ for (const std::string& part : {gpu, mem, hw.ramMB ? std::string(buf) : std::string(),
+ hw.cpuThreads ? std::to_string(hw.cpuThreads) + " threads" : std::string()})
+ if (!part.empty()) d.machine += (d.machine.empty() ? "" : ", ") + part;
+ if (d.machine.empty()) d.machine = "this computer";
+ if (renderTier == ProfileTier::Software || hw.gpuKind == GpuKind::Software) {
+ d.tier = HwTier::Floor;
+ d.limit = "software rendering";
+ return d;
+ }
+ int level = 0;
+ while (level < 3) {
+ const std::string why = shortOf(hw, c, kNeeds[level], level);
+ if (!why.empty()) {
+ d.limit = std::string(hwTierDisplayName(HwTier(level + 1))) + " needs " + kNeeds[level].words + " (" + shortfallWords(why) + ")";
+ break;
+ }
+ ++level;
+ }
+ d.tier = HwTier(level);
+ return d;
+}
+
+std::string tierSummary(const HwTierDetection& d, HwTier inEffect) {
+ return d.machine + ": " + hwTierDisplayName(inEffect);
+}
+
+std::vector<std::string> tierTurnsOn(HwTier tier, const TierBudgets& b) {
+ // Only what this build really does with the tier (the other budgets go to their readers as they land).
+ std::vector<std::string> out;
+ if (tier == HwTier::Floor) {
+ out.push_back("Settings tuned for this machine, so sculpting stays smooth");
+ out.push_back("Focus Detail keeps " + formatMegabytes(b.focusResidentMB) + " of full-resolution detail close by");
+ } else {
+ out.push_back("Focus Detail keeps " + formatMegabytes(b.focusResidentMB) + " of full-resolution detail close by, and streams it in faster");
+ }
+ if (b.maxTextureSize >= 16384) out.push_back("16K paint and bake textures");
+ out.push_back("Free memory is watched: if it gets tight, the tier steps down instead of running out");
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Memory guard
+// ---------------------------------------------------------------------------
+
+int TierMemoryGuard::update(double now, uint64_t freeMB, uint64_t totalMB, uint64_t gpuFreeMB, int maxSteps) {
+ if (freeMB == 0 && gpuFreeMB == 0) return 0; // nothing known
+ const uint64_t tightBelow = std::max<uint64_t>(1024, totalMB / 10);
+ const uint64_t roomyAbove = std::max<uint64_t>(3072, totalMB / 4);
+ const bool tight = (freeMB && freeMB < tightBelow) || (gpuFreeMB && gpuFreeMB < 256);
+ const bool roomy = (!freeMB || freeMB > roomyAbove) && (!gpuFreeMB || gpuFreeMB > 1024);
+ tightSince = tight ? (tightSince < 0.0 ? now : tightSince) : -1.0;
+ roomySince = roomy ? (roomySince < 0.0 ? now : roomySince) : -1.0;
+ if (now - lastChange < 10.0) return 0;
+ if (tight && now - tightSince >= 2.0 && stepDown < maxSteps) {
+ ++stepDown;
+ lastChange = now;
+ tightSince = now;
+ return 1;
+ }
+ if (roomy && stepDown > 0 && now - roomySince >= 60.0) {
+ --stepDown;
+ lastChange = now;
+ roomySince = now;
+ return -1;
+ }
+ return 0;
+}
+
+// ---------------------------------------------------------------------------
+// Compute
+// ---------------------------------------------------------------------------
+
+namespace {
+
+// Which tasks have a GPU path in this build. None yet: micro shading's (perf/micro-gpu-shade) is parked, measured
+// slower on the floor tier; the research track has GPU dabs. They flip here when a path lands.
+const ComputeTaskInfo kTasks[kComputeTaskCount] = {
+ {ComputeTask::BrushSolver, "brush_solver", "Brush solver", false},
+ {ComputeTask::Normals, "normals", "Normals", false},
+ {ComputeTask::Remesh, "remesh", "Remesh", false},
+ {ComputeTask::Bake, "bake", "Bake", false},
+ {ComputeTask::FocusDecode, "focus_decode", "Focus Detail decode", false},
+ {ComputeTask::MicroShade, "micro_shade", "Micro detail shading", false},
+};
+
+std::mutex g_computeMutex;
+bool g_failed[kComputeTaskCount] = {};
+std::string g_failureMessage;
+
+} // namespace
+
+const ComputeTaskInfo& computeTaskInfo(ComputeTask t) { return kTasks[std::clamp(int(t), 0, kComputeTaskCount - 1)]; }
+
+const char* computeChoiceName(ComputeChoice c) {
+ switch (c) {
+ case ComputeChoice::Cpu: return "cpu";
+ case ComputeChoice::Gpu: return "gpu";
+ case ComputeChoice::Auto: break;
+ }
+ return "auto";
+}
+
+bool computeChoiceFromName(const std::string& name, ComputeChoice& out) {
+ const std::string n = lower(trim(name));
+ if (n == "auto" || n.empty()) out = ComputeChoice::Auto;
+ else if (n == "cpu") out = ComputeChoice::Cpu;
+ else if (n == "gpu") out = ComputeChoice::Gpu;
+ else return false;
+ return true;
+}
+
+ComputeChoice computeChoiceWithEnv(ComputeChoice saved) {
+ ComputeChoice c;
+ const char* v = std::getenv("SF_COMPUTE");
+ return v && *v && computeChoiceFromName(v, c) ? c : saved;
+}
+
+ComputePath resolveCompute(ComputeTask task, ComputeChoice choice, HwTier tier, double cpuMs, double gpuMs) {
+ if (!computeTaskInfo(task).gpuPath || gpuComputeFailed(task) || choice == ComputeChoice::Cpu) return ComputePath::Cpu;
+ if (choice == ComputeChoice::Gpu) return ComputePath::Gpu;
+ // Auto: the Floor tier stays on the CPU (as fast as before); elsewhere the GPU only where it measured faster.
+ if (tier == HwTier::Floor || !(cpuMs > 0.0) || !(gpuMs > 0.0)) return ComputePath::Cpu;
+ return gpuMs < cpuMs * 0.8 ? ComputePath::Gpu : ComputePath::Cpu;
+}
+
+void reportGpuComputeFailure(ComputeTask task, const std::string& why) {
+ std::lock_guard<std::mutex> lock(g_computeMutex);
+ const int i = std::clamp(int(task), 0, kComputeTaskCount - 1);
+ if (g_failed[i]) return;
+ g_failed[i] = true;
+ g_failureMessage = std::string(kTasks[i].name) + " switched to the CPU: the GPU path failed (" + why + ")";
+}
+
+bool gpuComputeFailed(ComputeTask task) {
+ std::lock_guard<std::mutex> lock(g_computeMutex);
+ return g_failed[std::clamp(int(task), 0, kComputeTaskCount - 1)];
+}
+
+bool takeComputeFailureMessage(std::string& message) {
+ std::lock_guard<std::mutex> lock(g_computeMutex);
+ if (g_failureMessage.empty()) return false;
+ message = std::move(g_failureMessage);
+ g_failureMessage.clear();
+ return true;
+}
+
+void resetComputeFailures() {
+ std::lock_guard<std::mutex> lock(g_computeMutex);
+ for (bool& f : g_failed) f = false;
+ g_failureMessage.clear();
+}
+
+// ---------------------------------------------------------------------------
+// Graphics cards
+// ---------------------------------------------------------------------------
+
+std::string pciIdsName(const std::string& text, uint32_t vendor, uint32_t device) {
+ char v[8], d[8];
+ std::snprintf(v, sizeof v, "%04x", vendor);
+ std::snprintf(d, sizeof d, "%04x", device);
+ std::istringstream in(text);
+ std::string line, vendorName;
+ bool inVendor = false;
+ while (std::getline(in, line)) {
+ if (line.empty() || line[0] == '#') continue;
+ if (line[0] != '\t') {
+ if (inVendor) break; // past our vendor's devices
+ if (line.compare(0, 4, v) == 0 && line.size() > 6) {
+ inVendor = true;
+ vendorName = trim(line.substr(4));
+ }
+ continue;
+ }
+ if (!inVendor || line.size() < 7 || line[1] == '\t') continue;
+ if (line.compare(1, 4, d) != 0) continue;
+ std::string name = trim(line.substr(5));
+ if (const size_t a = name.find('['), b = name.rfind(']'); a != std::string::npos && b != std::string::npos && b > a)
+ name = name.substr(a + 1, b - a - 1);
+ // "NVIDIA Corporation" -> "NVIDIA", "Advanced Micro Devices, Inc. [AMD/ATI]" -> "AMD", "Intel Corporation" -> "Intel"
+ std::string shortVendor = vendorName;
+ if (has(lower(vendorName), "nvidia")) shortVendor = "NVIDIA";
+ else if (has(lower(vendorName), "advanced micro") || has(lower(vendorName), "amd")) shortVendor = "AMD";
+ else if (has(lower(vendorName), "intel")) shortVendor = "Intel";
+ if (name.rfind(shortVendor, 0) == 0) return name;
+ return shortVendor + " " + name;
+ }
+ return {};
+}
+
+std::vector<GpuAdapter> listGpusSysfs(const std::string& root, const std::string& pciIdsPath) {
+ std::vector<GpuAdapter> out;
+ std::error_code ec;
+ if (!std::filesystem::is_directory(root, ec)) return out;
+ std::vector<std::filesystem::path> cards;
+ for (const auto& e : std::filesystem::directory_iterator(root, ec)) {
+ const std::string n = e.path().filename().string();
+ if (n.rfind("card", 0) == 0 && n.find('-') == std::string::npos) cards.push_back(e.path());
+ }
+ std::sort(cards.begin(), cards.end());
+ const std::string ids = pciIdsPath.empty() ? std::string() : readText(pciIdsPath);
+ for (const auto& card : cards) {
+ const auto dev = card / "device";
+ const std::string cls = trim(readText((dev / "class").string()));
+ if (cls.rfind("0x03", 0) != 0) continue; // display controllers only
+ GpuAdapter g;
+ g.vendorId = uint32_t(std::strtoul(trim(readText((dev / "vendor").string())).c_str(), nullptr, 16));
+ g.deviceId = uint32_t(std::strtoul(trim(readText((dev / "device").string())).c_str(), nullptr, 16));
+ g.bootDisplay = trim(readText((dev / "boot_vga").string())) == "1";
+ if (const std::string vram = trim(readText((dev / "mem_info_vram_total").string())); !vram.empty())
+ g.vramMB = std::strtoull(vram.c_str(), nullptr, 10) >> 20;
+ // The PCI address: the device link's target ("../../../0000:01:00.0").
+ std::string address = std::filesystem::read_symlink(dev, ec).filename().string();
+ if (ec || address.empty()) address = trim(readText((dev / "uevent").string()));
+ if (const size_t at = address.find("PCI_SLOT_NAME="); at != std::string::npos) {
+ address = address.substr(at + 14);
+ address = address.substr(0, address.find('\n'));
+ }
+ std::string id = "pci-" + address;
+ std::replace(id.begin(), id.end(), ':', '_');
+ std::replace(id.begin(), id.end(), '.', '_');
+ g.id = id;
+ g.name = ids.empty() ? std::string() : pciIdsName(ids, g.vendorId, g.deviceId);
+ char fallback[64];
+ const char* vendor = g.vendorId == 0x10de ? "NVIDIA" : g.vendorId == 0x1002 ? "AMD" : g.vendorId == 0x8086 ? "Intel" : "GPU";
+ std::snprintf(fallback, sizeof fallback, "%s GPU %04x:%04x", vendor, g.vendorId, g.deviceId);
+ if (g.name.empty()) g.name = fallback;
+ // Discrete: NVIDIA always (Tegra has no PCI card); AMD / Intel when they report their own video memory over
+ // 2 GB (APUs and iGPUs carve out 512 MB or less) or the name says so.
+ const std::string ln = lower(g.name);
+ if (g.vendorId == 0x10de) g.discrete = true;
+ else if (g.vendorId == 0x1002) g.discrete = g.vramMB >= 2048 || has(ln, " rx ") || has(ln, "radeon pro");
+ else if (g.vendorId == 0x8086) g.discrete = has(ln, "arc a") || has(ln, "arc b") || has(ln, "dg2") || has(ln, "battlemage");
+ out.push_back(g);
+ }
+ return out;
+}
+
+#if defined(_WIN32)
+namespace {
+std::vector<GpuAdapter> listGpusDxgi() {
+ std::vector<GpuAdapter> out;
+ IDXGIFactory1* factory = nullptr;
+ if (FAILED(CreateDXGIFactory1(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&factory))) || !factory) return out;
+ 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)) {
+ GpuAdapter g;
+ char name[256] = {};
+ WideCharToMultiByte(CP_UTF8, 0, d.Description, -1, name, sizeof name - 1, nullptr, nullptr);
+ g.name = trim(name);
+ g.vendorId = d.VendorId;
+ g.deviceId = d.DeviceId;
+ g.vramMB = uint64_t(d.DedicatedVideoMemory) >> 20;
+ g.discrete = g.vramMB >= 2048 || d.VendorId == 0x10de;
+ g.bootDisplay = i == 0;
+ char id[64];
+ std::snprintf(id, sizeof id, "pci-%04x_%04x", d.VendorId, d.DeviceId);
+ g.id = id;
+ if (std::none_of(out.begin(), out.end(), [&](const GpuAdapter& o) { return o.id == g.id; })) out.push_back(g);
+ }
+ adapter->Release();
+ }
+ factory->Release();
+ return out;
+}
+} // namespace
+#endif
+
+std::vector<GpuAdapter> listGpus() {
+#if defined(_WIN32)
+ return listGpusDxgi();
+#elif defined(__linux__)
+ std::string ids;
+ for (const char* p : {"/usr/share/hwdata/pci.ids", "/usr/share/misc/pci.ids", "/usr/share/pci.ids"})
+ if (std::filesystem::exists(p)) {
+ ids = p;
+ break;
+ }
+ return listGpusSysfs("/sys/class/drm", ids);
+#else
+ return {}; // macOS picks the graphics card itself
+#endif
+}
+
+std::string autoGpuId(const std::vector<GpuAdapter>& gpus) {
+ const GpuAdapter* best = nullptr;
+ for (const GpuAdapter& g : gpus)
+ if (g.discrete && (!best || g.vramMB > best->vramMB)) best = &g;
+ return best ? best->id : std::string();
+}
+
+#if defined(__linux__)
+namespace {
+bool userSet(const char* name) {
+ const char* v = std::getenv(name);
+ return v && *v;
+}
+void setEnv(const char* name, const std::string& value) { setenv(name, value.c_str(), 0); }
+} // namespace
+#endif
+
+std::string applyGpuChoice(const std::string& choice, const std::vector<GpuAdapter>& gpus) {
+ const bool automatic = choice.empty() || choice == "auto";
+ const std::string id = automatic ? autoGpuId(gpus) : choice;
+ const auto it = std::find_if(gpus.begin(), gpus.end(), [&](const GpuAdapter& g) { return g.id == id; });
+ if (it == gpus.end()) return {};
+ // One card, or the card the desktop already runs on: nothing to do.
+ if (gpus.size() < 2 || it->bootDisplay) return {};
+#if defined(_WIN32)
+ // Windows' own per-app preference (what Settings > System > Display > Graphics writes): high performance for a
+ // discrete card, power saving for the integrated one. Read when the process creates its first GL / D3D device.
+ wchar_t exe[MAX_PATH];
+ if (!GetModuleFileNameW(nullptr, exe, MAX_PATH)) return {};
+ HKEY key;
+ if (RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\DirectX\\UserGpuPreferences", 0, nullptr, 0, KEY_SET_VALUE,
+ nullptr, &key, nullptr) != ERROR_SUCCESS)
+ return {};
+ const wchar_t* value = it->discrete ? L"GpuPreference=2;" : L"GpuPreference=1;";
+ RegSetValueExW(key, exe, 0, REG_SZ, reinterpret_cast<const BYTE*>(value), DWORD((wcslen(value) + 1) * sizeof(wchar_t)));
+ RegCloseKey(key);
+ return std::string("Windows graphics preference: ") + (it->discrete ? "high performance" : "power saving") + " (" + it->name + ")";
+#elif defined(__linux__)
+ if (it->vendorId == 0x10de) {
+ // NVIDIA's PRIME render offload (the proprietary driver): documented, per process.
+ if (userSet("__NV_PRIME_RENDER_OFFLOAD") || userSet("__GLX_VENDOR_LIBRARY_NAME") || userSet("DRI_PRIME")) return {};
+ if (!std::filesystem::exists("/proc/driver/nvidia")) {
+ // nouveau: Mesa's DRI_PRIME takes the card's PCI tag.
+ setEnv("DRI_PRIME", it->id);
+ return "DRI_PRIME=" + it->id + " (" + it->name + ")";
+ }
+ setEnv("__NV_PRIME_RENDER_OFFLOAD", "1");
+ setEnv("__GLX_VENDOR_LIBRARY_NAME", "nvidia");
+ setEnv("__VK_LAYER_NV_optimus", "NVIDIA_only");
+ return "NVIDIA PRIME render offload (" + it->name + ")";
+ }
+ if (userSet("DRI_PRIME")) return {};
+ setEnv("DRI_PRIME", it->id); // Mesa: "pci-0000_03_00_0"
+ return "DRI_PRIME=" + it->id + " (" + it->name + ")";
+#else
+ return {};
+#endif
+}
+
+void clearGpuChoice() {
+#if defined(_WIN32)
+ wchar_t exe[MAX_PATH];
+ if (!GetModuleFileNameW(nullptr, exe, MAX_PATH)) return;
+ RegDeleteKeyValueW(HKEY_CURRENT_USER, L"Software\\Microsoft\\DirectX\\UserGpuPreferences", exe);
+#endif
+}
+
+} // namespace sf
diff --git a/src/core/HardwareTier.h b/src/core/HardwareTier.h
new file mode 100644
index 00000000..f2fccfb0
--- /dev/null
+++ b/src/core/HardwareTier.h
@@ -0,0 +1,184 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Hardware tiers (docs/performance.md, "Hardware tiers"; ~/Work/.sf/billion.md): what the detected machine can carry
+// beyond the base experience, so the advanced levels (bigger Focus Detail caches, more micro triangles, 1B scenes,
+// 16K textures) switch on by themselves where they fit and never where they don't.
+//
+// Floor every supported machine; the budgets are exactly what every machine got before tiers (0.11.12)
+// Standard 16 GB RAM, 6+ threads, a 4 GB+ graphics card or a GPU sharing the memory
+// High 32 GB RAM, 8+ threads, an 8 GB+ graphics card or 32 GB+ shared (Apple Pro / Max)
+// Extreme 64 GB RAM, 16+ threads, a 16 GB+ graphics card or 64 GB+ shared (Apple Max / Ultra, big APUs)
+//
+// The tier comes from what the probe found (memory sizes, GPU type, threads), capped by what calibration measured
+// (a slow GPU or slow brushes never get the upper tiers). It is separate from the render profile (ProfileTier:
+// Software / Laptop / Workstation, which sets the view's triangle budgets from measured speed and is unchanged).
+// At run time a memory guard steps the tier in effect down one level at a time when free memory runs low, and back
+// up once there is room again; nothing fails, big scenes fall back to coarser levels.
+//
+// Read the budgets with currentTierConfig().budgets (core/TierConfig.h). SF_HW_SIMULATE=floor|standard|high|extreme
+// forces a tier (floor also keeps its old meaning: an integrated GPU's render budgets and 4 threads); every budget can
+// be pinned with SF_TIER_<NAME> (e.g. SF_TIER_FOCUS_RESIDENT_MB=1024), names as in tierBudgetFields().
+#pragma once
+
+#include "core/Json.h"
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+struct HardwareInfo;
+struct Calibration;
+enum class ProfileTier;
+
+enum class HwTier { Floor = 0, Standard = 1, High = 2, Extreme = 3 };
+constexpr int kHwTierCount = 4;
+const char* hwTierName(HwTier tier); // "Floor", "Standard", "High", "Extreme" (logs, JSON, SF_HW_SIMULATE)
+const char* hwTierDisplayName(HwTier tier); // what people see: "Essential", "Standard", "High", "Extreme"
+// Either name, any case.
+bool hwTierFromName(const std::string& name, HwTier& out);
+// SF_HW_SIMULATE=<tier>: the forced tier, if any.
+bool simulatedHwTier(HwTier& out);
+
+// The budgets a tier gives. Floor's are the values every machine used before tiers, so the Floor tier can't regress.
+struct TierBudgets {
+ // Scenes
+ uint64_t residentTriangles = 300'000'000; // triangles held in full detail; past it far parts use coarse levels
+ uint64_t maxMicroTriangles = 300'000'000; // micro triangles the tier holds before Divide to Micro asks (it then
+ // streams with Focus Detail rather than failing)
+ bool billionScenes = false; // 1B-triangle scenes without asking (else opt-in)
+ uint64_t optInMicroTriangles = 1'000'000'000; // the opt-in ceiling (past it: coarse levels and a message, no failure)
+ uint64_t maxDenseTriangles = 30'000'000; // one dense mesh past this: open works, a notice suggests micro levels
+ uint64_t microResidentMB = 512; // GPU: the compressed resident micro pyramid (billion-ideas); over it,
+ // coarse levels + Focus Detail stream
+ double derivNormalPx = 2.0; // triangles under this many pixels shade from screen derivatives
+ uint64_t waveletDabSamples = 64; // a dab spanning more samples than this edits the coarse level only
+ int gpuDabs = 0; // dabs as render passes (experimental): 0 off, 1 opt-in, 2 on
+ // Focus Detail (core/FocusDetail.h)
+ uint64_t focusTriangles = 300'000'000; // micro levels past this stream from a .sfdetail file
+ uint64_t focusResidentMB = 512; // CPU: full-resolution tiles kept before the LRU demotes
+ uint64_t focusGpuPoolMB = 384; // GPU page pool for close-up full tiles
+ double focusUpdateMs = 3.0; // main-thread promotion work per frame (App::updateFocusDetail)
+ double focusLookaheadSeconds = 0.25; // brush prediction
+ // Coarse LOD (microlod: Renderer::stillDetail / triangleBudget)
+ double stillFrameMs = 100.0; // GPU time a full-detail still frame may take before it stays coarse
+ double stillDelaySeconds = 0.15; // rest before full detail
+ double motionBudgetFraction = 0.5; // share of the triangle budget while the view moves
+ bool coarseLevels = true; // coarse levels for dense bases (Renderer::stillDetail)
+ // Strokes (core200m)
+ uint64_t draftDabVertices = 0; // dabs moving more vertices take the draft path (0 = never, as before)
+ double strokeBacklogMs = 50.0; // queued dab work before the stroke thins dabs (App kStrokeBacklogSeconds)
+ double normalsCatchUpMs = 0.0; // exact-normal catch-up per frame after a stroke (0 = as before: no cap)
+ // Textures and threads
+ int maxTextureSize = 8192; // largest paint / bake texture (also capped by the GPU and its memory)
+ int threads = 0; // worker threads (0 = every hardware thread, up to the pool's 16)
+};
+TierBudgets budgetsForTier(HwTier tier);
+
+// The budgets by name, for JSON, SF_TIER_<NAME> and set_performance_override ("focus_resident_mb", ...).
+struct TierBudgetField {
+ const char* name; // snake case
+ const char* what; // plain words for people
+ enum class Kind { U64, Double, Int, Bool } kind;
+ size_t offset;
+};
+const std::vector<TierBudgetField>& tierBudgetFields();
+double tierBudgetValue(const TierBudgets& b, const TierBudgetField& f);
+void setTierBudgetValue(TierBudgets& b, const TierBudgetField& f, double value);
+// SF_TIER_<NAME> pins (applied last, over the tier and the memory guard).
+void applyTierBudgetEnv(TierBudgets& b);
+Json tierBudgetsJson(const TierBudgets& b);
+
+// Short GPU name for people: "NVIDIA GeForce RTX 3060/PCIe/SSE2" -> "RTX 3060", "Mesa Intel(R) UHD Graphics 620 (KBL
+// GT2)" -> "Intel UHD Graphics 620", "Apple M1 Pro (G13S C0)" -> "Apple M1 Pro".
+std::string shortGpuName(const std::string& renderer);
+
+// What the OpenGL version string tells (macOS stops at 4.1; the renderer needs 3.3 and uses 4.4 buffer storage when
+// there). Reported only: no tier depends on GL features (Apple GPUs would all be Floor).
+struct GlFeatures {
+ int major = 0, minor = 0;
+ bool bufferStorage = false; // GL 4.4
+ bool compute = false; // GL 4.3 compute shaders
+};
+GlFeatures glFeatures(const std::string& glVersion);
+
+// The detected tier and why, in words: "RTX 3060, 12 GB VRAM, 32 GB RAM, 12 threads" and, below the top,
+// what the next tier needs ("Extreme needs a 16 GB graphics card and 64 GB RAM"). `renderTier` is the measured render
+// profile: Software (a software renderer, or a GPU too slow for anything else) is always Floor.
+struct HwTierDetection {
+ HwTier tier = HwTier::Floor;
+ std::string machine; // "RTX 3060, 12 GB VRAM, 32 GB RAM, 12 threads"
+ std::string limit; // what keeps it from the next tier ("" at Extreme)
+};
+HwTierDetection detectHwTier(const HardwareInfo& hw, const Calibration& c, ProfileTier renderTier);
+// "RTX 3060, 12 GB VRAM, 32 GB RAM: High"
+std::string tierSummary(const HwTierDetection& d, HwTier inEffect);
+// What the tier turns on, in plain words, one line each (Preferences > Performance, the first-run card).
+std::vector<std::string> tierTurnsOn(HwTier tier, const TierBudgets& b);
+
+// --- Memory guard: steps the tier in effect down when free memory runs low, back up when it recovers ---
+struct TierMemoryGuard {
+ int stepDown = 0; // levels below the detected tier
+ double tightSince = -1.0, roomySince = -1.0, lastChange = -1e9;
+ // Free memory now (MB; GPU 0 = unknown). Returns +1 when it stepped down, -1 when it stepped back up, else 0.
+ // Tight: under max(1 GB, a tenth of RAM) free (or under 256 MB of free video memory) for 2 s. Roomy: over max(3 GB,
+ // a quarter of RAM) for 60 s. At most one change per 10 s; never below Floor (`maxSteps`).
+ int update(double nowSeconds, uint64_t freeMB, uint64_t totalMB, uint64_t gpuFreeMB, int maxSteps);
+};
+// (Free system memory: availableMemoryBytes(), core/MemoryGuard.h.)
+
+// --- Compute: CPU or GPU, per task (Preferences > Performance) ---
+enum class ComputeTask { BrushSolver, Normals, Remesh, Bake, FocusDecode, MicroShade };
+constexpr int kComputeTaskCount = 6;
+enum class ComputeChoice { Auto, Cpu, Gpu };
+enum class ComputePath { Cpu, Gpu };
+struct ComputeTaskInfo {
+ ComputeTask task;
+ const char* id; // "brush_solver"
+ const char* name; // "Brush solver"
+ bool gpuPath; // this build has a GPU path for it
+};
+const ComputeTaskInfo& computeTaskInfo(ComputeTask task);
+const char* computeChoiceName(ComputeChoice c); // "auto", "cpu", "gpu"
+bool computeChoiceFromName(const std::string& name, ComputeChoice& out);
+// SF_COMPUTE=cpu|gpu|auto, else `saved`.
+ComputeChoice computeChoiceWithEnv(ComputeChoice saved);
+// The path a task takes: CPU where there is no GPU path or it failed this session; GPU when chosen; Auto takes the
+// GPU only off the Floor tier and only where it measured at least 20 % faster (gpuMs / cpuMs 0 = not measured: CPU).
+ComputePath resolveCompute(ComputeTask task, ComputeChoice choice, HwTier tier, double cpuMs, double gpuMs);
+// A GPU path that failed calls this (thread-safe): the task runs on the CPU for the rest of the session and the app
+// says so once (takeComputeFailureMessage).
+void reportGpuComputeFailure(ComputeTask task, const std::string& why);
+bool gpuComputeFailed(ComputeTask task);
+bool takeComputeFailureMessage(std::string& message);
+void resetComputeFailures(); // (tests)
+
+// --- Graphics cards (the GPU picker) ---
+struct GpuAdapter {
+ std::string id; // stable: "pci-0000_01_00_0" (Linux), "luid-..." (Windows)
+ std::string name; // "NVIDIA GeForce RTX 3060" (pci.ids / the driver), else "NVIDIA GPU 10de:2504"
+ uint32_t vendorId = 0, deviceId = 0;
+ bool discrete = false;
+ bool bootDisplay = false; // the one the desktop starts on (Linux boot_vga)
+ uint64_t vramMB = 0; // where known
+};
+// The machine's graphics cards (no OpenGL, no network). Linux: /sys/class/drm; Windows: DXGI; elsewhere empty.
+std::vector<GpuAdapter> listGpus();
+// Linux: the cards under `drmRoot` (tests pass a fake tree), named from a pci.ids file (`pciIds`, "" = none).
+std::vector<GpuAdapter> listGpusSysfs(const std::string& drmRoot, const std::string& pciIds);
+// "NVIDIA Corporation" / "GA106 [GeForce RTX 3060 Lite Hash Rate]" from a pci.ids text: the device's name in brackets
+// when there is one, prefixed by the short vendor ("NVIDIA GeForce RTX 3060 Lite Hash Rate").
+std::string pciIdsName(const std::string& pciIdsText, uint32_t vendor, uint32_t device);
+// What Auto picks: the discrete card with the most memory (else the first discrete, else ""= the system's choice).
+std::string autoGpuId(const std::vector<GpuAdapter>& gpus);
+// Before the GL context: makes the next context use `id` ("" or "auto" = Auto) through the platform's own mechanism
+// (Linux: Mesa DRI_PRIME / NVIDIA PRIME render offload; Windows: the per-app graphics preference Settings > Display >
+// Graphics writes). Never overrides variables the user set. Returns what it did, for the log ("" = nothing).
+std::string applyGpuChoice(const std::string& id, const std::vector<GpuAdapter>& gpus);
+// Undoes what applyGpuChoice left behind outside this process (Windows: the per-app preference), after a start on
+// the chosen card failed.
+void clearGpuChoice();
+
+} // namespace sf
diff --git a/src/core/MemoryGuard.cpp b/src/core/MemoryGuard.cpp
index a61a79d1..7c1913aa 100644
--- a/src/core/MemoryGuard.cpp
+++ b/src/core/MemoryGuard.cpp
@@ -82,6 +82,21 @@ MemoryCheck checkMemory(size_t need, size_t available) {
return c;
}
+std::string compactBytes(size_t b) {
+ char buf[16];
+ const double gb = double(b) / double(1ull << 30);
+ if (gb < 0.995) std::snprintf(buf, sizeof buf, "%.0fM", double(b) / double(1u << 20));
+ else std::snprintf(buf, sizeof buf, gb < 9.95 ? "%.1fG" : "%.0fG", gb);
+ return buf;
+}
+
+std::string memoryText(size_t b) {
+ std::string s = compactBytes(b);
+ const char unit = s.back();
+ s.pop_back();
+ return s + (unit == 'G' ? " GB" : " MB");
+}
+
std::string formatGigabytes(size_t b) {
const double gb = double(b) / 1e9;
char buf[32];
diff --git a/src/core/MemoryGuard.h b/src/core/MemoryGuard.h
index bce11791..8627e14b 100644
--- a/src/core/MemoryGuard.h
+++ b/src/core/MemoryGuard.h
@@ -32,6 +32,10 @@ struct MemoryCheck {
MemoryCheck checkMemory(size_t needBytes, size_t availableBytes);
inline MemoryCheck checkMemory(size_t needBytes) { return checkMemory(needBytes, availableMemoryBytes()); }
+// "1.2G", "14G", "640M": the top bar's compact memory figures, in binary units like the system monitors (a 12 GB
+// card is 12G, not 13G). memoryText: the same spelled out for tooltips, "1.2 GB", "640 MB".
+std::string compactBytes(size_t bytes);
+std::string memoryText(size_t bytes);
// "5 GB", "2.3 GB", "0.4 GB" (decimal gigabytes, as the system's own tools show them).
std::string formatGigabytes(size_t bytes);
// "33M skipped: needs ~5 GB free, 1.3 GB available. Close other apps and run again"
diff --git a/src/core/TierConfig.cpp b/src/core/TierConfig.cpp
index 9ed98df1..8b668a2e 100644
--- a/src/core/TierConfig.cpp
+++ b/src/core/TierConfig.cpp
@@ -34,7 +34,7 @@ int targetHzForDisplay(int hz) {
return 60;
}
-TierConfig tierConfigFor(const HardwareProfile& p, PowerSource power, int displayHz) {
+TierConfig tierConfigFor(const HardwareProfile& p, PowerSource power, int displayHz, int memoryStepDown) {
TierConfig c;
c.tier = p.tier;
c.power = power;
@@ -73,6 +73,20 @@ TierConfig tierConfigFor(const HardwareProfile& p, PowerSource power, int displa
c.outOfCorePoints = (c.residentCacheCapMB << 20) / 2;
if (p.overrides.draftBrush == 1) c.draftBrushMode = true;
else if (p.overrides.draftBrush == 2) c.draftBrushMode = false;
+ // The hardware tier's budgets, stepped down by the memory guard.
+ c.chosenHwTier = p.hwTier;
+ c.memoryStepDown = std::clamp(memoryStepDown, 0, int(p.hwTier));
+ c.hwTier = HwTier(int(p.hwTier) - c.memoryStepDown);
+ c.budgets = budgetsForTier(c.hwTier);
+ // Focus Detail's GPU pool on a small graphics card: 256 MB under a 1.5 GB video memory budget.
+ if (c.hwTier == HwTier::Floor && s.vramBudgetMB && s.vramBudgetMB < 1536) c.budgets.focusGpuPoolMB = 256;
+ c.budgets.maxTextureSize = s.maxTextureSize;
+ c.budgets.threads = s.threads; // (SF_HW_SIMULATE=floor: the app sets 4)
+ applyTierBudgetEnv(c.budgets);
+ ComputeChoice saved = ComputeChoice::Auto;
+ computeChoiceFromName(p.overrides.compute, saved);
+ c.compute = computeChoiceWithEnv(saved);
+ c.turbo = p.overrides.turbo;
return c;
}
@@ -90,6 +104,12 @@ Json tierConfigJson(const TierConfig& c) {
j.set("target_hz", c.targetHz);
j.set("power", powerSourceName(c.power));
j.set("on_battery", c.onBattery());
+ j.set("hw_tier", hwTierName(c.hwTier));
+ j.set("chosen_hw_tier", hwTierName(c.chosenHwTier));
+ j.set("memory_step_down", c.memoryStepDown);
+ j.set("budgets", tierBudgetsJson(c.budgets));
+ j.set("compute", computeChoiceName(c.compute));
+ j.set("turbo", c.turbo);
return j;
}
diff --git a/src/core/TierConfig.h b/src/core/TierConfig.h
index 11f2c7c0..dca2b686 100644
--- a/src/core/TierConfig.h
+++ b/src/core/TierConfig.h
@@ -46,6 +46,14 @@ struct TierConfig {
// per point, so a slower CPU shades fewer and the dabs and the orbit keep up; 0 = the points budget only).
double strokeShadeMs = 10.0;
uint64_t outOfCorePoints = 0;
+ // The hardware tier (core/HardwareTier.h): the one in effect (the detected or chosen one, minus the memory guard's
+ // steps) and its budgets, which the advanced levels read (Focus Detail, coarse LOD, micro levels, dense strokes).
+ HwTier hwTier = HwTier::Floor;
+ HwTier chosenHwTier = HwTier::Floor; // before the memory guard
+ int memoryStepDown = 0;
+ TierBudgets budgets;
+ ComputeChoice compute = ComputeChoice::Auto; // (SF_COMPUTE applied)
+ bool turbo = false; // Turbo is on (App: eye candy off while working, top budgets)
bool onBattery() const { return power == PowerSource::Battery; }
};
@@ -59,8 +67,9 @@ size_t microShadeBudget(const TierConfig& tier, bool stroking, bool viewMoving,
// 144 for displays of 143 Hz and up, 120 from 119 Hz, else 60 (also when unknown: 0).
int targetHzForDisplay(int displayHz);
-// The knobs for `profile` on this power source and display (displayHz 0 = unknown). Deterministic.
-TierConfig tierConfigFor(const HardwareProfile& profile, PowerSource power, int displayHz);
+// The knobs for `profile` on this power source and display (displayHz 0 = unknown), the hardware tier stepped down
+// `memoryStepDown` levels by the memory guard (never below Floor). Deterministic but for SF_TIER_* / SF_COMPUTE.
+TierConfig tierConfigFor(const HardwareProfile& profile, PowerSource power, int displayHz, int memoryStepDown = 0);
Json tierConfigJson(const TierConfig& config);
// The configuration in effect (the app sets it from the profile, the power source and the display).
diff --git a/tests/flaky.md b/tests/flaky.md
index 7aebaa7d..8b14d5b1 100644
--- a/tests/flaky.md
+++ b/tests/flaky.md
@@ -23,3 +23,4 @@ deletes it; remove its lines once fixed.
checks the CPU between frames and prints the frames' share apart. Remove these lines after a week of green Windows.
- **discord_bursts_send_the_latest**, CI macOS (owner sfmonitor, Discord presence): a timing check
(tests/test_discord_presence.cpp:537, `got.size() <= 2`) failed once on the macOS runner; the re-run passed.
+| 2026-11-07 | ui_hardware_profile | PC (WSL, RTX 3060) | 52ce3531 |
diff --git a/tests/test_hardware_tier.cpp b/tests/test_hardware_tier.cpp
new file mode 100644
index 00000000..619cceab
--- /dev/null
+++ b/tests/test_hardware_tier.cpp
@@ -0,0 +1,385 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Hardware tiers (core/HardwareTier.h): detection from synthetic machines, the budgets (Floor = the values before
+// tiers), names, SF_HW_SIMULATE / SF_TIER_* / SF_COMPUTE, the memory guard, compute choice, the GPU list parsers.
+#include "TestHarness.h"
+
+#include "core/HardwareProfile.h"
+#include "core/HardwareTier.h"
+#include "core/MemoryGuard.h"
+#include "core/TierConfig.h"
+
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+
+using namespace sf;
+
+namespace {
+
+HardwareInfo box(const std::string& vendor, const std::string& renderer, uint64_t vramMB, uint64_t ramMB, int threads) {
+ 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 = 32768;
+ h.appVersion = "9.9.9";
+ return h;
+}
+
+Calibration fast(double triM = 3000.0, double dabMs = 0.5) {
+ Calibration c;
+ c.trianglesPerSecondM = triM;
+ c.uploadGBps = 10.0;
+ c.dabMs = dabMs;
+ c.memoryGBps = 20.0;
+ c.runs = 5;
+ return c;
+}
+
+HwTier tierOf(const HardwareInfo& h, const Calibration& c = fast()) { return mapProfile(h, c).hwTier; }
+
+void setEnv(const char* k, const char* v) {
+#if defined(_WIN32)
+ _putenv_s(k, v ? v : "");
+#else
+ if (v) setenv(k, v, 1);
+ else unsetenv(k);
+#endif
+}
+
+void writeFile(const std::filesystem::path& p, const std::string& text) {
+ std::filesystem::create_directories(p.parent_path());
+ std::ofstream(p) << text;
+}
+
+} // namespace
+
+TEST(hw_tier_names) {
+ CHECK(std::string(hwTierName(HwTier::Floor)) == "Floor");
+ CHECK(std::string(hwTierDisplayName(HwTier::Floor)) == "Essential"); // never "low"
+ CHECK(std::string(hwTierDisplayName(HwTier::High)) == "High");
+ HwTier t;
+ CHECK(hwTierFromName("floor", t) && t == HwTier::Floor);
+ CHECK(hwTierFromName("Essential", t) && t == HwTier::Floor);
+ CHECK(hwTierFromName(" EXTREME ", t) && t == HwTier::Extreme);
+ CHECK(hwTierFromName("standard", t) && t == HwTier::Standard);
+ CHECK(!hwTierFromName("monster", t));
+}
+
+TEST(hw_tier_short_gpu_name) {
+ CHECK(shortGpuName("NVIDIA GeForce RTX 3060/PCIe/SSE2") == "RTX 3060");
+ CHECK(shortGpuName("Mesa Intel(R) UHD Graphics 620 (KBL GT2)") == "Intel UHD Graphics 620");
+ CHECK(shortGpuName("Apple M1 Pro (G13S C0)") == "Apple M1 Pro");
+ CHECK(shortGpuName("AMD Radeon RX 7900 XTX (radeonsi, navi31, LLVM 18.1.8, DRM 3.57)") == "Radeon RX 7900 XTX");
+ CHECK(shortGpuName("NVIDIA RTX A4000/PCIe/SSE2") == "RTX A4000");
+ CHECK(shortGpuName("llvmpipe (LLVM 19.1.0, 256 bits)") == "llvmpipe");
+ CHECK(shortGpuName("") == "");
+ // Mesa's layered drivers (WSL's D3D12, zink) name the real card in brackets.
+ CHECK(shortGpuName("D3D12 (NVIDIA GeForce RTX 3060)") == "RTX 3060");
+ CHECK(shortGpuName("zink Vulkan 1.3(NVIDIA GeForce RTX 3060 (NVIDIA_PROPRIETARY))") == "RTX 3060");
+}
+
+TEST(hw_tier_gl_features) {
+ GlFeatures f = glFeatures("4.6.0 NVIDIA 550.54");
+ CHECK(f.major == 4 && f.minor == 6 && f.compute && f.bufferStorage);
+ f = glFeatures("4.1 Metal - 88.1");
+ CHECK(f.major == 4 && f.minor == 1 && !f.compute && !f.bufferStorage);
+ f = glFeatures("3.3 (Core Profile) Mesa 24.1.0");
+ CHECK(f.major == 3 && f.minor == 3 && !f.compute);
+ f = glFeatures("OpenGL ES 3.2 Mesa");
+ CHECK(f.major == 3 && f.minor == 2);
+ f = glFeatures("");
+ CHECK(f.major == 0 && !f.compute);
+}
+
+TEST(hw_tier_detection) {
+ setEnv("SF_HW_SIMULATE", nullptr);
+ // The brief's example: RTX 3060 12 GB, 32 GB RAM, 12 threads -> High; Extreme needs 16 GB VRAM and 64 GB RAM.
+ const HardwareProfile pc = mapProfile(box("NVIDIA Corporation", "NVIDIA GeForce RTX 3060/PCIe/SSE2", 12288, 32020, 12), fast());
+ CHECK(pc.hwTier == HwTier::High);
+ CHECK(pc.detected.machine == "RTX 3060, 12 GB VRAM, 31 GB RAM, 12 threads" ||
+ pc.detected.machine == "RTX 3060, 12 GB VRAM, 32 GB RAM, 12 threads");
+ CHECK(pc.detected.limit.find("Extreme needs") == 0);
+ CHECK(tierSummary(pc.detected, pc.hwTier).find(": High") != std::string::npos);
+ // A 4090 workstation: Extreme.
+ CHECK(tierOf(box("NVIDIA Corporation", "NVIDIA GeForce RTX 4090/PCIe/SSE2", 24564, 128000, 32)) == HwTier::Extreme);
+ // ... but 8 threads keep it at High.
+ CHECK(tierOf(box("NVIDIA Corporation", "NVIDIA GeForce RTX 4090/PCIe/SSE2", 24564, 128000, 8)) == HwTier::High);
+ // A GTX 1650 4 GB in a 16 GB box: Standard. A 2 GB card: Floor (video memory).
+ CHECK(tierOf(box("NVIDIA Corporation", "NVIDIA GeForce GTX 1650/PCIe/SSE2", 3911, 15800, 8)) == HwTier::Standard);
+ const HardwareProfile small = mapProfile(box("NVIDIA Corporation", "NVIDIA GeForce MX250/PCIe/SSE2", 2048, 15800, 8), fast());
+ CHECK(small.hwTier == HwTier::Floor);
+ CHECK(small.detected.limit.find("video memory") != std::string::npos);
+ CHECK(small.detected.limit.find("this computer has less video memory") != std::string::npos);
+ // An 8 GB laptop with Intel graphics: Floor (RAM). 16 GB: Standard. 32 GB: still Standard (integrated).
+ CHECK(tierOf(box("Intel", "Mesa Intel(R) UHD Graphics 620 (KBL GT2)", 0, 7800, 8)) == HwTier::Floor);
+ CHECK(tierOf(box("Intel", "Mesa Intel(R) Iris(R) Xe Graphics (TGL GT2)", 0, 15700, 8)) == HwTier::Standard);
+ CHECK(tierOf(box("Intel", "Mesa Intel(R) Iris(R) Xe Graphics (TGL GT2)", 0, 31700, 8)) == HwTier::Standard);
+ // A big APU with 128 GB (Strix Halo): High.
+ CHECK(tierOf(box("AMD", "AMD Radeon 8060S (radeonsi, gfx1151)", 0, 126000, 32)) == HwTier::High);
+ // Apple: 16 GB M2 Standard, 32 GB M1 Pro High (10 threads), 64 GB M3 Max with 16 threads Extreme.
+ CHECK(tierOf(box("Apple", "Apple M2", 0, 16384, 8)) == HwTier::Standard);
+ CHECK(tierOf(box("Apple", "Apple M1 Pro", 0, 32768, 10)) == HwTier::High);
+ CHECK(tierOf(box("Apple", "Apple M3 Max", 0, 65536, 16)) == HwTier::Extreme);
+ // 4 threads: Floor whatever the GPU.
+ CHECK(tierOf(box("NVIDIA Corporation", "NVIDIA GeForce RTX 3060/PCIe/SSE2", 12288, 32020, 4)) == HwTier::Floor);
+ // A software renderer: Floor.
+ const HardwareProfile sw = mapProfile(box("Mesa", "llvmpipe (LLVM 19.1.0, 256 bits)", 0, 65536, 32), fast(40.0));
+ CHECK(sw.hwTier == HwTier::Floor);
+ // Measurements cap: a slow GPU (200M/s) or slow brushes stop at Standard.
+ const HardwareInfo big = box("NVIDIA Corporation", "NVIDIA GeForce RTX 4090/PCIe/SSE2", 24564, 128000, 32);
+ CHECK(tierOf(big, fast(200.0)) == HwTier::Standard);
+ CHECK(tierOf(big, fast(3000.0, 3.0)) == HwTier::Standard);
+ // Not measured (skipped): the memory sizes alone.
+ Calibration skipped;
+ skipped.skipped = true;
+ CHECK(tierOf(big, skipped) == HwTier::Extreme);
+ // Unknown GPU type (nothing probed): the base tier.
+ CHECK(tierOf(box("Vendor", "Some GPU", 0, 65536, 16)) == HwTier::Floor);
+ // Deterministic.
+ CHECK(tierOf(big) == tierOf(big));
+}
+
+TEST(hw_tier_budgets) {
+ // Floor = the values every machine had before tiers (focusdetail, core200m, microlod, billion-ideas read them).
+ const TierBudgets f = budgetsForTier(HwTier::Floor);
+ CHECK(f.focusTriangles == 300'000'000);
+ CHECK(f.focusResidentMB == 512);
+ CHECK(f.focusGpuPoolMB == 384);
+ CHECK(f.focusUpdateMs == 3.0);
+ CHECK(f.focusLookaheadSeconds == 0.25);
+ CHECK(f.strokeBacklogMs == 50.0);
+ CHECK(f.draftDabVertices == 0);
+ CHECK(f.normalsCatchUpMs == 0.0);
+ CHECK(f.stillFrameMs == 100.0);
+ CHECK(f.stillDelaySeconds == 0.15);
+ CHECK(f.motionBudgetFraction == 0.5);
+ CHECK(f.coarseLevels);
+ CHECK(!f.billionScenes);
+ CHECK(f.maxTextureSize == 8192);
+ CHECK(f.gpuDabs == 0);
+ // Each tier holds at least as much as the one below.
+ for (int i = 1; i < kHwTierCount; ++i) {
+ const TierBudgets a = budgetsForTier(HwTier(i - 1)), b = budgetsForTier(HwTier(i));
+ CHECK(b.residentTriangles >= a.residentTriangles);
+ CHECK(b.maxMicroTriangles >= a.maxMicroTriangles);
+ CHECK(b.focusResidentMB >= a.focusResidentMB);
+ CHECK(b.focusGpuPoolMB >= a.focusGpuPoolMB);
+ CHECK(b.microResidentMB >= a.microResidentMB);
+ CHECK(b.maxTextureSize >= a.maxTextureSize);
+ }
+ CHECK(budgetsForTier(HwTier::High).billionScenes);
+ CHECK(budgetsForTier(HwTier::Extreme).focusTriangles == 1'000'000'000);
+ // Names: snake case, unique; the JSON has every one.
+ const Json j = tierBudgetsJson(f);
+ bool foundResident = false;
+ for (const TierBudgetField& x : tierBudgetFields()) {
+ CHECK(j[x.name].type() != Json::Type::Null);
+ foundResident = foundResident || std::string(x.name) == "focus_resident_mb";
+ }
+ CHECK(foundResident);
+ CHECK(j["focus_resident_mb"].asNumber() == 512);
+ CHECK(j["billion_scenes"].type() == Json::Type::Bool);
+ // "What this turns on": something on every tier, positive wording on the base one.
+ for (int i = 0; i < kHwTierCount; ++i) CHECK(!tierTurnsOn(HwTier(i), budgetsForTier(HwTier(i))).empty());
+ for (const std::string& line : tierTurnsOn(HwTier::Floor, f)) {
+ CHECK(line.find("low") == std::string::npos);
+ CHECK(line.find("Low") == std::string::npos);
+ }
+}
+
+TEST(hw_tier_env_pins_and_simulate) {
+ setEnv("SF_HW_SIMULATE", nullptr);
+ const HardwareInfo pcHw = box("NVIDIA Corporation", "NVIDIA GeForce RTX 3060/PCIe/SSE2", 12288, 32020, 12);
+ // SF_HW_SIMULATE=<tier> forces each tier (floor keeps its old render-budget meaning in the app).
+ for (const char* name : {"floor", "standard", "high", "extreme", "Essential"}) {
+ setEnv("SF_HW_SIMULATE", name);
+ HwTier want;
+ CHECK(hwTierFromName(name, want));
+ CHECK(mapProfile(pcHw, fast()).hwTier == want);
+ CHECK(tierConfigFor(mapProfile(pcHw, fast()), PowerSource::AC, 60).hwTier == want);
+ }
+ setEnv("SF_HW_SIMULATE", nullptr);
+ // A tier set by hand (ProfileOverrides::level), kept through JSON.
+ ProfileOverrides o;
+ o.level = "Standard";
+ o.compute = "cpu";
+ o.gpu = "pci-0000_01_00_0";
+ o.turbo = true;
+ o.tierCardFor = "x";
+ const HardwareProfile byHand = mapProfile(pcHw, fast(), o);
+ CHECK(byHand.hwTier == HwTier::Standard);
+ CHECK(byHand.detected.tier == HwTier::High);
+ HardwareProfile back;
+ CHECK(hardwareProfileFromJson(hardwareProfileToJson(byHand), back));
+ CHECK(back.hwTier == HwTier::Standard);
+ CHECK(back.overrides.compute == "cpu" && back.overrides.gpu == "pci-0000_01_00_0" && back.overrides.turbo &&
+ back.overrides.tierCardFor == "x");
+ // The calibration JSON carries the tier and still validates.
+ std::string error;
+ const Json cj = calibrationJson(byHand);
+ CHECK(validateCalibrationJson(cj, error));
+ CHECK(cj["hardware_tier"]["tier"].asString() == "Standard");
+ CHECK(cj["hardware_tier"]["detected"].asString() == "High");
+ // SF_TIER_<NAME> pins one budget over the tier.
+ setEnv("SF_TIER_FOCUS_RESIDENT_MB", "777");
+ setEnv("SF_TIER_BILLION_SCENES", "on");
+ TierConfig c = tierConfigFor(mapProfile(pcHw, fast()), PowerSource::AC, 60);
+ CHECK(c.budgets.focusResidentMB == 777);
+ CHECK(c.budgets.billionScenes);
+ setEnv("SF_TIER_FOCUS_RESIDENT_MB", nullptr);
+ setEnv("SF_TIER_BILLION_SCENES", nullptr);
+ // SF_COMPUTE beats the saved choice.
+ setEnv("SF_COMPUTE", "gpu");
+ CHECK(tierConfigFor(byHand, PowerSource::AC, 60).compute == ComputeChoice::Gpu);
+ setEnv("SF_COMPUTE", nullptr);
+ CHECK(tierConfigFor(byHand, PowerSource::AC, 60).compute == ComputeChoice::Cpu);
+ CHECK(tierConfigFor(byHand, PowerSource::AC, 60).turbo);
+ // The memory guard's steps: High - 1 = Standard; never below Floor.
+ c = tierConfigFor(mapProfile(pcHw, fast()), PowerSource::AC, 60, 1);
+ CHECK(c.hwTier == HwTier::Standard && c.chosenHwTier == HwTier::High && c.memoryStepDown == 1);
+ CHECK(c.budgets.focusResidentMB == budgetsForTier(HwTier::Standard).focusResidentMB);
+ c = tierConfigFor(mapProfile(pcHw, fast()), PowerSource::AC, 60, 9);
+ CHECK(c.hwTier == HwTier::Floor && c.memoryStepDown == 2);
+ // 16K textures on High where the card has the memory.
+ CHECK(mapProfile(pcHw, fast()).settings.maxTextureSize == 16384);
+ CHECK(mapProfile(pcHw, fast(), o).settings.maxTextureSize <= 8192 || mapProfile(pcHw, fast(), o).tier == ProfileTier::Workstation);
+ // Back to automatic keeps the choices (any() counts the tier, not compute / gpu / turbo).
+ ProfileOverrides choices;
+ choices.compute = "gpu";
+ choices.turbo = true;
+ choices.gpu = "x";
+ CHECK(!choices.any());
+ choices.level = "High";
+ CHECK(choices.any());
+}
+
+TEST(hw_tier_memory_guard) {
+ TierMemoryGuard g;
+ const uint64_t total = 32768;
+ // Roomy: nothing happens.
+ CHECK(g.update(0.0, 20000, total, 0, 2) == 0);
+ // Tight (under 3.2 GB free) for under 2 s: holds; past 2 s: one step down.
+ CHECK(g.update(10.0, 2000, total, 0, 2) == 0);
+ CHECK(g.update(11.0, 2000, total, 0, 2) == 0);
+ CHECK(g.update(12.1, 2000, total, 0, 2) == 1);
+ CHECK(g.stepDown == 1);
+ // Still tight: no second step within 10 s.
+ CHECK(g.update(15.0, 2000, total, 0, 2) == 0);
+ CHECK(g.update(22.5, 2000, total, 0, 2) == 1);
+ CHECK(g.stepDown == 2);
+ // At the floor: no more steps.
+ CHECK(g.update(40.0, 2000, total, 0, 2) == 0);
+ CHECK(g.stepDown == 2);
+ // Roomy again for 60 s: one step back up, then another after 60 more.
+ CHECK(g.update(50.0, 20000, total, 0, 2) == 0);
+ CHECK(g.update(100.0, 20000, total, 0, 2) == 0);
+ CHECK(g.update(110.5, 20000, total, 0, 2) == -1);
+ CHECK(g.stepDown == 1);
+ CHECK(g.update(171.0, 20000, total, 0, 2) == -1);
+ CHECK(g.stepDown == 0);
+ // GPU memory alone can be tight.
+ TierMemoryGuard gpu;
+ CHECK(gpu.update(0.0, 20000, total, 100, 3) == 0);
+ CHECK(gpu.update(2.5, 20000, total, 100, 3) == 1);
+ // Unknown memory: nothing.
+ TierMemoryGuard none;
+ CHECK(none.update(100.0, 0, 0, 0, 3) == 0);
+}
+
+TEST(hw_tier_compute) {
+ resetComputeFailures();
+ // No GPU paths in this build yet: every task is CPU, whatever the choice.
+ for (int i = 0; i < kComputeTaskCount; ++i) {
+ const ComputeTask t = ComputeTask(i);
+ CHECK(computeTaskInfo(t).task == t);
+ CHECK(resolveCompute(t, ComputeChoice::Gpu, HwTier::Extreme, 10.0, 1.0) ==
+ (computeTaskInfo(t).gpuPath ? ComputePath::Gpu : ComputePath::Cpu));
+ CHECK(resolveCompute(t, ComputeChoice::Cpu, HwTier::Extreme, 10.0, 1.0) == ComputePath::Cpu);
+ CHECK(resolveCompute(t, ComputeChoice::Auto, HwTier::Floor, 10.0, 1.0) == ComputePath::Cpu); // Floor: as before
+ }
+ ComputeChoice c;
+ CHECK(computeChoiceFromName("GPU", c) && c == ComputeChoice::Gpu);
+ CHECK(computeChoiceFromName("", c) && c == ComputeChoice::Auto);
+ CHECK(!computeChoiceFromName("tpu", c));
+ // A failure is reported once and sticks for the session.
+ std::string msg;
+ CHECK(!takeComputeFailureMessage(msg));
+ reportGpuComputeFailure(ComputeTask::Normals, "shader compile");
+ reportGpuComputeFailure(ComputeTask::Normals, "again");
+ CHECK(gpuComputeFailed(ComputeTask::Normals));
+ CHECK(takeComputeFailureMessage(msg));
+ CHECK(msg.find("Normals switched to the CPU") == 0);
+ CHECK(msg.find("shader compile") != std::string::npos);
+ CHECK(!takeComputeFailureMessage(msg));
+ CHECK(resolveCompute(ComputeTask::Normals, ComputeChoice::Gpu, HwTier::Extreme, 10.0, 1.0) == ComputePath::Cpu);
+ resetComputeFailures();
+}
+
+TEST(hw_tier_gpu_list) {
+ const std::string ids =
+ "# comment\n"
+ "10de NVIDIA Corporation\n"
+ "\t2504 GA106 [GeForce RTX 3060 Lite Hash Rate]\n"
+ "\t\t1043 87f3 subsystem line\n"
+ "\t25a2 GA107M [GeForce RTX 3050 Mobile]\n"
+ "8086 Intel Corporation\n"
+ "\t9a49 TigerLake-LP GT2 [Iris Xe Graphics]\n"
+ "1002 Advanced Micro Devices, Inc. [AMD/ATI]\n"
+ "\t73ff Navi 23 [Radeon RX 6600/6600 XT/6600M]\n";
+ CHECK(pciIdsName(ids, 0x10de, 0x2504) == "NVIDIA GeForce RTX 3060 Lite Hash Rate");
+ CHECK(pciIdsName(ids, 0x8086, 0x9a49) == "Intel Iris Xe Graphics");
+ CHECK(pciIdsName(ids, 0x1002, 0x73ff) == "AMD Radeon RX 6600/6600 XT/6600M");
+ CHECK(pciIdsName(ids, 0x10de, 0xffff).empty());
+ // A hybrid laptop's sysfs: Intel iGPU (boot display) + NVIDIA dGPU.
+ const std::filesystem::path root = tempPath("sf_hw_tier_drm");
+ std::error_code ec;
+ std::filesystem::remove_all(root, ec);
+ auto card = [&](const char* name, const char* vendor, const char* device, const char* boot, const char* slot) {
+ const auto dev = root / name / "device";
+ writeFile(dev / "class", "0x030000\n");
+ writeFile(dev / "vendor", std::string(vendor) + "\n");
+ writeFile(dev / "device", std::string(device) + "\n");
+ writeFile(dev / "boot_vga", std::string(boot) + "\n");
+ writeFile(dev / "uevent", std::string("DRIVER=x\nPCI_SLOT_NAME=") + slot + "\n");
+ };
+ card("card0", "0x8086", "0x9a49", "1", "0000:00:02.0");
+ card("card1", "0x10de", "0x25a2", "0", "0000:01:00.0");
+ std::filesystem::create_directories(root / "card1-HDMI-A-1"); // a connector, not a card
+ writeFile(root / "pci.ids", ids);
+ const std::vector<GpuAdapter> gpus = listGpusSysfs(root.string(), (root / "pci.ids").string());
+ CHECK(gpus.size() == 2);
+ if (gpus.size() == 2) {
+ CHECK(gpus[0].name == "Intel Iris Xe Graphics");
+ CHECK(!gpus[0].discrete && gpus[0].bootDisplay);
+ CHECK(gpus[0].id == "pci-0000_00_02_0");
+ CHECK(gpus[1].name == "NVIDIA GeForce RTX 3050 Mobile");
+ CHECK(gpus[1].discrete && !gpus[1].bootDisplay);
+ CHECK(gpus[1].id == "pci-0000_01_00_0");
+ CHECK(autoGpuId(gpus) == "pci-0000_01_00_0");
+ }
+ // No pci.ids: a readable fallback name.
+ const std::vector<GpuAdapter> bare = listGpusSysfs(root.string(), "");
+ CHECK(bare.size() == 2 && bare[1].name == "NVIDIA GPU 10de:25a2");
+ CHECK(listGpusSysfs((root / "missing").string(), "").empty());
+ CHECK(autoGpuId({}).empty());
+ std::filesystem::remove_all(root, ec);
+}
+
+TEST(hw_tier_compact_memory) {
+ // The top bar's memory figures: short, binary units like the system monitors.
+ constexpr size_t MB = size_t(1) << 20, GB = size_t(1) << 30;
+ CHECK(compactBytes(640 * MB) == "640M");
+ CHECK(compactBytes(GB + GB / 5) == "1.2G");
+ CHECK(compactBytes(12 * GB) == "12G"); // a 12 GB card (12288 MB from the driver)
+ CHECK(compactBytes(9 * GB + 980 * MB) == "10G");
+ CHECK(compactBytes(0) == "0M");
+ CHECK(memoryText(12 * GB) == "12 GB");
+ CHECK(memoryText(343 * MB) == "343 MB");
+}
diff --git a/tests/ui/hardware_profile.sfui b/tests/ui/hardware_profile.sfui
index 423c6afc..53b37863 100644
--- a/tests/ui/hardware_profile.sfui
+++ b/tests/ui/hardware_profile.sfui
@@ -10,8 +10,14 @@ expect_no_text Getting to know this computer
click "Preferences##palette.preferences"
click "Performance##preferences.performance"
wait_for "Frame Governor" 10
-expect_text Hardware profile
-expect_text Detected
+expect_text Render profile
+expect_text render profile
+# The hardware tier (PanelHardwareTier.cpp): the machine and its tier, what it turns on, Compute and its tasks.
+expect_text What this turns on
+expect_text Focus Detail keeps
+expect_text Compute
+expect_text Brush solver: CPU
+expect_text CPU only for now
expect_text Triangles
expect_text View budget
expect_text Motion proxy from
diff --git a/tests/ui/hardware_tier.sfui b/tests/ui/hardware_tier.sfui
new file mode 100644
index 00000000..cc16ad92
--- /dev/null
+++ b/tests/ui/hardware_tier.sfui
@@ -0,0 +1,82 @@
+# cold
+# Hardware tiers (PanelHardwareTier.cpp, core/HardwareTier.h). CMake sets SF_HW_PROFILE_IN_TESTS=1,
+# SF_NO_CALIBRATION=1 and SF_HW_SIMULATE=high for this test, so the tier is High on any GPU and the first-run card
+# shows at once (a fresh settings folder is a first launch).
+# The first-run card: the machine, the tier, what it turns on; Got it puts it away for good on this machine.
+run new_sphere
+wait 0.5
+expect_text Tuned for your machine
+expect_text Your machine:
+expect_text Tier: High
+expect_text Turned on:
+shot card
+ui_scale 200
+wait 0.3
+shot card-2x
+ui_scale 100
+wait 0.3
+click "Got it"
+wait 0.3
+expect_no_text Tuned for your machine
+# The tier chip in the top bar; Turbo's bolt beside it.
+expect_text High
+click "Turbo##view.turbo"
+expect_status Turbo on
+wait 0.3
+shot turbo-on
+click "Turbo##view.turbo"
+expect_status Turbo off
+wait 0.4
+shot turbo-off
+# The key and View > Turbo do the same.
+key ctrl+alt+t
+expect_status Turbo on
+key ctrl+alt+t
+expect_status Turbo off
+# The chip opens Preferences > Performance at the tier.
+click "Performance tier##perf.tier_chip"
+wait 0.5
+expect_text "What this turns on:"
+expect_text Forced by SF_HW_SIMULATE=high
+expect_text Compute
+expect_text Brush solver: CPU
+expect_text CPU only for now
+shot panel
+ui_scale 200
+wait 0.3
+shot panel-2x
+ui_scale 100
+# Kept: after a restart the card stays away and Turbo is as left (off).
+restart
+wait 0.5
+expect_no_text Tuned for your machine
+# The chip and the bolt are in the top bar's drop order (title_version.sfui): nothing overlaps in any bar style at
+# 100 % and 200 %, nor at 512 logical px (a 1024 px window at 200 %); the chip goes first, then the bolt.
+expect_text High
+expect_value title_overlaps == 0
+shot topbar
+# Memory beside the triangles and frame rate (sfmonitor): this app's RAM / free RAM; the tooltip has the detail.
+expect_text free
+hover "##status.ram"
+wait 0.6
+expect_text RAM used by SculptForge
+expect_text Updated every second
+shot topbar-memory
+mouse_move 0.5 0.5
+ui_scale 200
+run ui_look look=classic layout=classic
+expect_value title_overlaps == 0
+run ui_look look=classic layout=sculptforge
+expect_value title_overlaps == 0
+shot topbar-2x
+run ui_look look=forge layout=sculptforge
+expect_value title_overlaps == 0
+shot topbar-2x-terminal
+run ui_look look=blueprint
+expect_value title_overlaps == 0
+ui_scale auto
+run ui_look look=forge layout=sculptforge
+logical_width 512
+wait_idle 30
+expect_value title_overlaps == 0
+shot topbar-512
diff --git a/tools/i18n/keep_english.txt b/tools/i18n/keep_english.txt
index 42cdedda..30d9921a 100644
--- a/tools/i18n/keep_english.txt
+++ b/tools/i18n/keep_english.txt
@@ -41,3 +41,6 @@ http://%s
Gen-2.5 Low
Gen-2.5 Medium
Gen-2.5 High
+CPU
+GPU
+Turbo