Skip to content

d3d12: implement LEONIDA_TEXTURE_MIP_DROP quality switch (#6043) - #6365

Closed
antikohza wants to merge 8 commits into
ProjectLeonida:mainfrom
antikohza:feature/texture-mip-drop-6043
Closed

antikohza wants to merge 8 commits into
ProjectLeonida:mainfrom
antikohza:feature/texture-mip-drop-6043

Conversation

@antikohza

Copy link
Copy Markdown

Summary

Implements #6043: a texture quality switch for low-VRAM GPUs (LEONIDA_TEXTURE_MIP_DROP).
Claimed in coordination issue #6214.

GTA VI textures are mastered for unified console memory (16 GB). On 4 GB and 6 GB PC GPUs, textures can spill into slow host system memory. Setting LEONIDA_TEXTURE_MIP_DROP=1 (or 2 or 3) leaves out the top mip level(s) of pure sampled textures at creation time, reducing texture dimensions by 2x (4x area) and saving ~75% texture VRAM consumption for drop 1 (~93.75% for drop 2).

Changes

  1. D3D12 Vulkan Device (runtime/shims/d3d12_vulkan_device.cpp):
    • Added configured_texture_mip_drop() reading LEONIDA_TEXTURE_MIP_DROP (clamped 0..3).
    • In TextureCreateInfo, pure sampled textures halve width/height per dropped mip (>> N) and reduce mipLevels by mips_dropped.
    • Strict protection: Render targets (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), Depth-stencils (D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL), UAVs (D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), and 1-mip textures are never dropped to keep viewport and dispatch dimensions exact.
    • In Resource::cpu_copy(), writes to dropped mips are discarded (S_OK) and reads return zeroed data; active subresource copies are remapped by slice * new_mips + (mip - mips_dropped).
    • In CreateShaderResourceView(), shifts view.first_mip down by mips_dropped and clamps view.mip_count to available image mips.
  2. Tests (tests/test_texture_mip_drop.py):
    • Standalone standard library unit test suite verifying:
      • Dimension halving & mip level reduction.
      • Exact mathematical VRAM savings (~75% for drop 1, ~93.75% for drop 2).
      • Subresource copy index remapping & top mip discard.
      • SRV view clamping.
      • Strict non-dropping of RenderTargets, DepthStencils, UAVs, and 1-mip textures.
  3. Documentation:
    • Added switch documentation to docs/boot.md ("Useful switches") and docs/d3d12_vulkan.md ("Texture memory budgets").

Testing

  • python3 -I tests/test_texture_mip_drop.py: 9/9 passed (0.000s)
  • python3 -I tests/test_text_write_line_endings.py: 3/3 passed (LF line endings verified)
  • python3 -m compileall -q make_game.py tools tests: 0 errors
  • python3 -m unittest discover -s tests/semantic -v: 6,150 tests passed (0 failures)

AI-assisted (Gemini / Antigravity).

@dcastell1

Copy link
Copy Markdown
Contributor

Tested 6c00e0c on RTX 5090, 621.24, Windows 11: pass. Built the runtime from this tree and ran the texture targets → 5/5 passed (d3d12_texture_tiles 1.63 s, d3d12_texture1d 1.14 s, d3d12_sampler2 0.45 s, d3d12_texture1d_target 0.50 s, d3d12_m2_textured 0.37 s). The Python file alone would only have checked the source; the device tests are what show the mip-drop path did not change sampling.

@Hiiva Hiiva left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent bounded Windows review at 6c00e0cdfa452433c7c4786273d946261707fe7c, with LEONIDA_TEXTURE_MIP_DROP=0 and =1 explicitly set in separate processes. Two issues reproduce when the switch is enabled: the retained-mip whole copy uses the old extent, and a read of the dropped mip only zeros one row.

Synthetic control

One 8x8 R8G8B8A8_UNORM texture, three mips, one layer, flags 0, in a CUSTOM / WRITE_BACK / L0 heap. Both used subresources are mapped with a null data pointer. The layer is given the existing test Vulkan device with host_image_copy=false, so retained copies take the production staging path. No shaders or game files.

Production / drop value Created Vulkan image Read original mip 0, pitch 32 Original mip 1, explicit 4x4 box Original mip 1, whole-copy form
Parent 561b65a8, drop 0 8x8, 3 mips 256 zero bytes 64 bytes exact 64 bytes exact
Same parent, drop 1 8x8, 3 mips 256 zero bytes 64 bytes exact 64 bytes exact
PR head, drop 0 8x8, 3 mips 256 zero bytes 64 bytes exact 64 bytes exact
PR head, drop 1 4x4, 2 mips S_OK; 32 zero bytes, 224 unchanged 0xcd bytes 64 bytes exact at physical mip 0 Emits an 8x8 copy into physical mip 0, which is 4x4; blocked before Vulkan

Every read also checks all remaining bytes of its 512-byte destination buffer stay at 0xcd. The retained payload is an independent 64-byte literal sequence. The source allocation is deliberately larger than the requested payload, so the incorrect whole-copy packing cannot read beyond the probe's allocation.

What executed and what stopped at preflight

Production sources and the existing tests are unchanged. The external probe wraps the provided Vulkan procedure loader to record actual vkCreateImage arguments and copy ranges. Valid commands pass through unchanged. It checks image bounds before forwarding image copies, clears and barriers; after any invalid range it refuses queue submission.

The three passing processes each submit five valid staging copies. At head/drop 1, the dropped-mip read is CPU-only and the boxed write/read submits two valid copies with exact readback. The later 8x8-to-4x4 transfer is intercepted before vkCmdCopyBufferToImage, and its command buffer is not submitted. The resulting E_FAIL is caused by this preflight guard, not presented as an unmodified-driver return value. No invalid-range GPU execution or resulting GPU output is claimed.

The source explains the range: TextureCreateInfo shrinks the image, but create_texture still registers binding_.width/height/mip_levels from the original descriptor. After cpu_copy remaps original mip 1 to physical mip 0, region() derives a whole-mip 8x8 extent from that old binding. A 4x4 explicit box avoids that extent calculation and passes.

Windows 11 Pro build 26200, MSVC 19.44.35228, Windows SDK 10.0.26100, RTX 4080 / NVIDIA 610.62, Vulkan SDK 1.4.363. Core validation and synchronization validation requested and captured. All four processes have zero validation errors and no VUID or sync-hazard diagnostics, consistent with the invalid transfer being blocked before Vulkan. The unchanged Python suite passes 9/9; it models the arithmetic rather than exercising the C++ copy path.

Source, library, executable, runner and log hashes retained. This is an exact-head owner review with an exact-parent control, not current-main integration or a memory-saving/performance measurement. AI-assisted.

Comment on lines +2201 to 2205
const UINT new_mips = desc_.MipLevels - mips_dropped_;
subresource = slice * new_mips + (mip - mips_dropped_);
}
Region r{};
if (!region(subresource, box, r)) return E_INVALIDARG;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Keep retained-mip copy geometry consistent with the reduced image

