Skip to main content

Performance optimization plan: fix/amberlith-and-oot-rendering

Source: code review on 2026-11-30 of the 44 commits on fix/amberlith-and-oot-rendering that are not on nx2-experimental. Three reviewers each covered one area: NVN/VTX-HLE, shader recompiler and pipelines, and core video_core/Vulkan. The impact ratings below come from the initial review. Tier 1 measurements are recorded after the checklist.

  • Verified: I read the code and confirmed the finding.
  • Reported: a reviewer found it, but I have not re-checked it.

Desktop defaults to GPU accuracy High (src/common/settings.h:585). So every Settings::IsGPULevelHigh() branch applies to desktop users by default.

Tier 1: cheap, low risk, large expected gain​

  • Viewport depth range in every graphics pipeline key.
    • Where:
      • fixed_pipeline_state.cpp:317-328, dirty-tracked at :157 (from a6e78383ad).
      • Copied into RuntimeInfo at vk_pipeline_cache.cpp:379 and serialized at stage_cache.cpp:472.
    • Problem: only EmitSetFragDepth (emit_spirv_context_get_set.cpp:548) uses the range. Yet every distinct non-[0,1] range rebuilds the fragment SPIR-V and the pipeline, even for shaders that never write depth.
    • Fix: zero the field unless the fragment program writes depth (info.stores_frag_depth). The stage hashes are refreshed just before state.Refresh, around vk_pipeline_cache.cpp:1101.
    • Better fix: pass min/max as a push constant, or use VK_EXT_depth_clamp_control dynamic state where it is available.
    • The shader header identifies fragment depth writers. Other pipeline keys omit the range, including when reading existing cache records.
  • Alpha-test reference is not rounded at High accuracy.
    • Where: fixed_pipeline_state.cpp:388.
    • Problem: this reintroduces one pipeline per frame of each alpha-tested fade. The deleted comment put that at about 84% of one title's runtime pipelines.
    • Preserve the full reference as a push constant. The fragment shader compares its floating-point alpha before render-target conversion, so 1/255 rounding can change which fragments pass even for an 8-bit target.
    • Related: BlitImageHelper::DrawTexture (blit_image.cpp:859) also keys on the raw alpha_reference.
    • Deferred pending the push-constant change.
  • VRAM budget queried on every bindless draw.
    • Where: nvn_bindless.cpp:714-724.
    • Problem: each call costs 2× vkGetPhysicalDeviceMemoryProperties2 and 3× vmaGetHeapBudgets. These run before the prime_count/prime_bytes early return. While priming is paused at the VRAM budget (8 GB AMD), they run on every bindless draw indefinitely.
    • Fix:
      • Move the sub-budget early return ahead of the queries.
      • Cache budget and usage per flight.seq.
      • While paused, skip the queries until the next submission.
    • Priming samples memory lazily once per submission. It accounts for subsequent cache growth and planned uploads using the cached sample.
  • getenv per instruction.
    • Where: ampere/instruction.h:53 (LowerExtended()), called twice per ULDC (control_flow.cpp:185, :189, :1249, :1305). ResolveTensorMode is called per HMMA (control_flow.cpp:1015, translate/impl/tensor.cpp:17).
    • Analysis reads LowerExtended once per program. Tensor validation and translation share the cached environment override.

Tier 1 measurements​

  • OoT in Fast mode. The same uncapped Kokiri Forest scene averaged 47.8 FPS over 1,200 steady frames in each build (20.915 ms before and 20.923 ms after). Both runs queued 1,004 pipelines from the same warm cache at startup. Neither logged a runtime graphics pipeline build over 2 ms.
  • Mario Kart World in Fast mode with VTX-HLE. The warm baseline held about 60 FPS in the course sequence. The updated build hit repeated five-second NVN event timeouts, including on a retry that loaded 752 cached pipelines. The runs did not provide comparable frame-time or pipeline-count measurements. Neither reached bindless texture priming, so this route did not measure the effect of caching VRAM queries.
  • Accuracy. Amberlith 1.2.0 in Accurate mode matched all 868 prior results (854 passes and the same 14 failures). All 111 Ampere and memory-tracker tests and all four targeted Vulkan Amberlith and NVN bindless tests passed.

