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.

18.1 KB
Raw Blame
// SculptForge - open source digital sculpting
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Preferences > Performance (Preferences > Performance and Mem): how the 3D view draws (Antialiasing,
// Fast Navigation), Multithreading, what the last stroke cost per dab, and the memory the scene holds. The
// numbers come from the same instruments as the benchmark (core/Benchmark.h, docs/performance.md).
#include "app/App.h"
#include "app/Ui.h"
#include "app/I18n.h"

#include "core/Benchmark.h"
#include "core/Micro.h"
#include "core/HardwareProfile.h"
#include "core/ThreadPool.h"

#include <imgui.h>

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

namespace sf {

namespace {

constexpr const char* kPath = "Preferences > Performance";
// Scenes this big draw without antialiasing while the view moves (with Fast Navigation on): the hardware profile's
// motion proxy threshold, which the frame governor adjusts (core/HardwareProfile.h), else 10 million. UI tests
// set it with the environment variable SF_FAST_NAVIGATION_TRIANGLES, so they needn't build a huge mesh.
size_t fastNavigationTriangles(bool governed) {
    const char* v = std::getenv("SF_FAST_NAVIGATION_TRIANGLES");
    if (v && *v) return size_t(std::strtoull(v, nullptr, 10));
    return governed ? size_t(motionProxyThreshold()) : size_t(10'000'000);
}

std::string megabytes(size_t bytes) {
    char buf[32];
    if (bytes >= size_t(1) << 30) std::snprintf(buf, sizeof buf, "%.2f GB", double(bytes) / double(size_t(1) << 30));
    else std::snprintf(buf, sizeof buf, "%.0f MB", double(bytes) / double(size_t(1) << 20));
    return buf;
}

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

} // namespace

void App::registerPerformanceUiActions() {
    auto add = [this](std::string id, std::string label, std::function<void()> run, std::function<bool()> checked,
                      std::string description) {
        Action a;
        a.id = std::move(id);
        a.label = std::move(label);
        a.palette = kPath;
        a.run = std::move(run);
        a.checked = std::move(checked);
        a.description = std::move(description);
        actions_.add(std::move(a));
    };
    for (int samples : {1, 2, 4, 8}) {
        const std::string name = samples == 1 ? "Off" : std::to_string(samples) + "x";
        add("perf.aa_" + std::to_string(samples), "AA " + name,
            [this, samples, name] {
                uiPrefs_.antialiasing = samples;
                status_ = "Antialiasing " + name + (samples > 1 && uiPrefs_.fastNavigation ? " (off while big scenes move)" : "");
            },
            [this, samples] { return uiPrefs_.antialiasing == samples; },
            samples == 1 ? "Draw the 3D view without antialiasing: fastest, with jagged edges."
                         : "Smooth the 3D view's edges with " + std::to_string(samples) +
                               " samples per pixel (multisampling). More samples look smoother and cost more on huge "
                               "meshes. If the GPU can't make room for them, the view uses fewer.");
    }
    add("perf.fast_navigation", "Fast Navigation",
        [this] {
            uiPrefs_.fastNavigation = !uiPrefs_.fastNavigation;
            status_ = uiPrefs_.fastNavigation ? "Fast Navigation on" : "Fast Navigation off";
        },
        [this] { return uiPrefs_.fastNavigation; },
        "While you rotate, pan or zoom a big scene (over the hardware profile's motion proxy threshold, which the "
        "frame governor adjusts; 10 million triangles without a profile), draw a lighter version without "
        "antialiasing, so the view keeps up; it is full detail again as soon as the view stops.");
    add("perf.multithreading", "Multithreading",
        [this] {
            uiPrefs_.multithreading = ThreadPool::shared().serial();
            applyPerformancePrefs();
            status_ = uiPrefs_.multithreading ? "Multithreading on (" + std::to_string(ThreadPool::shared().threads()) + " threads)"
                                              : "Multithreading off (one thread)";
        },
        [] { return !ThreadPool::shared().serial(); },
        "Run brushes, normal and BVH updates and project saving on every core. Turn it off only to compare speeds "
        "or rule it out when troubleshooting: the results are the same either way.");
    add("perf.predictive_strokes", "Predictive Strokes",
        [this] {
            uiPrefs_.predictiveStrokes = !uiPrefs_.predictiveStrokes;
            status_ = uiPrefs_.predictiveStrokes ? "Predictive strokes on" : "Predictive strokes off";
        },
        [this] { return uiPrefs_.predictiveStrokes; },
        "Sculpt strokes work out the brush on their own thread while the view keeps drawing at full speed, and show "
        "the dabs still being worked out as a preview on the surface, with the cursor and the stroke's head drawn "
        "where the pen is about to be. On a heavy mesh the surface moves under the pen at once and lifting the pen "
        "is instant. The finished sculpt is exactly the same either way.");
    add("perf.live_move", "Live Move (Experimental)",
        [this] {
            uiPrefs_.liveMove = !uiPrefs_.liveMove;
            status_ = uiPrefs_.liveMove ? "Live Move on" : "Live Move off";
        },
        [this] { return uiPrefs_.liveMove; },
        "Experimental. The Move brush's drag is drawn by the graphics card from where the surface started, so it "
        "follows the pen at the view's frame rate whatever the mesh size; the move itself is applied once, exactly, "
        "when you lift the pen. Not with masks, hidden parts, sculpt layers, micro levels, Connected Only or View "
        "falloff (Move works as before there).");
    add("perf.background_preview", "Background Preview (Experimental)",
        [this] {
            uiPrefs_.backgroundPreview = !uiPrefs_.backgroundPreview;
            status_ = uiPrefs_.backgroundPreview ? "Background preview on" : "Background preview off";
        },
        [this] { return uiPrefs_.backgroundPreview; },
        "Experimental. On meshes of 2 million vertices or more, big brushes are worked out on their own thread; "
        "with this on, the dabs still being worked out are shown as a preview on the surface (as Predictive "
        "Strokes does), so the stroke stays under the pen. The finished sculpt is exactly the same either way.");
    add("perf.fast_upload", "Fast Upload (Experimental)",
        [this] {
            uiPrefs_.fastUpload = !uiPrefs_.fastUpload;
            status_ = uiPrefs_.fastUpload ? "Fast upload on" : "Fast upload off";
        },
        [this] { return uiPrefs_.fastUpload; },
        "Experimental. While you sculpt, the changed part of the mesh goes to the graphics card through memory both "
        "can see, and the card copies it into place itself, instead of the driver copying it during the frame. The "
        "sculpt and the view are exactly the same either way; needs a driver with buffer storage (OpenGL 4.4).");
    add("perf.draft_strokes", "Draft Strokes",
        [this] {
            uiPrefs_.draftStrokes = !uiPrefs_.draftStrokes;
            status_ = uiPrefs_.draftStrokes ? "Draft strokes on" : "Draft strokes off";
        },
        [this] { return uiPrefs_.draftStrokes; },
        "With Predictive Strokes: while you sculpt, the brush only moves the surface and shades the moved part from "
        "its facets; the smooth shading, the cavities and the rest are worked out once when you lift the pen. "
        "Lighter on laptops and on battery: the hardware profile turns it on there by itself (its Draft brushes "
        "setting); this turns it on everywhere. Brushes that follow the surface's direction (Inflate, the plane "
        "brushes) use its direction from the stroke's start, so the result can differ slightly from a full stroke.");
    add("perf.fast_big_brushes", "Fast Big Brushes (Experimental)",
        [this] {
            uiPrefs_.fastBigBrushes = !uiPrefs_.fastBigBrushes;
            status_ = uiPrefs_.fastBigBrushes ? "Fast big brushes on" : "Fast big brushes off";
        },
        [this] { return uiPrefs_.fastBigBrushes; },
        "Experimental. Big brushes on dense meshes: a dab that reaches more than 150,000 vertices finds its plane "
        "from a sample of them and turns the shading along with the move it makes, and the dabs waiting for a frame "
        "are placed together in one pass. Every vertex still moves by the brush itself; the exact shading follows "
        "behind the brush and when you lift the pen. Small brushes, Smooth, Layer, Inflate, Nudge, Clay Block, "
        "alphas and masked areas are placed dab by dab as before. Try it on a heavy mesh and tell us how it feels.");
    registerPerformanceProfileUiActions(); // Re-calibrate, the frame governor (PanelPerformanceProfile.cpp)
}

size_t App::sceneTrianglesWithMicro() const {
    size_t triangles = 0;
    for (int i = 0; i < doc_.partCount(); ++i)
        if (doc_.parts[size_t(i)].visible) {
            const Mesh& m = doc_.partMesh(i);
            const size_t micro = microTriangleCount(m);
            triangles += micro ? micro : m.triangleCount();
        }
    return triangles;
}

void App::openPerformancePrefs() {
    auto& open = layout_.openSubpalettes;
    if (uiPrefs_.oneSubpalette) // as a click on its header would: the other Preferences sections close
        open.erase(std::remove_if(open.begin(), open.end(), [](const std::string& o) { return o.rfind("preferences.", 0) == 0; }),
                   open.end());
    if (std::find(open.begin(), open.end(), "preferences.performance") == open.end()) open.push_back("preferences.performance");
    flashSubpalette_ = "preferences.performance";
    flashSubpaletteStart_ = ImGui::GetTime();
    if (const Action* a = actions_.find("ui.palette.preferences"); a && a->run) a->run();
}

void App::applyPerformancePrefs() { ThreadPool::shared().setSerial(!uiPrefs_.multithreading); }

int App::viewSamples() {
    const int aa = uiPrefs_.antialiasing;
    // The view moved in the last few frames (orbit, pan, zoom, snapping, framing), or is being dragged.
    const glm::mat4 view = camera_.view();
    if (view != perf_.lastView) {
        perf_.lastView = view;
        perf_.framesStill = 0;
        perf_.stillSince = ImGui::GetTime(); // (the frame clock: scripted time in tests)
    } else if (perf_.framesStill < 1000) {
        ++perf_.framesStill;
    }
    const bool moving = drag_ == Drag::Orbit || drag_ == Drag::Pan || drag_ == Drag::Zoom || perf_.framesStill < 8;
    size_t triangles = 0;
    for (int i = 0; i < doc_.partCount(); ++i)
        if (doc_.parts[size_t(i)].visible) triangles += doc_.partMesh(i).triangleCount();
    perf_.movingNow = moving;
    perf_.sceneTriangles = triangles;
    // 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;
}

// How long the view has been still and whether a stroke runs: coarse levels give way to full detail at rest
// (Renderer::coarsePreviewOnly).
void App::noteStillness() {
    renderSettings_.stillSeconds = perf_.movingNow ? 0.0 : ImGui::GetTime() - perf_.stillSince;
    renderSettings_.stroking = doc_.sculptor.strokeActive() || strokeFinishing_ || !dabQueue_.empty();
    renderer_.setStroking(renderSettings_.stroking);
}

void App::notePerformanceFrame(double syncMs) {
    perf_.lastSyncMs = syncMs;
    if (doc_.sculptor.strokeActive()) {
        perf_.strokeSyncMs += syncMs;
        ++perf_.strokeFrames;
    }
    // A Part too big for the GPU's memory isn't drawn: say so once.
    bool oom = false;
    for (int i = 0; i < doc_.partCount(); ++i) oom = oom || (doc_.parts[size_t(i)].visible && renderer_.outOfMemory(doc_.meshKey(i)));
    if (oom && !perf_.gpuOutOfMemory)
        status_ = "Not enough GPU memory to show every Part: hide some, or step down a subdivision level "
                  "(Preferences > Performance)";
    perf_.gpuOutOfMemory = oom;
}

void App::drawPerformanceSection() {
    drawPerformanceProfileSection(); // what was detected and measured, the profile, overrides (PanelPerformanceProfile.cpp)
    // --- The 3D view ---
    ImGui::TextUnformatted(tr("Antialiasing"));
    ui::HelpText("Antialiasing", nullptr,
                 "Samples per pixel in the 3D view: more smooths edges, fewer is faster on huge meshes.", kPath);
    ui::Segmented(*this, {"perf.aa_1", "perf.aa_2", "perf.aa_4", "perf.aa_8"});
    ImGui::TextUnformatted(tr("View resolution"));
    ui::HelpText("View resolution", nullptr,
                 "Draw the 3D view at a share of the window's resolution and scale it up: 75% draws about half the "
                 "pixels, 50% a quarter. For slow or integrated GPUs and big screens; Save Render stays sharp (#80).",
                 kPath);
    ui::Segmented(*this, {"perf.res_100", "perf.res_75", "perf.res_50"});
    bool fast = uiPrefs_.fastNavigation;
    if (ImGui::Checkbox(tr("Fast Navigation"), &fast)) actions_.find("perf.fast_navigation")->run();
    ui::HelpAction(*this, "perf.fast_navigation");
    if (perf_.samplesUsed > 0 && perf_.samplesUsed < uiPrefs_.antialiasing && !perf_.fastNow)
        dimText("The GPU had no room for " + std::to_string(uiPrefs_.antialiasing) + "x: using " +
                (perf_.samplesUsed == 1 ? std::string("none") : std::to_string(perf_.samplesUsed) + "x") + ".");

    bool predictive = uiPrefs_.predictiveStrokes;
    if (ImGui::Checkbox(tr("Predictive Strokes"), &predictive)) actions_.find("perf.predictive_strokes")->run();
    ui::HelpAction(*this, "perf.predictive_strokes");
    bool draft = uiPrefs_.draftStrokes;
    if (ImGui::Checkbox(tr("Draft Strokes"), &draft)) actions_.find("perf.draft_strokes")->run();
    ui::HelpAction(*this, "perf.draft_strokes");
    bool liveMove = uiPrefs_.liveMove;
    if (ImGui::Checkbox(tr("Live Move (Experimental)"), &liveMove)) actions_.find("perf.live_move")->run();
    ui::HelpAction(*this, "perf.live_move");
    bool bgPreview = uiPrefs_.backgroundPreview;
    if (ImGui::Checkbox(tr("Background Preview (Experimental)"), &bgPreview)) actions_.find("perf.background_preview")->run();
    ui::HelpAction(*this, "perf.background_preview");
    bool fastUpload = uiPrefs_.fastUpload;
    if (ImGui::Checkbox(tr("Fast Upload (Experimental)"), &fastUpload)) actions_.find("perf.fast_upload")->run();
    ui::HelpAction(*this, "perf.fast_upload");
    bool fastBig = uiPrefs_.fastBigBrushes;
    if (ImGui::Checkbox(tr("Fast Big Brushes (Experimental)"), &fastBig)) actions_.find("perf.fast_big_brushes")->run();
    ui::HelpAction(*this, "perf.fast_big_brushes");

    // --- Threads ---
    bool threads = !ThreadPool::shared().serial();
    if (ImGui::Checkbox(tr("Multithreading##perf.mt"), &threads)) actions_.find("perf.multithreading")->run();
    ui::HelpAction(*this, "perf.multithreading");
    ImGui::SameLine();
    ImGui::TextDisabled(tr("%d threads"), threads ? ThreadPool::shared().threads() : 1);

    // --- The last stroke ---
    ImGui::Spacing();
    ImGui::TextUnformatted(tr("Last stroke"));
    ui::HelpText("Last stroke", nullptr,
                 "What the last brush stroke cost, per dab (one step of the brush, all symmetry sides): finding and "
                 "moving the vertices, updating their normals and the BVH (the picking structure), and sending the "
                 "change to the GPU (per frame). Under 16 ms keeps up with a 60 Hz display.",
                 kPath);
    const SculptTimings& t = perf_.lastStroke;
    if (t.dabs == 0) {
        dimText(tr("Sculpt a stroke to see what it costs."));
    } else {
        const double d = double(t.dabs);
        const double upload = perf_.lastStrokeFrames ? perf_.lastStrokeSyncMs / perf_.lastStrokeFrames : 0.0;
        char buf[256];
        std::snprintf(buf, sizeof buf, "%llu dabs, %.0fk vertices each\nBrush %.2f ms  Normals %.2f ms  BVH %.2f ms\nGPU upload %.2f ms per frame",
                      static_cast<unsigned long long>(t.dabs), double(t.vertices) / d / 1000.0, t.kernelMs / d,
                      t.normalsMs / d, t.bvhMs / d, upload);
        ImGui::TextUnformatted(buf);
        ImGui::LogText("%s", buf);
    }

    // --- Memory ---
    ImGui::Spacing();
    ImGui::TextUnformatted(tr("Memory"));
    ui::HelpText("Memory", nullptr,
                 "What the scene holds: the meshes with their topology, the BVHs, the subdivision levels kept for "
                 "stepping between them, the undo history (Edit keeps up to 1 GB, dropping the oldest steps), painted textures "
                 "with their layers and material channels (only painted 64x64 tiles of a channel use memory), and the "
                 "GPU buffers of the visible Parts.",
                 kPath);
    const MemoryUse m = documentMemory(doc_);
    const std::string mem = "Meshes " + megabytes(m.mesh) + "  BVH " + megabytes(m.bvh) + "\nSubdivision levels " +
                            megabytes(m.levels) + "\nUndo " + megabytes(m.undo) + " of " + megabytes(doc_.undo.byteBudget) +
                            "\nTextures " + megabytes(m.textures) + " (material channels " + megabytes(m.channels) + ")" +
                            (m.paintCaches ? "\nTexture painting caches " + megabytes(m.paintCaches) : std::string()) +
                            "\nGPU buffers about " + megabytes(m.gpu);
    ImGui::TextUnformatted(mem.c_str());
    ImGui::LogText("%s", mem.c_str());
    if (perf_.gpuOutOfMemory) {
        ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(ui::color::danger));
        ImGui::TextWrapped("%s", tr("Not enough GPU memory to show every Part: hide some or step down a subdivision level."));
        ImGui::PopStyleColor();
    }
}

} // namespace sf