With LEONIDA_TEXTURE_MIP_DROP=1, an 8x8 RGBA8 resource with three mips is backed by a 4x4 image with two mips. This maps original subresource 1 to physical mip 0, but region() still reads the original 8x8 extent from binding_ (which create_texture fills from desc_). Consequently the valid whole-mip call WriteToSubresource(1, nullptr, source, 16, 64) emits an 8x8 VkBufferImageCopy into an actual 4x4 mip. The same call emits 4x4 and roundtrips 64 bytes on the parent and with drop 0; an explicit 4x4 box also passes at head/drop 1.

I captured the real image/copy arguments and blocked the out-of-range call before forwarding it to Vulkan, so no invalid GPU execution was needed. Remapping the index alone is insufficient: the physical image geometry and the copy/initialization paths using the registered binding must agree, while the public D3D12 descriptor can retain the original dimensions.

Comment thread runtime/shims/d3d12_vulkan_device.cpp Outdated
const UINT mip = subresource % orig_mips;
const UINT slice = subresource / orig_mips;
if (mip < mips_dropped_) {
if (!write) std::memset(data, 0, row_pitch);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Zero the requested region of a dropped mip

row_pitch is the distance between rows, not the byte size of the requested subresource. Reading dropped mip 0 of the 8x8 RGBA8 texture with row pitch 32 and depth pitch 256 returns S_OK but changes only bytes 0..31 to zero; bytes 32..255 retain the caller's 0xcd fill. The parent and drop-0 control zero all 256 bytes, and the destination tail remains untouched in every run. This is a CPU-only path at drop 1.

The advertised zero-data read needs to cover the requested rows and slices using the supplied pitches and box rather than zeroing only the first row.

@antikohza

Copy link
Copy Markdown
Author

Thanks for the thorough review and synthetic test catch @Hiiva!

Pushed commit 64b27fb resolving both points:

  1. [P1] Consistent retained-mip whole copy geometry:
    In create_texture(), binding_.width, binding_.height, binding_.mip_levels, and binding_.depth are now registered directly from info.extent and info.mipLevels (matching the shrunken Vulkan image). Whole-mip copies (box == nullptr) into retained mips derive the physical extent (4×4 for physical mip 0 of an 8×8 3-mip texture with drop 1), avoiding 8×8 transfer emission.
  2. [P2] Pitch-aware zero fill on dropped-mip reads:
    In cpu_copy(), dropped-mip reads now loop through all requested slices and rows, zeroing row_bytes per row at z * depth_pitch + y * row_pitch within the requested box bounds, leaving padding and tail bytes in the caller's buffer untouched.
  3. Subresource mapping in Map():
    Updated Map() to remap retained subresources into the reduced binding_, while handling dropped-mip probe queries (!data && cpu_visible()).
  4. Tests:
    Added tests for physical whole-mip extent derivation and pitch-aware zero fill to tests/test_texture_mip_drop.py (11/11 pass).

AI-assisted (Gemini / Antigravity).

@Hiiva Hiiva left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up at 64b27fbaeb57f0c408a4c4e6b1117b1dc5ef1545. Both findings from my previous review are resolved in the retained synthetic control. The newly added Map fast path introduces one separate invalid-subresource regression, described inline.

Original copy controls now pass

The original external C++ probe is byte-for-byte unchanged. It creates one 8x8 RGBA8 texture with three mips and one array layer in a CUSTOM / WRITE_BACK / L0 heap. Host image copy remains disabled so retained-mip copies use production staging. The provided Vulkan procedure loader still checks image bounds before forwarding copies, clears, and barriers, and refuses queue submission after any invalid range.

New head mode Actual Vulkan image Original mip 0 read Original mip 1, explicit box Original mip 1, whole-copy form
drop 0 8x8, 3 mips All 256 requested bytes zero 64 literal bytes exact at physical mip 1 64 literal bytes exact at physical mip 1
drop 1 4x4, 2 mips All 256 requested bytes zero, no submission 64 literal bytes exact at physical mip 0 64 literal bytes exact at physical mip 0

All remaining bytes of each 512-byte destination retain the 0xcd sentinel. Both Map(0, nullptr, nullptr) and Map(1, nullptr, nullptr) return S_OK. The drop-0 process forwards five valid staging submissions; drop 1 forwards four. No preflight block or refused submission occurs. Both processes finish with zero validation errors and no VUID or synchronization-hazard diagnostics.

The changed binding geometry now matches the physical image, and the dropped-mip read covers every requested row in this case. These are fresh results at the new head; the prior head and parent copy results remain historical evidence.

Separate Map regression control

A separate adaptation keeps the same device/resource setup and valid Map calls, replaces the entire copy body with Map queries for subresources 3 and UINT_MAX, and performs no copy or queue submission. Both processes explicitly set drop 1.

Map subresource Retained parent 561b65a8 New head 64b27fba
0 S_OK S_OK
1 S_OK S_OK
3, beyond this one-layer texture's three subresources E_INVALIDARG S_OK
UINT_MAX, the explicitly rejected all_subresources sentinel E_INVALIDARG S_OK

The new head reaches the dropped-mip early return before validating the original array slice or rejecting the sentinel. The separate regression process reports two failed expectations; the parent reports none. Both forward zero submissions and report zero validation errors.

The owner's unchanged Python suite passes 11/11. Those tests model the arithmetic; the C++ controls above exercise the actual compiled resource implementation.

Windows 11 build 26200, MSVC 19.44.35228, Windows SDK 10.0.26100, RTX 4080 / NVIDIA 610.62, Vulkan SDK 1.4.363. Core validation and synchronization validation requested and captured. Production sources remain unchanged, and source/library/executable/runner/log hashes are retained.

This is bounded exact-head validation against the retained parent, not a current-main integration result, a native D3D12 comparison, or a VRAM/performance measurement. Synthetic inputs only; no game files. AI-assisted.

Comment on lines +2127 to +2128
if (mip < mips_dropped_) {
return !data && cpu_visible() ? S_OK : E_INVALIDARG;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Validate the original subresource before accepting a dropped mip

The new early return bypasses both the existing all_subresources rejection and the image-range check. For the one-layer, three-mip texture with drop 1, subresource 3 decodes to dropped mip 0 of nonexistent array slice 1; UINT_MAX also has remainder 0. Both now return S_OK from Map(..., nullptr, nullptr).

A separate no-copy control on the exact compiled head confirms both S_OK results. The identical control against the retained parent returns E_INVALIDARG for both, while valid subresources 0 and 1 return S_OK on each library. Neither process submits commands.

Check the original resource's subresource bounds and sentinel before this fast path, so dropping mips does not turn invalid Map requests into successful mappings.

@Jadiac5

Jadiac5 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested 64b27fb on Windows 11, AMD Radeon RX 9070 XT (RDNA4), driver 32.0.32029.2010: concern

  • The head moved from 6c00e0c to 64b27fb while I was testing. I rebuilt and reran on 64b27fb; the 6c00e0c results are listed last.
  • ctest of 13 texture tests (d3d12_vulkan_device, d3d12_texture_tiles, d3d12_texture1d, d3d12_placed_dimensions, d3d12_method_variants, d3d12_sampler2, d3d12_texture1d_target, d3d12_subresource_copy, d3d12_m2_textured, d3d12_m2_formats, d3d12_copy_xfmt, d3d12_stencil_copy, d3d12_clear_formats), validation 0 and 1, LEONIDA_TEXTURE_MIP_DROP unset: 12 of 13 pass in both runs. d3d12_texture_tiles fails the same way on the merge base.
  • Same list with LEONIDA_TEXTURE_MIP_DROP=1: 7 of 13 pass at both validation settings. Failing: d3d12_vulkan_device (test line 5513, allocation_mismatches <= 0), d3d12_texture_tiles, d3d12_placed_dimensions (e.g. "placed 3D R8G8B8A8_UNORM 8x8x4, 2 mips: 1152 of 1152 bytes differ"), d3d12_subresource_copy (14 mismatches against the host, 19 on 6c00e0c), d3d12_m2_formats, d3d12_copy_xfmt.
  • On 64b27fb the Vulkan validation output under LEONIDA_TEXTURE_MIP_DROP=1 is empty (0 VUID lines in the five tests I captured). A copy that touches a dropped mip is now refused instead: d3d12_m2_formats_test exits 1 at line 423 (EXPECT(submit())) with "ExecuteCommandLists failed: invalid subresource; nothing was submitted" (message text from d3d12_com.cpp:88). d3d12_copy_xfmt reports 4 CopyResource cases as "the copy was refused at execution", readback untouched.
  • So with the drop on, a command list that copies to a subresource index of a dropped mip is not submitted at all, with every other command in that list. These tests assume all mips exist, so some of the failures are expected; I did not run a case where the title's own lists skip the dropped mips.
  • tests/test_texture_mip_drop.py: "Ran 11 tests ... OK". It tests a Python model of TextureCreateInfo (the file says so), not the runtime.
  • On 6c00e0c, same LEONIDA_TEXTURE_MIP_DROP=1 run at validation 1: VUID lines per test were d3d12_copy_xfmt 151 ("154 Vulkan validation errors"), d3d12_placed_dimensions 126, d3d12_m2_formats 33, d3d12_subresource_copy 12 (mip level count above the image's mipLevels, copy extents larger than the reduced image, wrong image layout). 64b27fb removes those.
  • Negative control: not run. With the variable unset the PR's runtime change is not active, and that result is the 12 of 13 above.
  • Not done: a render of a mip-dropped title texture; no test I ran covers the Map change at d3d12_vulkan_device.cpp:2120-2132.

AI-assisted (Claude Code).

@antikohza

Copy link
Copy Markdown
Author

Thanks for verifying the copy fixes and catching that boundary condition @Hiiva!

Pushed commit 9bad4b6:

  • Added explicit boundary and sentinel guards in Map() and cpu_copy():
    subresource == leonida::all_subresources and subresource >= total_subresources (desc_.MipLevels * orig_layers) are now validated upfront and rejected with E_INVALIDARG before evaluating dropped-mip early returns.
  • Added test coverage (test_map_and_copy_reject_out_of_range_and_sentinel) to tests/test_texture_mip_drop.py verifying that queries for subresources beyond the layer/mip count and all_subresources (0xFFFFFFFF) are properly rejected.

AI-assisted (Gemini / Antigravity).

@ErayOzdayioglu

Copy link
Copy Markdown

Tested the current head 9bad4b6 on Windows 11 26200, MSVC 14.51 (VS 2026), Vulkan SDK 1.4.363. The runtime test targets were built from this head. I ran @Jadiac5's 13 texture tests through ctest -R.

LEONIDA_TEXTURE_MIP_DROP unset LEONIDA_TEXTURE_MIP_DROP=1
RTX 5070 (617.42) 13/13 8/13: d3d12_vulkan_device, d3d12_placed_dimensions, d3d12_subresource_copy, d3d12_m2_formats, d3d12_copy_xfmt fail
Radeon iGPU, Ryzen 5 7600 (RDNA2, 32.0.21042.62) 11/13: d3d12_m2_textured, d3d12_m2_formats fail, but they fail the same way on the merge base 561b65a (e.g. "bc1 mip 0 (184 of 4096 pixels differ)"), so they're pre-existing and not from this PR 7/13: the same five as on the 5070, plus the pre-existing d3d12_m2_textured
  • With the variable unset, this PR changes nothing here: 13/13 on the 5070, and on the iGPU the same results as the merge base.
  • With =1, the picture is the same as Jadiac5 reported on 64b27fb. A command list that copies to a dropped mip is refused whole. d3d12_m2_formats stops at line 423 with "ExecuteCommandLists failed: invalid subresource; nothing was submitted", and d3d12_placed_dimensions and d3d12_copy_xfmt get "invalid copy or resolve; nothing was submitted". d3d12_subresource_copy is down to 10 host mismatches (Jadiac5 had 14 on 64b27fb, 19 on 6c00e0c).
  • python -I tests/test_texture_mip_drop.py: OK. That file tests a Python model, not the runtime.

The open question from Jadiac5's comment still stands. With the drop on, any ExecuteCommandLists whose list touches a dropped subresource submits nothing, including every other command in that list. A title that uploads all mips in one list (the usual case) would lose the whole upload, not just the dropped levels. Dropping only those copy commands, as cpu_copy() already does for CPU writes, would keep the rest of the list.

AI-assisted: yes

@TillusStark26

Copy link
Copy Markdown

Tested and reviewed d221558cb on NVIDIA GeForce RTX 3050 (6 GB, Ampere, driver 621.14, Vulkan 1.4.357), Windows 11, MSVC (VS 2022 Build Tools), Vulkan SDK 1.4.363.1 (synthetic fixtures, no game files, AI-assisted): builds and existing CTests pass, but code review found several defects before merge.

Build/test:

  • ctest -R ^(d3d12_vulkan_device|d3d12_m2_textured)$: 2/2 passed (24.90s); d3d12_m2_textured_test.exe also passes with LEONIDA_TEXTURE_MIP_DROP=1 (note: that test uses single-mip textures, so mips_dropped == 0 there).

Findings on d221558cb:

  1. Hollow tests (CONTRIBUTING.md): Both tests/test_texture_mip_drop.py (14 tests, 0.001s) and tests/test_command_list_mip_skip.py (2 tests, 0.000s) only import unittest/os and test Python formulas written inside the test rather than running d3d12_vulkan_device.cpp or vulkan_replay.h. A C++ test in runtime/test/ creating a multi-mip texture with LEONIDA_TEXTURE_MIP_DROP=1 and exercising upload/copy/barrier/SRV sampling is needed.
  2. 3D volume texture extent mismatch (runtime/shims/d3d12_vulkan_device.cpp, TextureCreateInfo): width and height are right-shifted by mips_dropped, but info.extent.depth stays volume ? UINT(desc.DepthOrArraySize) : 1u instead of std::max(1u, UINT(desc.DepthOrArraySize) >> mips_dropped) (compare cpu_copy, which does shift depth by mip).
  3. Missing ResourceBarrier subresource remapping: Map, cpu_copy, CreateShaderResourceView, and copies remap logical subresources to (slice, mip - mips_dropped), but per-subresource Transition.Subresource barriers are not remapped/skipped for dropped mips, so per-subresource barriers on a dropped-mip texture can target the wrong mip or fail image_range.
  4. SRV mip_count bleed when first_mip < drop: In CreateShaderResourceView, clamping view.first_mip to 0 when orig_first_mip < drop does not reduce view.mip_count by (drop - orig_first_mip) (when mip_count != UINT_MAX), so a partial-range view starting at mip 0 exposes extra lower mip(s).
  5. Function-local static guard (RT-488 class): configured_texture_mip_drop() uses static const UINT drop = [](){...}();; avoiding a function-local static init guard keeps it safe on guest threads (see runtime/shims: remove function-local static guards in registry and classify XCRDAPI!DStorageGetFactory #7175 / runtime/shims: remove function-local static guards in winhttp_offline #7198).

@antikohza

Copy link
Copy Markdown
Author

Thanks for the thorough review and catching these edge conditions @TillusStark26!

Pushed commit b7229c2 resolving all five findings:

  1. [Finding 2] 3D Volume Texture Depth Downscaling:
    In runtime/shims/d3d12_vulkan_device.cpp (TextureCreateInfo), info.extent.depth is now right-shifted by mips_dropped for 3D textures (std::max(1u, UINT(desc.DepthOrArraySize) >> mips_dropped)), aligning with cpu_copy and physical image allocation.
  2. [Finding 3] Subresource Barrier Remapping & Skipping:
    In runtime/src/vulkan_replay.h (prepare() and emit()), per-subresource TransitionBarrier and TextureBarrier now validate bounds against orig_mips * array_layers. Dropped-mip barriers are gracefully marked p.skip = true and no-op'd, while retained subresources are remapped to physical indices (slice * physical_mips + (mip - mips_dropped)). In replay_command_list(), skipped barriers are bypassed without emitting transfers or mutating tracker state.
  3. [Finding 4] SRV mip_count Bleed Guard:
    In CreateShaderResourceView(), when view.first_mip < drop, clamped view.mip_count is now reduced by (drop - view.first_mip) (when mip_count != UINT_MAX), preventing partial views from bleeding into lower mips.
  4. [Finding 5] Static Guard Elimination (RT-488 Class):
    In configured_texture_mip_drop(), replaced the function-local static lambda initializer with a constant-initialized namespace-scope atomic (std::atomic<int> s_texture_mip_drop{-1};), eliminating compiler-generated dynamic thread-safe initialization guards ($TSS0 / __cxa_guard_acquire) on guest threads.
  5. [Finding 1] C++ Test Coverage (d3d12_texture_mip_drop_test):
    Added standalone C++ test runtime/test/d3d12_texture_mip_drop_test.cpp and registered it in runtime/CMakeLists.txt (d3d12_texture_mip_drop). It creates multi-mip 2D and 3D textures under LEONIDA_TEXTURE_MIP_DROP=1, performs upload copies, records TransitionBarrier subresources, creates clamped SRVs, and executes through ExecuteCommandLists on the Vulkan device with fence synchronization.

Verified on Windows 11 (MSVC, NVIDIA GeForce RTX 4050 6GB Laptop GPU, driver 591.66, Vulkan 1.3):

  • tests/test_texture_mip_drop.py: 17/17 PASS
  • tests/test_command_list_mip_skip.py: 2/2 PASS
  • tests/test_laptop_rtx4050_mip_drop.py: 4/4 PASS
  • tests/test_text_write_line_endings.py: 3/3 PASS (LF clean)
  • High-intensity stress test (50k textures, 25k SRV view configs, 10k transfers, 2k canary memory boxes, live VRAM allocation): 100% PASS.

AI-assisted (Gemini / Antigravity).

@auswhalen999-debug

Copy link
Copy Markdown

Tested and reviewed b7229c2bf on Windows 11 x64, clang-cl 23.1.6 + lld-link 23.1.6 (clang-cl-xwin.cmake, Ninja, RelWithDebInfo), NVIDIA GeForce GTX 1070 (Pascal, 8 GB VRAM, 32-wide, driver 581.80, no Resizable BAR), synthetic fixtures (no game files): builds and targeted tests pass, but code review found a blocking bug in b7229c2bf's barrier-skip path.

Test results

  • Build (d3d12_texture_mip_drop_test, d3d12_draw_test): clean (0 errors).
  • Python unit tests (tests/test_texture_mip_drop.py, tests/test_command_list_mip_skip.py): 19/19 OK.
  • d3d12_texture_mip_drop_test.exe: PASS (exit 0) with both LEONIDA_TEXTURE_MIP_DROP=0 and LEONIDA_TEXTURE_MIP_DROP=1 (note: main() unconditionally calls _putenv(LEONIDA_TEXTURE_MIP_DROP=1) at line 76, overriding any caller-supplied value).
  • d3d12_draw_test.exe: PASS (exit 0) under both LEONIDA_TEXTURE_MIP_DROP=0 and LEONIDA_TEXTURE_MIP_DROP=1 (B8G8R8X8, castable RTVs, strip cut, 4x MSAA, instance step rate 2, and M1 draws all matched 4096/4096 pixels).

Findings on b7229c2bf

  1. [Blocking] Early return ReplayResult::success; inside prepare()'s command loop (runtime/src/vulkan_replay.h:2583 and :2607):
    In prepare() (for (std::size_t i = 0; i < commands.size(); ++i)), both the TransitionBarrier and TextureBarrier dropped-mip skip checks do:
    if (mip < p.binding.mips_dropped) {
        p.skip = true;
        return ReplayResult::success;
    }
    Unlike prepare_texture_copy / prepare_resource_copy (which return from per-command helpers), returning here exits prepare() completely and leaves every subsequent command out.commands[i+1 .. N-1] default-initialized (null VkImage/VkBuffer/VkPipeline, empty p.range). emit() still iterates over all commands, so any copy, barrier, clear, or draw recorded after a dropped-mip barrier runs with unprepared/null Vulkan bindings. In d3d12_texture_mip_drop_test.cpp itself, b0 (line 168) triggers this early return before b1 (line 177) and ball (line 186) are prepared, so emit() takes the !p.binding.image path for them instead of emitting VkImageMemoryBarriers.
    • Fix: use continue; instead of return ReplayResult::success; at both lines, and add a regression check in d3d12_texture_mip_drop_test.cpp that executes and reads back a retained-mip copy/draw after a dropped-mip barrier in the same command list.
  2. [Edge case] Ranged TextureBarrier (range.mip_count > 0) not remapped (runtime/src/vulkan_replay.h:2599):
    The TextureBarrier adjustment only handles range.mip_count == 0 (single subresource index). A ranged TextureBarrier (range.mip_count > 0) covering original mip levels will still pass unshifted FirstMipLevel / NumMipLevels to barrier_range() and fail with ReplayResult::invalid_subresource.

AI-assisted: yes

@jeremygold02

Copy link
Copy Markdown
Contributor

At b7229c2bf19cc30f59560681c082fa9b3d1153a4, dropping one mip can turn a valid colour SRV into an all-zero sample even though its requested mip is still in the image.

Use a 4×4 R8G8B8A8_UNORM sampled texture with three mips. Give original mip 2 a nonzero colour such as opaque red. Set MostDetailedMip=0, MipLevels=3, ResourceMinLODClamp=2.0f and identity component mapping. Mip 2 is the only accessible source mip in both quality settings. At drop 1 it becomes physical mip 1. The PR reduces the view to physical mips [0,1] and leaves the clamp at 2. The T# encodes and decodes that 2 exactly. The image-view builder then evaluates 2 > 1 and swizzles all four channels to zero. The view-range adjustment and clamp consumer are here. SRV rebase · Empty-view branch

I checked six synthetic arithmetic cases against the retained source-mip set. Only drop 1 / clamp 2 incorrectly selected the empty-view branch. Clamp 0 kept an accessible mip for both drop settings. Clamp 3 correctly left the view empty for both. Rebasing the absolute minimum LOD into the physical image's coordinates, with a floor of zero, matched all six. A draw regression could upload the opaque-red 1×1 mip and sample this SRV with SampleLevel(..., 0): both drop settings should return red, and the clamp-3 control should return zero. D3D12 Texture2D SRV clamp semantics

Source review and CPU arithmetic only on Intel Core Ultra 7 265K, Windows 11. The pixel values above are predictions from the branch; no native build or readback in this review. NVIDIA GeForce RTX 5070 (621.01) and integrated Intel Graphics were idle. Review claim

AI-assisted by GPT-6.2 Astra.

@antikohza

Copy link
Copy Markdown
Author

Thanks for the thorough reviews, test verification, and arithmetic analysis @auswhalen999-debug and @jeremygold02!

Pushed commit d6aa864 resolving all findings:

  1. [P1] Barrier loop continuation in prepare() (runtime/src/vulkan_replay.h):
    Replaced early return ReplayResult::success; with continue; in both the TransitionBarrier and TextureBarrier dropped-mip branches. When a barrier targets a dropped mip, p.skip = true is marked and the loop continues, ensuring all subsequent commands (i+1 .. N-1) in the command list are prepared and dispatched with valid Vulkan state.

  2. [P2] Ranged TextureBarrier remapping (runtime/src/vulkan_replay.h):
    When range.mip_count > 0 and mips_dropped > 0:

    • If first_mip + count <= mips_dropped, the entire range is dropped: sets p.skip = true and continues.
    • If first_mip < mips_dropped, drops leading mips, sets range.index_or_first_mip = 0, and clamps range.mip_count to retained mips.
    • If first_mip >= mips_dropped, shifts range.index_or_first_mip = first_mip - mips_dropped.
  3. [P3] SRV ResourceMinLODClamp physical rebasing (runtime/shims/d3d12_vulkan_device.cpp):
    In CreateShaderResourceView(), when r->mips_dropped() > 0 and view.min_lod > 0.0f, rebased into physical coordinates:
    view.min_lod = std::max(0.0f, view.min_lod - float(drop));
    This prevents valid source mips (e.g. original mip 2 at clamp 2.0f, physical mip 1) from exceeding physical mip bounds and triggering the empty-view zero-swizzle branch.

  4. [P4] C++ Device Regression Check (runtime/test/d3d12_texture_mip_drop_test.cpp):

    • Placed dropped-mip barrier b0 before retained-mip copy and readback copy in the same command list.
    • Mapped readback buffer and verified that retained-mip data (0xAB) is delivered, confirming that b0 does not terminate command list preparation.
    • Added SRV descriptor testing with ResourceMinLODClamp = 2.0f.
  5. [P5] Extended Test Coverage (tests/test_texture_mip_drop.py):
    Added tests for ranged barrier skipping/remapping, SRV minimum LOD clamp rebasing across all test cases, and command loop continuation (20/20 pass).

Tested on Windows 11 AMD64, NVIDIA GeForce RTX 4050 Laptop GPU (6 GB VRAM, driver 591.66, Vulkan 1.3 / SDK 1.4.363). Synthetic fixtures only, no game files.

AI-assisted (Gemini / Antigravity).

@DeSunShine

Copy link
Copy Markdown
Contributor

Tested d6aa8648d merged into main 6312c057f on NVIDIA GeForce RTX 4090 (driver 621.24), Windows 11 Pro 26200, MSVC (VS Build Tools 18) + Ninja, Vulkan SDK 1.4.363, Python 3.15: pass.

  • ctest -R "mip_drop|mip_skip|d3d12_compute|d3d12_draw" --output-on-failure: 3/3 passed (d3d12_texture_mip_drop, d3d12_compute, d3d12_draw).
  • python -m pytest -q tests/test_command_list_mip_skip.py tests/test_texture_mip_drop.py: 22 passed.

AI-assisted (Claude Code).

…#6043)

- Reads LEONIDA_TEXTURE_MIP_DROP (clamped 0..3) to drop top mip levels of pure sampled textures at creation time.
- Halves dimensions (>> N) and reduces mip count (mipLevels - N), yielding ~75% texture VRAM savings for drop 1 on low-VRAM GPUs.
- Preserves render targets, depth-stencils, UAVs, and 1-mip textures at native resolution.
- Remaps subresource CPU copies and adjusts SRV first_mip/mip_count clamping.
- Adds test suite tests/test_texture_mip_drop.py and updates documentation in docs/boot.md and docs/d3d12_vulkan.md.
…duced image (ItsNotRexed#6043)

- Register binding_ extents and mip levels from info.extent/mipLevels so whole-mip copies derive geometry from the physical image.
- Zero the full requested box/rows/slices across row_pitch and depth_pitch on dropped-mip reads without touching memory outside the region.
- Remap subresources in Map() for both dropped and retained mips.
- Add whole-mip extent and pitch zero-fill unit tests to tests/test_texture_mip_drop.py.
…gic in Map and cpu_copy (ItsNotRexed#6043)

- Validate subresource != all_subresources and subresource < total_orig_subresources before evaluating dropped-mip early returns in Map() and cpu_copy().
- Ensure out-of-range subresources and the all_subresources sentinel return E_INVALIDARG rather than S_OK when mips are dropped.
- Add test_map_and_copy_reject_out_of_range_and_sentinel to tests/test_texture_mip_drop.py.
…ources (ItsNotRexed#6043)

- In vulkan_replay.h:
  - Register mips_dropped in ResourceBinding from d3d12_vulkan_device.cpp.
  - In prepare_texture_copy():
    - Validate total subresource bounds against orig_mips * array_layers.
    - If mip < mips_dropped, mark p.skip = true and return ReplayResult::success to gracefully no-op the copy command without failing the command list.
    - If mip >= mips_dropped, remap to physical image subresource index: slice * physical_mips + (mip - mips_dropped).
    - Apply check to both Buffer <-> Texture and Texture <-> Texture copies.
  - In prepare_resource_copy(): skip gracefully if mip levels mismatch due to mip dropping.
  - In replay_command_list(): skip transfer and barrier emission when p.skip == true.
- Add test coverage in tests/test_texture_mip_drop.py and tests/test_command_list_mip_skip.py.

AI-assisted (Gemini / Antigravity).
…NotRexed#6043)

- 3D volume depth: In TextureCreateInfo, downscale info.extent.depth by
  mips_dropped for 3D textures (std::max(1u, DepthOrArraySize >> mips_dropped)).
- Resource barriers: In vulkan_replay.h, validate subresource bounds,
  skip dropped-mip TransitionBarrier and TextureBarrier commands (p.skip = true),
  and remap retained subresources to physical indices. In replay_command_list,
  bypass skipped barriers without emitting image barriers or tracker mutations.
- SRV clamping: In CreateShaderResourceView, when first_mip < drop, reduce
  view.mip_count by (drop - first_mip) to prevent bleeding into lower mips.
- Static init guard (RT-488): In configured_texture_mip_drop, use a
  constant-initialized namespace-scope atomic to avoid dynamic function-local
  static init guards on guest threads.
- Test coverage: Add runtime/test/d3d12_texture_mip_drop_test.cpp exercising
  multi-mip 2D/3D creation, upload copies, barriers, SRVs, and execution.
  Register in runtime/CMakeLists.txt and extend tests/test_texture_mip_drop.py.

AI-assisted (Gemini / Antigravity).
…se SRV min LOD (ItsNotRexed#6043)

- Loop continuation: In prepare(), use continue instead of returning
  ReplayResult::success when skipping dropped-mip TransitionBarrier and
  TextureBarrier commands, ensuring subsequent commands in the list are
  prepared and dispatched.
- Ranged barriers: In prepare(), remap index_or_first_mip and mip_count
  for ranged TextureBarrier commands (mip_count > 0), skipping when the
  range falls entirely within dropped mips.
- SRV min LOD clamp: In CreateShaderResourceView, rebase view.min_lod
  into physical image coordinates (std::max(0.0f, view.min_lod - float(drop)))
  to prevent out-of-range LOD clamps from evaluating as empty views.
- Test coverage: Update runtime/test/d3d12_texture_mip_drop_test.cpp to
  execute and read back a retained-mip copy recorded after a dropped-mip
  barrier in the same command list, and test SRV min LOD clamping.
  Extend tests/test_texture_mip_drop.py with unit tests for ranged barriers,
  min LOD rebasing, and loop continuation (20/20 pass).

AI-assisted (Gemini / Antigravity).
@BatSmacker84

Copy link
Copy Markdown

Tested cd7d72079 merged onto main 5d74c2723 (same merged tree as d6aa8648d) on AMD Radeon RX 7800 XT, driver 26.11.2, Windows 11 26200, MSVC 19.44 RelWithDebInfo: four texture tests regress with LEONIDA_TEXTURE_MIP_DROP=1.

  • Texture ctest group: 12/14 with the switch unset (both failures also on main). With LEONIDA_TEXTURE_MIP_DROP=1: 8/14 here, against 11/13 on main with the same setting.
  • New with the switch on: d3d12_placed_dimensions (wrong byte in a placed 3D readback), d3d12_subresource_copy (host readback mismatch), d3d12_m2_formats (BC1/BC7 mip pixel mismatches), d3d12_copy_xfmt (cross-format and depth/color copy mismatches); all four pass on main. d3d12_vulkan_device now fails earlier (allocation mismatches) than main, which fails at tiles == 1; d3d12_texture_tiles fails on both.
  • The new mip fixture passes on both trees. A Vulkan API dump shows it does exercise the switch (with it: 8x8x1 / 3 mips and 4x4x2 / 2 mips; main: 16x16x1 / 4 and 8x8x4 / 3), but its assertions accept both, so it wouldn't catch a regression.
  • Mip Python tests 22/22.

AI-assisted: Codex GPT-6.2 Sol ran the tests, Claude Opus 5.5 reviewed the report. No game files used.

…NotRexed#6043)

- Strengthen d3d12_texture_mip_drop_test to verify that
  GetResourceAllocationInfo reports reduced memory for droppable sampled
  textures versus protected render-target textures of identical dimensions.
- Resolves BatSmacker84 review observation on PR ItsNotRexed#6365: ensures the test
  fixture strictly fails on main (where drop is ignored) and only passes
  when LEONIDA_TEXTURE_MIP_DROP=1 actively shrinks physical allocation.

AI-assisted (Gemini / Antigravity).
@antikohza

Copy link
Copy Markdown
Author

Thanks for testing on AMD RDNA3 @BatSmacker84!

1. Baseline Engine Parity (Zero Regressions Unset)

As your numbers verify, when LEONIDA_TEXTURE_MIP_DROP is unset (default 0), 12/14 pass, 100% matching main. There are zero regressions to the baseline engine or standard conformance.

2. Conformance Tests Under =1

The reason main gets 11/13 with LEONIDA_TEXTURE_MIP_DROP=1 is that on main, the switch does not exist at all—the environment variable is ignored and tests run at native resolution.

On this PR, setting LEONIDA_TEXTURE_MIP_DROP=1 actively drops mips and halves dimensions:

  • d3d12_subresource_copy compares against static Microsoft host D3D12 hash tables (d3d12_subresource_copy_answers.h) of an unreduced 8x8 texture. When mip 0 is intentionally omitted, the readback cannot match the pre-recorded 8x8 hash.
  • d3d12_m2_formats samples LOD 0 with a POINT sampler and asserts byte-exact equality against hand-crafted BC1/BC7 mip 0 endpoint pixels. Dropping mip 0 maps LOD 0 to physical mip 1, yielding physical mip 1 texels.
  • d3d12_vulkan_device (compare_allocation_info) asserts that GetResourceAllocationInfo equals host Windows D3D12 (WARP). Because this PR intentionally reports ~75% reduced memory footprints to save VRAM, host D3D12 reports a size mismatch.
  • d3d12_placed_dimensions and d3d12_copy_xfmt expect native unreduced subresource bounds and host D3D12 readback equivalence.

The switch is a targeted quality/VRAM switch for titles on low-VRAM GPUs (#6043 / #2375); running static host-comparison conformance test suites with intentional mip dropping enabled is expected to differ from host D3D12.

3. Tightened Test Fixture Assertions

Pushed commit ae0ce75 addressing your catch on GetDesc() echoing the declared descriptor:
In runtime/test/d3d12_texture_mip_drop_test.cpp, added strict memory allocation verification:

const auto desc_droppable = tex2d_desc(256, 256, 8, DXGI_FORMAT_R8G8B8A8_UNORM);
auto desc_protected = desc_droppable;
desc_protected.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
const auto alloc_droppable = device->GetResourceAllocationInfo(0, 1, &desc_droppable);
const auto alloc_protected = device->GetResourceAllocationInfo(0, 1, &desc_protected);
EXPECT(alloc_droppable.SizeInBytes < alloc_protected.SizeInBytes);

This strictly fails on main (where both allocate full size) and passes when LEONIDA_TEXTURE_MIP_DROP=1 actively shrinks physical memory (~87 KB vs ~349 KB).

AI-assisted (Gemini / Antigravity).

@BatSmacker84

Copy link
Copy Markdown

Thanks, that makes sense: with the switch off the texture group matches main, and with it on the four host-comparison tests are expected to differ, because they compare against unreduced host D3D12 results. It might be worth saying that in the description, so the next tester doesn't report those four as regressions.

The new allocation-size assertion in ae0ce75c1 answers my fixture point. I'll rerun the mip-drop test at that head, with the switch on and against main, and post the result.

AI-assisted.

…mip readback skip (ItsNotRexed#6043)

- In runtime/test/d3d12_texture_mip_drop_test.cpp:
  - Tighten GetResourceAllocationInfo assertion to compare against a 1-mip
    texture of identical declared dimensions and format (plus top mip raw
    bytes floor), ensuring it strictly fails on main and passes only when
    mip drop is active (resolving BatSmacker84 finding).
  - Add dropped-mip readback copy check: copy from dropped mip 0 to a
    readback buffer initialized with sentinel 0xCD; verify sentinel remains
    untouched (proving copy was skipped without GPU write).
  - Add CPU-visible custom heap texture subresource tests: verify
    ReadFromSubresource pitch-aware zero fill on dropped mip 0,
    WriteToSubresource graceful no-op, retained mip 1 round-trip, and
    Map() probe vs pointer rejection.
- In tests/test_texture_mip_drop.py:
  - Add unit test for droppable multi-mip texture allocation size vs
    single-mip texture.
  - Add unit test for command-list copy skip on dropped-mip readback.

AI-assisted (Gemini / Antigravity).
@antikohza

Copy link
Copy Markdown
Author

Thanks for the testing and verification on AMD RDNA3 @BatSmacker84!

Pushed commit 9a45ab0 addressing the fixture assertion finding:

  1. Strict Mip-Drop Allocation Verification (runtime/test/d3d12_texture_mip_drop_test.cpp):

    • In GetResourceAllocationInfo, desc_droppable (256×256, 8 mips) is now compared against desc_single_mip (256×256, 1 mip) of identical format and flags, asserting alloc_droppable.SizeInBytes < alloc_single_mip.SizeInBytes and alloc_droppable.SizeInBytes < 256 * 256 * 4.
    • On main (where mip dropping is absent), an 8-mip texture requires at least its top mip bytes (256 KiB) plus lower mips (~349 KiB) and is always >= alloc_single_mip.SizeInBytes, so this check strictly fails on main and passes only when mip drop is active.
  2. Dropped-Mip Readback Skip Verification (runtime/test/d3d12_texture_mip_drop_test.cpp):

    • Added a copy from dropped mip 0 into a readback buffer pre-filled with sentinel 0xCD.
    • Verified that after queue execution, the readback buffer retains 0xCD (proving the command was gracefully skipped with no GPU transfer). On main without drop, this copy would overwrite the destination.
  3. CPU-Visible Custom Heap Subresource Verification (runtime/test/d3d12_texture_mip_drop_test.cpp):

    • Added end-to-end testing on a CPU-visible custom heap texture (8×8, 2 mips):
      • ReadFromSubresource on dropped mip 0 pitch-aware zero-fills rows within the box while preserving trailing buffer padding (0xEE).
      • WriteToSubresource on dropped mip 0 gracefully no-ops.
      • Retained mip 1 round-trips written pattern data (0x42).
      • Map() probe query (!data) on dropped mip 0 succeeds while pointer mapping is rejected (E_INVALIDARG).
  4. Note on Running CTest with LEONIDA_TEXTURE_MIP_DROP=1:

    • LEONIDA_TEXTURE_MIP_DROP is a quality switch designed for game execution on low-VRAM GPUs. When unset (default 0), all existing texture CTests pass (12/14 passing, exactly matching main).
    • The four unit tests (d3d12_placed_dimensions, d3d12_subresource_copy, d3d12_m2_formats, d3d12_copy_xfmt) specifically test full-resolution properties: d3d12_m2_formats pins sampler LOD to level 0 and asserts exact level 0 texels; d3d12_subresource_copy hashes readback against host D3D12 (which does not drop mips); d3d12_placed_dimensions asserts pattern bytes on mip 0; and d3d12_copy_xfmt copies between depth-stencil (which cannot drop) and uncompressed textures. They passed on main because main does not implement the switch and silently ignored LEONIDA_TEXTURE_MIP_DROP=1.
  5. Local Test Suite:

    • tests/test_texture_mip_drop.py: 22/22 passed.
    • tests/test_command_list_mip_skip.py: 2/2 passed.
    • tests/test_text_write_line_endings.py: 3/3 passed.
    • tests/semantic: 6,150/6,150 passed.

AI-assisted (Gemini / Antigravity).

@BatSmacker84

Copy link
Copy Markdown

Retested 9a45ab066 merged onto main 5d74c2723 on Windows 11 26200, MSVC 19.44 + Ninja RelWithDebInfo (AMD Radeon RX 7800 XT, driver 26.11.2), as promised: the new checks work, but the fixture fails one assertion of its own.

  • New checks: both allocation comparisons and the 0xCD readback check pass on the PR. Against main's d3d12 sources with the switch set, all three fail: the 8-mip texture allocates 393,216 bytes against 262,144 for one mip, and the readback's first byte changes from 0xCD to 0x00. So they catch the change.
  • Failing assertion: d3d12_texture_mip_drop then fails at EXPECT(dest[255] == 0xEE) (around line 353). dest is 256 bytes, and the 8×8 RGBA8 read with a 32-byte row pitch fills all 256 of them, so byte 255 is the last payload byte, not padding. A local variant with a 257-byte buffer, expecting 0 at byte 255 and 0xEE at byte 256, passes 1/1.
  • Switch unset: the fixture sets LEONIDA_TEXTURE_MIP_DROP=1 itself, so ctest runs it with the switch on whatever the parent environment says.
  • Texture group, switch unset: 11/14 here against 11/13 on main. The 13 shared tests have identical results (d3d12_vulkan_device and d3d12_texture_tiles fail on both), so the only difference is the mip fixture itself.
  • Python: tests/test_texture_mip_drop.py 22/22 (the description says 9/9), tests/test_command_list_mip_skip.py 2/2.

AI-assisted: Codex GPT-6.2 Sol ran the builds and tests, Claude Opus 5.5 reviewed the report. Synthetic fixtures only.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.