Tier 2: review of accuracy trade-offs from e723c9fa05​

  • Drop hot-page tracking for emulated GPU buffers.
    • The earlier 1.2 ms/frame estimate included once-per-frame upload reuse, which can miss CPU writes between draws. Uploading on every use preserves those writes and incurs extra copies.
    • In OoT at High accuracy with the emulated Vulkan GPU and the speed limit disabled, the last 600 gameplay frames averaged 33.54 ms (29.8 FPS) with normal tracking and 55.81 ms (17.9 FPS) with hot pages. Both runs started without compatible disk pipelines. Frame captures confirmed the same Kokiri Forest scene.
    • A separate emulated GPU test reported a drop from about 52 FPS to 30 FPS or lower with hot pages enabled. Removed the experiment, including the EDEN_NX2_HOT_PAGES switch. Uploads restore normal tracking even for repeatedly written pages.
  • Keep synchronous readback for GPU-modified textures at High accuracy.
    • texture_cache.h waits when it finds a downloadable GPU-modified image. Compute writes, DMA, and aliases can leave such images dirty without binding them as render targets.
    • forced_flushed is a policy flag. It can be set before a download completes and can outlive a later write. BindRenderTarget queues preemptive downloads on binding changes, so testing the current bindings cannot establish that guest memory contains the latest contents.
    • A safe asynchronous path needs to prove that the relevant image generation has been copied back, including every overlapping image that contributes bytes to the read.
  • Defer GPU-side comparison of pending reports.
    • HostConditionalRenderingCompareValues waits for pending host reports and synchronizes buffer-cache writes before Maxwell's CPU comparison. A pending report may have no corresponding buffer-cache dirty range.
    • The existing Vulkan resolve shader compares two 64-bit operands at offsets 0 and 16 of one buffer and emits a 32-bit predicate. The query lookup maps the operands separately. The GPU path needs proven mappings and report widths, ordered writes from both caches, and valid storage for the predicate. Report rewrites, invalidated reports, short reports, and drivers that skip GPU report publication also need coverage before replacing the fallback.

OoT at 60 FPS on the emulated GPU​

The uncapped Fast-mode Kokiri Forest run at 1× resolution averaged 21.09 ms (47.4 FPS) over 900 steady frames on a Ryzen 7 9800X3D and RTX 4070 SUPER. It used the emulated Vulkan GPU, Default fence behavior, and no frame generation. The median of the one-second present p90s was 23.07 ms. Reaching a 16.67 ms average requires saving 4.42 ms per frame. Stable 60 FPS also requires reducing the tail.

The back thread used 18.18 ms of CPU time per frame and the front used 12.29 ms. Front and back overlap. The present fence returned as soon as the back thread completed the last list. The graphics card reported 57% median device-wide utilization (54–60% in the selected window). Both runs queued 1,040 disk pipelines at startup and the steady windows contained no slow runtime builds. These measurements put emulated GPU command processing on the critical path in this scene.

