Skip to content

ReStreet: FIFA Street (2012) recompiled for Windows PC, with online play, a launcher with friends, chat and rooms. Bring your own game.

441 KB
Raw Blame
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 9b3cdf5..51cf584 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -28,7 +28,7 @@ if(REXGLUE_ENABLE_TRACY)
     add_compile_definitions($<$<NOT:$<CONFIG:Release>>:REXGLUE_ENABLE_PROFILING>)
 endif()
 if(REXGLUE_ENABLE_PERF_COUNTERS)
-    add_compile_definitions($<$<NOT:$<CONFIG:Release>>:REXGLUE_ENABLE_PERF_COUNTERS>)
+    add_compile_definitions(REXGLUE_ENABLE_PERF_COUNTERS)
 endif()
 
 # Graphics backend selection
@@ -223,9 +223,11 @@ configure_file(
 )
 
 # Output directories (multi-config appends /<Config>/ automatically)
-set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${REXGLUE_ROOT}/out/${REX_PLATFORM}")
-set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${REXGLUE_ROOT}/out/${REX_PLATFORM}")
-set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${REXGLUE_ROOT}/out/${REX_PLATFORM}")
+set(REXGLUE_OUTPUT_DIRECTORY "${REXGLUE_ROOT}/out/${REX_PLATFORM}" CACHE PATH
+    "Runtime and library output directory")
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${REXGLUE_OUTPUT_DIRECTORY}")
+set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${REXGLUE_OUTPUT_DIRECTORY}")
+set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${REXGLUE_OUTPUT_DIRECTORY}")
 
 # Sanitizer support for debugging memory corruption and undefined behavior
 if(REXGLUE_ENABLE_SANITIZERS)
diff --git a/include/rex/graphics/command_processor.h b/include/rex/graphics/command_processor.h
index da8e432..5ba6484 100644
--- a/include/rex/graphics/command_processor.h
+++ b/include/rex/graphics/command_processor.h
@@ -75,6 +75,7 @@ enum class GammaRampType {
 
 class CommandProcessor {
  public:
+  memory::Memory& guest_memory() const { return *memory_; }
   enum class SwapPostEffect {
     kNone,
     kFxaa,
@@ -230,6 +231,38 @@ class CommandProcessor {
   // Shared memexport readback enable state with backend legacy-flag override support.
   bool IsReadbackMemexportEnabled(bool legacy_backend_flag) const;
 
+  // Adaptive "some" readback. `some` copies a resolve into guest memory only once per range, so that
+  // copy goes stale. When the guest later writes to pages overlapping such a range, shared memory
+  // re-uploads those pages from the stale copy over the newer GPU data, which shows up as garbage.
+  // Ranges that see such invalidations are refreshed on every resolve (like `fast`) for a while;
+  // the rest stay cheap.
+  struct SomeDecision {
+    bool refresh = false;  // copy this resolve into guest memory
+    bool sync = false;     // the copy slots are older than one frame: read the just-written one
+  };
+  // Render thread: counts one resolve of the range and decides whether to copy it into guest memory.
+  SomeDecision DecideSomeRefresh(uint64_t key, uint32_t address, uint32_t length, uint64_t frame);
+  void NoteSomeRangeSkipped(uint64_t key);
+  void NoteSomeRangeRefreshed(uint64_t key);
+  // Guest thread (called from the shared memory invalidation callback).
+  void OnGuestInvalidatedRange(uint32_t start, uint32_t length);
+
+  struct SomeRangeInfo {
+    uint32_t address = 0, length = 0;
+    uint32_t calls = 0, skipped = 0, refreshed = 0, hits = 0;
+    uint64_t hot_until_frame = 0;
+    uint64_t last_frame = 0;
+    uint64_t first_frame = 0;
+    uint32_t streak = 0;  // consecutive resolves on successive frames
+    bool stale = false;
+  };
+  std::mutex some_mutex_;
+  std::unordered_map<uint64_t, SomeRangeInfo> some_ranges_;
+  std::atomic<uint64_t> some_frame_{0};
+  uint32_t some_hit_logs_ = 0;
+  uint64_t some_decisions_ = 0;
+  uint64_t some_last_table_frame_ = 0;
+
   memory::Memory* memory_ = nullptr;
   system::KernelState* kernel_state_ = nullptr;
   GraphicsSystem* graphics_system_ = nullptr;
@@ -244,6 +277,11 @@ class CommandProcessor {
   std::vector<uint32_t> me_bin_;
 
   uint32_t counter_ = 0;
+  uint64_t frame_stats_last_tick_ = 0;
+  uint64_t frame_stats_start_tick_ = 0;
+  uint64_t frame_stats_count_ = 0;
+  uint64_t frame_stats_max_ticks_ = 0;
+  uint64_t frame_stats_over_17ms_ = 0;
 
   uint32_t primary_buffer_ptr_ = 0;
   uint32_t primary_buffer_size_ = 0;
diff --git a/include/rex/graphics/d3d12/command_processor.h b/include/rex/graphics/d3d12/command_processor.h
index 96d362b..3d26e54 100644
--- a/include/rex/graphics/d3d12/command_processor.h
+++ b/include/rex/graphics/d3d12/command_processor.h
@@ -310,7 +310,7 @@ class D3D12CommandProcessor : public CommandProcessor {
   // Rechecks submission number and reclaims per-submission resources. Pass 0 as
   // the submission to await to simply check status, or pass submission_current_
   // to wait for all queue operations to be completed.
-  void CheckSubmissionFence(uint64_t await_submission);
+  void CheckSubmissionFence(uint64_t await_submission, bool short_readback_wait = false);
   // If is_guest_command is true, a new full frame - with full cleanup of
   // resources and, if needed, starting capturing - is opened if pending (as
   // opposed to simply resuming after mid-frame synchronization). Returns
@@ -325,8 +325,8 @@ class D3D12CommandProcessor : public CommandProcessor {
   // as when there are unfinished graphics pipeline creation requests that would
   // need to be fulfilled before actually submitting the command list.
   bool CanEndSubmissionImmediately() const;
-  bool AwaitAllQueueOperationsCompletion() {
-    CheckSubmissionFence(submission_current_);
+  bool AwaitAllQueueOperationsCompletion(bool short_readback_wait = false) {
+    CheckSubmissionFence(submission_current_, short_readback_wait);
     return submission_completed_ + 1 >= submission_current_;
   }
   void LogDeviceRemovalDiagnostics(ID3D12Device* device, HRESULT reason);
@@ -378,6 +378,7 @@ class D3D12CommandProcessor : public CommandProcessor {
     void* mapped_data[2] = {nullptr, nullptr};
     uint64_t submission_written[2] = {0, 0};
     uint32_t written_size[2] = {0, 0};
+    std::vector<std::pair<uint32_t, uint32_t>> memexport_ranges[2];
     uint32_t current_index = 0;
     uint64_t last_used_frame = 0;
   };
@@ -603,6 +604,7 @@ class D3D12CommandProcessor : public CommandProcessor {
     uint32_t pixel_size_log2;
     uint32_t tile_count;
     uint32_t half_pixel_offset;
+    uint32_t average;  // per-channel block average (8:8:8:8 color)
   };
   enum class ResolveDownscaleRootParameter : UINT {
     kConstants,
@@ -615,6 +617,12 @@ class D3D12CommandProcessor : public CommandProcessor {
   Microsoft::WRL::ComPtr<ID3D12PipelineState> resolve_downscale_pipeline_;
   Microsoft::WRL::ComPtr<ID3D12Resource> resolve_downscale_buffer_;
   uint32_t resolve_downscale_buffer_size_ = 0;
+  // Diagnostic timestamps are sampled only with full synchronous readback.
+  Microsoft::WRL::ComPtr<ID3D12QueryHeap> resolve_timing_query_heap_;
+  Microsoft::WRL::ComPtr<ID3D12Resource> resolve_timing_readback_;
+  uint64_t resolve_timing_frequency_ = 0;
+  uint64_t resolve_timing_sample_counter_ = 0;
+  uint64_t resolve_timing_submission_ = 0;
 
   // PWL gamma ramp can result in values with more precision than 10bpc. Though
   // those sub-10bpc bits don't have any noticeable visual effect, so normally
diff --git a/include/rex/graphics/d3d12/texture_cache.h b/include/rex/graphics/d3d12/texture_cache.h
index 4d845c7..6986efc 100644
--- a/include/rex/graphics/d3d12/texture_cache.h
+++ b/include/rex/graphics/d3d12/texture_cache.h
@@ -14,6 +14,7 @@
 #include <array>
 #include <functional>
 #include <memory>
+#include <string>
 #include <unordered_map>
 #include <utility>
 #include <vector>
@@ -111,7 +112,8 @@ class D3D12TextureCache final : public TextureCache {
                                  size_t host_shader_binding_count) const;
   void WriteActiveTextureBindfulSRV(const D3D12Shader::TextureBinding& host_shader_binding,
                                     D3D12_CPU_DESCRIPTOR_HANDLE handle);
-  uint32_t GetActiveTextureBindlessSRVIndex(const D3D12Shader::TextureBinding& host_shader_binding);
+  uint32_t GetActiveTextureBindlessSRVIndex(const D3D12Shader::TextureBinding& host_shader_binding,
+                                          uint64_t shader_hash = 0);
 
   SamplerParameters GetSamplerParameters(const D3D12Shader::SamplerBinding& binding) const;
   void WriteSampler(SamplerParameters parameters, D3D12_CPU_DESCRIPTOR_HANDLE handle) const;
@@ -490,6 +492,15 @@ class D3D12TextureCache final : public TextureCache {
   };
   uint8_t unsupported_format_features_used_[64];
 
+  struct TextureMemoryDiagnostic {
+    Microsoft::WRL::ComPtr<ID3D12Resource> readback;
+    std::vector<uint8_t> cpu_bytes;
+    std::string path;
+    uint64_t submission;
+    uint32_t base;
+  };
+  std::vector<TextureMemoryDiagnostic> texture_memory_diagnostics_;
+
   // The tiled buffer for resolved data with resolution scaling.
   // Because on Direct3D 12 (at least on Windows 10 2004) typed SRV or UAV
   // creation fails for offsets above 4 GB, a single tiled 4.5 GB buffer can't
diff --git a/include/rex/graphics/flags.h b/include/rex/graphics/flags.h
index 2cf24c4..86fe5a1 100644
--- a/include/rex/graphics/flags.h
+++ b/include/rex/graphics/flags.h
@@ -15,6 +15,7 @@
 
 // GPU Core
 REXCVAR_DECLARE(bool, vsync);
+REXCVAR_DECLARE(bool, true_vsync);
 REXCVAR_DECLARE(bool, clear_memory_page_state);
 REXCVAR_DECLARE(bool, half_pixel_offset);
 REXCVAR_DECLARE(bool, async_shader_compilation);
@@ -27,6 +28,7 @@ REXCVAR_DECLARE(bool, resolve_resolution_scale_fill_half_pixel_offset);
 REXCVAR_DECLARE(bool, draw_resolution_scaled_texture_offsets);
 REXCVAR_DECLARE(std::string, readback_resolve);
 REXCVAR_DECLARE(bool, readback_resolve_half_pixel_offset);
+REXCVAR_DECLARE(bool, readback_resolve_average_color);
 REXCVAR_DECLARE(bool, readback_memexport);
 REXCVAR_DECLARE(bool, readback_memexport_fast);
 REXCVAR_DECLARE(bool, occlusion_query_enable);
diff --git a/include/rex/graphics/pipeline/shader/dxbc_translator.h b/include/rex/graphics/pipeline/shader/dxbc_translator.h
index 3b0fd61..be2c144 100644
--- a/include/rex/graphics/pipeline/shader/dxbc_translator.h
+++ b/include/rex/graphics/pipeline/shader/dxbc_translator.h
@@ -111,7 +111,7 @@ class DxbcShaderTranslator : public ShaderTranslator {
     // If anything in this is structure is changed in a way not compatible with
     // the previous layout, invalidate the pipeline storages by increasing this
     // version number (0xYYYYMMDD)!
-    static constexpr uint32_t kVersion = 0x20260226;
+    static constexpr uint32_t kVersion = 0x20260930;
 
     enum class DepthStencilMode : uint32_t {
       kNoModifiers,
diff --git a/include/rex/graphics/shared_memory.h b/include/rex/graphics/shared_memory.h
index 4d85a2b..4a57875 100644
--- a/include/rex/graphics/shared_memory.h
+++ b/include/rex/graphics/shared_memory.h
@@ -10,6 +10,7 @@
  * @modified    Tom Clay, 2026 - Adapted for ReXGlue runtime
  */
 
+#include <functional>
 #include <cstdint>
 #include <mutex>
 #include <utility>
@@ -79,6 +80,11 @@ class SharedMemory {
   bool RequestRanges(const std::pair<uint32_t, uint32_t>* ranges, size_t count);
   bool RequestRange(uint32_t start, uint32_t length);
 
+  // Called (from guest threads) with the page range invalidated by a guest write.
+  void SetInvalidationObserver(std::function<void(uint32_t, uint32_t)> observer) {
+    invalidation_observer_ = std::move(observer);
+  }
+
   // Marks the range and, if not exact_range, potentially its surroundings
   // (to up to the first GPU-written page, as an access violation exception
   // count optimization) as modified by the CPU, also invalidating GPU-written
@@ -154,6 +160,7 @@ class SharedMemory {
   uint32_t host_gpu_memory_sparse_allocations_ = 0;
   uint32_t host_gpu_memory_sparse_used_bytes_ = 0;
 
+  std::function<void(uint32_t, uint32_t)> invalidation_observer_;
   void* memory_invalidation_callback_handle_ = nullptr;
   void* memory_data_provider_handle_ = nullptr;
 
diff --git a/include/rex/graphics/vulkan/command_processor.h b/include/rex/graphics/vulkan/command_processor.h
index 696ff48..555a5e3 100644
--- a/include/rex/graphics/vulkan/command_processor.h
+++ b/include/rex/graphics/vulkan/command_processor.h
@@ -149,6 +149,7 @@ class VulkanCommandProcessor : public CommandProcessor {
     assert_true(submission_open_);
     return deferred_command_buffer_;
   }
+  bool IsResolveReadbackEnabled() const;
 
   bool submission_open() const { return submission_open_; }
   uint64_t GetCurrentSubmission() const {
@@ -271,7 +272,14 @@ class VulkanCommandProcessor : public CommandProcessor {
   struct CommandBuffer {
     VkCommandPool pool;
     VkCommandBuffer buffer;
+    VkQueryPool timing_queries = VK_NULL_HANDLE;
+    bool timing_pending = false;
   };
+  double timing_gpu_ms_ = 0, timing_submit_ms_ = 0, timing_wait_ms_ = 0;
+  uint64_t timing_samples_ = 0;
+  double timing_interval_start_ms_ = 0;
+  float timing_timestamp_period_ = 0;
+  uint64_t timing_timestamp_mask_ = 0;
 
   struct SparseBufferBind {
     VkBuffer buffer;
@@ -406,7 +414,7 @@ class VulkanCommandProcessor : public CommandProcessor {
   // Rechecks submission number and reclaims per-submission resources. Pass 0 as
   // the submission to await to simply check status, or pass
   // GetCurrentSubmission() to wait for all queue operations to be completed.
-  void CheckSubmissionFenceAndDeviceLoss(uint64_t await_submission);
+  void CheckSubmissionFenceAndDeviceLoss(uint64_t await_submission, const char* reason = "other");
   // If is_guest_command is true, a new full frame - with full cleanup of
   // resources and, if needed, starting capturing - is opened if pending (as
   // opposed to simply resuming after mid-frame synchronization). Returns
@@ -416,8 +424,8 @@ class VulkanCommandProcessor : public CommandProcessor {
   // clearing and stopping capturing. Returns whether the submission was done
   // successfully, if it has failed, leaves it open.
   bool EndSubmission(bool is_swap);
-  bool AwaitAllQueueOperationsCompletion() {
-    CheckSubmissionFenceAndDeviceLoss(GetCurrentSubmission());
+  bool AwaitAllQueueOperationsCompletion(const char* reason = "other") {
+    CheckSubmissionFenceAndDeviceLoss(GetCurrentSubmission(), reason);
     return !submission_open_ && submissions_in_flight_fences_.empty();
   }
   // Keep primary-buffer-end submit behavior aligned with D3D12: only submit
@@ -480,6 +488,7 @@ class VulkanCommandProcessor : public CommandProcessor {
     uint32_t tile_count;
     uint32_t source_offset_bytes;
     uint32_t half_pixel_offset;
+    uint32_t average;  // per-channel block average (8:8:8:8 color)
   };
   bool EnsureSwapFxaaSourceImage(uint32_t width, uint32_t height);
   void DestroySwapFxaaSourceImage();
diff --git a/include/rex/input/guide_capture.h b/include/rex/input/guide_capture.h
new file mode 100644
index 0000000..4d908d5
--- /dev/null
+++ b/include/rex/input/guide_capture.h
@@ -0,0 +1,18 @@
+#pragma once
+// While the (re-created) Xbox Guide is open it owns the pad: the title sees a
+// neutral controller and the guide receives the button presses instead.
+
+#include <cstdint>
+
+namespace rex::input {
+
+void SetGuideCapture(bool capture);
+bool GuideCaptureActive();
+// Buttons (XINPUT_GAMEPAD_* bits) newly pressed since the last call.
+uint32_t TakeGuidePresses();
+
+// While watching, a Back button press (edge) is recorded for TakeBackPress().
+void SetBackWatch(bool watch);
+bool TakeBackPress();
+
+}  // namespace rex::input
diff --git a/include/rex/input/input_system.h b/include/rex/input/input_system.h
index 1cb3faa..5529d0c 100644
--- a/include/rex/input/input_system.h
+++ b/include/rex/input/input_system.h
@@ -11,6 +11,7 @@
  */
 
 #include <memory>
+#include <mutex>
 #include <vector>
 
 #include <rex/input/device_assignment.h>
@@ -60,6 +61,8 @@ class InputSystem : public system::IInputSystem {
 
   std::unique_ptr<DeviceAssignment> assignment_;
   ActiveDeviceTracker active_devices_;
+  // Guest threads may poll capabilities, state and vibration concurrently.
+  std::mutex devices_mutex_;
 
   // Ordered by ordinal. Ordinals are never recycled, so unplugging pad one
   // does not renumber pad two.
diff --git a/include/rex/perf/counter.h b/include/rex/perf/counter.h
index b3947e0..21202c7 100644
--- a/include/rex/perf/counter.h
+++ b/include/rex/perf/counter.h
@@ -49,6 +49,8 @@ enum class CounterId : uint16_t {
   kPipelineCacheHits,
   kPipelineCacheMisses,
 
+  kFrameNumber,  // Guest swaps, monotonically increasing within a session
+
   kCount  // sentinel -- must be last
 };
 
diff --git a/include/rex/ppc/gprlr_inline.h b/include/rex/ppc/gprlr_inline.h
new file mode 100644
index 0000000..4506ec2
--- /dev/null
+++ b/include/rex/ppc/gprlr_inline.h
@@ -0,0 +1,72 @@
+/**
+ * @file        gprlr_inline.h
+ * @brief       Inline copies of the compiler's GPR/LR save and restore helpers
+ *
+ * The Xbox 360 compiler calls __savegprlr_N / __restgprlr_N (N = 14..31) from almost every
+ * non-leaf function. Recompiled as ordinary functions they are out-of-line weak calls carrying a
+ * PPCContext reference. Codegen emits calls to these always_inline copies instead; the bodies are
+ * the exact ones the helpers are recompiled to (r1 - 8 * (32 - i) - 8 for each register i, then the
+ * link register word at r1 - 8).
+ *
+ * Requires REX_LOAD_U32/U64, REX_STORE_U32/U64 and PPCContext from the module's pch.
+ */
+#pragma once
+
+#define REX_INL_SV(i) REX_STORE_U64(ctx.r1.u32 + (-8 * (32 - i) - 8), ctx.r##i.u64);
+#define REX_INL_RS(i) ctx.r##i.u64 = REX_LOAD_U64(ctx.r1.u32 + (-8 * (32 - i) - 8));
+
+#define REX_INL_SAVE_31 REX_INL_SV(31)
+#define REX_INL_SAVE_30 REX_INL_SV(30) REX_INL_SAVE_31
+#define REX_INL_SAVE_29 REX_INL_SV(29) REX_INL_SAVE_30
+#define REX_INL_SAVE_28 REX_INL_SV(28) REX_INL_SAVE_29
+#define REX_INL_SAVE_27 REX_INL_SV(27) REX_INL_SAVE_28
+#define REX_INL_SAVE_26 REX_INL_SV(26) REX_INL_SAVE_27
+#define REX_INL_SAVE_25 REX_INL_SV(25) REX_INL_SAVE_26
+#define REX_INL_SAVE_24 REX_INL_SV(24) REX_INL_SAVE_25
+#define REX_INL_SAVE_23 REX_INL_SV(23) REX_INL_SAVE_24
+#define REX_INL_SAVE_22 REX_INL_SV(22) REX_INL_SAVE_23
+#define REX_INL_SAVE_21 REX_INL_SV(21) REX_INL_SAVE_22
+#define REX_INL_SAVE_20 REX_INL_SV(20) REX_INL_SAVE_21
+#define REX_INL_SAVE_19 REX_INL_SV(19) REX_INL_SAVE_20
+#define REX_INL_SAVE_18 REX_INL_SV(18) REX_INL_SAVE_19
+#define REX_INL_SAVE_17 REX_INL_SV(17) REX_INL_SAVE_18
+#define REX_INL_SAVE_16 REX_INL_SV(16) REX_INL_SAVE_17
+#define REX_INL_SAVE_15 REX_INL_SV(15) REX_INL_SAVE_16
+#define REX_INL_SAVE_14 REX_INL_SV(14) REX_INL_SAVE_15
+
+#define REX_INL_REST_31 REX_INL_RS(31)
+#define REX_INL_REST_30 REX_INL_RS(30) REX_INL_REST_31
+#define REX_INL_REST_29 REX_INL_RS(29) REX_INL_REST_30
+#define REX_INL_REST_28 REX_INL_RS(28) REX_INL_REST_29
+#define REX_INL_REST_27 REX_INL_RS(27) REX_INL_REST_28
+#define REX_INL_REST_26 REX_INL_RS(26) REX_INL_REST_27
+#define REX_INL_REST_25 REX_INL_RS(25) REX_INL_REST_26
+#define REX_INL_REST_24 REX_INL_RS(24) REX_INL_REST_25
+#define REX_INL_REST_23 REX_INL_RS(23) REX_INL_REST_24
+#define REX_INL_REST_22 REX_INL_RS(22) REX_INL_REST_23
+#define REX_INL_REST_21 REX_INL_RS(21) REX_INL_REST_22
+#define REX_INL_REST_20 REX_INL_RS(20) REX_INL_REST_21
+#define REX_INL_REST_19 REX_INL_RS(19) REX_INL_REST_20
+#define REX_INL_REST_18 REX_INL_RS(18) REX_INL_REST_19
+#define REX_INL_REST_17 REX_INL_RS(17) REX_INL_REST_18
+#define REX_INL_REST_16 REX_INL_RS(16) REX_INL_REST_17
+#define REX_INL_REST_15 REX_INL_RS(15) REX_INL_REST_16
+#define REX_INL_REST_14 REX_INL_RS(14) REX_INL_REST_15
+
+#define REX_INL_GPRLR(N)                                                                      \
+  static inline __attribute__((always_inline)) void rex_inl_savegprlr_##N(                   \
+      PPCContext& __restrict ctx, uint8_t* base) {                                           \
+    REX_INL_SAVE_##N                                                                         \
+    REX_STORE_U32(ctx.r1.u32 + -8, ctx.r12.u32);                                             \
+  }                                                                                          \
+  static inline __attribute__((always_inline)) void rex_inl_restgprlr_##N(                   \
+      PPCContext& __restrict ctx, uint8_t* base) {                                           \
+    REX_INL_REST_##N                                                                         \
+    ctx.r12.u64 = REX_LOAD_U32(ctx.r1.u32 + -8);                                             \
+    ctx.lr = ctx.r12.u64;                                                                    \
+  }
+
+REX_INL_GPRLR(14) REX_INL_GPRLR(15) REX_INL_GPRLR(16) REX_INL_GPRLR(17) REX_INL_GPRLR(18)
+REX_INL_GPRLR(19) REX_INL_GPRLR(20) REX_INL_GPRLR(21) REX_INL_GPRLR(22) REX_INL_GPRLR(23)
+REX_INL_GPRLR(24) REX_INL_GPRLR(25) REX_INL_GPRLR(26) REX_INL_GPRLR(27) REX_INL_GPRLR(28)
+REX_INL_GPRLR(29) REX_INL_GPRLR(30) REX_INL_GPRLR(31)
diff --git a/include/rex/rex_app.h b/include/rex/rex_app.h
index 1f52480..4b169cb 100644
--- a/include/rex/rex_app.h
+++ b/include/rex/rex_app.h
@@ -134,7 +134,7 @@ class ReXApp : public ui::WindowedApp, public ui::WindowListener, public ui::Win
   /// Called from the ImGui drawer's Initialize() after the default font is
   /// registered and before the atlas is built. Override to add additional
   /// fonts via AddFontFromMemoryTTF() or similar.
-  virtual void OnConfigureFonts(ImFontAtlas* atlas) { (void)atlas; }
+  virtual void OnConfigureFonts(ImFontAtlas* atlas);
 
   /// Called from the ImGui drawer's Initialize() after the SDK defaults have
   /// been applied. `imgui_style` is the live global ImGuiStyle: patch fields,
diff --git a/include/rex/stream.h b/include/rex/stream.h
index 07eb5ea..ae8d43e 100644
--- a/include/rex/stream.h
+++ b/include/rex/stream.h
@@ -42,7 +42,8 @@ class BitStream {
   // Note: num_bits MUST be in the range 0-57 (inclusive)
   uint64_t Peek(size_t num_bits);
   uint64_t Read(size_t num_bits);
-  bool Write(uint64_t val, size_t num_bits);  // TODO(DrChat): Not tested!
+  // Returns false without modifying the stream if the write is out of bounds.
+  bool Write(uint64_t val, size_t num_bits);
 
   size_t Copy(uint8_t* dest_buffer, size_t num_bits);
 
diff --git a/include/rex/ui/d3d12/d3d12_presenter.h b/include/rex/ui/d3d12/d3d12_presenter.h
index 83d09f7..1058d82 100644
--- a/include/rex/ui/d3d12/d3d12_presenter.h
+++ b/include/rex/ui/d3d12/d3d12_presenter.h
@@ -246,11 +246,21 @@ class D3D12Presenter final : public Presenter {
         guest_output_intermediate_textures;
     UINT64 guest_output_intermediate_texture_last_usage = 0;
 
+    // True VSync: painting and presenting use their own queue, so waiting for the display refresh never
+    // holds the direct queue (and the guest's GPU readback waits behind it). Null otherwise.
+    Microsoft::WRL::ComPtr<ID3D12CommandQueue> present_queue;
+    Microsoft::WRL::ComPtr<ID3D12Fence> present_queue_direct_fence;
+    UINT64 present_queue_direct_fence_value = 0;
+
     // Connection-specific.
 
     uint32_t swap_chain_width = 0;
     uint32_t swap_chain_height = 0;
     bool swap_chain_allows_tearing = false;
+    // True VSync: the swap chain is in DXGI exclusive fullscreen at the chosen refresh rate.
+    bool swap_chain_exclusive = false;
+    // True VSync: signaled when the swap chain can take a frame without blocking (null otherwise).
+    HANDLE swap_chain_latency_waitable = nullptr;
     Microsoft::WRL::ComPtr<IDXGISwapChain3> swap_chain;
     std::array<Microsoft::WRL::ComPtr<ID3D12Resource>, kSwapChainBufferCount> swap_chain_buffers;
   };
diff --git a/include/rex/ui/guide_font.h b/include/rex/ui/guide_font.h
new file mode 100644
index 0000000..3a4c284
--- /dev/null
+++ b/include/rex/ui/guide_font.h
@@ -0,0 +1,16 @@
+#pragma once
+// Fonts of the re-created Xbox Guide / extra menu entries. They are the game's own
+// UI fonts, read from its data0.big when the ImGui atlas is built.
+
+#include <filesystem>
+
+struct ImFont;
+struct ImFontAtlas;
+
+namespace rex::ui {
+extern ImFont* g_guide_font;        // fs4_cn_bold: menu items, headings
+extern ImFont* g_guide_font_light;  // fs4_cn_regular: hint rows
+
+// Adds the game's fonts to `atlas` (no-op if the archive is missing).
+void LoadGameUiFonts(ImFontAtlas* atlas, const std::filesystem::path& game_data_root);
+}  // namespace rex::ui
diff --git a/include/rex/ui/overlay/debug_overlay.h b/include/rex/ui/overlay/debug_overlay.h
index e15e410..fa838ff 100644
--- a/include/rex/ui/overlay/debug_overlay.h
+++ b/include/rex/ui/overlay/debug_overlay.h
@@ -37,11 +37,11 @@ class DebugOverlayDialog : public ImGuiDialog {
 
  private:
   FrameStatsProvider stats_provider_;
-#ifdef REXGLUE_ENABLE_PERF_COUNTERS
   static constexpr size_t kFrameHistorySize = 120;
   std::array<float, kFrameHistorySize> frame_time_history_{};
   size_t frame_history_idx_ = 0;
-#endif
+  size_t frame_history_count_ = 0;
+  int64_t last_guest_frame_ = -1;
 };
 
 }  // namespace rex::ui
diff --git a/include/rex/ui/presenter.h b/include/rex/ui/presenter.h
index afb4a30..1cfc84f 100644
--- a/include/rex/ui/presenter.h
+++ b/include/rex/ui/presenter.h
@@ -374,6 +374,9 @@ class Presenter {
   // Requests (re)painting with the UI if there's UI to draw.
   void RequestUIPaintFromUIThread();
 
+  // Called by the guest vblank worker; false keeps the timer fallback.
+  bool WaitForMonitorVBlank(double refresh_rate_hz);
+
  protected:
   enum class PaintResult {
     kPresented,
@@ -398,6 +401,7 @@ class Presenter {
   static constexpr uint32_t kGuestOutputMailboxSize = 3;
 
   struct GuestOutputProperties {
+    uint64_t frame_sequence = 0;
     // At least any value being 0 here means the guest output is disabled for
     // this frame.
     uint32_t frontbuffer_width;
@@ -976,6 +980,7 @@ class Presenter {
   // Accessible only by refreshing, whether the last refresh contained an image
   // rather than being blank.
   bool guest_output_active_last_refresh_ = false;
+  uint64_t guest_output_frame_sequence_ = 0;
 
   // Ordered by the Z order, and then by the time of addition.
   // Note: All the iteration logic involving this Z ordering must be the same as
diff --git a/include/rex/ui/vulkan/fence_wait_timing.h b/include/rex/ui/vulkan/fence_wait_timing.h
new file mode 100644
index 0000000..97f4ba6
--- /dev/null
+++ b/include/rex/ui/vulkan/fence_wait_timing.h
@@ -0,0 +1,67 @@
+#pragma once
+
+#include <algorithm>
+#include <chrono>
+#include <rex/cvar.h>
+#include <rex/logging.h>
+
+namespace rex::ui::vulkan {
+
+// Observe existing CPU fence waits without inserting any GPU operations.
+class FenceWaitTiming {
+ public:
+  enum class Reason { Other, Resolve, Memexport, FrameReuse, ResourceReuse, Occlusion, OutputDescriptors, IntermediateImage, PaintPipeline, AcquireImage, Count };
+  FenceWaitTiming(const char* role, const void* tracker,
+                  Reason reason = Reason::Other, uint64_t fences = 1)
+      : role_(role), tracker_(tracker), reason_(reason), fences_(fences) {
+    // This diagnostic setting is selected before workers start, not hot-reloaded.
+    static thread_local const bool enabled = REXCVAR_QUERY(bool, vulkan_log_fence_waits);
+    enabled_ = enabled;
+    if (enabled_) start_ = Clock::now();
+  }
+  ~FenceWaitTiming() {
+    if (!enabled_) return;
+    const auto now = Clock::now();
+    const double ms = std::chrono::duration<double, std::milli>(now - start_).count();
+    struct Stats {
+      Clock::time_point start = Clock::now();
+      uint64_t calls = 0, over_8ms = 0, fences = 0;
+      double total = 0, maximum = 0;
+    };
+    static thread_local Stats all_stats[2][size_t(Reason::Count)];
+    const size_t role_index = role_[0] == 'g' ? 0 : 1;
+    Stats& stats = all_stats[role_index][size_t(reason_)];
+    ++stats.calls;
+    stats.fences += fences_;
+    stats.over_8ms += ms > 8.0;
+    stats.total += ms;
+    stats.maximum = std::max(stats.maximum, ms);
+    static thread_local Clock::time_point interval_start = Clock::now();
+    if (now - interval_start < std::chrono::seconds(5)) return;
+    constexpr const char* names[] = {"other", "resolve", "memexport", "frame_reuse",
+                                    "resource_reuse", "occlusion", "output_descriptors",
+                                    "intermediate_image", "paint_pipeline", "acquire_image"};
+    for (size_t role = 0; role < 2; ++role) {
+      for (size_t reason = 0; reason < size_t(Reason::Count); ++reason) {
+        Stats& entry = all_stats[role][reason];
+        if (!entry.calls) continue;
+        REXLOG_INFO("VulkanFenceWait: role={} reason={} calls={} fences={} "
+                    "total={:.3f}ms max={:.3f}ms over8ms={}",
+                    role == 0 ? "guest" : "presenter", names[reason], entry.calls,
+                    entry.fences, entry.total, entry.maximum, entry.over_8ms);
+        entry = Stats{};
+      }
+    }
+    interval_start = now;
+  }
+ private:
+  using Clock = std::chrono::steady_clock;
+  const char* role_;
+  const void* tracker_;
+  Reason reason_;
+  uint64_t fences_;
+  bool enabled_ = false;
+  Clock::time_point start_{};
+};
+
+}  // namespace rex::ui::vulkan
diff --git a/include/rex/ui/vulkan/functions/device_1_0.inc b/include/rex/ui/vulkan/functions/device_1_0.inc
index aa55a4a..ee502f0 100644
--- a/include/rex/ui/vulkan/functions/device_1_0.inc
+++ b/include/rex/ui/vulkan/functions/device_1_0.inc
@@ -25,6 +25,7 @@ XE_UI_VULKAN_FUNCTION(vkCmdEndQuery)
 XE_UI_VULKAN_FUNCTION(vkCmdPipelineBarrier)
 XE_UI_VULKAN_FUNCTION(vkCmdPushConstants)
 XE_UI_VULKAN_FUNCTION(vkCmdResetQueryPool)
+XE_UI_VULKAN_FUNCTION(vkCmdWriteTimestamp)
 XE_UI_VULKAN_FUNCTION(vkCmdSetBlendConstants)
 XE_UI_VULKAN_FUNCTION(vkCmdSetDepthBias)
 XE_UI_VULKAN_FUNCTION(vkCmdSetScissor)
@@ -71,6 +72,7 @@ XE_UI_VULKAN_FUNCTION(vkFreeMemory)
 XE_UI_VULKAN_FUNCTION(vkGetBufferMemoryRequirements)
 XE_UI_VULKAN_FUNCTION(vkGetDeviceQueue)
 XE_UI_VULKAN_FUNCTION(vkGetFenceStatus)
+XE_UI_VULKAN_FUNCTION(vkGetQueryPoolResults)
 XE_UI_VULKAN_FUNCTION(vkGetImageMemoryRequirements)
 XE_UI_VULKAN_FUNCTION(vkInvalidateMappedMemoryRanges)
 XE_UI_VULKAN_FUNCTION(vkMapMemory)
@@ -79,6 +81,7 @@ XE_UI_VULKAN_FUNCTION(vkResetDescriptorPool)
 XE_UI_VULKAN_FUNCTION(vkResetFences)
 XE_UI_VULKAN_FUNCTION(vkQueueBindSparse)
 XE_UI_VULKAN_FUNCTION(vkQueueSubmit)
+XE_UI_VULKAN_FUNCTION(vkQueueWaitIdle)
 XE_UI_VULKAN_FUNCTION(vkUnmapMemory)
 XE_UI_VULKAN_FUNCTION(vkUpdateDescriptorSets)
 XE_UI_VULKAN_FUNCTION(vkWaitForFences)
diff --git a/include/rex/ui/vulkan/presenter.h b/include/rex/ui/vulkan/presenter.h
index 56ee43b..4991869 100644
--- a/include/rex/ui/vulkan/presenter.h
+++ b/include/rex/ui/vulkan/presenter.h
@@ -281,7 +281,7 @@ class VulkanPresenter final : public Presenter {
       ~Submission();
 
       VkSemaphore acquire_semaphore() const { return acquire_semaphore_; }
-      VkSemaphore present_semaphore() const { return present_semaphore_; }
+    VkFence acquire_fence() const { return acquire_fence_; }
       VkCommandPool draw_command_pool() const { return draw_command_pool_; }
       VkCommandBuffer draw_command_buffer() const { return draw_command_buffer_; }
 
@@ -292,7 +292,7 @@ class VulkanPresenter final : public Presenter {
 
       const VulkanDevice* vulkan_device_;
       VkSemaphore acquire_semaphore_ = VK_NULL_HANDLE;
-      VkSemaphore present_semaphore_ = VK_NULL_HANDLE;
+    VkFence acquire_fence_ = VK_NULL_HANDLE;
       VkCommandPool draw_command_pool_ = VK_NULL_HANDLE;
       VkCommandBuffer draw_command_buffer_ = VK_NULL_HANDLE;
     };
@@ -415,6 +415,8 @@ class VulkanPresenter final : public Presenter {
     VkExtent2D swapchain_extent = {};
     bool swapchain_is_fifo = false;
     std::vector<VkImage> swapchain_images;
+    // Present waits are retired by reacquiring their image, not by a draw fence.
+    std::vector<VkSemaphore> swapchain_present_semaphores;
     std::vector<SwapchainFramebuffer> swapchain_framebuffers;
   };
 
diff --git a/include/rex/ui/vulkan/submission_tracker.h b/include/rex/ui/vulkan/submission_tracker.h
index 505b599..3eda4cb 100644
--- a/include/rex/ui/vulkan/submission_tracker.h
+++ b/include/rex/ui/vulkan/submission_tracker.h
@@ -17,6 +17,7 @@
 
 #include <rex/assert.h>
 #include <rex/ui/vulkan/device.h>
+#include <rex/ui/vulkan/fence_wait_timing.h>
 
 namespace rex {
 namespace ui {
@@ -104,7 +105,8 @@ class VulkanSubmissionTracker {
   // guarantees as needed (when downloading, as opposed to just destroying).
   // If false is returned, it's also not guaranteed that GetCompletedSubmission
   // will return a value >= submission_index.
-  bool AwaitSubmissionCompletion(uint64_t submission_index);
+  bool AwaitSubmissionCompletion(uint64_t submission_index,
+                                 FenceWaitTiming::Reason reason = FenceWaitTiming::Reason::Other);
   bool AwaitAllSubmissionsCompletion() {
     return AwaitSubmissionCompletion(submission_current_ - 1);
   }
diff --git a/resources/templates/codegen/_indirect_call.inja b/resources/templates/codegen/_indirect_call.inja
index d4b1830..3a33579 100644
--- a/resources/templates/codegen/_indirect_call.inja
+++ b/resources/templates/codegen/_indirect_call.inja
@@ -1,12 +1,14 @@
 //=============================================================================
 // Indirect Call Dispatch
+// Resolve through the runtime: function tables are independent of XEX images.
+// The dispatcher handles calls across all loaded modules.
 //
-// REX_LOOKUP_FUNC indexes into the per-module dispatch table at
-// IMAGE_BASE + IMAGE_SIZE. REX_CALL_INDIRECT_FUNC bounds-checks the target
-// against the caller's [REX_CODE_BASE, REX_CODE_BASE + REX_CODE_SIZE +
-// REX_THUNK_RESERVE_SIZE) range; out-of-bounds targets and in-bounds
-// unregistered slots fall back to rex::runtime::ResolveIndirectFunction,
-// which queries the global FunctionDispatcher across every loaded module.
+// Fast path: Memory::InitializeFunctionTable places the table of the module
+// loaded at code base 0x82610000 (FIFA Street's fifadllzf.xex.dll) right after
+// its image (FIFA_TABLE_FIX), where the SDK's original per-module lookup
+// expects it. Every other module has a dynamically allocated table, so it
+// keeps the dispatcher call. Out-of-range targets and empty slots also fall
+// back to the dispatcher, which is what the slow path always did.
 //=============================================================================
 
 #ifdef REXGLUE_ENABLE_PROFILING
@@ -17,22 +19,34 @@
 #endif
 
 #define REX_LOOKUP_FUNC(x, y) \
-  (*(PPCFunc**)(x + REX_IMAGE_BASE + REX_IMAGE_SIZE + (u64(u32(y) - REX_CODE_BASE) * 2)))
+  rex::runtime::ResolveIndirectFunction(static_cast<uint32_t>(y))
 
+#if REX_CODE_BASE == 0x82610000ull
 #define REX_CALL_INDIRECT_FUNC(x)                                                          \
   do {                                                                                     \
     REX_PROFILE_INDIRECT_DISPATCH();                                                       \
-    uint32_t rex_indirect_target_ = (uint32_t)(x);                                         \
-    PPCFunc* rex_indirect_func_;                                                           \
+    uint32_t rex_indirect_target_ = static_cast<uint32_t>(x);                              \
+    ctx.last_indirect_target = rex_indirect_target_;                                       \
+    PPCFunc* rex_indirect_func_ = nullptr;                                                 \
     if ((uint32_t)(rex_indirect_target_ - REX_CODE_BASE) <                                 \
         REX_CODE_SIZE + REX_THUNK_RESERVE_SIZE) [[likely]] {                               \
-      rex_indirect_func_ = REX_LOOKUP_FUNC(base, rex_indirect_target_);                    \
-    } else {                                                                               \
-      rex_indirect_func_ = nullptr;                                                        \
+      rex_indirect_func_ =                                                                 \
+          *(PPCFunc**)(base + REX_IMAGE_BASE + REX_IMAGE_SIZE +                            \
+                       (u64(rex_indirect_target_ - REX_CODE_BASE) * 2));                   \
     }                                                                                      \
     if (!rex_indirect_func_) [[unlikely]] {                                                \
-      ctx.last_indirect_target = rex_indirect_target_;                                     \
-      rex_indirect_func_ = rex::runtime::ResolveIndirectFunction(rex_indirect_target_);    \
+      rex_indirect_func_ = REX_LOOKUP_FUNC(base, rex_indirect_target_);                    \
     }                                                                                      \
     rex_indirect_func_(ctx, base);                                                         \
   } while (0)
+#else
+#define REX_CALL_INDIRECT_FUNC(x)                                      \
+  do {                                                                \
+    REX_PROFILE_INDIRECT_DISPATCH();                                   \
+    uint32_t rex_indirect_target_ = static_cast<uint32_t>(x);           \
+    ctx.last_indirect_target = rex_indirect_target_;                    \
+    PPCFunc* rex_indirect_func_ =                                      \
+        REX_LOOKUP_FUNC(base, rex_indirect_target_);                    \
+    rex_indirect_func_(ctx, base);                                     \
+  } while (0)
+#endif
diff --git a/resources/templates/codegen/pch_h.inja b/resources/templates/codegen/pch_h.inja
index 68274d2..5706b1e 100644
--- a/resources/templates/codegen/pch_h.inja
+++ b/resources/templates/codegen/pch_h.inja
@@ -246,6 +246,8 @@ extern PPCFuncMapping PPCFuncMappings[];
 
 {% include "codegen/_indirect_call.inja" %}
 
+#include <rex/ppc/gprlr_inline.h>
+
 //=============================================================================
 // Flush Mode
 //=============================================================================
diff --git a/src/codegen/builders/context.cpp b/src/codegen/builders/context.cpp
index f78e0d8..fff103a 100644
--- a/src/codegen/builders/context.cpp
+++ b/src/codegen/builders/context.cpp
@@ -13,6 +13,7 @@
 #include "helpers.h"
 
 #include <algorithm>
+#include <string_view>
 
 #include <rex/codegen/binary_view.h>
 #include <rex/logging.h>
@@ -226,6 +227,32 @@ void BuilderContext::emit_function_call(uint32_t address) {
         return;
       }
 
+      // GPR/LR save and restore helpers: emit the always_inline copy from
+      // rex/ppc/gprlr_inline.h (identical body) instead of an out-of-line call.
+      {
+        constexpr std::string_view kSave = "__savegprlr_";
+        constexpr std::string_view kRest = "__restgprlr_";
+        std::string_view view = name;
+        const bool is_save = view.substr(0, kSave.size()) == kSave;
+        const bool is_rest = view.substr(0, kRest.size()) == kRest;
+        if (is_save || is_rest) {
+          const std::string_view digits = view.substr(kSave.size());
+          unsigned n = 0;
+          bool numeric = !digits.empty() && digits.size() <= 2;
+          for (char c : digits) {
+            if (c < '0' || c > '9') {
+              numeric = false;
+              break;
+            }
+            n = n * 10 + unsigned(c - '0');
+          }
+          if (numeric && n >= 14 && n <= 31) {
+            println("\trex_inl_{}gprlr_{}(ctx, base);", is_save ? "save" : "rest", n);
+            return;
+          }
+        }
+      }
+
       emitCtx.reference(name);
       println("\t{}(ctx, base);", name);
       return;
@@ -281,7 +308,9 @@ void BuilderContext::emit_conditional_branch(bool not_, std::string_view cond) {
 
   // Use classifyTarget for consistent branch classification
   // false = branch instruction (not a call), so own-base means loop back
-  auto kind = graph().classifyTarget(target, base, false);
+  // The current FunctionNode owns this emission. A shared-tail entry can
+  // overlap its blocks, so an instruction-address lookup may find another node.
+  auto kind = graph().classifyTarget(target, fn.base(), false);
 
   switch (kind) {
     case TargetKind::InternalLabel:
diff --git a/src/codegen/builders/control_flow.cpp b/src/codegen/builders/control_flow.cpp
index 26957fc..d80db2b 100644
--- a/src/codegen/builders/control_flow.cpp
+++ b/src/codegen/builders/control_flow.cpp
@@ -29,7 +29,7 @@ bool build_b(BuilderContext& ctx) {
 
   // Use graph to classify the target - handles thunks that branch to nearby functions
   // false = branch instruction (not a call), so own-base means loop back
-  auto kind = ctx.graph().classifyTarget(target, ctx.base, false);
+  auto kind = ctx.graph().classifyTarget(target, ctx.fn.base(), false);
 
   switch (kind) {
     case TargetKind::InternalLabel:
@@ -67,7 +67,7 @@ bool build_bl(BuilderContext& ctx) {
 
   // Use graph to classify the target
   // true = call instruction, so own-base means recursive call (not loop back)
-  auto kind = ctx.graph().classifyTarget(target, ctx.base, true);
+  auto kind = ctx.graph().classifyTarget(target, ctx.fn.base(), true);
 
   switch (kind) {
     case TargetKind::InternalLabel:
@@ -138,7 +138,13 @@ bool build_bctr(BuilderContext& ctx) {
         continue;
       }
 
-      auto kind = ctx.graph().classifyTarget(label, ctx.base, false);
+      auto kind = ctx.graph().classifyTarget(label, ctx.fn.base(), false);
+      // A table can dispatch to separately registered case functions, even
+      // when speculative discovery also claimed their addresses as labels.
+      if (kind == TargetKind::InternalLabel && label != ctx.fn.base() &&
+          ctx.graph().isEntryPoint(label)) {
+        kind = TargetKind::Function;
+      }
       switch (kind) {
         case TargetKind::InternalLabel:
           ctx.println("\t\tgoto loc_{:X};", label);
diff --git a/src/codegen/builders/helpers.h b/src/codegen/builders/helpers.h
index dbc8d51..d02ca29 100644
--- a/src/codegen/builders/helpers.h
+++ b/src/codegen/builders/helpers.h
@@ -387,12 +387,23 @@ inline bool isMMIOUpperBits(uint32_t imm) {
  */
 inline void emitBranchWithBoundsCheck(BuilderContext& ctx, uint32_t target,
                                       std::string_view condition, std::string_view instr_name) {
-  if (target < ctx.fn.base() || target >= ctx.fn.end()) {
-    REXCODEGEN_WARN("{} at {:X} branches outside function to {:X}", instr_name, ctx.base, target);
-    ctx.println("\tif ({}) {{ /* branch to 0x{:X} outside function */ return; }}", condition,
-                target);
-  } else {
-    ctx.println("\tif ({}) goto loc_{:X};", condition, target);
+  switch (ctx.graph().classifyTarget(target, ctx.fn.base(), false)) {
+    case TargetKind::InternalLabel:
+      ctx.println("\tif ({}) goto loc_{:X};", condition, target);
+      break;
+    case TargetKind::Function:
+    case TargetKind::Import:
+      ctx.println("\tif ({}) {{", condition);
+      ctx.emit_function_call(target);
+      ctx.println("\t\treturn;");
+      ctx.println("\t}}");
+      break;
+    case TargetKind::Unknown:
+      REXCODEGEN_ERROR("Unresolved {} target 0x{:08X} from 0x{:08X}", instr_name, target,
+                       ctx.base);
+      ctx.println("\tif ({}) REX_FATAL(\"Unresolved branch from 0x{:08X} to 0x{:08X}\");",
+                  condition, ctx.base, target);
+      break;
   }
 }
 
diff --git a/src/codegen/builders/vector.cpp b/src/codegen/builders/vector.cpp
index cbdd7f7..9cf0f5c 100644
--- a/src/codegen/builders/vector.cpp
+++ b/src/codegen/builders/vector.cpp
@@ -1094,18 +1094,14 @@ bool build_vpkuhum(BuilderContext& ctx) {
 }
 
 bool build_vpkuhus(BuilderContext& ctx) {
-  // Vector Pack Unsigned Halfword Unsigned Saturate
-  // NOTE(tomc): _mm_packus_epi16 treats inputs as signed, so we need custom saturation for
-  // unsigned. Unsigned halfwords >= 0x8000 would be interpreted as negative and clamped to 0
-  // instead of 0xFF.
-  for (size_t i = 0; i < 8; i++) {
-    ctx.println("\t{}.u8[{}] = {}.u16[{}] > 0xFF ? 0xFF : (uint8_t){}.u16[{}];",
-                ctx.v(ctx.insn.operands[0]), 15 - i, ctx.v(ctx.insn.operands[1]), 7 - i,
-                ctx.v(ctx.insn.operands[1]), 7 - i);
-    ctx.println("\t{}.u8[{}] = {}.u16[{}] > 0xFF ? 0xFF : (uint8_t){}.u16[{}];",
-                ctx.v(ctx.insn.operands[0]), 7 - i, ctx.v(ctx.insn.operands[2]), 7 - i,
-                ctx.v(ctx.insn.operands[2]), 7 - i);
-  }
+  // Clamp unsigned inputs before signed packing; load both sources before writing
+  // the destination, which may alias either source register.
+  ctx.println(
+      "\tsimde_mm_store_si128((simde__m128i*){}.u8, "
+      "simde_mm_packus_epi16(simde_mm_min_epu16(simde_mm_load_si128((simde__m128i*){}.u16), "
+      "simde_mm_set1_epi16(0xFF)), simde_mm_min_epu16(simde_mm_load_si128((simde__m128i*){}.u16), "
+      "simde_mm_set1_epi16(0xFF))));",
+      ctx.v(ctx.insn.operands[0]), ctx.v(ctx.insn.operands[2]), ctx.v(ctx.insn.operands[1]));
   return true;
 }
 
@@ -1122,18 +1118,13 @@ bool build_vpkuwum(BuilderContext& ctx) {
 }
 
 bool build_vpkuwus(BuilderContext& ctx) {
-  // Vector Pack Unsigned Word Unsigned Saturate
-
-  // NOTE(tomc): _mm_packus_epi32 treats inputs as signed, so we need custom saturation for unsigned
-  // Saturate each u32 to [0, 0xFFFF], then pack to u16
-  for (size_t i = 0; i < 4; i++) {
-    ctx.println("\t{}.u16[{}] = {}.u32[{}] > 0xFFFF ? 0xFFFF : (uint16_t){}.u32[{}];",
-                ctx.v(ctx.insn.operands[0]), 7 - i, ctx.v(ctx.insn.operands[1]), 3 - i,
-                ctx.v(ctx.insn.operands[1]), 3 - i);
-    ctx.println("\t{}.u16[{}] = {}.u32[{}] > 0xFFFF ? 0xFFFF : (uint16_t){}.u32[{}];",
-                ctx.v(ctx.insn.operands[0]), 3 - i, ctx.v(ctx.insn.operands[2]), 3 - i,
-                ctx.v(ctx.insn.operands[2]), 3 - i);
-  }
+  // Preserve aliased sources and clamp unsigned words before signed packing.
+  ctx.println(
+      "\tsimde_mm_store_si128((simde__m128i*){}.u16, "
+      "simde_mm_packus_epi32(simde_mm_min_epu32(simde_mm_load_si128((simde__m128i*){}.u32), "
+      "simde_mm_set1_epi32(0xFFFF)), simde_mm_min_epu32(simde_mm_load_si128((simde__m128i*){}.u32), "
+      "simde_mm_set1_epi32(0xFFFF))));",
+      ctx.v(ctx.insn.operands[0]), ctx.v(ctx.insn.operands[2]), ctx.v(ctx.insn.operands[1]));
   return true;
 }
 
@@ -1168,6 +1159,14 @@ bool build_vpkswus(BuilderContext& ctx) {
 }
 
 bool build_vpkd3d128(BuilderContext& ctx) {
+  const bool aliases_source = ctx.insn.operands[0] == ctx.insn.operands[1];
+  auto source = ctx.v(ctx.insn.operands[1]);
+  if (aliases_source) {
+    // Packing changes element widths; preserve every source lane before writes.
+    ctx.println("\t{{");
+    ctx.println("\tconst auto vector_pack_source = {};", source);
+    source = "vector_pack_source";
+  }
   // TODO(tomc): vectorize
   // NOTE: handling vector reversal here too
   ctx.emit_set_flush_mode(true);
@@ -1185,8 +1184,8 @@ bool build_vpkd3d128(BuilderContext& ctx) {
         ctx.println(
             "\t{}.f32[{}] = !({}.f32[{}] >= 3.0f) ? 3.0f : ({}.f32[{}] > {}.f32[{}] ? {}.f32[{}] : "
             "{}.f32[{}]);",
-            ctx.v_temp(), i, ctx.v(ctx.insn.operands[1]), i, ctx.v(ctx.insn.operands[1]), i,
-            ctx.v_temp(), i, ctx.v_temp(), i, ctx.v(ctx.insn.operands[1]), i);
+            ctx.v_temp(), i, source, i, source, i,
+            ctx.v_temp(), i, ctx.v_temp(), i, source, i);
         ctx.println("\t{}.u32 {}= uint32_t({}.u8[{}]) << {};", ctx.temp(), i == 0 ? "" : "|",
                     ctx.v_temp(), i * 4, indices[i] * 8);
       }
@@ -1216,12 +1215,12 @@ bool build_vpkd3d128(BuilderContext& ctx) {
       // We need to saturate to signed 16-bit range [-32767, 32767] (NOT -32768, based on tests)
       // NOTE: Guest element 0 is at array index 3, element 1 is at index 2 (reversed for host)
       // Element 0 (index 3) goes to HIGH word, element 1 (index 2) goes to LOW word
-      ctx.println("\t{}.s32 = {}.s32[3] - 0x40400000;", ctx.temp(), ctx.v(ctx.insn.operands[1]));
+      ctx.println("\t{}.s32 = {}.s32[3] - 0x40400000;", ctx.temp(), source);
       ctx.println("\t{}.s32 = {}.s32 > 32767 ? 32767 : ({}.s32 < -32767 ? -32767 : {}.s32);",
                   ctx.temp(), ctx.temp(), ctx.temp(), ctx.temp());
       ctx.println("\t{}.u32[0] = uint32_t(uint16_t({}.s32)) << 16;", ctx.v_temp(),
                   ctx.temp());  // element 0 to high word
-      ctx.println("\t{}.s32 = {}.s32[2] - 0x40400000;", ctx.temp(), ctx.v(ctx.insn.operands[1]));
+      ctx.println("\t{}.s32 = {}.s32[2] - 0x40400000;", ctx.temp(), source);
       ctx.println("\t{}.s32 = {}.s32 > 32767 ? 32767 : ({}.s32 < -32767 ? -32767 : {}.s32);",
                   ctx.temp(), ctx.temp(), ctx.temp(), ctx.temp());
       ctx.println("\t{}.u32[0] |= uint16_t({}.s32);", ctx.v_temp(),
@@ -1243,32 +1242,32 @@ bool build_vpkd3d128(BuilderContext& ctx) {
       ctx.println(
           "\t{}.f32 = {}.f32[3] < kPack2101010_Min10 ? kPack2101010_Min10 : ({}.f32[3] > "
           "kPack2101010_Max10 ? kPack2101010_Max10 : {}.f32[3]);",
-          ctx.temp(), ctx.v(ctx.insn.operands[1]), ctx.v(ctx.insn.operands[1]),
-          ctx.v(ctx.insn.operands[1]));
+          ctx.temp(), source, source,
+          source);
       ctx.println("\t{}.u32[0] = {}.u32 & 0x3FF;", ctx.v_temp(), ctx.temp());
 
       // Pack y (10 bits, position 10-19) - Guest element 1 is at index 2
       ctx.println(
           "\t{}.f32 = {}.f32[2] < kPack2101010_Min10 ? kPack2101010_Min10 : ({}.f32[2] > "
           "kPack2101010_Max10 ? kPack2101010_Max10 : {}.f32[2]);",
-          ctx.temp(), ctx.v(ctx.insn.operands[1]), ctx.v(ctx.insn.operands[1]),
-          ctx.v(ctx.insn.operands[1]));
+          ctx.temp(), source, source,
+          source);
       ctx.println("\t{}.u32[0] |= ({}.u32 & 0x3FF) << 10;", ctx.v_temp(), ctx.temp());
 
       // Pack z (10 bits, position 20-29) - Guest element 2 is at index 1
       ctx.println(
           "\t{}.f32 = {}.f32[1] < kPack2101010_Min10 ? kPack2101010_Min10 : ({}.f32[1] > "
           "kPack2101010_Max10 ? kPack2101010_Max10 : {}.f32[1]);",
-          ctx.temp(), ctx.v(ctx.insn.operands[1]), ctx.v(ctx.insn.operands[1]),
-          ctx.v(ctx.insn.operands[1]));
+          ctx.temp(), source, source,
+          source);
       ctx.println("\t{}.u32[0] |= ({}.u32 & 0x3FF) << 20;", ctx.v_temp(), ctx.temp());
 
       // Pack w (2 bits, position 30-31) - Guest element 3 is at index 0
       ctx.println(
           "\t{}.f32 = {}.f32[0] < kPack2101010_Min2 ? kPack2101010_Min2 : ({}.f32[0] > "
           "kPack2101010_Max2 ? kPack2101010_Max2 : {}.f32[0]);",
-          ctx.temp(), ctx.v(ctx.insn.operands[1]), ctx.v(ctx.insn.operands[1]),
-          ctx.v(ctx.insn.operands[1]));
+          ctx.temp(), source, source,
+          source);
       ctx.println("\t{}.u32[0] |= ({}.u32 & 0x3) << 30;", ctx.v_temp(), ctx.temp());
 
       ctx.println("\t{}.u32[{}] = {}.u32[0];", ctx.v(ctx.insn.operands[0]), ctx.insn.operands[4],
@@ -1285,21 +1284,21 @@ bool build_vpkd3d128(BuilderContext& ctx) {
         size_t srcIdx = 3 - i;  // Guest element i is at host array index 3-i
         size_t dstIdx =
             (1 - i) + (2 * ctx.insn.operands[4]);  // Output reversed: elem 0 to high, elem 1 to low
-        ctx.println("\t{}.u32 = ({}.u32[{}]&0x7FFFFFFF);", ctx.temp(), ctx.v(ctx.insn.operands[1]),
+        ctx.println("\t{}.u32 = ({}.u32[{}]&0x7FFFFFFF);", ctx.temp(), source,
                     srcIdx);
         ctx.println(
             "\t{0}.u8[0] = ({1}.f32 != {1}.f32) || ({1}.f32 > 65504.0f) ? 0xFF : "
             "(({2}.u32[{3}]&0x7f800000)>>23);",
-            ctx.v_temp(), ctx.temp(), ctx.v(ctx.insn.operands[1]), srcIdx);
+            ctx.v_temp(), ctx.temp(), source, srcIdx);
         ctx.println("\t{}.u16 = {}.u8[0] != 0xFF ? (({}.u32[{}]&0x7FE000)>>13) : 0x0;", ctx.temp(),
-                    ctx.v_temp(), ctx.v(ctx.insn.operands[1]), srcIdx);
+                    ctx.v_temp(), source, srcIdx);
         ctx.println(
             "\t{0}.u16[{1}] = {2}.u8[0] != 0xFF ? ({2}.u8[0] > 0x70 ? "
             "((({2}.u8[0]-0x70)<<10)+{3}.u16) : (0x71-{2}.u8[0] > 31 ? 0x0 : "
             "((0x400+{3}.u16)>>(0x71-{2}.u8[0])))) : 0x7FFF;",
             ctx.v(ctx.insn.operands[0]), dstIdx, ctx.v_temp(), ctx.temp());
         ctx.println("\t{}.u16[{}] |= (({}.u32[{}]&0x80000000)>>16);", ctx.v(ctx.insn.operands[0]),
-                    dstIdx, ctx.v(ctx.insn.operands[1]), srcIdx);
+                    dstIdx, source, srcIdx);
       }
       break;
     }
@@ -1312,7 +1311,7 @@ bool build_vpkd3d128(BuilderContext& ctx) {
       for (size_t i = 0; i < 4; i++) {
         size_t srcIdx = 3 - i;  // Guest element i is at host array index 3-i
         size_t dstIdx = (3 - i) + (2 * ctx.insn.operands[4]);  // Output also reversed
-        ctx.println("\t{}.s32 = {}.s32[{}] - 0x40400000;", ctx.temp(), ctx.v(ctx.insn.operands[1]),
+        ctx.println("\t{}.s32 = {}.s32[{}] - 0x40400000;", ctx.temp(), source,
                     srcIdx);
         ctx.println("\t{}.s32 = {}.s32 > 32767 ? 32767 : ({}.s32 < -32767 ? -32767 : {}.s32);",
                     ctx.temp(), ctx.temp(), ctx.temp(), ctx.temp());
@@ -1333,21 +1332,21 @@ bool build_vpkd3d128(BuilderContext& ctx) {
       for (size_t i = 0; i < 4; i++) {
         size_t srcIdx = 3 - i;  // Guest element i is at host array index 3-i
         size_t dstIdx = (3 - i) + (2 * ctx.insn.operands[4]);  // Output also reversed
-        ctx.println("\t{}.u32 = ({}.u32[{}]&0x7FFFFFFF);", ctx.temp(), ctx.v(ctx.insn.operands[1]),
+        ctx.println("\t{}.u32 = ({}.u32[{}]&0x7FFFFFFF);", ctx.temp(), source,
                     srcIdx);
         ctx.println(
             "\t{0}.u8[0] = ({1}.f32 != {1}.f32) || ({1}.f32 > 65504.0f) ? 0xFF : "
             "(({2}.u32[{3}]&0x7f800000)>>23);",
-            ctx.v_temp(), ctx.temp(), ctx.v(ctx.insn.operands[1]), srcIdx);
+            ctx.v_temp(), ctx.temp(), source, srcIdx);
         ctx.println("\t{}.u16 = {}.u8[0] != 0xFF ? (({}.u32[{}]&0x7FE000)>>13) : 0x0;", ctx.temp(),
-                    ctx.v_temp(), ctx.v(ctx.insn.operands[1]), srcIdx);
+                    ctx.v_temp(), source, srcIdx);
         ctx.println(
             "\t{0}.u16[{1}] = {2}.u8[0] != 0xFF ? ({2}.u8[0] > 0x70 ? "
             "((({2}.u8[0]-0x70)<<10)+{3}.u16) : (0x71-{2}.u8[0] > 31 ? 0x0 : "
             "((0x400+{3}.u16)>>(0x71-{2}.u8[0])))) : 0x7FFF;",
             ctx.v(ctx.insn.operands[0]), dstIdx, ctx.v_temp(), ctx.temp());
         ctx.println("\t{}.u16[{}] |= (({}.u32[{}]&0x80000000)>>16);", ctx.v(ctx.insn.operands[0]),
-                    dstIdx, ctx.v(ctx.insn.operands[1]), srcIdx);
+                    dstIdx, source, srcIdx);
       }
       break;
     }
@@ -1357,16 +1356,16 @@ bool build_vpkd3d128(BuilderContext& ctx) {
       // Format: 4 bits for w, 20 bits each for x, y, z (packed into 64 bits)
       ctx.println("\t{}.u64[0] = 0;", ctx.v_temp());
       // Pack x (20 bits, position 0-19)
-      ctx.println("\t{}.s32 = int32_t({}.f32[0]);", ctx.temp(), ctx.v(ctx.insn.operands[1]));
+      ctx.println("\t{}.s32 = int32_t({}.f32[0]);", ctx.temp(), source);
       ctx.println("\t{}.u64[0] = uint64_t({}.s32 & 0xFFFFF);", ctx.v_temp(), ctx.temp());
       // Pack y (20 bits, position 20-39)
-      ctx.println("\t{}.s32 = int32_t({}.f32[1]);", ctx.temp(), ctx.v(ctx.insn.operands[1]));
+      ctx.println("\t{}.s32 = int32_t({}.f32[1]);", ctx.temp(), source);
       ctx.println("\t{}.u64[0] |= uint64_t({}.s32 & 0xFFFFF) << 20;", ctx.v_temp(), ctx.temp());
       // Pack z (20 bits, position 40-59)
-      ctx.println("\t{}.s32 = int32_t({}.f32[2]);", ctx.temp(), ctx.v(ctx.insn.operands[1]));
+      ctx.println("\t{}.s32 = int32_t({}.f32[2]);", ctx.temp(), source);
       ctx.println("\t{}.u64[0] |= uint64_t({}.s32 & 0xFFFFF) << 40;", ctx.v_temp(), ctx.temp());
       // Pack w (4 bits, position 60-63)
-      ctx.println("\t{}.s32 = int32_t({}.f32[3]);", ctx.temp(), ctx.v(ctx.insn.operands[1]));
+      ctx.println("\t{}.s32 = int32_t({}.f32[3]);", ctx.temp(), source);
       ctx.println("\t{}.u64[0] |= uint64_t({}.s32 & 0xF) << 60;", ctx.v_temp(), ctx.temp());
       ctx.println("\t{}.u64[{}] = {}.u64[0];", ctx.v(ctx.insn.operands[0]),
                   ctx.insn.operands[4] >> 1, ctx.v_temp());
@@ -1377,6 +1376,7 @@ bool build_vpkd3d128(BuilderContext& ctx) {
       ctx.println("\t__builtin_debugtrap();");
       break;
   }
+  if (aliases_source) ctx.println("\t}}");
   return true;
 }
 
@@ -1385,6 +1385,14 @@ bool build_vpkd3d128(BuilderContext& ctx) {
 //=============================================================================
 
 bool build_vupkd3d128(BuilderContext& ctx) {
+  const bool aliases_source = ctx.insn.operands[0] == ctx.insn.operands[1];
+  auto source = ctx.v(ctx.insn.operands[1]);
+  if (aliases_source) {
+    // Packing changes element widths; preserve every source lane before writes.
+    ctx.println("\t{{");
+    ctx.println("\tconst auto vector_pack_source = {};", source);
+    source = "vector_pack_source";
+  }
   // TODO(tomc): Vectorize
   // NOTE: handling vector reversal here too
   switch (ctx.insn.operands[2] >> 2) {
@@ -1392,7 +1400,7 @@ bool build_vupkd3d128(BuilderContext& ctx) {
       for (size_t i = 0; i < 4; i++) {
         constexpr size_t indices[] = {3, 0, 1, 2};
         ctx.println("\t{}.u32[{}] = {}.u8[{}] | 0x3F800000;", ctx.v_temp(), i,
-                    ctx.v(ctx.insn.operands[1]), indices[i]);
+                    source, indices[i]);
       }
       ctx.println("\t{} = {};", ctx.v(ctx.insn.operands[0]), ctx.v_temp());
       break;
@@ -1400,7 +1408,7 @@ bool build_vupkd3d128(BuilderContext& ctx) {
     case 1:  // NORMSHORT2 - unpack 2 shorts to floats (3.0+X form)
       for (size_t i = 0; i < 2; i++) {
         ctx.println("\t{}.f32 = 3.0f;", ctx.temp());
-        ctx.println("\t{}.s32 += {}.s16[{}];", ctx.temp(), ctx.v(ctx.insn.operands[1]), 1 - i);
+        ctx.println("\t{}.s32 += {}.s16[{}];", ctx.temp(), source, 1 - i);
         ctx.println("\t{}.f32[{}] = {}.f32;", ctx.v_temp(), 3 - i, ctx.temp());
       }
       ctx.println("\t{}.f32[1] = 0.0f;", ctx.v_temp());
@@ -1414,7 +1422,7 @@ bool build_vupkd3d128(BuilderContext& ctx) {
       // x, y, z --> 3.0+X form (signed 10-bit), w --> 1.0+w form
       // Output: x --> Guest element 0 (host u32[3]), y --> Guest element 1 (host u32[2]),
       //         z --> Guest element 2 (host u32[1]), w --> Guest element 3 (host u32[0])
-      auto vSrc = ctx.v(ctx.insn.operands[1]);
+      auto vSrc = source;
       auto vDst = ctx.v(ctx.insn.operands[0]);
       // x (bits 0-9) - sign extend from 10 bits --> Guest element 0 (host u32[3])
       ctx.println("\t{}.s32 = ({}.s32[0] << 22) >> 22;", ctx.temp(), vSrc);
@@ -1437,7 +1445,7 @@ bool build_vupkd3d128(BuilderContext& ctx) {
 
     case 3:  // FLOAT16_2 - unpack 2 float16 to floats
     {
-      auto vSrc = ctx.v(ctx.insn.operands[1]);
+      auto vSrc = source;
       auto vDst = ctx.v(ctx.insn.operands[0]);
       // Unpack 2 float16s from u16[0,1] to elements 0,1 (stored at u32[3,2])
       // Element 0 (at u32[3]) from u16[1] (high), element 1 (at u32[2]) from u16[0] (low)
@@ -1468,7 +1476,7 @@ bool build_vupkd3d128(BuilderContext& ctx) {
         size_t srcIdx = 3 - i;  // Read from u16 indices 3, 2, 1, 0 (guest shorts 0, 1, 2, 3)
         size_t dstIdx = 3 - i;  // Write to f32 indices 3, 2, 1, 0 (Guest elements 0, 1, 2, 3)
         ctx.println("\t{}.f32 = 3.0f;", ctx.temp());
-        ctx.println("\t{}.s32 += {}.s16[{}];", ctx.temp(), ctx.v(ctx.insn.operands[1]), srcIdx);
+        ctx.println("\t{}.s32 += {}.s16[{}];", ctx.temp(), source, srcIdx);
         ctx.println("\t{}.f32[{}] = {}.f32;", ctx.v(ctx.insn.operands[0]), dstIdx, ctx.temp());
       }
       break;
@@ -1476,7 +1484,7 @@ bool build_vupkd3d128(BuilderContext& ctx) {
 
     case 5:  // FLOAT16_4 - unpack 4 float16 to floats
     {
-      auto vSrc = ctx.v(ctx.insn.operands[1]);
+      auto vSrc = source;
       auto vDst = ctx.v(ctx.insn.operands[0]);
       // Unpack 4 float16s from Guest elements 2-3 (host u16[0-3]) to elements 0-3
       // Guest element order is reversed in host arrays
@@ -1499,7 +1507,7 @@ bool build_vupkd3d128(BuilderContext& ctx) {
 
     case 6:  // NORMPACKED64 - unpack 4:20:20:20 to floats
     {
-      auto vSrc = ctx.v(ctx.insn.operands[1]);
+      auto vSrc = source;
       auto vDst = ctx.v(ctx.insn.operands[0]);
       // Format: w(4 bits):z(20 bits):y(20 bits):x(20 bits) in 64 bits
       // x, y, z --> floats, w --> float
@@ -1522,6 +1530,7 @@ bool build_vupkd3d128(BuilderContext& ctx) {
       ctx.println("\t__builtin_debugtrap();");
       break;
   }
+  if (aliases_source) ctx.println("\t}}");
   return true;
 }
 
diff --git a/src/codegen/function_graph.cpp b/src/codegen/function_graph.cpp
index fc918bb..3df62bd 100644
--- a/src/codegen/function_graph.cpp
+++ b/src/codegen/function_graph.cpp
@@ -1266,6 +1266,12 @@ TargetKind FunctionGraph::classifyTarget(uint32_t target, uint32_t callerAddr,
     return isCallInstruction ? TargetKind::Function : TargetKind::InternalLabel;
   }
 
+  // A block discovered in this caller stays local even if a shared-tail entry
+  // is registered at the same address later during iterative discovery.
+  if (callerFn && callerFn->isLabel(target) && callerFn->containsAddress(target)) {
+    return TargetKind::InternalLabel;
+  }
+
   // Case 3: Target is a DIFFERENT function's entry point - this is a call/tail-call
   // This handles cases where a small thunk function branches to another function
   // whose entry point happens to fall within the thunk's address range
diff --git a/src/codegen/phase_discover.cpp b/src/codegen/phase_discover.cpp
index 1c73548..2d7d406 100644
--- a/src/codegen/phase_discover.cpp
+++ b/src/codegen/phase_discover.cpp
@@ -124,6 +124,20 @@ void discoverFunction(CodegenContext& ctx, uint32_t funcAddr,
 
   // Add unresolved branches for later resolution
   for (const auto& branch : result.unresolvedBranches) {
+    // Shared tails may be reached at an interior address of another function.
+    // Give an external branch target its own entry instead of accepting an
+    // address that validation can locate but code generation cannot call.
+    if (!branch.isCall && !graph.isEntryPoint(branch.target) &&
+        !node->containsAddress(branch.target) && !binary.isInImportExportRange(branch.target)) {
+      const auto* targetInsn = decoded.get(branch.target);
+      // The lightweight decoder does not classify every arithmetic opcode
+      // supported by the emitter (for example subfc). Only reject padding.
+      if (targetInsn && static_cast<uint32_t>(targetInsn->code) != 0 &&
+          static_cast<uint32_t>(targetInsn->code) != 0xFFFFFFFF) {
+        auto* tail = graph.addFunction(branch.target, 4, FunctionAuthority::DISCOVERED, true);
+        tail->setSharesRegisters(true);
+      }
+    }
     graph.addUnresolvedJumpToFunction(funcAddr, branch.site, branch.target, branch.isCall,
                                       branch.isConditional);
   }
diff --git a/src/core/bit_stream.cpp b/src/core/bit_stream.cpp
index 9329c6d..7c718a2 100644
--- a/src/core/bit_stream.cpp
+++ b/src/core/bit_stream.cpp
@@ -39,12 +39,20 @@ uint64_t BitStream::Peek(size_t num_bits) {
   assert_false(num_bits > 57);
   assert_false(offset_bits_ + num_bits > size_bits_);
 
+  if (!num_bits || num_bits > 57 || offset_bits_ > size_bits_ ||
+      num_bits > size_bits_ - offset_bits_) {
+    return 0;
+  }
+
   size_t offset_bytes = offset_bits_ >> 3;
   size_t rel_offset_bits = offset_bits_ - (offset_bytes << 3);
 
   // offset -->
   // ..[junk]..| target bits |....[junk].............
-  uint64_t bits = *(uint64_t*)(buffer_ + offset_bytes);
+  const size_t available_bits = size_bits_ - (offset_bytes << 3);
+  const size_t available_bytes = available_bits / 8 + (available_bits % 8 != 0);
+  uint64_t bits = 0;
+  std::memcpy(&bits, buffer_ + offset_bytes, std::min(sizeof(bits), available_bytes));
 
   // We need the data in little endian.
   // TODO: Have a flag specifying endianness of data?
@@ -68,82 +76,60 @@ uint64_t BitStream::Read(size_t num_bits) {
   return val;
 }
 
-// TODO: This is totally not tested!
 bool BitStream::Write(uint64_t val, size_t num_bits) {
-  assert_false(num_bits > 57);
-  assert_false(offset_bits_ + num_bits >= size_bits_);
-
-  size_t offset_bytes = offset_bits_ >> 3;
-  size_t rel_offset_bits = offset_bits_ - (offset_bytes << 3);
-
-  // Construct a mask
-  uint64_t mask = (1ULL << num_bits) - 1;
-  mask <<= 64 - (rel_offset_bits + num_bits);
-  mask = ~mask;
-
-  // Shift the value left into position.
-  val <<= 64 - (rel_offset_bits + num_bits);
-
-  // offset ----->
-  // ....[junk]...| target bits w/ junk |....[junk]......
-  uint64_t bits = *(uint64_t*)(buffer_ + offset_bytes);
-
-  // AND with mask
-  // ....[junk]...| target bits (0) |........[junk]......
-  bits &= mask;
-
-  // OR with val
-  // ....[junk]...| target bits (val) |......[junk]......
-  bits |= val;
-
-  // Store into the bitstream.
-  *(uint64_t*)(buffer_ + offset_bytes) = bits;
-
-  // Advance the bitstream forward.
-  Advance(num_bits);
-
+  if (num_bits > 57 || offset_bits_ > size_bits_ ||
+      num_bits > size_bits_ - offset_bits_) {
+    return false;
+  }
+  // Write only the affected bytes, in the same MSB-first order as Read.
+  size_t remaining = num_bits;
+  while (remaining) {
+    const size_t bit_in_byte = offset_bits_ & 7;
+    const size_t count = std::min(remaining, 8 - bit_in_byte);
+    const size_t shift = 8 - bit_in_byte - count;
+    const uint8_t mask = uint8_t(((1u << count) - 1) << shift);
+    const uint8_t value = uint8_t((val >> (remaining - count)) << shift);
+    auto& byte = buffer_[offset_bits_ >> 3];
+    byte = uint8_t((byte & ~mask) | (value & mask));
+    offset_bits_ += count;
+    remaining -= count;
+  }
   return true;
 }
 
 size_t BitStream::Copy(uint8_t* dest_buffer, size_t num_bits) {
-  size_t offset_bytes = offset_bits_ >> 3;
-  size_t rel_offset_bits = offset_bits_ - (offset_bytes << 3);
+  const size_t rel_offset_bits = offset_bits_ & 7;
+  if (!num_bits || offset_bits_ > size_bits_ ||
+      num_bits > size_bits_ - offset_bits_) {
+    return rel_offset_bits;
+  }
   size_t bits_left = num_bits;
   size_t out_offset_bytes = 0;
 
-  // First: Copy the first few bits up to a byte boundary.
+  // Preserve the source bit alignment in the first destination byte.
   if (rel_offset_bits) {
-    uint64_t bits = Peek(8 - rel_offset_bits);
-    uint8_t clear_mask = ~((uint8_t(1) << rel_offset_bits) - 1);
-    dest_buffer[out_offset_bytes] &= clear_mask;
-    dest_buffer[out_offset_bytes] |= (uint8_t)bits;
-
-    bits_left -= 8 - rel_offset_bits;
-    Advance(8 - rel_offset_bits);
-    out_offset_bytes++;
+    const size_t count = std::min(bits_left, 8 - rel_offset_bits);
+    const size_t shift = 8 - rel_offset_bits - count;
+    const uint8_t mask = uint8_t(((1u << count) - 1) << shift);
+    auto& byte = dest_buffer[out_offset_bytes++];
+    byte = uint8_t((byte & ~mask) | (uint8_t(Peek(count) << shift) & mask));
+    Advance(count);
+    bits_left -= count;
   }
-
-  // Second: Use memcpy for the bytes left.
   if (bits_left >= 8) {
-    std::memcpy(dest_buffer + out_offset_bytes, buffer_ + offset_bytes + out_offset_bytes,
-                bits_left / 8);
-    out_offset_bytes += (bits_left / 8);
-    Advance((bits_left / 8) * 8);
-    bits_left -= (bits_left / 8) * 8;
+    const size_t bytes = bits_left / 8;
+    std::memcpy(dest_buffer + out_offset_bytes, buffer_ + (offset_bits_ >> 3), bytes);
+    out_offset_bytes += bytes;
+    Advance(bytes * 8);
+    bits_left %= 8;
   }
-
-  // Third: Copy the last few bits.
   if (bits_left) {
-    uint64_t bits = Peek(bits_left);
-    bits <<= 8 - bits_left;
-
-    uint8_t clear_mask = ((uint8_t(1) << bits_left) - 1);
-    dest_buffer[out_offset_bytes] &= clear_mask;
-    dest_buffer[out_offset_bytes] |= (uint8_t)bits;
+    const size_t shift = 8 - bits_left;
+    const uint8_t mask = uint8_t(((1u << bits_left) - 1) << shift);
+    auto& byte = dest_buffer[out_offset_bytes];
+    byte = uint8_t((byte & ~mask) | (uint8_t(Peek(bits_left) << shift) & mask));
     Advance(bits_left);
   }
-
-  // Return the bit offset to the copied bits.
   return rel_offset_bits;
 }
 
diff --git a/src/core/byte_stream.cpp b/src/core/byte_stream.cpp
index 3dd190e..b45ba3e 100644
--- a/src/core/byte_stream.cpp
+++ b/src/core/byte_stream.cpp
@@ -11,6 +11,7 @@
 
 #include <cstring>
 #include <span>
+#include <stdexcept>
 
 #include <rex/assert.h>
 #include <rex/stream.h>
@@ -23,19 +24,29 @@ ByteStream::ByteStream(uint8_t* data, size_t data_length, size_t offset)
 ByteStream::~ByteStream() = default;
 
 void ByteStream::Advance(size_t num_bytes) {
-  assert_true(offset_ + num_bytes <= data_length_);
+  if (offset_ > data_length_ || num_bytes > data_length_ - offset_) {
+    throw std::out_of_range("ByteStream advance exceeds buffer");
+  }
   offset_ += num_bytes;
 }
 
 void ByteStream::Read(std::span<uint8_t> buf) {
-  assert_true(offset_ + buf.size() <= data_length_);
-  std::memcpy(buf.data(), data_ + offset_, buf.size());
+  if (offset_ > data_length_ || buf.size() > data_length_ - offset_) {
+    throw std::out_of_range("ByteStream read exceeds buffer");
+  }
+  if (!buf.empty()) {
+    std::memcpy(buf.data(), data_ + offset_, buf.size());
+  }
   Advance(buf.size());
 }
 
 void ByteStream::Write(std::span<const uint8_t> buf) {
-  assert_true(offset_ + buf.size() <= data_length_);
-  std::memcpy(data_ + offset_, buf.data(), buf.size());
+  if (offset_ > data_length_ || buf.size() > data_length_ - offset_) {
+    throw std::out_of_range("ByteStream write exceeds buffer");
+  }
+  if (!buf.empty()) {
+    std::memcpy(data_ + offset_, buf.data(), buf.size());
+  }
   Advance(buf.size());
 }
 
@@ -43,6 +54,9 @@ template <>
 std::string ByteStream::Read() {
   std::string str;
   uint32_t len = Read<uint32_t>();
+  if (offset_ > data_length_ || len > data_length_ - offset_) {
+    throw std::out_of_range("ByteStream string exceeds buffer");
+  }
   str.resize(len);
   Read(std::span<uint8_t>(reinterpret_cast<uint8_t*>(str.data()), len));
   return str;
@@ -52,6 +66,9 @@ template <>
 std::u16string ByteStream::Read() {
   std::u16string str;
   size_t len = Read<uint32_t>();
+  if (offset_ > data_length_ || len > (data_length_ - offset_) / sizeof(char16_t)) {
+    throw std::out_of_range("ByteStream UTF-16 string exceeds buffer");
+  }
   str.resize(len);
   Read(std::span<uint8_t>(reinterpret_cast<uint8_t*>(str.data()), len * sizeof(char16_t)));
   return str;
diff --git a/src/core/clock.cpp b/src/core/clock.cpp
index ae72b7a..7181765 100644
--- a/src/core/clock.cpp
+++ b/src/core/clock.cpp
@@ -10,6 +10,13 @@
  */
 
 #include <algorithm>
+#include <atomic>
+#if defined(_WIN32)
+#include <windows.h>
+#endif
+#if defined(__x86_64__) || defined(_M_X64)
+#include <immintrin.h>
+#endif
 #include <limits>
 #include <mutex>
 
@@ -35,13 +42,24 @@ uint64_t guest_system_time_base_ = Clock::QueryHostSystemTime();
 // Computed by RecomputeGuestTickScalar.
 std::pair<uint64_t, uint64_t> guest_tick_ratio_ = std::make_pair(1, 1);
 
-// Native guest ticks.
-uint64_t last_guest_tick_count_ = 0;
-// Last sampled host tick count.
-uint64_t last_host_tick_count_ = Clock::QueryHostTickCount();
-// Mutex to ensure last_host_tick_count_ and last_guest_tick_count_ are in sync
+// Guest tick count = guest_base + (host - host_base) * ratio. Readers (every mftb the game executes,
+// including its busy-wait loops) take no lock: the base is only rebased, under tick_mutex_ and a
+// sequence counter, when the ratio changes.
+std::atomic<uint32_t> clock_seq_{0};
+std::atomic<uint64_t> clock_host_base_{Clock::QueryHostTickCount()};
+std::atomic<uint64_t> clock_guest_base_{0};
+std::atomic<uint64_t> clock_ratio_num_{1};
+std::atomic<uint64_t> clock_ratio_den_{1};
+// Serialises writers (ratio changes) and guest_tick_ratio().
 std::mutex tick_mutex_;
 
+static uint64_t GuestTicksFromHost(uint64_t host_tick_count, uint64_t host_base, uint64_t guest_base,
+                                   uint64_t num, uint64_t den) {
+  const uint64_t delta = host_tick_count > host_base ? host_tick_count - host_base : 0;
+  // delta * num / den without a 128-bit division: whole multiples of den first, then the remainder.
+  return guest_base + (delta / den) * num + (delta % den) * num / den;
+}
+
 void RecomputeGuestTickScalar() {
   // Create a rational number with numerator (first) and denominator (second)
   auto frac = std::make_pair(guest_tick_frequency_, Clock::QueryHostTickFrequency());
@@ -58,37 +76,48 @@ void RecomputeGuestTickScalar() {
   reduce_fraction(frac);
 
   std::lock_guard<std::mutex> lock(tick_mutex_);
+  const uint64_t host_now = Clock::QueryHostTickCount();
+  const uint64_t guest_now =
+      GuestTicksFromHost(host_now, clock_host_base_.load(std::memory_order_relaxed),
+                         clock_guest_base_.load(std::memory_order_relaxed),
+                         clock_ratio_num_.load(std::memory_order_relaxed),
+                         clock_ratio_den_.load(std::memory_order_relaxed));
+  clock_seq_.fetch_add(1, std::memory_order_acq_rel);  // odd: update in progress
+  clock_host_base_.store(host_now, std::memory_order_relaxed);
+  clock_guest_base_.store(guest_now, std::memory_order_relaxed);
+  clock_ratio_num_.store(frac.first, std::memory_order_relaxed);
+  clock_ratio_den_.store(frac.second, std::memory_order_relaxed);
+  clock_seq_.fetch_add(1, std::memory_order_release);  // even: consistent
   guest_tick_ratio_ = frac;
 }
 
-// Update the guest timer for all threads.
-// Return a copy of the value so locking is reduced.
-uint64_t UpdateGuestClock() {
-  uint64_t host_tick_count = Clock::QueryHostTickCount();
+// Current guest tick count for all threads (lock-free).
+uint64_t UpdateGuestClockAt(uint64_t host_tick_count) {
 
   if (REXCVAR_GET(clock_no_scaling)) {
     // Nothing to update, calculate on the fly
     return host_tick_count * guest_tick_ratio_.first / guest_tick_ratio_.second;
   }
 
-  std::unique_lock<std::mutex> lock(tick_mutex_, std::defer_lock);
-  if (lock.try_lock()) {
-    // Translate host tick count to guest tick count.
-    uint64_t host_tick_delta =
-        host_tick_count > last_host_tick_count_ ? host_tick_count - last_host_tick_count_ : 0;
-    last_host_tick_count_ = host_tick_count;
-    uint64_t guest_tick_delta =
-        host_tick_delta * guest_tick_ratio_.first / guest_tick_ratio_.second;
-    last_guest_tick_count_ += guest_tick_delta;
-    return last_guest_tick_count_;
-  } else {
-    // Wait until another thread has finished updating the clock.
-    lock.lock();
-    return last_guest_tick_count_;
+  for (;;) {
+    const uint32_t seq = clock_seq_.load(std::memory_order_acquire);
+    if (seq & 1) {
+      continue;  // A ratio change is being published; it lasts a few instructions.
+    }
+    const uint64_t host_base = clock_host_base_.load(std::memory_order_relaxed);
+    const uint64_t guest_base = clock_guest_base_.load(std::memory_order_relaxed);
+    const uint64_t num = clock_ratio_num_.load(std::memory_order_relaxed);
+    const uint64_t den = clock_ratio_den_.load(std::memory_order_relaxed);
+    std::atomic_thread_fence(std::memory_order_acquire);
+    if (clock_seq_.load(std::memory_order_relaxed) == seq) {
+      return GuestTicksFromHost(host_tick_count, host_base, guest_base, num, den);
+    }
   }
 }
+uint64_t UpdateGuestClock() {
+  return UpdateGuestClockAt(Clock::QueryHostTickCount());
+}
 
-// Offset of the current guest system file time relative to the guest base time.
 inline uint64_t QueryGuestSystemTimeOffset() {
   if (REXCVAR_GET(clock_no_scaling)) {
     return Clock::QueryHostSystemTime() - guest_system_time_base_;
@@ -156,7 +185,30 @@ void Clock::set_guest_system_time_base(uint64_t time_base) {
 }
 
 uint64_t Clock::QueryGuestTickCount() {
-  auto guest_tick_count = UpdateGuestClock();
+  // The game polls the timebase (mftb) in tight busy-wait loops, for example its Direct3D fence and
+  // vblank waits, which on a 360 owned a dedicated hardware thread. On a shared host that loop burns
+  // a core and its SMT sibling. Calls that follow each other within ~2 us on a thread are such a loop:
+  // pause between them and, in a long run, give the core to another ready thread. The time that is
+  // returned is unaffected.
+  thread_local uint64_t previous_host_tick = 0;
+  thread_local uint32_t rapid_calls = 0;
+  const uint64_t host_tick = Clock::QueryHostTickCount();
+  static const uint64_t spacing_ticks = std::max<uint64_t>(1, Clock::QueryHostTickFrequency() / 500000);
+  if (previous_host_tick && host_tick - previous_host_tick < spacing_ticks) {
+    ++rapid_calls;
+#if defined(__x86_64__) || defined(_M_X64)
+    _mm_pause();
+#endif
+#if defined(_WIN32)
+    if ((rapid_calls & 0xFF) == 0) {
+      ::SwitchToThread();
+    }
+#endif
+  } else {
+    rapid_calls = 0;
+  }
+  previous_host_tick = host_tick;
+  auto guest_tick_count = UpdateGuestClockAt(host_tick);
   return guest_tick_count;
 }
 
diff --git a/src/core/perf/counter.cpp b/src/core/perf/counter.cpp
index 536009e..97f15f4 100644
--- a/src/core/perf/counter.cpp
+++ b/src/core/perf/counter.cpp
@@ -49,6 +49,7 @@ constexpr const char* kCounterNames[] = {
     "texture_cache_misses",
     "pipeline_cache_hits",
     "pipeline_cache_misses",
+    "frame_number",
 };
 static_assert(std::size(kCounterNames) == kNumCounters, "kCounterNames must match CounterId enum");
 
@@ -72,6 +73,7 @@ constexpr bool kIsGauge[] = {
     false,  // kTextureCacheMisses
     false,  // kPipelineCacheHits
     false,  // kPipelineCacheMisses
+    true,   // kFrameNumber
 };
 static_assert(std::size(kIsGauge) == kNumCounters, "kIsGauge must match CounterId enum");
 
@@ -79,6 +81,7 @@ static_assert(std::size(kIsGauge) == kNumCounters, "kIsGauge must match CounterI
 std::FILE* g_csv_file = nullptr;
 std::string g_csv_path;
 int g_csv_frame_count = 0;
+bool g_csv_initialized = false;
 
 }  // anonymous namespace
 
@@ -126,6 +129,7 @@ void Init() {
 }
 
 void SetCsvLogPath(const std::string& path) {
+  g_csv_initialized = true;
   if (g_csv_file) {
     std::fflush(g_csv_file);
     std::fclose(g_csv_file);
@@ -154,6 +158,7 @@ void SetCsvLogPath(const std::string& path) {
 }
 
 void WriteCsvFrame() {
+  if (!g_csv_initialized) SetCsvLogPath(REXCVAR_GET(perf_log_csv));
   if (!g_csv_file)
     return;
 
diff --git a/src/filesystem/devices/host_path_file.cpp b/src/filesystem/devices/host_path_file.cpp
index 4c57a18..c0d97c9 100644
--- a/src/filesystem/devices/host_path_file.cpp
+++ b/src/filesystem/devices/host_path_file.cpp
@@ -12,8 +12,64 @@
 #include <rex/filesystem/devices/host_path_entry.h>
 #include <rex/filesystem/devices/host_path_file.h>
 
+#include <algorithm>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <mutex>
+#include <vector>
+
 namespace rex::filesystem {
 
+namespace {
+
+// Byte patches served on top of game files, loaded from the folder named by FIFASTREET_MODS.
+// A patch is a file called "<game file>@<hex offset>.bin", for example "[email protected]":
+// its bytes replace the bytes of that game file at that offset whenever the game reads them.
+struct FilePatch {
+  std::string file;
+  uint64_t offset = 0;
+  std::vector<uint8_t> bytes;
+};
+
+std::vector<FilePatch>& Patches() {
+  static std::vector<FilePatch> patches;
+  static std::once_flag loaded;
+  std::call_once(loaded, [] {
+    // Folder of byte patches: FIFASTREET_MODS, or "Mods" next to the Game folder (<install>/Mods).
+    std::filesystem::path dir;
+    if (const char* env = std::getenv("FIFASTREET_MODS"); env && *env) {
+      dir = env;
+    } else {
+      dir = rex::filesystem::GetExecutableFolder().parent_path() / "Mods";
+    }
+    std::error_code ec;
+    if (!std::filesystem::is_directory(dir, ec)) return;
+    for (const auto& item : std::filesystem::directory_iterator(dir, ec)) {
+      if (!item.is_regular_file() || item.path().extension() != ".bin") continue;
+      std::string name = item.path().stem().string();
+      size_t at = name.rfind('@');
+      if (at == std::string::npos) continue;
+      FilePatch patch;
+      patch.file = name.substr(0, at);
+      std::transform(patch.file.begin(), patch.file.end(), patch.file.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+      patch.offset = std::strtoull(name.c_str() + at + 1, nullptr, 16);
+      std::ifstream in(item.path(), std::ios::binary);
+      patch.bytes.assign(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
+      if (!patch.bytes.empty()) {
+        std::fprintf(stderr, "[mods] %s @0x%llx (%zu bytes)", patch.file.c_str(), (unsigned long long)patch.offset, patch.bytes.size());
+        std::fputc(10, stderr);
+        patches.push_back(std::move(patch));
+      }
+    }
+  });
+  return patches;
+}
+
+}  // namespace
+
 HostPathFile::HostPathFile(uint32_t file_access, HostPathEntry* entry,
                            std::unique_ptr<rex::filesystem::FileHandle> file_handle)
     : File(file_access, entry), file_handle_(std::move(file_handle)) {}
@@ -31,6 +87,18 @@ X_STATUS HostPathFile::ReadSync(std::span<uint8_t> buffer, size_t byte_offset,
   }
 
   if (file_handle_->Read(byte_offset, buffer.data(), buffer.size(), out_bytes_read)) {
+    const auto& patches = Patches();
+    if (!patches.empty() && entry_ && out_bytes_read) {
+      std::string name = entry_->name();
+      std::transform(name.begin(), name.end(), name.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+      const uint64_t start = byte_offset, end = byte_offset + *out_bytes_read;
+      for (const auto& patch : patches) {
+        if (patch.file != name) continue;
+        const uint64_t patch_end = patch.offset + patch.bytes.size();
+        const uint64_t from = std::max(start, patch.offset), to = std::min(end, patch_end);
+        if (from < to) std::memcpy(buffer.data() + (from - start), patch.bytes.data() + (from - patch.offset), size_t(to - from));
+      }
+    }
     return X_STATUS_SUCCESS;
   } else {
     return X_STATUS_END_OF_FILE;
diff --git a/src/graphics/command_processor.cpp b/src/graphics/command_processor.cpp
index a744375..a4f27e1 100644
--- a/src/graphics/command_processor.cpp
+++ b/src/graphics/command_processor.cpp
@@ -36,6 +36,15 @@
 #include <rex/system/user_module.h>
 
 REXCVAR_DEFINE_BOOL(vsync, true, "GPU", "Enable vertical sync");
+REXCVAR_DEFINE_BOOL(true_vsync, false, "GPU",
+                    "True VSync: the guest runs unlocked from the display (guest vblank at 1 kHz, frame cap = "
+                    "refresh rate) and the presenter shows the newest frame at every refresh with real VSync, "
+                    "so the frame rate follows the chosen Hz without tearing.");
+
+REXCVAR_DEFINE_BOOL(log_frame_stats, false, "GPU",
+                    "Log guest swap cadence every five seconds: average FPS, worst interval, "
+                    "and intervals longer than 17 ms. Includes loading and pauses.")
+    .lifecycle(rex::cvar::Lifecycle::kHotReload);
 
 REXCVAR_DEFINE_BOOL(clear_memory_page_state, true, "GPU",
                     "Refresh page-valid state from GPU-written memory at frame end. "
@@ -54,6 +63,67 @@ REXCVAR_DEFINE_STRING(readback_resolve, "none", "GPU",
     .allowed({"none", "fast", "some", "full"})
     .lifecycle(rex::cvar::Lifecycle::kHotReload);
 
+REXCVAR_DEFINE_BOOL(readback_some_adaptive, true, "GPU",
+                    "In 'some' readback mode, refresh the guest-memory copy of a resolved range "
+                    "on every resolve once the guest has written to pages overlapping it "
+                    "(prevents stale data being re-uploaded over newer GPU data).")
+    .lifecycle(rex::cvar::Lifecycle::kHotReload);
+
+REXCVAR_DEFINE_INT32(readback_some_hot_frames, 900, "GPU",
+                     "How many frames a range stays refreshed after the guest last invalidated it.")
+    .range(1, 100000)
+    .lifecycle(rex::cvar::Lifecycle::kHotReload);
+
+REXCVAR_DEFINE_BOOL(readback_some_refresh_sporadic, true, "GPU",
+                    "In 'some' readback mode, always refresh ranges that are not resolved on "
+                    "every frame (textures the game builds from GPU results, for example while "
+                    "loading). Only ranges resolved every frame are skipped.")
+    .lifecycle(rex::cvar::Lifecycle::kHotReload);
+
+REXCVAR_DEFINE_STRING(readback_some_skip_addrs, "", "GPU",
+                      "Comma separated hex start addresses of resolve ranges that 'some' readback "
+                      "never refreshes (diagnostics).")
+    .lifecycle(rex::cvar::Lifecycle::kHotReload);
+
+REXCVAR_DEFINE_STRING(readback_some_sync_addrs, "1282B000", "GPU",
+                      "Comma separated hex start addresses of resolve ranges that 'some' readback "
+                      "always refreshes and reads synchronously (diagnostics).")
+    .lifecycle(rex::cvar::Lifecycle::kHotReload);
+
+REXCVAR_DEFINE_INT32(readback_some_sync_below, 3145728, "GPU",
+                     "In 'some' readback mode, ranges smaller than this many bytes that are "
+                     "refreshed are read synchronously for the current frame (like 'full'), "
+                     "instead of one frame late. 0 = off.")
+    .range(0, 1 << 28)
+    .lifecycle(rex::cvar::Lifecycle::kHotReload);
+
+REXCVAR_DEFINE_BOOL(readback_some_sporadic_sync, true, "GPU",
+                    "Read sporadic ranges synchronously (current frame), like 'full'. They are "
+                    "rare, so this costs almost nothing, and the game may build textures from them.")
+    .lifecycle(rex::cvar::Lifecycle::kHotReload);
+
+REXCVAR_DEFINE_INT32(readback_some_refresh_interval, 0, "GPU",
+                     "In 'some' readback mode, also refresh every range once every N resolves "
+                     "(0 = never). Bounds how stale the guest copy can get.")
+    .range(0, 100000)
+    .lifecycle(rex::cvar::Lifecycle::kHotReload);
+
+REXCVAR_DEFINE_INT32(readback_some_refresh_below, 3145728, "GPU",
+                     "In 'some' readback mode, always refresh ranges smaller than this many bytes "
+                     "(cheap to copy). 0 = off.")
+    .range(0, 1 << 28)
+    .lifecycle(rex::cvar::Lifecycle::kHotReload);
+
+REXCVAR_DEFINE_BOOL(readback_some_log, false, "GPU",
+                    "Log the adaptive 'some' readback decisions and guest invalidations.")
+    .lifecycle(rex::cvar::Lifecycle::kHotReload);
+
+REXCVAR_DEFINE_BOOL(readback_resolve_average_color, true, "GPU",
+                    "When draw resolution scaling is active, average each scaled block of 8:8:8:8 color resolves "
+                    "copied back to guest memory (smooth render-to-texture images such as player portraits) "
+                    "instead of picking one sample")
+    .lifecycle(rex::cvar::Lifecycle::kHotReload);
+
 REXCVAR_DEFINE_BOOL(readback_resolve_half_pixel_offset, false, "GPU",
                     "When draw resolution scaling is active, sample from the center of each "
                     "scaled block during resolve readback downscale")
@@ -181,6 +251,144 @@ ReadbackResolveMode CommandProcessor::GetReadbackResolveMode(
                                          : ReadbackResolveMode::kDisabled;
 }
 
+namespace {
+// Parses a comma separated list of hex addresses; cached by string value.
+bool AddressInList(const std::string& list, uint32_t address) {
+  size_t pos = 0;
+  while (pos < list.size()) {
+    size_t end = list.find(',', pos);
+    if (end == std::string::npos) {
+      end = list.size();
+    }
+    if (end > pos) {
+      const uint32_t value = uint32_t(std::strtoul(list.substr(pos, end - pos).c_str(), nullptr, 16));
+      if (value == address) {
+        return true;
+      }
+    }
+    pos = end + 1;
+  }
+  return false;
+}
+}  // namespace
+
+CommandProcessor::SomeDecision CommandProcessor::DecideSomeRefresh(uint64_t key, uint32_t address,
+                                                                    uint32_t length,
+                                                                    uint64_t frame) {
+  some_frame_.store(frame, std::memory_order_relaxed);
+  SomeDecision decision;
+  std::lock_guard<std::mutex> lock(some_mutex_);
+  SomeRangeInfo& info = some_ranges_[key];
+  info.address = address;
+  info.length = length;
+  ++info.calls;
+  // Frame cadence of this range. Several resolves in one frame say nothing, so they keep the streak.
+  if (info.last_frame != 0 && frame > info.last_frame) {
+    if (frame - info.last_frame <= 2) {
+      ++info.streak;
+    } else {
+      info.streak = 0;
+    }
+  }
+  info.last_frame = frame;
+  if (info.first_frame == 0) {
+    info.first_frame = frame;
+  }
+  // Only a range resolved on at least half of all frames since it was first seen counts as "every frame";
+  // one that is merely resolved in bursts keeps being refreshed.
+  const uint64_t age = frame - info.first_frame;
+  const bool every_frame = info.streak >= 8 && age >= 1200 && uint64_t(info.calls) * 2 >= age;
+  const int32_t interval = REXCVAR_GET(readback_some_refresh_interval);
+  const int32_t below = REXCVAR_GET(readback_some_refresh_below);
+  if (REXCVAR_GET(readback_some_adaptive) && frame <= info.hot_until_frame) {
+    decision.refresh = true;
+  } else if (REXCVAR_GET(readback_some_refresh_sporadic) && !every_frame) {
+    decision.refresh = true;
+    decision.sync = REXCVAR_GET(readback_some_sporadic_sync);
+  } else if (interval > 0 && info.calls % uint32_t(interval) == 0) {
+    decision.refresh = true;
+  } else if (below > 0 && length < uint32_t(below)) {
+    decision.refresh = true;
+  }
+  ++some_decisions_;
+  if (REXCVAR_GET(readback_some_log) && frame >= some_last_table_frame_ + 600) {
+    some_last_table_frame_ = frame;
+    std::vector<std::pair<uint64_t, const SomeRangeInfo*>> rows;
+    for (const auto& [row_key, row] : some_ranges_) {
+      rows.emplace_back(row_key, &row);
+    }
+    std::sort(rows.begin(), rows.end(), [](const auto& a, const auto& b) {
+      return uint64_t(a.second->length) * a.second->calls > uint64_t(b.second->length) * b.second->calls;
+    });
+    REXGPU_INFO("[SOMETABLE] frame={} ranges={} (sorted by bytes resolved)", frame, rows.size());
+    for (size_t i = 0; i < rows.size() && i < 40; ++i) {
+      const SomeRangeInfo& row = *rows[i].second;
+      REXGPU_INFO(
+          "[SOMETABLE] {:08X}+{:X} ({:.2f} MB) calls={} skipped={} refreshed={} streak={} hits={} stale={}",
+          row.address, row.length, row.length / 1048576.0, row.calls, row.skipped, row.refreshed,
+          row.streak, row.hits, row.stale);
+    }
+  }
+  // After skipped resolves the double-buffer slots hold old data, so the first refresh must read
+  // the slot that was just written.
+  const int32_t sync_below = REXCVAR_GET(readback_some_sync_below);
+  if (decision.refresh && sync_below > 0 && length < uint32_t(sync_below)) {
+    decision.sync = true;
+  }
+  decision.sync = decision.sync || (decision.refresh && info.stale);
+  const std::string skip_addrs = REXCVAR_GET(readback_some_skip_addrs);
+  const std::string sync_addrs = REXCVAR_GET(readback_some_sync_addrs);
+  if (!skip_addrs.empty() && AddressInList(skip_addrs, address)) {
+    decision = SomeDecision{};
+  } else if (!sync_addrs.empty() && AddressInList(sync_addrs, address)) {
+    decision.refresh = true;
+    decision.sync = true;
+  }
+  return decision;
+}
+
+void CommandProcessor::NoteSomeRangeSkipped(uint64_t key) {
+  std::lock_guard<std::mutex> lock(some_mutex_);
+  SomeRangeInfo& info = some_ranges_[key];
+  ++info.skipped;
+  info.stale = true;
+}
+
+void CommandProcessor::NoteSomeRangeRefreshed(uint64_t key) {
+  std::lock_guard<std::mutex> lock(some_mutex_);
+  SomeRangeInfo& info = some_ranges_[key];
+  ++info.refreshed;
+  info.stale = false;
+}
+
+void CommandProcessor::OnGuestInvalidatedRange(uint32_t start, uint32_t length) {
+  if (!length) {
+    return;
+  }
+  const uint64_t end = uint64_t(start) + length;
+  const uint64_t frame = some_frame_.load(std::memory_order_relaxed);
+  const bool log = REXCVAR_GET(readback_some_log);
+  const uint64_t hot_frames = uint64_t(REXCVAR_GET(readback_some_hot_frames));
+  std::lock_guard<std::mutex> lock(some_mutex_);
+  for (auto& [key, info] : some_ranges_) {
+    if (uint64_t(info.address) >= end || uint64_t(info.address) + info.length <= start) {
+      continue;
+    }
+    ++info.hits;
+    if (info.stale) {
+      info.hot_until_frame = frame + hot_frames;
+    }
+    if (log && some_hit_logs_ < 200) {
+      ++some_hit_logs_;
+      REXGPU_INFO(
+          "[SOME] guest invalidated {:08X}+{:X} over range {:08X}+{:X} (key {:016X}, calls={} "
+          "skipped={} refreshed={} stale={} hits={})",
+          start, length, info.address, info.length, key, info.calls, info.skipped, info.refreshed,
+          info.stale, info.hits);
+    }
+  }
+}
+
 bool CommandProcessor::IsReadbackMemexportEnabled(bool legacy_backend_flag) const {
   if (legacy_readback_memexport_cvar_name_ &&
       rex::cvar::HasNonDefaultValue(legacy_readback_memexport_cvar_name_)) {
@@ -930,6 +1138,33 @@ bool CommandProcessor::ExecutePacketType3_XE_SWAP(memory::RingBuffer* reader, ui
                                                   uint32_t count) {
   SCOPE_profile_cpu_f("gpu");
 
+  if (REXCVAR_GET(log_frame_stats)) {
+    uint64_t now = rex::chrono::Clock::QueryHostTickCount();
+    uint64_t frequency = rex::chrono::Clock::QueryHostTickFrequency();
+    if (frame_stats_last_tick_) {
+      uint64_t interval = now - frame_stats_last_tick_;
+      ++frame_stats_count_;
+      frame_stats_max_ticks_ = std::max(frame_stats_max_ticks_, interval);
+      frame_stats_over_17ms_ += double(interval) * 1000.0 / double(frequency) > 17.0;
+      uint64_t elapsed = now - frame_stats_start_tick_;
+      if (elapsed >= frequency * 5) {
+        REXGPU_INFO("Guest frame timing: {:.2f} FPS average, {:.2f} ms worst interval, "
+                    "{}/{} intervals over 17 ms (includes loading/pauses)",
+                    double(frame_stats_count_) * double(frequency) / double(elapsed),
+                    double(frame_stats_max_ticks_) * 1000.0 / double(frequency),
+                    frame_stats_over_17ms_, frame_stats_count_);
+        frame_stats_start_tick_ = now;
+        frame_stats_count_ = frame_stats_max_ticks_ = frame_stats_over_17ms_ = 0;
+      }
+    } else {
+      frame_stats_start_tick_ = now;
+    }
+    frame_stats_last_tick_ = now;
+  } else {
+    frame_stats_last_tick_ = frame_stats_start_tick_ = 0;
+    frame_stats_count_ = frame_stats_max_ticks_ = frame_stats_over_17ms_ = 0;
+  }
+
 #ifdef REXGLUE_ENABLE_PERF_COUNTERS
   {
     static uint64_t last_frame_tick = 0;
@@ -943,6 +1178,7 @@ bool CommandProcessor::ExecutePacketType3_XE_SWAP(memory::RingBuffer* reader, ui
     last_frame_tick = now;
   }
 #endif
+  PERF_counter_set(kFrameNumber, counter_ + 1);
   rex::perf::Profiler::Flip();
 
   // Xenia-specific VdSwap hook.
diff --git a/src/graphics/d3d12/command_processor.cpp b/src/graphics/d3d12/command_processor.cpp
index 19874a5..f543162 100644
--- a/src/graphics/d3d12/command_processor.cpp
+++ b/src/graphics/d3d12/command_processor.cpp
@@ -10,6 +10,7 @@
  */
 
 #include <algorithm>
+#include <chrono>
 #include <cstdarg>
 #include <cstring>
 #include <sstream>
@@ -35,6 +36,41 @@
 REXCVAR_DEFINE_BOOL(d3d12_bindless, true, "GPU/D3D12", "Use bindless resources where available")
     .lifecycle(rex::cvar::Lifecycle::kRequiresRestart);
 
+REXCVAR_DEFINE_BOOL(log_resolve_timing, false, "GPU/D3D12",
+                    "Log aggregate resolve readback timing every five seconds");
+
+REXCVAR_DEFINE_BOOL(d3d12_readback_short_wait, false, "GPU/D3D12",
+                    "Poll full resolve fences briefly before sleeping");
+
+REXCVAR_DEFINE_UINT32(d3d12_readback_spin_us, 200, "GPU/D3D12",
+                     "Maximum CPU polling time before the blocking full-readback wait");
+// Fence wait limit for the current CheckSubmissionFence (set only around the budgeted floor readback, on the
+// command processor thread); INFINITE otherwise.
+static thread_local DWORD g_fence_wait_timeout_ms = INFINITE;
+
+static void NoteReadbackBudget(bool fresh, double waited_us) {
+  // Diagnostics for the budgeted floor readback: how often the GPU was done in time.
+  static uint64_t fresh_count = 0, stale_count = 0;
+  static double max_us = 0;
+  static auto window = std::chrono::steady_clock::now();
+  (fresh ? fresh_count : stale_count) += 1;
+  max_us = std::max(max_us, waited_us);
+  if (std::chrono::steady_clock::now() - window >= std::chrono::seconds(5)) {
+    REXGPU_INFO("Readback sync budget: current_frame={} previous_frame={} max_wait_us={:.0f}", fresh_count,
+                stale_count, max_us);
+    fresh_count = stale_count = 0;
+    max_us = 0;
+    window = std::chrono::steady_clock::now();
+  }
+}
+
+REXCVAR_DEFINE_UINT32(d3d12_readback_sync_budget_us, 0, "GPU/D3D12",
+                     "'some' readback ranges read synchronously (readback_some_sync_*): wait at most this long "
+                     "for the GPU, then use the previous frame's copy instead (0 = always wait)");
+
+REXCVAR_DEFINE_UINT32(d3d12_resolve_readback_max_bytes, 0, "GPU/D3D12",
+                     "Experimental CPU resolve readback size ceiling; zero preserves full readback");
+
 REXCVAR_DEFINE_BOOL(d3d12_readback_memexport, false, "GPU/D3D12",
                     "Read data written by memory export in shaders on the CPU")
     .lifecycle(rex::cvar::Lifecycle::kHotReload);
@@ -930,6 +966,8 @@ bool D3D12CommandProcessor::SetupContext() {
     REXGPU_ERROR("Failed to initialize shared memory");
     return false;
   }
+  shared_memory_->SetInvalidationObserver(
+      [this](uint32_t start, uint32_t length) { OnGuestInvalidatedRange(start, length); });
 
   // Initialize the render target cache before configuring binding - need to
   // know if using rasterizer-ordered views for the bindless root signature.
@@ -1672,6 +1710,11 @@ void D3D12CommandProcessor::ShutdownContext() {
   scratch_buffer_size_ = 0;
   resolve_downscale_buffer_size_ = 0;
   resolve_downscale_buffer_.Reset();
+  resolve_timing_readback_.Reset();
+  resolve_timing_query_heap_.Reset();
+  resolve_timing_frequency_ = 0;
+  resolve_timing_sample_counter_ = 0;
+  resolve_timing_submission_ = 0;
 
   for (const std::pair<uint64_t, ID3D12Resource*>& resource_for_deletion :
        resources_for_deletion_) {
@@ -1735,6 +1778,9 @@ void D3D12CommandProcessor::ShutdownContext() {
 
   render_target_cache_.reset();
 
+  if (shared_memory_) {
+    shared_memory_->SetInvalidationObserver(nullptr);
+  }
   shared_memory_.reset();
 
   deferred_command_list_.Reset();
@@ -2784,6 +2830,11 @@ bool D3D12CommandProcessor::IssueDraw_MemexportReadbackFastPath(uint32_t total_s
       MakeMemexportReadbackKey(memexport_ranges_.front().base_address_dwords, total_size);
   ReadbackBuffer& readback = memexport_readback_buffers_[readback_key];
   readback.last_used_frame = frame_current_;
+  std::vector<std::pair<uint32_t, uint32_t>> current_ranges;
+  current_ranges.reserve(memexport_ranges_.size());
+  for (const auto& range : memexport_ranges_) {
+    current_ranges.emplace_back(range.base_address_dwords, range.size_bytes);
+  }
 
   auto ensure_readback_slot = [&](uint32_t index, uint32_t size) -> bool {
     if (readback.buffers[index] && readback.mapped_data[index] && size <= readback.sizes[index]) {
@@ -2847,11 +2898,13 @@ bool D3D12CommandProcessor::IssueDraw_MemexportReadbackFastPath(uint32_t total_s
   }
   readback.submission_written[write_index] = submission_current_;
   readback.written_size[write_index] = total_size;
+  readback.memexport_ranges[write_index] = current_ranges;
 
   CheckSubmissionFence(0);
   bool previous_slot_ready = readback.buffers[read_index] && readback.mapped_data[read_index] &&
                              total_size <= readback.sizes[read_index] &&
                              total_size <= readback.written_size[read_index] &&
+                             readback.memexport_ranges[read_index] == current_ranges &&
                              readback.submission_written[read_index] &&
                              readback.submission_written[read_index] <= submission_completed_;
   if (!previous_slot_ready) {
@@ -2887,6 +2940,54 @@ bool D3D12CommandProcessor::IssueCopy() {
 }
 
 bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
+  using ResolveClock = std::chrono::steady_clock;
+  struct ResolveTiming {
+    struct Range {
+      uint64_t calls = 0, bytes = 0;
+      double total_ms = 0;
+    };
+    ResolveClock::time_point interval_start = ResolveClock::now();
+    uint64_t calls = 0, bytes = 0;
+    double total_ms = 0, wait_ms = 0, worst_ms = 0;
+    uint64_t gpu_samples = 0;
+    double gpu_resolve_ms = 0, gpu_downscale_ms = 0, gpu_copy_ms = 0;
+    uint64_t gpu_pre_resolve_samples = 0;
+    double gpu_pre_resolve_ms = 0;
+    std::unordered_map<uint64_t, Range> ranges;
+  };
+  static thread_local ResolveTiming timing;
+  const bool measure = REXCVAR_GET(log_resolve_timing);
+  const auto started = measure ? ResolveClock::now() : ResolveClock::time_point{};
+  bool gpu_sample = measure &&
+      GetReadbackResolveMode(REXCVAR_GET(d3d12_readback_resolve)) == ReadbackResolveMode::kFull &&
+      (++resolve_timing_sample_counter_ % 64 == 0);
+  if (gpu_sample && !resolve_timing_query_heap_) {
+    const auto& provider = GetD3D12Provider();
+    ID3D12Device* device = provider.GetDevice();
+    D3D12_QUERY_HEAP_DESC heap_desc = {};
+    heap_desc.Type = D3D12_QUERY_HEAP_TYPE_TIMESTAMP;
+    heap_desc.Count = 5;
+    D3D12_RESOURCE_DESC buffer_desc;
+    ui::d3d12::util::FillBufferResourceDesc(buffer_desc, sizeof(uint64_t) * 5,
+                                          D3D12_RESOURCE_FLAG_NONE);
+    if (FAILED(provider.GetDirectQueue()->GetTimestampFrequency(&resolve_timing_frequency_)) ||
+        !resolve_timing_frequency_ ||
+        FAILED(device->CreateQueryHeap(&heap_desc, IID_PPV_ARGS(&resolve_timing_query_heap_))) ||
+        FAILED(device->CreateCommittedResource(&ui::d3d12::util::kHeapPropertiesReadback,
+            provider.GetHeapFlagCreateNotZeroed(), &buffer_desc,
+            D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&resolve_timing_readback_)))) {
+      resolve_timing_query_heap_.Reset();
+      resolve_timing_readback_.Reset();
+      REXGPU_WARN("Resolve GPU timing resources unavailable; readback remains unchanged");
+    }
+  }
+  gpu_sample = gpu_sample && resolve_timing_query_heap_ && resolve_timing_readback_;
+  if (gpu_sample) {
+    deferred_command_list_.D3DEndQuery(resolve_timing_query_heap_.Get(),
+                                      D3D12_QUERY_TYPE_TIMESTAMP, 0);
+  }
+  const bool gpu_submission_sample = gpu_sample &&
+      resolve_timing_submission_ == submission_current_;
   uint32_t written_address, written_length;
   if (!render_target_cache_->Resolve(*memory_, *shared_memory_, *texture_cache_, written_address,
                                      written_length)) {
@@ -2897,14 +2998,39 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
     return true;
   }
 
+  // Diagnostic experiment only: Resolve has already updated GPU memory.
+  // A size ceiling does not prove that guest CPU reads of larger targets are
+  // unnecessary, so leave it disabled unless explicitly testing this hypothesis.
+  const uint32_t readback_ceiling = REXCVAR_GET(d3d12_resolve_readback_max_bytes);
+  if (readback_ceiling && written_length > readback_ceiling) {
+    return true;
+  }
+
   if (!memory_->TranslatePhysical(written_address)) {
     return true;
   }
 
+  if (gpu_sample) {
+    deferred_command_list_.D3DEndQuery(resolve_timing_query_heap_.Get(),
+                                      D3D12_QUERY_TYPE_TIMESTAMP, 1);
+  }
   bool is_scaled = texture_cache_->IsDrawResolutionScaled();
   uint64_t resolve_key = MakeReadbackResolveKey(written_address, written_length);
   ReadbackBuffer& rb = readback_buffers_[resolve_key];
   rb.last_used_frame = frame_current_;
+  ReadbackResolveMode readback_mode = GetReadbackResolveMode(REXCVAR_GET(d3d12_readback_resolve));
+  // Some only copies into guest memory on a cache miss. Once both slots are
+  // initialized, recording another GPU-to-CPU copy cannot change its result.
+  // Keep Resolve above: subsequent draws still need the GPU-side texture data.
+  SomeDecision some_decision;
+  if (readback_mode == ReadbackResolveMode::kSome) {
+    some_decision = DecideSomeRefresh(resolve_key, written_address, written_length, frame_current_);
+    if (!some_decision.refresh && rb.mapped_data[0] && rb.mapped_data[1] &&
+        rb.written_size[0] >= written_length && rb.written_size[1] >= written_length) {
+      NoteSomeRangeSkipped(resolve_key);
+      return true;
+    }
+  }
 
   uint32_t write_index = rb.current_index;
   uint32_t size = AlignReadbackBufferSize(written_length);
@@ -2922,6 +3048,10 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
       return true;
     }
     if (rb.buffers[write_index]) {
+      if (!AwaitAllQueueOperationsCompletion()) {
+        buffer->Release();
+        return true;
+      }
       if (rb.mapped_data[write_index]) {
         rb.buffers[write_index]->Unmap(0, nullptr);
         rb.mapped_data[write_index] = nullptr;
@@ -3042,6 +3172,18 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
                                    (constants.scale_x > 1 || constants.scale_y > 1))
                                       ? 1u
                                       : 0u;
+    // Color render-to-texture copies (player face portraits) are averaged; depth and other formats stay
+    // point-sampled, an average of their bits would be meaningless.
+    {
+      const auto copy_control = register_file_->Get<reg::RB_COPY_CONTROL>();
+      const auto dest_format = copy_dest_info.copy_dest_format;
+      constants.average = (REXCVAR_GET(readback_resolve_average_color) && pixel_size_log2 == 2 &&
+                           copy_control.copy_src_select != 4 &&
+                           (dest_format == xenos::ColorFormat::k_8_8_8_8 ||
+                            dest_format == xenos::ColorFormat::k_8_8_8_8_A))
+                              ? 1u
+                              : 0u;
+    }
     deferred_command_list_.D3DSetComputeRoot32BitConstants(
         UINT(ResolveDownscaleRootParameter::kConstants), sizeof(constants) / sizeof(uint32_t),
         &constants, 0);
@@ -3055,6 +3197,10 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
     PushTransitionBarrier(resolve_downscale_buffer_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
                           D3D12_RESOURCE_STATE_COPY_SOURCE);
     SubmitBarriers();
+    if (gpu_sample) {
+      deferred_command_list_.D3DEndQuery(resolve_timing_query_heap_.Get(),
+                                        D3D12_QUERY_TYPE_TIMESTAMP, 2);
+    }
     deferred_command_list_.D3DCopyBufferRegion(rb.buffers[write_index], 0,
                                                resolve_downscale_buffer_.Get(), 0, written_length);
     PushTransitionBarrier(resolve_downscale_buffer_.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE,
@@ -3065,23 +3211,88 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
     shared_memory_->UseAsCopySource();
     SubmitBarriers();
     ID3D12Resource* shared_memory_buffer = shared_memory_->GetBuffer();
+    if (gpu_sample) {
+      deferred_command_list_.D3DEndQuery(resolve_timing_query_heap_.Get(),
+                                        D3D12_QUERY_TYPE_TIMESTAMP, 2);
+    }
     deferred_command_list_.D3DCopyBufferRegion(rb.buffers[write_index], 0, shared_memory_buffer,
                                                written_address, written_length);
   }
 
-  ReadbackResolveMode readback_mode = GetReadbackResolveMode(REXCVAR_GET(d3d12_readback_resolve));
+  if (gpu_sample) {
+    deferred_command_list_.D3DEndQuery(resolve_timing_query_heap_.Get(),
+                                      D3D12_QUERY_TYPE_TIMESTAMP, 3);
+    deferred_command_list_.D3DResolveQueryData(resolve_timing_query_heap_.Get(),
+        D3D12_QUERY_TYPE_TIMESTAMP, 0, gpu_submission_sample ? 5 : 4,
+        resolve_timing_readback_.Get(), 0);
+  }
+  rb.submission_written[write_index] = submission_current_;
+  rb.written_size[write_index] = written_length;
   bool use_delayed_sync =
       readback_mode == ReadbackResolveMode::kFast || readback_mode == ReadbackResolveMode::kSome;
   uint32_t read_index = write_index;
   if (use_delayed_sync) {
     read_index = 1 - write_index;
-  } else if (!AwaitAllQueueOperationsCompletion()) {
-    return true;
+  } else {
+    const auto wait_started = measure ? ResolveClock::now() : ResolveClock::time_point{};
+    const bool completed = AwaitAllQueueOperationsCompletion(
+        REXCVAR_GET(d3d12_readback_short_wait));
+    if (measure) {
+      timing.wait_ms += std::chrono::duration<double, std::milli>(
+          ResolveClock::now() - wait_started).count();
+    }
+    if (!completed) {
+      return true;
+    }
   }
 
+  if (gpu_sample) {
+    // The existing full-readback wait also completes these timestamps.
+    void* mapping = nullptr;
+    D3D12_RANGE read_range = {0, sizeof(uint64_t) * (gpu_submission_sample ? 5 : 4)};
+    if (SUCCEEDED(resolve_timing_readback_->Map(0, &read_range, &mapping))) {
+      const auto* stamps = static_cast<const uint64_t*>(mapping);
+      if (stamps[0] <= stamps[1] && stamps[1] <= stamps[2] && stamps[2] <= stamps[3]) {
+        const double milliseconds_per_tick = 1000.0 / double(resolve_timing_frequency_);
+        timing.gpu_resolve_ms += double(stamps[1] - stamps[0]) * milliseconds_per_tick;
+        timing.gpu_downscale_ms += double(stamps[2] - stamps[1]) * milliseconds_per_tick;
+        timing.gpu_copy_ms += double(stamps[3] - stamps[2]) * milliseconds_per_tick;
+        ++timing.gpu_samples;
+        if (gpu_submission_sample && stamps[4] <= stamps[0]) {
+          timing.gpu_pre_resolve_ms += double(stamps[0] - stamps[4]) * milliseconds_per_tick;
+          ++timing.gpu_pre_resolve_samples;
+        }
+      }
+      D3D12_RANGE no_writes = {0, 0};
+      resolve_timing_readback_->Unmap(0, &no_writes);
+    }
+  }
   bool is_cache_miss = false;
-  if (use_delayed_sync && (!rb.buffers[read_index] || written_length > rb.sizes[read_index] ||
-                           !rb.mapped_data[read_index])) {
+  // A forced-synchronous range (e.g. the stadium floor data) normally stalls until the GPU is done, which
+  // costs about a third of the frame rate. With a budget: if the GPU finishes within it, read this frame's
+  // data; otherwise use last frame's copy (what the delayed path does), so fast GPUs keep current data
+  // without a long stall and slow GPUs never wait more than the budget.
+  const bool previous_copy_usable = rb.buffers[read_index] && written_length <= rb.sizes[read_index] &&
+                                    rb.mapped_data[read_index] && rb.submission_written[read_index];
+  const uint32_t sync_budget_us = REXCVAR_GET(d3d12_readback_sync_budget_us);
+  bool budget_decided = false;
+  if (use_delayed_sync && some_decision.sync && previous_copy_usable && sync_budget_us) {
+    // The normal full wait (ends the submission, reclaims and downloads as usual), limited to the budget.
+    const auto budget_start = std::chrono::steady_clock::now();
+    g_fence_wait_timeout_ms = std::max<DWORD>(1, DWORD((sync_budget_us + 999) / 1000));
+    const bool completed = AwaitAllQueueOperationsCompletion();
+    g_fence_wait_timeout_ms = INFINITE;
+    if (completed) {
+      is_cache_miss = true;
+      read_index = write_index;
+    }
+    NoteReadbackBudget(completed, std::chrono::duration<double, std::micro>(
+                                      std::chrono::steady_clock::now() - budget_start).count());
+    budget_decided = true;
+  }
+  if (!budget_decided && use_delayed_sync &&
+      (some_decision.sync || !rb.buffers[read_index] || written_length > rb.sizes[read_index] ||
+       !rb.mapped_data[read_index])) {
     is_cache_miss = true;
     read_index = write_index;
     if (!AwaitAllQueueOperationsCompletion()) {
@@ -3089,7 +3300,16 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
     }
   }
 
-  bool should_copy = (readback_mode == ReadbackResolveMode::kSome) ? is_cache_miss : true;
+  bool should_copy = (readback_mode == ReadbackResolveMode::kSome)
+                         ? (is_cache_miss || some_decision.refresh)
+                         : true;
+  if (should_copy && rb.submission_written[read_index] &&
+      rb.submission_written[read_index] > submission_completed_) {
+    CheckSubmissionFence(rb.submission_written[read_index]);
+    if (rb.submission_written[read_index] > submission_completed_) {
+      return true;
+    }
+  }
   if (should_copy && rb.buffers[read_index] && written_length <= rb.sizes[read_index] &&
       rb.mapped_data[read_index]) {
     uint8_t* destination = memory_->TranslatePhysical(written_address);
@@ -3097,12 +3317,76 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
       std::memcpy(destination, static_cast<uint8_t*>(rb.mapped_data[read_index]), written_length);
     }
   }
+  if (readback_mode == ReadbackResolveMode::kSome) {
+    if (should_copy) {
+      NoteSomeRangeRefreshed(resolve_key);
+    } else {
+      NoteSomeRangeSkipped(resolve_key);
+    }
+  }
 
   rb.current_index = 1 - rb.current_index;
+  if (measure) {
+    const auto finished = ResolveClock::now();
+    const double elapsed_ms =
+        std::chrono::duration<double, std::milli>(finished - started).count();
+    ++timing.calls;
+    timing.bytes += written_length;
+    timing.total_ms += elapsed_ms;
+    timing.worst_ms = std::max(timing.worst_ms, elapsed_ms);
+    auto& range_timing = timing.ranges[resolve_key];
+    ++range_timing.calls;
+    range_timing.bytes += written_length;
+    range_timing.total_ms += elapsed_ms;
+    const double interval_s =
+        std::chrono::duration<double>(finished - timing.interval_start).count();
+    if (interval_s >= 5.0) {
+      REXGPU_INFO("Resolve timing: calls={} interval={:.2f}s total={:.2f}ms "
+                  "wait={:.2f}ms worst={:.2f}ms bytes={} mode={}",
+                  timing.calls, interval_s, timing.total_ms, timing.wait_ms,
+                  timing.worst_ms, timing.bytes, int(readback_mode));
+      if (timing.gpu_samples) {
+        REXGPU_INFO("Resolve GPU timing: samples={} resolve={:.4f}ms downscale={:.4f}ms "
+                    "copy={:.4f}ms (sample means; includes stage barriers)",
+                    timing.gpu_samples, timing.gpu_resolve_ms / timing.gpu_samples,
+                    timing.gpu_downscale_ms / timing.gpu_samples,
+                    timing.gpu_copy_ms / timing.gpu_samples);
+      }
+      if (timing.gpu_pre_resolve_samples) {
+        REXGPU_INFO("Resolve GPU preceding work: samples={} queued={:.4f}ms "
+                    "(submission start to resolve; sample mean)",
+                    timing.gpu_pre_resolve_samples,
+                    timing.gpu_pre_resolve_ms / timing.gpu_pre_resolve_samples);
+      }
+      std::vector<std::pair<uint64_t, ResolveTiming::Range>> hottest(
+          timing.ranges.begin(), timing.ranges.end());
+      std::sort(hottest.begin(), hottest.end(), [](const auto& a, const auto& b) {
+        return a.second.total_ms > b.second.total_ms;
+      });
+      for (size_t i = 0; i < std::min(size_t(8), hottest.size()); ++i) {
+        REXGPU_INFO("Resolve range: key={:016X} calls={} bytes={} total={:.2f}ms",
+                    hottest[i].first, hottest[i].second.calls,
+                    hottest[i].second.bytes, hottest[i].second.total_ms);
+      }
+      timing = ResolveTiming{};
+    }
+  }
   return true;
 }
 
-void D3D12CommandProcessor::CheckSubmissionFence(uint64_t await_submission) {
+void D3D12CommandProcessor::CheckSubmissionFence(uint64_t await_submission,
+                                                bool short_readback_wait) {
+  // Separate command recording/submission cost from GPU fence waiting.
+  // Timing is diagnostic only and never changes completion requirements.
+  using WaitClock = std::chrono::steady_clock;
+  const bool measure_readback = short_readback_wait && REXCVAR_GET(log_resolve_timing);
+  struct ReadbackWaitStats {
+    WaitClock::time_point interval_start = WaitClock::now();
+    uint64_t calls = 0, polled_complete = 0, slept = 0;
+    double submit_ms = 0, poll_ms = 0, sleep_ms = 0, cleanup_ms = 0;
+  };
+  static thread_local ReadbackWaitStats wait_stats;
+  const auto phase_started = measure_readback ? WaitClock::now() : WaitClock::time_point{};
   if (await_submission >= submission_current_) {
     if (submission_open_) {
       EndSubmission(false);
@@ -3114,9 +3398,9 @@ void D3D12CommandProcessor::CheckSubmissionFence(uint64_t await_submission) {
     if (queue_operations_done_since_submission_signal_) {
       UINT64 fence_value = ++queue_operations_since_submission_fence_last_;
       ID3D12CommandQueue* direct_queue = GetD3D12Provider().GetDirectQueue();
-      if (SUCCEEDED(direct_queue->Signal(queue_operations_since_submission_fence_, fence_value) &&
-                    SUCCEEDED(queue_operations_since_submission_fence_->SetEventOnCompletion(
-                        fence_value, fence_completion_event_)))) {
+      if (SUCCEEDED(direct_queue->Signal(queue_operations_since_submission_fence_, fence_value)) &&
+          SUCCEEDED(queue_operations_since_submission_fence_->SetEventOnCompletion(
+              fence_value, fence_completion_event_))) {
         PROFILE_CMD_BUFFER_STALL();
         WaitForSingleObject(fence_completion_event_, INFINITE);
         queue_operations_done_since_submission_signal_ = false;
@@ -3131,19 +3415,50 @@ void D3D12CommandProcessor::CheckSubmissionFence(uint64_t await_submission) {
     await_submission = submission_current_ - 1;
   }
 
+  const auto submit_finished = measure_readback ? WaitClock::now() : WaitClock::time_point{};
   uint64_t submission_completed_before = submission_completed_;
   submission_completed_ = submission_fence_->GetCompletedValue();
+  if (short_readback_wait && submission_completed_ < await_submission) {
+    // Full readback still requires this exact submission. Avoid a kernel sleep
+    // for very short GPU work, but bound CPU polling before the normal wait.
+    const auto deadline = std::chrono::steady_clock::now() + std::chrono::microseconds(
+        std::min(uint32_t(1000), REXCVAR_GET(d3d12_readback_spin_us)));
+    do {
+      YieldProcessor();
+      submission_completed_ = submission_fence_->GetCompletedValue();
+    } while (submission_completed_ < await_submission &&
+             std::chrono::steady_clock::now() < deadline);
+  }
+  const auto poll_finished = measure_readback ? WaitClock::now() : WaitClock::time_point{};
+  const bool needs_sleep = submission_completed_ < await_submission;
   if (submission_completed_ < await_submission) {
     if (SUCCEEDED(
             submission_fence_->SetEventOnCompletion(await_submission, fence_completion_event_))) {
       PROFILE_CMD_BUFFER_STALL();
-      WaitForSingleObject(fence_completion_event_, INFINITE);
+      WaitForSingleObject(fence_completion_event_, g_fence_wait_timeout_ms);
       submission_completed_ = submission_fence_->GetCompletedValue();
     }
   }
-  if (submission_completed_ < await_submission) {
+  if (submission_completed_ < await_submission && g_fence_wait_timeout_ms == INFINITE) {
     REXGPU_ERROR("Failed to await a submission completion Direct3D 12 fence");
   }
+  const auto wait_finished = measure_readback ? WaitClock::now() : WaitClock::time_point{};
+  if (measure_readback) {
+    ++wait_stats.calls;
+    wait_stats.polled_complete += !needs_sleep;
+    wait_stats.slept += needs_sleep;
+    wait_stats.submit_ms += std::chrono::duration<double, std::milli>(submit_finished - phase_started).count();
+    wait_stats.poll_ms += std::chrono::duration<double, std::milli>(poll_finished - submit_finished).count();
+    wait_stats.sleep_ms += std::chrono::duration<double, std::milli>(wait_finished - poll_finished).count();
+    if (wait_finished - wait_stats.interval_start >= std::chrono::seconds(5)) {
+      REXGPU_INFO("D3D12ReadbackWait: calls={} no_sleep={} slept={} submit={:.3f}ms poll={:.3f}ms sleep={:.3f}ms budget_us={}",
+          wait_stats.calls, wait_stats.polled_complete, wait_stats.slept,
+          wait_stats.submit_ms, wait_stats.poll_ms, wait_stats.sleep_ms,
+          std::min(uint32_t(1000), REXCVAR_GET(d3d12_readback_spin_us)));
+      wait_stats = ReadbackWaitStats{};
+    }
+  }
+
   if (submission_completed_ <= submission_completed_before) {
     // Not updated - no need to reclaim or download things.
     return;
@@ -3302,6 +3617,12 @@ bool D3D12CommandProcessor::BeginSubmission(bool is_guest_command) {
     // end of the submission (when async pipeline creation requests are
     // fulfilled).
     deferred_command_list_.Reset();
+    if (resolve_timing_query_heap_ && REXCVAR_GET(log_resolve_timing) &&
+        GetReadbackResolveMode(REXCVAR_GET(d3d12_readback_resolve)) == ReadbackResolveMode::kFull) {
+      deferred_command_list_.D3DEndQuery(resolve_timing_query_heap_.Get(),
+                                        D3D12_QUERY_TYPE_TIMESTAMP, 4);
+      resolve_timing_submission_ = submission_current_;
+    }
 
     // Reset cached state of the command list.
     ff_viewport_update_needed_ = true;
@@ -4432,7 +4753,7 @@ bool D3D12CommandProcessor::UpdateBindings(const D3D12Shader* vertex_shader,
       for (size_t i = 0; i < texture_count_pixel; ++i) {
         const D3D12Shader::TextureBinding& texture = (*textures_pixel)[i];
         descriptor_indices[texture.bindless_descriptor_index] =
-            texture_cache_->GetActiveTextureBindlessSRVIndex(texture) -
+            texture_cache_->GetActiveTextureBindlessSRVIndex(texture, pixel_shader->ucode_data_hash()) -
             uint32_t(SystemBindlessView::kUnboundedSRVsStart);
       }
       current_texture_layout_uid_pixel_ = texture_layout_uid_pixel;
@@ -4755,7 +5076,10 @@ void D3D12CommandProcessor::EvictOldReadbackBuffers(
     ReadbackBuffer& readback = it->second;
     bool evict =
         buffer_map.size() > kMaxReadbackBuffers || readback.last_used_frame < eviction_frame_floor;
-    if (!evict) {
+    // A readback resource may still be referenced by a deferred or submitted
+    // command list, including when the cache exceeds its soft size limit.
+    if (!evict || readback.submission_written[0] > submission_completed_ ||
+        readback.submission_written[1] > submission_completed_) {
       ++it;
       continue;
     }
diff --git a/src/graphics/d3d12/pipeline_cache.cpp b/src/graphics/d3d12/pipeline_cache.cpp
index 8e6b854..ab5a70b 100644
--- a/src/graphics/d3d12/pipeline_cache.cpp
+++ b/src/graphics/d3d12/pipeline_cache.cpp
@@ -11,6 +11,8 @@
 
 #include "thirdparty/dxbc/DXBCChecksum.h"
 
+#include <d3d11shader.h>
+
 #include <algorithm>
 #include <atomic>
 #include <cinttypes>
@@ -78,6 +80,8 @@ namespace shaders {
 #include "../shaders/bytecode/d3d12_5_1/discrete_triangle_3cp_hs.h"
 #include "../shaders/bytecode/d3d12_5_1/float24_round_ps.h"
 #include "../shaders/bytecode/d3d12_5_1/float24_truncate_ps.h"
+#include "../shaders/bytecode/d3d12_5_1/float24_round_ps_position_only.h"
+#include "../shaders/bytecode/d3d12_5_1/float24_truncate_ps_position_only.h"
 #include "../shaders/bytecode/d3d12_5_1/tessellation_adaptive_vs.h"
 #include "../shaders/bytecode/d3d12_5_1/tessellation_indexed_vs.h"
 }  // namespace shaders
@@ -2843,11 +2847,23 @@ ID3D12PipelineState* PipelineCache::CreateD3D12Pipeline(
         (description.depth_func != xenos::CompareFunction::kAlways || description.depth_write) &&
         description.depth_format == xenos::DepthRenderTargetFormat::kD24FS8) {
       if (render_target_cache_.depth_float24_round()) {
-        state_desc.PS.pShaderBytecode = shaders::float24_round_ps;
-        state_desc.PS.BytecodeLength = sizeof(shaders::float24_round_ps);
+        if (!DxbcShaderTranslator::Modification(description.vertex_shader_modification)
+                 .vertex.interpolator_mask) {
+          state_desc.PS.pShaderBytecode = shaders::float24_round_ps_position_only;
+          state_desc.PS.BytecodeLength = sizeof(shaders::float24_round_ps_position_only);
+        } else {
+          state_desc.PS.pShaderBytecode = shaders::float24_round_ps;
+          state_desc.PS.BytecodeLength = sizeof(shaders::float24_round_ps);
+        }
       } else {
-        state_desc.PS.pShaderBytecode = shaders::float24_truncate_ps;
-        state_desc.PS.BytecodeLength = sizeof(shaders::float24_truncate_ps);
+        if (!DxbcShaderTranslator::Modification(description.vertex_shader_modification)
+                 .vertex.interpolator_mask) {
+          state_desc.PS.pShaderBytecode = shaders::float24_truncate_ps_position_only;
+          state_desc.PS.BytecodeLength = sizeof(shaders::float24_truncate_ps_position_only);
+        } else {
+          state_desc.PS.pShaderBytecode = shaders::float24_truncate_ps;
+          state_desc.PS.BytecodeLength = sizeof(shaders::float24_truncate_ps);
+        }
       }
     }
   }
@@ -3028,8 +3044,53 @@ ID3D12PipelineState* PipelineCache::CreateD3D12Pipeline(
 
   // Create the D3D12 pipeline state object.
   ID3D12Device* device = command_processor_.GetD3D12Provider().GetDevice();
-  ID3D12PipelineState* state;
-  if (FAILED(device->CreateGraphicsPipelineState(&state_desc, IID_PPV_ARGS(&state)))) {
+  ID3D12PipelineState* state = nullptr;
+  const HRESULT create_result =
+      device->CreateGraphicsPipelineState(&state_desc, IID_PPV_ARGS(&state));
+  if (FAILED(create_result)) {
+    // Inspect linkage only after a failure, using the compiler already loaded
+    // by the provider. This avoids changing device or pipeline configuration.
+    using ReflectFn = HRESULT(WINAPI*)(LPCVOID, SIZE_T, REFIID, void**);
+    const HMODULE compiler_module = GetModuleHandleW(L"D3DCompiler_47.dll");
+    const auto reflect = compiler_module ? reinterpret_cast<ReflectFn>(
+        GetProcAddress(compiler_module, "D3DReflect")) : nullptr;
+    if (reflect) {
+      const auto log_signature = [&](const char* stage,
+                                     D3D12_SHADER_BYTECODE bytecode, bool output) {
+        if (!bytecode.BytecodeLength) return;
+        Microsoft::WRL::ComPtr<ID3D11ShaderReflection> reflection;
+        if (FAILED(reflect(bytecode.pShaderBytecode, bytecode.BytecodeLength,
+                           IID_PPV_ARGS(&reflection)))) return;
+        D3D11_SHADER_DESC shader_desc{};
+        if (FAILED(reflection->GetDesc(&shader_desc))) return;
+        const UINT count = output ? shader_desc.OutputParameters : shader_desc.InputParameters;
+        for (UINT i = 0; i < std::min(count, UINT(64)); ++i) {
+          D3D11_SIGNATURE_PARAMETER_DESC parameter{};
+          const HRESULT result = output ? reflection->GetOutputParameterDesc(i, &parameter)
+                                        : reflection->GetInputParameterDesc(i, &parameter);
+          if (SUCCEEDED(result)) {
+            REXGPU_ERROR("D3D12 failed pipeline signature: stage={} semantic={}{} register={} mask={} used={} type={}",
+                stage, parameter.SemanticName, parameter.SemanticIndex, parameter.Register,
+                uint32_t(parameter.Mask), uint32_t(parameter.ReadWriteMask),
+                uint32_t(parameter.ComponentType));
+          }
+        }
+      };
+      log_signature("VS-output", state_desc.VS, true);
+      log_signature("GS-output", state_desc.GS, true);
+      log_signature("PS-input", state_desc.PS, false);
+    }
+    REXGPU_ERROR(
+        "D3D12 pipeline failure: HRESULT=0x{:08X} device_reason=0x{:08X} "
+        "samples={} native_2x={} rtv_count={} dsv_format={} depth={} stencil={} "
+        "cull_mode={} vs_bytes={} ps_bytes={} gs_bytes={}",
+        uint32_t(create_result), uint32_t(device->GetDeviceRemovedReason()),
+        state_desc.SampleDesc.Count, render_target_cache_.msaa_2x_supported(),
+        state_desc.NumRenderTargets, uint32_t(state_desc.DSVFormat),
+        bool(state_desc.DepthStencilState.DepthEnable),
+        bool(state_desc.DepthStencilState.StencilEnable), uint32_t(description.cull_mode),
+        state_desc.VS.BytecodeLength, state_desc.PS.BytecodeLength,
+        state_desc.GS.BytecodeLength);
     if (runtime_description.pixel_shader != nullptr) {
       REXGPU_ERROR("Failed to create graphics pipeline with VS {:016X}, PS {:016X}",
                    runtime_description.vertex_shader->shader().ucode_data_hash(),
diff --git a/src/graphics/d3d12/render_target_cache.cpp b/src/graphics/d3d12/render_target_cache.cpp
index dd321a5..544275c 100644
--- a/src/graphics/d3d12/render_target_cache.cpp
+++ b/src/graphics/d3d12/render_target_cache.cpp
@@ -1196,7 +1196,9 @@ bool D3D12RenderTargetCache::Resolve(const memory::Memory& memory, D3D12SharedMe
           draw_util::resolve_copy_shader_info[size_t(copy_shader)];
       bool direct_resolved = false;
       if (GetPath() == Path::kHostRenderTargets) {
-        if (REXCVAR_GET(direct_host_resolve)) {
+        if (REXCVAR_GET(direct_host_resolve) &&
+            REXCVAR_GET(readback_resolve) == "none" &&
+            !REXCVAR_GET(d3d12_readback_resolve)) {
           direct_resolved =
               TryResolveCopyDirectly(resolve_info, copy_shader, draw_resolution_scaled);
           if (direct_resolved) {
diff --git a/src/graphics/d3d12/texture_cache.cpp b/src/graphics/d3d12/texture_cache.cpp
index 2be0e8e..05b54f5 100644
--- a/src/graphics/d3d12/texture_cache.cpp
+++ b/src/graphics/d3d12/texture_cache.cpp
@@ -14,11 +14,15 @@
 #include <cfloat>
 #include <cstddef>
 #include <cstring>
+#include <fstream>
+#include <filesystem>
 #include <memory>
 #include <utility>
+#include <unordered_set>
 
 #include <rex/assert.h>
 #include <rex/dbg.h>
+#include <rex/cvar.h>
 #include <rex/graphics/d3d12/command_processor.h>
 #include <rex/graphics/d3d12/shared_memory.h>
 #include <rex/graphics/d3d12/texture_cache.h>
@@ -32,6 +36,12 @@
 #include <rex/ui/d3d12/d3d12_upload_buffer_pool.h>
 #include <rex/ui/d3d12/d3d12_util.h>
 
+REXCVAR_DEFINE_BOOL(log_texture_uploads, false, "GPU/Diagnostics",
+                    "Log up to 4096 texture allocations and their conversion layout");
+
+REXCVAR_DEFINE_STRING(texture_diagnostic_directory, "", "GPU/Diagnostics",
+                      "Directory for up to 64 raw two-channel 3D texture samples; empty disables");
+
 namespace rex::graphics::d3d12 {
 
 // Generated with `xb buildshaders`.
@@ -678,6 +688,36 @@ void D3D12TextureCache::BeginFrame() {
 }
 
 void D3D12TextureCache::EndFrame() {
+  // Read only completed diagnostic copies. Never wait for the GPU here.
+  for (auto it = texture_memory_diagnostics_.begin(); it != texture_memory_diagnostics_.end();) {
+    if (it->submission > command_processor_.GetCompletedSubmission()) {
+      ++it;
+      continue;
+    }
+    void* mapped = nullptr;
+    D3D12_RANGE range{0, it->cpu_bytes.size()};
+    if (SUCCEEDED(it->readback->Map(0, &range, &mapped))) {
+      const auto* gpu_bytes = static_cast<const uint8_t*>(mapped);
+      size_t differences = 0;
+      size_t first_difference = it->cpu_bytes.size();
+      for (size_t i = 0; i < it->cpu_bytes.size(); ++i) {
+        if (gpu_bytes[i] != it->cpu_bytes[i]) {
+          if (!differences) first_difference = i;
+          ++differences;
+        }
+      }
+      std::ofstream output(it->path, std::ios::binary);
+      output.write(static_cast<const char*>(mapped), it->cpu_bytes.size());
+      const D3D12_RANGE no_writes{0, 0};
+      it->readback->Unmap(0, &no_writes);
+      REXGPU_INFO("Texture GPU memory diagnostic: base={:08X} bytes={} differences={} "
+                  "first_difference={} saved={}", it->base, it->cpu_bytes.size(),
+                  differences, first_difference, bool(output));
+    } else {
+      REXGPU_ERROR("Texture GPU memory diagnostic: Map failed for {:08X}", it->base);
+    }
+    it = texture_memory_diagnostics_.erase(it);
+  }
   // Report used unsupported texture formats.
   bool unsupported_header_written = false;
   for (uint32_t i = 0; i < 64; ++i) {
@@ -878,11 +918,34 @@ void D3D12TextureCache::WriteActiveTextureBindfulSRV(
 }
 
 uint32_t D3D12TextureCache::GetActiveTextureBindlessSRVIndex(
-    const D3D12Shader::TextureBinding& host_shader_binding) {
+    const D3D12Shader::TextureBinding& host_shader_binding, uint64_t shader_hash) {
   assert_true(bindless_resources_used_);
   uint32_t descriptor_index = UINT32_MAX;
   uint32_t fetch_constant_index = host_shader_binding.fetch_constant;
   const TextureBinding* binding = GetValidTextureBinding(fetch_constant_index);
+  if (binding && binding->key.format == xenos::TextureFormat::k_8_8 &&
+      REXCVAR_GET(log_texture_uploads)) {
+    static std::unordered_set<std::string> diagnosed_bindings;
+    if (diagnosed_bindings.size() < 512) {
+      const auto fetch = register_file().GetTextureFetch(fetch_constant_index);
+      std::string diagnostic_key = std::to_string(shader_hash) + ":" +
+          std::to_string(fetch_constant_index) + ":" +
+          std::to_string(uint32_t(host_shader_binding.dimension)) + ":" +
+          std::to_string(host_shader_binding.is_signed);
+      for (uint32_t word : {fetch.dword_0, fetch.dword_1, fetch.dword_2,
+                            fetch.dword_3, fetch.dword_4, fetch.dword_5}) {
+        diagnostic_key += ":" + std::to_string(word);
+      }
+      if (diagnosed_bindings.insert(diagnostic_key).second) {
+        REXGPU_INFO("Texture shader binding: shader={:016X} fetch={} dimension={} signed={} "
+                    "base={:08X} raw={:08X},{:08X},{:08X},{:08X},{:08X},{:08X}",
+                    shader_hash, fetch_constant_index, uint32_t(host_shader_binding.dimension),
+                    host_shader_binding.is_signed, uint32_t(binding->key.base_page) << 12,
+                    fetch.dword_0, fetch.dword_1, fetch.dword_2, fetch.dword_3,
+                    fetch.dword_4, fetch.dword_5);
+      }
+    }
+  }
   if (binding && AreDimensionsCompatible(host_shader_binding.dimension, binding->key.dimension)) {
     bool force_special_view = binding->key.dimension == xenos::DataDimension::k3D &&
                               (host_shader_binding.dimension == xenos::FetchOpDimension::k1D ||
@@ -1519,6 +1582,21 @@ uint32_t D3D12TextureCache::GetMaxHostTextureDepthOrArraySize(
 std::unique_ptr<TextureCache::Texture> D3D12TextureCache::CreateTexture(TextureKey key) {
   D3D12_RESOURCE_DESC desc;
   desc.Format = GetDXGIResourceFormat(key);
+  // Allocation-only logging keeps the diagnostic cost out of normal draws.
+  static uint32_t diagnostics_count = 0;
+  if (REXCVAR_GET(log_texture_uploads) && diagnostics_count < 4096) {
+    ++diagnostics_count;
+    REXGPU_INFO("Texture diagnostic: base={:08X} mips={:08X} size={}x{}x{} "
+                "dimension={} format={} host={} endian={} tiled={} pitch={} "
+                "packed={} levels={} scaled={} loader={}",
+                uint32_t(key.base_page) << 12, uint32_t(key.mip_page) << 12,
+                key.GetWidth(), key.GetHeight(), key.GetDepthOrArraySize(),
+                uint32_t(key.dimension), uint32_t(key.format), uint32_t(desc.Format),
+                uint32_t(key.endianness), uint32_t(key.tiled), uint32_t(key.pitch),
+                uint32_t(key.packed_mips), uint32_t(key.mip_max_level) + 1,
+                uint32_t(key.scaled_resolve), uint32_t(GetLoadShaderIndex(key)));
+  }
+
   if (desc.Format == DXGI_FORMAT_UNKNOWN) {
     unsupported_format_features_used_[uint32_t(key.format)] |= kUnsupportedResourceBit;
     return nullptr;
@@ -1561,6 +1639,66 @@ bool D3D12TextureCache::LoadTextureDataFromResidentMemoryImpl(Texture& texture,
                                                               bool load_mips) {
   D3D12Texture& d3d12_texture = static_cast<D3D12Texture&>(texture);
   TextureKey texture_key = d3d12_texture.key();
+  static uint32_t texture_data_diagnostic_count = 0;
+  const std::string diagnostic_directory = REXCVAR_GET(texture_diagnostic_directory);
+  if (!diagnostic_directory.empty() && load_base && texture_key.base_page &&
+      texture_key.format == xenos::TextureFormat::k_8_8 &&
+      texture_key.dimension == xenos::DataDimension::k3D &&
+      texture_data_diagnostic_count < 64) {
+    uint32_t sample_size = d3d12_texture.GetGuestBaseSize();
+    const auto* sample = command_processor_.guest_memory().TranslatePhysical(uint32_t(texture_key.base_page) << 12);
+    if (sample && sample_size && sample_size <= 4 * 1024 * 1024) {
+      std::error_code error;
+      std::filesystem::create_directories(diagnostic_directory, error);
+      if (!error) {
+        uint32_t sample_index = texture_data_diagnostic_count++;
+        auto sample_path = std::filesystem::path(diagnostic_directory) /
+            ("texture-" + std::to_string(sample_index) + ".bin");
+        std::ofstream output(sample_path, std::ios::binary);
+        output.write(reinterpret_cast<const char*>(sample), sample_size);
+        // Capture the actual shader input from shared GPU memory, before
+        // conversion. The CPU snapshot alone cannot establish GPU coherency.
+        if (!texture_key.scaled_resolve) {
+          TextureMemoryDiagnostic diagnostic;
+          D3D12_RESOURCE_DESC desc{};
+          desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
+          desc.Width = sample_size;
+          desc.Height = 1;
+          desc.DepthOrArraySize = 1;
+          desc.MipLevels = 1;
+          desc.SampleDesc.Count = 1;
+          desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+          D3D12_HEAP_PROPERTIES heap{};
+          heap.Type = D3D12_HEAP_TYPE_READBACK;
+          if (SUCCEEDED(command_processor_.GetD3D12Provider().GetDevice()->CreateCommittedResource(
+                  &heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST,
+                  nullptr, IID_PPV_ARGS(&diagnostic.readback)))) {
+            diagnostic.cpu_bytes.assign(sample, sample + sample_size);
+            diagnostic.base = uint32_t(texture_key.base_page) << 12;
+            diagnostic.submission = command_processor_.GetCurrentSubmission();
+            diagnostic.path = (std::filesystem::path(diagnostic_directory) /
+                ("texture-" + std::to_string(sample_index) + "-gpu.bin")).string();
+            auto& shared = static_cast<D3D12SharedMemory&>(shared_memory());
+            shared.UseAsCopySource();
+            command_processor_.SubmitBarriers();
+            command_processor_.GetDeferredCommandList().D3DCopyBufferRegion(
+                diagnostic.readback.Get(), 0, shared.GetBuffer(), diagnostic.base, sample_size);
+            texture_memory_diagnostics_.push_back(std::move(diagnostic));
+          } else {
+            REXGPU_ERROR("Texture GPU memory diagnostic: readback allocation failed");
+          }
+        }
+        const auto& layout = d3d12_texture.guest_layout().base;
+        REXGPU_INFO("Texture data diagnostic: index={} base={:08X} bytes={} size={}x{}x{} "
+                    "row_bytes={} z_rows={} endian={} tiled={} saved={}",
+                    sample_index, uint32_t(texture_key.base_page) << 12, sample_size,
+                    texture_key.GetWidth(), texture_key.GetHeight(), texture_key.GetDepthOrArraySize(),
+                    layout.row_pitch_bytes, layout.z_slice_stride_block_rows,
+                    uint32_t(texture_key.endianness), uint32_t(texture_key.tiled), bool(output));
+      }
+    }
+  }
+
 
   DeferredCommandList& command_list = command_processor_.GetDeferredCommandList();
   ID3D12Device* device = command_processor_.GetD3D12Provider().GetDevice();
@@ -1634,14 +1772,14 @@ bool D3D12TextureCache::LoadTextureDataFromResidentMemoryImpl(Texture& texture,
     host_x_blocks_per_thread *= block_width;
   }
   UINT64 copy_buffer_size = 0;
-  D3D12_PLACED_SUBRESOURCE_FOOTPRINT host_slice_layout_base;
-  UINT64 host_slice_size_base;
+  D3D12_PLACED_SUBRESOURCE_FOOTPRINT host_slice_layout_base{};
+  UINT64 host_slice_size_base = 0;
   // Indexing is the same as for guest stored mips:
   // 1...min(level_last, level_packed) if level_packed is not 0, or only 0 if
   // level_packed == 0.
   D3D12_PLACED_SUBRESOURCE_FOOTPRINT
-  host_slice_layouts_mips[xenos::kTextureMaxMips];
-  UINT64 host_slice_sizes_mips[xenos::kTextureMaxMips];
+  host_slice_layouts_mips[xenos::kTextureMaxMips]{};
+  UINT64 host_slice_sizes_mips[xenos::kTextureMaxMips]{};
   // Using custom calculations instead of GetCopyableFootprints because
   // shaders may unconditionally copy multiple blocks along X per thread for
   // simplicity, to make sure all rows (also including the last one -
@@ -1688,6 +1826,11 @@ bool D3D12TextureCache::LoadTextureDataFromResidentMemoryImpl(Texture& texture,
     (is_base ? host_slice_size_base : host_slice_sizes_mips[level]) = level_host_slice_size;
     copy_buffer_size += level_host_slice_size * array_size;
   }
+  if (!copy_buffer_size || copy_buffer_size > UINT32_MAX) {
+    REXLOG_ERROR("Texture upload buffer size {} exceeds the supported range",
+                 copy_buffer_size);
+    return false;
+  }
   D3D12_RESOURCE_STATES copy_buffer_state = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
   ID3D12Resource* copy_buffer =
       command_processor_.RequestScratchGPUBuffer(uint32_t(copy_buffer_size), copy_buffer_state);
@@ -1982,6 +2125,22 @@ ID3D12Resource* D3D12TextureCache::D3D12Texture::GetOrCreate3DAs2DResource(
   auto& d3d12_cache = static_cast<D3D12TextureCache&>(texture_cache());
 
   if (texture_3d_as_2d_) {
+    bool wrapper_outdated = texture_3d_as_2d_->outdated_mask() != 0;
+    // The wrapper watches guest memory independently of the native 3D texture.
+    // Reusing the resource must still process invalidation after CPU writes or
+    // GPU resolves; otherwise it keeps the contents of its first upload.
+    // LoadTextureData is a no-op while the watched ranges remain up to date.
+    if (!d3d12_cache.LoadTextureData(*texture_3d_as_2d_)) {
+      REXGPU_ERROR("D3D12TextureCache: Failed to refresh 3D-as-2D wrapper data");
+      return nullptr;
+    }
+    if (wrapper_outdated && REXCVAR_GET(log_texture_uploads)) {
+      static uint32_t refresh_diagnostics_count = 0;
+      if (refresh_diagnostics_count++ < 64) {
+        REXGPU_INFO("Texture wrapper refreshed after invalidation: base={:08X} format={}",
+                    uint32_t(key().base_page) << 12, uint32_t(key().format));
+      }
+    }
     d3d12_cache.command_processor_.PushTransitionBarrier(
         texture_3d_as_2d_->resource(), texture_3d_as_2d_->SetResourceState(end_state), end_state);
     return texture_3d_as_2d_->resource();
@@ -2051,6 +2210,18 @@ uint32_t D3D12TextureCache::FindOrCreateTextureDescriptor(D3D12Texture& texture,
   PROFILE_TEXTURE_CACHE_MISS();
 
   TextureKey texture_key = texture.key();
+  static uint32_t view_diagnostics_count = 0;
+  if (REXCVAR_GET(log_texture_uploads) && texture_key.dimension == xenos::DataDimension::k3D &&
+      view_diagnostics_count < 512) {
+    ++view_diagnostics_count;
+    REXGPU_INFO("Texture view diagnostic: base={:08X} format={} guest_dimension={} "
+                "view_dimension={} signed={} swizzle={:08X} depth={} wrapper={}",
+                uint32_t(texture_key.base_page) << 12, uint32_t(texture_key.format),
+                uint32_t(texture_key.dimension), uint32_t(dimension), is_signed,
+                host_swizzle, texture_key.GetDepthOrArraySize(),
+                dimension == xenos::DataDimension::k1D ||
+                    dimension == xenos::DataDimension::k2DOrStacked);
+  }
 
   // Create a new bindless or cached descriptor if supported.
   D3D12_SHADER_RESOURCE_VIEW_DESC desc = {};
diff --git a/src/graphics/graphics_system.cpp b/src/graphics/graphics_system.cpp
index 8f2fcb0..7e9edf8 100644
--- a/src/graphics/graphics_system.cpp
+++ b/src/graphics/graphics_system.cpp
@@ -1,3 +1,4 @@
+#include <rex/ui/presenter.h>
 /**
  ******************************************************************************
  * Xenia : Xbox 360 Emulator Research Project                                 *
@@ -14,12 +15,20 @@
 #include <algorithm>
 #include <cctype>
 #include <cstdint>
+#include <filesystem>
 #include <functional>
 #include <memory>
+#include <chrono>
 #include <mutex>
+#include <string>
+#include <thread>
+#include <tuple>
+#include <unordered_map>
 #include <utility>
+#include <vector>
 
 #include <rex/cvar.h>
+#include <rex/filesystem.h>
 #include <rex/graphics/command_processor.h>
 #include <rex/graphics/flags.h>
 #include <rex/kernel/xboxkrnl/video.h>
@@ -31,6 +40,11 @@
 #include <rex/ui/window.h>
 #include <rex/ui/windowed_app_context.h>
 
+#if REX_PLATFORM_WIN32
+#include "../core/platform_win.h"
+#include <tlhelp32.h>
+#endif
+
 REXCVAR_DEFINE_STRING(swap_post_effect, "none", "GPU", "Swap post effect: none, fxaa, fxaa_extreme")
     .allowed({"none", "fxaa", "fxaa_extreme"})
     .lifecycle(rex::cvar::Lifecycle::kRequiresRestart);
@@ -39,6 +53,17 @@ REXCVAR_DEFINE_BOOL(store_shaders, true, "GPU",
                     "Store shaders persistently and load them when loading games to avoid "
                     "runtime spikes and freezes when playing the game not for the first time.");
 
+REXCVAR_DEFINE_BOOL(guest_vblank_unlocked, true, "GPU",
+                    "Allow 1000 Hz guest vblank when host VSync is disabled; disable to preserve video-mode timing");
+
+REXCVAR_DEFINE_BOOL(log_thread_cpu, false, "GPU",
+                    "Every two seconds log the process threads that use at least 5% of a core, with their "
+                    "[t#####] id and name, to see which thread limits the frame rate.");
+
+REXCVAR_DEFINE_BOOL(log_thread_samples, false, "GPU",
+                    "With log_thread_cpu: sample the instruction pointer of saturated threads and log "
+                    "the hottest module+RVA entries (diagnostic).");
+
 namespace {
 
 rex::graphics::CommandProcessor::SwapPostEffect ParseSwapPostEffect(
@@ -115,6 +140,140 @@ X_STATUS GraphicsSystem::SetupPresentation(ui::WindowedAppContext* app_context)
   return X_STATUS_SUCCESS;
 }
 
+#if REX_PLATFORM_WIN32
+// Diagnostics: per-thread CPU use of this process, logged every two seconds.
+void StartThreadCpuLogger() {
+  static std::once_flag once;
+  std::call_once(once, [] {
+    std::thread([] {
+      using GetThreadDescriptionFn = HRESULT(WINAPI*)(HANDLE, PWSTR*);
+      auto get_description = reinterpret_cast<GetThreadDescriptionFn>(
+          ::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"), "GetThreadDescription"));
+      std::unordered_map<DWORD, uint64_t> previous;
+      auto last = std::chrono::steady_clock::now();
+      const DWORD pid = ::GetCurrentProcessId();
+      for (;;) {
+        std::this_thread::sleep_for(std::chrono::seconds(2));
+        const auto now = std::chrono::steady_clock::now();
+        const double wall = std::chrono::duration<double>(now - last).count();
+        last = now;
+        HANDLE snapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
+        if (snapshot == INVALID_HANDLE_VALUE) continue;
+        std::vector<std::tuple<double, DWORD, std::string>> rows;
+        THREADENTRY32 entry{};
+        entry.dwSize = sizeof(entry);
+        for (BOOL ok = ::Thread32First(snapshot, &entry); ok; ok = ::Thread32Next(snapshot, &entry)) {
+          if (entry.th32OwnerProcessID != pid) continue;
+          HANDLE thread = ::OpenThread(THREAD_QUERY_LIMITED_INFORMATION, FALSE, entry.th32ThreadID);
+          if (!thread) continue;
+          FILETIME creation, exit_time, kernel, user;
+          if (::GetThreadTimes(thread, &creation, &exit_time, &kernel, &user)) {
+            auto to_u64 = [](const FILETIME& f) { return (uint64_t(f.dwHighDateTime) << 32) | f.dwLowDateTime; };
+            const uint64_t total = to_u64(kernel) + to_u64(user);  // 100 ns units
+            uint64_t& before = previous[entry.th32ThreadID];
+            const double percent = (before && wall > 0) ? double(total - before) / 1e7 / wall * 100.0 : 0.0;
+            before = total;
+            if (percent >= 5.0) {
+              std::string name;
+              PWSTR description = nullptr;
+              if (get_description && SUCCEEDED(get_description(thread, &description)) && description) {
+                for (const wchar_t* c = description; *c; ++c) name += *c < 128 ? char(*c) : '?';
+                ::LocalFree(description);
+              }
+              rows.emplace_back(percent, entry.th32ThreadID, name);
+            }
+          }
+          ::CloseHandle(thread);
+        }
+        ::CloseHandle(snapshot);
+        std::sort(rows.begin(), rows.end(), [](const auto& a, const auto& b) { return std::get<0>(a) > std::get<0>(b); });
+        std::string line;
+        for (size_t i = 0; i < rows.size() && i < 8; ++i) {
+          line += " | t" + std::to_string(std::get<1>(rows[i])) + " '" + std::get<2>(rows[i]) + "' " +
+                  std::to_string(int(std::get<0>(rows[i]) + 0.5)) + "%";
+        }
+        REXGPU_INFO("ThreadCPU (2 s):{}", line.empty() ? " none above 5%" : line);
+        if (REXCVAR_GET(log_thread_samples)) {
+          // Instruction-pointer sampling of the threads that are saturated: 800 suspend/read/resume
+          // samples each, aggregated as module+RVA so the hot recompiled function can be named from
+          // the module's PDB (llvm-symbolizer). Diagnostic only.
+          for (size_t r = 0; r < rows.size() && r < 5; ++r) {
+            if (std::get<0>(rows[r]) < 30.0) continue;
+            HANDLE thread = ::OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT |
+                                             THREAD_QUERY_LIMITED_INFORMATION,
+                                         FALSE, std::get<1>(rows[r]));
+            if (!thread) continue;
+            auto describe = [](uint64_t address) {
+              HMODULE module = nullptr;
+              if (!::GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
+                                            GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
+                                        reinterpret_cast<LPCWSTR>(address), &module) || !module) {
+                return std::string("unknown");
+              }
+              wchar_t path[MAX_PATH] = {};
+              ::GetModuleFileNameW(module, path, MAX_PATH);
+              std::wstring wpath(path);
+              const size_t slash = wpath.find_last_of(L"\\/");
+              std::string file;
+              for (wchar_t c : wpath.substr(slash == std::wstring::npos ? 0 : slash + 1)) {
+                file += c < 128 ? char(c) : (char)63;
+              }
+              char rva[32];
+              snprintf(rva, sizeof(rva), "+0x%llX",
+                       (unsigned long long)(address - reinterpret_cast<uint64_t>(module)));
+              return file + rva;
+            };
+            std::unordered_map<std::string, uint32_t> by_symbol;
+            for (int s = 0; s < 800; ++s) {
+              if (::SuspendThread(thread) == DWORD(-1)) break;
+              CONTEXT context{};
+              context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
+              if (::GetThreadContext(thread, &context)) {
+                std::string leaf = describe(context.Rip), runtime_frame, game_frame;
+                CONTEXT walk = context;
+                int game_frames = 0;
+                for (int depth = 0; depth < 40 && game_frames < 4; ++depth) {
+                  DWORD64 image_base = 0;
+                  UNWIND_HISTORY_TABLE history{};
+                  PRUNTIME_FUNCTION entry = ::RtlLookupFunctionEntry(walk.Rip, &image_base, &history);
+                  const std::string here = describe(entry ? image_base + entry->BeginAddress : walk.Rip);
+                  if (depth > 0) {
+                    if (here.rfind("fifastreet_", 0) == 0) { game_frame += (game_frame.empty() ? "" : " <- ") + describe(walk.Rip); ++game_frames; }
+                    else if (runtime_frame.empty() && (here.rfind("rexruntime", 0) == 0 || here.rfind("rexgpu", 0) == 0)) runtime_frame = here;
+                  }
+                  if (!entry) {
+                    if (!walk.Rsp) break;
+                    walk.Rip = *reinterpret_cast<uint64_t*>(walk.Rsp);
+                    walk.Rsp += 8;
+                  } else {
+                    void* handler_data = nullptr;
+                    DWORD64 establisher = 0;
+                    ::RtlVirtualUnwind(UNW_FLAG_NHANDLER, image_base, walk.Rip, entry, &walk, &handler_data, &establisher, nullptr);
+                  }
+                  if (!walk.Rip) break;
+                }
+                by_symbol[leaf + (runtime_frame.empty() ? "" : " via " + runtime_frame) + (game_frame.empty() ? "" : " <- " + game_frame)]++;
+              }
+              ::ResumeThread(thread);
+              std::this_thread::sleep_for(std::chrono::microseconds(300));
+            }
+            ::CloseHandle(thread);
+            std::vector<std::pair<uint32_t, std::string>> ranked;
+            for (const auto& [key, count] : by_symbol) ranked.emplace_back(count, key);
+            std::sort(ranked.rbegin(), ranked.rend());
+            std::string text;
+            for (size_t i = 0; i < ranked.size() && i < 14; ++i) {
+              text += " " + ranked[i].second + "=" + std::to_string(ranked[i].first);
+            }
+            REXGPU_INFO("ThreadSamples t{} '{}':{}", std::get<1>(rows[r]), std::get<2>(rows[r]), text);
+          }
+        }
+      }
+    }).detach();
+  });
+}
+#endif
+
 X_STATUS GraphicsSystem::SetupGuestGpu(runtime::FunctionDispatcher* function_dispatcher,
                                        system::KernelState* kernel_state) {
   memory_ = function_dispatcher->memory();
@@ -136,6 +295,9 @@ X_STATUS GraphicsSystem::SetupGuestGpu(runtime::FunctionDispatcher* function_dis
     return X_STATUS_UNSUCCESSFUL;
   }
   command_processor_->SetDesiredSwapPostEffect(ParseSwapPostEffect(REXCVAR_GET(swap_post_effect)));
+#if REX_PLATFORM_WIN32
+  if (REXCVAR_GET(log_thread_cpu)) StartThreadCpuLogger();
+#endif
 
   // Register GPU MMIO handlers
   // GPU registers are at 0x7FC80000-0x7FCFFFFF
@@ -157,15 +319,75 @@ X_STATUS GraphicsSystem::SetupGuestGpu(runtime::FunctionDispatcher* function_dis
         uint64_t vsync_interval_ticks =
             std::max(uint64_t(1), uint64_t(double(guest_tick_frequency) / refresh_rate_hz));
         uint64_t no_vsync_interval_ticks = std::max(uint64_t(1), guest_tick_frequency / 1000);
+#if REX_PLATFORM_WIN32
+        // Wait for the next guest deadline without changing the selected rate.
+        // Older Windows versions fall back to the existing polling sleep.
+        std::unique_ptr<void, decltype(&::CloseHandle)> precise_timer(
+            ::CreateWaitableTimerExW(nullptr, nullptr, 0x00000002,
+                                    TIMER_MODIFY_STATE | SYNCHRONIZE), &::CloseHandle);
+#endif
         uint64_t last_frame_time = chrono::Clock::QueryGuestTickCount();
+        uint64_t monitor_report_time = last_frame_time;
+        uint64_t monitor_waits = 0;
+        uint64_t monitor_recovered_ticks = 0;
+        uint64_t monitor_max_elapsed_ticks = 0;
         while (vsync_worker_running_) {
+          // Share the physical display clock only when the selected mode matches.
+          // Unlocked or time-scaled guests retain the existing timer behavior.
+          if (REXCVAR_GET(vsync) &&
+              chrono::Clock::guest_time_scalar() == 1.0 && presenter_ &&
+              presenter_->WaitForMonitorVBlank(refresh_rate_hz)) {
+            if (!vsync_worker_running_) break;
+            const uint64_t monitor_time = chrono::Clock::QueryGuestTickCount();
+            const uint64_t elapsed_ticks = monitor_time - last_frame_time;
+            // Native waits can span multiple refresh cycles when this worker
+            // is descheduled. Preserve elapsed guest vblanks just as the timer
+            // fallback does, instead of slowing the guest clock under load.
+            const uint64_t elapsed_vblanks = std::max(uint64_t(1),
+                (elapsed_ticks + vsync_interval_ticks / 2) / vsync_interval_ticks);
+            ++monitor_waits;
+            monitor_recovered_ticks += elapsed_vblanks - 1;
+            monitor_max_elapsed_ticks = std::max(monitor_max_elapsed_ticks, elapsed_ticks);
+            // Measure before dispatch: interrupt execution time belongs to the
+            // next interval and must not be discarded from elapsed time.
+            last_frame_time = monitor_time;
+            for (uint64_t i = 0; i < elapsed_vblanks && vsync_worker_running_; ++i) {
+              MarkVblank();
+            }
+            if (monitor_time - monitor_report_time >= guest_tick_frequency * 5) {
+              REXLOG_INFO("MonitorVblankTiming: waits={} recovered_ticks={} max_interval_ms={:.3f}",
+                  monitor_waits, monitor_recovered_ticks,
+                  double(monitor_max_elapsed_ticks) * 1000.0 / double(guest_tick_frequency));
+              monitor_report_time = monitor_time;
+              monitor_waits = monitor_recovered_ticks = monitor_max_elapsed_ticks = 0;
+            }
+            continue;
+          }
           uint64_t current_time = chrono::Clock::QueryGuestTickCount();
           uint64_t interval_ticks =
-              REXCVAR_GET(vsync) ? vsync_interval_ticks : no_vsync_interval_ticks;
+              (REXCVAR_GET(vsync) || !REXCVAR_GET(guest_vblank_unlocked))
+                  ? vsync_interval_ticks : no_vsync_interval_ticks;
           while (current_time - last_frame_time >= interval_ticks) {
             MarkVblank();
             last_frame_time += interval_ticks;
           }
+#if REX_PLATFORM_WIN32
+          if (precise_timer) {
+            current_time = chrono::Clock::QueryGuestTickCount();
+            const uint64_t elapsed_ticks = current_time - last_frame_time;
+            if (elapsed_ticks >= interval_ticks) continue;
+            const double scalar = std::max(0.001, chrono::Clock::guest_time_scalar());
+            const double remaining_seconds =
+                double(interval_ticks - elapsed_ticks) / double(guest_tick_frequency) / scalar;
+            LARGE_INTEGER due_time;
+            due_time.QuadPart = -std::max(int64_t(1), int64_t(
+                std::min(remaining_seconds, 0.020) * 10000000.0));
+            if (::SetWaitableTimer(precise_timer.get(), &due_time, 0, nullptr, nullptr, FALSE) &&
+                ::WaitForSingleObject(precise_timer.get(), 50) == WAIT_OBJECT_0) {
+              continue;
+            }
+          }
+#endif
           rex::thread::Sleep(std::chrono::milliseconds(1));
         }
         return 0;
@@ -180,8 +402,8 @@ X_STATUS GraphicsSystem::SetupGuestGpu(runtime::FunctionDispatcher* function_dis
 
 void GraphicsSystem::Shutdown() {
   if (command_processor_) {
+    // Keep the object alive while vblank may still increment its counter.
     command_processor_->Shutdown();
-    command_processor_.reset();
   }
 
   if (vsync_worker_thread_) {
@@ -190,6 +412,8 @@ void GraphicsSystem::Shutdown() {
     vsync_worker_thread_.reset();
   }
 
+  command_processor_.reset();
+
   if (presenter_) {
     if (app_context_) {
       app_context_->CallInUIThreadSynchronous([this]() { presenter_.reset(); });
@@ -344,6 +568,24 @@ void GraphicsSystem::InitializeShaderStorage(const std::filesystem::path& cache_
   if (!REXCVAR_GET(store_shaders)) {
     return;
   }
+  // First run: start from the pipelines/shaders shipped next to the executable (shader-seed/), so
+  // the first matches do not compile everything from scratch. Files the player already has are
+  // never touched.
+  {
+    std::error_code ec;
+    const auto seed = rex::filesystem::GetExecutableFolder() / "shader-seed";
+    const auto target = cache_root / "shaders" / "shareable";
+    if (std::filesystem::is_directory(seed, ec)) {
+      std::filesystem::create_directories(target, ec);
+      for (const auto& entry : std::filesystem::directory_iterator(seed, ec)) {
+        if (!entry.is_regular_file(ec)) continue;
+        const auto destination = target / entry.path().filename();
+        if (std::filesystem::exists(destination, ec)) continue;
+        std::filesystem::copy_file(entry.path(), destination, ec);
+        REXGPU_INFO("Shader cache seeded: {}", entry.path().filename().string());
+      }
+    }
+  }
   if (blocking) {
     if (command_processor_->is_paused()) {
       // Safe to run on any thread while the command processor is paused, no
diff --git a/src/graphics/pipeline/shader/dxbc_translator_fetch.cpp b/src/graphics/pipeline/shader/dxbc_translator_fetch.cpp
index 31de175..267f7da 100644
--- a/src/graphics/pipeline/shader/dxbc_translator_fetch.cpp
+++ b/src/graphics/pipeline/shader/dxbc_translator_fetch.cpp
@@ -842,6 +842,28 @@ void DxbcShaderTranslator::ProcessTextureFetchInstruction(
                   RequestTextureFetchConstantWord(tfetch_index, 2));
         break;
       case xenos::FetchOpDimension::k2D:
+      {
+        // A 2D view of a guest 3D texture retains the guest fetch constant's
+        // 11/11/10 size packing. Using 13/13 here normalizes offsets against
+        // unrelated height/depth bits rather than the wrapper's actual size.
+        uint32_t resource_dimension_temp = PushSystemTemp();
+        a_.OpUBFE(dxbc::Dest::R(resource_dimension_temp, 0b0001), dxbc::Src::LU(2),
+                  dxbc::Src::LU(9), RequestTextureFetchConstantWord(tfetch_index, 5));
+        a_.OpIEq(dxbc::Dest::R(resource_dimension_temp, 0b0001),
+                 dxbc::Src::R(resource_dimension_temp, dxbc::Src::kXXXX),
+                 dxbc::Src::LU(uint32_t(xenos::DataDimension::k3D)));
+        a_.OpIf(true, dxbc::Src::R(resource_dimension_temp, dxbc::Src::kXXXX));
+        a_.OpUBFE(dxbc::Dest::R(size_and_is_3d_temp, size_needed_components),
+                  dxbc::Src::LU(11, 11, 0, 0), dxbc::Src::LU(0, 11, 0, 0),
+                  RequestTextureFetchConstantWord(tfetch_index, 2));
+        a_.OpElse();
+        a_.OpUBFE(dxbc::Dest::R(size_and_is_3d_temp, size_needed_components),
+                  dxbc::Src::LU(13, 13, 0, 0), dxbc::Src::LU(0, 13, 0, 0),
+                  RequestTextureFetchConstantWord(tfetch_index, 2));
+        a_.OpEndIf();
+        PopSystemTemp();
+        break;
+      }
       case xenos::FetchOpDimension::kCube:
         a_.OpUBFE(dxbc::Dest::R(size_and_is_3d_temp, size_needed_components),
                   dxbc::Src::LU(13, 13, 0, 0), dxbc::Src::LU(0, 13, 0, 0),
diff --git a/src/graphics/pipeline/shader/spirv_translator_fetch.cpp b/src/graphics/pipeline/shader/spirv_translator_fetch.cpp
index 9ce3bb4..dbde6be 100644
--- a/src/graphics/pipeline/shader/spirv_translator_fetch.cpp
+++ b/src/graphics/pipeline/shader/spirv_translator_fetch.cpp
@@ -19,9 +19,14 @@
 #include <fmt/format.h>
 
 #include <rex/assert.h>
+#include <rex/cvar.h>
 #include <rex/graphics/pipeline/shader/spirv_translator.h>
 #include <rex/math.h>
 
+REXCVAR_DEFINE_BOOL(vulkan_fix_2d_fetch_of_3d_size, true, "GPU/Vulkan",
+                    "Read the 11/11/10 size packing when a 2D fetch samples a guest 3D texture (FIFA Street "
+                    "menu bars); disable to compare with the previous behaviour.");
+
 namespace rex::graphics {
 
 void SpirvShaderTranslator::ProcessVertexFetchInstruction(
@@ -823,6 +828,12 @@ void SpirvShaderTranslator::ProcessTextureFetchInstruction(
       // whether the texture is 3D unconditionally.
       data_is_3d_needed = true;
     }
+    if (REXCVAR_GET(vulkan_fix_2d_fetch_of_3d_size) &&
+        instr.dimension == xenos::FetchOpDimension::k2D && (size_needed_components & 0b11)) {
+      // A 2D fetch of a guest 3D texture (FIFA Street k_8_8 UI textures) keeps the 11/11/10 size
+      // packing of the fetch constant; same fix as the DXBC translator.
+      data_is_3d_needed = true;
+    }
     spv::Id data_is_3d = spv::NoResult;
     if (data_is_3d_needed) {
       // Get the data dimensionality from the bits 9:10 of the fetch constant
@@ -868,10 +879,18 @@ void SpirvShaderTranslator::ProcessTextureFetchInstruction(
         } break;
         case xenos::FetchOpDimension::k2D:
         case xenos::FetchOpDimension::kCube: {
+          const bool is_2d = data_is_3d != spv::NoResult && instr.dimension == xenos::FetchOpDimension::k2D;
           if (size_needed_components & 0b1) {
             size[0] = builder_->createTriOp(
                 spv::OpBitFieldUExtract, type_uint_, fetch_constant_word_2, const_uint_0_,
                 builder_->makeUintConstant(xenos::kTexture2DCubeMaxWidthHeightLog2));
+            if (is_2d) {
+              spv::Id size_3d = builder_->createTriOp(
+                  spv::OpBitFieldUExtract, type_uint_, fetch_constant_word_2, const_uint_0_,
+                  builder_->makeUintConstant(xenos::kTexture3DMaxWidthHeightLog2));
+              size[0] = builder_->createTriOp(spv::OpSelect, type_uint_, data_is_3d, size_3d,
+                                              size[0]);
+            }
           }
           if (size_needed_components & 0b10) {
             spv::Id width_height_bit_count =
@@ -879,6 +898,15 @@ void SpirvShaderTranslator::ProcessTextureFetchInstruction(
             size[1] =
                 builder_->createTriOp(spv::OpBitFieldUExtract, type_uint_, fetch_constant_word_2,
                                       width_height_bit_count, width_height_bit_count);
+            if (is_2d) {
+              spv::Id bit_count_3d =
+                  builder_->makeUintConstant(xenos::kTexture3DMaxWidthHeightLog2);
+              spv::Id size_3d =
+                  builder_->createTriOp(spv::OpBitFieldUExtract, type_uint_, fetch_constant_word_2,
+                                        bit_count_3d, bit_count_3d);
+              size[1] = builder_->createTriOp(spv::OpSelect, type_uint_, data_is_3d, size_3d,
+                                              size[1]);
+            }
           }
           assert_zero(size_needed_components & 0b100);
         } break;
diff --git a/src/graphics/shaders/bytecode/d3d12_5_1/float24_round_ps_position_only.h b/src/graphics/shaders/bytecode/d3d12_5_1/float24_round_ps_position_only.h
new file mode 100644
index 0000000..201959d
--- /dev/null
+++ b/src/graphics/shaders/bytecode/d3d12_5_1/float24_round_ps_position_only.h
@@ -0,0 +1,73 @@
+// Derived from float24_round_ps.h: identical depth instructions, SV_Position at v0.
+// Generated by work/generate-position-only-depth.py; original licensing applies.
+const BYTE float24_round_ps_position_only[] = {
+  68, 88, 66, 67, 162, 99, 171, 178, 104, 88, 180, 227, 99, 114, 31, 75, 42, 220, 126, 82,
+  1, 0, 0, 0, 100, 5, 0, 0, 5, 0, 0, 0, 52, 0, 0, 0, 160, 0, 0, 0,
+  212, 0, 0, 0, 8, 1, 0, 0, 200, 4, 0, 0, 82, 68, 69, 70, 100, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 0, 0, 0, 1, 5, 255, 255,
+  0, 5, 0, 0, 60, 0, 0, 0, 19, 19, 68, 37, 60, 0, 0, 0, 24, 0, 0, 0,
+  40, 0, 0, 0, 40, 0, 0, 0, 36, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0,
+  77, 105, 99, 114, 111, 115, 111, 102, 116, 32, 40, 82, 41, 32, 72, 76, 83, 76, 32, 83,
+  104, 97, 100, 101, 114, 32, 67, 111, 109, 112, 105, 108, 101, 114, 32, 49, 48, 46, 49, 0,
+  73, 83, 71, 78, 44, 0, 0, 0, 1, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0,
+  0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 15, 4, 0, 0,
+  83, 86, 95, 80, 111, 115, 105, 116, 105, 111, 110, 0, 79, 83, 71, 78, 44, 0, 0, 0,
+  1, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  3, 0, 0, 0, 255, 255, 255, 255, 1, 14, 0, 0, 83, 86, 95, 68, 101, 112, 116, 104,
+  0, 171, 171, 171, 83, 72, 69, 88, 184, 3, 0, 0, 81, 0, 0, 0, 238, 0, 0, 0,
+  106, 8, 0, 1, 100, 56, 0, 4, 66, 16, 16, 0, 0, 0, 0, 0, 1, 0, 0, 0,
+  101, 0, 0, 2, 1, 192, 0, 0, 104, 0, 0, 2, 2, 0, 0, 0, 56, 32, 8, 7,
+  18, 0, 16, 0, 0, 0, 0, 0, 42, 16, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0,
+  0, 0, 0, 64, 80, 0, 16, 7, 34, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0,
+  255, 255, 255, 127, 10, 0, 16, 0, 0, 0, 0, 0, 1, 0, 8, 7, 18, 0, 16, 0,
+  0, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0,
+  84, 0, 8, 7, 18, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0,
+  1, 64, 0, 0, 248, 255, 255, 63, 140, 0, 16, 11, 34, 0, 16, 0, 0, 0, 0, 0,
+  1, 64, 0, 0, 23, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 0, 10, 0, 16, 0,
+  0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 128, 0, 85, 0, 32, 7, 66, 0, 16, 0,
+  0, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 23, 0, 0, 0,
+  30, 0, 32, 8, 66, 0, 16, 0, 0, 0, 0, 0, 42, 0, 16, 128, 65, 0, 0, 0,
+  0, 0, 0, 0, 1, 64, 0, 0, 113, 0, 0, 0, 84, 0, 32, 7, 66, 0, 16, 0,
+  0, 0, 0, 0, 42, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 24, 0, 0, 0,
+  85, 0, 16, 7, 34, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0,
+  42, 0, 16, 0, 0, 0, 0, 0, 79, 0, 32, 7, 66, 0, 16, 0, 0, 0, 0, 0,
+  10, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 128, 56, 30, 0, 8, 7,
+  18, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0,
+  0, 0, 0, 200, 55, 0, 8, 9, 18, 0, 16, 0, 0, 0, 0, 0, 42, 0, 16, 0,
+  0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0,
+  138, 0, 16, 9, 34, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 1, 0, 0, 0,
+  1, 64, 0, 0, 3, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 30, 0, 8, 7,
+  18, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0,
+  0, 0, 0, 0, 30, 0, 8, 7, 18, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0,
+  0, 0, 0, 0, 1, 64, 0, 0, 3, 0, 0, 0, 138, 0, 56, 15, 114, 0, 16, 0,
+  0, 0, 0, 0, 2, 64, 0, 0, 24, 0, 0, 0, 20, 0, 0, 0, 4, 0, 0, 0,
+  0, 0, 0, 0, 2, 64, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 23, 0, 0, 0,
+  0, 0, 0, 0, 6, 0, 16, 0, 0, 0, 0, 0, 135, 0, 64, 5, 130, 0, 16, 0,
+  0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 30, 0, 64, 7, 130, 0, 16, 0,
+  0, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 245, 255, 255, 255,
+  55, 0, 64, 9, 130, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0,
+  58, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 21, 0, 0, 0, 30, 0, 8, 8,
+  18, 0, 16, 0, 1, 0, 0, 0, 58, 0, 16, 128, 65, 0, 0, 0, 0, 0, 0, 0,
+  1, 64, 0, 0, 1, 0, 0, 0, 55, 0, 8, 9, 18, 0, 16, 0, 1, 0, 0, 0,
+  42, 0, 16, 0, 0, 0, 0, 0, 42, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0,
+  1, 0, 0, 0, 41, 0, 64, 7, 130, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0,
+  0, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 1, 0, 64, 7, 130, 0, 16, 0,
+  0, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 255, 255, 15, 0,
+  55, 0, 16, 9, 34, 0, 16, 0, 0, 0, 0, 0, 42, 0, 16, 0, 0, 0, 0, 0,
+  26, 0, 16, 0, 0, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 41, 0, 32, 7,
+  66, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 1, 0, 0, 0, 1, 64, 0, 0,
+  23, 0, 0, 0, 30, 0, 32, 7, 66, 0, 16, 0, 0, 0, 0, 0, 42, 0, 16, 0,
+  0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 128, 55, 41, 0, 16, 7, 34, 0, 16, 0,
+  0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 3, 0, 0, 0,
+  30, 0, 16, 7, 34, 0, 16, 0, 0, 0, 0, 0, 42, 0, 16, 0, 0, 0, 0, 0,
+  26, 0, 16, 0, 0, 0, 0, 0, 55, 0, 8, 8, 1, 192, 0, 0, 10, 0, 16, 0,
+  0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 0,
+  62, 0, 0, 1, 83, 84, 65, 84, 148, 0, 0, 0, 30, 0, 0, 0, 2, 0, 0, 0,
+  0, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 11, 0, 0, 0, 8, 0, 0, 0,
+  1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+};
diff --git a/src/graphics/shaders/bytecode/d3d12_5_1/float24_truncate_ps_position_only.h b/src/graphics/shaders/bytecode/d3d12_5_1/float24_truncate_ps_position_only.h
new file mode 100644
index 0000000..fb3ad69
--- /dev/null
+++ b/src/graphics/shaders/bytecode/d3d12_5_1/float24_truncate_ps_position_only.h
@@ -0,0 +1,42 @@
+// Derived from float24_truncate_ps.h: identical depth instructions, SV_Position at v0.
+// Generated by work/generate-position-only-depth.py; original licensing applies.
+const BYTE float24_truncate_ps_position_only[] = {
+  68, 88, 66, 67, 58, 223, 9, 93, 150, 73, 58, 100, 233, 164, 57, 28, 8, 192, 95, 196,
+  1, 0, 0, 0, 232, 2, 0, 0, 5, 0, 0, 0, 52, 0, 0, 0, 160, 0, 0, 0,
+  212, 0, 0, 0, 16, 1, 0, 0, 76, 2, 0, 0, 82, 68, 69, 70, 100, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 0, 0, 0, 1, 5, 255, 255,
+  0, 5, 0, 0, 60, 0, 0, 0, 19, 19, 68, 37, 60, 0, 0, 0, 24, 0, 0, 0,
+  40, 0, 0, 0, 40, 0, 0, 0, 36, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0,
+  77, 105, 99, 114, 111, 115, 111, 102, 116, 32, 40, 82, 41, 32, 72, 76, 83, 76, 32, 83,
+  104, 97, 100, 101, 114, 32, 67, 111, 109, 112, 105, 108, 101, 114, 32, 49, 48, 46, 49, 0,
+  73, 83, 71, 78, 44, 0, 0, 0, 1, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0,
+  0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 15, 4, 0, 0,
+  83, 86, 95, 80, 111, 115, 105, 116, 105, 111, 110, 0, 79, 83, 71, 78, 52, 0, 0, 0,
+  1, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  3, 0, 0, 0, 255, 255, 255, 255, 1, 14, 0, 0, 83, 86, 95, 68, 101, 112, 116, 104,
+  76, 101, 115, 115, 69, 113, 117, 97, 108, 0, 171, 171, 83, 72, 69, 88, 52, 1, 0, 0,
+  81, 0, 0, 0, 77, 0, 0, 0, 106, 8, 0, 1, 100, 56, 0, 4, 66, 16, 16, 0,
+  0, 0, 0, 0, 1, 0, 0, 0, 101, 0, 0, 2, 1, 112, 2, 0, 104, 0, 0, 2,
+  1, 0, 0, 0, 56, 32, 8, 7, 18, 0, 16, 0, 0, 0, 0, 0, 42, 16, 16, 0,
+  0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 64, 80, 0, 16, 7, 34, 0, 16, 0,
+  0, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 128, 46,
+  31, 0, 4, 3, 26, 0, 16, 0, 0, 0, 0, 0, 138, 0, 16, 9, 34, 0, 16, 0,
+  0, 0, 0, 0, 1, 64, 0, 0, 8, 0, 0, 0, 1, 64, 0, 0, 23, 0, 0, 0,
+  10, 0, 16, 0, 0, 0, 0, 0, 30, 0, 16, 8, 34, 0, 16, 0, 0, 0, 0, 0,
+  26, 0, 16, 128, 65, 0, 0, 0, 0, 0, 0, 0, 1, 64, 0, 0, 116, 0, 0, 0,
+  36, 0, 16, 7, 34, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0,
+  1, 64, 0, 0, 3, 0, 0, 0, 140, 0, 8, 11, 18, 0, 16, 0, 0, 0, 0, 0,
+  26, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 0, 1, 64, 0, 0,
+  0, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 18, 0, 0, 1, 54, 0, 8, 5,
+  18, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 0, 21, 0, 0, 1,
+  56, 0, 8, 6, 1, 112, 2, 0, 10, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0,
+  0, 0, 0, 63, 62, 0, 0, 1, 83, 84, 65, 84, 148, 0, 0, 0, 12, 0, 0, 0,
+  1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0,
+  1, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0,
+};
diff --git a/src/graphics/shaders/bytecode/d3d12_5_1/resolve_downscale_cs.h b/src/graphics/shaders/bytecode/d3d12_5_1/resolve_downscale_cs.h
index da071c5..ed8e52e 100644
--- a/src/graphics/shaders/bytecode/d3d12_5_1/resolve_downscale_cs.h
+++ b/src/graphics/shaders/bytecode/d3d12_5_1/resolve_downscale_cs.h
@@ -1,6 +1,31 @@
 #if 0
 //
-// Generated by Microsoft (R) D3D Shader Disassembler
+// Generated by Microsoft (R) HLSL Shader Compiler 10.1
+//
+//
+// Buffer Definitions: 
+//
+// cbuffer XeResolveDownscaleConstants
+// {
+//
+//   uint xe_downscale_scale_x;         // Offset:    0 Size:     4
+//   uint xe_downscale_scale_y;         // Offset:    4 Size:     4
+//   uint xe_downscale_pixel_size_log2; // Offset:    8 Size:     4
+//   uint xe_downscale_tile_count;      // Offset:   12 Size:     4
+//   uint xe_downscale_half_pixel_offset;// Offset:   16 Size:     4
+//   uint xe_downscale_average;         // Offset:   20 Size:     4
+//
+// }
+//
+//
+// Resource Bindings:
+//
+// Name                                 Type  Format         Dim      ID      HLSL Bind  Count
+// ------------------------------ ---------- ------- ----------- ------- -------------- ------
+// xe_resolve_source                 texture    byte         r/o      T0             t0      1 
+// xe_resolve_dest                       UAV    byte         r/w      U0             u0      1 
+// XeResolveDownscaleConstants       cbuffer      NA          NA     CB0            cb0      1 
+//
 //
 //
 // Input signature:
@@ -15,19 +40,19 @@
 // -------------------- ----- ------ -------- -------- ------- ------
 // no Output
 cs_5_1
-dcl_globalFlags refactoringAllowed | allResourcesBound
+dcl_globalFlags refactoringAllowed
 dcl_constantbuffer CB0[0:0][2], immediateIndexed, space=0
 dcl_resource_raw T0[0:0], space=0
 dcl_uav_raw U0[0:0], space=0
 dcl_input vThreadGroupID.x
 dcl_input vThreadIDInGroup.xy
-dcl_temps 2
+dcl_temps 4
 dcl_tgsm_structured g0, 4, 1024
 dcl_thread_group 32, 32, 1
 uge r0.x, vThreadGroupID.x, CB0[0][0].w
 if_nz r0.x
-  ret
-endif
+  ret 
+endif 
 imad r0.x, vThreadIDInGroup.y, l(32), vThreadIDInGroup.x
 ishl r0.yz, l(0, 1, 1024, 0), CB0[0][0].zzzz
 imul null, r0.w, CB0[0][0].y, CB0[0][0].x
@@ -35,193 +60,743 @@ ine r1.y, CB0[0][1].x, l(0)
 ult r1.z, l(1), r0.w
 and r1.y, r1.z, r1.y
 if_nz r1.y
-  ushr r1.yz, CB0[0][0].xxyx, l(0, 1, 1, 0)
-  imad r1.y, r1.z, CB0[0][0].x, r1.y
-else
+  ushr r1.yw, CB0[0][0].xxxy, l(0, 1, 0, 1)
+  imad r1.y, r1.w, CB0[0][0].x, r1.y
+else 
   mov r1.y, l(0)
-endif
-imul null, r1.xz, r0.wwyw, r0.zzxz
-imul null, r0.w, r0.w, r1.z
-imad r0.w, vThreadGroupID.x, r1.x, r0.w
-imad r0.y, r1.y, r0.y, r0.w
-ult r0.w, CB0[0][0].z, l(2)
-if_nz r0.w
+endif 
+imul null, r1.xw, r0.wwwy, r0.zzzx
+imul null, r2.x, r0.w, r1.w
+imad r1.x, vThreadGroupID.x, r1.x, r2.x
+imad r0.y, r1.y, r0.y, r1.x
+ult r1.y, CB0[0][0].z, l(2)
+if_nz r1.y
   if_z CB0[0][0].z
-    and r0.w, r0.y, l(-4)
-    ld_raw r0.w, r0.w, T0[0].xxxx
-    bfi r1.xw, l(2, 0, 0, 2), l(3, 0, 0, 3), r0.yyyx, l(0, 0, 0, 0)
-    ushr r0.w, r0.w, r1.x
-    ushr r1.x, r0.x, l(2)
-    and r1.z, r0.x, l(3)
-    bfi r0.w, l(8), r1.w, r0.w, l(0)
-    if_z r1.z
-      store_structured g0.x, r1.x, l(0), r0.w
-    endif
+    and r1.y, r0.y, l(-4)
+    ld_raw r1.y, r1.y, T0[0].xxxx
+    bfi r1.w, l(2), l(3), r0.y, l(0)
+    ushr r1.y, r1.y, r1.w
+    ushr r2.x, r0.x, l(2)
+    and r1.w, r0.x, l(3)
+    bfi r2.z, l(2), l(3), r0.x, l(0)
+    bfi r1.y, l(8), r2.z, r1.y, l(0)
+    if_z r1.w
+      store_structured g0.x, r2.x, l(0), r1.y
+    endif 
     sync_g_t
-    if_nz r1.z
-      mov r1.y, l(0)
-      atomic_or g0, r1.xyxx, r0.w
-    endif
+    if_nz r1.w
+      mov r2.y, l(0)
+      atomic_or g0, r2.xyxx, r1.y
+    endif 
     sync_g_t
-    if_z r1.z
-      and r0.w, r0.x, l(1020)
-      imad r0.w, vThreadGroupID.x, l(1024), r0.w
-      ld_structured r1.x, r1.x, l(0), g0.xxxx
-      store_raw U0[0].x, r0.w, r1.x
-    endif
-  else
-    and r0.w, r0.y, l(-4)
-    ld_raw r0.w, r0.w, T0[0].xxxx
-    ishl r1.x, r0.y, l(3)
-    and r1.x, r1.x, l(16)
-    ushr r0.w, r0.w, r1.x
-    ushr r1.x, r0.x, l(1)
-    and r1.z, r0.x, l(1)
+    if_z r1.w
+      and r1.y, r0.x, l(1020)
+      imad r1.y, vThreadGroupID.x, l(1024), r1.y
+      ld_structured r1.w, r2.x, l(0), g0.xxxx
+      store_raw U0[0].x, r1.y, r1.w
+    endif 
+  else 
+    and r1.y, r0.y, l(-4)
+    ld_raw r1.y, r1.y, T0[0].xxxx
+    ishl r1.w, r0.y, l(3)
+    and r1.w, r1.w, l(16)
+    ushr r1.y, r1.y, r1.w
+    ushr r2.x, r0.x, l(1)
+    and r1.w, r0.x, l(1)
     bfi r0.x, l(1), l(4), r0.x, l(0)
-    bfi r0.x, l(16), r0.x, r0.w, l(0)
-    if_z r1.z
-      store_structured g0.x, r1.x, l(0), r0.x
-    endif
+    bfi r0.x, l(16), r0.x, r1.y, l(0)
+    if_z r1.w
+      store_structured g0.x, r2.x, l(0), r0.x
+    endif 
     sync_g_t
-    if_nz r1.z
-      mov r1.y, l(0)
-      atomic_or g0, r1.xyxx, r0.x
-    endif
+    if_nz r1.w
+      mov r2.y, l(0)
+      atomic_or g0, r2.xyxx, r0.x
+    endif 
     sync_g_t
-    if_z r1.z
-      ishl r0.x, r1.x, l(2)
+    if_z r1.w
+      ishl r0.x, r2.x, l(2)
       imad r0.x, vThreadGroupID.x, l(2048), r0.x
-      ld_structured r0.w, r1.x, l(0), g0.xxxx
-      store_raw U0[0].x, r0.x, r0.w
-    endif
-  endif
-else
-  imad r0.z, vThreadGroupID.x, r0.z, r1.z
+      ld_structured r1.y, r2.x, l(0), g0.xxxx
+      store_raw U0[0].x, r0.x, r1.y
+    endif 
+  endif 
+else 
+  imad r0.z, vThreadGroupID.x, r0.z, r1.w
   ieq r0.x, CB0[0][0].z, l(2)
   if_nz r0.x
-    ld_raw r0.x, r0.y, T0[0].xxxx
+    ine r0.x, CB0[0][1].y, l(0)
+    and r0.x, r1.z, r0.x
+    if_nz r0.x
+      mov r2.xyzw, l(0,0,0,0)
+      mov r0.x, l(0)
+      loop 
+        uge r1.y, r0.x, r0.w
+        breakc_nz r1.y
+        ishl r1.y, r0.x, l(2)
+        iadd r1.y, r1.y, r1.x
+        ld_raw r1.y, r1.y, T0[0].xxxx
+        and r3.x, r1.y, l(255)
+        ubfe r3.yz, l(0, 8, 8, 0), l(0, 8, 16, 0), r1.yyyy
+        ushr r3.w, r1.y, l(24)
+        iadd r2.xyzw, r2.xyzw, r3.xyzw
+        iadd r0.x, r0.x, l(1)
+      endloop 
+      ushr r0.x, r0.w, l(1)
+      iadd r1.xyzw, r0.xxxx, r2.xyzw
+      udiv r1.xyzw, null, r1.xyzw, r0.wwww
+      ishl r1.yzw, r1.yyzw, l(0, 8, 16, 24)
+      or r0.x, r1.y, r1.x
+      or r0.x, r1.z, r0.x
+      or r0.x, r1.w, r0.x
+    else 
+      ld_raw r0.x, r0.y, T0[0].xxxx
+    endif 
     store_raw U0[0].x, r0.z, r0.x
-  else
+  else 
     ieq r0.x, CB0[0][0].z, l(3)
     if_nz r0.x
       ld_raw r0.xy, r0.y, T0[0].xyxx
       store_raw U0[0].xy, r0.z, r0.xyxx
-    endif
-  endif
-endif
-ret
-// Approximately 0 instruction slots used
+    endif 
+  endif 
+endif 
+ret 
+// Approximately 113 instruction slots used
 #endif
 
-const BYTE resolve_downscale_cs[] = {
-    68,  88,  66, 67, 235, 139, 102, 94, 189, 150, 220, 235, 94,  229, 59, 205, 74,  78,  159, 167,
-    1,   0,   0,  0,  164, 8,   0,   0,  3,   0,   0,   0,   44,  0,   0,  0,   60,  0,   0,   0,
-    76,  0,   0,  0,  73,  83,  71,  78, 8,   0,   0,   0,   0,   0,   0,  0,   8,   0,   0,   0,
-    79,  83,  71, 78, 8,   0,   0,   0,  0,   0,   0,   0,   8,   0,   0,  0,   83,  72,  69,  88,
-    80,  8,   0,  0,  81,  0,   5,   0,  20,  2,   0,   0,   106, 8,   8,  1,   89,  0,   0,   7,
-    70,  142, 48, 0,  0,   0,   0,   0,  0,   0,   0,   0,   0,   0,   0,  0,   2,   0,   0,   0,
-    0,   0,   0,  0,  161, 0,   0,   6,  70,  126, 48,  0,   0,   0,   0,  0,   0,   0,   0,   0,
-    0,   0,   0,  0,  0,   0,   0,   0,  157, 0,   0,   6,   70,  238, 49, 0,   0,   0,   0,   0,
-    0,   0,   0,  0,  0,   0,   0,   0,  0,   0,   0,   0,   95,  0,   0,  2,   18,  16,  2,   0,
-    95,  0,   0,  2,  50,  32,  2,   0,  104, 0,   0,   2,   2,   0,   0,  0,   160, 0,   0,   5,
-    0,   240, 17, 0,  0,   0,   0,   0,  4,   0,   0,   0,   0,   4,   0,  0,   155, 0,   0,   4,
-    32,  0,   0,  0,  32,  0,   0,   0,  1,   0,   0,   0,   80,  0,   0,  8,   18,  0,   16,  0,
-    0,   0,   0,  0,  10,  16,  2,   0,  58,  128, 48,  0,   0,   0,   0,  0,   0,   0,   0,   0,
-    0,   0,   0,  0,  31,  0,   4,   3,  10,  0,   16,  0,   0,   0,   0,  0,   62,  0,   0,   1,
-    21,  0,   0,  1,  35,  0,   0,   7,  18,  0,   16,  0,   0,   0,   0,  0,   26,  32,  2,   0,
-    1,   64,  0,  0,  32,  0,   0,   0,  10,  32,  2,   0,   41,  0,   0,  12,  98,  0,   16,  0,
-    0,   0,   0,  0,  2,   64,  0,   0,  0,   0,   0,   0,   1,   0,   0,  0,   0,   4,   0,   0,
-    0,   0,   0,  0,  166, 138, 48,  0,  0,   0,   0,   0,   0,   0,   0,  0,   0,   0,   0,   0,
-    38,  0,   0,  12, 0,   208, 0,   0,  130, 0,   16,  0,   0,   0,   0,  0,   26,  128, 48,  0,
-    0,   0,   0,  0,  0,   0,   0,   0,  0,   0,   0,   0,   10,  128, 48, 0,   0,   0,   0,   0,
-    0,   0,   0,  0,  0,   0,   0,   0,  39,  0,   0,   9,   34,  0,   16, 0,   1,   0,   0,   0,
-    10,  128, 48, 0,  0,   0,   0,   0,  0,   0,   0,   0,   1,   0,   0,  0,   1,   64,  0,   0,
-    0,   0,   0,  0,  79,  0,   0,   7,  66,  0,   16,  0,   1,   0,   0,  0,   1,   64,  0,   0,
-    1,   0,   0,  0,  58,  0,   16,  0,  0,   0,   0,   0,   1,   0,   0,  7,   34,  0,   16,  0,
-    1,   0,   0,  0,  42,  0,   16,  0,  1,   0,   0,   0,   26,  0,   16, 0,   1,   0,   0,   0,
-    31,  0,   4,  3,  26,  0,   16,  0,  1,   0,   0,   0,   85,  0,   0,  12,  98,  0,   16,  0,
-    1,   0,   0,  0,  6,   129, 48,  0,  0,   0,   0,   0,   0,   0,   0,  0,   0,   0,   0,   0,
-    2,   64,  0,  0,  0,   0,   0,   0,  1,   0,   0,   0,   1,   0,   0,  0,   0,   0,   0,   0,
-    35,  0,   0,  11, 34,  0,   16,  0,  1,   0,   0,   0,   42,  0,   16, 0,   1,   0,   0,   0,
-    10,  128, 48, 0,  0,   0,   0,   0,  0,   0,   0,   0,   0,   0,   0,  0,   26,  0,   16,  0,
-    1,   0,   0,  0,  18,  0,   0,   1,  54,  0,   0,   5,   34,  0,   16, 0,   1,   0,   0,   0,
-    1,   64,  0,  0,  0,   0,   0,   0,  21,  0,   0,   1,   38,  0,   0,  8,   0,   208, 0,   0,
-    82,  0,   16, 0,  1,   0,   0,   0,  246, 13,  16,  0,   0,   0,   0,  0,   166, 8,   16,  0,
-    0,   0,   0,  0,  38,  0,   0,   8,  0,   208, 0,   0,   130, 0,   16, 0,   0,   0,   0,   0,
-    58,  0,   16, 0,  0,   0,   0,   0,  42,  0,   16,  0,   1,   0,   0,  0,   35,  0,   0,   8,
-    130, 0,   16, 0,  0,   0,   0,   0,  10,  16,  2,   0,   10,  0,   16, 0,   1,   0,   0,   0,
-    58,  0,   16, 0,  0,   0,   0,   0,  35,  0,   0,   9,   34,  0,   16, 0,   0,   0,   0,   0,
-    26,  0,   16, 0,  1,   0,   0,   0,  26,  0,   16,  0,   0,   0,   0,  0,   58,  0,   16,  0,
-    0,   0,   0,  0,  79,  0,   0,   9,  130, 0,   16,  0,   0,   0,   0,  0,   42,  128, 48,  0,
-    0,   0,   0,  0,  0,   0,   0,   0,  0,   0,   0,   0,   1,   64,  0,  0,   2,   0,   0,   0,
-    31,  0,   4,  3,  58,  0,   16,  0,  0,   0,   0,   0,   31,  0,   0,  5,   42,  128, 48,  0,
-    0,   0,   0,  0,  0,   0,   0,   0,  0,   0,   0,   0,   1,   0,   0,  7,   130, 0,   16,  0,
-    0,   0,   0,  0,  26,  0,   16,  0,  0,   0,   0,   0,   1,   64,  0,  0,   252, 255, 255, 255,
-    165, 0,   0,  8,  130, 0,   16,  0,  0,   0,   0,   0,   58,  0,   16, 0,   0,   0,   0,   0,
-    6,   112, 32, 0,  0,   0,   0,   0,  0,   0,   0,   0,   140, 0,   0,  20,  146, 0,   16,  0,
-    1,   0,   0,  0,  2,   64,  0,   0,  2,   0,   0,   0,   0,   0,   0,  0,   0,   0,   0,   0,
-    2,   0,   0,  0,  2,   64,  0,   0,  3,   0,   0,   0,   0,   0,   0,  0,   0,   0,   0,   0,
-    3,   0,   0,  0,  86,  1,   16,  0,  0,   0,   0,   0,   2,   64,  0,  0,   0,   0,   0,   0,
-    0,   0,   0,  0,  0,   0,   0,   0,  0,   0,   0,   0,   85,  0,   0,  7,   130, 0,   16,  0,
-    0,   0,   0,  0,  58,  0,   16,  0,  0,   0,   0,   0,   10,  0,   16, 0,   1,   0,   0,   0,
-    85,  0,   0,  7,  18,  0,   16,  0,  1,   0,   0,   0,   10,  0,   16, 0,   0,   0,   0,   0,
-    1,   64,  0,  0,  2,   0,   0,   0,  1,   0,   0,   7,   66,  0,   16, 0,   1,   0,   0,   0,
-    10,  0,   16, 0,  0,   0,   0,   0,  1,   64,  0,   0,   3,   0,   0,  0,   140, 0,   0,   11,
-    130, 0,   16, 0,  0,   0,   0,   0,  1,   64,  0,   0,   8,   0,   0,  0,   58,  0,   16,  0,
-    1,   0,   0,  0,  58,  0,   16,  0,  0,   0,   0,   0,   1,   64,  0,  0,   0,   0,   0,   0,
-    31,  0,   0,  3,  42,  0,   16,  0,  1,   0,   0,   0,   168, 0,   0,  9,   18,  240, 17,  0,
-    0,   0,   0,  0,  10,  0,   16,  0,  1,   0,   0,   0,   1,   64,  0,  0,   0,   0,   0,   0,
-    58,  0,   16, 0,  0,   0,   0,   0,  21,  0,   0,   1,   190, 24,  0,  1,   31,  0,   4,   3,
-    42,  0,   16, 0,  1,   0,   0,   0,  54,  0,   0,   5,   34,  0,   16, 0,   1,   0,   0,   0,
-    1,   64,  0,  0,  0,   0,   0,   0,  170, 0,   0,   7,   0,   240, 17, 0,   0,   0,   0,   0,
-    70,  0,   16, 0,  1,   0,   0,   0,  58,  0,   16,  0,   0,   0,   0,  0,   21,  0,   0,   1,
-    190, 24,  0,  1,  31,  0,   0,   3,  42,  0,   16,  0,   1,   0,   0,  0,   1,   0,   0,   7,
-    130, 0,   16, 0,  0,   0,   0,   0,  10,  0,   16,  0,   0,   0,   0,  0,   1,   64,  0,   0,
-    252, 3,   0,  0,  35,  0,   0,   8,  130, 0,   16,  0,   0,   0,   0,  0,   10,  16,  2,   0,
-    1,   64,  0,  0,  0,   4,   0,   0,  58,  0,   16,  0,   0,   0,   0,  0,   167, 0,   0,   9,
-    18,  0,   16, 0,  1,   0,   0,   0,  10,  0,   16,  0,   1,   0,   0,  0,   1,   64,  0,   0,
-    0,   0,   0,  0,  6,   240, 17,  0,  0,   0,   0,   0,   166, 0,   0,  8,   18,  224, 33,  0,
-    0,   0,   0,  0,  0,   0,   0,   0,  58,  0,   16,  0,   0,   0,   0,  0,   10,  0,   16,  0,
-    1,   0,   0,  0,  21,  0,   0,   1,  18,  0,   0,   1,   1,   0,   0,  7,   130, 0,   16,  0,
-    0,   0,   0,  0,  26,  0,   16,  0,  0,   0,   0,   0,   1,   64,  0,  0,   252, 255, 255, 255,
-    165, 0,   0,  8,  130, 0,   16,  0,  0,   0,   0,   0,   58,  0,   16, 0,   0,   0,   0,   0,
-    6,   112, 32, 0,  0,   0,   0,   0,  0,   0,   0,   0,   41,  0,   0,  7,   18,  0,   16,  0,
-    1,   0,   0,  0,  26,  0,   16,  0,  0,   0,   0,   0,   1,   64,  0,  0,   3,   0,   0,   0,
-    1,   0,   0,  7,  18,  0,   16,  0,  1,   0,   0,   0,   10,  0,   16, 0,   1,   0,   0,   0,
-    1,   64,  0,  0,  16,  0,   0,   0,  85,  0,   0,   7,   130, 0,   16, 0,   0,   0,   0,   0,
-    58,  0,   16, 0,  0,   0,   0,   0,  10,  0,   16,  0,   1,   0,   0,  0,   85,  0,   0,   7,
-    18,  0,   16, 0,  1,   0,   0,   0,  10,  0,   16,  0,   0,   0,   0,  0,   1,   64,  0,   0,
-    1,   0,   0,  0,  1,   0,   0,   7,  66,  0,   16,  0,   1,   0,   0,  0,   10,  0,   16,  0,
-    0,   0,   0,  0,  1,   64,  0,   0,  1,   0,   0,   0,   140, 0,   0,  11,  18,  0,   16,  0,
-    0,   0,   0,  0,  1,   64,  0,   0,  1,   0,   0,   0,   1,   64,  0,  0,   4,   0,   0,   0,
-    10,  0,   16, 0,  0,   0,   0,   0,  1,   64,  0,   0,   0,   0,   0,  0,   140, 0,   0,   11,
-    18,  0,   16, 0,  0,   0,   0,   0,  1,   64,  0,   0,   16,  0,   0,  0,   10,  0,   16,  0,
-    0,   0,   0,  0,  58,  0,   16,  0,  0,   0,   0,   0,   1,   64,  0,  0,   0,   0,   0,   0,
-    31,  0,   0,  3,  42,  0,   16,  0,  1,   0,   0,   0,   168, 0,   0,  9,   18,  240, 17,  0,
-    0,   0,   0,  0,  10,  0,   16,  0,  1,   0,   0,   0,   1,   64,  0,  0,   0,   0,   0,   0,
-    10,  0,   16, 0,  0,   0,   0,   0,  21,  0,   0,   1,   190, 24,  0,  1,   31,  0,   4,   3,
-    42,  0,   16, 0,  1,   0,   0,   0,  54,  0,   0,   5,   34,  0,   16, 0,   1,   0,   0,   0,
-    1,   64,  0,  0,  0,   0,   0,   0,  170, 0,   0,   7,   0,   240, 17, 0,   0,   0,   0,   0,
-    70,  0,   16, 0,  1,   0,   0,   0,  10,  0,   16,  0,   0,   0,   0,  0,   21,  0,   0,   1,
-    190, 24,  0,  1,  31,  0,   0,   3,  42,  0,   16,  0,   1,   0,   0,  0,   41,  0,   0,   7,
-    18,  0,   16, 0,  0,   0,   0,   0,  10,  0,   16,  0,   1,   0,   0,  0,   1,   64,  0,   0,
-    2,   0,   0,  0,  35,  0,   0,   8,  18,  0,   16,  0,   0,   0,   0,  0,   10,  16,  2,   0,
-    1,   64,  0,  0,  0,   8,   0,   0,  10,  0,   16,  0,   0,   0,   0,  0,   167, 0,   0,   9,
-    130, 0,   16, 0,  0,   0,   0,   0,  10,  0,   16,  0,   1,   0,   0,  0,   1,   64,  0,   0,
-    0,   0,   0,  0,  6,   240, 17,  0,  0,   0,   0,   0,   166, 0,   0,  8,   18,  224, 33,  0,
-    0,   0,   0,  0,  0,   0,   0,   0,  10,  0,   16,  0,   0,   0,   0,  0,   58,  0,   16,  0,
-    0,   0,   0,  0,  21,  0,   0,   1,  21,  0,   0,   1,   18,  0,   0,  1,   35,  0,   0,   8,
-    66,  0,   16, 0,  0,   0,   0,   0,  10,  16,  2,   0,   42,  0,   16, 0,   0,   0,   0,   0,
-    42,  0,   16, 0,  1,   0,   0,   0,  32,  0,   0,   9,   18,  0,   16, 0,   0,   0,   0,   0,
-    42,  128, 48, 0,  0,   0,   0,   0,  0,   0,   0,   0,   0,   0,   0,  0,   1,   64,  0,   0,
-    2,   0,   0,  0,  31,  0,   4,   3,  10,  0,   16,  0,   0,   0,   0,  0,   165, 0,   0,   8,
-    18,  0,   16, 0,  0,   0,   0,   0,  26,  0,   16,  0,   0,   0,   0,  0,   6,   112, 32,  0,
-    0,   0,   0,  0,  0,   0,   0,   0,  166, 0,   0,   8,   18,  224, 33, 0,   0,   0,   0,   0,
-    0,   0,   0,  0,  42,  0,   16,  0,  0,   0,   0,   0,   10,  0,   16, 0,   0,   0,   0,   0,
-    18,  0,   0,  1,  32,  0,   0,   9,  18,  0,   16,  0,   0,   0,   0,  0,   42,  128, 48,  0,
-    0,   0,   0,  0,  0,   0,   0,   0,  0,   0,   0,   0,   1,   64,  0,  0,   3,   0,   0,   0,
-    31,  0,   4,  3,  10,  0,   16,  0,  0,   0,   0,   0,   165, 0,   0,  8,   50,  0,   16,  0,
-    0,   0,   0,  0,  26,  0,   16,  0,  0,   0,   0,   0,   70,  112, 32, 0,   0,   0,   0,   0,
-    0,   0,   0,  0,  166, 0,   0,   8,  50,  224, 33,  0,   0,   0,   0,  0,   0,   0,   0,   0,
-    42,  0,   16, 0,  0,   0,   0,   0,  70,  0,   16,  0,   0,   0,   0,  0,   21,  0,   0,   1,
-    21,  0,   0,  1,  21,  0,   0,   1,  62,  0,   0,   1};
+const BYTE resolve_downscale_cs[] =
+{
+     68,  88,  66,  67, 132, 194, 
+    134, 149, 211, 248,  31, 125, 
+    111, 222,  59,  55, 141,  27, 
+    121, 240,   1,   0,   0,   0, 
+    204,  14,   0,   0,   5,   0, 
+      0,   0,  52,   0,   0,   0, 
+     32,   3,   0,   0,  48,   3, 
+      0,   0,  64,   3,   0,   0, 
+     48,  14,   0,   0,  82,  68, 
+     69,  70, 228,   2,   0,   0, 
+      1,   0,   0,   0, 244,   0, 
+      0,   0,   3,   0,   0,   0, 
+     60,   0,   0,   0,   1,   5, 
+     83,  67,   0, 133,   0,   0, 
+    186,   2,   0,   0,  19,  19, 
+     68,  37,  60,   0,   0,   0, 
+     24,   0,   0,   0,  40,   0, 
+      0,   0,  40,   0,   0,   0, 
+     36,   0,   0,   0,  12,   0, 
+      0,   0,   0,   0,   0,   0, 
+    180,   0,   0,   0,   7,   0, 
+      0,   0,   6,   0,   0,   0, 
+      1,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      1,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0, 198,   0, 
+      0,   0,   8,   0,   0,   0, 
+      6,   0,   0,   0,   1,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   1,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0, 214,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   1,   0,   0,   0, 
+      1,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+    120, 101,  95, 114, 101, 115, 
+    111, 108, 118, 101,  95, 115, 
+    111, 117, 114,  99, 101,   0, 
+    120, 101,  95, 114, 101, 115, 
+    111, 108, 118, 101,  95, 100, 
+    101, 115, 116,   0,  88, 101, 
+     82, 101, 115, 111, 108, 118, 
+    101,  68, 111, 119, 110, 115, 
+     99,  97, 108, 101,  67, 111, 
+    110, 115, 116,  97, 110, 116, 
+    115,   0, 171, 171, 214,   0, 
+      0,   0,   6,   0,   0,   0, 
+     12,   1,   0,   0,  32,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0, 252,   1, 
+      0,   0,   0,   0,   0,   0, 
+      4,   0,   0,   0,   2,   0, 
+      0,   0,  24,   2,   0,   0, 
+      0,   0,   0,   0, 255, 255, 
+    255, 255,   0,   0,   0,   0, 
+    255, 255, 255, 255,   0,   0, 
+      0,   0,  60,   2,   0,   0, 
+      4,   0,   0,   0,   4,   0, 
+      0,   0,   2,   0,   0,   0, 
+     24,   2,   0,   0,   0,   0, 
+      0,   0, 255, 255, 255, 255, 
+      0,   0,   0,   0, 255, 255, 
+    255, 255,   0,   0,   0,   0, 
+     81,   2,   0,   0,   8,   0, 
+      0,   0,   4,   0,   0,   0, 
+      2,   0,   0,   0,  24,   2, 
+      0,   0,   0,   0,   0,   0, 
+    255, 255, 255, 255,   0,   0, 
+      0,   0, 255, 255, 255, 255, 
+      0,   0,   0,   0, 110,   2, 
+      0,   0,  12,   0,   0,   0, 
+      4,   0,   0,   0,   2,   0, 
+      0,   0,  24,   2,   0,   0, 
+      0,   0,   0,   0, 255, 255, 
+    255, 255,   0,   0,   0,   0, 
+    255, 255, 255, 255,   0,   0, 
+      0,   0, 134,   2,   0,   0, 
+     16,   0,   0,   0,   4,   0, 
+      0,   0,   2,   0,   0,   0, 
+     24,   2,   0,   0,   0,   0, 
+      0,   0, 255, 255, 255, 255, 
+      0,   0,   0,   0, 255, 255, 
+    255, 255,   0,   0,   0,   0, 
+    165,   2,   0,   0,  20,   0, 
+      0,   0,   4,   0,   0,   0, 
+      2,   0,   0,   0,  24,   2, 
+      0,   0,   0,   0,   0,   0, 
+    255, 255, 255, 255,   0,   0, 
+      0,   0, 255, 255, 255, 255, 
+      0,   0,   0,   0, 120, 101, 
+     95, 100, 111, 119, 110, 115, 
+     99,  97, 108, 101,  95, 115, 
+     99,  97, 108, 101,  95, 120, 
+      0, 100, 119, 111, 114, 100, 
+      0, 171,   0,   0,  19,   0, 
+      1,   0,   1,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,  17,   2, 
+      0,   0, 120, 101,  95, 100, 
+    111, 119, 110, 115,  99,  97, 
+    108, 101,  95, 115,  99,  97, 
+    108, 101,  95, 121,   0, 120, 
+    101,  95, 100, 111, 119, 110, 
+    115,  99,  97, 108, 101,  95, 
+    112, 105, 120, 101, 108,  95, 
+    115, 105, 122, 101,  95, 108, 
+    111, 103,  50,   0, 120, 101, 
+     95, 100, 111, 119, 110, 115, 
+     99,  97, 108, 101,  95, 116, 
+    105, 108, 101,  95,  99, 111, 
+    117, 110, 116,   0, 120, 101, 
+     95, 100, 111, 119, 110, 115, 
+     99,  97, 108, 101,  95, 104, 
+     97, 108, 102,  95, 112, 105, 
+    120, 101, 108,  95, 111, 102, 
+    102, 115, 101, 116,   0, 120, 
+    101,  95, 100, 111, 119, 110, 
+    115,  99,  97, 108, 101,  95, 
+     97, 118, 101, 114,  97, 103, 
+    101,   0,  77, 105,  99, 114, 
+    111, 115, 111, 102, 116,  32, 
+     40,  82,  41,  32,  72,  76, 
+     83,  76,  32,  83, 104,  97, 
+    100, 101, 114,  32,  67, 111, 
+    109, 112, 105, 108, 101, 114, 
+     32,  49,  48,  46,  49,   0, 
+    171, 171,  73,  83,  71,  78, 
+      8,   0,   0,   0,   0,   0, 
+      0,   0,   8,   0,   0,   0, 
+     79,  83,  71,  78,   8,   0, 
+      0,   0,   0,   0,   0,   0, 
+      8,   0,   0,   0,  83,  72, 
+     69,  88, 232,  10,   0,   0, 
+     81,   0,   5,   0, 186,   2, 
+      0,   0, 106,   8,   0,   1, 
+     89,   0,   0,   7,  70, 142, 
+     48,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   2,   0,   0,   0, 
+      0,   0,   0,   0, 161,   0, 
+      0,   6,  70, 126,  48,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0, 157,   0, 
+      0,   6,  70, 238,  49,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,  95,   0, 
+      0,   2,  18,  16,   2,   0, 
+     95,   0,   0,   2,  50,  32, 
+      2,   0, 104,   0,   0,   2, 
+      4,   0,   0,   0, 160,   0, 
+      0,   5,   0, 240,  17,   0, 
+      0,   0,   0,   0,   4,   0, 
+      0,   0,   0,   4,   0,   0, 
+    155,   0,   0,   4,  32,   0, 
+      0,   0,  32,   0,   0,   0, 
+      1,   0,   0,   0,  80,   0, 
+      0,   8,  18,   0,  16,   0, 
+      0,   0,   0,   0,  10,  16, 
+      2,   0,  58, 128,  48,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+     31,   0,   4,   3,  10,   0, 
+     16,   0,   0,   0,   0,   0, 
+     62,   0,   0,   1,  21,   0, 
+      0,   1,  35,   0,   0,   7, 
+     18,   0,  16,   0,   0,   0, 
+      0,   0,  26,  32,   2,   0, 
+      1,  64,   0,   0,  32,   0, 
+      0,   0,  10,  32,   2,   0, 
+     41,   0,   0,  12,  98,   0, 
+     16,   0,   0,   0,   0,   0, 
+      2,  64,   0,   0,   0,   0, 
+      0,   0,   1,   0,   0,   0, 
+      0,   4,   0,   0,   0,   0, 
+      0,   0, 166, 138,  48,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+     38,   0,   0,  12,   0, 208, 
+      0,   0, 130,   0,  16,   0, 
+      0,   0,   0,   0,  26, 128, 
+     48,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,  10, 128,  48,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+     39,   0,   0,   9,  34,   0, 
+     16,   0,   1,   0,   0,   0, 
+     10, 128,  48,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      1,   0,   0,   0,   1,  64, 
+      0,   0,   0,   0,   0,   0, 
+     79,   0,   0,   7,  66,   0, 
+     16,   0,   1,   0,   0,   0, 
+      1,  64,   0,   0,   1,   0, 
+      0,   0,  58,   0,  16,   0, 
+      0,   0,   0,   0,   1,   0, 
+      0,   7,  34,   0,  16,   0, 
+      1,   0,   0,   0,  42,   0, 
+     16,   0,   1,   0,   0,   0, 
+     26,   0,  16,   0,   1,   0, 
+      0,   0,  31,   0,   4,   3, 
+     26,   0,  16,   0,   1,   0, 
+      0,   0,  85,   0,   0,  12, 
+    162,   0,  16,   0,   1,   0, 
+      0,   0,   6, 132,  48,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      2,  64,   0,   0,   0,   0, 
+      0,   0,   1,   0,   0,   0, 
+      0,   0,   0,   0,   1,   0, 
+      0,   0,  35,   0,   0,  11, 
+     34,   0,  16,   0,   1,   0, 
+      0,   0,  58,   0,  16,   0, 
+      1,   0,   0,   0,  10, 128, 
+     48,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,  26,   0,  16,   0, 
+      1,   0,   0,   0,  18,   0, 
+      0,   1,  54,   0,   0,   5, 
+     34,   0,  16,   0,   1,   0, 
+      0,   0,   1,  64,   0,   0, 
+      0,   0,   0,   0,  21,   0, 
+      0,   1,  38,   0,   0,   8, 
+      0, 208,   0,   0, 146,   0, 
+     16,   0,   1,   0,   0,   0, 
+    246,   7,  16,   0,   0,   0, 
+      0,   0, 166,   2,  16,   0, 
+      0,   0,   0,   0,  38,   0, 
+      0,   8,   0, 208,   0,   0, 
+     18,   0,  16,   0,   2,   0, 
+      0,   0,  58,   0,  16,   0, 
+      0,   0,   0,   0,  58,   0, 
+     16,   0,   1,   0,   0,   0, 
+     35,   0,   0,   8,  18,   0, 
+     16,   0,   1,   0,   0,   0, 
+     10,  16,   2,   0,  10,   0, 
+     16,   0,   1,   0,   0,   0, 
+     10,   0,  16,   0,   2,   0, 
+      0,   0,  35,   0,   0,   9, 
+     34,   0,  16,   0,   0,   0, 
+      0,   0,  26,   0,  16,   0, 
+      1,   0,   0,   0,  26,   0, 
+     16,   0,   0,   0,   0,   0, 
+     10,   0,  16,   0,   1,   0, 
+      0,   0,  79,   0,   0,   9, 
+     34,   0,  16,   0,   1,   0, 
+      0,   0,  42, 128,  48,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      1,  64,   0,   0,   2,   0, 
+      0,   0,  31,   0,   4,   3, 
+     26,   0,  16,   0,   1,   0, 
+      0,   0,  31,   0,   0,   5, 
+     42, 128,  48,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   1,   0, 
+      0,   7,  34,   0,  16,   0, 
+      1,   0,   0,   0,  26,   0, 
+     16,   0,   0,   0,   0,   0, 
+      1,  64,   0,   0, 252, 255, 
+    255, 255, 165,   0,   0,   8, 
+     34,   0,  16,   0,   1,   0, 
+      0,   0,  26,   0,  16,   0, 
+      1,   0,   0,   0,   6, 112, 
+     32,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0, 140,   0, 
+      0,  11, 130,   0,  16,   0, 
+      1,   0,   0,   0,   1,  64, 
+      0,   0,   2,   0,   0,   0, 
+      1,  64,   0,   0,   3,   0, 
+      0,   0,  26,   0,  16,   0, 
+      0,   0,   0,   0,   1,  64, 
+      0,   0,   0,   0,   0,   0, 
+     85,   0,   0,   7,  34,   0, 
+     16,   0,   1,   0,   0,   0, 
+     26,   0,  16,   0,   1,   0, 
+      0,   0,  58,   0,  16,   0, 
+      1,   0,   0,   0,  85,   0, 
+      0,   7,  18,   0,  16,   0, 
+      2,   0,   0,   0,  10,   0, 
+     16,   0,   0,   0,   0,   0, 
+      1,  64,   0,   0,   2,   0, 
+      0,   0,   1,   0,   0,   7, 
+    130,   0,  16,   0,   1,   0, 
+      0,   0,  10,   0,  16,   0, 
+      0,   0,   0,   0,   1,  64, 
+      0,   0,   3,   0,   0,   0, 
+    140,   0,   0,  11,  66,   0, 
+     16,   0,   2,   0,   0,   0, 
+      1,  64,   0,   0,   2,   0, 
+      0,   0,   1,  64,   0,   0, 
+      3,   0,   0,   0,  10,   0, 
+     16,   0,   0,   0,   0,   0, 
+      1,  64,   0,   0,   0,   0, 
+      0,   0, 140,   0,   0,  11, 
+     34,   0,  16,   0,   1,   0, 
+      0,   0,   1,  64,   0,   0, 
+      8,   0,   0,   0,  42,   0, 
+     16,   0,   2,   0,   0,   0, 
+     26,   0,  16,   0,   1,   0, 
+      0,   0,   1,  64,   0,   0, 
+      0,   0,   0,   0,  31,   0, 
+      0,   3,  58,   0,  16,   0, 
+      1,   0,   0,   0, 168,   0, 
+      0,   9,  18, 240,  17,   0, 
+      0,   0,   0,   0,  10,   0, 
+     16,   0,   2,   0,   0,   0, 
+      1,  64,   0,   0,   0,   0, 
+      0,   0,  26,   0,  16,   0, 
+      1,   0,   0,   0,  21,   0, 
+      0,   1, 190,  24,   0,   1, 
+     31,   0,   4,   3,  58,   0, 
+     16,   0,   1,   0,   0,   0, 
+     54,   0,   0,   5,  34,   0, 
+     16,   0,   2,   0,   0,   0, 
+      1,  64,   0,   0,   0,   0, 
+      0,   0, 170,   0,   0,   7, 
+      0, 240,  17,   0,   0,   0, 
+      0,   0,  70,   0,  16,   0, 
+      2,   0,   0,   0,  26,   0, 
+     16,   0,   1,   0,   0,   0, 
+     21,   0,   0,   1, 190,  24, 
+      0,   1,  31,   0,   0,   3, 
+     58,   0,  16,   0,   1,   0, 
+      0,   0,   1,   0,   0,   7, 
+     34,   0,  16,   0,   1,   0, 
+      0,   0,  10,   0,  16,   0, 
+      0,   0,   0,   0,   1,  64, 
+      0,   0, 252,   3,   0,   0, 
+     35,   0,   0,   8,  34,   0, 
+     16,   0,   1,   0,   0,   0, 
+     10,  16,   2,   0,   1,  64, 
+      0,   0,   0,   4,   0,   0, 
+     26,   0,  16,   0,   1,   0, 
+      0,   0, 167,   0,   0,   9, 
+    130,   0,  16,   0,   1,   0, 
+      0,   0,  10,   0,  16,   0, 
+      2,   0,   0,   0,   1,  64, 
+      0,   0,   0,   0,   0,   0, 
+      6, 240,  17,   0,   0,   0, 
+      0,   0, 166,   0,   0,   8, 
+     18, 224,  33,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+     26,   0,  16,   0,   1,   0, 
+      0,   0,  58,   0,  16,   0, 
+      1,   0,   0,   0,  21,   0, 
+      0,   1,  18,   0,   0,   1, 
+      1,   0,   0,   7,  34,   0, 
+     16,   0,   1,   0,   0,   0, 
+     26,   0,  16,   0,   0,   0, 
+      0,   0,   1,  64,   0,   0, 
+    252, 255, 255, 255, 165,   0, 
+      0,   8,  34,   0,  16,   0, 
+      1,   0,   0,   0,  26,   0, 
+     16,   0,   1,   0,   0,   0, 
+      6, 112,  32,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+     41,   0,   0,   7, 130,   0, 
+     16,   0,   1,   0,   0,   0, 
+     26,   0,  16,   0,   0,   0, 
+      0,   0,   1,  64,   0,   0, 
+      3,   0,   0,   0,   1,   0, 
+      0,   7, 130,   0,  16,   0, 
+      1,   0,   0,   0,  58,   0, 
+     16,   0,   1,   0,   0,   0, 
+      1,  64,   0,   0,  16,   0, 
+      0,   0,  85,   0,   0,   7, 
+     34,   0,  16,   0,   1,   0, 
+      0,   0,  26,   0,  16,   0, 
+      1,   0,   0,   0,  58,   0, 
+     16,   0,   1,   0,   0,   0, 
+     85,   0,   0,   7,  18,   0, 
+     16,   0,   2,   0,   0,   0, 
+     10,   0,  16,   0,   0,   0, 
+      0,   0,   1,  64,   0,   0, 
+      1,   0,   0,   0,   1,   0, 
+      0,   7, 130,   0,  16,   0, 
+      1,   0,   0,   0,  10,   0, 
+     16,   0,   0,   0,   0,   0, 
+      1,  64,   0,   0,   1,   0, 
+      0,   0, 140,   0,   0,  11, 
+     18,   0,  16,   0,   0,   0, 
+      0,   0,   1,  64,   0,   0, 
+      1,   0,   0,   0,   1,  64, 
+      0,   0,   4,   0,   0,   0, 
+     10,   0,  16,   0,   0,   0, 
+      0,   0,   1,  64,   0,   0, 
+      0,   0,   0,   0, 140,   0, 
+      0,  11,  18,   0,  16,   0, 
+      0,   0,   0,   0,   1,  64, 
+      0,   0,  16,   0,   0,   0, 
+     10,   0,  16,   0,   0,   0, 
+      0,   0,  26,   0,  16,   0, 
+      1,   0,   0,   0,   1,  64, 
+      0,   0,   0,   0,   0,   0, 
+     31,   0,   0,   3,  58,   0, 
+     16,   0,   1,   0,   0,   0, 
+    168,   0,   0,   9,  18, 240, 
+     17,   0,   0,   0,   0,   0, 
+     10,   0,  16,   0,   2,   0, 
+      0,   0,   1,  64,   0,   0, 
+      0,   0,   0,   0,  10,   0, 
+     16,   0,   0,   0,   0,   0, 
+     21,   0,   0,   1, 190,  24, 
+      0,   1,  31,   0,   4,   3, 
+     58,   0,  16,   0,   1,   0, 
+      0,   0,  54,   0,   0,   5, 
+     34,   0,  16,   0,   2,   0, 
+      0,   0,   1,  64,   0,   0, 
+      0,   0,   0,   0, 170,   0, 
+      0,   7,   0, 240,  17,   0, 
+      0,   0,   0,   0,  70,   0, 
+     16,   0,   2,   0,   0,   0, 
+     10,   0,  16,   0,   0,   0, 
+      0,   0,  21,   0,   0,   1, 
+    190,  24,   0,   1,  31,   0, 
+      0,   3,  58,   0,  16,   0, 
+      1,   0,   0,   0,  41,   0, 
+      0,   7,  18,   0,  16,   0, 
+      0,   0,   0,   0,  10,   0, 
+     16,   0,   2,   0,   0,   0, 
+      1,  64,   0,   0,   2,   0, 
+      0,   0,  35,   0,   0,   8, 
+     18,   0,  16,   0,   0,   0, 
+      0,   0,  10,  16,   2,   0, 
+      1,  64,   0,   0,   0,   8, 
+      0,   0,  10,   0,  16,   0, 
+      0,   0,   0,   0, 167,   0, 
+      0,   9,  34,   0,  16,   0, 
+      1,   0,   0,   0,  10,   0, 
+     16,   0,   2,   0,   0,   0, 
+      1,  64,   0,   0,   0,   0, 
+      0,   0,   6, 240,  17,   0, 
+      0,   0,   0,   0, 166,   0, 
+      0,   8,  18, 224,  33,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,  10,   0,  16,   0, 
+      0,   0,   0,   0,  26,   0, 
+     16,   0,   1,   0,   0,   0, 
+     21,   0,   0,   1,  21,   0, 
+      0,   1,  18,   0,   0,   1, 
+     35,   0,   0,   8,  66,   0, 
+     16,   0,   0,   0,   0,   0, 
+     10,  16,   2,   0,  42,   0, 
+     16,   0,   0,   0,   0,   0, 
+     58,   0,  16,   0,   1,   0, 
+      0,   0,  32,   0,   0,   9, 
+     18,   0,  16,   0,   0,   0, 
+      0,   0,  42, 128,  48,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      1,  64,   0,   0,   2,   0, 
+      0,   0,  31,   0,   4,   3, 
+     10,   0,  16,   0,   0,   0, 
+      0,   0,  39,   0,   0,   9, 
+     18,   0,  16,   0,   0,   0, 
+      0,   0,  26, 128,  48,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   1,   0,   0,   0, 
+      1,  64,   0,   0,   0,   0, 
+      0,   0,   1,   0,   0,   7, 
+     18,   0,  16,   0,   0,   0, 
+      0,   0,  42,   0,  16,   0, 
+      1,   0,   0,   0,  10,   0, 
+     16,   0,   0,   0,   0,   0, 
+     31,   0,   4,   3,  10,   0, 
+     16,   0,   0,   0,   0,   0, 
+     54,   0,   0,   8, 242,   0, 
+     16,   0,   2,   0,   0,   0, 
+      2,  64,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,  54,   0,   0,   5, 
+     18,   0,  16,   0,   0,   0, 
+      0,   0,   1,  64,   0,   0, 
+      0,   0,   0,   0,  48,   0, 
+      0,   1,  80,   0,   0,   7, 
+     34,   0,  16,   0,   1,   0, 
+      0,   0,  10,   0,  16,   0, 
+      0,   0,   0,   0,  58,   0, 
+     16,   0,   0,   0,   0,   0, 
+      3,   0,   4,   3,  26,   0, 
+     16,   0,   1,   0,   0,   0, 
+     41,   0,   0,   7,  34,   0, 
+     16,   0,   1,   0,   0,   0, 
+     10,   0,  16,   0,   0,   0, 
+      0,   0,   1,  64,   0,   0, 
+      2,   0,   0,   0,  30,   0, 
+      0,   7,  34,   0,  16,   0, 
+      1,   0,   0,   0,  26,   0, 
+     16,   0,   1,   0,   0,   0, 
+     10,   0,  16,   0,   1,   0, 
+      0,   0, 165,   0,   0,   8, 
+     34,   0,  16,   0,   1,   0, 
+      0,   0,  26,   0,  16,   0, 
+      1,   0,   0,   0,   6, 112, 
+     32,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   1,   0, 
+      0,   7,  18,   0,  16,   0, 
+      3,   0,   0,   0,  26,   0, 
+     16,   0,   1,   0,   0,   0, 
+      1,  64,   0,   0, 255,   0, 
+      0,   0, 138,   0,   0,  15, 
+     98,   0,  16,   0,   3,   0, 
+      0,   0,   2,  64,   0,   0, 
+      0,   0,   0,   0,   8,   0, 
+      0,   0,   8,   0,   0,   0, 
+      0,   0,   0,   0,   2,  64, 
+      0,   0,   0,   0,   0,   0, 
+      8,   0,   0,   0,  16,   0, 
+      0,   0,   0,   0,   0,   0, 
+     86,   5,  16,   0,   1,   0, 
+      0,   0,  85,   0,   0,   7, 
+    130,   0,  16,   0,   3,   0, 
+      0,   0,  26,   0,  16,   0, 
+      1,   0,   0,   0,   1,  64, 
+      0,   0,  24,   0,   0,   0, 
+     30,   0,   0,   7, 242,   0, 
+     16,   0,   2,   0,   0,   0, 
+     70,  14,  16,   0,   2,   0, 
+      0,   0,  70,  14,  16,   0, 
+      3,   0,   0,   0,  30,   0, 
+      0,   7,  18,   0,  16,   0, 
+      0,   0,   0,   0,  10,   0, 
+     16,   0,   0,   0,   0,   0, 
+      1,  64,   0,   0,   1,   0, 
+      0,   0,  22,   0,   0,   1, 
+     85,   0,   0,   7,  18,   0, 
+     16,   0,   0,   0,   0,   0, 
+     58,   0,  16,   0,   0,   0, 
+      0,   0,   1,  64,   0,   0, 
+      1,   0,   0,   0,  30,   0, 
+      0,   7, 242,   0,  16,   0, 
+      1,   0,   0,   0,   6,   0, 
+     16,   0,   0,   0,   0,   0, 
+     70,  14,  16,   0,   2,   0, 
+      0,   0,  78,   0,   0,   8, 
+    242,   0,  16,   0,   1,   0, 
+      0,   0,   0, 208,   0,   0, 
+     70,  14,  16,   0,   1,   0, 
+      0,   0, 246,  15,  16,   0, 
+      0,   0,   0,   0,  41,   0, 
+      0,  10, 226,   0,  16,   0, 
+      1,   0,   0,   0,  86,  14, 
+     16,   0,   1,   0,   0,   0, 
+      2,  64,   0,   0,   0,   0, 
+      0,   0,   8,   0,   0,   0, 
+     16,   0,   0,   0,  24,   0, 
+      0,   0,  60,   0,   0,   7, 
+     18,   0,  16,   0,   0,   0, 
+      0,   0,  26,   0,  16,   0, 
+      1,   0,   0,   0,  10,   0, 
+     16,   0,   1,   0,   0,   0, 
+     60,   0,   0,   7,  18,   0, 
+     16,   0,   0,   0,   0,   0, 
+     42,   0,  16,   0,   1,   0, 
+      0,   0,  10,   0,  16,   0, 
+      0,   0,   0,   0,  60,   0, 
+      0,   7,  18,   0,  16,   0, 
+      0,   0,   0,   0,  58,   0, 
+     16,   0,   1,   0,   0,   0, 
+     10,   0,  16,   0,   0,   0, 
+      0,   0,  18,   0,   0,   1, 
+    165,   0,   0,   8,  18,   0, 
+     16,   0,   0,   0,   0,   0, 
+     26,   0,  16,   0,   0,   0, 
+      0,   0,   6, 112,  32,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,  21,   0,   0,   1, 
+    166,   0,   0,   8,  18, 224, 
+     33,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,  42,   0, 
+     16,   0,   0,   0,   0,   0, 
+     10,   0,  16,   0,   0,   0, 
+      0,   0,  18,   0,   0,   1, 
+     32,   0,   0,   9,  18,   0, 
+     16,   0,   0,   0,   0,   0, 
+     42, 128,  48,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   1,  64, 
+      0,   0,   3,   0,   0,   0, 
+     31,   0,   4,   3,  10,   0, 
+     16,   0,   0,   0,   0,   0, 
+    165,   0,   0,   8,  50,   0, 
+     16,   0,   0,   0,   0,   0, 
+     26,   0,  16,   0,   0,   0, 
+      0,   0,  70, 112,  32,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0, 166,   0,   0,   8, 
+     50, 224,  33,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+     42,   0,  16,   0,   0,   0, 
+      0,   0,  70,   0,  16,   0, 
+      0,   0,   0,   0,  21,   0, 
+      0,   1,  21,   0,   0,   1, 
+     21,   0,   0,   1,  62,   0, 
+      0,   1,  83,  84,  65,  84, 
+    148,   0,   0,   0, 113,   0, 
+      0,   0,   4,   0,   0,   0, 
+      0,   0,   0,   0,   2,   0, 
+      0,   0,   0,   0,   0,   0, 
+     23,   0,   0,   0,  24,   0, 
+      0,   0,   8,   0,   0,   0, 
+     13,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   5,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   5,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   4,   0,   0,   0, 
+      2,   0,   0,   0,   4,   0, 
+      0,   0
+};
diff --git a/src/graphics/shaders/resolve_downscale.cs.glsl b/src/graphics/shaders/resolve_downscale.cs.glsl
index a3c8c12..f52ea66 100644
--- a/src/graphics/shaders/resolve_downscale.cs.glsl
+++ b/src/graphics/shaders/resolve_downscale.cs.glsl
@@ -32,6 +32,8 @@ layout(push_constant) uniform ResolveDownscaleConstants {
   // games, which at Nx resolution scaling shifts rendered content by
   // (N/2, N/2) host pixels.
   uint xe_downscale_half_pixel_offset;
+  // Non-zero (32-bit 8:8:8:8 color only): per-channel average of the scaled block (see the HLSL version).
+  uint xe_downscale_average;
 };
 
 // Source buffer (scaled resolve data)
@@ -146,8 +148,20 @@ void main() {
       }
       break;
     }
-    case 2u: {  // 32-bit - direct copy
-      xe_resolve_dest.data[dst_offset] = xe_resolve_source.data[src_offset];
+    case 2u: {  // 32-bit - direct copy, or the per-channel block average for 8:8:8:8 color
+      if (xe_downscale_average != 0u && scale_xy > 1u) {
+        uint block_base = (xe_downscale_source_offset_bytes + tile_index * tile_size_scaled +
+                           pixel_index * pixel_size * scale_xy) >> 2u;
+        uvec4 sum = uvec4(0u);
+        for (uint s = 0u; s < scale_xy; ++s) {
+          uint texel = xe_resolve_source.data[block_base + s];
+          sum += uvec4(texel & 0xFFu, (texel >> 8u) & 0xFFu, (texel >> 16u) & 0xFFu, texel >> 24u);
+        }
+        sum = (sum + uvec4(scale_xy >> 1u)) / uvec4(scale_xy);
+        xe_resolve_dest.data[dst_offset] = sum.x | (sum.y << 8u) | (sum.z << 16u) | (sum.w << 24u);
+      } else {
+        xe_resolve_dest.data[dst_offset] = xe_resolve_source.data[src_offset];
+      }
       break;
     }
     case 3u: {  // 64-bit - direct copy (2 uints)
diff --git a/src/graphics/shaders/resolve_downscale.cs.hlsl b/src/graphics/shaders/resolve_downscale.cs.hlsl
index 91c2f95..5b07640 100644
--- a/src/graphics/shaders/resolve_downscale.cs.hlsl
+++ b/src/graphics/shaders/resolve_downscale.cs.hlsl
@@ -27,6 +27,10 @@ cbuffer XeResolveDownscaleConstants : register(b0) {
   // games, which at Nx resolution scaling shifts rendered content by
   // (N/2, N/2) host pixels.
   uint xe_downscale_half_pixel_offset;
+  // When non-zero (32-bit 8:8:8:8 color only), average the whole scaled block per byte channel instead of
+  // picking one sample: point picking left render-to-texture images (player face portraits) aliased and
+  // pixelated after the copy back to guest memory.
+  uint xe_downscale_average;
 };
 
 ByteAddressBuffer xe_resolve_source : register(t0);
@@ -135,8 +139,19 @@ void main(uint3 xe_group_id : SV_GroupID,
       }
       break;
     }
-    case 2: {  // 32-bit - direct copy
-      xe_resolve_dest.Store(dst_offset, xe_resolve_source.Load(src_offset));
+    case 2: {  // 32-bit - direct copy, or the per-channel block average for 8:8:8:8 color
+      [branch] if (xe_downscale_average != 0u && scale_xy > 1u) {
+        uint block_base = tile_index * tile_size_scaled + pixel_index * pixel_size * scale_xy;
+        uint4 sum = uint4(0u, 0u, 0u, 0u);
+        for (uint s = 0u; s < scale_xy; ++s) {
+          uint texel = xe_resolve_source.Load(block_base + s * 4u);
+          sum += uint4(texel & 0xFFu, (texel >> 8u) & 0xFFu, (texel >> 16u) & 0xFFu, texel >> 24u);
+        }
+        sum = (sum + (scale_xy >> 1u)) / scale_xy;
+        xe_resolve_dest.Store(dst_offset, sum.x | (sum.y << 8u) | (sum.z << 16u) | (sum.w << 24u));
+      } else {
+        xe_resolve_dest.Store(dst_offset, xe_resolve_source.Load(src_offset));
+      }
       break;
     }
     case 3: {  // 64-bit - direct copy
diff --git a/src/graphics/shaders/vulkan_spirv/resolve_downscale_cs.h b/src/graphics/shaders/vulkan_spirv/resolve_downscale_cs.h
index fd9d6a7..0d87d0d 100644
--- a/src/graphics/shaders/vulkan_spirv/resolve_downscale_cs.h
+++ b/src/graphics/shaders/vulkan_spirv/resolve_downscale_cs.h
@@ -1,376 +1,272 @@
-// Generated with `xb buildshaders`.
-#if 0
-; SPIR-V
-; Version: 1.0
-; Generator: Khronos Glslang Reference Front End; 11
-; Bound: 25190
-; Schema: 0
-               OpCapability Shader
-          %1 = OpExtInstImport "GLSL.std.450"
-               OpMemoryModel Logical GLSL450
-               OpEntryPoint GLCompute %5663 "main" %gl_WorkGroupID %gl_LocalInvocationID
-               OpExecutionMode %5663 LocalSize 32 32 1
-               OpDecorate %gl_WorkGroupID BuiltIn WorkgroupId
-               OpDecorate %_struct_1056 Block
-               OpMemberDecorate %_struct_1056 0 Offset 0
-               OpMemberDecorate %_struct_1056 1 Offset 4
-               OpMemberDecorate %_struct_1056 2 Offset 8
-               OpMemberDecorate %_struct_1056 3 Offset 12
-               OpMemberDecorate %_struct_1056 4 Offset 16
-               OpMemberDecorate %_struct_1056 5 Offset 20
-               OpDecorate %gl_LocalInvocationID BuiltIn LocalInvocationId
-               OpDecorate %_runtimearr_uint ArrayStride 4
-               OpDecorate %_struct_1948 BufferBlock
-               OpMemberDecorate %_struct_1948 0 NonWritable
-               OpMemberDecorate %_struct_1948 0 Offset 0
-               OpDecorate %3152 NonWritable
-               OpDecorate %3152 Binding 0
-               OpDecorate %3152 DescriptorSet 0
-               OpDecorate %_runtimearr_uint_0 ArrayStride 4
-               OpDecorate %_struct_1949 BufferBlock
-               OpMemberDecorate %_struct_1949 0 NonReadable
-               OpMemberDecorate %_struct_1949 0 Offset 0
-               OpDecorate %5522 NonReadable
-               OpDecorate %5522 Binding 1
-               OpDecorate %5522 DescriptorSet 0
-               OpDecorate %gl_WorkGroupSize BuiltIn WorkgroupSize
-       %void = OpTypeVoid
-       %1282 = OpTypeFunction %void
-       %uint = OpTypeInt 32 0
-     %v3uint = OpTypeVector %uint 3
-%_ptr_Input_v3uint = OpTypePointer Input %v3uint
-%gl_WorkGroupID = OpVariable %_ptr_Input_v3uint Input
-     %uint_0 = OpConstant %uint 0
-%_ptr_Input_uint = OpTypePointer Input %uint
-%_struct_1056 = OpTypeStruct %uint %uint %uint %uint %uint %uint
-%_ptr_PushConstant__struct_1056 = OpTypePointer PushConstant %_struct_1056
-       %4930 = OpVariable %_ptr_PushConstant__struct_1056 PushConstant
-        %int = OpTypeInt 32 1
-      %int_3 = OpConstant %int 3
-%_ptr_PushConstant_uint = OpTypePointer PushConstant %uint
-       %bool = OpTypeBool
-%gl_LocalInvocationID = OpVariable %_ptr_Input_v3uint Input
-     %uint_1 = OpConstant %uint 1
-    %uint_32 = OpConstant %uint 32
-      %int_2 = OpConstant %int 2
-  %uint_1024 = OpConstant %uint 1024
-      %int_0 = OpConstant %int 0
-      %int_1 = OpConstant %int 1
-      %int_5 = OpConstant %int 5
-      %int_4 = OpConstant %int 4
-     %uint_2 = OpConstant %uint 2
-%_runtimearr_uint = OpTypeRuntimeArray %uint
-%_struct_1948 = OpTypeStruct %_runtimearr_uint
-%_ptr_Uniform__struct_1948 = OpTypePointer Uniform %_struct_1948
-       %3152 = OpVariable %_ptr_Uniform__struct_1948 Uniform
-%_ptr_Uniform_uint = OpTypePointer Uniform %uint
-     %uint_3 = OpConstant %uint 3
-     %uint_8 = OpConstant %uint 8
-   %uint_255 = OpConstant %uint 255
-%_arr_uint_uint_1024 = OpTypeArray %uint %uint_1024
-%_ptr_Workgroup__arr_uint_uint_1024 = OpTypePointer Workgroup %_arr_uint_uint_1024
-       %4017 = OpVariable %_ptr_Workgroup__arr_uint_uint_1024 Workgroup
-%_ptr_Workgroup_uint = OpTypePointer Workgroup %uint
-   %uint_264 = OpConstant %uint 264
-%_runtimearr_uint_0 = OpTypeRuntimeArray %uint
-%_struct_1949 = OpTypeStruct %_runtimearr_uint_0
-%_ptr_Uniform__struct_1949 = OpTypePointer Uniform %_struct_1949
-       %5522 = OpVariable %_ptr_Uniform__struct_1949 Uniform
-   %uint_256 = OpConstant %uint 256
- %uint_65535 = OpConstant %uint 65535
-    %uint_16 = OpConstant %uint 16
-   %uint_512 = OpConstant %uint 512
-%gl_WorkGroupSize = OpConstantComposite %v3uint %uint_32 %uint_32 %uint_1
-       %5663 = OpFunction %void None %1282
-      %15110 = OpLabel
-               OpSelectionMerge %14903 None
-               OpSwitch %uint_0 %11880
-      %11880 = OpLabel
-      %22245 = OpAccessChain %_ptr_Input_uint %gl_WorkGroupID %uint_0
-      %15627 = OpLoad %uint %22245
-      %22225 = OpAccessChain %_ptr_PushConstant_uint %4930 %int_3
-       %7085 = OpLoad %uint %22225
-       %7405 = OpUGreaterThanEqual %bool %15627 %7085
-               OpSelectionMerge %16413 None
-               OpBranchConditional %7405 %21992 %16413
-      %21992 = OpLabel
-               OpBranch %14903
-      %16413 = OpLabel
-      %20632 = OpAccessChain %_ptr_Input_uint %gl_LocalInvocationID %uint_1
-      %15628 = OpLoad %uint %20632
-      %21427 = OpAccessChain %_ptr_Input_uint %gl_LocalInvocationID %uint_0
-      %12090 = OpLoad %uint %21427
-       %6234 = OpIMul %uint %15628 %uint_32
-       %8353 = OpIAdd %uint %6234 %12090
-      %16525 = OpAccessChain %_ptr_PushConstant_uint %4930 %int_2
-      %13159 = OpLoad %uint %16525
-      %15178 = OpShiftLeftLogical %uint %uint_1 %13159
-      %21815 = OpIMul %uint %uint_1024 %15178
-      %13000 = OpAccessChain %_ptr_PushConstant_uint %4930 %int_0
-      %18628 = OpLoad %uint %13000
-      %21428 = OpAccessChain %_ptr_PushConstant_uint %4930 %int_1
-      %12166 = OpLoad %uint %21428
-      %24613 = OpIMul %uint %18628 %12166
-      %13723 = OpIMul %uint %21815 %24613
-       %8597 = OpAccessChain %_ptr_PushConstant_uint %4930 %int_5
-      %21470 = OpLoad %uint %8597
-      %24311 = OpINotEqual %bool %21470 %uint_0
-      %23629 = OpUGreaterThan %bool %24613 %uint_1
-      %11037 = OpLogicalAnd %bool %24311 %23629
-               OpSelectionMerge %23266 None
-               OpBranchConditional %11037 %11410 %23266
-      %11410 = OpLabel
-      %20167 = OpShiftRightLogical %uint %18628 %uint_1
-      %24779 = OpShiftRightLogical %uint %12166 %uint_1
-      %16010 = OpIMul %uint %24779 %18628
-      %19240 = OpIAdd %uint %20167 %16010
-               OpBranch %23266
-      %23266 = OpLabel
-      %19748 = OpPhi %uint %uint_0 %16413 %19240 %11410
-      %25074 = OpAccessChain %_ptr_PushConstant_uint %4930 %int_4
-      %25189 = OpLoad %uint %25074
-       %7507 = OpIMul %uint %15627 %13723
-      %17182 = OpIAdd %uint %25189 %7507
-      %19692 = OpIMul %uint %8353 %15178
-      %16238 = OpIMul %uint %19692 %24613
-       %6869 = OpIAdd %uint %17182 %16238
-      %21638 = OpIMul %uint %19748 %15178
-      %18521 = OpIAdd %uint %6869 %21638
-       %7572 = OpShiftRightLogical %uint %18521 %uint_2
-       %6935 = OpIMul %uint %15627 %21815
-       %9665 = OpIAdd %uint %6935 %19692
-       %9085 = OpShiftRightLogical %uint %9665 %uint_2
-               OpSelectionMerge %18023 None
-               OpSwitch %13159 %18023 0 %11881 1 %16414 2 %16415 3 %8158
-      %11881 = OpLabel
-      %24791 = OpAccessChain %_ptr_Uniform_uint %3152 %int_0 %7572
-      %12865 = OpLoad %uint %24791
-      %12121 = OpBitwiseAnd %uint %18521 %uint_3
-      %13987 = OpIMul %uint %12121 %uint_8
-      %14461 = OpShiftRightLogical %uint %12865 %13987
-      %15580 = OpBitwiseAnd %uint %14461 %uint_255
-      %19824 = OpShiftRightLogical %uint %8353 %uint_2
-      %19243 = OpBitwiseAnd %uint %8353 %uint_3
-      %14114 = OpIMul %uint %19243 %uint_8
-      %23170 = OpShiftLeftLogical %uint %15580 %14114
-      %15629 = OpIEqual %bool %19243 %uint_0
-               OpSelectionMerge %20883 None
-               OpBranchConditional %15629 %12148 %20883
-      %12148 = OpLabel
-      %21533 = OpAccessChain %_ptr_Workgroup_uint %4017 %19824
-               OpStore %21533 %23170
-               OpBranch %20883
-      %20883 = OpLabel
-               OpControlBarrier %uint_2 %uint_2 %uint_264
-      %15932 = OpINotEqual %bool %19243 %uint_0
-               OpSelectionMerge %9094 None
-               OpBranchConditional %15932 %15549 %9094
-      %15549 = OpLabel
-       %9637 = OpAccessChain %_ptr_Workgroup_uint %4017 %19824
-       %6303 = OpAtomicOr %uint %9637 %uint_1 %uint_0 %23170
-               OpBranch %9094
-       %9094 = OpLabel
-               OpControlBarrier %uint_2 %uint_2 %uint_264
-               OpSelectionMerge %18021 None
-               OpBranchConditional %15629 %20882 %18021
-      %20882 = OpLabel
-      %10747 = OpIMul %uint %15627 %uint_256
-      %14186 = OpIAdd %uint %10747 %19824
-      %14036 = OpAccessChain %_ptr_Workgroup_uint %4017 %19824
-      %15421 = OpLoad %uint %14036
-      %23477 = OpAccessChain %_ptr_Uniform_uint %5522 %int_0 %14186
-               OpStore %23477 %15421
-               OpBranch %18021
-      %18021 = OpLabel
-               OpBranch %18023
-      %16414 = OpLabel
-      %23178 = OpAccessChain %_ptr_Uniform_uint %3152 %int_0 %7572
-      %12866 = OpLoad %uint %23178
-      %12122 = OpBitwiseAnd %uint %18521 %uint_2
-      %13988 = OpIMul %uint %12122 %uint_8
-      %14462 = OpShiftRightLogical %uint %12866 %13988
-      %15581 = OpBitwiseAnd %uint %14462 %uint_65535
-      %19825 = OpShiftRightLogical %uint %8353 %uint_1
-      %19244 = OpBitwiseAnd %uint %8353 %uint_1
-      %14115 = OpIMul %uint %19244 %uint_16
-      %23171 = OpShiftLeftLogical %uint %15581 %14115
-      %15630 = OpIEqual %bool %19244 %uint_0
-               OpSelectionMerge %20884 None
-               OpBranchConditional %15630 %12149 %20884
-      %12149 = OpLabel
-      %21534 = OpAccessChain %_ptr_Workgroup_uint %4017 %19825
-               OpStore %21534 %23171
-               OpBranch %20884
-      %20884 = OpLabel
-               OpControlBarrier %uint_2 %uint_2 %uint_264
-      %15933 = OpINotEqual %bool %19244 %uint_0
-               OpSelectionMerge %9095 None
-               OpBranchConditional %15933 %15550 %9095
-      %15550 = OpLabel
-       %9638 = OpAccessChain %_ptr_Workgroup_uint %4017 %19825
-       %6304 = OpAtomicOr %uint %9638 %uint_1 %uint_0 %23171
-               OpBranch %9095
-       %9095 = OpLabel
-               OpControlBarrier %uint_2 %uint_2 %uint_264
-               OpSelectionMerge %18022 None
-               OpBranchConditional %15630 %20885 %18022
-      %20885 = OpLabel
-      %10748 = OpIMul %uint %15627 %uint_512
-      %14187 = OpIAdd %uint %10748 %19825
-      %14037 = OpAccessChain %_ptr_Workgroup_uint %4017 %19825
-      %15422 = OpLoad %uint %14037
-      %23478 = OpAccessChain %_ptr_Uniform_uint %5522 %int_0 %14187
-               OpStore %23478 %15422
-               OpBranch %18022
-      %18022 = OpLabel
-               OpBranch %18023
-      %16415 = OpLabel
-      %20633 = OpAccessChain %_ptr_Uniform_uint %3152 %int_0 %7572
-      %15646 = OpLoad %uint %20633
-      %23479 = OpAccessChain %_ptr_Uniform_uint %5522 %int_0 %9085
-               OpStore %23479 %15646
-               OpBranch %18023
-       %8158 = OpLabel
-      %20634 = OpAccessChain %_ptr_Uniform_uint %3152 %int_0 %7572
-      %15647 = OpLoad %uint %20634
-      %21178 = OpAccessChain %_ptr_Uniform_uint %5522 %int_0 %9085
-               OpStore %21178 %15647
-      %19686 = OpIAdd %uint %9085 %uint_1
-      %13384 = OpIAdd %uint %7572 %uint_1
-      %10810 = OpAccessChain %_ptr_Uniform_uint %3152 %int_0 %13384
-      %15423 = OpLoad %uint %10810
-      %23480 = OpAccessChain %_ptr_Uniform_uint %5522 %int_0 %19686
-               OpStore %23480 %15423
-               OpBranch %18023
-      %18023 = OpLabel
-               OpBranch %14903
-      %14903 = OpLabel
-               OpReturn
-               OpFunctionEnd
-#endif
-
+// Generated with glslangValidator -S comp -V --target-env vulkan1.0 from resolve_downscale.cs.glsl (ReStreet 1.3).
 const uint32_t resolve_downscale_cs[] = {
-    0x07230203, 0x00010000, 0x0008000B, 0x00006266, 0x00000000, 0x00020011, 0x00000001, 0x0006000B,
-    0x00000001, 0x4C534C47, 0x6474732E, 0x3035342E, 0x00000000, 0x0003000E, 0x00000000, 0x00000001,
-    0x0007000F, 0x00000005, 0x0000161F, 0x6E69616D, 0x00000000, 0x00000BEF, 0x00000DA3, 0x00060010,
-    0x0000161F, 0x00000011, 0x00000020, 0x00000020, 0x00000001, 0x00040047, 0x00000BEF, 0x0000000B,
-    0x0000001A, 0x00030047, 0x00000420, 0x00000002, 0x00050048, 0x00000420, 0x00000000, 0x00000023,
-    0x00000000, 0x00050048, 0x00000420, 0x00000001, 0x00000023, 0x00000004, 0x00050048, 0x00000420,
-    0x00000002, 0x00000023, 0x00000008, 0x00050048, 0x00000420, 0x00000003, 0x00000023, 0x0000000C,
-    0x00050048, 0x00000420, 0x00000004, 0x00000023, 0x00000010, 0x00050048, 0x00000420, 0x00000005,
-    0x00000023, 0x00000014, 0x00040047, 0x00000DA3, 0x0000000B, 0x0000001B, 0x00040047, 0x000007D0,
-    0x00000006, 0x00000004, 0x00030047, 0x0000079C, 0x00000003, 0x00040048, 0x0000079C, 0x00000000,
-    0x00000018, 0x00050048, 0x0000079C, 0x00000000, 0x00000023, 0x00000000, 0x00030047, 0x00000C50,
-    0x00000018, 0x00040047, 0x00000C50, 0x00000021, 0x00000000, 0x00040047, 0x00000C50, 0x00000022,
-    0x00000000, 0x00040047, 0x000007D1, 0x00000006, 0x00000004, 0x00030047, 0x0000079D, 0x00000003,
-    0x00040048, 0x0000079D, 0x00000000, 0x00000019, 0x00050048, 0x0000079D, 0x00000000, 0x00000023,
-    0x00000000, 0x00030047, 0x00001592, 0x00000019, 0x00040047, 0x00001592, 0x00000021, 0x00000001,
-    0x00040047, 0x00001592, 0x00000022, 0x00000000, 0x00040047, 0x000000FC, 0x0000000B, 0x00000019,
-    0x00020013, 0x00000008, 0x00030021, 0x00000502, 0x00000008, 0x00040015, 0x0000000B, 0x00000020,
-    0x00000000, 0x00040017, 0x00000014, 0x0000000B, 0x00000003, 0x00040020, 0x00000291, 0x00000001,
-    0x00000014, 0x0004003B, 0x00000291, 0x00000BEF, 0x00000001, 0x0004002B, 0x0000000B, 0x00000A0A,
-    0x00000000, 0x00040020, 0x00000288, 0x00000001, 0x0000000B, 0x0008001E, 0x00000420, 0x0000000B,
-    0x0000000B, 0x0000000B, 0x0000000B, 0x0000000B, 0x0000000B, 0x00040020, 0x0000069D, 0x00000009,
-    0x00000420, 0x0004003B, 0x0000069D, 0x00001342, 0x00000009, 0x00040015, 0x0000000C, 0x00000020,
-    0x00000001, 0x0004002B, 0x0000000C, 0x00000A14, 0x00000003, 0x00040020, 0x00000289, 0x00000009,
-    0x0000000B, 0x00020014, 0x00000009, 0x0004003B, 0x00000291, 0x00000DA3, 0x00000001, 0x0004002B,
-    0x0000000B, 0x00000A0D, 0x00000001, 0x0004002B, 0x0000000B, 0x00000A6A, 0x00000020, 0x0004002B,
-    0x0000000C, 0x00000A11, 0x00000002, 0x0004002B, 0x0000000B, 0x00000A47, 0x00000400, 0x0004002B,
-    0x0000000C, 0x00000A0B, 0x00000000, 0x0004002B, 0x0000000C, 0x00000A0E, 0x00000001, 0x0004002B,
-    0x0000000C, 0x00000A1A, 0x00000005, 0x0004002B, 0x0000000C, 0x00000A17, 0x00000004, 0x0004002B,
-    0x0000000B, 0x00000A10, 0x00000002, 0x0003001D, 0x000007D0, 0x0000000B, 0x0003001E, 0x0000079C,
-    0x000007D0, 0x00040020, 0x00000A19, 0x00000002, 0x0000079C, 0x0004003B, 0x00000A19, 0x00000C50,
-    0x00000002, 0x00040020, 0x0000028A, 0x00000002, 0x0000000B, 0x0004002B, 0x0000000B, 0x00000A13,
-    0x00000003, 0x0004002B, 0x0000000B, 0x00000A22, 0x00000008, 0x0004002B, 0x0000000B, 0x00000144,
-    0x000000FF, 0x0004001C, 0x00000293, 0x0000000B, 0x00000A47, 0x00040020, 0x00000510, 0x00000004,
-    0x00000293, 0x0004003B, 0x00000510, 0x00000FB1, 0x00000004, 0x00040020, 0x0000028B, 0x00000004,
-    0x0000000B, 0x0004002B, 0x0000000B, 0x0000015F, 0x00000108, 0x0003001D, 0x000007D1, 0x0000000B,
-    0x0003001E, 0x0000079D, 0x000007D1, 0x00040020, 0x00000A1B, 0x00000002, 0x0000079D, 0x0004003B,
-    0x00000A1B, 0x00001592, 0x00000002, 0x0004002B, 0x0000000B, 0x00000147, 0x00000100, 0x0004002B,
-    0x0000000B, 0x000001C1, 0x0000FFFF, 0x0004002B, 0x0000000B, 0x00000A3A, 0x00000010, 0x0004002B,
-    0x0000000B, 0x00000447, 0x00000200, 0x0006002C, 0x00000014, 0x000000FC, 0x00000A6A, 0x00000A6A,
-    0x00000A0D, 0x00050036, 0x00000008, 0x0000161F, 0x00000000, 0x00000502, 0x000200F8, 0x00003B06,
-    0x000300F7, 0x00003A37, 0x00000000, 0x000300FB, 0x00000A0A, 0x00002E68, 0x000200F8, 0x00002E68,
-    0x00050041, 0x00000288, 0x000056E5, 0x00000BEF, 0x00000A0A, 0x0004003D, 0x0000000B, 0x00003D0B,
-    0x000056E5, 0x00050041, 0x00000289, 0x000056D1, 0x00001342, 0x00000A14, 0x0004003D, 0x0000000B,
-    0x00001BAD, 0x000056D1, 0x000500AE, 0x00000009, 0x00001CED, 0x00003D0B, 0x00001BAD, 0x000300F7,
-    0x0000401D, 0x00000000, 0x000400FA, 0x00001CED, 0x000055E8, 0x0000401D, 0x000200F8, 0x000055E8,
-    0x000200F9, 0x00003A37, 0x000200F8, 0x0000401D, 0x00050041, 0x00000288, 0x00005098, 0x00000DA3,
-    0x00000A0D, 0x0004003D, 0x0000000B, 0x00003D0C, 0x00005098, 0x00050041, 0x00000288, 0x000053B3,
-    0x00000DA3, 0x00000A0A, 0x0004003D, 0x0000000B, 0x00002F3A, 0x000053B3, 0x00050084, 0x0000000B,
-    0x0000185A, 0x00003D0C, 0x00000A6A, 0x00050080, 0x0000000B, 0x000020A1, 0x0000185A, 0x00002F3A,
-    0x00050041, 0x00000289, 0x0000408D, 0x00001342, 0x00000A11, 0x0004003D, 0x0000000B, 0x00003367,
-    0x0000408D, 0x000500C4, 0x0000000B, 0x00003B4A, 0x00000A0D, 0x00003367, 0x00050084, 0x0000000B,
-    0x00005537, 0x00000A47, 0x00003B4A, 0x00050041, 0x00000289, 0x000032C8, 0x00001342, 0x00000A0B,
-    0x0004003D, 0x0000000B, 0x000048C4, 0x000032C8, 0x00050041, 0x00000289, 0x000053B4, 0x00001342,
-    0x00000A0E, 0x0004003D, 0x0000000B, 0x00002F86, 0x000053B4, 0x00050084, 0x0000000B, 0x00006025,
-    0x000048C4, 0x00002F86, 0x00050084, 0x0000000B, 0x0000359B, 0x00005537, 0x00006025, 0x00050041,
-    0x00000289, 0x00002195, 0x00001342, 0x00000A1A, 0x0004003D, 0x0000000B, 0x000053DE, 0x00002195,
-    0x000500AB, 0x00000009, 0x00005EF7, 0x000053DE, 0x00000A0A, 0x000500AC, 0x00000009, 0x00005C4D,
-    0x00006025, 0x00000A0D, 0x000500A7, 0x00000009, 0x00002B1D, 0x00005EF7, 0x00005C4D, 0x000300F7,
-    0x00005AE2, 0x00000000, 0x000400FA, 0x00002B1D, 0x00002C92, 0x00005AE2, 0x000200F8, 0x00002C92,
-    0x000500C2, 0x0000000B, 0x00004EC7, 0x000048C4, 0x00000A0D, 0x000500C2, 0x0000000B, 0x000060CB,
-    0x00002F86, 0x00000A0D, 0x00050084, 0x0000000B, 0x00003E8A, 0x000060CB, 0x000048C4, 0x00050080,
-    0x0000000B, 0x00004B28, 0x00004EC7, 0x00003E8A, 0x000200F9, 0x00005AE2, 0x000200F8, 0x00005AE2,
-    0x000700F5, 0x0000000B, 0x00004D24, 0x00000A0A, 0x0000401D, 0x00004B28, 0x00002C92, 0x00050041,
-    0x00000289, 0x000061F2, 0x00001342, 0x00000A17, 0x0004003D, 0x0000000B, 0x00006265, 0x000061F2,
-    0x00050084, 0x0000000B, 0x00001D53, 0x00003D0B, 0x0000359B, 0x00050080, 0x0000000B, 0x0000431E,
-    0x00006265, 0x00001D53, 0x00050084, 0x0000000B, 0x00004CEC, 0x000020A1, 0x00003B4A, 0x00050084,
-    0x0000000B, 0x00003F6E, 0x00004CEC, 0x00006025, 0x00050080, 0x0000000B, 0x00001AD5, 0x0000431E,
-    0x00003F6E, 0x00050084, 0x0000000B, 0x00005486, 0x00004D24, 0x00003B4A, 0x00050080, 0x0000000B,
-    0x00004859, 0x00001AD5, 0x00005486, 0x000500C2, 0x0000000B, 0x00001D94, 0x00004859, 0x00000A10,
-    0x00050084, 0x0000000B, 0x00001B17, 0x00003D0B, 0x00005537, 0x00050080, 0x0000000B, 0x000025C1,
-    0x00001B17, 0x00004CEC, 0x000500C2, 0x0000000B, 0x0000237D, 0x000025C1, 0x00000A10, 0x000300F7,
-    0x00004667, 0x00000000, 0x000B00FB, 0x00003367, 0x00004667, 0x00000000, 0x00002E69, 0x00000001,
-    0x0000401E, 0x00000002, 0x0000401F, 0x00000003, 0x00001FDE, 0x000200F8, 0x00002E69, 0x00060041,
-    0x0000028A, 0x000060D7, 0x00000C50, 0x00000A0B, 0x00001D94, 0x0004003D, 0x0000000B, 0x00003241,
-    0x000060D7, 0x000500C7, 0x0000000B, 0x00002F59, 0x00004859, 0x00000A13, 0x00050084, 0x0000000B,
-    0x000036A3, 0x00002F59, 0x00000A22, 0x000500C2, 0x0000000B, 0x0000387D, 0x00003241, 0x000036A3,
-    0x000500C7, 0x0000000B, 0x00003CDC, 0x0000387D, 0x00000144, 0x000500C2, 0x0000000B, 0x00004D70,
-    0x000020A1, 0x00000A10, 0x000500C7, 0x0000000B, 0x00004B2B, 0x000020A1, 0x00000A13, 0x00050084,
-    0x0000000B, 0x00003722, 0x00004B2B, 0x00000A22, 0x000500C4, 0x0000000B, 0x00005A82, 0x00003CDC,
-    0x00003722, 0x000500AA, 0x00000009, 0x00003D0D, 0x00004B2B, 0x00000A0A, 0x000300F7, 0x00005193,
-    0x00000000, 0x000400FA, 0x00003D0D, 0x00002F74, 0x00005193, 0x000200F8, 0x00002F74, 0x00050041,
-    0x0000028B, 0x0000541D, 0x00000FB1, 0x00004D70, 0x0003003E, 0x0000541D, 0x00005A82, 0x000200F9,
-    0x00005193, 0x000200F8, 0x00005193, 0x000400E0, 0x00000A10, 0x00000A10, 0x0000015F, 0x000500AB,
-    0x00000009, 0x00003E3C, 0x00004B2B, 0x00000A0A, 0x000300F7, 0x00002386, 0x00000000, 0x000400FA,
-    0x00003E3C, 0x00003CBD, 0x00002386, 0x000200F8, 0x00003CBD, 0x00050041, 0x0000028B, 0x000025A5,
-    0x00000FB1, 0x00004D70, 0x000700F1, 0x0000000B, 0x0000189F, 0x000025A5, 0x00000A0D, 0x00000A0A,
-    0x00005A82, 0x000200F9, 0x00002386, 0x000200F8, 0x00002386, 0x000400E0, 0x00000A10, 0x00000A10,
-    0x0000015F, 0x000300F7, 0x00004665, 0x00000000, 0x000400FA, 0x00003D0D, 0x00005192, 0x00004665,
-    0x000200F8, 0x00005192, 0x00050084, 0x0000000B, 0x000029FB, 0x00003D0B, 0x00000147, 0x00050080,
-    0x0000000B, 0x0000376A, 0x000029FB, 0x00004D70, 0x00050041, 0x0000028B, 0x000036D4, 0x00000FB1,
-    0x00004D70, 0x0004003D, 0x0000000B, 0x00003C3D, 0x000036D4, 0x00060041, 0x0000028A, 0x00005BB5,
-    0x00001592, 0x00000A0B, 0x0000376A, 0x0003003E, 0x00005BB5, 0x00003C3D, 0x000200F9, 0x00004665,
-    0x000200F8, 0x00004665, 0x000200F9, 0x00004667, 0x000200F8, 0x0000401E, 0x00060041, 0x0000028A,
-    0x00005A8A, 0x00000C50, 0x00000A0B, 0x00001D94, 0x0004003D, 0x0000000B, 0x00003242, 0x00005A8A,
-    0x000500C7, 0x0000000B, 0x00002F5A, 0x00004859, 0x00000A10, 0x00050084, 0x0000000B, 0x000036A4,
-    0x00002F5A, 0x00000A22, 0x000500C2, 0x0000000B, 0x0000387E, 0x00003242, 0x000036A4, 0x000500C7,
-    0x0000000B, 0x00003CDD, 0x0000387E, 0x000001C1, 0x000500C2, 0x0000000B, 0x00004D71, 0x000020A1,
-    0x00000A0D, 0x000500C7, 0x0000000B, 0x00004B2C, 0x000020A1, 0x00000A0D, 0x00050084, 0x0000000B,
-    0x00003723, 0x00004B2C, 0x00000A3A, 0x000500C4, 0x0000000B, 0x00005A83, 0x00003CDD, 0x00003723,
-    0x000500AA, 0x00000009, 0x00003D0E, 0x00004B2C, 0x00000A0A, 0x000300F7, 0x00005194, 0x00000000,
-    0x000400FA, 0x00003D0E, 0x00002F75, 0x00005194, 0x000200F8, 0x00002F75, 0x00050041, 0x0000028B,
-    0x0000541E, 0x00000FB1, 0x00004D71, 0x0003003E, 0x0000541E, 0x00005A83, 0x000200F9, 0x00005194,
-    0x000200F8, 0x00005194, 0x000400E0, 0x00000A10, 0x00000A10, 0x0000015F, 0x000500AB, 0x00000009,
-    0x00003E3D, 0x00004B2C, 0x00000A0A, 0x000300F7, 0x00002387, 0x00000000, 0x000400FA, 0x00003E3D,
-    0x00003CBE, 0x00002387, 0x000200F8, 0x00003CBE, 0x00050041, 0x0000028B, 0x000025A6, 0x00000FB1,
-    0x00004D71, 0x000700F1, 0x0000000B, 0x000018A0, 0x000025A6, 0x00000A0D, 0x00000A0A, 0x00005A83,
-    0x000200F9, 0x00002387, 0x000200F8, 0x00002387, 0x000400E0, 0x00000A10, 0x00000A10, 0x0000015F,
-    0x000300F7, 0x00004666, 0x00000000, 0x000400FA, 0x00003D0E, 0x00005195, 0x00004666, 0x000200F8,
-    0x00005195, 0x00050084, 0x0000000B, 0x000029FC, 0x00003D0B, 0x00000447, 0x00050080, 0x0000000B,
-    0x0000376B, 0x000029FC, 0x00004D71, 0x00050041, 0x0000028B, 0x000036D5, 0x00000FB1, 0x00004D71,
-    0x0004003D, 0x0000000B, 0x00003C3E, 0x000036D5, 0x00060041, 0x0000028A, 0x00005BB6, 0x00001592,
-    0x00000A0B, 0x0000376B, 0x0003003E, 0x00005BB6, 0x00003C3E, 0x000200F9, 0x00004666, 0x000200F8,
-    0x00004666, 0x000200F9, 0x00004667, 0x000200F8, 0x0000401F, 0x00060041, 0x0000028A, 0x00005099,
-    0x00000C50, 0x00000A0B, 0x00001D94, 0x0004003D, 0x0000000B, 0x00003D1E, 0x00005099, 0x00060041,
-    0x0000028A, 0x00005BB7, 0x00001592, 0x00000A0B, 0x0000237D, 0x0003003E, 0x00005BB7, 0x00003D1E,
-    0x000200F9, 0x00004667, 0x000200F8, 0x00001FDE, 0x00060041, 0x0000028A, 0x0000509A, 0x00000C50,
-    0x00000A0B, 0x00001D94, 0x0004003D, 0x0000000B, 0x00003D1F, 0x0000509A, 0x00060041, 0x0000028A,
-    0x000052BA, 0x00001592, 0x00000A0B, 0x0000237D, 0x0003003E, 0x000052BA, 0x00003D1F, 0x00050080,
-    0x0000000B, 0x00004CE6, 0x0000237D, 0x00000A0D, 0x00050080, 0x0000000B, 0x00003448, 0x00001D94,
-    0x00000A0D, 0x00060041, 0x0000028A, 0x00002A3A, 0x00000C50, 0x00000A0B, 0x00003448, 0x0004003D,
-    0x0000000B, 0x00003C3F, 0x00002A3A, 0x00060041, 0x0000028A, 0x00005BB8, 0x00001592, 0x00000A0B,
-    0x00004CE6, 0x0003003E, 0x00005BB8, 0x00003C3F, 0x000200F9, 0x00004667, 0x000200F8, 0x00004667,
-    0x000200F9, 0x00003A37, 0x000200F8, 0x00003A37, 0x000100FD, 0x00010038,
+	0x07230203,0x00010000,0x0008000a,0x00000162,0x00000000,0x00020011,0x00000001,0x0006000b,
+	0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
+	0x0007000f,0x00000005,0x00000004,0x6e69616d,0x00000000,0x0000000b,0x0000001f,0x00060010,
+	0x00000004,0x00000011,0x00000020,0x00000020,0x00000001,0x00030003,0x00000002,0x000001cc,
+	0x00040005,0x00000004,0x6e69616d,0x00000000,0x00050005,0x00000008,0x656c6974,0x646e695f,
+	0x00007865,0x00060005,0x0000000b,0x575f6c67,0x476b726f,0x70756f72,0x00004449,0x00090005,
+	0x00000011,0x6f736552,0x4465766c,0x736e776f,0x656c6163,0x736e6f43,0x746e6174,0x00000073,
+	0x00090006,0x00000011,0x00000000,0x645f6578,0x736e776f,0x656c6163,0x6163735f,0x785f656c,
+	0x00000000,0x00090006,0x00000011,0x00000001,0x645f6578,0x736e776f,0x656c6163,0x6163735f,
+	0x795f656c,0x00000000,0x000b0006,0x00000011,0x00000002,0x645f6578,0x736e776f,0x656c6163,
+	0x7869705f,0x735f6c65,0x5f657a69,0x32676f6c,0x00000000,0x00090006,0x00000011,0x00000003,
+	0x645f6578,0x736e776f,0x656c6163,0x6c69745f,0x6f635f65,0x00746e75,0x000c0006,0x00000011,
+	0x00000004,0x645f6578,0x736e776f,0x656c6163,0x756f735f,0x5f656372,0x7366666f,0x625f7465,
+	0x73657479,0x00000000,0x000b0006,0x00000011,0x00000005,0x645f6578,0x736e776f,0x656c6163,
+	0x6c61685f,0x69705f66,0x5f6c6578,0x7366666f,0x00007465,0x00090006,0x00000011,0x00000006,
+	0x645f6578,0x736e776f,0x656c6163,0x6576615f,0x65676172,0x00000000,0x00030005,0x00000013,
+	0x00000000,0x00030005,0x0000001e,0x00776f72,0x00080005,0x0000001f,0x4c5f6c67,0x6c61636f,
+	0x6f766e49,0x69746163,0x44496e6f,0x00000000,0x00040005,0x00000023,0x756c6f63,0x00006e6d,
+	0x00050005,0x00000026,0x65786970,0x6e695f6c,0x00786564,0x00050005,0x0000002c,0x65786970,
+	0x69735f6c,0x0000657a,0x00060005,0x00000031,0x656c6974,0x7a69735f,0x78315f65,0x00000000,
+	0x00050005,0x00000035,0x6c616373,0x79785f65,0x00000000,0x00070005,0x0000003d,0x656c6974,
+	0x7a69735f,0x63735f65,0x64656c61,0x00000000,0x00070005,0x00000041,0x636f6c62,0x61735f6b,
+	0x656c706d,0x66666f5f,0x00746573,0x00050005,0x0000004b,0x7366666f,0x785f7465,0x00000000,
+	0x00050005,0x0000004f,0x7366666f,0x795f7465,0x00000000,0x00060005,0x00000059,0x5f637273,
+	0x65747962,0x66666f5f,0x00746573,0x00050005,0x0000006b,0x5f637273,0x7366666f,0x00007465,
+	0x00060005,0x0000006f,0x5f747364,0x65747962,0x66666f5f,0x00746573,0x00050005,0x00000077,
+	0x5f747364,0x7366666f,0x00007465,0x00050005,0x00000081,0x5f637273,0x64726f77,0x00000000,
+	0x00060005,0x00000083,0x72756f53,0x75426563,0x72656666,0x00000000,0x00050006,0x00000083,
+	0x00000000,0x61746164,0x00000000,0x00070005,0x00000085,0x725f6578,0x6c6f7365,0x735f6576,
+	0x6372756f,0x00000065,0x00050005,0x0000008a,0x65747962,0x6c61765f,0x00000000,0x00050005,
+	0x00000094,0x6b636170,0x646e695f,0x00007865,0x00050005,0x00000097,0x65747962,0x736f705f,
+	0x00000000,0x00060005,0x0000009a,0x746e6f63,0x75626972,0x6e6f6974,0x00000000,0x00060005,
+	0x000000a5,0x745f7367,0x5f656c69,0x61746164,0x00000000,0x00050005,0x000000b8,0x74736544,
+	0x66667542,0x00007265,0x00050006,0x000000b8,0x00000000,0x61746164,0x00000000,0x00060005,
+	0x000000ba,0x725f6578,0x6c6f7365,0x645f6576,0x00747365,0x00050005,0x000000c5,0x5f637273,
+	0x64726f77,0x00000000,0x00050005,0x000000c9,0x726f6873,0x61765f74,0x0000006c,0x00050005,
+	0x000000d1,0x6b636170,0x646e695f,0x00007865,0x00050005,0x000000d4,0x726f6873,0x6f705f74,
+	0x00000073,0x00060005,0x000000d7,0x746e6f63,0x75626972,0x6e6f6974,0x00000000,0x00050005,
+	0x00000103,0x636f6c62,0x61625f6b,0x00006573,0x00030005,0x00000113,0x006d7573,0x00030005,
+	0x00000115,0x00000073,0x00040005,0x0000011e,0x65786574,0x0000006c,0x00040047,0x0000000b,
+	0x0000000b,0x0000001a,0x00050048,0x00000011,0x00000000,0x00000023,0x00000000,0x00050048,
+	0x00000011,0x00000001,0x00000023,0x00000004,0x00050048,0x00000011,0x00000002,0x00000023,
+	0x00000008,0x00050048,0x00000011,0x00000003,0x00000023,0x0000000c,0x00050048,0x00000011,
+	0x00000004,0x00000023,0x00000010,0x00050048,0x00000011,0x00000005,0x00000023,0x00000014,
+	0x00050048,0x00000011,0x00000006,0x00000023,0x00000018,0x00030047,0x00000011,0x00000002,
+	0x00040047,0x0000001f,0x0000000b,0x0000001b,0x00040047,0x00000082,0x00000006,0x00000004,
+	0x00040048,0x00000083,0x00000000,0x00000018,0x00050048,0x00000083,0x00000000,0x00000023,
+	0x00000000,0x00030047,0x00000083,0x00000003,0x00040047,0x00000085,0x00000022,0x00000000,
+	0x00040047,0x00000085,0x00000021,0x00000000,0x00040047,0x000000b7,0x00000006,0x00000004,
+	0x00040048,0x000000b8,0x00000000,0x00000019,0x00050048,0x000000b8,0x00000000,0x00000023,
+	0x00000000,0x00030047,0x000000b8,0x00000003,0x00040047,0x000000ba,0x00000022,0x00000000,
+	0x00040047,0x000000ba,0x00000021,0x00000001,0x00040047,0x00000161,0x0000000b,0x00000019,
+	0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00040015,0x00000006,0x00000020,
+	0x00000000,0x00040020,0x00000007,0x00000007,0x00000006,0x00040017,0x00000009,0x00000006,
+	0x00000003,0x00040020,0x0000000a,0x00000001,0x00000009,0x0004003b,0x0000000a,0x0000000b,
+	0x00000001,0x0004002b,0x00000006,0x0000000c,0x00000000,0x00040020,0x0000000d,0x00000001,
+	0x00000006,0x0009001e,0x00000011,0x00000006,0x00000006,0x00000006,0x00000006,0x00000006,
+	0x00000006,0x00000006,0x00040020,0x00000012,0x00000009,0x00000011,0x0004003b,0x00000012,
+	0x00000013,0x00000009,0x00040015,0x00000014,0x00000020,0x00000001,0x0004002b,0x00000014,
+	0x00000015,0x00000003,0x00040020,0x00000016,0x00000009,0x00000006,0x00020014,0x00000019,
+	0x0004003b,0x0000000a,0x0000001f,0x00000001,0x0004002b,0x00000006,0x00000020,0x00000001,
+	0x0004002b,0x00000006,0x00000028,0x00000020,0x0004002b,0x00000014,0x0000002d,0x00000002,
+	0x0004002b,0x00000006,0x00000032,0x00000400,0x0004002b,0x00000014,0x00000036,0x00000000,
+	0x0004002b,0x00000014,0x00000039,0x00000001,0x0004002b,0x00000014,0x00000042,0x00000005,
+	0x0004002b,0x00000014,0x0000005a,0x00000004,0x0004002b,0x00000006,0x0000006d,0x00000002,
+	0x0003001d,0x00000082,0x00000006,0x0003001e,0x00000083,0x00000082,0x00040020,0x00000084,
+	0x00000002,0x00000083,0x0004003b,0x00000084,0x00000085,0x00000002,0x00040020,0x00000087,
+	0x00000002,0x00000006,0x0004002b,0x00000006,0x0000008d,0x00000003,0x0004002b,0x00000006,
+	0x0000008f,0x00000008,0x0004002b,0x00000006,0x00000092,0x000000ff,0x0004001c,0x000000a3,
+	0x00000006,0x00000032,0x00040020,0x000000a4,0x00000004,0x000000a3,0x0004003b,0x000000a4,
+	0x000000a5,0x00000004,0x00040020,0x000000a8,0x00000004,0x00000006,0x0004002b,0x00000006,
+	0x000000aa,0x00000108,0x0003001d,0x000000b7,0x00000006,0x0003001e,0x000000b8,0x000000b7,
+	0x00040020,0x000000b9,0x00000002,0x000000b8,0x0004003b,0x000000b9,0x000000ba,0x00000002,
+	0x0004002b,0x00000006,0x000000bc,0x00000100,0x0004002b,0x00000006,0x000000cf,0x0000ffff,
+	0x0004002b,0x00000006,0x000000da,0x00000010,0x0004002b,0x00000006,0x000000f1,0x00000200,
+	0x0004002b,0x00000014,0x000000fa,0x00000006,0x00040017,0x00000111,0x00000006,0x00000004,
+	0x00040020,0x00000112,0x00000007,0x00000111,0x0007002c,0x00000111,0x00000114,0x0000000c,
+	0x0000000c,0x0000000c,0x0000000c,0x0004002b,0x00000006,0x0000012d,0x00000018,0x0006002c,
+	0x00000009,0x00000161,0x00000028,0x00000028,0x00000020,0x00050036,0x00000002,0x00000004,
+	0x00000000,0x00000003,0x000200f8,0x00000005,0x0004003b,0x00000007,0x00000008,0x00000007,
+	0x0004003b,0x00000007,0x0000001e,0x00000007,0x0004003b,0x00000007,0x00000023,0x00000007,
+	0x0004003b,0x00000007,0x00000026,0x00000007,0x0004003b,0x00000007,0x0000002c,0x00000007,
+	0x0004003b,0x00000007,0x00000031,0x00000007,0x0004003b,0x00000007,0x00000035,0x00000007,
+	0x0004003b,0x00000007,0x0000003d,0x00000007,0x0004003b,0x00000007,0x00000041,0x00000007,
+	0x0004003b,0x00000007,0x0000004b,0x00000007,0x0004003b,0x00000007,0x0000004f,0x00000007,
+	0x0004003b,0x00000007,0x00000059,0x00000007,0x0004003b,0x00000007,0x0000006b,0x00000007,
+	0x0004003b,0x00000007,0x0000006f,0x00000007,0x0004003b,0x00000007,0x00000077,0x00000007,
+	0x0004003b,0x00000007,0x00000081,0x00000007,0x0004003b,0x00000007,0x0000008a,0x00000007,
+	0x0004003b,0x00000007,0x00000094,0x00000007,0x0004003b,0x00000007,0x00000097,0x00000007,
+	0x0004003b,0x00000007,0x0000009a,0x00000007,0x0004003b,0x00000007,0x000000c5,0x00000007,
+	0x0004003b,0x00000007,0x000000c9,0x00000007,0x0004003b,0x00000007,0x000000d1,0x00000007,
+	0x0004003b,0x00000007,0x000000d4,0x00000007,0x0004003b,0x00000007,0x000000d7,0x00000007,
+	0x0004003b,0x00000007,0x00000103,0x00000007,0x0004003b,0x00000112,0x00000113,0x00000007,
+	0x0004003b,0x00000007,0x00000115,0x00000007,0x0004003b,0x00000007,0x0000011e,0x00000007,
+	0x00050041,0x0000000d,0x0000000e,0x0000000b,0x0000000c,0x0004003d,0x00000006,0x0000000f,
+	0x0000000e,0x0003003e,0x00000008,0x0000000f,0x0004003d,0x00000006,0x00000010,0x00000008,
+	0x00050041,0x00000016,0x00000017,0x00000013,0x00000015,0x0004003d,0x00000006,0x00000018,
+	0x00000017,0x000500ae,0x00000019,0x0000001a,0x00000010,0x00000018,0x000300f7,0x0000001c,
+	0x00000000,0x000400fa,0x0000001a,0x0000001b,0x0000001c,0x000200f8,0x0000001b,0x000100fd,
+	0x000200f8,0x0000001c,0x00050041,0x0000000d,0x00000021,0x0000001f,0x00000020,0x0004003d,
+	0x00000006,0x00000022,0x00000021,0x0003003e,0x0000001e,0x00000022,0x00050041,0x0000000d,
+	0x00000024,0x0000001f,0x0000000c,0x0004003d,0x00000006,0x00000025,0x00000024,0x0003003e,
+	0x00000023,0x00000025,0x0004003d,0x00000006,0x00000027,0x0000001e,0x00050084,0x00000006,
+	0x00000029,0x00000027,0x00000028,0x0004003d,0x00000006,0x0000002a,0x00000023,0x00050080,
+	0x00000006,0x0000002b,0x00000029,0x0000002a,0x0003003e,0x00000026,0x0000002b,0x00050041,
+	0x00000016,0x0000002e,0x00000013,0x0000002d,0x0004003d,0x00000006,0x0000002f,0x0000002e,
+	0x000500c4,0x00000006,0x00000030,0x00000020,0x0000002f,0x0003003e,0x0000002c,0x00000030,
+	0x0004003d,0x00000006,0x00000033,0x0000002c,0x00050084,0x00000006,0x00000034,0x00000032,
+	0x00000033,0x0003003e,0x00000031,0x00000034,0x00050041,0x00000016,0x00000037,0x00000013,
+	0x00000036,0x0004003d,0x00000006,0x00000038,0x00000037,0x00050041,0x00000016,0x0000003a,
+	0x00000013,0x00000039,0x0004003d,0x00000006,0x0000003b,0x0000003a,0x00050084,0x00000006,
+	0x0000003c,0x00000038,0x0000003b,0x0003003e,0x00000035,0x0000003c,0x0004003d,0x00000006,
+	0x0000003e,0x00000031,0x0004003d,0x00000006,0x0000003f,0x00000035,0x00050084,0x00000006,
+	0x00000040,0x0000003e,0x0000003f,0x0003003e,0x0000003d,0x00000040,0x0003003e,0x00000041,
+	0x0000000c,0x00050041,0x00000016,0x00000043,0x00000013,0x00000042,0x0004003d,0x00000006,
+	0x00000044,0x00000043,0x000500ab,0x00000019,0x00000045,0x00000044,0x0000000c,0x0004003d,
+	0x00000006,0x00000046,0x00000035,0x000500ac,0x00000019,0x00000047,0x00000046,0x00000020,
+	0x000500a7,0x00000019,0x00000048,0x00000045,0x00000047,0x000300f7,0x0000004a,0x00000000,
+	0x000400fa,0x00000048,0x00000049,0x0000004a,0x000200f8,0x00000049,0x00050041,0x00000016,
+	0x0000004c,0x00000013,0x00000036,0x0004003d,0x00000006,0x0000004d,0x0000004c,0x000500c2,
+	0x00000006,0x0000004e,0x0000004d,0x00000020,0x0003003e,0x0000004b,0x0000004e,0x00050041,
+	0x00000016,0x00000050,0x00000013,0x00000039,0x0004003d,0x00000006,0x00000051,0x00000050,
+	0x000500c2,0x00000006,0x00000052,0x00000051,0x00000020,0x0003003e,0x0000004f,0x00000052,
+	0x0004003d,0x00000006,0x00000053,0x0000004b,0x0004003d,0x00000006,0x00000054,0x0000004f,
+	0x00050041,0x00000016,0x00000055,0x00000013,0x00000036,0x0004003d,0x00000006,0x00000056,
+	0x00000055,0x00050084,0x00000006,0x00000057,0x00000054,0x00000056,0x00050080,0x00000006,
+	0x00000058,0x00000053,0x00000057,0x0003003e,0x00000041,0x00000058,0x000200f9,0x0000004a,
+	0x000200f8,0x0000004a,0x00050041,0x00000016,0x0000005b,0x00000013,0x0000005a,0x0004003d,
+	0x00000006,0x0000005c,0x0000005b,0x0004003d,0x00000006,0x0000005d,0x00000008,0x0004003d,
+	0x00000006,0x0000005e,0x0000003d,0x00050084,0x00000006,0x0000005f,0x0000005d,0x0000005e,
+	0x00050080,0x00000006,0x00000060,0x0000005c,0x0000005f,0x0004003d,0x00000006,0x00000061,
+	0x00000026,0x0004003d,0x00000006,0x00000062,0x0000002c,0x00050084,0x00000006,0x00000063,
+	0x00000061,0x00000062,0x0004003d,0x00000006,0x00000064,0x00000035,0x00050084,0x00000006,
+	0x00000065,0x00000063,0x00000064,0x00050080,0x00000006,0x00000066,0x00000060,0x00000065,
+	0x0004003d,0x00000006,0x00000067,0x00000041,0x0004003d,0x00000006,0x00000068,0x0000002c,
+	0x00050084,0x00000006,0x00000069,0x00000067,0x00000068,0x00050080,0x00000006,0x0000006a,
+	0x00000066,0x00000069,0x0003003e,0x00000059,0x0000006a,0x0004003d,0x00000006,0x0000006c,
+	0x00000059,0x000500c2,0x00000006,0x0000006e,0x0000006c,0x0000006d,0x0003003e,0x0000006b,
+	0x0000006e,0x0004003d,0x00000006,0x00000070,0x00000008,0x0004003d,0x00000006,0x00000071,
+	0x00000031,0x00050084,0x00000006,0x00000072,0x00000070,0x00000071,0x0004003d,0x00000006,
+	0x00000073,0x00000026,0x0004003d,0x00000006,0x00000074,0x0000002c,0x00050084,0x00000006,
+	0x00000075,0x00000073,0x00000074,0x00050080,0x00000006,0x00000076,0x00000072,0x00000075,
+	0x0003003e,0x0000006f,0x00000076,0x0004003d,0x00000006,0x00000078,0x0000006f,0x000500c2,
+	0x00000006,0x00000079,0x00000078,0x0000006d,0x0003003e,0x00000077,0x00000079,0x00050041,
+	0x00000016,0x0000007a,0x00000013,0x0000002d,0x0004003d,0x00000006,0x0000007b,0x0000007a,
+	0x000300f7,0x00000080,0x00000000,0x000b00fb,0x0000007b,0x00000080,0x00000000,0x0000007c,
+	0x00000001,0x0000007d,0x00000002,0x0000007e,0x00000003,0x0000007f,0x000200f8,0x0000007c,
+	0x0004003d,0x00000006,0x00000086,0x0000006b,0x00060041,0x00000087,0x00000088,0x00000085,
+	0x00000036,0x00000086,0x0004003d,0x00000006,0x00000089,0x00000088,0x0003003e,0x00000081,
+	0x00000089,0x0004003d,0x00000006,0x0000008b,0x00000081,0x0004003d,0x00000006,0x0000008c,
+	0x00000059,0x000500c7,0x00000006,0x0000008e,0x0000008c,0x0000008d,0x00050084,0x00000006,
+	0x00000090,0x0000008e,0x0000008f,0x000500c2,0x00000006,0x00000091,0x0000008b,0x00000090,
+	0x000500c7,0x00000006,0x00000093,0x00000091,0x00000092,0x0003003e,0x0000008a,0x00000093,
+	0x0004003d,0x00000006,0x00000095,0x00000026,0x000500c2,0x00000006,0x00000096,0x00000095,
+	0x0000006d,0x0003003e,0x00000094,0x00000096,0x0004003d,0x00000006,0x00000098,0x00000026,
+	0x000500c7,0x00000006,0x00000099,0x00000098,0x0000008d,0x0003003e,0x00000097,0x00000099,
+	0x0004003d,0x00000006,0x0000009b,0x0000008a,0x0004003d,0x00000006,0x0000009c,0x00000097,
+	0x00050084,0x00000006,0x0000009d,0x0000009c,0x0000008f,0x000500c4,0x00000006,0x0000009e,
+	0x0000009b,0x0000009d,0x0003003e,0x0000009a,0x0000009e,0x0004003d,0x00000006,0x0000009f,
+	0x00000097,0x000500aa,0x00000019,0x000000a0,0x0000009f,0x0000000c,0x000300f7,0x000000a2,
+	0x00000000,0x000400fa,0x000000a0,0x000000a1,0x000000a2,0x000200f8,0x000000a1,0x0004003d,
+	0x00000006,0x000000a6,0x00000094,0x0004003d,0x00000006,0x000000a7,0x0000009a,0x00050041,
+	0x000000a8,0x000000a9,0x000000a5,0x000000a6,0x0003003e,0x000000a9,0x000000a7,0x000200f9,
+	0x000000a2,0x000200f8,0x000000a2,0x000400e0,0x0000006d,0x0000006d,0x000000aa,0x0004003d,
+	0x00000006,0x000000ab,0x00000097,0x000500ab,0x00000019,0x000000ac,0x000000ab,0x0000000c,
+	0x000300f7,0x000000ae,0x00000000,0x000400fa,0x000000ac,0x000000ad,0x000000ae,0x000200f8,
+	0x000000ad,0x0004003d,0x00000006,0x000000af,0x00000094,0x00050041,0x000000a8,0x000000b0,
+	0x000000a5,0x000000af,0x0004003d,0x00000006,0x000000b1,0x0000009a,0x000700f1,0x00000006,
+	0x000000b2,0x000000b0,0x00000020,0x0000000c,0x000000b1,0x000200f9,0x000000ae,0x000200f8,
+	0x000000ae,0x000400e0,0x0000006d,0x0000006d,0x000000aa,0x0004003d,0x00000006,0x000000b3,
+	0x00000097,0x000500aa,0x00000019,0x000000b4,0x000000b3,0x0000000c,0x000300f7,0x000000b6,
+	0x00000000,0x000400fa,0x000000b4,0x000000b5,0x000000b6,0x000200f8,0x000000b5,0x0004003d,
+	0x00000006,0x000000bb,0x00000008,0x00050084,0x00000006,0x000000bd,0x000000bb,0x000000bc,
+	0x0004003d,0x00000006,0x000000be,0x00000094,0x00050080,0x00000006,0x000000bf,0x000000bd,
+	0x000000be,0x0004003d,0x00000006,0x000000c0,0x00000094,0x00050041,0x000000a8,0x000000c1,
+	0x000000a5,0x000000c0,0x0004003d,0x00000006,0x000000c2,0x000000c1,0x00060041,0x00000087,
+	0x000000c3,0x000000ba,0x00000036,0x000000bf,0x0003003e,0x000000c3,0x000000c2,0x000200f9,
+	0x000000b6,0x000200f8,0x000000b6,0x000200f9,0x00000080,0x000200f8,0x0000007d,0x0004003d,
+	0x00000006,0x000000c6,0x0000006b,0x00060041,0x00000087,0x000000c7,0x00000085,0x00000036,
+	0x000000c6,0x0004003d,0x00000006,0x000000c8,0x000000c7,0x0003003e,0x000000c5,0x000000c8,
+	0x0004003d,0x00000006,0x000000ca,0x000000c5,0x0004003d,0x00000006,0x000000cb,0x00000059,
+	0x000500c7,0x00000006,0x000000cc,0x000000cb,0x0000006d,0x00050084,0x00000006,0x000000cd,
+	0x000000cc,0x0000008f,0x000500c2,0x00000006,0x000000ce,0x000000ca,0x000000cd,0x000500c7,
+	0x00000006,0x000000d0,0x000000ce,0x000000cf,0x0003003e,0x000000c9,0x000000d0,0x0004003d,
+	0x00000006,0x000000d2,0x00000026,0x000500c2,0x00000006,0x000000d3,0x000000d2,0x00000020,
+	0x0003003e,0x000000d1,0x000000d3,0x0004003d,0x00000006,0x000000d5,0x00000026,0x000500c7,
+	0x00000006,0x000000d6,0x000000d5,0x00000020,0x0003003e,0x000000d4,0x000000d6,0x0004003d,
+	0x00000006,0x000000d8,0x000000c9,0x0004003d,0x00000006,0x000000d9,0x000000d4,0x00050084,
+	0x00000006,0x000000db,0x000000d9,0x000000da,0x000500c4,0x00000006,0x000000dc,0x000000d8,
+	0x000000db,0x0003003e,0x000000d7,0x000000dc,0x0004003d,0x00000006,0x000000dd,0x000000d4,
+	0x000500aa,0x00000019,0x000000de,0x000000dd,0x0000000c,0x000300f7,0x000000e0,0x00000000,
+	0x000400fa,0x000000de,0x000000df,0x000000e0,0x000200f8,0x000000df,0x0004003d,0x00000006,
+	0x000000e1,0x000000d1,0x0004003d,0x00000006,0x000000e2,0x000000d7,0x00050041,0x000000a8,
+	0x000000e3,0x000000a5,0x000000e1,0x0003003e,0x000000e3,0x000000e2,0x000200f9,0x000000e0,
+	0x000200f8,0x000000e0,0x000400e0,0x0000006d,0x0000006d,0x000000aa,0x0004003d,0x00000006,
+	0x000000e4,0x000000d4,0x000500ab,0x00000019,0x000000e5,0x000000e4,0x0000000c,0x000300f7,
+	0x000000e7,0x00000000,0x000400fa,0x000000e5,0x000000e6,0x000000e7,0x000200f8,0x000000e6,
+	0x0004003d,0x00000006,0x000000e8,0x000000d1,0x00050041,0x000000a8,0x000000e9,0x000000a5,
+	0x000000e8,0x0004003d,0x00000006,0x000000ea,0x000000d7,0x000700f1,0x00000006,0x000000eb,
+	0x000000e9,0x00000020,0x0000000c,0x000000ea,0x000200f9,0x000000e7,0x000200f8,0x000000e7,
+	0x000400e0,0x0000006d,0x0000006d,0x000000aa,0x0004003d,0x00000006,0x000000ec,0x000000d4,
+	0x000500aa,0x00000019,0x000000ed,0x000000ec,0x0000000c,0x000300f7,0x000000ef,0x00000000,
+	0x000400fa,0x000000ed,0x000000ee,0x000000ef,0x000200f8,0x000000ee,0x0004003d,0x00000006,
+	0x000000f0,0x00000008,0x00050084,0x00000006,0x000000f2,0x000000f0,0x000000f1,0x0004003d,
+	0x00000006,0x000000f3,0x000000d1,0x00050080,0x00000006,0x000000f4,0x000000f2,0x000000f3,
+	0x0004003d,0x00000006,0x000000f5,0x000000d1,0x00050041,0x000000a8,0x000000f6,0x000000a5,
+	0x000000f5,0x0004003d,0x00000006,0x000000f7,0x000000f6,0x00060041,0x00000087,0x000000f8,
+	0x000000ba,0x00000036,0x000000f4,0x0003003e,0x000000f8,0x000000f7,0x000200f9,0x000000ef,
+	0x000200f8,0x000000ef,0x000200f9,0x00000080,0x000200f8,0x0000007e,0x00050041,0x00000016,
+	0x000000fb,0x00000013,0x000000fa,0x0004003d,0x00000006,0x000000fc,0x000000fb,0x000500ab,
+	0x00000019,0x000000fd,0x000000fc,0x0000000c,0x0004003d,0x00000006,0x000000fe,0x00000035,
+	0x000500ac,0x00000019,0x000000ff,0x000000fe,0x00000020,0x000500a7,0x00000019,0x00000100,
+	0x000000fd,0x000000ff,0x000300f7,0x00000102,0x00000000,0x000400fa,0x00000100,0x00000101,
+	0x0000014c,0x000200f8,0x00000101,0x00050041,0x00000016,0x00000104,0x00000013,0x0000005a,
+	0x0004003d,0x00000006,0x00000105,0x00000104,0x0004003d,0x00000006,0x00000106,0x00000008,
+	0x0004003d,0x00000006,0x00000107,0x0000003d,0x00050084,0x00000006,0x00000108,0x00000106,
+	0x00000107,0x00050080,0x00000006,0x00000109,0x00000105,0x00000108,0x0004003d,0x00000006,
+	0x0000010a,0x00000026,0x0004003d,0x00000006,0x0000010b,0x0000002c,0x00050084,0x00000006,
+	0x0000010c,0x0000010a,0x0000010b,0x0004003d,0x00000006,0x0000010d,0x00000035,0x00050084,
+	0x00000006,0x0000010e,0x0000010c,0x0000010d,0x00050080,0x00000006,0x0000010f,0x00000109,
+	0x0000010e,0x000500c2,0x00000006,0x00000110,0x0000010f,0x0000006d,0x0003003e,0x00000103,
+	0x00000110,0x0003003e,0x00000113,0x00000114,0x0003003e,0x00000115,0x0000000c,0x000200f9,
+	0x00000116,0x000200f8,0x00000116,0x000400f6,0x00000118,0x00000119,0x00000000,0x000200f9,
+	0x0000011a,0x000200f8,0x0000011a,0x0004003d,0x00000006,0x0000011b,0x00000115,0x0004003d,
+	0x00000006,0x0000011c,0x00000035,0x000500b0,0x00000019,0x0000011d,0x0000011b,0x0000011c,
+	0x000400fa,0x0000011d,0x00000117,0x00000118,0x000200f8,0x00000117,0x0004003d,0x00000006,
+	0x0000011f,0x00000103,0x0004003d,0x00000006,0x00000120,0x00000115,0x00050080,0x00000006,
+	0x00000121,0x0000011f,0x00000120,0x00060041,0x00000087,0x00000122,0x00000085,0x00000036,
+	0x00000121,0x0004003d,0x00000006,0x00000123,0x00000122,0x0003003e,0x0000011e,0x00000123,
+	0x0004003d,0x00000006,0x00000124,0x0000011e,0x000500c7,0x00000006,0x00000125,0x00000124,
+	0x00000092,0x0004003d,0x00000006,0x00000126,0x0000011e,0x000500c2,0x00000006,0x00000127,
+	0x00000126,0x0000008f,0x000500c7,0x00000006,0x00000128,0x00000127,0x00000092,0x0004003d,
+	0x00000006,0x00000129,0x0000011e,0x000500c2,0x00000006,0x0000012a,0x00000129,0x000000da,
+	0x000500c7,0x00000006,0x0000012b,0x0000012a,0x00000092,0x0004003d,0x00000006,0x0000012c,
+	0x0000011e,0x000500c2,0x00000006,0x0000012e,0x0000012c,0x0000012d,0x00070050,0x00000111,
+	0x0000012f,0x00000125,0x00000128,0x0000012b,0x0000012e,0x0004003d,0x00000111,0x00000130,
+	0x00000113,0x00050080,0x00000111,0x00000131,0x00000130,0x0000012f,0x0003003e,0x00000113,
+	0x00000131,0x000200f9,0x00000119,0x000200f8,0x00000119,0x0004003d,0x00000006,0x00000132,
+	0x00000115,0x00050080,0x00000006,0x00000133,0x00000132,0x00000039,0x0003003e,0x00000115,
+	0x00000133,0x000200f9,0x00000116,0x000200f8,0x00000118,0x0004003d,0x00000111,0x00000134,
+	0x00000113,0x0004003d,0x00000006,0x00000135,0x00000035,0x000500c2,0x00000006,0x00000136,
+	0x00000135,0x00000020,0x00070050,0x00000111,0x00000137,0x00000136,0x00000136,0x00000136,
+	0x00000136,0x00050080,0x00000111,0x00000138,0x00000134,0x00000137,0x0004003d,0x00000006,
+	0x00000139,0x00000035,0x00070050,0x00000111,0x0000013a,0x00000139,0x00000139,0x00000139,
+	0x00000139,0x00050086,0x00000111,0x0000013b,0x00000138,0x0000013a,0x0003003e,0x00000113,
+	0x0000013b,0x0004003d,0x00000006,0x0000013c,0x00000077,0x00050041,0x00000007,0x0000013d,
+	0x00000113,0x0000000c,0x0004003d,0x00000006,0x0000013e,0x0000013d,0x00050041,0x00000007,
+	0x0000013f,0x00000113,0x00000020,0x0004003d,0x00000006,0x00000140,0x0000013f,0x000500c4,
+	0x00000006,0x00000141,0x00000140,0x0000008f,0x000500c5,0x00000006,0x00000142,0x0000013e,
+	0x00000141,0x00050041,0x00000007,0x00000143,0x00000113,0x0000006d,0x0004003d,0x00000006,
+	0x00000144,0x00000143,0x000500c4,0x00000006,0x00000145,0x00000144,0x000000da,0x000500c5,
+	0x00000006,0x00000146,0x00000142,0x00000145,0x00050041,0x00000007,0x00000147,0x00000113,
+	0x0000008d,0x0004003d,0x00000006,0x00000148,0x00000147,0x000500c4,0x00000006,0x00000149,
+	0x00000148,0x0000012d,0x000500c5,0x00000006,0x0000014a,0x00000146,0x00000149,0x00060041,
+	0x00000087,0x0000014b,0x000000ba,0x00000036,0x0000013c,0x0003003e,0x0000014b,0x0000014a,
+	0x000200f9,0x00000102,0x000200f8,0x0000014c,0x0004003d,0x00000006,0x0000014d,0x00000077,
+	0x0004003d,0x00000006,0x0000014e,0x0000006b,0x00060041,0x00000087,0x0000014f,0x00000085,
+	0x00000036,0x0000014e,0x0004003d,0x00000006,0x00000150,0x0000014f,0x00060041,0x00000087,
+	0x00000151,0x000000ba,0x00000036,0x0000014d,0x0003003e,0x00000151,0x00000150,0x000200f9,
+	0x00000102,0x000200f8,0x00000102,0x000200f9,0x00000080,0x000200f8,0x0000007f,0x0004003d,
+	0x00000006,0x00000153,0x00000077,0x0004003d,0x00000006,0x00000154,0x0000006b,0x00060041,
+	0x00000087,0x00000155,0x00000085,0x00000036,0x00000154,0x0004003d,0x00000006,0x00000156,
+	0x00000155,0x00060041,0x00000087,0x00000157,0x000000ba,0x00000036,0x00000153,0x0003003e,
+	0x00000157,0x00000156,0x0004003d,0x00000006,0x00000158,0x00000077,0x00050080,0x00000006,
+	0x00000159,0x00000158,0x00000020,0x0004003d,0x00000006,0x0000015a,0x0000006b,0x00050080,
+	0x00000006,0x0000015b,0x0000015a,0x00000020,0x00060041,0x00000087,0x0000015c,0x00000085,
+	0x00000036,0x0000015b,0x0004003d,0x00000006,0x0000015d,0x0000015c,0x00060041,0x00000087,
+	0x0000015e,0x000000ba,0x00000036,0x00000159,0x0003003e,0x0000015e,0x0000015d,0x000200f9,
+	0x00000080,0x000200f8,0x00000080,0x000100fd,0x00010038
 };
diff --git a/src/graphics/shared_memory.cpp b/src/graphics/shared_memory.cpp
index ec0df7c..2ac72b9 100644
--- a/src/graphics/shared_memory.cpp
+++ b/src/graphics/shared_memory.cpp
@@ -530,6 +530,11 @@ std::pair<uint32_t, uint32_t> SharedMemory::MemoryInvalidationCallback(
 
   FireWatches(page_first, page_last, false);
 
+  if (invalidation_observer_) {
+    invalidation_observer_(page_first << page_size_log2_,
+                           (page_last - page_first + 1) << page_size_log2_);
+  }
+
   return std::make_pair(page_first << page_size_log2_, (page_last - page_first + 1)
                                                            << page_size_log2_);
 }
diff --git a/src/graphics/util/draw_extent_estimator.cpp b/src/graphics/util/draw_extent_estimator.cpp
index 3027dc8..54f77a9 100644
--- a/src/graphics/util/draw_extent_estimator.cpp
+++ b/src/graphics/util/draw_extent_estimator.cpp
@@ -24,7 +24,7 @@
 #include <rex/memory.h>
 #include <rex/ui/graphics_util.h>
 
-REXCVAR_DEFINE_BOOL(execute_unclipped_draw_vs_on_cpu, false, "GPU",
+REXCVAR_DEFINE_BOOL(execute_unclipped_draw_vs_on_cpu, true, "GPU",
                     "Execute unclipped draw vertex shader on CPU");
 
 REXCVAR_DEFINE_BOOL(execute_unclipped_draw_vs_on_cpu_with_scissor, false, "GPU",
diff --git a/src/graphics/vulkan/command_processor.cpp b/src/graphics/vulkan/command_processor.cpp
index 001f36b..f2af0d9 100644
--- a/src/graphics/vulkan/command_processor.cpp
+++ b/src/graphics/vulkan/command_processor.cpp
@@ -11,6 +11,7 @@
 
 #include <algorithm>
 #include <array>
+#include <chrono>
 #include <cstdint>
 #include <cstring>
 #include <iterator>
@@ -27,6 +28,7 @@
 #include <rex/cvar.h>
 #include <rex/dbg.h>
 #include <rex/logging.h>
+#include <rex/perf/counter.h>
 #include <rex/math.h>
 #include <rex/graphics/util/draw.h>
 #include <rex/graphics/flags.h>
@@ -44,9 +46,41 @@
 #include <rex/memory/utils.h>
 #include <rex/ui/flags.h>
 #include <rex/ui/vulkan/presenter.h>
+#include <rex/ui/vulkan/fence_wait_timing.h>
 #include <rex/ui/vulkan/util.h>
 
 // Legacy backend compatibility aliases for shared readback controls.
+REXCVAR_DEFINE_BOOL(vulkan_readback_short_wait, false, "GPU/Vulkan",
+                    "Poll the final resolve fence briefly before the blocking wait");
+REXCVAR_DEFINE_UINT32(vulkan_readback_sync_budget_us, 0, "GPU/Vulkan",
+                     "'some' readback ranges read synchronously (readback_some_sync_*): wait at most this long "
+                     "for the GPU, then use the previous frame's copy instead (0 = always wait)");
+static void NoteReadbackBudget(bool fresh, double waited_us) {
+  // Diagnostics for the budgeted floor readback: how often the GPU was done in time.
+  static uint64_t fresh_count = 0, stale_count = 0;
+  static double max_us = 0;
+  static auto window = std::chrono::steady_clock::now();
+  (fresh ? fresh_count : stale_count) += 1;
+  max_us = std::max(max_us, waited_us);
+  if (std::chrono::steady_clock::now() - window >= std::chrono::seconds(5)) {
+    REXGPU_INFO("Readback sync budget: current_frame={} previous_frame={} max_wait_us={:.0f}", fresh_count,
+                stale_count, max_us);
+    fresh_count = stale_count = 0;
+    max_us = 0;
+    window = std::chrono::steady_clock::now();
+  }
+}
+// Fence wait limit for the current resolve wait (set only around a budgeted readback, command processor thread).
+static thread_local uint64_t g_resolve_wait_timeout_ns = UINT64_MAX;
+REXCVAR_DEFINE_UINT32(vulkan_readback_spin_us, 200, "GPU/Vulkan",
+                     "Maximum CPU polling time before the blocking full-readback wait");
+
+REXCVAR_DEFINE_BOOL(vulkan_log_sync_timing, false, "GPU/Vulkan",
+                    "Measure submission CPU time, fence waits and GPU execution without extra waits");
+
+REXCVAR_DEFINE_BOOL(vulkan_log_resolve_contents, false, "GPU/Vulkan",
+                    "Log bounded resolve content fingerprints for renderer comparisons.");
+
 REXCVAR_DEFINE_BOOL(vulkan_readback_resolve, false, "GPU/Vulkan",
                     "Read render-to-texture results on the CPU")
     .lifecycle(rex::cvar::Lifecycle::kHotReload);
@@ -896,6 +930,8 @@ bool VulkanCommandProcessor::SetupContext() {
     REXGPU_ERROR("Failed to initialize shared memory");
     return false;
   }
+  shared_memory_->SetInvalidationObserver(
+      [this](uint32_t start, uint32_t length) { OnGuestInvalidatedRange(start, length); });
 
   primitive_processor_ =
       std::make_unique<VulkanPrimitiveProcessor>(*register_file_, *memory_, *shared_memory_, *this);
@@ -2026,6 +2062,9 @@ void VulkanCommandProcessor::ShutdownContext() {
 
   primitive_processor_.reset();
 
+  if (shared_memory_) {
+    shared_memory_->SetInvalidationObserver(nullptr);
+  }
   shared_memory_.reset();
 
   ClearTransientDescriptorPools();
@@ -2059,10 +2098,16 @@ void VulkanCommandProcessor::ShutdownContext() {
 
   deferred_command_buffer_.Reset();
   for (const auto& command_buffer_pair : command_buffers_submitted_) {
+    if (command_buffer_pair.second.timing_queries != VK_NULL_HANDLE) {
+      dfn.vkDestroyQueryPool(device, command_buffer_pair.second.timing_queries, nullptr);
+    }
     dfn.vkDestroyCommandPool(device, command_buffer_pair.second.pool, nullptr);
   }
   command_buffers_submitted_.clear();
   for (const CommandBuffer& command_buffer : command_buffers_writable_) {
+    if (command_buffer.timing_queries != VK_NULL_HANDLE) {
+      dfn.vkDestroyQueryPool(device, command_buffer.timing_queries, nullptr);
+    }
     dfn.vkDestroyCommandPool(device, command_buffer.pool, nullptr);
   }
   command_buffers_writable_.clear();
@@ -3822,7 +3867,7 @@ bool VulkanCommandProcessor::IssueDraw(xenos::PrimitiveType prim_type, uint32_t
     uint64_t sampler_overflow_await_submission =
         texture_cache_->GetSubmissionToAwaitOnSamplerOverflow(samplers_overflowed_count);
     assert_true(sampler_overflow_await_submission <= GetCurrentSubmission());
-    CheckSubmissionFenceAndDeviceLoss(sampler_overflow_await_submission);
+    CheckSubmissionFenceAndDeviceLoss(sampler_overflow_await_submission, "resource_reuse");
   }
 
   uint32_t normalized_color_mask =
@@ -4154,6 +4199,8 @@ bool VulkanCommandProcessor::IssueDraw(xenos::PrimitiveType prim_type, uint32_t
                                               0, 0, 0);
   }
 
+  PROFILE_DRAW_CALL();
+  PROFILE_VERTICES(primitive_processing_result.host_draw_vertex_count);
   // Invalidate textures in memexported memory and watch for changes.
   if (!memexport_ranges_.empty()) {
     for (const draw_util::MemExportRange& memexport_range : memexport_ranges_) {
@@ -4222,7 +4269,7 @@ bool VulkanCommandProcessor::IssueDraw_MemexportReadbackFullPath(uint32_t total_
                           VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
                           VK_ACCESS_HOST_READ_BIT);
 
-  if (!AwaitAllQueueOperationsCompletion()) {
+  if (!AwaitAllQueueOperationsCompletion("memexport")) {
     REXGPU_ERROR("Failed to await completion of Vulkan memexport readback");
     dfn.vkDestroyBuffer(device, readback_buffer, nullptr);
     dfn.vkFreeMemory(device, readback_memory, nullptr);
@@ -4297,7 +4344,7 @@ bool VulkanCommandProcessor::IssueDraw_MemexportReadbackFastPath(uint32_t total_
     }
 
     if (readback.buffers[index] != VK_NULL_HANDLE || readback.memories[index] != VK_NULL_HANDLE) {
-      if (!AwaitAllQueueOperationsCompletion()) {
+      if (!AwaitAllQueueOperationsCompletion("resource_reuse")) {
         dfn.vkUnmapMemory(device, new_memory);
         dfn.vkDestroyBuffer(device, new_buffer, nullptr);
         dfn.vkFreeMemory(device, new_memory, nullptr);
@@ -4381,6 +4428,11 @@ bool VulkanCommandProcessor::IssueDraw_MemexportReadbackFastPath(uint32_t total_
   return true;
 }
 
+bool VulkanCommandProcessor::IsResolveReadbackEnabled() const {
+  return GetReadbackResolveMode(REXCVAR_GET(vulkan_readback_resolve)) !=
+         ReadbackResolveMode::kDisabled;
+}
+
 bool VulkanCommandProcessor::IssueCopy() {
 #if XE_GPU_FINE_GRAINED_DRAW_SCOPES
   SCOPE_profile_cpu_f("gpu");
@@ -4448,7 +4500,7 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
     }
 
     if (readback.buffers[index] != VK_NULL_HANDLE || readback.memories[index] != VK_NULL_HANDLE) {
-      if (!AwaitAllQueueOperationsCompletion()) {
+      if (!AwaitAllQueueOperationsCompletion("resource_reuse")) {
         dfn.vkUnmapMemory(device, new_memory);
         dfn.vkDestroyBuffer(device, new_buffer, nullptr);
         dfn.vkFreeMemory(device, new_memory, nullptr);
@@ -4476,6 +4528,10 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
   uint64_t resolve_key = MakeReadbackResolveKey(written_address, written_length);
   ReadbackBuffer& readback = readback_buffers_[resolve_key];
   readback.last_used_frame = frame_current_;
+  SomeDecision some_decision;
+  if (readback_mode == ReadbackResolveMode::kSome) {
+    some_decision = DecideSomeRefresh(resolve_key, written_address, written_length, frame_current_);
+  }
   uint32_t write_index = readback.current_index;
   uint32_t readback_size = AlignReadbackBufferSize(written_length);
   if (!ensure_readback_slot(readback, write_index, readback_size)) {
@@ -4515,7 +4571,20 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
     }
 
     VkBuffer scaled_resolve_buffer = texture_cache_->scaled_resolve_buffer();
-    if (scaled_resolve_buffer == VK_NULL_HANDLE || scaled_start > uint64_t(UINT32_MAX)) {
+    if (scaled_resolve_buffer == VK_NULL_HANDLE) {
+      return true;
+    }
+    // Bind only this resolve range. A 3x resolve buffer spans 4.5 GiB,
+    // exceeding both descriptor range limits and absolute shader byte offsets.
+    const uint64_t source_alignment =
+        std::max(uint64_t(1), uint64_t(vulkan_device->properties().minStorageBufferOffsetAlignment));
+    const uint64_t source_binding_offset = scaled_start - scaled_start % source_alignment;
+    const uint64_t source_relative_offset = scaled_start - source_binding_offset;
+    const uint64_t source_binding_range = source_relative_offset + scaled_length;
+    if (source_binding_range > vulkan_device->properties().maxStorageBufferRange ||
+        source_binding_range > uint64_t(UINT32_MAX)) {
+      REXGPU_ERROR("Vulkan resolve downscale range exceeds storage buffer limits: {} bytes",
+                   source_binding_range);
       return true;
     }
 
@@ -4533,7 +4602,7 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
       }
       if (resolve_downscale_buffer_ != VK_NULL_HANDLE ||
           resolve_downscale_buffer_memory_ != VK_NULL_HANDLE) {
-        if (!AwaitAllQueueOperationsCompletion()) {
+        if (!AwaitAllQueueOperationsCompletion("resource_reuse")) {
           dfn.vkDestroyBuffer(device, new_buffer, nullptr);
           dfn.vkFreeMemory(device, new_memory, nullptr);
           return true;
@@ -4561,8 +4630,8 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
 
     VkDescriptorBufferInfo buffer_infos[2] = {};
     buffer_infos[0].buffer = scaled_resolve_buffer;
-    buffer_infos[0].offset = 0;
-    buffer_infos[0].range = VK_WHOLE_SIZE;
+    buffer_infos[0].offset = source_binding_offset;
+    buffer_infos[0].range = source_binding_range;
     buffer_infos[1].buffer = resolve_downscale_buffer_;
     buffer_infos[1].offset = 0;
     buffer_infos[1].range = written_length;
@@ -4601,11 +4670,23 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
     constants.scale_y = texture_cache_->draw_resolution_scale_y();
     constants.pixel_size_log2 = pixel_size_log2;
     constants.tile_count = tile_count;
-    constants.source_offset_bytes = uint32_t(scaled_start);
+    constants.source_offset_bytes = uint32_t(source_relative_offset);
     constants.half_pixel_offset = (REXCVAR_GET(readback_resolve_half_pixel_offset) &&
                                    (constants.scale_x > 1 || constants.scale_y > 1))
                                       ? 1u
                                       : 0u;
+    // Color render-to-texture copies (player face portraits) are averaged; depth and other formats stay
+    // point-sampled, an average of their bits would be meaningless.
+    {
+      const auto copy_control = register_file_->Get<reg::RB_COPY_CONTROL>();
+      const auto dest_format = copy_dest_info.copy_dest_format;
+      constants.average = (REXCVAR_GET(readback_resolve_average_color) && pixel_size_log2 == 2 &&
+                           copy_control.copy_src_select != 4 &&
+                           (dest_format == xenos::ColorFormat::k_8_8_8_8 ||
+                            dest_format == xenos::ColorFormat::k_8_8_8_8_A))
+                              ? 1u
+                              : 0u;
+    }
     deferred_command_buffer_.CmdVkPushConstants(resolve_downscale_pipeline_layout_,
                                                 VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(constants),
                                                 &constants);
@@ -4649,27 +4730,89 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
                           VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT,
                           VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT);
 
+  // Attribute synchronous readback waits to the guest destination. These
+  // waits include preceding GPU work, not just the buffer transfer itself.
+  const bool measure_resolve_wait = REXCVAR_GET(vulkan_log_sync_timing);
+  const auto resolve_wait_start = std::chrono::steady_clock::now();
   bool use_delayed_sync =
       readback_mode == ReadbackResolveMode::kFast || readback_mode == ReadbackResolveMode::kSome;
   uint32_t read_index = write_index;
   if (use_delayed_sync) {
     read_index = 1 - write_index;
-  } else if (!AwaitAllQueueOperationsCompletion()) {
+  } else if (!AwaitAllQueueOperationsCompletion("resolve")) {
     return true;
   }
 
   bool is_cache_miss = false;
-  if (use_delayed_sync && (readback.buffers[read_index] == VK_NULL_HANDLE ||
-                           written_length > readback.sizes[read_index] ||
-                           readback.mapped_data[read_index] == nullptr)) {
+  // Same budget as D3D12: a forced-synchronous range waits at most the budget for the GPU, then uses last
+  // frame's copy (the full stall cost about a third of the frame rate).
+  const uint32_t sync_budget_us = REXCVAR_GET(vulkan_readback_sync_budget_us);
+  bool budget_decided = false;
+  if (use_delayed_sync && some_decision.sync && sync_budget_us &&
+      readback.buffers[read_index] != VK_NULL_HANDLE && written_length <= readback.sizes[read_index] &&
+      readback.mapped_data[read_index] != nullptr) {
+    const auto budget_start = std::chrono::steady_clock::now();
+    g_resolve_wait_timeout_ns = uint64_t(sync_budget_us) * 1000;
+    const bool completed = AwaitAllQueueOperationsCompletion("resolve");
+    g_resolve_wait_timeout_ns = UINT64_MAX;
+    if (device_lost_) {
+      return true;
+    }
+    if (completed) {
+      is_cache_miss = true;
+      read_index = write_index;
+    }
+    NoteReadbackBudget(completed, std::chrono::duration<double, std::micro>(
+                                      std::chrono::steady_clock::now() - budget_start).count());
+    budget_decided = true;
+  }
+  if (!budget_decided && use_delayed_sync &&
+      (some_decision.sync || readback.buffers[read_index] == VK_NULL_HANDLE ||
+       written_length > readback.sizes[read_index] || readback.mapped_data[read_index] == nullptr)) {
     is_cache_miss = true;
     read_index = write_index;
-    if (!AwaitAllQueueOperationsCompletion()) {
+    if (!AwaitAllQueueOperationsCompletion("resolve")) {
       return true;
     }
   }
 
-  bool should_copy = (readback_mode == ReadbackResolveMode::kSome) ? is_cache_miss : true;
+  if (measure_resolve_wait && (!use_delayed_sync || is_cache_miss)) {
+    struct ResolveWaitRange {
+      double milliseconds = 0;
+      uint64_t calls = 0;
+    };
+    static thread_local std::unordered_map<uint64_t, ResolveWaitRange> ranges;
+    static thread_local auto interval_start = std::chrono::steady_clock::now();
+    const auto now = std::chrono::steady_clock::now();
+    auto& range = ranges[MakeReadbackResolveKey(written_address, written_length)];
+    range.milliseconds +=
+        std::chrono::duration<double, std::milli>(now - resolve_wait_start).count();
+    ++range.calls;
+    if (now - interval_start >= std::chrono::seconds(5)) {
+      std::vector<std::pair<uint64_t, ResolveWaitRange>> hottest(ranges.begin(), ranges.end());
+      std::sort(hottest.begin(), hottest.end(), [](const auto& a, const auto& b) {
+        return a.second.milliseconds > b.second.milliseconds;
+      });
+      for (size_t i = 0; i < std::min<size_t>(8, hottest.size()); ++i) {
+        REXGPU_INFO("Vulkan resolve wait: key={:016X} calls={} wait={:.2f}ms",
+                    hottest[i].first, hottest[i].second.calls,
+                    hottest[i].second.milliseconds);
+      }
+      ranges.clear();
+      interval_start = now;
+    }
+  }
+
+  bool should_copy = (readback_mode == ReadbackResolveMode::kSome)
+                         ? (is_cache_miss || some_decision.refresh)
+                         : true;
+  if (readback_mode == ReadbackResolveMode::kSome) {
+    if (should_copy) {
+      NoteSomeRangeRefreshed(resolve_key);
+    } else {
+      NoteSomeRangeSkipped(resolve_key);
+    }
+  }
   if (should_copy && readback.buffers[read_index] != VK_NULL_HANDLE &&
       written_length <= readback.sizes[read_index] && readback.mapped_data[read_index] != nullptr) {
     VkMappedMemoryRange readback_memory_range = {};
@@ -4682,6 +4825,28 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
     uint8_t* destination = memory_->TranslatePhysical(written_address);
     if (destination) {
       std::memcpy(destination, readback.mapped_data[read_index], written_length);
+      // Inspect the completed readback, without adding submissions or GPU waits.
+      // This is diagnostic work, not suitable for performance measurements.
+      if (REXCVAR_GET(vulkan_log_resolve_contents)) {
+        static thread_local std::unordered_map<uint64_t, uint64_t> sampled_frames;
+        static thread_local uint32_t sample_count = 0;
+        const uint64_t key = MakeReadbackResolveKey(written_address, written_length);
+        auto found = sampled_frames.find(key);
+        if (sample_count < 4096 &&
+            (found == sampled_frames.end() || frame_current_ - found->second >= 60)) {
+          sampled_frames[key] = frame_current_;
+          ++sample_count;
+          uint64_t hash = 14695981039346656037ull;
+          uint32_t nonzero = 0;
+          for (uint32_t i = 0; i < written_length; ++i) {
+            hash = (hash ^ destination[i]) * 1099511628211ull;
+            nonzero += destination[i] != 0;
+          }
+          REXGPU_INFO("Vulkan resolve content: frame={} address={:08X} bytes={} "
+                      "nonzero={} hash={:016X}",
+                      frame_current_, written_address, written_length, nonzero, hash);
+        }
+      }
     }
   }
 
@@ -4886,7 +5051,7 @@ bool VulkanCommandProcessor::EndGuestOcclusionQuery(uint32_t sample_count_addres
   if (!EndSubmission(false)) {
     return false;
   }
-  if (!AwaitAllQueueOperationsCompletion()) {
+  if (!AwaitAllQueueOperationsCompletion("occlusion")) {
     return false;
   }
 
@@ -4943,7 +5108,8 @@ void VulkanCommandProcessor::WriteGuestOcclusionResult(uint32_t sample_count_add
   sample_counts->StencilFail_B = 0;
 }
 
-void VulkanCommandProcessor::CheckSubmissionFenceAndDeviceLoss(uint64_t await_submission) {
+void VulkanCommandProcessor::CheckSubmissionFenceAndDeviceLoss(uint64_t await_submission, const char* reason) {
+  const bool measure = REXCVAR_GET(vulkan_log_sync_timing);
   // Only report once, no need to retry a wait that won't succeed anyway.
   if (device_lost_) {
     return;
@@ -4951,7 +5117,12 @@ void VulkanCommandProcessor::CheckSubmissionFenceAndDeviceLoss(uint64_t await_su
 
   if (await_submission >= GetCurrentSubmission()) {
     if (submission_open_) {
+      const auto submit_started = std::chrono::steady_clock::now();
       EndSubmission(false);
+      if (measure) {
+        timing_submit_ms_ += std::chrono::duration<double, std::milli>(
+            std::chrono::steady_clock::now() - submit_started).count();
+      }
     }
     // A submission won't be ended if it hasn't been started, or if ending
     // has failed - clamp the index.
@@ -4965,17 +5136,43 @@ void VulkanCommandProcessor::CheckSubmissionFenceAndDeviceLoss(uint64_t await_su
   size_t fences_total = submissions_in_flight_fences_.size();
   size_t fences_awaited = 0;
   if (await_submission > submission_completed_) {
-    // Await in a blocking way if requested.
-    // TODO(Triang3l): Await only one fence. "Fence signal operations that are
-    // defined by vkQueueSubmit additionally include in the first
-    // synchronization scope all commands that occur earlier in submission
-    // order."
-    VkResult wait_result =
-        dfn.vkWaitForFences(device, uint32_t(await_submission - submission_completed_),
-                            submissions_in_flight_fences_.data(), VK_TRUE, UINT64_MAX);
+    // Every tracked submission is sent to graphics_compute queue 0. The final
+    // submission fence includes preceding submissions on that same queue.
+    const size_t await_count = size_t(await_submission - submission_completed_);
+    assert_true(await_count <= fences_total);
+    const VkFence target_fence = submissions_in_flight_fences_[await_count - 1];
+    const auto wait_started = std::chrono::steady_clock::now();
+    PROFILE_CMD_BUFFER_STALL();
+    VkResult wait_result;
+    {
+      using Timing = ui::vulkan::FenceWaitTiming;
+      Timing::Reason wait_reason = Timing::Reason::Other;
+      if (std::strcmp(reason, "resolve") == 0) wait_reason = Timing::Reason::Resolve;
+      else if (std::strcmp(reason, "resource_reuse") == 0) wait_reason = Timing::Reason::ResourceReuse;
+      else if (std::strcmp(reason, "memexport") == 0) wait_reason = Timing::Reason::Memexport;
+      else if (std::strcmp(reason, "frame_reuse") == 0) wait_reason = Timing::Reason::FrameReuse;
+      else if (std::strcmp(reason, "occlusion") == 0) wait_reason = Timing::Reason::Occlusion;
+      Timing timing("guest", this, wait_reason, await_submission - submission_completed_);
+      wait_result = dfn.vkGetFenceStatus(device, target_fence);
+      if (wait_result == VK_NOT_READY && wait_reason == Timing::Reason::Resolve &&
+          REXCVAR_GET(vulkan_readback_short_wait)) {
+        const auto deadline = std::chrono::steady_clock::now() +
+            std::chrono::microseconds(std::min(uint32_t(1000), REXCVAR_GET(vulkan_readback_spin_us)));
+        do {
+          wait_result = dfn.vkGetFenceStatus(device, target_fence);
+        } while (wait_result == VK_NOT_READY && std::chrono::steady_clock::now() < deadline);
+      }
+      if (wait_result == VK_NOT_READY) {
+        wait_result = dfn.vkWaitForFences(device, 1, &target_fence, VK_TRUE, g_resolve_wait_timeout_ns);
+      }
+    }
+    if (measure) {
+      timing_wait_ms_ += std::chrono::duration<double, std::milli>(
+          std::chrono::steady_clock::now() - wait_started).count();
+    }
     if (wait_result == VK_SUCCESS) {
       fences_awaited += await_submission - submission_completed_;
-    } else {
+    } else if (wait_result != VK_TIMEOUT) {  // VK_TIMEOUT: budgeted resolve wait, GPU not done yet
       REXGPU_ERROR("Failed to await submission completion Vulkan fences");
       if (wait_result == VK_ERROR_DEVICE_LOST) {
         device_lost_ = true;
@@ -5032,11 +5229,35 @@ void VulkanCommandProcessor::CheckSubmissionFenceAndDeviceLoss(uint64_t await_su
     if (command_buffer_pair.first > submission_completed_) {
       break;
     }
+    const auto& completed_buffer = command_buffer_pair.second;
+    if (completed_buffer.timing_pending) {
+      uint64_t timestamps[2];
+      if (dfn.vkGetQueryPoolResults(device, completed_buffer.timing_queries, 0, 2,
+              sizeof(timestamps), timestamps, sizeof(uint64_t), VK_QUERY_RESULT_64_BIT) == VK_SUCCESS) {
+        timing_gpu_ms_ += double((timestamps[1] - timestamps[0]) & timing_timestamp_mask_) *
+                          double(timing_timestamp_period_) / 1000000.0;
+        ++timing_samples_;
+      }
+    }
     command_buffers_writable_.push_back(command_buffer_pair.second);
     command_buffers_submitted_.pop_front();
   }
 
   shared_memory_->CompletedSubmissionUpdated();
+  if (measure) {
+    const double now_ms = std::chrono::duration<double, std::milli>(
+        std::chrono::steady_clock::now().time_since_epoch()).count();
+    if (!timing_interval_start_ms_) timing_interval_start_ms_ = now_ms;
+    if (now_ms - timing_interval_start_ms_ >= 5000.0) {
+      REXGPU_INFO("Vulkan timing: interval={:.2f}s submissions={} GPU={:.2f}ms "
+                  "submitCPU={:.2f}ms fenceWait={:.2f}ms",
+                  (now_ms - timing_interval_start_ms_) / 1000.0, timing_samples_,
+                  timing_gpu_ms_, timing_submit_ms_, timing_wait_ms_);
+      timing_interval_start_ms_ = now_ms;
+      timing_samples_ = 0;
+      timing_gpu_ms_ = timing_submit_ms_ = timing_wait_ms_ = 0;
+    }
+  }
 
   primitive_processor_->CompletedSubmissionUpdated();
 
@@ -5111,7 +5332,7 @@ bool VulkanCommandProcessor::BeginSubmission(bool is_guest_command) {
   // is still available, and whether the await was successful.
   uint64_t await_submission =
       is_opening_frame ? closed_frame_submissions_[frame_current_ % kMaxFramesInFlight] : 0;
-  CheckSubmissionFenceAndDeviceLoss(await_submission);
+  CheckSubmissionFenceAndDeviceLoss(await_submission, "frame_reuse");
   if (device_lost_ || submission_completed_ < await_submission) {
     return false;
   }
@@ -5284,6 +5505,9 @@ bool VulkanCommandProcessor::EndSubmission(bool is_swap) {
       if (dfn.vkAllocateCommandBuffers(device, &command_buffer_allocate_info,
                                        &command_buffer.buffer) != VK_SUCCESS) {
         REXGPU_ERROR("Failed to allocate a Vulkan command buffer");
+        if (command_buffer.timing_queries != VK_NULL_HANDLE) {
+          dfn.vkDestroyQueryPool(device, command_buffer.timing_queries, nullptr);
+        }
         dfn.vkDestroyCommandPool(device, command_buffer.pool, nullptr);
         return false;
       }
@@ -5372,6 +5596,32 @@ bool VulkanCommandProcessor::EndSubmission(bool is_swap) {
 
     assert_false(command_buffers_writable_.empty());
     CommandBuffer command_buffer = command_buffers_writable_.back();
+    command_buffer.timing_pending = false;
+    if (REXCVAR_GET(vulkan_log_sync_timing)) {
+      if (!timing_timestamp_period_) {
+        const auto& ifn = vulkan_device->vulkan_instance()->functions();
+        VkPhysicalDeviceProperties properties;
+        ifn.vkGetPhysicalDeviceProperties(vulkan_device->physical_device(), &properties);
+        uint32_t family_count = 0;
+        ifn.vkGetPhysicalDeviceQueueFamilyProperties(vulkan_device->physical_device(), &family_count, nullptr);
+        std::vector<VkQueueFamilyProperties> families(family_count);
+        ifn.vkGetPhysicalDeviceQueueFamilyProperties(vulkan_device->physical_device(), &family_count, families.data());
+        const uint32_t valid_bits = families[vulkan_device->queue_family_graphics_compute()].timestampValidBits;
+        timing_timestamp_period_ = properties.limits.timestampPeriod;
+        timing_timestamp_mask_ = valid_bits >= 64 ? UINT64_MAX : ((uint64_t(1) << valid_bits) - 1);
+      }
+      if (timing_timestamp_mask_ && command_buffer.timing_queries == VK_NULL_HANDLE) {
+        VkQueryPoolCreateInfo query_info = {};
+        query_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
+        query_info.queryType = VK_QUERY_TYPE_TIMESTAMP;
+        query_info.queryCount = 2;
+        if (dfn.vkCreateQueryPool(device, &query_info, nullptr, &command_buffer.timing_queries) != VK_SUCCESS) {
+          command_buffer.timing_queries = VK_NULL_HANDLE;
+        }
+        command_buffers_writable_.back().timing_queries = command_buffer.timing_queries;
+      }
+      command_buffer.timing_pending = command_buffer.timing_queries != VK_NULL_HANDLE;
+    }
     if (dfn.vkResetCommandPool(device, command_buffer.pool, 0) != VK_SUCCESS) {
       REXGPU_ERROR("Failed to reset a Vulkan command pool");
       return false;
@@ -5385,7 +5635,14 @@ bool VulkanCommandProcessor::EndSubmission(bool is_swap) {
       REXGPU_ERROR("Failed to begin a Vulkan command buffer");
       return false;
     }
+    if (command_buffer.timing_pending) {
+      dfn.vkCmdResetQueryPool(command_buffer.buffer, command_buffer.timing_queries, 0, 2);
+      dfn.vkCmdWriteTimestamp(command_buffer.buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, command_buffer.timing_queries, 0);
+    }
     deferred_command_buffer_.Execute(command_buffer.buffer);
+    if (command_buffer.timing_pending) {
+      dfn.vkCmdWriteTimestamp(command_buffer.buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, command_buffer.timing_queries, 1);
+    }
     if (dfn.vkEndCommandBuffer(command_buffer.buffer) != VK_SUCCESS) {
       REXGPU_ERROR("Failed to end a Vulkan command buffer");
       return false;
@@ -5452,7 +5709,7 @@ bool VulkanCommandProcessor::EndSubmission(bool is_swap) {
     // Submission already closed now, so minus 1.
     closed_frame_submissions_[(frame_current_++) % kMaxFramesInFlight] = GetCurrentSubmission() - 1;
 
-    if (cache_clear_requested_ && AwaitAllQueueOperationsCompletion()) {
+    if (cache_clear_requested_ && AwaitAllQueueOperationsCompletion("resource_reuse")) {
       cache_clear_requested_ = false;
 
       DestroyScratchBuffer();
@@ -5464,6 +5721,9 @@ bool VulkanCommandProcessor::EndSubmission(bool is_swap) {
 
       assert_true(command_buffers_submitted_.empty());
       for (const CommandBuffer& command_buffer : command_buffers_writable_) {
+        if (command_buffer.timing_queries != VK_NULL_HANDLE) {
+          dfn.vkDestroyQueryPool(device, command_buffer.timing_queries, nullptr);
+        }
         dfn.vkDestroyCommandPool(device, command_buffer.pool, nullptr);
       }
       command_buffers_writable_.clear();
diff --git a/src/graphics/vulkan/render_target_cache.cpp b/src/graphics/vulkan/render_target_cache.cpp
index 0298f06..cd25e98 100644
--- a/src/graphics/vulkan/render_target_cache.cpp
+++ b/src/graphics/vulkan/render_target_cache.cpp
@@ -41,6 +41,9 @@ REXCVAR_DEFINE_STRING(render_target_path_vulkan, "", "GPU/Vulkan",
                       "Vulkan render target implementation path")
     .lifecycle(rex::cvar::Lifecycle::kInitOnly);
 
+REXCVAR_DEFINE_BOOL(vulkan_log_render_targets, false, "GPU/Vulkan",
+                    "Log up to 64 distinct host render-target format and write-mask combinations");
+
 // DEFINE_string(
 //     render_target_path_vulkan, "",
 //     "Render target emulation path to use on Vulkan.\n"
@@ -1164,7 +1167,8 @@ bool VulkanRenderTargetCache::Resolve(const memory::Memory& memory,
           draw_util::resolve_copy_shader_info[size_t(copy_shader)];
       bool direct_resolved = false;
       if (GetPath() == Path::kHostRenderTargets) {
-        if (REXCVAR_GET(direct_host_resolve)) {
+        if (REXCVAR_GET(direct_host_resolve) &&
+            !command_processor_.IsResolveReadbackEnabled()) {
           direct_resolved =
               TryResolveCopyDirectly(resolve_info, copy_shader, draw_resolution_scaled);
           if (direct_resolved) {
@@ -1185,6 +1189,30 @@ bool VulkanRenderTargetCache::Resolve(const memory::Memory& memory,
             REXGPU_ERROR("VulkanRenderTargetCache: Failed to dump host render targets for resolve");
             return false;
           }
+          // Focus ownership diagnostics on the ranges that differed between
+          // the FIFA Street FBO and FSI captures. Never change ownership here.
+          if (REXCVAR_GET(vulkan_log_render_targets) &&
+              (resolve_info.copy_dest_extent_start == 0x12493000 ||
+               resolve_info.copy_dest_extent_start == 0x12BC3000)) {
+            static thread_local uint32_t diagnostic_calls = 0;
+            static thread_local uint32_t diagnostic_samples = 0;
+            if (diagnostic_samples < 128 && (diagnostic_calls++ % 60) == 0) {
+              ++diagnostic_samples;
+              REXGPU_INFO("Vulkan resolve ownership: address={:08X} bytes={} "
+                          "depth={} base={} row_tiles={} rows={} pitch={} owners={}",
+                          resolve_info.copy_dest_extent_start,
+                          resolve_info.copy_dest_extent_length,
+                          resolve_info.IsCopyingDepth(), dump_base, dump_row_length_used,
+                          dump_rows, dump_pitch, dump_rectangles_.size());
+              for (const ResolveCopyDumpRectangle& rectangle : dump_rectangles_) {
+                const auto owner = rectangle.render_target->key();
+                REXGPU_INFO("Vulkan resolve owner: base={} pitch={} depth={} "
+                            "format={} msaa={}", owner.base_tiles, owner.GetPitchTiles(),
+                            uint32_t(owner.is_depth), uint32_t(owner.resource_format),
+                            uint32_t(owner.msaa_samples));
+              }
+            }
+          }
         }
       }
 
@@ -1425,6 +1453,26 @@ bool VulkanRenderTargetCache::Update(bool is_rasterization_done,
             depth_and_color_render_targets[4]->key().GetColorFormat();
       }
 
+      if (REXCVAR_GET(vulkan_log_render_targets)) {
+        // Bounded diagnostics: do not log every draw or retain unbounded state.
+        static thread_local std::vector<std::array<uint32_t, 8>> combinations;
+        const std::array<uint32_t, 8> combination = {
+            uint32_t(render_pass_key.depth_and_color_used),
+            uint32_t(render_pass_key.depth_format),
+            uint32_t(render_pass_key.color_0_view_format),
+            uint32_t(render_pass_key.color_1_view_format),
+            uint32_t(render_pass_key.color_2_view_format),
+            uint32_t(render_pass_key.color_3_view_format),
+            uint32_t(render_pass_key.msaa_samples), normalized_color_mask};
+        if (combinations.size() < 64 &&
+            std::find(combinations.begin(), combinations.end(), combination) == combinations.end()) {
+          combinations.push_back(combination);
+          REXGPU_INFO("Vulkan FBO targets: used={:02X} depth={} colors={}/{}/{}/{} samples={} writeMask={:04X}",
+                      combination[0], combination[1], combination[2], combination[3],
+                      combination[4], combination[5], combination[6], combination[7]);
+        }
+      }
+
       const Framebuffer* framebuffer = last_update_framebuffer_;
       VkRenderPass render_pass = last_update_render_pass_key_ == render_pass_key
                                      ? last_update_render_pass_
diff --git a/src/graphics/vulkan/texture_cache.cpp b/src/graphics/vulkan/texture_cache.cpp
index ecbd940..11751c9 100644
--- a/src/graphics/vulkan/texture_cache.cpp
+++ b/src/graphics/vulkan/texture_cache.cpp
@@ -1952,12 +1952,31 @@ VkImageView VulkanTextureCache::VulkanTexture::GetOrCreate3DAs2DImageView(bool i
 
   VkImageView& cached_view =
       is_signed ? image_view_3d_as_2d_signed_ : image_view_3d_as_2d_unsigned_;
+  VulkanTextureCache& vulkan_texture_cache = static_cast<VulkanTextureCache&>(texture_cache());
   if (cached_view != VK_NULL_HANDLE) {
+    // This copy has its own memory watch. Reusing the view must not bypass
+    // invalidation of its contents after CPU or GPU writes to guest memory.
+    if (!texture_3d_as_2d_ || !vulkan_texture_cache.LoadTextureData(*texture_3d_as_2d_)) {
+      return VK_NULL_HANDLE;
+    }
+    texture_3d_as_2d_->MarkAsUsed();
+    const Usage old_usage = texture_3d_as_2d_->SetUsage(Usage::kGuestShaderSampled);
+    if (old_usage != Usage::kGuestShaderSampled) {
+      VkPipelineStageFlags src_stages;
+      VkAccessFlags src_access;
+      VkImageLayout old_layout;
+      vulkan_texture_cache.GetTextureUsageMasks(old_usage, src_stages, src_access, old_layout);
+      if (!vulkan_texture_cache.command_processor_.PushImageMemoryBarrier(
+              texture_3d_as_2d_->image(), ui::vulkan::util::InitializeSubresourceRange(),
+              src_stages, vulkan_texture_cache.guest_shader_pipeline_stages_,
+              src_access, VK_ACCESS_SHADER_READ_BIT, old_layout,
+              VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)) {
+        return VK_NULL_HANDLE;
+      }
+    }
     return cached_view;
   }
 
-  VulkanTextureCache& vulkan_texture_cache = static_cast<VulkanTextureCache&>(texture_cache());
-
   if (!texture_3d_as_2d_) {
     const HostFormatPair& host_format_pair = vulkan_texture_cache.GetHostFormatPair(key());
     VkFormat wrapper_format = host_format_pair.format_unsigned.format;
diff --git a/src/input/input_system.cpp b/src/input/input_system.cpp
index 813bb1c..7867984 100644
--- a/src/input/input_system.cpp
+++ b/src/input/input_system.cpp
@@ -10,11 +10,13 @@
  */
 
 #include <algorithm>
+#include <atomic>
 #include <cmath>
 
 #include <rex/dbg.h>
 #include <rex/input/device_assignment.h>
 #include <rex/input/flags.h>
+#include <rex/input/guide_capture.h>
 #include <rex/input/input_driver.h>
 #include <rex/input/input_system.h>
 #include <rex/input/mnk/mnk_input_driver.h>
@@ -48,6 +50,7 @@ X_STATUS InputSystem::Setup() {
 }
 
 void InputSystem::Shutdown() {
+  std::lock_guard lock(devices_mutex_);
   // device_owners_ holds raw driver pointers.
   devices_.clear();
   device_owners_.clear();
@@ -187,6 +190,7 @@ const DeviceInfo* InputSystem::DeviceInfoFor(DeviceId id) const {
 X_RESULT InputSystem::GetCapabilities(uint32_t user_index, uint32_t flags,
                                       X_INPUT_CAPABILITIES* out_caps) {
   SCOPE_profile_cpu_f("hid");
+  std::lock_guard lock(devices_mutex_);
   if (!out_caps || !assignment_) {
     return X_ERROR_DEVICE_NOT_CONNECTED;
   }
@@ -212,8 +216,23 @@ X_RESULT InputSystem::GetCapabilities(uint32_t user_index, uint32_t flags,
   return driver->GetDeviceCapabilities(chosen, flags, out_caps);
 }
 
+namespace {
+std::atomic<bool> g_guide_capture{false};
+std::atomic<uint32_t> g_guide_presses{0};
+uint16_t g_guide_prev_buttons = 0;
+std::atomic<bool> g_back_watch{false};
+std::atomic<bool> g_back_pressed{false};
+}  // namespace
+
+void SetGuideCapture(bool capture) { g_guide_capture.store(capture); }
+bool GuideCaptureActive() { return g_guide_capture.load(); }
+uint32_t TakeGuidePresses() { return g_guide_presses.exchange(0); }
+void SetBackWatch(bool watch) { g_back_watch.store(watch); }
+bool TakeBackPress() { return g_back_pressed.exchange(false); }
+
 X_RESULT InputSystem::GetState(uint32_t user_index, X_INPUT_STATE* out_state) {
   SCOPE_profile_cpu_f("hid");
+  std::lock_guard lock(devices_mutex_);
   if (!assignment_) {
     return X_ERROR_DEVICE_NOT_CONNECTED;
   }
@@ -245,6 +264,27 @@ X_RESULT InputSystem::GetState(uint32_t user_index, X_INPUT_STATE* out_state) {
   if (!any) {
     return X_ERROR_DEVICE_NOT_CONNECTED;
   }
+  if (user_index == 0) {
+    const uint16_t buttons = static_cast<uint16_t>(merged.gamepad.buttons);
+    // Exit chord: START + B (Xbox layout) / START + Circle (PlayStation layout, same SDL button).
+    constexpr uint16_t kExitChord = 0x0010 | 0x2000;
+    if (g_back_watch.load() && (buttons & kExitChord) == kExitChord &&
+        (g_guide_prev_buttons & kExitChord) != kExitChord) {
+      g_back_pressed.store(true);
+    }
+    if (g_guide_capture.load()) {
+      // The dialog owns the pad: hand it the new presses, give the title a neutral pad.
+      g_guide_presses.fetch_or(static_cast<uint32_t>(buttons & ~g_guide_prev_buttons));
+      g_guide_prev_buttons = buttons;
+      merged.gamepad.buttons = 0;
+      merged.gamepad.left_trigger = 0;
+      merged.gamepad.right_trigger = 0;
+      merged.gamepad.thumb_lx = merged.gamepad.thumb_ly = 0;
+      merged.gamepad.thumb_rx = merged.gamepad.thumb_ry = 0;
+    } else {
+      g_guide_prev_buttons = buttons;  // a button held while opening is not a press
+    }
+  }
   if (out_state) {
     *out_state = merged;
   }
@@ -253,6 +293,7 @@ X_RESULT InputSystem::GetState(uint32_t user_index, X_INPUT_STATE* out_state) {
 
 X_RESULT InputSystem::SetState(uint32_t user_index, X_INPUT_VIBRATION* vibration) {
   SCOPE_profile_cpu_f("hid");
+  std::lock_guard lock(devices_mutex_);
   if (!assignment_) {
     return X_ERROR_DEVICE_NOT_CONNECTED;
   }
@@ -295,10 +336,15 @@ X_RESULT InputSystem::SetState(uint32_t user_index, X_INPUT_VIBRATION* vibration
 X_RESULT InputSystem::GetKeystroke(uint32_t user_index, uint32_t flags,
                                    X_INPUT_KEYSTROKE* out_keystroke) {
   SCOPE_profile_cpu_f("hid");
+  std::lock_guard lock(devices_mutex_);
   if (!assignment_) {
     return X_ERROR_DEVICE_NOT_CONNECTED;
   }
 
+  if (user_index == 0 && g_guide_capture.load()) {
+    return X_ERROR_EMPTY;  // the exit dialog owns the pad
+  }
+
   RefreshDevices();
   std::vector<DeviceId> ids;
   assignment_->DevicesForUser(user_index, ids);
diff --git a/src/input/sdl/sdl_input_driver.cpp b/src/input/sdl/sdl_input_driver.cpp
index c7c440d..d998314 100644
--- a/src/input/sdl/sdl_input_driver.cpp
+++ b/src/input/sdl/sdl_input_driver.cpp
@@ -10,6 +10,7 @@
  */
 
 #include <array>
+#include <cstdlib>
 #include <filesystem>
 
 #include <rex/assert.h>
@@ -27,6 +28,8 @@ namespace rex::input::sdl {
 
 namespace {
 
+int g_fifastreet_controller_ordinal = 0;
+
 // SDL clamps to SDL_MAX_RUMBLE_DURATION_MS, which is not a public constant.
 constexpr uint32_t kRumbleDurationMs = 0xFFFF;
 
@@ -460,6 +463,16 @@ void SDLInputDriver::OnControllerDeviceAddedLocked(const SDL_Event& event) {
   // SDL_GetGamepadPlayerIndex is deliberately ignored: on Windows it reports
   // the XInput user index the OS assigned, which is unrelated to connection
   // order and leaves non-XInput pads unnumbered.
+  const int detected_ordinal = g_fifastreet_controller_ordinal++;
+  const char* forced_slot = std::getenv("FIFASTREET_XINPUT_SLOT");
+  if (forced_slot && *forced_slot) {
+    const int wanted = std::atoi(forced_slot);
+    if (wanted >= 0 && detected_ordinal != wanted) {
+      SDL_CloseGamepad(controller);
+      return;
+    }
+  }
+
   ControllerState state = {};
   state.sdl = controller;
   state.id = AllocateDeviceId();
diff --git a/src/input/xinput/xinput_input_driver.cpp b/src/input/xinput/xinput_input_driver.cpp
index a6a1da9..c5b318e 100644
--- a/src/input/xinput/xinput_input_driver.cpp
+++ b/src/input/xinput/xinput_input_driver.cpp
@@ -12,6 +12,7 @@
 #include <array>
 #include <filesystem>
 
+#include <cstdlib>
 #include <rex/assert.h>
 #include <rex/chrono/clock.h>
 #include <rex/cvar.h>
@@ -36,7 +37,18 @@ bool SlotForDevice(rex::input::DeviceId id, uint32_t* out_slot) {
   if ((raw & ~0xFFull) != 0x58490000ull || (raw & 0xFF) >= kXinputSlotCount) {
     return false;
   }
-  *out_slot = static_cast<uint32_t>(raw & 0xFF);
+
+  const uint32_t slot = static_cast<uint32_t>(raw & 0xFF);
+  const char* forced_slot = std::getenv("FIFASTREET_XINPUT_SLOT");
+  if (forced_slot && *forced_slot) {
+    const int wanted = std::atoi(forced_slot);
+    if (wanted < 0 || wanted >= static_cast<int>(kXinputSlotCount) ||
+        slot != static_cast<uint32_t>(wanted)) {
+      return false;
+    }
+  }
+
+  *out_slot = slot;
   return true;
 }
 
diff --git a/src/kernel/CMakeLists.txt b/src/kernel/CMakeLists.txt
index 984b97d..33688e4 100644
--- a/src/kernel/CMakeLists.txt
+++ b/src/kernel/CMakeLists.txt
@@ -3,6 +3,7 @@ set(REXKERNEL_SOURCES
 
     # XAM subsystem - provides __imp__Xam* symbols
     xam/xam_module.cpp
+    xam/exit_overlay.cpp
     xam/xam_avatar.cpp
     xam/xam_content.cpp
     xam/xam_content_aggregate.cpp
diff --git a/src/kernel/xam/apps/xlivebase_app.cpp b/src/kernel/xam/apps/xlivebase_app.cpp
index 3593403..42597d2 100644
--- a/src/kernel/xam/apps/xlivebase_app.cpp
+++ b/src/kernel/xam/apps/xlivebase_app.cpp
@@ -30,6 +30,19 @@ X_HRESULT XLiveBaseApp::DispatchMessageSync(uint32_t message, uint32_t buffer_pt
   // NOTE: buffer_length may be zero or valid.
   auto buffer = memory_->TranslateVirtual(buffer_ptr);
   switch (message) {
+    case 0x0005000C: {
+      // FIFA Street: allow the Online Hub XLIVEBASE request.
+      REXKRNL_INFO(
+          "[ONLINE] XLiveBaseFifaStreet5000C accepted buffer={:08X} length={:08X}",
+          buffer_ptr, buffer_length);
+      return X_E_SUCCESS;
+    }
+
+    case 0x00050010: {
+      // FIFA Street online: accept this XLIVEBASE request for now.
+      REXKRNL_DEBUG("XLiveBaseFifaStreet50010({:08X}, {:08X})", buffer_ptr, buffer_length);
+      return X_E_SUCCESS;
+    }
     case 0x00058004: {
       // Called on startup, seems to just return a bool in the buffer.
       assert_true(!buffer_length || buffer_length == 4);
diff --git a/src/kernel/xam/exit_overlay.cpp b/src/kernel/xam/exit_overlay.cpp
new file mode 100644
index 0000000..ebb9121
--- /dev/null
+++ b/src/kernel/xam/exit_overlay.cpp
@@ -0,0 +1,174 @@
+/**
+ * Exit shortcut: START + B (Xbox layout) / START + Circle (PlayStation layout) on any screen
+ * opens an "exit the game?" confirmation drawn in the game's own style; A confirms, B cancels.
+ */
+#include <atomic>
+#include <chrono>
+#include <memory>
+#include <string>
+#include <thread>
+
+#include <imgui.h>
+#include <spdlog/spdlog.h>
+#if defined(_WIN32)
+#include <windows.h>
+#endif
+
+#include <rex/input/guide_capture.h>
+#include <rex/logging.h>
+#include <rex/runtime.h>
+#include <rex/system/kernel_state.h>
+#include <rex/ui/guide_font.h>
+#include <rex/ui/imgui_dialog.h>
+#include <rex/ui/imgui_drawer.h>
+#include <rex/ui/windowed_app_context.h>
+
+namespace rex::kernel::xam {
+uint32_t XGetLanguage_entry();  // xam_info.cpp: the game's current language (XLanguage)
+}
+
+namespace rex {
+namespace kernel {
+namespace xam {
+namespace {
+
+enum class Str { kExitConfirm, kYes, kNo };
+
+// Texts per game language (XLanguage: 1 EN, 3 DE, 4 FR, 5 ES, 6 IT, 9 PT). Others use English.
+std::string Tr(Str id) {
+  struct Row { const char* en; const char* de; const char* fr; const char* es; const char* it; const char* pt; };
+  static const Row kRows[] = {
+      /*kExitConfirm*/ {"EXIT THE GAME?", "SPIEL BEENDEN?", "QUITTER LE JEU ?", "\xC2\xBFSALIR DEL JUEGO?",
+                        "USCIRE DAL GIOCO?", "SAIR DO JOGO?"},
+      /*kYes*/ {"YES", "JA", "OUI", "SI", "SI", "SIM"},
+      /*kNo*/ {"NO", "NEIN", "NON", "NO", "NO", "NAO"},
+  };
+  const Row& row = kRows[static_cast<size_t>(id)];
+  switch (XGetLanguage_entry()) {
+    case 3: return row.de;
+    case 4: return row.fr;
+    case 5: return row.es;
+    case 6: return row.it;
+    case 9: return row.pt;
+    default: return row.en;
+  }
+}
+
+// The game's look: slanted black bars, yellow highlight, heavy condensed caps.
+struct Style {
+  ImDrawList* dl;
+  ImFont* font;
+  float s;  // layout scale (display height / 720)
+
+  void Slant(float x, float y, float w, float h, ImU32 color, float skew = 14.0f) const {
+    const float k = skew * s;
+    ImVec2 pts[4] = {ImVec2(x + k, y), ImVec2(x + w + k, y), ImVec2(x + w, y + h), ImVec2(x, y + h)};
+    dl->AddConvexPolyFilled(pts, 4, color);
+  }
+  void Text(float x, float y, float size, ImU32 color, const std::string& text) const {
+    dl->AddText(font, size * s, ImVec2(x, y), color, text.c_str());
+  }
+  float TextWidth(float size, const std::string& text) const {
+    return font->CalcTextSizeA(size * s, 3.4e38f, 0.0f, text.c_str()).x;
+  }
+  // Round button glyph like the footer hints of the game: (A) text.
+  void Hint(float& x, float y, const char* letter, const char* label, ImU32 ring) const {
+    const float r = 15.0f * s;
+    dl->AddCircle(ImVec2(x + r, y + r), r, ring, 24, 2.5f * s);
+    const float lw = TextWidth(22, letter);
+    Text(x + r - lw * 0.5f, y + r - 11.0f * s, 22, ring, letter);
+    x += 2 * r + 10.0f * s;
+    Text(x, y + 1.0f * s, 24, IM_COL32(255, 255, 255, 255), label);
+    x += TextWidth(24, label) + 34.0f * s;
+  }
+};
+
+std::atomic_bool g_confirm{false};
+
+void DrawExit(float width, float height) {
+  constexpr uint32_t kA = 0x1000, kB = 0x2000;
+  // The chord is recorded by the input system while watching.
+  rex::input::SetBackWatch(!g_confirm.load());
+  if (!g_confirm.load() && rex::input::TakeBackPress()) g_confirm = true;
+
+  const bool confirm = g_confirm.load();
+  if (confirm != rex::input::GuideCaptureActive()) {
+    rex::input::SetGuideCapture(confirm);
+    if (confirm) rex::input::TakeGuidePresses();  // drop presses from before it opened
+  }
+  if (!confirm) return;
+  const uint32_t presses = rex::input::TakeGuidePresses();
+
+  ImFont* font = rex::ui::g_guide_font ? rex::ui::g_guide_font : ImGui::GetFont();
+  const float s = height / 720.0f;
+
+  ImGui::SetNextWindowPos(ImVec2(0, 0));
+  ImGui::SetNextWindowSize(ImVec2(width, height));
+  ImGui::SetNextWindowBgAlpha(0.0f);
+  ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
+  ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
+  const ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoNav |
+                                 ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
+                                 ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoBackground |
+                                 ImGuiWindowFlags_NoBringToFrontOnFocus;
+  if (ImGui::Begin("##exit_canvas", nullptr, flags)) {
+    Style g{ImGui::GetWindowDrawList(), font, s};
+    const float w = 560 * s, h = 132 * s, x = (width - w) * 0.5f, y = height * 0.5f - h * 0.5f;
+    g.dl->AddRectFilled(ImVec2(0, 0), ImVec2(width, height), IM_COL32(0, 0, 0, 150));
+    g.Slant(x - 6 * s, y - 6 * s, w + 12 * s, h + 12 * s, IM_COL32(244, 196, 12, 255));
+    g.Slant(x, y, w, h, IM_COL32(12, 12, 14, 240));
+    g.Text(x + 34 * s, y + 26 * s, 46, IM_COL32(255, 255, 255, 255), Tr(Str::kExitConfirm));
+    float hx = x + 34 * s;
+    g.Hint(hx, y + h - 46 * s, "A", Tr(Str::kYes).c_str(), IM_COL32(244, 196, 12, 255));
+    g.Hint(hx, y + h - 46 * s, "B", Tr(Str::kNo).c_str(), IM_COL32(255, 255, 255, 255));
+    if (presses & kA) {
+      REXKRNL_INFO("[EXIT] closing the game (START + B)");
+      g_confirm = false;
+      rex::input::SetGuideCapture(false);
+      if (auto logger = spdlog::default_logger()) logger->flush();
+#if defined(_WIN32)
+      TerminateProcess(GetCurrentProcess(), 0);  // clean exit code, no crash dialog
+#else
+      std::_Exit(0);
+#endif
+    } else if (presses & kB) {
+      g_confirm = false;
+    }
+  }
+  ImGui::End();
+  ImGui::PopStyleVar(2);
+}
+
+class ExitOverlayDialog : public rex::ui::ImGuiDialog {
+ public:
+  explicit ExitOverlayDialog(rex::ui::ImGuiDrawer* drawer) : rex::ui::ImGuiDialog(drawer) {}
+  void OnDraw(ImGuiIO& io) override { DrawExit(io.DisplaySize.x, io.DisplaySize.y); }
+};
+
+std::unique_ptr<ExitOverlayDialog> g_overlay;
+
+}  // namespace
+
+// Creates the overlay once the emulator's ImGui drawer exists.
+void StartExitOverlay() {
+  static std::atomic_bool started{false};
+  if (started.exchange(true)) return;
+  std::thread([]() {
+    for (;;) {
+      auto* state = REX_KERNEL_STATE();
+      const Runtime* emulator = state ? state->emulator() : nullptr;
+      rex::ui::ImGuiDrawer* drawer = emulator ? emulator->imgui_drawer() : nullptr;
+      rex::ui::WindowedAppContext* context = emulator ? emulator->app_context() : nullptr;
+      if (drawer && context) {
+        context->CallInUIThreadSynchronous([drawer]() { g_overlay = std::make_unique<ExitOverlayDialog>(drawer); });
+        REXKRNL_INFO("[EXIT] exit shortcut ready");
+        return;
+      }
+      std::this_thread::sleep_for(std::chrono::milliseconds(500));
+    }
+  }).detach();
+}
+
+}  // namespace xam
+}  // namespace kernel
+}  // namespace rex
diff --git a/src/kernel/xam/xam_info.cpp b/src/kernel/xam/xam_info.cpp
index 1fda053..fcdf567 100644
--- a/src/kernel/xam/xam_info.cpp
+++ b/src/kernel/xam/xam_info.cpp
@@ -16,6 +16,7 @@
 #include <rex/types.h>
 #include <rex/string.h>
 #include <rex/system/kernel_state.h>
+#include <rex/system/flags.h>
 #include <rex/system/user_module.h>
 #include <rex/system/xenumerator.h>
 #include <rex/system/xthread.h>
@@ -183,19 +184,12 @@ u32 XGetGameRegion_entry() {
 }
 
 u32 XGetLanguage_entry() {
-  auto desired_language = XLanguage::kEnglish;
-
-  // Switch the language based on game region.
-  // TODO(benvanik): pull from xex header.
-  uint32_t game_region = XEX_REGION_NTSCU;
-  if (game_region & XEX_REGION_NTSCU) {
-    desired_language = XLanguage::kEnglish;
-  } else if (game_region & XEX_REGION_NTSCJ) {
-    desired_language = XLanguage::kJapanese;
+  const uint32_t language = REXCVAR_GET(user_language);
+  if (language > static_cast<uint32_t>(XLanguage::kInvalid) &&
+      language < static_cast<uint32_t>(XLanguage::kMaxLanguages)) {
+    return language;
   }
-  // Add more overrides?
-
-  return uint32_t(desired_language);
+  return static_cast<uint32_t>(XLanguage::kEnglish);
 }
 
 u32 XamGetCurrentTitleId_entry() {
@@ -268,7 +262,7 @@ void XamLoaderLaunchTitle_entry(mapped_string raw_name_ptr, u32 flags) {
 
   // Translate the launch path to a full path.
   if (raw_name_ptr) {
-    auto path = raw_name_ptr.value();
+    std::string path(raw_name_ptr.value());
     if (path.empty()) {
       loader_data.launch_path = "game:\\default.xex";
     } else {
@@ -293,8 +287,13 @@ void XamLoaderTerminateTitle_entry() {
   REX_KERNEL_STATE()->TerminateTitle();
 }
 
-u32 XamAlloc_entry(u32 unk, u32 size, mapped_u32 out_ptr) {
-  assert_true(unk == 0);
+u32 XamAlloc_entry(u32 heap_flags, u32 size, mapped_u32 out_ptr) {
+  // Titles also request non-default XAM heaps. All XAM heaps share the
+  // runtime's system allocator and are released through XamFree.
+  if (!out_ptr) {
+    return X_ERROR_INVALID_PARAMETER;
+  }
+  REXKRNL_DEBUG("XamAlloc(heap_flags={:08X}, size={})", heap_flags, size);
 
   // Allocate from the heap. Not sure why XAM does this specially, perhaps
   // it keeps stuff in a separate heap?
diff --git a/src/kernel/xam/xam_module.cpp b/src/kernel/xam/xam_module.cpp
index 6bad7c7..7f1d311 100644
--- a/src/kernel/xam/xam_module.cpp
+++ b/src/kernel/xam/xam_module.cpp
@@ -23,6 +23,8 @@ namespace xam {
 using namespace rex::system;
 using namespace rex::system::xam;
 
+void StartExitOverlay();  // exit_overlay.cpp
+
 std::atomic<int> xam_dialogs_shown_ = {0};
 
 bool xeXamIsUIActive() {
@@ -31,6 +33,7 @@ bool xeXamIsUIActive() {
 
 XamModule::XamModule(Runtime* emulator, KernelState* kernel_state)
     : KernelModule(kernel_state, "xe:\\xam.xex"), loader_data_() {
+  StartExitOverlay();
   RegisterExportTable(export_resolver_);
 
   // Register all exported functions.
diff --git a/src/kernel/xam/xam_net.cpp b/src/kernel/xam/xam_net.cpp
index 58e36a4..3cbb652 100644
--- a/src/kernel/xam/xam_net.cpp
+++ b/src/kernel/xam/xam_net.cpp
@@ -355,17 +355,27 @@ u32 NetDll_WSASendTo_entry(u32 caller, u32 socket_handle, ppc_ptr_t<XWSABUF> buf
 
 u32 NetDll_WSAWaitForMultipleEvents_entry(u32 num_events, mapped_u32 events, u32 wait_all,
                                           u32 timeout, u32 alertable) {
-  if (num_events > 64) {
+  if (num_events == 0 || num_events > 64) {
     XThread::SetLastError(87);  // ERROR_INVALID_PARAMETER
     return ~0u;
   }
 
-  uint64_t timeout_wait = (uint64_t)timeout;
+  uint64_t timeout_wait = static_cast<uint64_t>(timeout);
+
+  // XObject::WaitMultiple uses:
+  //   wait_type != 0 -> WaitAny
+  //   wait_type == 0 -> WaitAll
+  //
+  // WSAWaitForMultipleEvents uses the opposite semantic for bWaitAll:
+  //   FALSE -> WaitAny
+  //   TRUE  -> WaitAll
+  const uint32_t wait_type = wait_all ? 0u : 1u;
 
   X_STATUS result = 0;
   do {
-    result = xboxkrnl::xeNtWaitForMultipleObjectsEx(num_events, events, wait_all, 1, alertable,
-                                                    timeout != -1 ? &timeout_wait : nullptr);
+    result = xboxkrnl::xeNtWaitForMultipleObjectsEx(
+        num_events, events, wait_type, 1, alertable,
+        timeout != 0xFFFFFFFFu ? &timeout_wait : nullptr);
   } while (result == X_STATUS_ALERTED);
 
   if (XFAILED(result)) {
@@ -373,7 +383,15 @@ u32 NetDll_WSAWaitForMultipleEvents_entry(u32 num_events, mapped_u32 events, u32
     XThread::SetLastError(error);
     return ~0u;
   }
-  return 0;
+
+  REXKRNL_INFO(
+      "[ONLINE] WSAWaitForMultipleEvents count={} wait_all={} timeout={} result=0x{:08X}",
+      num_events, wait_all, timeout, static_cast<uint32_t>(result));
+
+  // WaitAny success is already 0 + event index.
+  // WaitAll success is 0.
+  // X_STATUS_TIMEOUT is 0x102, matching WSA_WAIT_TIMEOUT.
+  return static_cast<uint32_t>(result);
 }
 
 u32 NetDll_WSACreateEvent_entry() {
@@ -393,7 +411,14 @@ u32 NetDll_WSACloseEvent_entry(u32 event_handle) {
 }
 
 u32 NetDll_WSAResetEvent_entry(u32 event_handle) {
+  REXKRNL_INFO("[ONLINE] WSAResetEvent enter handle=0x{:08X}", event_handle);
+
   X_STATUS result = xboxkrnl::xeNtClearEvent(event_handle);
+
+  REXKRNL_INFO(
+      "[ONLINE] WSAResetEvent leave handle=0x{:08X} result=0x{:08X}",
+      event_handle, static_cast<uint32_t>(result));
+
   if (XFAILED(result)) {
     uint32_t error = xboxkrnl::xeRtlNtStatusToDosError(result);
     XThread::SetLastError(error);
@@ -919,6 +944,65 @@ u32 NetDll_sendto_entry(u32 caller, u32 socket_handle, mapped_void buf_ptr, u32
   return socket->SendTo(buf_ptr, buf_len, flags, &native_to, to_len);
 }
 
+u32 NetDll_getsockname_entry(u32 caller, u32 socket_handle,
+                             ppc_ptr_t<XSOCKADDR_IN> name,
+                             mapped_u32 namelen_ptr) {
+  if (!name || !namelen_ptr) {
+    // WSAEFAULT
+    XThread::SetLastError(0x271E);
+    return -1;
+  }
+
+  auto socket = REX_KERNEL_OBJECTS()->LookupObject<XSocket>(socket_handle);
+  if (!socket) {
+    // WSAENOTSOCK
+    XThread::SetLastError(0x2736);
+    return -1;
+  }
+
+  N_XSOCKADDR_IN native_name = {};
+
+#if REX_PLATFORM_WIN32
+  int native_len = sizeof(native_name);
+  int ret = ::getsockname(
+      static_cast<SOCKET>(socket->native_handle()),
+      reinterpret_cast<sockaddr*>(&native_name),
+      &native_len);
+#else
+  socklen_t native_len = sizeof(native_name);
+  int ret = ::getsockname(
+      static_cast<int>(socket->native_handle()),
+      reinterpret_cast<sockaddr*>(&native_name),
+      &native_len);
+#endif
+
+  if (ret == -1) {
+#if REX_PLATFORM_WIN32
+    XThread::SetLastError(WSAGetLastError());
+#else
+    XThread::SetLastError(0);
+#endif
+    return -1;
+  }
+
+  name->sin_family = native_name.sin_family;
+  name->sin_port = native_name.sin_port;
+  name->sin_addr = native_name.sin_addr;
+  std::memset(name->x_sin_zero, 0, sizeof(name->x_sin_zero));
+
+  *namelen_ptr = static_cast<uint32_t>(native_len);
+
+  REXKRNL_INFO(
+      "[ONLINE] NetDll_getsockname socket={} name=0x{:08X} lenptr=0x{:08X} family={} port={} len={}",
+      socket_handle,
+      name.guest_address(),
+      namelen_ptr.guest_address(),
+      native_name.sin_family,
+      ntohs(static_cast<uint16_t>(native_name.sin_port)),
+      static_cast<uint32_t>(native_len));
+
+  return 0;
+}
 u32 NetDll___WSAFDIsSet_entry(u32 socket_handle, ppc_ptr_t<x_fd_set> fd_set) {
   const uint8_t max_fd_count = std::min((uint32_t)fd_set->fd_count, uint32_t(64));
   for (uint8_t i = 0; i < max_fd_count; i++) {
@@ -1098,5 +1182,5 @@ REX_EXPORT_STUB(__imp__NetDll_XnpToolSetCallbacks);
 REX_EXPORT_STUB(__imp__NetDll_XnpUnregisterKeyForCallerType);
 REX_EXPORT_STUB(__imp__NetDll_XnpUpdateConfigParams);
 REX_EXPORT_STUB(__imp__NetDll_getpeername);
-REX_EXPORT_STUB(__imp__NetDll_getsockname);
+REX_EXPORT(__imp__NetDll_getsockname, rex::kernel::xam::NetDll_getsockname_entry)
 REX_EXPORT_STUB(__imp__NetDll_getsockopt);
diff --git a/src/kernel/xam/xam_ui.cpp b/src/kernel/xam/xam_ui.cpp
index 5a572ce..0d2ff30 100644
--- a/src/kernel/xam/xam_ui.cpp
+++ b/src/kernel/xam/xam_ui.cpp
@@ -609,7 +609,7 @@ REX_EXPORT_STUB(__imp__XamShowFitnessWarnAboutTimeUI);
 REX_EXPORT_STUB(__imp__XamShowFofUI);
 REX_EXPORT_STUB(__imp__XamShowForcedNameChangeUI);
 REX_EXPORT_STUB(__imp__XamShowFriendRequestUI);
-REX_EXPORT_STUB(__imp__XamShowFriendsUI);
+REX_EXPORT_STUB_RETURN(__imp__XamShowFriendsUI, 0);
 REX_EXPORT_STUB(__imp__XamShowFriendsUIp);
 REX_EXPORT_STUB(__imp__XamShowGameInviteUI);
 REX_EXPORT_STUB(__imp__XamShowGameVoiceChannelUI);
diff --git a/src/kernel/xam/xam_user.cpp b/src/kernel/xam/xam_user.cpp
index 8778066..f87781c 100644
--- a/src/kernel/xam/xam_user.cpp
+++ b/src/kernel/xam/xam_user.cpp
@@ -98,7 +98,7 @@ i32 XamUserGetSigninInfo_entry(u32 user_index, u32 flags, ppc_ptr_t<X_USER_SIGNI
 
   const auto& user_profile = REX_KERNEL_STATE()->user_profile();
   info->xuid = user_profile->xuid();
-  info->signin_state = user_profile->signin_state();
+  info->signin_state = 2; // FIFA Street: report Xbox Live sign-in
   rex::string::copy_truncating(info->name, user_profile->name(), rex::countof(info->name));
   return X_E_SUCCESS;
 }
@@ -382,8 +382,9 @@ u32 XamUserCheckPrivilege_entry(u32 user_index, u32 mask, mapped_u32 out_value)
     }
   }
 
-  // If we deny everything, games should hopefully not try to do stuff.
-  *out_value = 0;
+  // FIFA Street online test
+  REXKRNL_INFO("FIFA SIGNIN TRACE: XamUserCheckPrivilege user={} privilege={} -> ALLOWED", user_index, mask);
+  *out_value = 1;
   return X_ERROR_SUCCESS;
 }
 
@@ -769,7 +770,8 @@ REX_EXPORT_STUB(__imp__XamUserGetAgeGroup);
 REX_EXPORT_STUB(__imp__XamUserGetCachedUserFlags);
 REX_EXPORT_STUB(__imp__XamUserGetDeviceId);
 REX_EXPORT_STUB(__imp__XamUserGetIndexFromXUID);
-REX_EXPORT_STUB(__imp__XamUserGetMembershipTierFromXUID);
+u32 XamUserGetMembershipTierFromXUID_entry(u64 xuid) { REXKRNL_INFO("FIFA SIGNIN TRACE: XamUserGetMembershipTierFromXUID xuid={:016X} -> GOLD(6)", xuid); return 6; }
+REX_EXPORT(__imp__XamUserGetMembershipTierFromXUID, XamUserGetMembershipTierFromXUID_entry);
 REX_EXPORT_STUB(__imp__XamUserGetOnlineCountryFromXUID);
 REX_EXPORT_STUB(__imp__XamUserGetOnlineLanguageFromXUID);
 REX_EXPORT_STUB(__imp__XamUserGetOnlineXUIDFromOfflineXUID);
@@ -814,3 +816,10 @@ REX_EXPORT_STUB(__imp__XamUserUpdateRecentPlayer);
 REX_EXPORT_STUB(__imp__XamUserValidateAvatarManifest);
 REX_EXPORT_STUB(__imp__XamUserWriteUserPreference);
 REX_EXPORT_STUB(__imp__XamVerifyPasscode);
+
+
+
+
+
+
+
diff --git a/src/kernel/xboxkrnl/xboxkrnl_modules.cpp b/src/kernel/xboxkrnl/xboxkrnl_modules.cpp
index dcd2001..97dd0ed 100644
--- a/src/kernel/xboxkrnl/xboxkrnl_modules.cpp
+++ b/src/kernel/xboxkrnl/xboxkrnl_modules.cpp
@@ -85,6 +85,13 @@ u32 XexGetModuleSection_entry(mapped_void hmodule, mapped_string name, mapped_u3
 
 u32 XexLoadImage_entry(mapped_string module_name, u32 module_flags, u32 min_version,
                        mapped_u32 hmodule_ptr) {
+
+  REXKRNL_ERROR(
+      "FIFA TRACE XexLoadImage: module='{}' flags=0x{:08X} min_version=0x{:08X}",
+      module_name.value(),
+      module_flags,
+      min_version);
+
   X_STATUS result = X_STATUS_NO_SUCH_FILE;
 
   uint32_t hmodule = 0;
@@ -118,7 +125,13 @@ u32 XexLoadImage_entry(mapped_string module_name, u32 module_flags, u32 min_vers
 
   *hmodule_ptr = hmodule;
 
-  return result;
+REXKRNL_ERROR(
+    "FIFA TRACE XexLoadImage RESULT: module='{}' result=0x{:08X} hmodule=0x{:08X}",
+    module_name.value(),
+    static_cast<uint32_t>(result),
+    hmodule);
+
+return result;
 }
 
 u32 XexUnloadImage_entry(mapped_void hmodule) {
@@ -170,6 +183,13 @@ u32 XexGetProcedureAddress_entry(mapped_void hmodule, u32 ordinal, mapped_u32 ou
     module = XModule::GetFromHModule(REX_KERNEL_STATE(), hmodule);
   }
   if (module) {
+    REXKRNL_ERROR(
+        "FIFA TRACE XexGetProcedureAddress: module='{}' hmodule=0x{:08X} "
+        "ordinal=0x{:08X} caller=0x{:08X}",
+        module->name(),
+        static_cast<uint32_t>(hmodule),
+        ordinal,
+        caller_address);
     uint32_t ptr;
     if (is_string_name) {
       ptr = module->GetProcAddressByName(string_name);
@@ -177,6 +197,13 @@ u32 XexGetProcedureAddress_entry(mapped_void hmodule, u32 ordinal, mapped_u32 ou
       ptr = module->GetProcAddressByOrdinal(ordinal, caller_address);
     }
     if (ptr) {
+    REXKRNL_ERROR(
+        "FIFA TRACE XexGetProcedureAddress RESULT: module='{}' "
+        "ordinal=0x{:08X} -> ptr=0x{:08X} caller=0x{:08X}",
+        module->name(),
+        ordinal,
+        ptr,
+        caller_address);
       *out_function_ptr = ptr;
       result = X_STATUS_SUCCESS;
     } else {
diff --git a/src/kernel/xboxkrnl/xboxkrnl_rtl.cpp b/src/kernel/xboxkrnl/xboxkrnl_rtl.cpp
index 8b862fc..bc6d50a 100644
--- a/src/kernel/xboxkrnl/xboxkrnl_rtl.cpp
+++ b/src/kernel/xboxkrnl/xboxkrnl_rtl.cpp
@@ -13,6 +13,7 @@
 #pragma GCC diagnostic ignored "-Wunused-parameter"
 
 #include <algorithm>
+#include <immintrin.h>
 #include <string>
 
 #include <rex/chrono/chrono_steady_cast.h>
@@ -387,14 +388,18 @@ void RtlEnterCriticalSection_entry(ppc_ptr_t<X_RTL_CRITICAL_SECTION> cs) {
     return;
   }
 
-  // Spin loop
+  // Spin loop. Test before the locked compare-exchange and pause between tries; the guest's spin
+  // counts (up to 65k) were meant for a dedicated hardware thread, so cap them on a shared host.
+  spin_count = std::min<uint32_t>(spin_count, 2048);
   while (spin_count--) {
-    if (rex::thread::atomic_cas(-1, 0, &cs->lock_count)) {
+    if (*reinterpret_cast<volatile int32_t*>(&cs->lock_count) == -1 &&
+        rex::thread::atomic_cas(-1, 0, &cs->lock_count)) {
       // Acquired.
       cs->owning_thread = cur_thread;
       cs->recursion_count = 1;
       return;
     }
+    _mm_pause();
   }
 
   if (rex::thread::atomic_inc(&cs->lock_count) != 0) {
diff --git a/src/kernel/xboxkrnl/xboxkrnl_video.cpp b/src/kernel/xboxkrnl/xboxkrnl_video.cpp
index 1254710..fb641aa 100644
--- a/src/kernel/xboxkrnl/xboxkrnl_video.cpp
+++ b/src/kernel/xboxkrnl/xboxkrnl_video.cpp
@@ -14,6 +14,10 @@
 
 #include <algorithm>
 #include <atomic>
+#include <chrono>
+#include <cstring>
+#include <cstdlib>
+#include <thread>
 #include <string>
 
 #include <rex/cvar.h>
@@ -33,6 +37,10 @@
 #include <rex/system/xtypes.h>
 #include <rex/ui/flags.h>
 
+#if REX_PLATFORM_WIN32
+#include <windows.h>
+#endif
+
 namespace {
 // Display gamma type: 0 - linear, 1 - sRGB (CRT), 2 - BT.709 (HDTV), 3 - power
 constexpr uint32_t kDisplayGammaType = 2;
@@ -437,6 +445,59 @@ u32 VdRetrainEDRAM_entry(u32 unk0, u32 unk1, u32 unk2, u32 unk3, u32 unk4, u32 u
   return 0;
 }
 
+// True VSync (REX_TRUE_VSYNC=1): hold the game's render thread to the chosen refresh rate at its own
+// swap, so the game runs at exactly the display rate. Pacing in the swap callback instead slowed videos/audio.
+static void PaceTrueVsyncSwap() {
+  using Clock = std::chrono::steady_clock;
+  static const double hz = [] {
+    const char* on = std::getenv("REX_TRUE_VSYNC");
+    if (!on || on[0] != '1') return 0.0;
+    // REX_TRUE_VSYNC_FPS: displayed frame rate when it is a divisor of the refresh rate (30 at 60 Hz).
+    const char* value = std::getenv("REX_TRUE_VSYNC_FPS");
+    if (!value) value = std::getenv("REX_VIDEO_MODE_REFRESH_RATE");
+    const double parsed = value ? std::strtod(value, nullptr) : 0.0;
+    if (parsed < 20.0 || parsed > 1000.0) return 0.0;
+    // Default ("newest"): the game runs on its own clock and each refresh shows its newest frame; the game
+    // simulates on a separate thread, so holding rendering to the display made motion uneven. It is only
+    // capped at twice the displayed rate so a fresh frame is always ready without wasting power.
+    // REX_TRUE_VSYNC_MODE=locked: rendering held to the display (smooth only if the game's clock agrees).
+    const char* mode = std::getenv("REX_TRUE_VSYNC_MODE");
+    return (mode && std::strcmp(mode, "locked") == 0) ? parsed : -parsed * 2.0;
+  }();
+  if (hz == 0.0) return;
+  const bool locked = hz > 0.0;
+  const double rate = locked ? hz : -hz;
+#if REX_PLATFORM_WIN32
+  // D3D12 publishes its swap chain latency waitable: waiting on it clocks the game by the real display
+  // refresh (no drift against a CPU timer, so no skipped or doubled frames). The timer below then only
+  // stops the game from outrunning the chosen rate on a faster monitor.
+  char handle_text[32];
+  const bool display_paced =
+      locked && GetEnvironmentVariableA("REX_TRUE_VSYNC_WAITABLE", handle_text, sizeof(handle_text)) > 0;
+  if (display_paced) {
+    const HANDLE waitable = HANDLE(uintptr_t(std::strtoull(handle_text, nullptr, 16)));
+    // Presents that are not game frames (window repaints) also release the semaphore: take every pending
+    // release at once (no surplus builds up, so the game never runs ahead of the display and drops frames),
+    // and only wait when the display has not taken a frame since the last swap.
+    int released = 0;
+    while (WaitForSingleObject(waitable, 0) == WAIT_OBJECT_0) ++released;
+    if (released == 0) WaitForSingleObject(waitable, 100);
+  }
+#else
+  const bool display_paced = false;
+#endif
+  static Clock::time_point next{};
+  const auto period = std::chrono::duration_cast<Clock::duration>(
+      std::chrono::duration<double>(1.0 / (display_paced ? rate * 1.05 : rate)));
+  auto now = Clock::now();
+  if (next == Clock::time_point{} || now - next > period * 2) next = now;  // late or first: no catch-up burst
+  if (now < next) {
+    if (next - now > std::chrono::milliseconds(2)) std::this_thread::sleep_for(next - now - std::chrono::milliseconds(1));
+    while (Clock::now() < next) std::this_thread::yield();
+  }
+  next += period;
+}
+
 void VdSwap_entry(mapped_void buffer_ptr,      // ptr into primary ringbuffer
                   mapped_void fetch_ptr,       // frontbuffer Direct3D 9 texture header fetch
                   mapped_void unk2,            // system writeback ptr
@@ -445,6 +506,7 @@ void VdSwap_entry(mapped_void buffer_ptr,      // ptr into primary ringbuffer
                   mapped_u32 frontbuffer_ptr,  // ptr to frontbuffer address
                   mapped_u32 texture_format_ptr, mapped_u32 color_space_ptr, mapped_u32 width,
                   mapped_u32 height) {
+  PaceTrueVsyncSwap();
   // All of these parameters are REQUIRED.
   assert(buffer_ptr);
   assert(fetch_ptr);
diff --git a/src/system/function_dispatcher.cpp b/src/system/function_dispatcher.cpp
index bd43109..8a47e13 100644
--- a/src/system/function_dispatcher.cpp
+++ b/src/system/function_dispatcher.cpp
@@ -13,7 +13,18 @@
  *              role as a function dispatch table rather than a CPU emulator.
  */
 
+#include <atomic>
+#include <chrono>
+#include <cstdlib>
+#include <cstring>
+#include <thread>
+#if defined(__x86_64__) || defined(_M_X64)
+#include <immintrin.h>
+#endif
+#include <string>
+
 #include <rex/assert.h>
+#include <rex/cvar.h>
 #include <rex/dbg.h>
 #include <rex/logging.h>
 #include <rex/perf/counter.h>
@@ -23,6 +34,16 @@
 #include <rex/system/function_dispatcher.h>
 #include <rex/system/thread_state.h>
 
+REXCVAR_DEFINE_INT32(guest_present_interval_cap, 1, "GPU",
+                     "FIFA Street only: highest present interval (vblanks per displayed frame) the game's D3D swap "
+                     "callback may use. The game asks for 2 in menus, replays and cutscenes, which halves the frame "
+                     "rate on any refresh rate; 1 shows every frame. 0 leaves the game's own interval unchanged.")
+    .range(0, 15);
+
+REXCVAR_DEFINE_BOOL(guest_present_interval_log, false, "GPU",
+                    "FIFA Street only: every two seconds log how many swaps asked for each present interval "
+                    "(0..15) and how many were capped, to find which scenes use an interval above 1.");
+
 namespace rex::runtime {
 
 namespace {
@@ -32,9 +53,118 @@ FunctionDispatcher* GetBoundFunctionDispatcher() {
   return runtime ? runtime->function_dispatcher() : nullptr;
 }
 
+// FIFA Street's D3D library (fifadllzf.xex.dll, sub_8270F040) schedules each swap for the vblank
+// "last swap + interval", with the interval taken from bits 8..11 of its argument. Capping it here changes
+// how often frames are displayed and nothing else; the game's own frame pacing follows the display.
+constexpr uint32_t kFifaStreetSwapCallback = 0x8270F040;
+::PPCFunc* g_swap_callback_original = nullptr;
+uint32_t g_swap_interval_cap = 1;
+
+// Optional global frame limit applied where the game's swap is executed. REX_FPS_LIMIT_HZ=<Hz>|auto
+// ("auto" follows REX_VIDEO_MODE_REFRESH_RATE). It caps every scene, including logos and menus, at the
+// chosen refresh rate when host VSync is off; unset or 0 leaves the frame rate alone.
+double FrameLimitHz() {
+  static const double hz = [] {
+    const char* value = std::getenv("REX_FPS_LIMIT_HZ");
+    if (value && std::strcmp(value, "auto") == 0) value = std::getenv("REX_VIDEO_MODE_REFRESH_RATE");
+    const double parsed = value ? std::strtod(value, nullptr) : 0.0;
+    return parsed >= 20.0 && parsed <= 1000.0 ? parsed : 0.0;
+  }();
+  return hz;
+}
+
+void LimitFrameRate() {
+  double hz = FrameLimitHz();
+  // No automatic cap for True VSync: sleeping in the swap callback slowed videos and audio to slow motion.
+  if (hz <= 0.0) return;
+  using Clock = std::chrono::steady_clock;
+  static Clock::time_point next{};
+  const auto period = std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double>(1.0 / hz));
+  auto now = Clock::now();
+  if (next == Clock::time_point{}) next = now;
+  if (now < next) {
+    const auto remaining = next - now;
+    if (remaining > std::chrono::milliseconds(2)) {
+      std::this_thread::sleep_for(remaining - std::chrono::milliseconds(1));
+    }
+    while (Clock::now() < next) {
+#if defined(__x86_64__) || defined(_M_X64)
+      _mm_pause();
+#endif
+    }
+  }
+  now = Clock::now();
+  next = (now - next > period * 2) ? now + period : next + period;
+}
+
+void CappedSwapCallback(PPCContext& ctx, uint8_t* base) {
+  const uint32_t interval = (ctx.r3.u32 >> 8) & 0xF;
+  if (REXCVAR_GET(guest_present_interval_log)) {
+    static std::atomic<uint32_t> counts[16];
+    static std::atomic<uint32_t> capped{0};
+    static std::atomic<int64_t> last_report_ns{0};
+    counts[interval].fetch_add(1, std::memory_order_relaxed);
+    if (interval > g_swap_interval_cap) capped.fetch_add(1, std::memory_order_relaxed);
+    const int64_t now = std::chrono::duration_cast<std::chrono::nanoseconds>(
+                            std::chrono::steady_clock::now().time_since_epoch()).count();
+    int64_t last = last_report_ns.load(std::memory_order_relaxed);
+    if (last == 0) {
+      last_report_ns.store(now, std::memory_order_relaxed);
+    } else if (now - last >= 2'000'000'000 &&
+               last_report_ns.compare_exchange_strong(last, now, std::memory_order_relaxed)) {
+      std::string text;
+      for (uint32_t i = 0; i < 16; ++i) {
+        const uint32_t n = counts[i].exchange(0, std::memory_order_relaxed);
+        if (n) text += " interval" + std::to_string(i) + "=" + std::to_string(n);
+      }
+      REXLOG_INFO("Present interval stats (2 s):{} capped={} cap={}", text.empty() ? " none" : text,
+                  capped.exchange(0, std::memory_order_relaxed), g_swap_interval_cap);
+    }
+  }
+  if (interval > g_swap_interval_cap) {
+    ctx.r3.u64 = (ctx.r3.u64 & ~uint64_t(0xF00)) | (uint64_t(g_swap_interval_cap) << 8);
+  }
+  LimitFrameRate();
+  g_swap_callback_original(ctx, base);
+}
+
+void ApplyFifaStreetPresentIntervalCap(FunctionDispatcher& dispatcher, const std::string& module_id) {
+  if (module_id != "fifadllzf.xex.dll") return;
+  const int32_t cap = REXCVAR_GET(guest_present_interval_cap);
+  if (cap < 1) return;
+  const uint8_t* code = dispatcher.memory()->TranslateVirtual(kFifaStreetSwapCallback);
+  // Only the exact build this was found in: mflr r12 / stwu r1,-176(r1) / mr r30,r3.
+  if (!code || memory::load_and_swap<uint32_t>(code) != 0x7D8802A6 ||
+      memory::load_and_swap<uint32_t>(code + 8) != 0x9421FF50 ||
+      memory::load_and_swap<uint32_t>(code + 12) != 0x7C7E1B78) {
+    REXLOG_WARN("Present interval cap: swap callback {:08X} does not match the known code, not applied",
+                kFifaStreetSwapCallback);
+    return;
+  }
+  ::PPCFunc* original = dispatcher.GetFunction(kFifaStreetSwapCallback);
+  if (!original || original == &CappedSwapCallback) return;
+  g_swap_callback_original = original;
+  g_swap_interval_cap = uint32_t(cap);
+  dispatcher.SetFunction(kFifaStreetSwapCallback, &CappedSwapCallback);
+  REXLOG_INFO("Present interval cap: swap callback {:08X} limited to {} vblank(s) per frame",
+              kFifaStreetSwapCallback, cap);
+}
+
 }  // namespace
 
 static void InvalidFunctionTrap(PPCContext& ctx, uint8_t* /*base*/) {
+  REXCPU_ERROR(
+      "INVALID INDIRECT CALL: target={:08X} LR={:08X} CTR={:08X} "
+      "r1={:08X} r2={:08X} r3={:08X} r11={:08X} r12={:08X}",
+      ctx.last_indirect_target,
+      static_cast<uint32_t>(ctx.lr),
+      static_cast<uint32_t>(ctx.ctr.u64),
+      static_cast<uint32_t>(ctx.r1.u64),
+      static_cast<uint32_t>(ctx.r2.u64),
+      static_cast<uint32_t>(ctx.r3.u64),
+      static_cast<uint32_t>(ctx.r11.u64),
+      static_cast<uint32_t>(ctx.r12.u64));
+
   REX_FATAL("Call to invalid or unregistered function at guest address 0x{:08X}",
             ctx.last_indirect_target);
 }
@@ -61,29 +191,52 @@ bool FunctionDispatcher::Execute(ThreadState* thread_state, uint32_t address) {
   SCOPE_profile_cpu_f("cpu");
   PROFILE_FUNCTION_DISPATCHED();
 
-  PPCFunc* fn = GetFunction(address);
-  if (!fn) {
-    REXCPU_ERROR("Execute({:08X}): function not in function table", address);
-    return false;
-  }
+ PPCFunc* fn = GetFunction(address);
+if (!fn) {
+  auto* ctx = thread_state->context();
+
+  REXCPU_ERROR(
+      "EXECUTE MISS: address={:08X} last_indirect_target={:08X} "
+      "LR={:08X} CTR={:08X} r1={:08X} r2={:08X} "
+      "r3={:08X} r11={:08X} r12={:08X}",
+      address,
+      ctx->last_indirect_target,
+      static_cast<uint32_t>(ctx->lr),
+      static_cast<uint32_t>(ctx->ctr.u64),
+      static_cast<uint32_t>(ctx->r1.u64),
+      static_cast<uint32_t>(ctx->r2.u64),
+      static_cast<uint32_t>(ctx->r3.u64),
+      static_cast<uint32_t>(ctx->r11.u64),
+      static_cast<uint32_t>(ctx->r12.u64));
+
+  return false;
+}
 
   auto* ctx = thread_state->context();
   auto* previous_thread_state = ThreadState::Get();
 
+  struct DispatchRestoreGuard {
+    PPCContext* context;
+    ThreadState* previous_thread;
+    uint64_t stack_pointer;
+    uint64_t link_register;
+    ~DispatchRestoreGuard() {
+      context->lr = link_register;
+      context->r1.u64 = stack_pointer;
+      ThreadState::Bind(previous_thread);
+    }
+  } restore{ctx, previous_thread_state, ctx->r1.u64, ctx->lr};
+
   // Rebind the active guest thread for cross-module callbacks.
   ThreadState::Bind(thread_state);
 
   // Pad out stack a bit, as some games seem to overwrite the caller by about 16 to 32b.
   ctx->r1.u64 -= 64 + 112;
 
-  uint64_t previous_lr = ctx->lr;
   ctx->lr = 0xBCBCBCBC;
 
   fn(*ctx, memory_->virtual_membase());
 
-  ctx->lr = previous_lr;
-  ctx->r1.u64 += 64 + 112;
-  ThreadState::Bind(previous_thread_state);
 
   return true;
 }
@@ -130,13 +283,16 @@ uint64_t FunctionDispatcher::Execute(ThreadState* thread_state, uint32_t address
 uint64_t FunctionDispatcher::ExecuteTrap(ThreadState* thread_state, uint32_t address,
                                          uint64_t args[], size_t arg_count) {
   auto* ctx = thread_state->context();
-  PPCContext saved = *ctx;
-
-  uint64_t result = Execute(thread_state, address, args, arg_count);
+  struct ContextRestoreGuard {
+    PPCContext* context;
+    PPCContext saved;
+    ~ContextRestoreGuard() {
+      *context = saved;
+      context->fpscr.restoreGuestBits(saved.fpscr.csr);
+    }
+  } restore{ctx, *ctx};
 
-  *ctx = saved;
-  ctx->fpscr.restoreGuestBits(saved.fpscr.csr);
-  return result;
+  return Execute(thread_state, address, args, arg_count);
 }
 
 uint64_t FunctionDispatcher::ExecuteInterrupt(ThreadState* thread_state, uint32_t address,
@@ -166,49 +322,77 @@ uint64_t FunctionDispatcher::ExecuteInterrupt(ThreadState* thread_state, uint32_
   auto pcr_address = memory_->TranslateVirtual(static_cast<uint32_t>(ctx->r13.u64));
   uint32_t old_tls_ptr = memory::load_and_swap<uint32_t>(pcr_address);
   memory::store_and_swap<uint32_t>(pcr_address, 0);
+  struct TlsRestoreGuard {
+    uint8_t* address;
+    uint32_t value;
+    ~TlsRestoreGuard() { memory::store_and_swap<uint32_t>(address, value); }
+  } tls_restore{pcr_address, old_tls_ptr};
 
   if (!Execute(thread_state, address)) {
     return 0xDEADBABE;
   }
 
-  // Restore TLS ptr.
-  memory::store_and_swap<uint32_t>(pcr_address, old_tls_ptr);
 
   return ctx->r3.u64;
 }
 
 // rexglue function table management
 
-bool FunctionDispatcher::InitializeFunctionTable(uint32_t code_base, uint32_t code_size,
-                                                 uint32_t image_base, uint32_t image_size,
+bool FunctionDispatcher::InitializeFunctionTable(uint32_t code_base,
+                                                 uint32_t code_size,
+                                                 uint32_t image_base,
+                                                 uint32_t image_size,
                                                  bool is_entrypoint) {
   std::lock_guard<std::recursive_mutex> lock(dispatch_mutex_);
 
+  const uint64_t image_end = uint64_t(image_base) + image_size;
+  const uint64_t code_end = uint64_t(code_base) + code_size + kThunkReserveSize;
+  if (!code_size || !image_size || (code_base & 3) || (code_size & 3) ||
+      image_end > UINT32_MAX || code_end > UINT32_MAX ||
+      (uint64_t(code_size) + kThunkReserveSize) * 2 > UINT32_MAX) {
+    REXLOG_ERROR("InitializeFunctionTable: invalid or overflowing module range");
+    return false;
+  }
+
   if (is_entrypoint && entrypoint_code_base_ != 0) {
     REXLOG_ERROR("InitializeFunctionTable: entrypoint already registered at {:08X}",
                  entrypoint_code_base_);
     return false;
   }
 
-  uint32_t new_table_end = image_base + image_size + (code_size + kThunkReserveSize) * 2;
-  uint32_t new_code_end = code_base + code_size + kThunkReserveSize;
+  uint32_t new_image_end = image_base + image_size;
+  uint32_t new_code_end =
+      code_base + code_size + kThunkReserveSize;
+
   for (const auto& existing : module_tables_) {
-    uint32_t existing_table_end =
-        existing.image_base + existing.image_size + (existing.code_size + kThunkReserveSize) * 2;
-    uint32_t existing_code_end = existing.code_base + existing.code_size + kThunkReserveSize;
-    if (image_base < existing_table_end && new_table_end > existing.image_base) {
-      REXLOG_ERROR("Module image range [{:08X}, {:08X}) overlaps existing [{:08X}, {:08X})",
-                   image_base, new_table_end, existing.image_base, existing_table_end);
+    uint32_t existing_image_end =
+        existing.image_base + existing.image_size;
+
+    uint32_t existing_code_end =
+        existing.code_base + existing.code_size +
+        kThunkReserveSize;
+
+    if (image_base < existing_image_end &&
+        new_image_end > existing.image_base) {
+      REXLOG_ERROR(
+          "Module image range [{:08X}, {:08X}) overlaps existing [{:08X}, {:08X})",
+          image_base, new_image_end,
+          existing.image_base, existing_image_end);
       return false;
     }
-    if (code_base < existing_code_end && new_code_end > existing.code_base) {
-      REXLOG_ERROR("Module code range [{:08X}, {:08X}) overlaps existing [{:08X}, {:08X})",
-                   code_base, new_code_end, existing.code_base, existing_code_end);
+
+    if (code_base < existing_code_end &&
+        new_code_end > existing.code_base) {
+      REXLOG_ERROR(
+          "Module code range [{:08X}, {:08X}) overlaps existing [{:08X}, {:08X})",
+          code_base, new_code_end,
+          existing.code_base, existing_code_end);
       return false;
     }
   }
 
-  if (!memory_->InitializeFunctionTable(code_base, code_size, image_base, image_size)) {
+  if (!memory_->InitializeFunctionTable(
+          code_base, code_size, image_base, image_size)) {
     REXLOG_ERROR("Failed to initialize guest memory function table");
     return false;
   }
@@ -226,11 +410,13 @@ bool FunctionDispatcher::InitializeFunctionTable(uint32_t code_base, uint32_t co
     entrypoint_code_base_ = code_base;
   }
 
-  REXLOG_INFO("Function table initialized for module: code={:08X}-{:08X}, image={:08X}-{:08X}",
-              code_base, code_base + code_size, image_base, image_base + image_size);
+  REXLOG_INFO(
+      "Function table initialized for module: code={:08X}-{:08X}, image={:08X}-{:08X}",
+      code_base, code_base + code_size,
+      image_base, image_base + image_size);
+
   return true;
 }
-
 FunctionDispatcher::ModuleTableInfo* FunctionDispatcher::FindModuleByAddress(
     uint32_t guest_address) {
   for (auto& mod : module_tables_) {
@@ -253,6 +439,11 @@ bool FunctionDispatcher::SetFunction(uint32_t guest_address, ::PPCFunc* func) {
   std::lock_guard<std::recursive_mutex> lock(dispatch_mutex_);
   assert_true(!module_tables_.empty());
 
+  if (guest_address & 3) {
+    REXLOG_ERROR("SetFunction: unaligned guest address {:08X}", guest_address);
+    return false;
+  }
+
   if (!FindModuleByAddress(guest_address)) {
     REXLOG_ERROR("SetFunction: address {:08X} outside all registered module ranges", guest_address);
     return false;
@@ -343,6 +534,7 @@ void FunctionDispatcher::RegisterModule(const std::string& module_id, uint32_t c
   } guard{this};
 
   register_func(this);
+  ApplyFifaStreetPresentIntervalCap(*this, module_id);
 
   ModuleRegistration reg;
   reg.code_base = code_base;
diff --git a/src/system/kernel_state.cpp b/src/system/kernel_state.cpp
index 697399c..f609238 100644
--- a/src/system/kernel_state.cpp
+++ b/src/system/kernel_state.cpp
@@ -914,11 +914,44 @@ void KernelState::RegisterRecompiledModule(const char* pe_name, const char* gues
 std::optional<KernelState::RecompiledModuleInfo> KernelState::FindRecompiledModule(
     std::string_view guest_path) {
   auto global_lock = global_critical_region_.Acquire();
+
   auto normalized = NormalizeGuestPath(guest_path);
+
+  // Primeiro tenta correspondência exata.
   for (const auto& info : recompiled_modules_) {
-    if (info.guest_path == normalized)
+    if (info.guest_path == normalized) {
       return info;
+    }
+  }
+
+  // Fallback: comparar apenas o nome do ficheiro.
+  std::string normalized_str(normalized);
+  size_t pos = normalized_str.find_last_of("\\/");
+  std::string filename =
+      pos == std::string::npos ? normalized_str : normalized_str.substr(pos + 1);
+
+  std::optional<RecompiledModuleInfo> filename_match;
+  for (const auto& info : recompiled_modules_) {
+    std::string info_path(info.guest_path);
+    size_t info_pos = info_path.find_last_of("\\/");
+    std::string info_filename =
+        info_pos == std::string::npos ? info_path : info_path.substr(info_pos + 1);
+
+    if (info_filename == filename) {
+      if (filename_match) {
+        REXSYS_ERROR("FindRecompiledModule: ambiguous filename '{}' for '{}'", filename, normalized);
+        return std::nullopt;
+      }
+      filename_match = info;
+    }
+  }
+
+  if (filename_match) {
+    REXSYS_INFO("FindRecompiledModule: matched '{}' to '{}' by filename", normalized,
+                filename_match->guest_path);
+    return filename_match;
   }
+  REXSYS_WARN("FindRecompiledModule: no registered recompiled module for '{}'", normalized);
   return std::nullopt;
 }
 
diff --git a/src/system/runtime.cpp b/src/system/runtime.cpp
index c10694c..2e6bceb 100644
--- a/src/system/runtime.cpp
+++ b/src/system/runtime.cpp
@@ -34,8 +34,37 @@ REXCVAR_DEFINE_STRING(update_data_root, "", "Runtime", "Override update data pat
 REXCVAR_DEFINE_STRING(cache_root, "", "Runtime", "Override shader cache path");
 REXCVAR_DEFINE_STRING(metadata_root, "", "Runtime", "Override metadata path");
 
+#ifdef _WIN32
+#include <windows.h>
+#endif
+
 namespace rex {
 
+namespace {
+
+// Guest waits and host sleeps are only as precise as the system timer. At the default 15.6 ms tick a
+// 1 ms wait costs a whole tick. Ask for 1 ms and opt out of power throttling (EcoQoS) for this process.
+void RequestPreciseTimerAndNoThrottling() {
+#ifdef _WIN32
+  using NtSetTimerResolutionFn = LONG(NTAPI*)(ULONG, BOOLEAN, PULONG);
+  if (HMODULE ntdll = GetModuleHandleW(L"ntdll.dll")) {
+    if (auto set_resolution = reinterpret_cast<NtSetTimerResolutionFn>(
+            GetProcAddress(ntdll, "NtSetTimerResolution"))) {
+      ULONG current = 0;
+      set_resolution(10000, TRUE, &current);  // 100 ns units: 1 ms.
+    }
+  }
+  PROCESS_POWER_THROTTLING_STATE state{};
+  state.Version = PROCESS_POWER_THROTTLING_CURRENT_VERSION;
+  state.ControlMask =
+      PROCESS_POWER_THROTTLING_EXECUTION_SPEED | PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION;
+  state.StateMask = 0;
+  SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &state, sizeof(state));
+#endif
+}
+
+}  // namespace
+
 // Static instance for global access
 Runtime* Runtime::instance_ = nullptr;
 
@@ -94,6 +123,14 @@ X_STATUS Runtime::Setup(RuntimeConfig config) {
     return X_STATUS_UNSUCCESSFUL;
   }
   instance_ = this;
+  RequestPreciseTimerAndNoThrottling();
+  // True VSync (REX_TRUE_VSYNC=1): the guest runs unlocked from the display and the presenter does the
+  // real VSync, so the frame rate follows the refresh rate without the guest waiting on vblank events.
+  if (const char* true_vsync = std::getenv("REX_TRUE_VSYNC"); true_vsync && true_vsync[0] == '1') {
+    cvar::SetFlagByName("true_vsync", "true");
+    cvar::SetFlagByName("guest_vblank_unlocked", "true");
+    cvar::SetFlagByName("vsync", "false");
+  }
 
   auto fail = [this](X_STATUS status, std::string_view reason) {
     REXSYS_ERROR("Runtime::Setup failed: {}", reason);
diff --git a/src/system/xmemory.cpp b/src/system/xmemory.cpp
index 76cc877..121f321 100644
--- a/src/system/xmemory.cpp
+++ b/src/system/xmemory.cpp
@@ -784,24 +784,58 @@ bool Memory::Restore(stream::ByteStream* stream) {
 // Recompiled Code Function Table
 //=============================================================================
 
-bool Memory::InitializeFunctionTable(uint32_t code_base, uint32_t code_size, uint32_t image_base,
+bool Memory::InitializeFunctionTable(uint32_t code_base, uint32_t code_size,
+                                     uint32_t image_base,
                                      uint32_t image_size) {
-  constexpr uint32_t kThunkReserveSize = runtime::FunctionDispatcher::kThunkReserveSize;
-  uint32_t table_base = image_base + image_size;
+  constexpr uint32_t kThunkReserveSize =
+      runtime::FunctionDispatcher::kThunkReserveSize;
+
   uint32_t table_size = (code_size + kThunkReserveSize) * 2;
+  uint32_t table_base = 0;
+
+  // FIFA Street fifadllzf.xex.dll.
+  // Generated indirect calls expect this module's function table
+  // immediately after the original XEX image.
+  if (code_base == 0x82610000) {
+    table_base = image_base + image_size;
+
+    REXSYS_DEBUG(
+        "FIFA_TABLE_FIX: forcing DLL function table at {:08X}",
+        table_base);
+
+    if (!heaps_.v80000000.AllocFixed(
+            table_base, table_size, 0x10000,
+            memory::kMemoryAllocationReserve |
+                memory::kMemoryAllocationCommit,
+            memory::kMemoryProtectRead |
+                memory::kMemoryProtectWrite)) {
+      REXSYS_ERROR(
+          "FIFA_TABLE_FIX: failed to allocate table at {:08X}",
+          table_base);
+      return false;
+    }
+  } else {
+    // Other modules use dynamically allocated function tables so they
+    // cannot overlap subsequent XEX images.
+    if (!heaps_.v80000000.Alloc(
+            table_size, 0x10000,
+            memory::kMemoryAllocationReserve |
+                memory::kMemoryAllocationCommit,
+            memory::kMemoryProtectRead |
+                memory::kMemoryProtectWrite,
+            true, &table_base)) {
+      REXSYS_ERROR(
+          "Failed to allocate function table, size {:08X}",
+          table_size);
+      return false;
+    }
+  }
 
   REXSYS_DEBUG(
       "Initializing function table at {:08X}, size {:08X} for code {:08X}-{:08X} "
       "(+{:08X} thunk reserve)",
-      table_base, table_size, code_base, code_base + code_size, kThunkReserveSize);
-
-  if (!heaps_.v80000000.AllocFixed(
-          table_base, table_size, 0x10000,
-          memory::kMemoryAllocationReserve | memory::kMemoryAllocationCommit,
-          memory::kMemoryProtectRead | memory::kMemoryProtectWrite)) {
-    REXSYS_ERROR("Failed to allocate function table at {:08X}", table_base);
-    return false;
-  }
+      table_base, table_size, code_base, code_base + code_size,
+      kThunkReserveSize);
 
   Zero(table_base, table_size);
 
@@ -821,28 +855,38 @@ bool Memory::DestroyFunctionTable(uint32_t code_base) {
   uint32_t table_size = 0;
   uint32_t logged_code_base = 0;
   uint32_t logged_code_size = 0;
+
   {
     std::lock_guard lock(function_tables_mutex_);
+
     auto it = std::find_if(
         function_tables_.begin(), function_tables_.end(),
-        [code_base](const FunctionTableEntry& entry) { return entry.code_base == code_base; });
+        [code_base](const FunctionTableEntry& entry) {
+          return entry.code_base == code_base;
+        });
+
     if (it == function_tables_.end()) {
       return false;
     }
+
     table_base = it->table_base;
-    table_size = (it->code_size + it->thunk_reserve) * 2;
+    table_size =
+        (it->code_size + it->thunk_reserve) * 2;
     logged_code_base = it->code_base;
     logged_code_size = it->code_size;
+
     function_tables_.erase(it);
   }
 
-  REXSYS_DEBUG("Destroying function table at {:08X}, size {:08X} for code {:08X}-{:08X}",
-               table_base, table_size, logged_code_base, logged_code_base + logged_code_size);
+  REXSYS_DEBUG(
+      "Destroying function table at {:08X}, size {:08X} for code {:08X}-{:08X}",
+      table_base, table_size,
+      logged_code_base,
+      logged_code_base + logged_code_size);
 
   heaps_.v80000000.Release(table_base);
   return true;
 }
-
 bool Memory::SetFunction(uint32_t guest_address, PPCFunc* host_function) {
   uint32_t table_address = 0;
   {
diff --git a/src/ui/CMakeLists.txt b/src/ui/CMakeLists.txt
index 5bd3dc5..e573a94 100644
--- a/src/ui/CMakeLists.txt
+++ b/src/ui/CMakeLists.txt
@@ -7,6 +7,7 @@ set(REXUI_CORE_SOURCES
     image_decode.cpp
     imgui_dialog.cpp
     imgui_drawer.cpp
+    game_ui_fonts.cpp
     immediate_drawer.cpp
     keybinds.cpp
     menu_item.cpp
diff --git a/src/ui/d3d12/d3d12_presenter.cpp b/src/ui/d3d12/d3d12_presenter.cpp
index 306118e..04cce26 100644
--- a/src/ui/d3d12/d3d12_presenter.cpp
+++ b/src/ui/d3d12/d3d12_presenter.cpp
@@ -11,7 +11,10 @@
 
 #include <algorithm>
 #include <climits>
+#include <atomic>
 #include <cmath>
+#include <thread>
+#include <chrono>
 #include <memory>
 #include <utility>
 
@@ -20,6 +23,9 @@
 #include <rex/logging.h>
 #include <rex/math.h>
 #include <rex/ui/d3d12/d3d12_presenter.h>
+
+#include <cmath>
+#include <vector>
 #include <rex/ui/d3d12/d3d12_provider.h>
 #include <rex/ui/d3d12/d3d12_util.h>
 #include <rex/ui/surface_win.h>
@@ -33,10 +39,19 @@
 REXCVAR_DEFINE_BOOL(d3d12_allow_variable_refresh_rate_and_tearing, true, "UI/D3D12",
                     "Allow variable refresh rate and tearing");
 
+// Without the tearing flag, flip-model presentation is gated by the display refresh and the readback fence waits,
+// which share the direct queue, each cost two refreshes (measured 33.5 ms per resolve at 60 Hz, 0.3 ms with it).
+// The game clock is paced separately, so presenting without waiting for the display does not change game speed.
+REXCVAR_DEFINE_BOOL(d3d12_paced_present_tearing, true, "UI/D3D12",
+                    "Create the swap chain with tearing support even when VRR is not requested, so presents do "
+                    "not throttle the direct queue (set to false to restore the old behaviour)");
+
 namespace rex::ui::d3d12 {
 
 // Generated with `xb buildshaders`.
 namespace shaders {
+
+
 #include "ui/shaders/bytecode/d3d12_5_1/guest_output_bilinear_dither_ps.h"
 #include "ui/shaders/bytecode/d3d12_5_1/guest_output_bilinear_ps.h"
 #if defined(REX_HAS_FIDELITYFX_SDK)
@@ -51,6 +66,50 @@ namespace shaders {
 #include "ui/shaders/bytecode/d3d12_5_1/guest_output_triangle_strip_rect_vs.h"
 }  // namespace shaders
 
+namespace {
+// True VSync flavour: "newest" (default) lets the game run free and shows its newest frame at each displayed
+// refresh; "locked" holds the game to the display in VdSwap (xboxkrnl_video.cpp).
+bool TrueVsyncNewest() {
+  static const bool newest = [] {
+    const char* mode = std::getenv("REX_TRUE_VSYNC_MODE");
+    return !(mode && std::strcmp(mode, "locked") == 0);
+  }();
+  return newest;
+}
+// True VSync in fullscreen uses DXGI exclusive fullscreen at the chosen refresh rate: with Adaptive Sync /
+// FreeSync on, a borderless window covering the monitor made the panel run at its maximum rate (~165 refreshes/s
+// with 60 Hz chosen) so frames stayed on screen for 2 or 3 refreshes. REX_TRUE_VSYNC_EXCLUSIVE=0 disables it.
+// Set when the display behaves as Adaptive Sync / FreeSync: it refreshes on its own fast grid (~165 Hz) while the
+// game shows 60 images, so a refresh-synchronized present lands on that grid (12/18 ms holds = judder). From then
+// on, True VSync presents immediately (tearing allowed) at the even clock rate: a VRR display starts a refresh when
+// the image arrives, so every image stays exactly one period on screen and nothing tears.
+std::atomic<bool> g_true_vsync_vrr{false};
+DXGI_MODE_DESC& TrueVsyncExclusiveMode() {
+  static DXGI_MODE_DESC mode = {};
+  return mode;
+}
+bool TrueVsyncExclusive() {
+  static const bool exclusive = [] {
+    const char* fullscreen = std::getenv("REX_FULLSCREEN");
+    const char* knob = std::getenv("REX_TRUE_VSYNC_EXCLUSIVE");
+    return fullscreen && std::strcmp(fullscreen, "true") == 0 && knob && knob[0] == '1';  // opt-in test knob
+  }();
+  return exclusive && REXCVAR_QUERY(bool, true_vsync);
+}
+// Refreshes each displayed image stays on screen: refresh rate / REX_TRUE_VSYNC_FPS (30 at 60 Hz = 2).
+UINT TrueVsyncInterval() {
+  static const UINT interval = [] {
+    const char* refresh_text = std::getenv("REX_VIDEO_MODE_REFRESH_RATE");
+    const char* fps_text = std::getenv("REX_TRUE_VSYNC_FPS");
+    const double refresh = refresh_text ? std::strtod(refresh_text, nullptr) : 0.0;
+    const double fps = fps_text ? std::strtod(fps_text, nullptr) : 0.0;
+    if (refresh <= 0.0 || fps <= 0.0) return UINT(1);
+    return UINT(std::clamp(std::lround(refresh / fps), 1L, 4L));
+  }();
+  return interval;
+}
+}  // namespace
+
 D3D12Presenter::~D3D12Presenter() {
   // Await completion of the usage of everything before destroying anything.
   // From most likely the latest to most likely the earliest to be signaled, so
@@ -363,7 +422,9 @@ D3D12Presenter::ConnectOrReconnectPaintingToSurfaceFromUIThread(Surface& new_sur
     }
     bool swap_chain_resized = SUCCEEDED(paint_context_.swap_chain->ResizeBuffers(
         0, UINT(new_swap_chain_width), UINT(new_swap_chain_height), DXGI_FORMAT_UNKNOWN,
-        paint_context_.swap_chain_allows_tearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0));
+        (paint_context_.swap_chain_allows_tearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0) |
+            (paint_context_.swap_chain_latency_waitable
+                 ? DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT : 0)));
     if (swap_chain_resized) {
       for (uint32_t i = 0; i < PaintContext::kSwapChainBufferCount; ++i) {
         if (FAILED(paint_context_.swap_chain->GetBuffer(
@@ -408,13 +469,20 @@ D3D12Presenter::ConnectOrReconnectPaintingToSurfaceFromUIThread(Surface& new_sur
     swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
     swap_chain_desc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
     swap_chain_desc.Flags = 0;
-    if (REXCVAR_GET(d3d12_allow_variable_refresh_rate_and_tearing) && dxgi_supports_tearing_) {
+    if ((REXCVAR_GET(d3d12_allow_variable_refresh_rate_and_tearing) ||
+         REXCVAR_GET(d3d12_paced_present_tearing) || REXCVAR_QUERY(bool, true_vsync)) &&
+        dxgi_supports_tearing_) {
       // Allow tearing in borderless fullscreen to support variable refresh
       // rate.
       swap_chain_desc.Flags |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
     }
+    if (REXCVAR_QUERY(bool, true_vsync)) {
+      swap_chain_desc.Flags |= DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
+    }
     IDXGIFactory2* dxgi_factory = provider_.GetDXGIFactory();
-    ID3D12CommandQueue* direct_queue = provider_.GetDirectQueue();
+    ID3D12CommandQueue* direct_queue = paint_context_.present_queue
+                                           ? paint_context_.present_queue.Get()
+                                           : provider_.GetDirectQueue();
     Microsoft::WRL::ComPtr<IDXGISwapChain1> swap_chain_1;
     switch (surface_type) {
 #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_GAMES)
@@ -450,6 +518,76 @@ D3D12Presenter::ConnectOrReconnectPaintingToSurfaceFromUIThread(Surface& new_sur
     paint_context_.swap_chain_height = new_swap_chain_height;
     paint_context_.swap_chain_allows_tearing =
         (swap_chain_desc.Flags & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING) != 0;
+    if (swap_chain_desc.Flags & DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT) {
+      paint_context_.swap_chain->SetMaximumFrameLatency(1);
+      paint_context_.swap_chain_latency_waitable =
+          paint_context_.swap_chain->GetFrameLatencyWaitableObject();
+      // VdSwap waits on it so the game is clocked by the display refresh (see xboxkrnl_video.cpp).
+      char handle_text[32];
+      snprintf(handle_text, sizeof(handle_text), "%llx",
+               (unsigned long long)(uintptr_t)paint_context_.swap_chain_latency_waitable);
+      SetEnvironmentVariableA("REX_TRUE_VSYNC_WAITABLE", handle_text);
+    }
+    if (TrueVsyncExclusive()) {
+      Microsoft::WRL::ComPtr<IDXGIOutput> output;
+      const char* refresh_text = std::getenv("REX_VIDEO_MODE_REFRESH_RATE");
+      const UINT refresh = refresh_text ? UINT(std::strtoul(refresh_text, nullptr, 10)) : 0;
+      if (refresh && SUCCEEDED(paint_context_.swap_chain->GetContainingOutput(&output))) {
+        DXGI_MODE_DESC wanted = {};
+        wanted.Width = UINT(new_swap_chain_width);
+        wanted.Height = UINT(new_swap_chain_height);
+        wanted.RefreshRate = {refresh, 1};
+        wanted.Format = kSwapChainFormat;
+        // Pick the monitor's own mode with this size and the refresh rate closest to the chosen one.
+        DXGI_MODE_DESC mode = {};
+        UINT mode_count = 0;
+        HRESULT hr = output->GetDisplayModeList(wanted.Format, 0, &mode_count, nullptr);
+        std::vector<DXGI_MODE_DESC> modes(mode_count);
+        if (SUCCEEDED(hr) && mode_count) hr = output->GetDisplayModeList(wanted.Format, 0, &mode_count, modes.data());
+        double best_error = 1e9;
+        for (UINT m = 0; SUCCEEDED(hr) && m < mode_count; ++m) {
+          const DXGI_MODE_DESC& candidate = modes[m];
+          if (candidate.Width != wanted.Width || candidate.Height != wanted.Height || !candidate.RefreshRate.Denominator) {
+            continue;
+          }
+          const double error = std::abs(double(candidate.RefreshRate.Numerator) / candidate.RefreshRate.Denominator -
+                                        double(refresh));
+          if (error < best_error) {
+            best_error = error;
+            mode = candidate;
+          }
+        }
+        if (SUCCEEDED(hr) && best_error > 1.0) hr = DXGI_ERROR_NOT_FOUND;
+        // Enter exclusive fullscreen first, then set the mode: ResizeTarget before it only resizes the window.
+        // Windows only grants it to the foreground window (DXGI_ERROR_NOT_CURRENTLY_AVAILABLE while the game
+        // window is still coming up): bring it to the front and retry for up to 3 s.
+        HWND hwnd = nullptr;
+        paint_context_.swap_chain->GetHwnd(&hwnd);
+        for (int attempt = 0; SUCCEEDED(hr) && attempt < 30; ++attempt) {
+          const HRESULT fullscreen_hr = paint_context_.swap_chain->SetFullscreenState(TRUE, output.Get());
+          if (fullscreen_hr != DXGI_ERROR_NOT_CURRENTLY_AVAILABLE) {
+            hr = fullscreen_hr;
+            break;
+          }
+          hr = fullscreen_hr;
+          if (hwnd) SetForegroundWindow(hwnd);
+          Sleep(100);
+          hr = S_OK;
+          if (attempt == 29) hr = fullscreen_hr;
+        }
+        if (SUCCEEDED(hr)) hr = paint_context_.swap_chain->ResizeTarget(&mode);
+        if (SUCCEEDED(hr)) TrueVsyncExclusiveMode() = mode;
+        if (SUCCEEDED(hr)) {
+          hr = paint_context_.swap_chain->ResizeBuffers(0, UINT(new_swap_chain_width), UINT(new_swap_chain_height),
+                                                        DXGI_FORMAT_UNKNOWN, swap_chain_desc.Flags);
+        }
+        paint_context_.swap_chain_exclusive = SUCCEEDED(hr);
+        REXLOG_INFO("D3D12Presenter: True VSync exclusive fullscreen {}x{} @ {:.2f} Hz: {}", mode.Width, mode.Height,
+                    mode.RefreshRate.Denominator ? double(mode.RefreshRate.Numerator) / mode.RefreshRate.Denominator : 0.0,
+                    SUCCEEDED(hr) ? "on" : "failed");
+        if (FAILED(hr)) REXLOG_WARN("D3D12Presenter: exclusive fullscreen error 0x{:08X} ({} modes)", uint32_t(hr), mode_count);
+      }
+    }
     for (uint32_t i = 0; i < PaintContext::kSwapChainBufferCount; ++i) {
       if (FAILED(paint_context_.swap_chain->GetBuffer(
               i, IID_PPV_ARGS(&paint_context_.swap_chain_buffers[i])))) {
@@ -478,7 +616,11 @@ D3D12Presenter::ConnectOrReconnectPaintingToSurfaceFromUIThread(Surface& new_sur
         provider_.OffsetRTVDescriptor(rtv_heap_start, PaintContext::kRTVIndexSwapChainBuffer0 + i));
   }
 
-  is_vsync_implicit_out = false;
+  // True VSync presents with interval 0 (no CPU wait), so it must keep painting from the guest output thread.
+  // True VSync paints on the UI thread, once per display refresh, the newest guest frame (triple buffering):
+  // the GPU thread and the game never wait for the display.
+  is_vsync_implicit_out =
+      REXCVAR_QUERY(bool, vsync) || (REXCVAR_QUERY(bool, true_vsync) && TrueVsyncNewest());
   return SurfacePaintConnectResult::kSuccess;
 }
 
@@ -548,13 +690,66 @@ void D3D12Presenter::PaintContext::DestroySwapChain() {
   for (Microsoft::WRL::ComPtr<ID3D12Resource>& swap_chain_buffer_ref : swap_chain_buffers) {
     swap_chain_buffer_ref.Reset();
   }
+  if (swap_chain_exclusive) {
+    swap_chain->SetFullscreenState(FALSE, nullptr);  // a swap chain must leave exclusive fullscreen before release
+    swap_chain_exclusive = false;
+  }
   swap_chain.Reset();
   swap_chain_allows_tearing = false;
+  if (swap_chain_latency_waitable) {
+    SetEnvironmentVariableA("REX_TRUE_VSYNC_WAITABLE", nullptr);
+    CloseHandle(swap_chain_latency_waitable);
+    swap_chain_latency_waitable = nullptr;
+  }
   swap_chain_height = 0;
   swap_chain_width = 0;
 }
 
 Presenter::PaintResult D3D12Presenter::PaintAndPresentImpl(bool execute_ui_drawers) {
+  // True VSync: wait (on the UI thread) until the display has taken the previous frame, then paint whatever
+  // guest frame is newest at that moment, so each refresh shows the latest image and none is queued stale.
+  // Exclusive fullscreen is left on Alt+Tab: take it back once the game window is in front again.
+  if (paint_context_.swap_chain_exclusive) {
+    static uint32_t paint_count = 0;
+    if (++paint_count % 60 == 0) {
+      BOOL fullscreen = FALSE;
+      HWND hwnd = nullptr;
+      paint_context_.swap_chain->GetHwnd(&hwnd);
+      if (SUCCEEDED(paint_context_.swap_chain->GetFullscreenState(&fullscreen, nullptr)) && !fullscreen && hwnd &&
+          GetForegroundWindow() == hwnd && !IsIconic(hwnd) &&
+          SUCCEEDED(paint_context_.swap_chain->SetFullscreenState(TRUE, nullptr))) {
+        paint_context_.swap_chain->ResizeTarget(&TrueVsyncExclusiveMode());
+        REXLOG_INFO("D3D12Presenter: True VSync exclusive fullscreen restored");
+      }
+    }
+  }
+  if (paint_context_.swap_chain_latency_waitable && TrueVsyncNewest()) {
+    WaitForSingleObject(paint_context_.swap_chain_latency_waitable, 100);
+    // Also present on an even clock at the chosen rate: with Adaptive Sync / FreeSync the display shows each
+    // frame as soon as it arrives, so uneven present times (18-23 ms gaps measured) were visible as judder.
+    // On a fixed-refresh display the refresh wait above dominates and this changes nothing.
+    static const double present_hz = [] {
+      const char* refresh_text = std::getenv("REX_VIDEO_MODE_REFRESH_RATE");
+      const double refresh = refresh_text ? std::strtod(refresh_text, nullptr) : 0.0;
+      return refresh > 0.0 ? refresh / double(TrueVsyncInterval()) : 0.0;
+    }();
+    if (present_hz > 0.0) {
+      using Clock = std::chrono::steady_clock;
+      static Clock::time_point next{};
+      const auto period = std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double>(1.0 / present_hz));
+      auto now = Clock::now();
+      if (next == Clock::time_point{} || now - next > period * 2) next = now;
+      if (now < next) {
+        if (next - now > std::chrono::milliseconds(2)) {
+          std::this_thread::sleep_for(next - now - std::chrono::milliseconds(1));
+        }
+        while (Clock::now() < next) YieldProcessor();
+      }
+      next += period;
+    }
+  }
+  // True VSync: when the display has not taken the queued frames yet, skip this paint (the next one shows
+  // the newest guest frame) instead of waiting; also keeps the back buffer written here off the screen.
   // Begin the command list with the command allocator not currently potentially
   // used on the GPU.
   UINT64 current_paint_submission = paint_context_.paint_submission_tracker.GetCurrentSubmission();
@@ -1142,7 +1337,15 @@ Presenter::PaintResult D3D12Presenter::PaintAndPresentImpl(bool execute_ui_drawe
   // Execute and present.
   command_list->Close();
   ID3D12CommandList* execute_command_list = command_list;
-  provider_.GetDirectQueue()->ExecuteCommandLists(1, &execute_command_list);
+  if (paint_context_.present_queue) {
+    // The guest output was written on the direct queue: paint only after that work is done.
+    const UINT64 fence_value = ++paint_context_.present_queue_direct_fence_value;
+    provider_.GetDirectQueue()->Signal(paint_context_.present_queue_direct_fence.Get(), fence_value);
+    paint_context_.present_queue->Wait(paint_context_.present_queue_direct_fence.Get(), fence_value);
+    paint_context_.present_queue->ExecuteCommandLists(1, &execute_command_list);
+  } else {
+    provider_.GetDirectQueue()->ExecuteCommandLists(1, &execute_command_list);
+  }
   if (execute_ui_drawers) {
     ui_submission_tracker_.NextSubmission();
   }
@@ -1155,13 +1358,80 @@ Presenter::PaintResult D3D12Presenter::PaintAndPresentImpl(bool execute_ui_drawe
   // fullscreen is ever used in, the allow tearing flag must not be passed in
   // fullscreen, but DXGI fullscreen is largely unneeded with the flip
   // presentation model used in Direct3D 12).
-  HRESULT present_result = paint_context_.swap_chain->Present(
-      0, DXGI_PRESENT_RESTART |
-             (paint_context_.swap_chain_allows_tearing ? DXGI_PRESENT_ALLOW_TEARING : 0));
+  // True VSync: sync interval 0 without ALLOW_TEARING on a flip swap chain shows the newest frame at the next
+  // refresh without tearing and without blocking the queue (Present(1) blocked it and dropped the game to 1-3 FPS).
+  // True VSync presents with sync interval 1 on its own present queue: every frame is shown exactly once
+  // (interval 0 discarded about one frame per second = visible jumps), and the refresh wait stays on that queue.
+  const bool presentation_vsync =
+      REXCVAR_QUERY(bool, true_vsync) ? paint_context_.present_queue != nullptr : REXCVAR_QUERY(bool, vsync);
+  const bool vrr_present = REXCVAR_QUERY(bool, true_vsync) && paint_context_.swap_chain_allows_tearing &&
+                           !paint_context_.swap_chain_exclusive && g_true_vsync_vrr.load(std::memory_order_relaxed);
+  const bool allow_tearing =
+      paint_context_.swap_chain_allows_tearing && (!REXCVAR_QUERY(bool, true_vsync) || vrr_present);
+  HRESULT present_result = vrr_present
+      ? paint_context_.swap_chain->Present(0, DXGI_PRESENT_ALLOW_TEARING)
+      : paint_context_.swap_chain->Present(
+            presentation_vsync ? (REXCVAR_QUERY(bool, true_vsync) ? TrueVsyncInterval() : 1) : 0,
+            presentation_vsync ? 0 : (DXGI_PRESENT_RESTART | (allow_tearing ? DXGI_PRESENT_ALLOW_TEARING : 0)));
   // Even if presentation has failed, work might have been enqueued anyway
   // internally before the failure according to Jesse Natalie from the DirectX
   // Discord server.
   paint_context_.present_submission_tracker.NextSubmission();
+  if (FAILED(present_result)) {
+    REXLOG_ERROR("D3D12Presenter: Present failed with 0x{:08X} (true_vsync={}, interval={})",
+                 uint32_t(present_result), REXCVAR_QUERY(bool, true_vsync), TrueVsyncInterval());
+  }
+  if (REXCVAR_QUERY(bool, true_vsync)) {
+    // Diagnostics: what the display really showed, once per second. "refreshes" = vblanks that passed,
+    // "shown" = new images flipped on screen, "repeats" = refreshes that showed an old image again (stutter).
+    static uint64_t window_start_ms = 0, presents = 0, stats_fail = 0;
+    static UINT first_present_count = 0, first_refresh_count = 0;
+    static bool have_first = false;
+    static uint64_t last_qpc_shown = 0, max_gap_us = 0;
+    static UINT last_present_count = 0;
+    ++presents;
+    DXGI_FRAME_STATISTICS st = {};
+    LARGE_INTEGER freq;
+    QueryPerformanceFrequency(&freq);
+    if (SUCCEEDED(paint_context_.swap_chain->GetFrameStatistics(&st))) {
+      if (!have_first) {
+        first_present_count = st.PresentCount;
+        first_refresh_count = st.SyncRefreshCount;
+        have_first = true;
+      }
+      if (st.PresentCount != last_present_count) {
+        const uint64_t qpc = uint64_t(st.SyncQPCTime.QuadPart);
+        if (last_qpc_shown && qpc > last_qpc_shown) {
+          max_gap_us = std::max(max_gap_us, (qpc - last_qpc_shown) * 1000000ull / uint64_t(freq.QuadPart));
+        }
+        last_qpc_shown = qpc;
+        last_present_count = st.PresentCount;
+      }
+    } else {
+      ++stats_fail;
+    }
+    const uint64_t now_ms = GetTickCount64();
+    if (!window_start_ms) window_start_ms = now_ms;
+    if (now_ms - window_start_ms >= 1000) {
+      const UINT shown = have_first ? st.PresentCount - first_present_count : 0;
+      const UINT refreshes = have_first ? st.SyncRefreshCount - first_refresh_count : 0;
+      REXLOG_INFO("TrueVsyncDisplay: presents={} refreshes={} shown={} repeats={} max_gap_ms={:.1f} stats_fail={} vrr={}",
+                  presents, refreshes, shown, refreshes > shown ? refreshes - shown : 0,
+                  double(max_gap_us) / 1000.0, stats_fail, g_true_vsync_vrr.load());
+      // Two windows in a row where the display refreshed far more often than it got images, none lost:
+      // Adaptive Sync / FreeSync grid (see g_true_vsync_vrr).
+      static int vrr_windows = 0;
+      const bool vrr_like = presents >= 20 && stats_fail == 0 && shown + 2 >= presents &&
+                            refreshes * 2 >= shown * 3;
+      vrr_windows = vrr_like ? vrr_windows + 1 : 0;
+      if (vrr_windows >= 2 && !g_true_vsync_vrr.exchange(true)) {
+        REXLOG_INFO("True VSync: Adaptive Sync / FreeSync display detected, presenting on the even clock");
+      }
+      window_start_ms = now_ms;
+      presents = stats_fail = max_gap_us = 0;
+      have_first = false;
+    }
+  }
   switch (present_result) {
     case DXGI_ERROR_DEVICE_REMOVED:
       return PaintResult::kGpuLostExternally;
@@ -1442,6 +1712,20 @@ bool D3D12Presenter::InitializeSurfaceIndependent() {
   // Initialize connection-independent parts of the painting context.
 
   ID3D12CommandQueue* direct_queue = provider_.GetDirectQueue();
+  if (REXCVAR_QUERY(bool, true_vsync)) {
+    D3D12_COMMAND_QUEUE_DESC present_queue_desc = {};
+    present_queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
+    if (SUCCEEDED(device->CreateCommandQueue(&present_queue_desc,
+                                             IID_PPV_ARGS(&paint_context_.present_queue))) &&
+        SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE,
+                                      IID_PPV_ARGS(&paint_context_.present_queue_direct_fence)))) {
+      direct_queue = paint_context_.present_queue.Get();
+      REXLOG_INFO("D3D12Presenter: True VSync uses a separate presentation queue");
+    } else {
+      paint_context_.present_queue.Reset();
+      paint_context_.present_queue_direct_fence.Reset();
+    }
+  }
 
   // Paint submission trackers.
   if (!paint_context_.paint_submission_tracker.Initialize(device, direct_queue) ||
@@ -1501,7 +1785,7 @@ bool D3D12Presenter::InitializeSurfaceIndependent() {
     return false;
   }
 
-  if (!guest_output_resource_refresher_submission_tracker_.Initialize(device, direct_queue)) {
+  if (!guest_output_resource_refresher_submission_tracker_.Initialize(device, provider_.GetDirectQueue())) {
     return false;
   }
 
diff --git a/src/ui/d3d12/d3d12_provider.cpp b/src/ui/d3d12/d3d12_provider.cpp
index bf8252b..8175193 100644
--- a/src/ui/d3d12/d3d12_provider.cpp
+++ b/src/ui/d3d12/d3d12_provider.cpp
@@ -19,6 +19,7 @@
 #include <rex/ui/d3d12/d3d12_provider.h>
 
 #include <malloc.h>
+#include <wrl/client.h>
 
 REXCVAR_DEFINE_BOOL(d3d12_debug, false, "UI/D3D12", "Enable Direct3D 12 and DXGI debug layer")
     .lifecycle(rex::cvar::Lifecycle::kInitOnly);
@@ -351,6 +352,21 @@ bool D3D12Provider::Initialize() {
     if (REXCVAR_GET(d3d12_break_on_warning)) {
       d3d12_info_queue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, TRUE);
     }
+    // With the debug layer on, write its warnings and errors to the game log (no debugger needed).
+    Microsoft::WRL::ComPtr<ID3D12InfoQueue1> d3d12_info_queue_1;
+    if (debug && SUCCEEDED(d3d12_info_queue->QueryInterface(IID_PPV_ARGS(&d3d12_info_queue_1)))) {
+      DWORD cookie = 0;
+      d3d12_info_queue_1->RegisterMessageCallback(
+          [](D3D12_MESSAGE_CATEGORY, D3D12_MESSAGE_SEVERITY severity, D3D12_MESSAGE_ID id,
+             LPCSTR description, void*) {
+            if (severity <= D3D12_MESSAGE_SEVERITY_WARNING) {
+              REXLOG_ERROR("D3D12 debug layer (severity {}, id {}): {}", int(severity), int(id),
+                           description ? description : "");
+            }
+          },
+          D3D12_MESSAGE_CALLBACK_FLAG_NONE, nullptr, &cookie);
+      REXLOG_INFO("D3D12 debug layer messages are written to this log");
+    }
     d3d12_info_queue->Release();
   }
 
diff --git a/src/ui/game_ui_fonts.cpp b/src/ui/game_ui_fonts.cpp
new file mode 100644
index 0000000..e637829
--- /dev/null
+++ b/src/ui/game_ui_fonts.cpp
@@ -0,0 +1,162 @@
+// Loads the game's own UI fonts (the TrueType files stored in data0.big) so that the overlays
+// drawn by the runtime use exactly the lettering of the original menus.
+//
+// data0.big is a BIG4 archive; the font entries are "chunklzx" blobs (Xbox 360 LZX):
+//   'chunklzx', version, total size, chunk size, chunk count, ..., then per chunk an 8-byte
+//   header (u32 compressed size, u32 3) followed by 32 KB LZX frames. Frames are
+//   [u16 size] (full frame) or [0xFF][u16 usize][u16 csize] (short last frame); the frame
+//   headers are not part of the LZX bitstream.
+
+#include <imgui.h>
+
+#include <rex/logging.h>
+#include <rex/system/lzx.h>
+#include <rex/ui/guide_font.h>
+
+#include <cstdint>
+#include <cstdio>
+#include <cstring>
+#include <filesystem>
+#include <string>
+#include <vector>
+
+namespace rex::ui {
+
+ImFont* g_guide_font = nullptr;
+ImFont* g_guide_font_light = nullptr;
+
+namespace {
+
+uint32_t Be32(const uint8_t* p) {
+  return (uint32_t(p[0]) << 24) | (uint32_t(p[1]) << 16) | (uint32_t(p[2]) << 8) | p[3];
+}
+uint32_t Le32(const uint8_t* p) {
+  return (uint32_t(p[3]) << 24) | (uint32_t(p[2]) << 16) | (uint32_t(p[1]) << 8) | p[0];
+}
+uint16_t Be16(const uint8_t* p) { return uint16_t((p[0] << 8) | p[1]); }
+
+bool ReadAt(FILE* file, uint64_t offset, void* out, size_t size) {
+  if (_fseeki64(file, static_cast<long long>(offset), SEEK_SET) != 0) return false;
+  return std::fread(out, 1, size, file) == size;
+}
+
+bool DecompressChunkLzx(const std::vector<uint8_t>& data, std::vector<uint8_t>& out) {
+  if (data.size() < 48 || std::memcmp(data.data(), "chunklzx", 8) != 0) return false;
+  const uint32_t total = Be32(&data[12]);
+  const uint32_t chunk_size = Be32(&data[16]);
+  if (!total || !chunk_size || total > (64u << 20)) return false;
+  out.assign(total, 0);
+  size_t produced = 0;
+  size_t header = 40;
+  while (produced < total) {
+    if (header + 8 > data.size()) return false;
+    const uint32_t csize = Be32(&data[header]);
+    const size_t start = header + 8;
+    const size_t want = std::min<size_t>(chunk_size, total - produced);
+    std::vector<uint8_t> payload;
+    size_t pos = start, got = 0;
+    while (got < want) {
+      if (pos + 2 > data.size()) return false;
+      uint32_t usize = 32768, size;
+      size_t body;
+      if (data[pos] == 0xFF) {
+        if (pos + 5 > data.size()) return false;
+        usize = Be16(&data[pos + 1]);
+        size = Be16(&data[pos + 3]);
+        body = pos + 5;
+      } else {
+        size = Be16(&data[pos]);
+        body = pos + 2;
+      }
+      if (body + size > data.size()) return false;
+      payload.insert(payload.end(), data.begin() + body, data.begin() + body + size);
+      pos = body + size;
+      got += std::min<size_t>(usize, want - got);
+    }
+    if (lzx_decompress(payload.data(), payload.size(), out.data() + produced, want, 1u << 17,
+                       nullptr, 0) != 0) {
+      return false;
+    }
+    produced += want;
+    if (produced >= total) break;
+    // The next chunk header is (u32 size, u32 3) shortly after this chunk's data.
+    size_t next = 0;
+    for (size_t p = std::max(start + csize, start + 16) - 16; p < std::min(data.size() - 8, start + csize + 96);
+         ++p) {
+      if (data[p] == 0 && Be32(&data[p + 4]) == 3) {
+        const uint32_t size = Be32(&data[p]);
+        if (size > 0 && size <= data.size() - p - 8) {
+          next = p;
+          if (p + 4 >= start + csize) break;
+        }
+      }
+    }
+    if (!next) return false;
+    header = next;
+  }
+  return true;
+}
+
+// Finds `wanted` (lowercase file name suffix) in a BIG4 archive and returns its raw bytes.
+bool ReadBigEntry(FILE* file, const std::string& wanted, std::vector<uint8_t>& out) {
+  uint8_t head[16];
+  if (!ReadAt(file, 0, head, sizeof(head)) || std::memcmp(head, "BIG4", 4) != 0) return false;
+  const uint32_t count = Be32(&head[8]);
+  const uint32_t header_size = Be32(&head[12]);
+  if (header_size < 16 || header_size > (64u << 20)) return false;
+  std::vector<uint8_t> table(header_size - 16);
+  if (!ReadAt(file, 16, table.data(), table.size())) return false;
+  size_t p = 0;
+  for (uint32_t i = 0; i < count && p + 9 <= table.size(); ++i) {
+    const uint32_t offset = Be32(&table[p]);
+    const uint32_t size = Be32(&table[p + 4]);
+    p += 8;
+    size_t end = p;
+    while (end < table.size() && table[end]) ++end;
+    std::string name(reinterpret_cast<const char*>(&table[p]), end - p);
+    p = end + 1;
+    for (char& c : name) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
+    if (name == wanted) {
+      out.resize(size);
+      return ReadAt(file, offset, out.data(), size);
+    }
+  }
+  return false;
+}
+
+ImFont* AddFont(ImFontAtlas* atlas, FILE* big, const char* entry, float pixels) {
+  std::vector<uint8_t> raw, ttf;
+  if (!ReadBigEntry(big, entry, raw) || !DecompressChunkLzx(raw, ttf)) {
+    REXLOG_WARN("Game UI font {} could not be loaded", entry);
+    return nullptr;
+  }
+  void* copy = ImGui::MemAlloc(ttf.size());  // owned by the atlas
+  std::memcpy(copy, ttf.data(), ttf.size());
+  static const ImWchar ranges[] = {0x0020, 0x017F, 0};  // Latin, accents (ES/FR/DE/IT/PT)
+  ImFontConfig config;
+  config.OversampleH = config.OversampleV = 2;
+  return atlas->AddFontFromMemoryTTF(copy, static_cast<int>(ttf.size()), pixels, &config, ranges);
+}
+
+}  // namespace
+
+void LoadGameUiFonts(ImFontAtlas* atlas, const std::filesystem::path& game_data_root) {
+  const auto archive = game_data_root / "data0.big";
+  FILE* big = nullptr;
+#if defined(_WIN32)
+  _wfopen_s(&big, archive.c_str(), L"rb");
+#else
+  big = std::fopen(archive.string().c_str(), "rb");
+#endif
+  if (!big) {
+    REXLOG_WARN("Game UI fonts: {} not found", archive.string());
+    return;
+  }
+  g_guide_font = AddFont(atlas, big, "data/ui/fonts/fs4_cn_bold.ttf", 48.0f);
+  g_guide_font_light = AddFont(atlas, big, "data/ui/fonts/fs4_cn_regular.ttf", 48.0f);
+  std::fclose(big);
+  REXLOG_INFO("Game UI fonts loaded: bold={} regular={}", g_guide_font != nullptr,
+              g_guide_font_light != nullptr);
+}
+
+}  // namespace rex::ui
diff --git a/src/ui/imgui_drawer.cpp b/src/ui/imgui_drawer.cpp
index f270f3c..3dd2055 100644
--- a/src/ui/imgui_drawer.cpp
+++ b/src/ui/imgui_drawer.cpp
@@ -18,15 +18,20 @@
 #include <rex/chrono/clock.h>
 #include <rex/logging.h>
 #include <rex/ui/imgui_dialog.h>
+#include <rex/cvar.h>
+#include <rex/ui/guide_font.h>
 #include <rex/ui/imgui_drawer.h>
 #include <rex/ui/ui_event.h>
 #include <rex/ui/window.h>
 
 #include <imgui.h>
 
+REXCVAR_DECLARE(std::string, game_data_root);
+
 namespace rex {
 namespace ui {
 
+
 // File: 'ProggyTiny.ttf' (35656 bytes)
 // Exported using binary_to_compressed_c.cpp
 const char kProggyTinyCompressedDataBase85[10950 + 1] =
@@ -197,10 +202,34 @@ void ImGuiDrawer::Initialize() {
   }
 #endif
 
+
   if (font_setup_) {
     font_setup_(io.Fonts);
   }
 
+  // The game's own UI fonts, read from its data archive.
+  if (!g_guide_font) {
+    const std::string root = REXCVAR_GET(game_data_root);
+    if (!root.empty()) LoadGameUiFonts(io.Fonts, std::filesystem::path(root));
+  }
+
+  // Without the game's fonts, fall back to a heavy system face.
+  if (!g_guide_font) {
+#if REX_PLATFORM_WIN32
+  // Display font for the guide: a heavy condensed face close to the game's UI.
+  for (const char* candidate :
+       {"C:\\Windows\\Fonts\\impact.ttf", "C:\\Windows\\Fonts\\arialbd.ttf"}) {
+    if (std::filesystem::exists(candidate)) {
+      ImFontConfig guide_config;
+      guide_config.OversampleH = 2;
+      guide_config.OversampleV = 2;
+      g_guide_font = io.Fonts->AddFontFromFileTTF(candidate, 32.0f, &guide_config, font_glyph_ranges);
+      break;
+    }
+  }
+#endif
+  }
+
   auto& style = ImGui::GetStyle();
   ApplyDefaultStyle(style);
   if (style_setup_) {
diff --git a/src/ui/keybinds.cpp b/src/ui/keybinds.cpp
index 9822f3b..604936b 100644
--- a/src/ui/keybinds.cpp
+++ b/src/ui/keybinds.cpp
@@ -209,6 +209,7 @@ void UnregisterBind(std::string_view name) {
 }
 
 bool ProcessKeyEvent(KeyEvent& e) {
+  if (e.prev_state()) return false;  // Toggle once per press, never on keyboard repeat.
   std::lock_guard lock(g_binds_mutex);
   for (auto& entry : g_binds) {
     if (!entry.callback)
diff --git a/src/ui/overlay/debug_overlay.cpp b/src/ui/overlay/debug_overlay.cpp
index 43d6c06..f133df8 100644
--- a/src/ui/overlay/debug_overlay.cpp
+++ b/src/ui/overlay/debug_overlay.cpp
@@ -10,8 +10,13 @@
  *              See LICENSE file in the project root for full license text.
  */
 #include <rex/ui/overlay/debug_overlay.h>
+#include <rex/ui/guide_font.h>
 #include <rex/version.h>
 #include <imgui.h>
+#include <algorithm>
+#include <chrono>
+#include <cstdio>
+#include <cstdlib>
 #ifdef REXGLUE_ENABLE_PERF_COUNTERS
 #include <rex/perf/counter.h>
 #include <cinttypes>
@@ -25,84 +30,102 @@ DebugOverlayDialog::DebugOverlayDialog(ImGuiDrawer* imgui_drawer, FrameStatsProv
 DebugOverlayDialog::~DebugOverlayDialog() {}
 
 void DebugOverlayDialog::OnDraw(ImGuiIO& io) {
-  ImGui::SetNextWindowPos(ImVec2(10, 10), ImGuiCond_FirstUseEver);
+  // Small FPS counter in the top-left corner (toggled with Home). It replaces the old
+  // statistics panel: one coloured line on a translucent background.
+  (void)io;
+  double fps = 0.0;
 #ifdef REXGLUE_ENABLE_PERF_COUNTERS
-  ImGui::SetNextWindowSize(ImVec2(280, 280), ImGuiCond_FirstUseEver);
-#else
-  ImGui::SetNextWindowSize(ImVec2(220, 60), ImGuiCond_FirstUseEver);
+  // Recent average over the last guest frames (same source the old statistics panel used).
+  const auto frame_time_us = rex::perf::GetSnapshotCounter(rex::perf::CounterId::kFrameTimeUs);
+  const float frame_time_ms = static_cast<float>(frame_time_us) / 1000.0f;
+  const auto guest_frame = rex::perf::GetSnapshotCounter(rex::perf::CounterId::kFrameNumber);
+  if (guest_frame != last_guest_frame_ && frame_time_ms > 0.0f) {
+    last_guest_frame_ = guest_frame;
+    frame_time_history_[frame_history_idx_] = frame_time_ms;
+    frame_history_idx_ = (frame_history_idx_ + 1) % kFrameHistorySize;
+    frame_history_count_ = std::min(frame_history_count_ + 1, kFrameHistorySize);
+  }
+  float total_ms = 0.0f;
+  for (size_t i = 0; i < frame_history_count_; ++i) total_ms += frame_time_history_[i];
+  if (total_ms > 0.0f) fps = 1000.0 * frame_history_count_ / total_ms;
 #endif
-  ImGui::SetNextWindowBgAlpha(0.5f);
-  if (ImGui::Begin("Debug##overlay", nullptr, ImGuiWindowFlags_NoCollapse)) {
-    if (stats_provider_) {
-      auto stats = stats_provider_();
-      if (stats.frame_count > 0) {
-        ImGui::Text("Guest: %.1f FPS (%.2f ms)", stats.fps, stats.frame_time_ms);
-      }
+  // True VSync: the game renders more images than the display shows; count displayed ones (this overlay is
+  // drawn once per displayed image), the same number GPU driver overlays (AMD, NVIDIA) report.
+  static const bool true_vsync = [] {
+    const char* on = std::getenv("REX_TRUE_VSYNC");
+    return on && on[0] == '1';
+  }();
+  if (true_vsync) {
+    using Clock = std::chrono::steady_clock;
+    static Clock::time_point window_start = Clock::now();
+    static uint32_t draws = 0;
+    static double shown_fps = 0.0;
+    ++draws;
+    const double elapsed = std::chrono::duration<double>(Clock::now() - window_start).count();
+    if (elapsed >= 0.5) {
+      shown_fps = draws / elapsed;
+      draws = 0;
+      window_start = Clock::now();
     }
-#ifdef REXGLUE_ENABLE_PERF_COUNTERS
-    ImGui::Separator();
-
-    // Frame time graph
-    auto ft_us = rex::perf::GetSnapshotCounter(rex::perf::CounterId::kFrameTimeUs);
-    float ft_ms = static_cast<float>(ft_us) / 1000.0f;
-    frame_time_history_[frame_history_idx_] = ft_ms;
-    frame_history_idx_ = (frame_history_idx_ + 1) % kFrameHistorySize;
-    ImGui::PlotLines("##ft", frame_time_history_.data(), kFrameHistorySize,
-                     static_cast<int>(frame_history_idx_), "Frame (ms)", 0.0f, 50.0f,
-                     ImVec2(200, 40));
-
-    // GPU
-    ImGui::Text("Draw: %" PRId64 "  Stalls: %" PRId64 "  Verts: %" PRId64,
-                rex::perf::GetSnapshotCounter(rex::perf::CounterId::kDrawCalls),
-                rex::perf::GetSnapshotCounter(rex::perf::CounterId::kCommandBufferStalls),
-                rex::perf::GetSnapshotCounter(rex::perf::CounterId::kVerticesProcessed));
-
-    // Audio
-    ImGui::Text("XMA: %" PRId64 "  Lat: %.1fms  BufQ: %" PRId64,
-                rex::perf::GetSnapshotCounter(rex::perf::CounterId::kXmaFramesDecoded),
-                static_cast<float>(
-                    rex::perf::GetSnapshotCounter(rex::perf::CounterId::kAudioFrameLatencyUs)) /
-                    1000.0f,
-                rex::perf::GetSnapshotCounter(rex::perf::CounterId::kBufferQueueDepth));
-
-    // Dispatch
-    ImGui::Text("Dispatch: %" PRId64 "  IRQ: %" PRId64,
-                rex::perf::GetSnapshotCounter(rex::perf::CounterId::kFunctionsDispatched),
-                rex::perf::GetSnapshotCounter(rex::perf::CounterId::kInterruptDispatches));
+    fps = shown_fps;
+  }
+  if (fps <= 0.0 && stats_provider_) {
+    const auto stats = stats_provider_();
+    if (stats.frame_count > 0) fps = stats.fps;
+  }
+  if (fps <= 0.0) return;
 
-    // Threading
-    ImGui::Text("Threads: %" PRId64 "  APC: %" PRId64 "  Contention: %" PRId64,
-                rex::perf::GetSnapshotCounter(rex::perf::CounterId::kActiveThreads),
-                rex::perf::GetSnapshotCounter(rex::perf::CounterId::kApcQueueDepth),
-                rex::perf::GetSnapshotCounter(rex::perf::CounterId::kCriticalRegionContentions));
+  // The game's own heavy UI font, sized from the display height (16 units of a 720p layout), so
+  // the counter keeps the same proportion at every game resolution.
+  const float scale = io.DisplaySize.y / 720.0f;
+  ImFont* font = rex::ui::g_guide_font ? rex::ui::g_guide_font : ImGui::GetFont();
+  const float text_size = 16.0f * scale;
+  char text[32];
+  std::snprintf(text, sizeof(text), "%.0f FPS", fps);
 
-    // Caches
-    auto tex_h = rex::perf::GetSnapshotCounter(rex::perf::CounterId::kTextureCacheHits);
-    auto tex_m = rex::perf::GetSnapshotCounter(rex::perf::CounterId::kTextureCacheMisses);
-    auto pip_h = rex::perf::GetSnapshotCounter(rex::perf::CounterId::kPipelineCacheHits);
-    auto pip_m = rex::perf::GetSnapshotCounter(rex::perf::CounterId::kPipelineCacheMisses);
-    ImGui::Text("TexCache: %" PRId64 "/%" PRId64 "  PipeCache: %" PRId64 "/%" PRId64, tex_h,
-                tex_h + tex_m, pip_h, pip_h + pip_m);
-#endif
+  // Measure the ink of the real glyphs (not the font's line box) so the text is centred in the
+  // box: visible left/right/top/bottom of the string, relative to the pen start and the baseline.
+  ImFontBaked* baked = font->GetFontBaked(text_size);
+  const float k = (baked && baked->Size > 0) ? text_size / baked->Size : 1.0f;
+  float ink_left = 1e9f, ink_right = -1e9f, ink_top = 1e9f, ink_bottom = -1e9f, pen = 0.0f;
+  for (const char* c = text; *c; ++c) {
+    const ImFontGlyph* glyph = baked ? baked->FindGlyph(static_cast<ImWchar>(*c)) : nullptr;
+    if (!glyph) continue;
+    if (glyph->Visible) {
+      ink_left = std::min(ink_left, pen + glyph->X0 * k);
+      ink_right = std::max(ink_right, pen + glyph->X1 * k);
+      ink_top = std::min(ink_top, glyph->Y0 * k);
+      ink_bottom = std::max(ink_bottom, glyph->Y1 * k);
+    }
+    pen += glyph->AdvanceX * k;
   }
-  ImGui::End();
+  if (ink_left > ink_right) {  // no glyph data: fall back to the line box
+    const ImVec2 extent = font->CalcTextSizeA(text_size, 3.4e38f, 0.0f, text);
+    ink_left = 0.0f; ink_right = extent.x; ink_top = 0.0f; ink_bottom = extent.y;
+  }
+  const float pad_x = 9.0f * scale, pad_y = 6.0f * scale;
+  const ImVec2 window_size((ink_right - ink_left) + 2 * pad_x, (ink_bottom - ink_top) + 2 * pad_y);
 
-  // Build stamp watermark -- centered near bottom of screen
-  auto text_size = ImGui::CalcTextSize(REXGLUE_BUILD_STAMP);
-  float padding = ImGui::GetStyle().WindowPadding.x * 2.0f;
-  float bottom_offset = io.DisplaySize.y * 0.03f;
-  ImGui::SetNextWindowPos(ImVec2((io.DisplaySize.x - text_size.x - padding) * 0.5f,
-                                 io.DisplaySize.y - text_size.y - bottom_offset));
-  ImGui::SetNextWindowSize(ImVec2(0, 0));
-  ImGui::PushStyleColor(ImGuiCol_Text, imgui_drawer()->style().debug.muted_text);
-  if (ImGui::Begin("##watermark", nullptr,
-                   ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoBackground |
-                       ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoNav |
-                       ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize)) {
-    ImGui::TextUnformatted(REXGLUE_BUILD_STAMP);
+  ImGui::SetNextWindowPos(ImVec2(10.0f * scale, 8.0f * scale), ImGuiCond_Always);
+  ImGui::SetNextWindowSize(window_size, ImGuiCond_Always);
+  ImGui::SetNextWindowBgAlpha(0.45f);
+  const ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoNav |
+                                 ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
+                                 ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoScrollbar |
+                                 ImGuiWindowFlags_NoFocusOnAppearing;
+  ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
+  if (ImGui::Begin("##fps_counter", nullptr, flags)) {
+    // Green at 55 FPS or more, yellow from 30, red below.
+    const ImU32 color = fps >= 55.0   ? IM_COL32(120, 255, 120, 255)
+                        : fps >= 30.0 ? IM_COL32(255, 220, 80, 255)
+                                      : IM_COL32(255, 90, 90, 255);
+    const ImVec2 origin = ImGui::GetWindowPos();
+    // AddText positions the top of the line box; shift so the ink starts at the padding.
+    ImGui::GetWindowDrawList()->AddText(
+        font, text_size, ImVec2(origin.x + pad_x - ink_left, origin.y + pad_y - ink_top), color, text);
   }
   ImGui::End();
-  ImGui::PopStyleColor();
+  ImGui::PopStyleVar();
 }
 
 }  // namespace rex::ui
diff --git a/src/ui/presenter.cpp b/src/ui/presenter.cpp
index 7360ed9..d3db6a0 100644
--- a/src/ui/presenter.cpp
+++ b/src/ui/presenter.cpp
@@ -576,6 +576,8 @@ bool Presenter::RefreshGuestOutput(
     guest_output_active_last_refresh_ = false;
   }
 
+  writable_properties.frame_sequence = ++guest_output_frame_sequence_;
+
   // Make the new image the next to present on the host (the "ready" one),
   // replacing the one already specified as the next (dropping it instead of
   // enqueueing the new image after it) to achieve the lowest latency (also,
@@ -613,7 +615,9 @@ bool Presenter::RefreshGuestOutput(
     guest_output_mailbox_writable_ = (3 - last_acquired - guest_output_mailbox_writable_) % 3;
   }
 
-  // Trigger the presentation on the host.
+  // Trigger presentation after publishing the mailbox. Preserve the notification
+  // even when painting or reconfiguration currently owns the mode mutex, so a
+  // final guest frame cannot be left unpainted.
   PaintResult paint_result = PaintResult::kNotPresented;
   {
     std::lock_guard<std::mutex> paint_mode_mutex_lock(paint_mode_mutex_);
@@ -1605,6 +1609,33 @@ void Presenter::WaitForUITickFromUIThread() {
 #endif  // XE_PLATFORM
 }
 
+bool Presenter::WaitForMonitorVBlank(double refresh_rate_hz) {
+#if REX_PLATFORM_WIN32
+  Microsoft::WRL::ComPtr<IDXGIOutput> output;
+  {
+    std::lock_guard<std::mutex> lock(dxgi_ui_tick_mutex_);
+    if (dxgi_ui_tick_thread_shutdown_) return false;
+    output = dxgi_ui_tick_output_;
+  }
+  if (!output) return false;
+  DXGI_OUTPUT_DESC description;
+  DEVMODEW mode = {};
+  mode.dmSize = sizeof(mode);
+  if (FAILED(output->GetDesc(&description)) || !description.AttachedToDesktop ||
+      !::EnumDisplaySettingsExW(description.DeviceName, ENUM_CURRENT_SETTINGS, &mode, 0) ||
+      double(mode.dmDisplayFrequency) < refresh_rate_hz - 1.0 ||
+      double(mode.dmDisplayFrequency) > refresh_rate_hz + 1.0) {
+    return false;
+  }
+  // Never hold the monitor mutex while the driver blocks.
+  if (FAILED(output->WaitForVBlank())) return false;
+  std::lock_guard<std::mutex> lock(dxgi_ui_tick_mutex_);
+  return !dxgi_ui_tick_thread_shutdown_ && output.Get() == dxgi_ui_tick_output_.Get();
+#else
+  return false;
+#endif
+}
+
 void Presenter::ForceUIThreadPaintTick() {
 #if REX_PLATFORM_WIN32
   std::scoped_lock<std::mutex> dxgi_ui_tick_lock(dxgi_ui_tick_mutex_);
@@ -1644,13 +1675,15 @@ void Presenter::DXGIUITickThread() {
     // Wait for vertical blank, with the mutex unlocked (holding a new reference
     // to the current output while it's happening) so subscribers can still do
     // early-out checks.
-    bool wait_succeeded;
-    {
-      Microsoft::WRL::ComPtr<IDXGIOutput> dxgi_output = dxgi_ui_tick_output_;
-      dxgi_ui_tick_lock.unlock();
-      wait_succeeded = SUCCEEDED(dxgi_ui_tick_output_->WaitForVBlank());
-    }
+    Microsoft::WRL::ComPtr<IDXGIOutput> dxgi_output = dxgi_ui_tick_output_;
+    dxgi_ui_tick_lock.unlock();
+    bool wait_succeeded = SUCCEEDED(dxgi_output->WaitForVBlank());
     dxgi_ui_tick_lock.lock();
+    // A monitor change may replace the output while its vblank wait is active.
+    // Do not apply the old output's result to the new output.
+    if (dxgi_output.Get() != dxgi_ui_tick_output_.Get()) {
+      continue;
+    }
     if (wait_succeeded) {
       ++dxgi_ui_tick_last_vblank_;
     } else {
diff --git a/src/ui/rex_app.cpp b/src/ui/rex_app.cpp
index b94fe9e..756b89a 100644
--- a/src/ui/rex_app.cpp
+++ b/src/ui/rex_app.cpp
@@ -20,6 +20,7 @@
 #include <rex/filesystem.h>
 #include <rex/logging/sink.h>
 #include <rex/logging.h>
+#include <rex/ui/guide_font.h>
 #include <rex/ui/overlay/achievement_toast.h>
 #include <rex/ui/overlay/achievements_overlay.h>
 #include <rex/ui/overlay/console_overlay.h>
@@ -384,6 +385,10 @@ bool ReXApp::SetupPresentation() {
   return true;
 }
 
+void ReXApp::OnConfigureFonts(ImFontAtlas* atlas) {
+  (void)atlas;  // the game's UI fonts are loaded by the ImGui drawer itself
+}
+
 void ReXApp::SetupOverlays(rex::ui::Presenter* presenter, rex::ui::ImmediateDrawer* drawer) {
   imgui_drawer_ = std::make_unique<rex::ui::ImGuiDrawer>(
       window_.get(), 64, [this](ImFontAtlas* atlas) { OnConfigureFonts(atlas); },
@@ -394,7 +399,7 @@ void ReXApp::SetupOverlays(rex::ui::Presenter* presenter, rex::ui::ImmediateDraw
   // gated eager font upload in SetImmediateDrawer is skipped (font uploads
   // lazily on the first Draw instead).
   imgui_drawer_->SetPresenterAndImmediateDrawer(presenter, drawer);
-  rex::ui::RegisterBind("bind_debug_overlay", "F3", "Toggle debug overlay", [this] {
+  rex::ui::RegisterBind("bind_debug_overlay", "Home", "Toggle statistics view", [this] {
     if (debug_overlay_) {
       debug_overlay_.reset();
     } else {
diff --git a/src/ui/vulkan/vulkan_presenter.cpp b/src/ui/vulkan/vulkan_presenter.cpp
index 23645ef..39ddbfe 100644
--- a/src/ui/vulkan/vulkan_presenter.cpp
+++ b/src/ui/vulkan/vulkan_presenter.cpp
@@ -11,12 +11,16 @@
 
 #include <algorithm>
 #include <atomic>
+#include <array>
+#include <chrono>
 #include <cstddef>
 #include <cstdint>
 #include <cmath>
 #include <cstring>
 #include <memory>
 #include <utility>
+#include <thread>
+#include <cstdlib>
 #include <vector>
 
 #include <rex/assert.h>
@@ -58,10 +62,101 @@ REXCVAR_DEFINE_BOOL(vulkan_allow_present_mode_mailbox, true, "UI/Vulkan",
 REXCVAR_DEFINE_BOOL(vulkan_allow_present_mode_fifo_relaxed, true, "UI/Vulkan",
                     "Allow FIFO relaxed present mode");
 
+REXCVAR_DEFINE_BOOL(vulkan_log_present_timing, false, "UI/Vulkan",
+                    "Log aggregate CPU presentation timings every five seconds");
+
 namespace rex {
 namespace ui {
 namespace vulkan {
 
+namespace {
+
+// Observe successfully queued host presents, not physical scanout timestamps.
+void LogPresentSequence(const void* presenter, uint64_t sequence) {
+  if (!REXCVAR_GET(vulkan_log_present_timing) || !sequence) return;
+  using Clock = std::chrono::steady_clock;
+  struct Stats {
+    const void* owner = nullptr;
+    Clock::time_point start = Clock::now(), last_new = {};
+    uint64_t last_sequence = 0, presents = 0, repeated = 0, skipped = 0;
+    std::vector<double> intervals;
+  };
+  static thread_local Stats stats;
+  if (stats.owner != presenter) { stats = Stats{}; stats.owner = presenter; }
+  const auto now = Clock::now();
+  ++stats.presents;
+  if (sequence == stats.last_sequence) {
+    ++stats.repeated;
+  } else {
+    if (stats.last_sequence) {
+      if (sequence > stats.last_sequence + 1) stats.skipped += sequence - stats.last_sequence - 1;
+      stats.intervals.push_back(std::chrono::duration<double, std::milli>(now - stats.last_new).count());
+    }
+    stats.last_sequence = sequence;
+    stats.last_new = now;
+  }
+  const double elapsed = std::chrono::duration<double>(now - stats.start).count();
+  if (elapsed < 5.0) return;
+  std::sort(stats.intervals.begin(), stats.intervals.end());
+  const size_t count = stats.intervals.size();
+  REXLOG_INFO("VulkanFrameCadence: seconds={:.3f} presents={} repeated={} skipped={} "
+              "new_frame_ms median={:.3f} p95={:.3f} max={:.3f}", elapsed, stats.presents,
+              stats.repeated, stats.skipped, count ? stats.intervals[count / 2] : 0.0,
+              count ? stats.intervals[(count - 1) * 95 / 100] : 0.0,
+              count ? stats.intervals.back() : 0.0);
+  stats.start = now;
+  stats.presents = stats.repeated = stats.skipped = 0;
+  stats.intervals.clear();
+}
+
+// CPU timings only: no GPU queries, waits, or presentation policy changes.
+struct PresentTiming {
+  using Clock = std::chrono::steady_clock;
+  bool enabled = REXCVAR_GET(vulkan_log_present_timing);
+  bool acquire_timeout = false;
+  Clock::time_point previous = enabled ? Clock::now() : Clock::time_point{};
+  std::array<double, 5> stages{};
+
+  void Mark(size_t stage) {
+    if (!enabled) return;
+    auto now = Clock::now();
+    stages[stage] = std::chrono::duration<double, std::milli>(now - previous).count();
+    previous = now;
+  }
+
+  ~PresentTiming() {
+    if (!enabled) return;
+    struct Stats {
+      Clock::time_point start = Clock::now();
+      uint64_t count = 0;
+      uint64_t timeouts = 0;
+      std::array<double, 5> sums{};
+      std::array<double, 5> maxima{};
+    };
+    static thread_local Stats stats;
+    ++stats.count;
+    stats.timeouts += acquire_timeout ? 1 : 0;
+    for (size_t i = 0; i < stages.size(); ++i) {
+      stats.sums[i] += stages[i];
+      stats.maxima[i] = std::max(stats.maxima[i], stages[i]);
+    }
+    if (Clock::now() - stats.start < std::chrono::seconds(5)) return;
+    REXLOG_INFO(
+        "VulkanPresentTiming: calls={} timeouts={} CPU ms avg/max "
+        "reuse={:.3f}/{:.3f} acquire={:.3f}/{:.3f} record={:.3f}/{:.3f} "
+        "submit={:.3f}/{:.3f} present={:.3f}/{:.3f}",
+        stats.count, stats.timeouts,
+        stats.sums[0] / stats.count, stats.maxima[0],
+        stats.sums[1] / stats.count, stats.maxima[1],
+        stats.sums[2] / stats.count, stats.maxima[2],
+        stats.sums[3] / stats.count, stats.maxima[3],
+        stats.sums[4] / stats.count, stats.maxima[4]);
+    stats = Stats{};
+  }
+};
+
+}  // namespace
+
 #if defined(REX_HAS_FIDELITYFX_RUNTIME) && REX_HAS_FIDELITYFX_RUNTIME
 namespace {
 
@@ -129,12 +224,12 @@ VulkanPresenter::PaintContext::Submission::~Submission() {
     dfn.vkDestroyCommandPool(device, draw_command_pool_, nullptr);
   }
 
-  if (present_semaphore_ != VK_NULL_HANDLE) {
-    dfn.vkDestroySemaphore(device, present_semaphore_, nullptr);
-  }
   if (acquire_semaphore_ != VK_NULL_HANDLE) {
     dfn.vkDestroySemaphore(device, acquire_semaphore_, nullptr);
   }
+  if (acquire_fence_ != VK_NULL_HANDLE) {
+    dfn.vkDestroyFence(device, acquire_fence_, nullptr);
+  }
 }
 
 bool VulkanPresenter::PaintContext::Submission::Initialize() {
@@ -152,11 +247,11 @@ bool VulkanPresenter::PaintContext::Submission::Initialize() {
         "semaphore");
     return false;
   }
-  if (dfn.vkCreateSemaphore(device, &semaphore_create_info, nullptr, &present_semaphore_) !=
-      VK_SUCCESS) {
-    REXLOG_ERROR(
-        "VulkanPresenter: Failed to create a swapchain image presentation "
-        "semaphore");
+
+  VkFenceCreateInfo acquire_fence_info = {};
+  acquire_fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
+  if (dfn.vkCreateFence(device, &acquire_fence_info, nullptr, &acquire_fence_) != VK_SUCCESS) {
+    REXLOG_ERROR("VulkanPresenter: Failed to create an image acquisition fence");
     return false;
   }
 
@@ -988,6 +1083,21 @@ VulkanPresenter::ConnectOrReconnectPaintingToSurfaceFromUIThread(Surface& new_su
     return SurfacePaintConnectResult::kFailure;
   }
 
+  // Buffer present semaphores by swapchain image. Waiting on a submission
+  // fence alone does not guarantee that its presentation wait has finished.
+  assert_true(paint_context_.swapchain_present_semaphores.empty());
+  paint_context_.swapchain_present_semaphores.resize(
+      paint_context_.swapchain_images.size(), VK_NULL_HANDLE);
+  VkSemaphoreCreateInfo present_semaphore_info = {};
+  present_semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
+  for (VkSemaphore& semaphore : paint_context_.swapchain_present_semaphores) {
+    if (dfn.vkCreateSemaphore(device, &present_semaphore_info, nullptr, &semaphore) != VK_SUCCESS) {
+      REXLOG_ERROR("VulkanPresenter: Failed to create a per-image presentation semaphore");
+      paint_context_.DestroySwapchainAndVulkanSurface();
+      return SurfacePaintConnectResult::kFailure;
+    }
+  }
+
   // Create the image views and the framebuffers.
   assert_true(paint_context_.swapchain_framebuffers.empty());
   paint_context_.swapchain_framebuffers.reserve(paint_context_.swapchain_images.size());
@@ -1061,7 +1171,7 @@ bool VulkanPresenter::RefreshGuestOutputImpl(
   if (image_instance.image && (image_instance.image->extent().width != frontbuffer_width ||
                                image_instance.image->extent().height != frontbuffer_height)) {
     guest_output_image_refresher_submission_tracker_.AwaitSubmissionCompletion(
-        image_instance.last_refresher_submission);
+        image_instance.last_refresher_submission, FenceWaitTiming::Reason::ResourceReuse);
     image_instance.image.reset();
   }
   if (!image_instance.image) {
@@ -1381,19 +1491,25 @@ VkSwapchainKHR VulkanPresenter::PaintContext::CreateSwapchainForVulkanSurface(
   // interfering with GPU command processing, and also to allow tearing so
   // variable refresh rate may be used where it's available.
   // Note: If the priorities here are changes, update the cvar descriptions.
-  if (REXCVAR_GET(vulkan_allow_present_mode_immediate) &&
+  const bool presentation_vsync = (REXCVAR_QUERY(bool, vsync) || REXCVAR_QUERY(bool, true_vsync));
+  if (REXCVAR_QUERY(bool, true_vsync)) {
+    // True VSync (same as D3D12): FIFO makes painting move to the UI thread (implicit vsync), which waits
+    // for each refresh and then shows the newest guest frame; the game and the GPU thread never wait, and
+    // the FPS overlay counts exactly the displayed frames. FIFO exists on every Vulkan driver.
+    swapchain_create_info.presentMode = VK_PRESENT_MODE_FIFO_KHR;
+  } else if (!presentation_vsync && REXCVAR_GET(vulkan_allow_present_mode_immediate) &&
       std::find(present_modes.cbegin(), present_modes.cend(), VK_PRESENT_MODE_IMMEDIATE_KHR) !=
           present_modes.cend()) {
     // Allowing tearing to reduce latency, and possibly variable refresh rate
     // (though on Windows with borderless fullscreen, GDI copying is used
     // instead of independent flip, so it's not supported there).
     swapchain_create_info.presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
-  } else if (REXCVAR_GET(vulkan_allow_present_mode_mailbox) &&
+  } else if (!presentation_vsync && REXCVAR_GET(vulkan_allow_present_mode_mailbox) &&
              std::find(present_modes.cbegin(), present_modes.cend(), VK_PRESENT_MODE_MAILBOX_KHR) !=
                  present_modes.cend()) {
     // Allowing dropping frames to reduce latency, but no tearing.
     swapchain_create_info.presentMode = VK_PRESENT_MODE_MAILBOX_KHR;
-  } else if (REXCVAR_GET(vulkan_allow_present_mode_fifo_relaxed) &&
+  } else if (!presentation_vsync && REXCVAR_GET(vulkan_allow_present_mode_fifo_relaxed) &&
              std::find(present_modes.cbegin(), present_modes.cend(),
                        VK_PRESENT_MODE_FIFO_RELAXED_KHR) != present_modes.cend()) {
     // Limiting the frame rate, but lets too long frames cause tearing not to
@@ -1428,6 +1544,13 @@ VkSwapchainKHR VulkanPresenter::PaintContext::CreateSwapchainForVulkanSurface(
 VkSwapchainKHR VulkanPresenter::PaintContext::PrepareForSwapchainRetirement() {
   if (swapchain != VK_NULL_HANDLE) {
     submission_tracker.AwaitAllSubmissionsCompletion();
+    // Drain the present queue only when retiring the swapchain, never per frame.
+    // This is the conventional unextended Vulkan retirement path.
+    if (present_queue_family != UINT32_MAX) {
+      const VulkanDevice::Queue::Acquisition queue =
+          vulkan_device->AcquireQueue(present_queue_family, 0);
+      vulkan_device->functions().vkQueueWaitIdle(queue.queue());
+    }
   }
   const VulkanDevice::Functions& dfn = vulkan_device->functions();
   const VkDevice device = vulkan_device->device();
@@ -1436,6 +1559,12 @@ VkSwapchainKHR VulkanPresenter::PaintContext::PrepareForSwapchainRetirement() {
     dfn.vkDestroyImageView(device, framebuffer.image_view, nullptr);
   }
   swapchain_framebuffers.clear();
+  for (VkSemaphore semaphore : swapchain_present_semaphores) {
+    if (semaphore != VK_NULL_HANDLE) {
+      dfn.vkDestroySemaphore(device, semaphore, nullptr);
+    }
+  }
+  swapchain_present_semaphores.clear();
   swapchain_images.clear();
   swapchain_extent.width = 0;
   swapchain_extent.height = 0;
@@ -1529,6 +1658,29 @@ bool VulkanPresenter::GuestOutputImage::Initialize() {
 }
 
 Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_drawers) {
+  // True VSync (same as D3D12): present on an even clock at the chosen rate. With Adaptive Sync / FreeSync the
+  // display shows each image when it arrives, so uneven present times were visible as judder (99% low ~55).
+  if (REXCVAR_QUERY(bool, true_vsync)) {
+    static const double present_hz = [] {
+      const char* refresh_text = std::getenv("REX_VIDEO_MODE_REFRESH_RATE");
+      return refresh_text ? std::strtod(refresh_text, nullptr) : 0.0;
+    }();
+    if (present_hz > 0.0) {
+      using Clock = std::chrono::steady_clock;
+      static Clock::time_point next{};
+      const auto period = std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double>(1.0 / present_hz));
+      auto now = Clock::now();
+      if (next == Clock::time_point{} || now - next > period * 2) next = now;
+      if (now < next) {
+        if (next - now > std::chrono::milliseconds(2)) {
+          std::this_thread::sleep_for(next - now - std::chrono::milliseconds(1));
+        }
+        while (Clock::now() < next) std::this_thread::yield();
+      }
+      next += period;
+    }
+  }
+  PresentTiming timing;
   // Begin the submission in place of the one not currently potentially used on
   // the GPU.
   uint64_t current_paint_submission_index =
@@ -1536,8 +1688,9 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
   uint64_t paint_submission_count = uint64_t(paint_context_.submissions.size());
   if (current_paint_submission_index >= paint_submission_count) {
     paint_context_.submission_tracker.AwaitSubmissionCompletion(current_paint_submission_index -
-                                                                paint_submission_count);
+                                                                paint_submission_count, FenceWaitTiming::Reason::FrameReuse);
   }
+  timing.Mark(0);
   const PaintContext::Submission& paint_submission =
       *paint_context_.submissions[current_paint_submission_index % paint_submission_count];
 
@@ -1568,11 +1721,27 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
   // safe to return early from this function in case of an error.
 
   VkSemaphore acquire_semaphore = paint_submission.acquire_semaphore();
+  // In FIFO mode keep the monitor readiness wait on the presentation CPU
+  // thread, rather than enqueueing an unresolved wait on the guest GPU queue.
+  // The binary semaphore is still consumed by the draw submission as required.
+  const VkFence acquire_fence = paint_context_.swapchain_is_fifo
+      ? paint_submission.acquire_fence() : VK_NULL_HANDLE;
+  if (acquire_fence != VK_NULL_HANDLE &&
+      dfn.vkResetFences(device, 1, &acquire_fence) != VK_SUCCESS) {
+    return PaintResult::kGpuLostResponsible;
+  }
   uint32_t swapchain_image_index;
   VkResult acquire_result =
-      dfn.vkAcquireNextImageKHR(device, paint_context_.swapchain, UINT64_MAX, acquire_semaphore,
-                                VK_NULL_HANDLE, &swapchain_image_index);
+      // A minimized window may stop returning swapchain images. Keep the UI
+      // thread responsive so it can process restore and surface-change events.
+      dfn.vkAcquireNextImageKHR(device, paint_context_.swapchain, 50000000, acquire_semaphore,
+                                acquire_fence, &swapchain_image_index);
+  timing.Mark(1);
+  timing.acquire_timeout = acquire_result == VK_TIMEOUT || acquire_result == VK_NOT_READY;
   switch (acquire_result) {
+    case VK_TIMEOUT:
+    case VK_NOT_READY:
+      return PaintResult::kNotPresented;
     case VK_SUCCESS:
     case VK_SUBOPTIMAL_KHR:
       break;
@@ -1595,6 +1764,18 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
       return PaintResult::kNotPresented;
   }
 
+  if (acquire_fence != VK_NULL_HANDLE) {
+    FenceWaitTiming acquire_timing("presenter", this, FenceWaitTiming::Reason::AcquireImage);
+    const VkResult ready_result =
+        dfn.vkWaitForFences(device, 1, &acquire_fence, VK_TRUE, UINT64_MAX);
+    if (ready_result != VK_SUCCESS) {
+      REXLOG_ERROR("VulkanPresenter: Image acquisition readiness failed ({})",
+                   int(ready_result));
+      return ready_result == VK_ERROR_DEVICE_LOST ? PaintResult::kGpuLostResponsible
+          : PaintResult::kNotPresentedConnectionOutdated;
+    }
+  }
+
   // Non-zero extents needed for both the viewport (width must not be zero) and
   // the guest output rectangle.
   assert_not_zero(paint_context_.swapchain_extent.width);
@@ -1688,7 +1869,7 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
           // its descriptors.
           paint_context_.submission_tracker.AwaitSubmissionCompletion(
               paint_context_.guest_output_image_paint_refs[guest_output_image_paint_ref_new_index]
-                  .first);
+                  .first, FenceWaitTiming::Reason::OutputDescriptors);
         }
         guest_output_image_paint_ref_index = guest_output_image_paint_ref_new_index;
         // The actual submission index will be set if the image is actually
@@ -1736,7 +1917,8 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
             // size is needed.
             if (intermediate_image_ptr_ref) {
               paint_context_.submission_tracker.AwaitSubmissionCompletion(
-                  paint_context_.guest_output_intermediate_image_last_submission);
+                  paint_context_.guest_output_intermediate_image_last_submission,
+                  FenceWaitTiming::Reason::IntermediateImage);
               intermediate_image_ptr_ref.reset();
               util::DestroyAndNullHandle(dfn.vkDestroyFramebuffer, device,
                                          paint_context_.guest_output_intermediate_framebuffers[i]);
@@ -1829,7 +2011,8 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
               swapchain_effect_pipeline.swapchain_format !=
                   paint_context_.swapchain_render_pass_format) {
             paint_context_.submission_tracker.AwaitSubmissionCompletion(
-                paint_context_.guest_output_image_paint_last_submission);
+                paint_context_.guest_output_image_paint_last_submission,
+                FenceWaitTiming::Reason::PaintPipeline);
             util::DestroyAndNullHandle(dfn.vkDestroyPipeline, device,
                                        swapchain_effect_pipeline.swapchain_pipeline);
           }
@@ -1840,6 +2023,9 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
                 swapchain_effect, paint_context_.swapchain_render_pass);
             if (swapchain_effect_pipeline.swapchain_pipeline == VK_NULL_HANDLE) {
               guest_output_flow.effect_count = 0;
+            } else {
+              swapchain_effect_pipeline.swapchain_format =
+                  paint_context_.swapchain_render_pass_format;
             }
           }
         }
@@ -2174,7 +2360,9 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
     paint_context_.ui_setup_command_buffer_current_index = SIZE_MAX;
   }
   command_buffers[command_buffer_count++] = draw_command_buffer;
-  VkSemaphore present_semaphore = paint_submission.present_semaphore();
+  VkSemaphore present_semaphore =
+      paint_context_.swapchain_present_semaphores[swapchain_image_index];
+  timing.Mark(2);
   VkSubmitInfo submit_info;
   submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
   submit_info.pNext = nullptr;
@@ -2227,6 +2415,7 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
     }
   }
 
+  timing.Mark(3);
   VkPresentInfoKHR present_info;
   present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
   present_info.pNext = nullptr;
@@ -2242,6 +2431,10 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
         vulkan_device_->AcquireQueue(paint_context_.present_queue_family, 0);
     present_result = dfn.vkQueuePresentKHR(queue_acquisition.queue(), &present_info);
   }
+  timing.Mark(4);
+  if (present_result == VK_SUCCESS || present_result == VK_SUBOPTIMAL_KHR) {
+    LogPresentSequence(this, guest_output_properties.frame_sequence);
+  }
   switch (present_result) {
     case VK_SUCCESS:
       return PaintResult::kPresented;
diff --git a/src/ui/vulkan/vulkan_submission_tracker.cpp b/src/ui/vulkan/vulkan_submission_tracker.cpp
index 07a07b2..610c9b0 100644
--- a/src/ui/vulkan/vulkan_submission_tracker.cpp
+++ b/src/ui/vulkan/vulkan_submission_tracker.cpp
@@ -10,11 +10,15 @@
  */
 
 #include <cstdint>
+#include <rex/ui/vulkan/fence_wait_timing.h>
 
 #include <rex/assert.h>
 #include <rex/ui/vulkan/submission_tracker.h>
 #include <rex/ui/vulkan/util.h>
 
+REXCVAR_DEFINE_BOOL(vulkan_log_fence_waits, false, "UI/Vulkan",
+                    "Log aggregate existing CPU fence waits without GPU queries");
+
 namespace rex {
 namespace ui {
 namespace vulkan {
@@ -88,7 +92,8 @@ uint64_t VulkanSubmissionTracker::UpdateAndGetCompletedSubmission() {
   return submission_completed_on_gpu_;
 }
 
-bool VulkanSubmissionTracker::AwaitSubmissionCompletion(uint64_t submission_index) {
+bool VulkanSubmissionTracker::AwaitSubmissionCompletion(uint64_t submission_index,
+                                                       FenceWaitTiming::Reason reason) {
   // The tracker itself can't give a submission index for a submission that
   // hasn't even started being recorded yet, the client has provided a
   // completely invalid value or has done overly optimistic math if such an
@@ -119,8 +124,12 @@ bool VulkanSubmissionTracker::AwaitSubmissionCompletion(uint64_t submission_inde
       assert_true(pending_pair.first > submission_completed_on_gpu_);
       if (pending_pair.first <= submission_index) {
         // Wait if requested.
-        if (dfn.vkWaitForFences(device, 1, &pending_pair.second, VK_TRUE, UINT64_MAX) ==
-            VK_SUCCESS) {
+        VkResult wait_result;
+        {
+          FenceWaitTiming timing("presenter", this, reason);
+          wait_result = dfn.vkWaitForFences(device, 1, &pending_pair.second, VK_TRUE, UINT64_MAX);
+        }
+        if (wait_result == VK_SUCCESS) {
           break;
         }
       }
diff --git a/src/ui/window_sdl.cpp b/src/ui/window_sdl.cpp
index 2251429..c813d31 100644
--- a/src/ui/window_sdl.cpp
+++ b/src/ui/window_sdl.cpp
@@ -15,7 +15,9 @@
 
 #include <algorithm>
 #include <cmath>
+#include <cstdlib>
 #include <cstring>
+#include <string>
 #include <filesystem>
 
 #define UTF_CPP_CPLUSPLUS 201703L  // -fno-char8_t
@@ -40,8 +42,116 @@
 #include <rex/ui/surface_gnulinux.h>
 #endif
 
+REXCVAR_DEFINE_STRING(launcher_monitor_device, "", "UI/Window",
+                      "Windows display device selected by the launcher");
+
 namespace rex::ui {
 
+namespace {
+// True VSync (REX_TRUE_VSYNC=1) needs the desktop compositor to show the frames: with a window exactly covering
+// the monitor, Windows lets the game flip straight to the display, and with FreeSync/VRR the panel then runs at
+// its maximum rate instead of the chosen one (60 Hz chosen, ~162 refreshes/s measured), so frames stay on screen
+// for 2 or 3 refreshes. A borderless window one pixel taller than the monitor looks the same but stays composed.
+// Test knob REX_TRUE_VSYNC_COMPOSE: taller (default) | overlay | both | none.
+const char* ComposeMode() {
+  const char* mode = std::getenv("REX_TRUE_VSYNC_COMPOSE");
+  return mode ? mode : "none";  // D3D12 uses exclusive fullscreen instead (d3d12_presenter.cpp)
+}
+
+#if REX_PLATFORM_WIN32
+// A 1x1, almost transparent, click-through window above the game: Windows cannot flip the game straight to the
+// display while another window covers part of it, so the desktop compositor keeps presenting it.
+void PlaceCompositionGuard(SDL_Window* window, const SDL_Rect& bounds) {
+  static HWND guard = nullptr;
+  HWND owner = HWND(SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WIN32_HWND_POINTER,
+                                           nullptr));
+  if (!guard) {
+    guard = CreateWindowExW(WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE,
+                            L"STATIC", L"", WS_POPUP, bounds.x, bounds.y, 1, 1, owner, nullptr, nullptr, nullptr);
+    if (guard) SetLayeredWindowAttributes(guard, 0, 1, LWA_ALPHA);
+  }
+  if (guard) {
+    SetWindowPos(guard, HWND_TOPMOST, bounds.x, bounds.y, 1, 1, SWP_NOACTIVATE | SWP_SHOWWINDOW);
+  }
+  REXLOG_INFO("True VSync: composition guard window {}", guard ? "placed" : "failed");
+}
+#endif
+
+bool UseComposedFullscreen() {
+  static const bool composed = [] {
+    const char* on = std::getenv("REX_TRUE_VSYNC");
+    return on && on[0] == '1';
+  }();
+  return composed;
+}
+
+void SetWindowFullscreenState(SDL_Window* window, bool fullscreen) {
+  static SDL_Rect windowed_rect{};
+  static bool composed_active = false;
+  if (!UseComposedFullscreen()) {
+    SDL_SetWindowFullscreen(window, fullscreen);
+    return;
+  }
+  SDL_Rect bounds{};
+  if (fullscreen) {
+    if (!SDL_GetDisplayBounds(SDL_GetDisplayForWindow(window), &bounds)) {
+      SDL_SetWindowFullscreen(window, true);
+      return;
+    }
+    if (!composed_active) {
+      SDL_GetWindowPosition(window, &windowed_rect.x, &windowed_rect.y);
+      SDL_GetWindowSize(window, &windowed_rect.w, &windowed_rect.h);
+    }
+    const std::string mode = ComposeMode();
+    if (mode == "none") {
+      SDL_SetWindowFullscreen(window, true);
+      return;
+    }
+    if (mode == "overlay" || mode == "region" || mode == "layered") {
+      SDL_SetWindowFullscreen(window, true);
+    } else {
+      SDL_SetWindowFullscreen(window, false);
+      SDL_SetWindowBordered(window, false);
+      SDL_SetWindowSize(window, bounds.w, bounds.h + 1);
+      SDL_SetWindowPosition(window, bounds.x, bounds.y);
+    }
+#if REX_PLATFORM_WIN32
+    if (mode == "overlay" || mode == "both") PlaceCompositionGuard(window, bounds);
+    HWND hwnd = HWND(SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WIN32_HWND_POINTER,
+                                            nullptr));
+    if (hwnd && mode == "region") {
+      // Clip one corner pixel off the window: its visible area no longer covers the whole monitor.
+      int cw = 0, ch = 0;
+      SDL_GetWindowSize(window, &cw, &ch);
+      HRGN full = CreateRectRgn(0, 0, cw, ch);
+      HRGN corner = CreateRectRgn(cw - 1, ch - 1, cw, ch);
+      CombineRgn(full, full, corner, RGN_DIFF);
+      DeleteObject(corner);
+      SetWindowRgn(hwnd, full, TRUE);  // the system owns the region now
+    }
+    if (hwnd && mode == "layered") {
+      SetWindowLongW(hwnd, GWL_EXSTYLE, GetWindowLongW(hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
+      SetLayeredWindowAttributes(hwnd, 0, 255, LWA_ALPHA);
+    }
+#endif
+    int ww = 0, wh = 0;
+    SDL_GetWindowSize(window, &ww, &wh);
+    REXLOG_INFO("True VSync fullscreen ({}): display {}x{}, window {}x{}", mode, bounds.w, bounds.h, ww, wh);
+    composed_active = true;
+  } else {
+    SDL_SetWindowFullscreen(window, false);
+    if (composed_active) {
+      SDL_SetWindowBordered(window, true);
+      if (windowed_rect.w > 0 && windowed_rect.h > 0) {
+        SDL_SetWindowSize(window, windowed_rect.w, windowed_rect.h);
+        SDL_SetWindowPosition(window, windowed_rect.x, windowed_rect.y);
+      }
+      composed_active = false;
+    }
+  }
+}
+}  // namespace
+
 namespace {
 
 uint32_t ResolveWindowWidth(uint32_t requested_width) {
@@ -170,9 +280,37 @@ bool WindowSDL::OpenImpl() {
     }
   }
 
+#if REX_PLATFORM_WIN32
+  // Windows and SDL enumeration orders need not match. Match the selected
+  // device's desktop position rather than interpreting a DXGI index as SDL.
+  const std::string selected_device = REXCVAR_GET(launcher_monitor_device);
+  if (!selected_device.empty()) {
+    DEVMODEA mode = {};
+    mode.dmSize = sizeof(mode);
+    if (::EnumDisplaySettingsA(selected_device.c_str(), ENUM_CURRENT_SETTINGS, &mode)) {
+      int count = 0;
+      SDL_DisplayID* displays = SDL_GetDisplays(&count);
+      if (displays) {
+        for (int i = 0; i < count; ++i) {
+          SDL_Rect bounds;
+          if (SDL_GetDisplayBounds(displays[i], &bounds) &&
+              bounds.x == mode.dmPosition.x && bounds.y == mode.dmPosition.y) {
+            SDL_SetWindowPosition(sdl_window_, SDL_WINDOWPOS_CENTERED_DISPLAY(displays[i]),
+                                  SDL_WINDOWPOS_CENTERED_DISPLAY(displays[i]));
+            break;
+          }
+        }
+        SDL_free(displays);
+      }
+    } else {
+      REXLOG_WARN("Could not locate launcher monitor {}", selected_device);
+    }
+  }
+#endif
+
   if (IsFullscreen()) {
     // Borderless desktop fullscreen (a NULL display mode is SDL3's default).
-    SDL_SetWindowFullscreen(sdl_window_, true);
+    SetWindowFullscreenState(sdl_window_, true);
   }
 #if REX_PLATFORM_MAC
   CFPreferencesSetAppValue(CFSTR("ApplePressAndHoldEnabled"), kCFBooleanFalse,
@@ -295,7 +433,7 @@ void WindowSDL::ApplyNewFullscreen() {
   if (!sdl_window_) {
     return;
   }
-  SDL_SetWindowFullscreen(sdl_window_, IsFullscreen());
+  SetWindowFullscreenState(sdl_window_, IsFullscreen());
 }
 
 void WindowSDL::ApplyNewTitle() {
@@ -450,7 +588,8 @@ void WindowSDL::HandleWindowEvent(SDL_Event& event) {
       // Track the user-driven size as the desired size for the normal state
       // only (mirrors the Win32 WM_SIZE handling).
       SDL_WindowFlags flags = SDL_GetWindowFlags(sdl_window_);
-      if (!(flags & (SDL_WINDOW_MAXIMIZED | SDL_WINDOW_FULLSCREEN | SDL_WINDOW_MINIMIZED))) {
+      if (!(flags & (SDL_WINDOW_MAXIMIZED | SDL_WINDOW_FULLSCREEN | SDL_WINDOW_MINIMIZED)) &&
+          !IsFullscreen()) {
 #if REX_PLATFORM_MAC
         // Cocoa reports the client size in logical points. Converting it from
         // the backing DPI a second time would halve the desired size on Retina
@@ -484,11 +623,28 @@ void WindowSDL::HandleWindowEvent(SDL_Event& event) {
       OnPaint(true);
       break;
     case SDL_EVENT_WINDOW_MINIMIZED:
+      // SDL can retain the previous pixel size while minimized. Explicitly
+      // stop presentation instead of waiting for a zero-size resize event.
+      OnActualSizeUpdate(0, 0, destruction_receiver);
+      if (destruction_receiver.IsWindowDestroyed()) {
+        break;
+      }
       OnMinimized(destruction_receiver);
       break;
-    case SDL_EVENT_WINDOW_RESTORED:
+    case SDL_EVENT_WINDOW_RESTORED: {
+      int width = 0, height = 0;
+      SDL_GetWindowSizeInPixels(sdl_window_, &width, &height);
+      // Restore painting even if SDL sends no pixel-size-change event.
+      OnActualSizeUpdate(uint32_t(width), uint32_t(height), destruction_receiver);
+      if (destruction_receiver.IsWindowDestroyed()) {
+        break;
+      }
       OnRestored(destruction_receiver);
+      if (!destruction_receiver.IsWindowDestroyed()) {
+        OnPaint(true);
+      }
       break;
+    }
     case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
       // SDL destroys nothing on its own; this is the veto point.
       if (SendCloseRequestToListeners(destruction_receiver)) {
diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt
index 7bd264b..e5b229e 100644
--- a/tests/unit/CMakeLists.txt
+++ b/tests/unit/CMakeLists.txt
@@ -36,6 +36,7 @@ target_link_libraries(unit_tests PRIVATE
     rexcodegen
     rexruntime
     Catch2::Catch2WithMain
+    xxHash::xxhash
 )
 
 # ReXApp is shipped as source for recomp projects, rather than compiled into
diff --git a/tests/unit/codegen/output_stamp_test.cpp b/tests/unit/codegen/output_stamp_test.cpp
index d97edb5..f030f58 100644
--- a/tests/unit/codegen/output_stamp_test.cpp
+++ b/tests/unit/codegen/output_stamp_test.cpp
@@ -224,6 +224,6 @@ TEST_CASE("Depfile escapes characters make treats as syntax", "[output_stamp]")
   std::ifstream in(depfile, std::ios::binary);
   std::string content((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
 
-  CHECK(content.find("has\ space.toml") != std::string::npos);
-  CHECK(content.find("hash\#.toml") != std::string::npos);
+  CHECK(content.find("has\\ space.toml") != std::string::npos);
+  CHECK(content.find("hash\\#.toml") != std::string::npos);
 }
diff --git a/tests/unit/core/stream_test.cpp b/tests/unit/core/stream_test.cpp
index 9929507..d40aae3 100644
--- a/tests/unit/core/stream_test.cpp
+++ b/tests/unit/core/stream_test.cpp
@@ -1,3 +1,5 @@
+#include <stdexcept>
+#include <limits>
 /**
  * Unit tests for stream utilities (BitStream, ByteStream)
  *
@@ -288,13 +290,9 @@ TEST_CASE("BitStream Read crossing byte boundary", "[stream][bitstream]") {
 
 // =============================================================================
 // BitStream Write Tests
-// NOTE: BitStream::Write is marked "TODO: This is totally not tested!" in source.
-// It has a bug: doesn't byte-swap when storing, but Read expects big-endian.
-// These tests are skipped until Write is fixed.
 // =============================================================================
 
-TEST_CASE("BitStream Write byte-aligned", "[stream][bitstream][!mayfail]") {
-  SKIP("BitStream::Write is broken - doesn't byte-swap on store");
+TEST_CASE("BitStream Write byte-aligned", "[stream][bitstream]") {
 
   std::array<uint8_t, 16> buffer{};
   BitStream stream(buffer.data(), buffer.size() * 8);
@@ -306,8 +304,7 @@ TEST_CASE("BitStream Write byte-aligned", "[stream][bitstream][!mayfail]") {
   CHECK(stream.Read(8) == 0xAB);
 }
 
-TEST_CASE("BitStream Write 16-bit value", "[stream][bitstream][!mayfail]") {
-  SKIP("BitStream::Write is broken - doesn't byte-swap on store");
+TEST_CASE("BitStream Write 16-bit value", "[stream][bitstream]") {
 
   std::array<uint8_t, 16> buffer{};
   BitStream stream(buffer.data(), buffer.size() * 8);
@@ -318,8 +315,7 @@ TEST_CASE("BitStream Write 16-bit value", "[stream][bitstream][!mayfail]") {
   CHECK(stream.Read(16) == 0x1234);
 }
 
-TEST_CASE("BitStream Write non-byte-aligned", "[stream][bitstream][!mayfail]") {
-  SKIP("BitStream::Write is broken - doesn't byte-swap on store");
+TEST_CASE("BitStream Write non-byte-aligned", "[stream][bitstream]") {
 
   std::array<uint8_t, 16> buffer{};
   BitStream stream(buffer.data(), buffer.size() * 8);
@@ -332,8 +328,7 @@ TEST_CASE("BitStream Write non-byte-aligned", "[stream][bitstream][!mayfail]") {
   CHECK(stream.Read(8) == 0xAB);
 }
 
-TEST_CASE("BitStream Write preserves surrounding bits", "[stream][bitstream][!mayfail]") {
-  SKIP("BitStream::Write is broken - doesn't byte-swap on store");
+TEST_CASE("BitStream Write preserves surrounding bits", "[stream][bitstream]") {
 
   std::array<uint8_t, 16> buffer = {0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
   BitStream stream(buffer.data(), buffer.size() * 8);
@@ -380,3 +375,73 @@ TEST_CASE("BitStream BitsRemaining decreases", "[stream][bitstream]") {
   stream.Read(32);
   CHECK(stream.BitsRemaining() == 16);
 }
+
+TEST_CASE("BitStream Write exact boundary and failed writes preserve memory", "[stream][bitstream]") {
+  std::array<uint8_t, 3> buffer = {0xAA, 0xFF, 0xBB};
+  BitStream stream(buffer.data() + 1, 8);
+  REQUIRE(stream.Write(0, 0));
+  REQUIRE(stream.Write(0x35, 8));
+  CHECK(buffer[0] == 0xAA);
+  CHECK(buffer[1] == 0x35);
+  CHECK(buffer[2] == 0xBB);
+  CHECK_FALSE(stream.Write(1, 1));
+  CHECK_FALSE(stream.Write(0, 58));
+  CHECK(stream.offset_bits() == 8);
+  CHECK(buffer[1] == 0x35);
+}
+
+TEST_CASE("BitStream reads a short final byte and a zero-length end", "[stream][bitstream]") {
+  std::array<uint8_t, 1> buffer = {0xA5};
+  BitStream stream(buffer.data(), 8);
+  CHECK(stream.Read(4) == 0xA);
+  CHECK(stream.Read(4) == 0x5);
+  CHECK(stream.Peek(0) == 0);
+  CHECK(stream.offset_bits() == 8);
+}
+
+TEST_CASE("BitStream Copy preserves alignment and untouched destination bits", "[stream][bitstream]") {
+  // Exhaust all short copy lengths and source bit offsets against a bit oracle.
+  for (size_t offset = 0; offset < 8; ++offset) {
+    for (size_t length = 0; length <= 24 - offset; ++length) {
+      std::array<uint8_t, 3> source = {0xA5, 0x3C, 0xF0};
+      std::array<uint8_t, 4> output = {0x5A, 0x5A, 0x5A, 0x5A};
+      auto expected = output;
+      for (size_t bit = offset; bit < offset + length; ++bit) {
+        const uint8_t mask = uint8_t(1u << (7 - (bit & 7)));
+        expected[bit / 8] = uint8_t((expected[bit / 8] & ~mask) | (source[bit / 8] & mask));
+      }
+      BitStream stream(source.data(), 24);
+      stream.SetOffset(offset);
+      REQUIRE(stream.Copy(output.data(), length) == offset);
+      REQUIRE(output == expected);
+      REQUIRE(stream.offset_bits() == offset + length);
+    }
+  }
+}
+
+TEST_CASE("ByteStream rejects overflow and truncated strings in Release", "[stream][bytestream]") {
+  std::array<uint8_t, 8> buffer{};
+  ByteStream stream(buffer.data(), buffer.size());
+  SECTION("Advance overflow") {
+    stream.Advance(1);
+    REQUIRE_THROWS_AS(stream.Advance(std::numeric_limits<size_t>::max()), std::out_of_range);
+    CHECK(stream.offset() == 1);
+  }
+  SECTION("Read outside buffer") {
+    stream.set_offset(buffer.size());
+    REQUIRE_THROWS_AS(stream.Read<uint32_t>(), std::out_of_range);
+    CHECK(stream.offset() == buffer.size());
+  }
+  SECTION("Write outside buffer") {
+    stream.set_offset(buffer.size());
+    REQUIRE_THROWS_AS(stream.Write(uint32_t(42)), std::out_of_range);
+    CHECK(buffer == std::array<uint8_t, 8>{});
+  }
+  SECTION("Truncated string length") {
+    stream.Write(uint32_t(0xFFFFFFFFu));
+    stream.set_offset(0);
+    REQUIRE_THROWS_AS(stream.Read<std::string>(), std::out_of_range);
+    stream.set_offset(0);
+    REQUIRE_THROWS_AS(stream.Read<std::u16string>(), std::out_of_range);
+  }
+}
diff --git a/tests/unit/system/function_dispatcher_test.cpp b/tests/unit/system/function_dispatcher_test.cpp
index 88617f2..142d5b9 100644
--- a/tests/unit/system/function_dispatcher_test.cpp
+++ b/tests/unit/system/function_dispatcher_test.cpp
@@ -278,3 +278,59 @@ TEST_CASE("PPCContext: restoring a zeroed fpscr leaves host FP exception masks i
   CHECK((ctx.fpscr.getcsr() & ~kGuestMask) == (host_before & ~kGuestMask));
   CHECK(ctx.fpscr.csr == ctx.fpscr.getcsr());
 }
+
+
+namespace {
+void ThrowingDispatchFn(PPCContext& ctx, uint8_t*) {
+  ctx.r1.u64 -= 32;
+  ctx.lr = 0;
+  ctx.r14.u64 = 0;
+  throw 42;
+}
+}
+
+TEST_CASE("FunctionDispatcher: invalid ranges and unaligned functions are rejected",
+          "[runtime][dispatcher]") {
+  auto& memory = GetTestMemory();
+  rex::runtime::ExportResolver resolver;
+  rex::runtime::FunctionDispatcher dispatcher(&memory, &resolver);
+  CHECK_FALSE(dispatcher.InitializeFunctionTable(0xFFFFFF00u, 0x10000u,
+                                                 0xFFFFFF00u, 0x100000u));
+  CHECK_FALSE(dispatcher.InitializeFunctionTable(0x8B000001u, 0x10000u,
+                                                 0x8B000000u, 0x100000u));
+  REQUIRE(dispatcher.InitializeFunctionTable(0x8B000000u, 0x10000u,
+                                              0x8B000000u, 0x100000u));
+  CHECK_FALSE(dispatcher.SetFunction(0x8B000001u, &DummyFn));
+  CHECK(dispatcher.GetFunction(0x8B000001u) == nullptr);
+  REQUIRE(dispatcher.SetFunction(0x8B000000u, &DummyFn));
+  CHECK(dispatcher.GetFunction(0x8B000000u) == &DummyFn);
+}
+
+TEST_CASE("FunctionDispatcher: exceptions restore dispatch and trap state",
+          "[runtime][dispatcher]") {
+  auto& memory = GetTestMemory();
+  rex::runtime::ExportResolver resolver;
+  rex::runtime::FunctionDispatcher dispatcher(&memory, &resolver);
+  constexpr uint32_t base = 0x8A000000u;
+  REQUIRE(dispatcher.InitializeFunctionTable(base, 0x10000u, base, 0x100000u));
+  REQUIRE(dispatcher.SetFunction(base + 0x40, &ThrowingDispatchFn));
+  rex::runtime::ThreadState previous(1, 0x71000000u, 0x60000000u, &memory);
+  rex::runtime::ThreadState target(2, 0x70000000u, 0x60000000u, &memory);
+  auto* ctx = target.context();
+  ctx->lr = 0x12345678u;
+  ctx->r14.u64 = 0x14141414u;
+  rex::runtime::ThreadState::Bind(&previous);
+  SECTION("Execute") {
+    uint64_t args[] = {0};
+    REQUIRE_THROWS_AS(dispatcher.Execute(&target, base + 0x40, args, 1), int);
+  }
+  SECTION("ExecuteTrap") {
+    uint64_t args[] = {0};
+    REQUIRE_THROWS_AS(dispatcher.ExecuteTrap(&target, base + 0x40, args, 1), int);
+    CHECK(ctx->r14.u64 == 0x14141414u);
+  }
+  CHECK(ctx->r1.u64 == 0x70000000u);
+  CHECK(ctx->lr == 0x12345678u);
+  CHECK(rex::runtime::ThreadState::Get() == &previous);
+  rex::runtime::ThreadState::Bind(nullptr);
+}
diff --git a/thirdparty/CMakeLists.txt b/thirdparty/CMakeLists.txt
index f102b56..e23f430 100644
--- a/thirdparty/CMakeLists.txt
+++ b/thirdparty/CMakeLists.txt
@@ -374,6 +374,11 @@ if(REXGLUE_ENABLE_TRACY)
 
     target_link_libraries(TracyClient PUBLIC Threads::Threads ${CMAKE_DL_LIBS})
 
+    if(WIN32 AND CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC")
+        # The Universal CRT exports _fileno; avoid the legacy POSIX alias.
+        target_compile_definitions(TracyClient PRIVATE fileno=_fileno)
+    endif()
+
     if(WIN32 AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
         target_link_libraries(TracyClient PUBLIC ws2_32 dbghelp)
     endif()
@@ -702,3 +707,8 @@ set_target_properties(libavutil libavcodec PROPERTIES
     C_VISIBILITY_PRESET hidden
     VISIBILITY_INLINES_HIDDEN ON
     FOLDER "FFmpeg")
+
+if(WIN32 AND CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC")
+    target_compile_definitions(libavutil PRIVATE isatty=_isatty)
+    target_compile_definitions(SDL3-static PRIVATE itoa=_itoa)
+endif()