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.

34.5 KB
Raw Blame
// SculptForge - open source digital sculpting
// SPDX-License-Identifier: GPL-3.0-or-later
//
// The hardware profile in the app (docs/performance.md, "Hardware profile"):
//  - on first launch, and when the GPU, its driver or the app version changes, calibration runs over the first
//    frames (about 2 seconds, one short step per frame under a small overlay; Esc skips) and the result is cached
//    in the settings folder; later starts read the cache;
//  - Preferences > Performance shows what was detected and measured, the profile and its settings, the frame
//    governor's state, Re-calibrate and manual overrides;
//  - the adaptive frame governor (core/FrameGovernor.h) gets every drawn frame's CPU time and GPU time (timer
//    queries, read a few frames later) and moves the motion proxy threshold / render triangle budget.
// Tests, renders, recordings and the --measure-* runs never calibrate (their results must not depend on the
// machine), and keep the fixed 10 million triangle Fast Navigation threshold.
#include "app/App.h"
#include "app/Calibration.h"
#include "app/HwProfileUi.h"
#include "app/CrashLog.h"
#include "app/Ui.h"
#include "app/UserData.h"

#include "core/FrameGovernor.h"
#include "core/HardwareProfile.h"
#include "core/Micro.h"
#include "core/Multires.h"
#include "core/PerfTrace.h"
#include "core/ThreadPool.h"
#include "core/TierConfig.h"

#include <SDL3/SDL.h>

#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <deque>
#include <future>