The detailed runs with EDEN_NX2_GPU_PROFILE=1 and EDEN_NX2_SAMPLER=1 averaged 36.86 ms. The timers materially changed throughput. Use their counts and zone rankings as leads and collect benchmark times with both disabled. The back profile processed about 4.5 million ring entries and 106,000 draws per second. Its largest named zones were ring replay and engine methods. Buffer setup, handle reads and image-view resolution also accounted for substantial time. The front spent much of its wall time waiting at semaphore acquires, which overlaps the back's work.

  1. Start with command replay. Instrument ring batches and method IDs with per-window counters. GpuSplit::BackLoop decodes commands and checks for pending waits and hooks between entries. Extend existing ordered state and constant-buffer batching to cover a frequent sequence identified by the counters. Preserve draw begin/end, shadow registers, upload offsets, and the publication points used by fences and semaphore waits. Compare the same guest command stream in verification mode before using the fast path.
  2. Measure draw preparation. Count which geometry bindings, uniform uploads, and texture handle groups repeat across draws. GraphicsPipeline::ConfigureImpl already reuses descriptor payloads after preparing them. The opportunity is to avoid repeated preparation when the inputs are provably current. Track mapping and write generations, preserve per-draw side effects, and cover same-frame CPU and GPU writes before reusing a result.
  3. Check the remaining synchronization and GPU cost. Break down why Puller still drains the back for semaphore acquires. Extend the existing writer proofs only for cases those counters show are common. The current frame fence protects OoT from the guest overwriting data that the back thread still reads. Earlier-frame release caused one-frame flashes. If host GPU work becomes limiting, use GPU timestamps on the heavy passes, including the native anti-aliasing pass.

Use the same save, camera, Fast settings, and warmed route for each A/B. Compare real presents, frame-time tails, and back-thread CPU time. Check Amberlith and repeat a camera pan or scene transition in OoT to catch temporary rendering errors. The NVN mirror-pool and staging work applies to VTX-HLE.

Constant-buffer replay experiment​

EDEN_NX2_REPLAY_STATS=1 counts replay entries and methods every ten seconds without timing individual calls. In steady Kokiri Forest gameplay the back thread replayed 6.2–6.4 million constant-buffer groups per window, averaging 1.9 words each. It also ran about 15 million groups of non-executable register writes per window.

The revised constant-buffer path reads existing batches directly from the ring. It removes the two temporary arrays used to unpack methods and arguments and preserves the same batch boundaries and per-word fallbacks. In a matched A/B with the counters off, 1,200 steady frames averaged 20.74 ms before and 20.09 ms after. GPUBack CPU time averaged 17.59 ms before and 17.60 ms after. A slow window in the baseline contributed substantially to the frame-time difference. This pair did not establish a replay speedup. Profile the more frequent non-executable register runs before extending the optimization.

Non-executable register runs​

Extending dirty-flag coalescing to non-contiguous register runs left GPUBack CPU time effectively unchanged. The experiment accumulated duplicate dirty flags when no draw was pending and used the existing per-write path when a deferred draw could observe intermediate state. Four runs of the same binary on the warmed Kokiri Forest route used emulated GPU, Fast accuracy, GPU split mode 2, native resolution, uncapped presents and frame generation off. Each run contributed 900 steady frames.

Run orderExisting replayCoalesced replayGPUBack CPU, existing / coalesced
Existing first48.79 FPS47.54 FPS18.35 / 18.38 ms
Coalesced first48.24 FPS48.76 FPS17.78 / 17.79 ms
Pooled48.51 FPS48.15 FPS18.07 / 18.09 ms

On emulated GPU in Accurate mode, all 868 Amberlith case results matched the ordered-batch baseline, with 854 passes and the same 14 failures. The fast path was removed because it did not reduce GPUBack time in OoT. The replay tests now cover both ring encodings, pipeline dirty state, and deferred draw ordering.

Measure draw preparation next. In GraphicsPipeline::ConfigureImpl, count how many handle reads revisit the same GPU page across stages and draws. If reuse is high enough, measure keeping page translations across draws while validating the memory manager and map serial and reading fresh handle values each time.

Lichii-inspired draw and synchronization trials​

The Kokiri Forest A/Bs used Fast, emulated GPU split mode 2, default fences, 1× resolution and uncapped real presents. Each arm used the same saved scene and warm shader cache, and contributed 900 steady frames after discarding its first gameplay window. The p90 column is the median of the one-second present p90s.

TrialBaseline FPSTrial FPSGPUBack CPU, baseline / trialPresent p90, baseline / trial
Reuse direct sampled texture bindings48.4447.0117.68 / 18.12 ms22.45 / 22.95 ms
Check unresolved greater-or-equal acquires on GPUBack49.8747.4117.34 / 18.24 ms21.90 / 23.18 ms
Retain learned preflush marks49.8748.9017.34 / 17.43 ms21.90 / 22.39 ms
  • EDEN_NX2_SAMPLED_BINDINGS=1 reuses resolved views and samplers for direct sampled handles. It checks the current handle and the exact TIC/TSC bytes, and falls back on remaps, view invalidation, or images that still need preparation. verify runs the full path and logs differences. The draft uses the exact-byte approach in Lichii's sampled texture memo.
  • EDEN_NX2_DEFER_ACQUIRE=1 parks the waiting channel and checks the value at its original ring position on the back. This measures the cost of deferring the drain with Eglantine's existing writer tracking. Lichii's QMD view additionally reconstructs compute releases on the front and can let the channel proceed immediately when the value is proven.
  • EDEN_NX2_READBACK_STATS=1 measures reactive readback waits. The sampled steady baseline spent 2.1 ms of guest wait and 1.5 ms in synchronous GPU flushes per second. Keeping marks with EDEN_NX2_PERF_OFF=preflush_aging reduced the sampled flush time to 0.9 ms per second, with similar frame times. That leaves little room for Lichii's asynchronous readback to recover in this specific scene.

The two drafts are opt-in. The timings give priority to reuse that avoids work earlier in draw preparation, such as a write-tracked delta that can skip rereading the descriptor records.

The final OoT verification run logged over 680,000 binding hits with matching view and sampler IDs. Accurate Amberlith with sampled binding reuse enabled matched all 868 reference cases, with 854 passes and the same 14 failures. All 141 targeted unit tests passed, including descriptor-table invalidation and GPU split write tracking.

Tier 3: NVN hot paths (mostly MKW)​

  • Raw-global draws re-check whole mirror pools on every draw.
    • Where: nvn_draw_descriptors.cpp:2221-2230 (from 47fc62888e), plus whole pools pushed to UploadRanges at :2326.
    • Problem: each check re-snapshots gpu_dirty under dirty_mutex.
    • Fix:
      • Cache a per-pool "clean" result keyed on (flight.seq, cpu_write_gen, mirror_raw_write_epoch, gpu_dirty gen).
      • Break out of the per-range loop at :2212 once need is true.
    • Status: Verified that the loop exists; the cost is Reported.
  • Bulk SyncSparse and giant untile wait on the GPU after every 32 MiB chunk.
    • Where: nvn_exec.cpp:3151-3320 (the FlushAndWait at :3318) and :4052-4190. A fresh 32 MiB host buffer is also allocated on each call.
    • Fix:
      • Alternate between two persistent staging buffers.
      • Wait only on the signal from two chunks back.
      • Put the final chunk on flight.keepalive.
    • Watch for host-visible heap pressure, which is why the flush was added.
    • Status: Verified that FlushAndWait is called after every chunk.
  • TryCopyMirrorRangeToArena does costly checks before the cheap one.
    • Where: nvn_draw.cpp:2822-2832.
    • Fix: test MirrorNeedsUpload first, and carry its result into plan.ranges so PrepareOutsidePass doesn't recompute it.
    • Status: Reported.
  • MirrorNeedsUpload re-arms pages one at a time.
    • Where: nvn_exec.cpp:1702. Each page takes read_trap_mutex and does one mprotect.
    • Fix: arm contiguous runs in one call.
    • Status: Reported.
  • O(n²) overlap check in UploadRanges.
    • Where: nvn_exec.cpp:1898-1915.
    • Fix: sort by (pool, begin) and compare only neighbours.
    • Status: Reported.
  • Counter-report checks now also run outside passes, including every compute dispatch.
    • Where: nvn_draw_descriptors.cpp:2127-2146. The reports_begin/reports_end filter mixes offsets from different pools.
    • Fix: keep the bounds per pool.
    • Status: Reported.