namespace sf {


namespace {

constexpr const char* kPath = "Preferences > Performance";

double nowMs() { return double(SDL_GetTicksNS()) * 1e-6; }

void dim(const std::string& text) {
    ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
    ImGui::TextWrapped("%s", text.c_str());
    ImGui::PopStyleColor();
}

std::string fmt(const char* f, double v) {
    char buf[64];
    std::snprintf(buf, sizeof buf, f, v);
    return buf;
}

bool calibrationDisabled() {
    const char* v = std::getenv("SF_NO_CALIBRATION");
    return v && *v && *v != '0';
}

// Battery or mains (SDL_GetPowerInfo): a laptop on battery sends less per frame and drops to 60 Hz (core/TierConfig.h).
PowerSource powerSource() {
    switch (SDL_GetPowerInfo(nullptr, nullptr)) {
    case SDL_POWERSTATE_ON_BATTERY: return PowerSource::Battery;
    case SDL_POWERSTATE_NO_BATTERY:
    case SDL_POWERSTATE_CHARGING:
    case SDL_POWERSTATE_CHARGED: return PowerSource::AC;
    default: return PowerSource::Unknown;
    }
}

int displayRefreshHz(SDL_Window* window) {
    if (!window) return 0;
    const SDL_DisplayID display = SDL_GetDisplayForWindow(window);
    const SDL_DisplayMode* mode = display ? SDL_GetCurrentDisplayMode(display) : nullptr;
    return mode ? int(mode->refresh_rate + 0.5f) : 0;
}

} // namespace

float App::motionResolution() {
    static const float scale = [] {
        if (const char* v = std::getenv("SF_MOTION_RESOLUTION"); v && *v) return std::clamp(float(std::atof(v)) / 100.0f, 0.25f, 1.0f);
        return simulatedFloorTier() ? 0.75f : 1.0f;
    }();
    return scale;
}

bool App::hardwareProfileGoverns() const { return hwProfile_ && hwProfile_->active; }

void App::initHardwareProfile() {
    // Deterministic runs (UI tests, renders, recordings, demos) and the --measure-* runs keep the fixed defaults; a
    // UI test of this panel turns it on with SF_HW_PROFILE_IN_TESTS=1 (its settings folder is a temporary one).
    const char* inTests = std::getenv("SF_HW_PROFILE_IN_TESTS");
    const bool testThis = !options_.uiTest.empty() && inTests && std::string(inTests) == "1";
    if (!testThis && (uiConfigDeterministic_ || !options_.renderPath.empty() || !options_.recordPath.empty() ||
                      !options_.uiTest.empty() || options_.measureIdle > 0.0f || options_.measureStroke > 0.0f))
        return;
    hwProfile_ = std::make_shared<HwProfileUi>();
    HwProfileUi& hw = *hwProfile_;
    hw.displayHz = displayRefreshHz(window_);
    hw.power = powerSource();
    // The calibrate command (console, MCP) measures the GPU too while the app runs.
    setGpuCalibrator([this](HardwareProfile& out, std::string&) {
        HardwareProfile cached;
        const ProfileOverrides keep = loadHardwareProfile(hardwareProfilePath(), cached) ? cached.overrides : hwProfile_->profile.overrides;
        const bool same = cached.hardware.glRenderer == hwProfile_->profile.hardware.glRenderer;
        out = calibrateNow(false, keep, same ? &cached.measuredTier : nullptr);
        std::string error;
        saveHardwareProfile(hardwareProfilePath(), out, error);
        // Applied on the next frame (the command saved it; the revision check reloads it).
        hwProfile_->revision = 0;
        return true;
    });
    HardwareInfo current;
    probeHardware(current);
    HardwareProfile cached;
    const bool hasCache = loadHardwareProfile(hardwareProfilePath(), cached);
    hw.calibrationReason = recalibrationReason(hasCache ? &cached : nullptr, current);
    HardwareProfile start;
    if (hw.calibrationReason.empty()) {
        // The cache fits: no measuring. Only what changes between runs (free video memory) is refreshed.
        cached.hardware.vramAvailableMB = current.vramAvailableMB;
        start = cached;
        hw.saved = true;
    } else {
        // What the probe alone suggests (overrides kept): the profile while calibrating, or for good when
        // SF_NO_CALIBRATION=1.
        Calibration none;
        none.skipped = true;
        start = mapProfile(current, none, hasCache ? cached.overrides : ProfileOverrides{});
        if (!calibrationDisabled()) {
            SDL_Log("Hardware profile: calibrating (%s)", hw.calibrationReason.c_str());
            hw.calibrator = std::make_unique<Calibrator>(false);
            hw.announce = true;
        }
    }
    applyHardwareProfile(start, false);
    if (!hw.calibrator) SDL_Log("Hardware profile: %s", start.reason.c_str());
    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
// calibration that wasn't asked for) says so in the status bar and adapts the preferences a profile implies.
void App::applyHardwareProfile(const HardwareProfile& p, bool announce) {
    HwProfileUi& hw = *hwProfile_;
    hw.profile = p;
    hw.active = true;
    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;
    s.uploadBudgetMBPerFrame = hw.tier.uploadBudgetMBPerFrame;
    const bool floor = simulatedFloorTier();
    if (floor) { // SF_HW_SIMULATE=floor: an integrated GPU's budgets (docs/design/perf-moonshots.md §0)
        s.renderTriangleBudget = std::min<uint64_t>(s.renderTriangleBudget, 2'000'000);
        s.motionProxyThreshold = std::min<uint64_t>(s.motionProxyThreshold, 3'000'000);
        s.vramBudgetMB = std::min<uint64_t>(s.vramBudgetMB, 1536);
        s.uploadBudgetMBPerFrame = std::min<uint64_t>(s.uploadBudgetMBPerFrame, 16);
        s.threads = 4;
        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");
    }
    hw.profile.settings.targetFps = s.targetFps;
    setCurrentPerformanceSettings(s);
    // (the still frame's cost before any is measured: the calibrated rate; the simulated floor tier keeps its budget's)
    renderer_.setTriangleRate(floor ? 0.0 : hw.profile.calibration.trianglesPerSecondM);
    GovernorConfig cfg;
    cfg.targetFps = s.targetFps;
    cfg.minBudget = std::max<uint64_t>(250'000, s.renderTriangleBudget / 8);
    cfg.maxBudget = std::min<uint64_t>(2'000'000'000, std::max<uint64_t>(s.renderTriangleBudget * 4, cfg.minBudget));
    if (floor) cfg.maxBudget = s.renderTriangleBudget; // (the governor may lower the budget, never raise it)
    hw.governor.reset(cfg, s.renderTriangleBudget);
    hw.revision = performanceSettingsRevision();
    if (!announce) return;
    // A software renderer draws every sample on the CPU: no antialiasing.
    if (p.tier == ProfileTier::Software && uiPrefs_.antialiasing > 1) uiPrefs_.antialiasing = 1;
    const std::string gpu = p.hardware.glRenderer.empty() ? std::string("this computer") : p.hardware.glRenderer;
    status_ = std::string(p.calibration.skipped ? "Calibration skipped: " : "Calibrated for this computer: ") + gpu + " -> " +
              tierName(p.tier) + " profile (Preferences > Performance)";
}

void App::finishCalibration() {
    HwProfileUi& hw = *hwProfile_;
    HardwareProfile cached;
    const ProfileOverrides keep = loadHardwareProfile(hardwareProfilePath(), cached) ? cached.overrides : hw.profile.overrides;
    const bool same = !cached.hardware.glRenderer.empty() && cached.hardware.glRenderer == hw.profile.hardware.glRenderer;
    const HardwareProfile p = hw.calibrator->profile(keep, same ? &cached.measuredTier : nullptr);
    hw.calibrator.reset();
    std::string error;
    hw.saved = saveHardwareProfile(hardwareProfilePath(), p, error);
    if (!hw.saved) SDL_Log("Hardware profile not saved: %s", error.c_str());
    SDL_Log("Hardware profile: %s (%.0f ms)", p.reason.c_str(), p.calibration.durationMs);
    applyHardwareProfile(p, hw.announce);
    hw.announce = false;
    // 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() {
    setGpuCalibrator(nullptr);
    if (hwProfile_) hwProfile_->timer.release();
    hwProfile_.reset();
}

void App::hardwareProfileFrameBegin() {
    if (!hwProfile_) return;
    HwProfileUi& hw = *hwProfile_;
    if (hw.calibrator) {
        // One step per frame, after the overlay has been on screen once.
        if (hw.calibrationFrames++ > 0 && !hw.calibrator->step()) finishCalibration();
        activeUntil_ = std::max(activeUntil_, double(SDL_GetTicksNS()) * 1e-9 + 0.3); // keep the frames coming
    }
    hw.frameStartMs = nowMs();
    hw.drawStartMs = -1.0;
    if (!hw.calibrator) hw.timer.begin();
}

void App::hardwareProfileDrawStart() {
    if (hwProfile_) hwProfile_->drawStartMs = nowMs();
}

void App::hardwareProfileFrameEnd() {
    if (!hwProfile_) return;
    HwProfileUi& hw = *hwProfile_;
    const uint64_t frame = hw.frame++;
    if (hw.calibrator) return;
    hw.timer.end(frame);
    FrameSample sample;
    sample.cpuMs = nowMs() - hw.frameStartMs;
    sample.drawnTriangles = renderer_.lastDrawnTriangles();
    sample.sceneTriangles = perf_.sceneTriangles;
    sample.moving = perf_.movingNow;
    sample.limited = perf_.proxyNow;
    hw.lastCpuMs = sample.cpuMs;
    bool changed = false;
    if (hw.timer.available()) {
        hw.pending.push_back({frame, sample, hw.drawStartMs >= 0.0 ? hw.drawStartMs - hw.frameStartMs : sample.cpuMs});
        uint64_t doneFrame = 0;
        double gpuMs = 0.0;
        while (hw.timer.poll(doneFrame, gpuMs)) {
            while (!hw.pending.empty() && hw.pending.front().frame < doneFrame) hw.pending.pop_front(); // lost
            if (!hw.pending.empty() && hw.pending.front().frame == doneFrame) {
                FrameSample s = hw.pending.front().sample;
                const double cpuBeforeDrawMs = hw.pending.front().cpuBeforeDrawMs;
                hw.pending.pop_front();
                s.gpuMs = gpuMs;
                hw.lastGpuMs = gpuMs;
                renderer_.noteGpuFrame(gpuMs, s.drawnTriangles, cpuBeforeDrawMs);
                if (proof_ && proofGpuMs_.size() < 4096) proofGpuMs_.push_back(gpuMs);
                changed = hw.governor.addFrame(s) || changed;
            }
        }
        while (hw.pending.size() > 8) { // the GPU time never came: count the CPU time alone
            changed = hw.governor.addFrame(hw.pending.front().sample) || changed;
            hw.pending.pop_front();
        }
    } else {
        changed = hw.governor.addFrame(sample);
    }
    static const bool pinned = [] { // SF_GOVERNOR=0: the budgets stay as the profile set them (benchmark A/Bs)
        const char* v = std::getenv("SF_GOVERNOR");
        return v && *v == '0';
    }();
    if (changed && !pinned && hw.profile.overrides.governor && !hw.profile.overrides.motionProxyThreshold)
        setGovernedBudgets(hw.governor.budget(), hw.governor.proxyThreshold());
    // The display (the window moved to a 120 Hz screen) or the power source (unplugged) may change: every few
    // seconds, look; a change re-applies the profile with the new tier configuration.
    if (const double t = double(SDL_GetTicksNS()) * 1e-9; t >= hw.nextPowerCheck) {
        hw.nextPowerCheck = t + 5.0;
        const int hz = displayRefreshHz(window_);
        const PowerSource power = powerSource();
        if (hz != hw.displayHz || power != hw.power) {
            const bool battery = power == PowerSource::Battery, wasBattery = hw.power == PowerSource::Battery;
            hw.displayHz = hz;
            hw.power = power;
            const HardwareProfile p = hw.profile;
            applyHardwareProfile(p, false);
            if (battery != wasBattery)
                status_ = battery ? "On battery: lighter uploads, " + std::to_string(hw.tier.targetHz) + " Hz"
                                  : "On mains power: " + std::string(hw.tier.draftBrushMode ? "draft" : "continuous") + " brushes, " +
                                        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;
        if (loadHardwareProfile(hardwareProfilePath(), cached)) applyHardwareProfile(cached, false);
        else hw.revision = performanceSettingsRevision();
    }
}

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();
    ImGui::SetNextWindowPos(ImVec2(vp->WorkPos.x + vp->WorkSize.x * 0.5f, vp->WorkPos.y + vp->WorkSize.y * 0.5f), ImGuiCond_Always,
                            ImVec2(0.5f, 0.5f));
    ImGui::SetNextWindowSize(ImVec2(380.0f * uiScale_, 0.0f));
    ImGui::SetNextWindowFocus();
    if (ImGui::Begin("##calibration", nullptr,
                     ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
                         ImGuiWindowFlags_AlwaysAutoResize)) {
        if (fontBold_) ImGui::PushFont(fontBold_);
        ImGui::TextUnformatted(tr("Getting to know this computer"));
        if (fontBold_) ImGui::PopFont();
        dim(tr("A two-second check of the GPU, the CPU and memory, so big scenes stay smooth. Once, then again only when "
            "the graphics card, its driver or SculptForge changes. Nothing leaves this computer."));
        ImGui::ProgressBar(hw.calibrator->progress(), ImVec2(-1.0f, 0.0f), hw.calibrator->stageName());
        const bool esc = ImGui::IsKeyPressed(ImGuiKey_Escape, false);
        if (ImGui::Button(tr("Skip")) || esc) {
            hw.calibrator->skip();
            finishCalibration();
        }
        ImGui::SameLine();
        ImGui::TextDisabled(tr("Esc"));
    }
    ImGui::End();
}

void App::registerPerformanceProfileUiActions() {
    registerHardwareTierUiActions(); // the tier, Compute, the graphics card, Turbo (PanelHardwareTier.cpp)
    {
        Action a;
        a.id = "perf.recalibrate";
        a.label = "Re-calibrate";
        a.palette = kPath;
        a.run = [this] {
            if (!hwProfile_) {
                status_ = "Calibration is off in this run (tests, renders and recordings use fixed settings)";
                return;
            }
            hwProfile_->calibrator = std::make_unique<Calibrator>(false);
            hwProfile_->calibrationFrames = 0;
            hwProfile_->announce = true;
            status_ = "Calibrating...";
        };
        a.description = "Measure this computer again (about 2 seconds): the GPU's triangle throughput and upload speed, "
                        "brush speed and memory bandwidth, then pick the performance profile. Your overrides are kept.";
        actions_.add(std::move(a));
    }
    {
        Action a;
        a.id = "perf.governor";
        a.label = "Frame Governor";
        a.palette = kPath;
        a.run = [this] {
            if (!hwProfile_) return;
            ProfileOverrides o = hwProfile_->profile.overrides;
            o.governor = !o.governor;
            const HardwareProfile p = mapProfile(hwProfile_->profile.hardware, hwProfile_->profile.calibration, o);
            std::string error;
            saveHardwareProfile(hardwareProfilePath(), p, error);
            applyHardwareProfile(p, false);
            status_ = o.governor ? "Frame governor on" : "Frame governor off (the profile's budgets stay as set)";
        };
        a.checked = [this] { return hwProfile_ && hwProfile_->profile.overrides.governor; };
        a.description = "Hold the view at the target frame rate (60 fps, or 120 on a 120 Hz display) by drawing big "
                        "scenes' lighter motion proxy sooner or later while the view moves. Only what you see changes, "
                        "never the model.";
        actions_.add(std::move(a));
    }
}

void App::drawPerformanceProfileSection() {
    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 "
                 "scenes switch to their lighter motion proxy, GPU memory and upload budgets, texture and subdivision "
                 "limits, threads. Nothing is sent anywhere.",
                 kPath);
    if (!hwProfile_) {
        dim(tr("Off in this run: tests, renders and recordings use fixed settings."));
        ImGui::Spacing();
        return;
    }
    HwProfileUi& hw = *hwProfile_;
    if (hw.calibrator) {
        ImGui::ProgressBar(hw.calibrator->progress(), ImVec2(-1.0f, 0.0f), hw.calibrator->stageName());
        ImGui::Spacing();
        return;
    }
    const HardwareProfile& p = hw.profile;
    const HardwareInfo& h = p.hardware;
    const Calibration& c = p.calibration;
    const PerformanceSettings& s = p.settings;
    // "Detected Apple M1 Pro, 21.3 GB unified -> Workstation"
    // Shared memory shows what the GPU may use (the budget), not what the driver reports (often all of the RAM).
    const bool shared = h.gpuKind == GpuKind::Unified || h.gpuKind == GpuKind::Integrated;
    const std::string vram = shared      ? formatMegabytes(s.vramBudgetMB) + " shared"
                             : h.vramMB ? formatMegabytes(h.vramMB)
                                        : std::string("memory unknown");
    if (fontBold_) ImGui::PushFont(fontBold_);
    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).
    std::string why = p.reason;
    if (const size_t arrow = why.find(" -> "); arrow != std::string::npos)
        if (const size_t open = why.find(" (", arrow); open != std::string::npos && why.back() == ')')
            why = why.substr(open + 2, why.size() - open - 3);
    dim(why);
    std::string measured;
    if (c.skipped) measured = "Not measured (skipped): settings from the GPU type and memory sizes.\n";
    else {
        measured += "Triangles " + fmt("%.0fM/s", c.trianglesPerSecondM) + (c.gpuTimer ? " (GPU timer)" : " (glFinish)") +
                    "   Upload " + fmt("%.1f GB/s", c.uploadGBps) + "\n";
        measured += "Brush dab " + fmt("%.2f ms", c.dabMs) + " (" + fmt("%.1fk", c.dabVertices / 1000.0) + " vertices)   Memory " +
                    fmt("%.1f GB/s", c.memoryGBps) + "\n";
    }
    std::string simd;
    for (const auto& x : h.simd) simd += (simd.empty() ? "" : ", ") + x;
    measured += h.cpu + (h.cpu.empty() ? "" : ", ") + std::to_string(h.cpuThreads) + " threads" + (simd.empty() ? "" : " (" + simd + ")") +
                ", " + formatMegabytes(h.ramMB) + " RAM\nVideo memory: " + (h.vramSource.empty() ? std::string("none") : h.vramSource) +
                (h.vramAvailableMB ? ", " + formatMegabytes(h.vramAvailableMB) + " free" : std::string()) + "\n" + h.os + ", OpenGL " +
                h.glVersion;
    ImGui::TextWrapped("%s", measured.c_str());
    ImGui::LogText("%s", measured.c_str());

    ImGui::Spacing();
    const uint64_t governed = renderTriangleBudget();
    std::string set = "View budget " + formatTriangles(s.renderTriangleBudget) + " triangles" +
                      (governed != s.renderTriangleBudget ? " (governed: " + formatTriangles(governed) + ")" : std::string()) +
                      "\nMotion proxy from " + formatTriangles(motionProxyThreshold()) + " triangles\nGPU memory budget " +
                      formatMegabytes(s.vramBudgetMB) + ", uploads " + std::to_string(s.uploadBudgetMBPerFrame) +
                      " MB per frame\nTextures up to " + std::to_string(s.maxTextureSize) + ", subdivision up to " +
                      formatTriangles(s.maxSubdivisionTriangles) + ", micro-triangles up to " + formatTriangles(s.microTriangleLimit) +
                      "\n" + std::to_string(s.threads) + " threads" +
                      (s.threads != ThreadPool::shared().threads() ? " (after a restart; now " + std::to_string(ThreadPool::shared().threads()) + ")" : std::string()) +
                      ", target " + std::to_string(s.targetFps) + " fps";
    const TierConfig& tc = hw.tier;
    set += "\n" + std::string(tc.draftBrushMode ? "Draft brushes (normals and cavity at pen release)" : "Continuous brushes") +
           ", active " + formatTriangles(tc.activeTriangleBudget) + " triangles, cache up to " + formatMegabytes(tc.residentCacheCapMB) +
           (tc.zeroCopyUMA ? ", zero-copy (shared memory)" : "") +
           (tc.onBattery() ? "\nOn battery" : tc.power == PowerSource::AC ? "\nOn mains power" : "");
    ImGui::TextWrapped("%s", set.c_str());
    ImGui::LogText("%s", set.c_str());

    bool governor = p.overrides.governor;
    if (ImGui::Checkbox(tr("Frame Governor"), &governor)) actions_.find("perf.governor")->run();
    ui::HelpAction(*this, "perf.governor");
    if (governor && hw.governor.decisions() > 0) {
        const char* action = hw.governor.lastAction() == FrameGovernor::Action::Lowered  ? "drawing less"
                             : hw.governor.lastAction() == FrameGovernor::Action::Raised ? "drawing more"
                                                                                          : "holding";
        dim("Moving view: " + fmt("%.1f ms", hw.governor.lastCostMs()) + " of " + fmt("%.1f ms", hw.governor.targetMs()) + " per frame (" +
            (hw.lastGpuMs >= 0.0 ? "GPU timer" : "CPU time") + "), " + action);
    } else if (governor) {
        dim(tr("Learns from frames while the view moves."));
    }
    if (ImGui::Button(tr("Re-calibrate"))) actions_.find("perf.recalibrate")->run();
    ui::HelpAction(*this, "perf.recalibrate");

    // --- Manual overrides ---
    if (ImGui::TreeNode(tr("Manual overrides"))) {
        ProfileOverrides o = p.overrides;
        bool edited = false;
        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;
        ImGui::SetNextItemWidth(-1.0f);
        if (ImGui::Combo("##perf.tier", &tierIndex, tiers, 4)) {
            o.tier = tierIndex == 0 ? std::string() : std::string(tierName(ProfileTier(tierIndex - 1)));
            edited = true;
        }
        // Numbers: 0 = automatic (shown as the profile's value, dimmed hint).
        auto number = [&](const char* label, uint64_t& value, uint64_t automatic, double scale, const char* unit) {
            float v = float(double(value ? value : 0) / scale);
            ImGui::SetNextItemWidth(120.0f * uiScale_);
            const std::string hint = fmt("%.1f", double(automatic) / scale) + " " + unit + " (auto)";
            ImGui::PushID(label);
            if (ImGui::InputFloat("##v", &v, 0.0f, 0.0f, value ? "%.1f" : hint.c_str(), ImGuiInputTextFlags_EnterReturnsTrue)) {
                value = v > 0.0f ? uint64_t(double(v) * scale) : 0;
                edited = true;
            }
            ImGui::SameLine();
            ImGui::TextUnformatted(label);
            ImGui::PopID();
        };
        number(tr("View budget (M triangles)"), o.renderTriangleBudget, p.automatic.renderTriangleBudget, 1e6, "M");
        number(tr("Motion proxy from (M triangles)"), o.motionProxyThreshold, p.automatic.motionProxyThreshold, 1e6, "M");
        number(tr("GPU memory budget (GB)"), o.vramBudgetMB, p.automatic.vramBudgetMB, 1024.0, "GB");
        number(tr("Uploads per frame (MB)"), o.uploadBudgetMBPerFrame, p.automatic.uploadBudgetMBPerFrame, 1.0, "MB");
        number(tr("Subdivision limit (M triangles)"), o.maxSubdivisionTriangles, p.automatic.maxSubdivisionTriangles, 1e6, "M");
        {
            uint64_t threads = uint64_t(o.threads);
            number(tr("Threads (next start)"), threads, uint64_t(p.automatic.threads), 1.0, "");
            o.threads = int(threads);
        }
        const char* draftNames[] = {tr("Draft brushes: automatic"), tr("Draft brushes: always"), tr("Draft brushes: never")};
        ImGui::SetNextItemWidth(-1.0f);
        if (ImGui::Combo("##perf.draft", &o.draftBrush, draftNames, 3)) edited = true;
        const char* fpsNames[] = {tr("Target: automatic"), tr("30 fps"), tr("60 fps"), tr("120 fps"), tr("144 fps")};
        const int fpsValues[] = {0, 30, 60, 120, 144};
        int fpsIndex = 0;
        for (int i = 0; i < 5; ++i)
            if (o.targetFps == fpsValues[i]) fpsIndex = i;
        ImGui::SetNextItemWidth(-1.0f);
        if (ImGui::Combo("##perf.fps", &fpsIndex, fpsNames, 5)) {
            o.targetFps = fpsValues[fpsIndex];
            edited = true;
        }
        if (o.any() && ImGui::Button(tr("Back to automatic"))) {
            const ProfileOverrides was = o;
            o = ProfileOverrides{};
            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) {
            const HardwareProfile next = mapProfile(h, c, o);
            std::string error;
            if (!saveHardwareProfile(hardwareProfilePath(), next, error)) status_ = "Not saved: " + error;
            applyHardwareProfile(next, false);
        }
        ImGui::TreePop();
    }
    ImGui::Separator();
    ImGui::Spacing();
}

} // namespace sf

// --- Help > Record a performance trace (core/PerfTrace.h, #127) ---

namespace sf {

namespace {

std::string millions(size_t n) { return n < 1000000 ? std::to_string(n) : fmt("%.2fM", double(n) * 1e-6); }

} // namespace

void App::togglePerfTrace() {
    if (perftrace::on()) {
        perftrace::stop();
        status_ = "Performance trace stopped: sculptforge-trace.log is in the log folder (Help > Open log folder)";
        return;
    }
    std::string folder = crashlog::path();
    if (const size_t slash = folder.find_last_of("/\\"); slash != std::string::npos) folder.resize(slash + 1);
    else folder.clear();
    if (folder.empty()) {
        folder = userDataDir();
    }
    HardwareInfo hw;
    if (hwProfile_) hw = hwProfile_->profile.hardware;
    else probeHardware(hw);
    std::string header = std::string("SculptForge ") + SCULPTFORGE_VERSION + " performance trace | GPU " + hw.glRenderer +
                         " (" + hw.glVendor + ", " + gpuKindName(hw.gpuKind) + ", " + std::to_string(hw.vramMB) +
                         " MB) | OpenGL " + hw.glVersion + " | " + hw.cpu + ", " + std::to_string(hw.cpuThreads) +
                         " threads, " + std::to_string(hw.ramMB) + " MB RAM, " + hw.simdBuild + " | " + hw.os;
    if (hwProfile_)
        header += std::string(" | profile ") + tierName(hwProfile_->profile.tier) + ", " +
                  std::to_string(hwProfile_->tier.targetHz) + " Hz target, display " + std::to_string(hwProfile_->displayHz) + " Hz";
    perf_.traceLongMs = perftrace::kLongFrameMs;
    if (const char* ms = std::getenv("SF_PERF_TRACE_MS"); ms && *ms) perf_.traceLongMs = std::atof(ms);
    header += fmt(" | frames over %.0f ms are written", perf_.traceLongMs);
    if (folder.empty() || !perftrace::start(folder, header)) {
        status_ = "Couldn't write the performance trace (the user data folder couldn't be written)";
        return;
    }
    perf_.traceJobs = perfTraceJobs();
    perf_.traceJobsSince = double(SDL_GetTicksNS()) * 1e-9;
    perftrace::line("recording | " + perfTraceScene() + (perf_.traceJobs.empty() ? "" : " | running: " + perf_.traceJobs));
    status_ = "Recording a performance trace: do what is slow, then Help > Record a performance trace again to stop";
}

std::string App::perfTraceScene() const {
    const Mesh& m = doc_.mesh;
    std::string s = "Part " + std::to_string(doc_.activePart + 1) + "/" + std::to_string(doc_.partCount()) + " " +
                    millions(m.triangleCount()) + " tris " + millions(m.vertexCount()) + " verts";
    if (const int levels = subdivLevelCount(m); levels > 0)
        s += ", level " + std::to_string(subdivCurrentLevel(m) + 1) + "/" + std::to_string(levels);
    if (m.micro) s += ", micro level " + std::to_string(m.micro->level) + " (" + millions(m.micro->microTriangles()) + " tris)";
    s += " | scene " + millions(perf_.sceneTriangles) + " tris, drawn " + millions(renderer_.lastDrawnTriangles());
    s += ", AA " + std::to_string(perf_.samplesUsed) + fmt(", view %.0f%%", double(uiPrefs_.viewResolution));
    if (perf_.movingNow) s += ", moving";
    if (perf_.proxyNow) s += ", proxy";
    if (doc_.sculptor.strokeActive()) s += ", stroke";
    if (perf_.gpuOutOfMemory) s += ", GPU out of memory";
    return s;
}

std::string App::perfTraceJobs() const {
    auto running = [](const auto& f) { return f.valid() && f.wait_for(std::chrono::seconds(0)) != std::future_status::ready; };
    std::string s;
    auto add = [&](bool busy, const char* name) {
        if (!busy) return;
        if (!s.empty()) s += ", ";
        s += name;
    };
    add(bool(voxelRemesh_), "remesh");
    add(bool(qremesh_), "QRemesh");
    add(bool(autoUv_), "Auto UV");
    add(bakeBusy(), "bake");
    add(meshMapsBusy(), "mesh maps");
    add(uvEditorBusy(), "UV editor");
    add(thumbs_.busy(), "thumbnails");
    add(libraryScanner_.busy(), "library scan");
    add(galleryBusy(), "brush gallery");
    add(renderer_.environmentPending(), "environment");
    add(splatTrainBusy(), "splat training");
    add(sculptableBusy(), "make sculptable");
    add(phoneBusy(), "phone");
    add(bool(updateJob_), "update check");
    add(running(pendingBrush_) || running(pendingGenerator_) || running(pendingModels_) || running(pendingUnreal_) ||
            running(pendingComfyCheck_),
        "AI / bridge request");
    add(solverBusy(), "stroke solver");
    return s;
}

void App::tracePerfFrame(const double* phase) {
    // Background jobs that started or ended since the last frame.
    const double now = double(SDL_GetTicksNS()) * 1e-9;
    if (std::string jobs = perfTraceJobs(); jobs != perf_.traceJobs) {
        perftrace::line(fmt("jobs after %.2f s: ", now - perf_.traceJobsSince) + (perf_.traceJobs.empty() ? "none" : perf_.traceJobs) +
                        " -> " + (jobs.empty() ? "none" : jobs));
        perf_.traceJobs = std::move(jobs);
        perf_.traceJobsSince = now;
    }
    const double total = phase[6] - phase[0];
    if (total <= perf_.traceLongMs) return;
    char buf[320];
    std::snprintf(buf, sizeof buf,
                  "long frame %.1f ms: events %.1f, dabs %.1f, UI %.1f, ghost + sync %.1f (uploads %.1f), draw %.1f, "
                  "UI draw + swap %.1f | GPU %s ms (a frame before) | ",
                  total, phase[1] - phase[0], phase[2] - phase[1], phase[3] - phase[2], phase[4] - phase[3], perf_.lastSyncMs,
                  phase[5] - phase[4], phase[6] - phase[5],
                  hwProfile_ && hwProfile_->lastGpuMs >= 0.0 ? fmt("%.1f", hwProfile_->lastGpuMs).c_str() : "?");
    perftrace::line(buf + perfTraceScene() + (perf_.traceJobs.empty() ? "" : " | running: " + perf_.traceJobs));
}

void App::tracePerfStroke(const std::string& label) {
    const SculptTimings& t = perf_.lastStroke;
    char buf[256];
    std::snprintf(buf, sizeof buf,
                  "stroke %s: %llu dabs, %s verts moved, kernel %.1f ms, normals %.1f, BVH %.1f, dynamic topology %.1f, "
                  "uploads %.1f over %d frames | ",
                  label.c_str(), (unsigned long long)t.dabs, millions(size_t(t.vertices)).c_str(), t.kernelMs, t.normalsMs,
                  t.bvhMs, t.remeshMs, perf_.lastStrokeSyncMs, perf_.lastStrokeFrames);
    perftrace::line(buf + perfTraceScene());
}

} // namespace sf