Tier 4: smaller wins​

  • Rectangle normalization on every graphics Color2D sample.
    • Where: emit_spirv_image.cpp:502-518, enabled by runtime_rectangle_sampling = true in vk_pipeline_cache.cpp:659 and :757.
    • Problem: every sample pays for a size query, a divide and a select.
    • Fix: branch on the push-constant bit, or emit the check only when the texture type is unknown or bindless.
    • Status: Verified.
  • use_array_instance_id in the pipeline key.
    • Where: fixed_pipeline_state.h:245, vk_pipeline_cache.cpp:1086-1102, draw_manager.cpp:127-138.
    • Problem: the bit flips between the first and later instances, so each pipeline is built twice and the state refresh runs again.
    • Fix: mask it when the vertex shader doesn't read InstanceId, or move it to a push constant.
    • Status: Reported.
  • Unused key fields.
    • sample_mask[0] is set for single-sample targets; force it to ~0 there.
    • default_tessellation_levels holds raw floats (fixed_pipeline_state.cpp:280); use a push or specialization constant.
    • Status: Reported.
  • Indexed quads with primitive restart run QuadIndexedPass::Assemble and then discard its output in favour of CPU-generated indices.
    • Where: vk_rasterizer.cpp:1640-1711 and :1884.
    • Fix: skip the assembly, or handle restart in vulkan_quad_indexed.comp.
    • Status: Reported.
  • Dynamic states recorded on every draw without change tracking.
    • SetDepthClampRangeEXT at vk_rasterizer.cpp:4060-4075.
    • SetPrimitiveRestartIndexEXT at :1329-1347.
    • Status: Reported.
  • AccelerateDMA::BufferCopy gives up whenever any image overlaps the destination.
    • Where: vk_rasterizer.cpp:3997 and texture_cache.h:2318-2339.
    • Fix: fall back only for GPU-modified images that the copy does not fully cover.
    • Status: Reported.
  • Shader passes.
    • ValueNumberingPass runs twice (maxwell/translate_program.cpp:451, :460), and each run rebuilds the dominator tree and runs IdentityRemovalPass. Reuse the tree, reserve the maps, and run IdentityRemovalPass once.
    • The trivial-phi fixpoint in SsaRewritePass is O(phis²) (ssa_rewrite_pass.cpp:520-561); replace it with a worklist.
    • Status: Reported.
  • JIT: FRSQRTE on the default-accuracy AVX path.
    • Where: emit_x64_vector_floating_point.cpp:1761-1771.
    • Problem: it does stmxcsr/ldmxcsr on every execution. The F16C fast paths are also disabled whenever FPCR.DN is set.
    • Status: Reported.
  • Miscellaneous.
    • Diagnostic mutex plus std::set on hot paths (nvn_draw_descriptors.cpp:2371, nvn_exec.cpp:5286).
    • shared_ptr returned by value per dispatch (shader_cache.cpp:270-290, :354-372).
    • ComputePipelineLayoutCache::Get holds its lock while creating layouts (vk_descriptor_pool.h:104-116).
    • NativeProgramKey hashed three times (shader_environment.cpp:604, :611, :632).
    • The HintCold page walk runs on the render thread (hle_runtime.cpp:144).
    • SetDescriptorSlot adds and releases a pool ref on unchanged slots (recorder.cpp:1492).
    • Status: Reported.

Order once accuracy work is done​

  1. Tier 1. Then count runtime pipeline builds before and after, in OoT and MKW.
  2. Keep normal page tracking. Revisit GPU-side report comparison if a profile shows material time in pending-report waits.
  3. The NVN mirror-pool cache and staging reuse, measured in MKW.
  4. Tier 4 as time allows.