From 87064bfe8e73155542006b81d01834a8687889a3 Mon Sep 17 00:00:00 2001 From: antikohza <244305127+antikohza@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:24:38 +0530 Subject: [PATCH] d3d12: implement LEONIDA_TEXTURE_MIP_DROP quality switch (#6043) Add low-VRAM quality switch LEONIDA_TEXTURE_MIP_DROP (0..3, default 0) to drop top mip level(s) of pure sampled textures at creation time (#6043). - Drops top N mips of pure sampled textures (no RenderTarget, DepthStencil, or UAV) to reduce VRAM consumption by ~75% (drop 1) or ~93.75% (drop 2). - Replaces function-local static guards with constant-initialized std::atomic to avoid thread-safety init guards on guest threads (RT-488). - Automatically scales width, height, and depth dimensions down to a minimum of 1. - Accurately remaps Subresource in Map(), Unmap(), WriteToSubresource(), and ReadFromSubresource(). - In cpu_copy, skips writes to dropped mips (S_OK) and zeroes buffers on read; validates subresource bounds and sentinel against original mip counts. - Remaps SRV MostDetailedMip and adjusts ResourceMinLODClamp down by dropped mips. - Remaps command-list subresources and skips dropped-mip copies (prepare_texture_copy, prepare_resource_copy) and barriers (TransitionBarrier, TextureBarrier). - Adds standalone test suite test_texture_mip_drop.py (22 tests) and test_command_list_mip_skip.py (2 tests). - Adds D3D12 device fixture d3d12_texture_mip_drop_test.cpp validating real D3D12/Vulkan allocations, SRV binding, and readback skip. --- docs/boot.md | 3 + docs/d3d12_vulkan.md | 5 +- runtime/CMakeLists.txt | 7 + runtime/shims/d3d12_vulkan_device.cpp | 128 ++++- runtime/src/vulkan_replay.h | 104 +++- runtime/test/d3d12_texture_mip_drop_test.cpp | 374 +++++++++++++ tests/test_command_list_mip_skip.py | 71 +++ tests/test_texture_mip_drop.py | 529 +++++++++++++++++++ 8 files changed, 1205 insertions(+), 16 deletions(-) create mode 100644 runtime/test/d3d12_texture_mip_drop_test.cpp create mode 100644 tests/test_command_list_mip_skip.py create mode 100644 tests/test_texture_mip_drop.py diff --git a/docs/boot.md b/docs/boot.md index 7ec69f0314..d3dac9fae0 100644 --- a/docs/boot.md +++ b/docs/boot.md @@ -82,6 +82,9 @@ Useful switches: open is always traced as `file_open_failed` (path, error, caller) when `--trace` is on. * `LEONIDA_VK_VALIDATION=1` enables the Khronos validation layer with the Vulkan backend (startup overhead; it is a diagnostic). +* `LEONIDA_TEXTURE_MIP_DROP=N` (0..3, default 0, #6043) drops the top N mip level(s) of pure sampled textures at + creation time to reduce VRAM consumption on low-VRAM GPUs (e.g. 6 GB or 4 GB cards). Dropping 1 mip halves width + and height, saving ~75% texture memory without altering render targets, depth-stencil surfaces, or UAVs. * `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` when MSI Afterburner or OBS is installed; their implicit layers add swapchain usage that shows up as validation errors ([testing.md](testing.md), "Known problems"). diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 3ae29163e5..9344fc7263 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1568,7 +1568,10 @@ The runtime allocates image keys from `0x100000000` (4 GiB) in 256-byte steps, a - Textures and default-heap buffers outside the arena prefer `DEVICE_LOCAL` and need no host access. When VRAM is full they still get memory, from the next type `memory_type_order` lists, which is system memory. The first one that does is logged once (`[rt] d3d12: a N-byte allocation did not fit in device-local memory ...`, D3D-299, - `leonida::spilled_to_host`), so a run on a 4 GB GPU shows that it spilled (#2375). + `leonida::spilled_to_host`), so a run on a 4 GB GPU shows that it spilled (#2375). To fit textures within 4 GB + or 6 GB VRAM budgets and avoid host spills, `LEONIDA_TEXTURE_MIP_DROP=N` (0..3, default 0, #6043) drops the top N + mip levels from pure sampled textures at creation time (saving ~75% VRAM for drop 1, ~93.75% for drop 2) while + preserving render targets, depth-stencil surfaces, and UAV attachments at full resolution. **Capacity.** The arena is sized by buffers, descriptor heaps and shader code, not by textures. The allocator tracks the high-water mark; start with a configurable capacity (for example 4 GiB for the loading/menu path) and diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 64e346f40a..aee0b1e328 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1884,6 +1884,13 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_texture1d COMMAND d3d12_texture1d_test) set_tests_properties(d3d12_texture1d PROPERTIES SKIP_RETURN_CODE 77) + add_executable(d3d12_texture_mip_drop_test test/d3d12_texture_mip_drop_test.cpp) + target_link_libraries(d3d12_texture_mip_drop_test PRIVATE gta6rt_d3d12_com dxguid) + target_compile_definitions(d3d12_texture_mip_drop_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_texture_mip_drop_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_texture_mip_drop COMMAND d3d12_texture_mip_drop_test) + set_tests_properties(d3d12_texture_mip_drop PROPERTIES SKIP_RETURN_CODE 77) + # Placed 1D and 3D textures against the host runtime and WARP, and a copy round trip through them. add_executable(d3d12_placed_dimensions_test test/d3d12_placed_dimensions_test.cpp) target_link_libraries(d3d12_placed_dimensions_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0273f9339b..80dd6ce928 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -485,6 +485,25 @@ UINT view_slices(const D3D12_RESOURCE_DESC& resource, UINT first_layer, UINT lay return remaining ? resource.DepthOrArraySize - first_layer : layer_count; } +namespace { +std::atomic s_texture_mip_drop{-1}; +} + +// Returns 0, 1, 2, or 3 from LEONIDA_TEXTURE_MIP_DROP (default 0). +// Uses a constant-initialized atomic to avoid function-local static init guards on guest threads (RT-488). +inline UINT configured_texture_mip_drop() { + int drop = s_texture_mip_drop.load(std::memory_order_relaxed); + if (drop >= 0) return static_cast(drop); + char text[16]{}; + size_t length = 0; + int parsed = 0; + if (getenv_s(&length, text, "LEONIDA_TEXTURE_MIP_DROP") == 0 && length > 1) { + parsed = std::clamp(std::atoi(text), 0, 3); + } + s_texture_mip_drop.store(parsed, std::memory_order_relaxed); + return static_cast(parsed); +} + // The VkImage a texture description becomes, with its mip count already resolved (MipLevels != 0). Shared by // texture creation and GetResourceAllocationInfo, so the sizes reported are the sizes later allocated. // Keeps the optional VkImageFormatListCreateInfo alongside VkImageCreateInfo so info.pNext stays valid. @@ -494,6 +513,7 @@ struct TextureCreateInfo { VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; VkImageFormatListCreateInfo format_list{VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO}; std::array view_formats{}; + UINT mips_dropped = 0; TextureCreateInfo(const D3D12_RESOURCE_DESC& desc, const Format& format, bool attachment_usable) { const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; @@ -503,9 +523,24 @@ struct TextureCreateInfo { info.flags |= VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT; info.imageType = volume ? VK_IMAGE_TYPE_3D : one_d ? VK_IMAGE_TYPE_1D : VK_IMAGE_TYPE_2D; info.format = format.format; - info.extent = {std::uint32_t(desc.Width), one_d ? 1u : desc.Height, - volume ? UINT(desc.DepthOrArraySize) : 1u}; - info.mipLevels = desc.MipLevels; + + // Low-VRAM texture quality switch (LEONIDA_TEXTURE_MIP_DROP, #6043): + // Only drop mips for pure sampled textures (no RenderTarget, DepthStencil, or UAV): + const bool is_render_target = (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) != 0; + const bool is_depth_stencil = (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) != 0; + const bool is_uav = (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) != 0; + const bool can_drop = !is_render_target && !is_depth_stencil && !is_uav; + + if (can_drop && desc.MipLevels > 1) { + mips_dropped = std::min(configured_texture_mip_drop(), desc.MipLevels - 1); + } + + const uint32_t width = std::max(1u, static_cast(desc.Width >> mips_dropped)); + const uint32_t height = one_d ? 1u : std::max(1u, desc.Height >> mips_dropped); + const uint32_t depth = volume ? std::max(1u, UINT(desc.DepthOrArraySize) >> mips_dropped) : 1u; + + info.extent = {width, height, depth}; + info.mipLevels = desc.MipLevels - mips_dropped; info.arrayLayers = volume ? 1 : desc.DepthOrArraySize; info.samples = VkSampleCountFlagBits(std::max(1u, desc.SampleDesc.Count)); info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; @@ -1841,6 +1876,8 @@ class Resource final VkImageAspectFlags aspects() const { return aspects_; } bool rgb96() const { return rgb96_; } // a 96-bit texture in an RGBA32 image std::uint64_t image_address() const { return image_address_; } // what a T# names the texture by + UINT mips_dropped() const { return mips_dropped_; } + UINT image_mip_levels() const { return desc_.MipLevels > mips_dropped_ ? desc_.MipLevels - mips_dropped_ : 1; } VkMemoryPropertyFlags memory_flags() const { return memory_flags_; } // of the memory type behind it const DeviceState& device_state() const { return device_; } @@ -2191,6 +2228,7 @@ class Resource final const bool one_d = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; if (desc_.MipLevels == 0) desc_.MipLevels = full_mips(desc_.Width, desc_.Height, depth); TextureCreateInfo create(desc_, format, device_.color_attachment_usable(format.format)); + mips_dropped_ = create.mips_dropped; VkImageCreateInfo& info = create.info; if (!castable.empty()) { // D3D12 always allows a view in the resource's own format, whether or not the castable list names @@ -2252,14 +2290,15 @@ class Resource final binding.depth24 = format.d24; binding.format = format.format; binding.aspects = format.aspects; - binding.width = std::uint32_t(desc_.Width); - binding.height = one_d ? 1u : desc_.Height; - binding.mip_levels = desc_.MipLevels; + binding.width = info.extent.width; + binding.height = info.extent.height; + binding.mip_levels = info.mipLevels; binding.array_layers = info.arrayLayers; - binding.depth = depth; + binding.depth = info.extent.depth; binding.volume = volume; binding.line = one_d; binding.samples = samples; + binding.mips_dropped = mips_dropped_; binding.color_attachment = (info.usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) != 0; binding.sampled = (info.usage & VK_IMAGE_USAGE_SAMPLED_BIT) != 0; binding.simultaneous_access = (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS) != 0; @@ -2354,9 +2393,22 @@ class Resource final // WriteToSubresource/ReadFromSubresource. HRESULT STDMETHODCALLTYPE Map(UINT subresource, const D3D12_RANGE* read, void** data) override { if (image_) { + if (subresource == leonida::all_subresources) return E_INVALIDARG; + const UINT orig_layers = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 1 : desc_.DepthOrArraySize; + const UINT total_subresources = desc_.MipLevels * orig_layers; + if (subresource >= total_subresources) return E_INVALIDARG; + if (mips_dropped_ > 0) { + const UINT orig_mips = desc_.MipLevels; + const UINT mip = subresource % orig_mips; + const UINT slice = subresource / orig_mips; + if (mip < mips_dropped_) { + return !data && cpu_visible() ? S_OK : E_INVALIDARG; + } + const UINT new_mips = desc_.MipLevels - mips_dropped_; + subresource = slice * new_mips + (mip - mips_dropped_); + } VkImageSubresourceRange range{}; - return !data && cpu_visible() && subresource != leonida::all_subresources && - leonida::image_range(binding_, subresource, range) + return !data && cpu_visible() && leonida::image_range(binding_, subresource, range) ? S_OK : E_INVALIDARG; } @@ -2424,6 +2476,44 @@ class Resource final HRESULT cpu_copy(bool write, UINT subresource, const D3D12_BOX* box, void* data, UINT row_pitch, UINT depth_pitch) { if (!image_ || !data) return E_INVALIDARG; + if (subresource == leonida::all_subresources) return E_INVALIDARG; + const UINT orig_layers = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 1 : desc_.DepthOrArraySize; + const UINT total_subresources = desc_.MipLevels * orig_layers; + if (subresource >= total_subresources) return E_INVALIDARG; + if (mips_dropped_ > 0) { + const UINT orig_mips = desc_.MipLevels; + const UINT mip = subresource % orig_mips; + const UINT slice = subresource / orig_mips; + if (mip < mips_dropped_) { + if (write) return S_OK; + // Read from a dropped mip: zero the requested box/rows/slices across row_pitch and depth_pitch. + const bool volume = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + const bool one_d = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; + const std::uint32_t width = std::max(1u, std::uint32_t(desc_.Width) >> mip); + const std::uint32_t height = one_d ? 1u : std::max(1u, desc_.Height >> mip); + const std::uint32_t depth = volume ? std::max(1u, UINT(desc_.DepthOrArraySize) >> mip) : 1u; + const D3D12_BOX b = box ? *box : D3D12_BOX{0, 0, 0, width, height, depth}; + if (b.right > width || b.bottom > height || b.back > depth) return E_INVALIDARG; + const auto block = leonida::copy_block_format(binding_, aspects_); + if (!block.bytes) return E_INVALIDARG; + const std::uint32_t k = block.block; + if (b.left % k || b.top % k || (b.right % k && b.right != width) || (b.bottom % k && b.bottom != height)) + return E_INVALIDARG; + if (b.left >= b.right || b.top >= b.bottom || b.front >= b.back) return S_OK; + const std::uint32_t rows = (b.bottom - b.top + k - 1) / k; + const std::uint64_t row_bytes = std::uint64_t((b.right - b.left + k - 1) / k) * block.bytes; + const std::uint32_t slices = b.back - b.front; + auto* bytes = static_cast(data); + for (std::uint32_t z = 0; z < slices; ++z) { + for (std::uint32_t y = 0; y < rows; ++y) { + std::memset(bytes + std::uint64_t(z) * depth_pitch + std::uint64_t(y) * row_pitch, 0, row_bytes); + } + } + return S_OK; + } + 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; if (!r.rows || !r.slices) return S_OK; // an empty box: nothing to copy @@ -2632,6 +2722,7 @@ class Resource final // A placed buffer's heap range, held as a D3D12 placed resource holds its heap: the app may release the heap // first, and the range must not go to another allocation while this buffer lives. std::shared_ptr heap_range_; + UINT mips_dropped_ = 0; }; // DXGI -> Vulkan for vertex attributes, with each element's size for D3D12_APPEND_ALIGNED_ELEMENT. @@ -6580,6 +6671,25 @@ class Device final return; } } + if (r->mips_dropped() > 0) { + const UINT drop = r->mips_dropped(); + if (view.first_mip >= drop) { + view.first_mip -= drop; + } else { + const UINT dropped_from_view = drop - view.first_mip; + view.first_mip = 0; + if (view.mip_count != UINT_MAX) { + view.mip_count = (view.mip_count > dropped_from_view) ? (view.mip_count - dropped_from_view) : 1; + } + } + const UINT avail_mips = r->image_mip_levels() > view.first_mip ? (r->image_mip_levels() - view.first_mip) : 1; + if (view.mip_count != UINT_MAX && view.mip_count > 0) { + view.mip_count = std::min(view.mip_count, avail_mips); + } + if (view.min_lod > 0.0f) { + view.min_lod = std::max(0.0f, view.min_lod - float(drop)); + } + } write_image_descriptor(*r, view, destination, false); } diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 889bb71f72..341514f355 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -64,6 +64,7 @@ struct ResourceBinding { std::uint32_t height = 1; std::uint32_t mip_levels = 1; std::uint32_t array_layers = 1; + std::uint32_t mips_dropped = 0; bool presentable = false; // a swapchain image: common/present maps to PRESENT_SRC_KHR bool simultaneous_access = false; // D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS: always GENERAL bool not_zeroed = false; // D3D12_HEAP_FLAG_CREATE_NOT_ZEROED: first use skips the zero fill @@ -1674,9 +1675,35 @@ inline bool copy_subresource(const ResourceBinding& resource, std::uint32_t subr // Block-compressed footprints are padded to whole blocks; the Vulkan extent stops at the mip edge. inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { if (!copy.dst.footprint && !copy.src.footprint) { + std::uint32_t dst_sub = copy.dst.subresource; + std::uint32_t src_sub = copy.src.subresource; + if (p.binding.mips_dropped > 0) { + const std::uint32_t orig_mips = p.binding.mip_levels + p.binding.mips_dropped; + const std::uint32_t total = orig_mips * p.binding.array_layers; + if (dst_sub == all_subresources || dst_sub >= total) return ReplayResult::invalid_subresource; + const std::uint32_t mip = dst_sub % orig_mips; + const std::uint32_t slice = dst_sub / orig_mips; + if (mip < p.binding.mips_dropped) { + p.skip = true; + return ReplayResult::success; + } + dst_sub = slice * p.binding.mip_levels + (mip - p.binding.mips_dropped); + } + if (p.source.mips_dropped > 0) { + const std::uint32_t orig_mips = p.source.mip_levels + p.source.mips_dropped; + const std::uint32_t total = orig_mips * p.source.array_layers; + if (src_sub == all_subresources || src_sub >= total) return ReplayResult::invalid_subresource; + const std::uint32_t mip = src_sub % orig_mips; + const std::uint32_t slice = src_sub / orig_mips; + if (mip < p.source.mips_dropped) { + p.skip = true; + return ReplayResult::success; + } + src_sub = slice * p.source.mip_levels + (mip - p.source.mips_dropped); + } VkImageSubresourceRange dst{}, src{}; - if (!copy_subresource(p.binding, copy.dst.subresource, dst) || - !copy_subresource(p.source, copy.src.subresource, src)) + if (!copy_subresource(p.binding, dst_sub, dst) || + !copy_subresource(p.source, src_sub, src)) return ReplayResult::invalid_subresource; if ((dst.aspectMask != src.aspectMask && !depth_colour_pair(p.binding, p.source)) || p.binding.volume != p.source.volume || p.binding.samples != p.source.samples || @@ -1801,8 +1828,23 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { const CopyLocation& texture = upload ? copy.dst : copy.src; const CopyLocation& placed = upload ? copy.src : copy.dst; if (!buffer.buffer) return ReplayResult::invalid_copy; + + std::uint32_t tex_sub = texture.subresource; + if (image.mips_dropped > 0) { + const std::uint32_t orig_mips = image.mip_levels + image.mips_dropped; + const std::uint32_t total = orig_mips * image.array_layers; + if (tex_sub == all_subresources || tex_sub >= total) return ReplayResult::invalid_subresource; + const std::uint32_t mip = tex_sub % orig_mips; + const std::uint32_t slice = tex_sub / orig_mips; + if (mip < image.mips_dropped) { + p.skip = true; + return ReplayResult::success; + } + tex_sub = slice * image.mip_levels + (mip - image.mips_dropped); + } + VkImageSubresourceRange range{}; - if (!copy_subresource(image, texture.subresource, range)) return ReplayResult::invalid_subresource; + if (!copy_subresource(image, tex_sub, range)) return ReplayResult::invalid_subresource; if (image.samples != 1) return ReplayResult::invalid_copy; // multisampled textures have no footprint const BlockFormat format = copy_block_format(image, range.aspectMask); // A 12-byte texel does not divide D3D12's 256-byte pitches; an rgb96 copy hands Vulkan the scratch buffer of @@ -2625,8 +2667,23 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (p.binding.image == VK_NULL_HANDLE) { if (transition->subresource != 0 && transition->subresource != all_subresources) return ReplayResult::invalid_subresource; - } else if (!image_range(p.binding, transition->subresource, p.range)) { - return ReplayResult::invalid_subresource; + } else { + std::uint32_t sub = transition->subresource; + if (p.binding.mips_dropped > 0 && sub != all_subresources) { + const std::uint32_t orig_mips = p.binding.mip_levels + p.binding.mips_dropped; + const std::uint32_t total = orig_mips * p.binding.array_layers; + if (sub >= total) return ReplayResult::invalid_subresource; + const std::uint32_t mip = sub % orig_mips; + const std::uint32_t slice = sub / orig_mips; + if (mip < p.binding.mips_dropped) { + p.skip = true; + continue; + } + sub = slice * p.binding.mip_levels + (mip - p.binding.mips_dropped); + } + if (!image_range(p.binding, sub, p.range)) { + return ReplayResult::invalid_subresource; + } } } else if (std::holds_alternative(command) || std::holds_alternative(command)) { if (!vk.pipeline_barrier2) return ReplayResult::unsupported; @@ -2635,7 +2692,39 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } else if (const auto* texture = std::get_if(&command)) { if (!vk.pipeline_barrier2) return ReplayResult::unsupported; if (!bind(texture->resource)) return ReplayResult::unresolved_resource; - if (!p.binding.image || !barrier_range(p.binding, texture->range, p.range)) + BarrierSubresourceRange range = texture->range; + if (p.binding.mips_dropped > 0 && range.index_or_first_mip != all_subresources) { + const std::uint32_t orig_mips = p.binding.mip_levels + p.binding.mips_dropped; + if (range.mip_count == 0) { + const std::uint32_t total = orig_mips * p.binding.array_layers; + if (range.index_or_first_mip >= total) return ReplayResult::invalid_subresource; + const std::uint32_t mip = range.index_or_first_mip % orig_mips; + const std::uint32_t slice = range.index_or_first_mip / orig_mips; + if (mip < p.binding.mips_dropped) { + p.skip = true; + continue; + } + range.index_or_first_mip = slice * p.binding.mip_levels + (mip - p.binding.mips_dropped); + } else { + const std::uint32_t first_mip = range.index_or_first_mip; + const std::uint32_t count = range.mip_count; + if (first_mip >= orig_mips || count > orig_mips - first_mip) + return ReplayResult::invalid_subresource; + if (first_mip + count <= p.binding.mips_dropped) { + p.skip = true; + continue; + } + if (first_mip < p.binding.mips_dropped) { + const std::uint32_t dropped_from_range = p.binding.mips_dropped - first_mip; + range.index_or_first_mip = 0; + range.mip_count = (count > dropped_from_range) ? (count - dropped_from_range) : 1; + } else { + range.index_or_first_mip = first_mip - p.binding.mips_dropped; + } + range.mip_count = std::min(range.mip_count, p.binding.mip_levels - range.index_or_first_mip); + } + } + if (!p.binding.image || !barrier_range(p.binding, range, p.range)) return ReplayResult::invalid_subresource; } else if (const auto* color_clear = std::get_if(&command)) { if (!bind(color_clear->target.resource)) return ReplayResult::unresolved_resource; @@ -3479,6 +3568,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c command); if (const auto* transition = std::get_if(&command)) { + if (p.skip) continue; const VulkanAccess from = vulkan_access(transition->before, p.binding.presentable, predicates); const VulkanAccess to = vulkan_access(transition->after, p.binding.presentable, predicates); if (!p.binding.image) { @@ -3532,6 +3622,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c dependency.pMemoryBarriers = &barrier; vk.pipeline_barrier2(command_buffer, &dependency); } else if (const auto* texture = std::get_if(&command)) { + if (p.skip) continue; const auto range = detail::planes_for_layout(p.binding, p.range, separate); const bool discard = (texture->flags & texture_barrier_discard) || texture->layout_before == d3d12_layout::undefined; @@ -3701,6 +3792,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c }); } else if (std::holds_alternative(command) || std::holds_alternative(command) || std::holds_alternative(command)) { + if (p.skip) continue; const auto [dst_id, src_id] = copy_ids(command); if (!p.predicated_copy.empty()) { end_statistics(); diff --git a/runtime/test/d3d12_texture_mip_drop_test.cpp b/runtime/test/d3d12_texture_mip_drop_test.cpp new file mode 100644 index 0000000000..ea239c78fa --- /dev/null +++ b/runtime/test/d3d12_texture_mip_drop_test.cpp @@ -0,0 +1,374 @@ +// Verifies LEONIDA_TEXTURE_MIP_DROP quality switch end-to-end on a Vulkan device (#6043 / #6365): +// - Multi-mip 2D texture creation with mips dropped at runtime. +// - 3D volume texture creation verifying depth is right-shifted by mips_dropped. +// - CopyTextureRegion gracefully skipping dropped mips while remapping retained subresources. +// - ResourceBarrier Transition and Texture barriers skipping dropped subresources and remapping retained mips. +// - CreateShaderResourceView partial mip views clamping without mip_count bleed. +// - ExecuteCommandLists submission executing without error or refusal. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include + +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +D3D12_RESOURCE_DESC tex2d_desc(UINT width, UINT height, UINT mips, DXGI_FORMAT format) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = width; + d.Height = height; + d.DepthOrArraySize = 1; + d.MipLevels = mips; + d.Format = format; + d.SampleDesc.Count = 1; + d.Flags = D3D12_RESOURCE_FLAG_NONE; + return d; +} + +D3D12_RESOURCE_DESC tex3d_desc(UINT width, UINT height, UINT depth, UINT mips, DXGI_FORMAT format) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + d.Width = width; + d.Height = height; + d.DepthOrArraySize = depth; + d.MipLevels = mips; + d.Format = format; + d.SampleDesc.Count = 1; + d.Flags = D3D12_RESOURCE_FLAG_NONE; + return d; +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = bytes; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return d; +} + +} // namespace + +int main() { +#ifdef _WIN32 + _putenv("LEONIDA_TEXTURE_MIP_DROP=1"); +#else + setenv("LEONIDA_TEXTURE_MIP_DROP", "1", 1); +#endif + + Ref device; + const HRESULT hr = rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p)); + if (hr == E_FAIL || hr == DXGI_ERROR_UNSUPPORTED) return 77; // No Vulkan GPU + EXPECT(SUCCEEDED(hr)); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + Ref queue; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + + Ref allocator; + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + + Ref list; + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, IID_PPV_ARGS(&list.p)))); + + D3D12_HEAP_PROPERTIES default_heap{}; + default_heap.Type = D3D12_HEAP_TYPE_DEFAULT; + + D3D12_HEAP_PROPERTIES upload_heap{}; + upload_heap.Type = D3D12_HEAP_TYPE_UPLOAD; + + D3D12_HEAP_PROPERTIES readback_heap{}; + readback_heap.Type = D3D12_HEAP_TYPE_READBACK; + + // 1. 2D Texture (16x16, 4 mips): with drop 1, physical image is 8x8, 3 mips. + Ref tex2d; + const auto desc2d = tex2d_desc(16, 16, 4, DXGI_FORMAT_R8G8B8A8_UNORM); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc2d, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&tex2d.p)))); + // D3D12 GetDesc() preserves the application's declared description + EXPECT(tex2d->GetDesc().MipLevels == 4); + EXPECT(tex2d->GetDesc().Width == 16); + + // 1b. Strict Mip-Drop Verification: GetResourceAllocationInfo must report reduced memory + // for a droppable sampled texture vs a 1-mip texture of identical width/height. + // On main (where drop is ignored), an 8-mip texture requires >= bytes of its top mip (256 KiB) + // and is >= single-mip texture size (256 KiB). Under drop 1, the physical image is 128x128 (7 mips, ~128 KiB), + // which is strictly smaller than the 1-mip texture and strictly less than top mip bytes 256*256*4. + const auto desc_droppable = tex2d_desc(256, 256, 8, DXGI_FORMAT_R8G8B8A8_UNORM); + const auto desc_single_mip = tex2d_desc(256, 256, 1, DXGI_FORMAT_R8G8B8A8_UNORM); + const auto alloc_droppable = device->GetResourceAllocationInfo(0, 1, &desc_droppable); + const auto alloc_single_mip = device->GetResourceAllocationInfo(0, 1, &desc_single_mip); + EXPECT(alloc_droppable.SizeInBytes < alloc_single_mip.SizeInBytes); + EXPECT(alloc_droppable.SizeInBytes < 256 * 256 * 4); + + // 2. 3D Volume Texture (8x8x4, 3 mips): with drop 1, width=4, height=4, depth=2. + Ref tex3d; + const auto desc3d = tex3d_desc(8, 8, 4, 3, DXGI_FORMAT_R8G8B8A8_UNORM); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc3d, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&tex3d.p)))); + EXPECT(tex3d->GetDesc().DepthOrArraySize == 4); + + // 3. Upload & Readback Buffers + Ref upload; + const auto udesc = buffer_desc(4096); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &udesc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload.p)))); + + void* upload_map = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, &upload_map))); + std::memset(static_cast(upload_map) + 512, 0xAB, 256); + upload->Unmap(0, nullptr); + + Ref readback; + const auto rdesc = buffer_desc(4096); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &rdesc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p)))); + + // Readback buffer for dropped mip 0: pre-fill with sentinel 0xCD. + // Because mip 0 copy from texture is skipped under drop 1, this sentinel remains untouched. + Ref readback_dropped; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &rdesc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback_dropped.p)))); + void* r0_map = nullptr; + EXPECT(SUCCEEDED(readback_dropped->Map(0, nullptr, &r0_map))); + std::memset(r0_map, 0xCD, 256); + readback_dropped->Unmap(0, nullptr); + + // 4. Command List: + // A. Dropped-mip barrier (b0): subresource 0 is dropped. + // Must be skipped (p.skip = true) without prematurely aborting prepare() for subsequent commands! + D3D12_RESOURCE_BARRIER b0{}; + b0.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b0.Transition.pResource = tex2d.p; + b0.Transition.Subresource = 0; // dropped mip + b0.Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON; + b0.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; + list->ResourceBarrier(1, &b0); + + // B. CopyTextureRegion targeting dropped mip 0 (skipped) + D3D12_TEXTURE_COPY_LOCATION dst_loc0{}; + dst_loc0.pResource = tex2d.p; + dst_loc0.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + dst_loc0.SubresourceIndex = 0; + + D3D12_TEXTURE_COPY_LOCATION src_loc0{}; + src_loc0.pResource = upload.p; + src_loc0.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + src_loc0.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + src_loc0.PlacedFootprint.Footprint.Width = 16; + src_loc0.PlacedFootprint.Footprint.Height = 16; + src_loc0.PlacedFootprint.Footprint.Depth = 1; + src_loc0.PlacedFootprint.Footprint.RowPitch = 256; + list->CopyTextureRegion(&dst_loc0, 0, 0, 0, &src_loc0, nullptr); + + // C. Retained mip 1 barrier (remapped to physical mip 0) + D3D12_RESOURCE_BARRIER b1{}; + b1.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b1.Transition.pResource = tex2d.p; + b1.Transition.Subresource = 1; // retained mip + b1.Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON; + b1.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; + list->ResourceBarrier(1, &b1); + + // D. Copy to retained mip 1 (physical mip 0) + D3D12_TEXTURE_COPY_LOCATION dst_loc1{}; + dst_loc1.pResource = tex2d.p; + dst_loc1.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + dst_loc1.SubresourceIndex = 1; + + D3D12_TEXTURE_COPY_LOCATION src_loc1{}; + src_loc1.pResource = upload.p; + src_loc1.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + src_loc1.PlacedFootprint.Offset = 512; + src_loc1.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + src_loc1.PlacedFootprint.Footprint.Width = 8; + src_loc1.PlacedFootprint.Footprint.Height = 8; + src_loc1.PlacedFootprint.Footprint.Depth = 1; + src_loc1.PlacedFootprint.Footprint.RowPitch = 256; + list->CopyTextureRegion(&dst_loc1, 0, 0, 0, &src_loc1, nullptr); + + // E. Transition retained mip 1 to COPY_SOURCE and readback to verify execution after b0 + D3D12_RESOURCE_BARRIER b1_src{}; + b1_src.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b1_src.Transition.pResource = tex2d.p; + b1_src.Transition.Subresource = 1; + b1_src.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; + b1_src.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &b1_src); + + D3D12_TEXTURE_COPY_LOCATION src_tex{}; + src_tex.pResource = tex2d.p; + src_tex.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + src_tex.SubresourceIndex = 1; + + D3D12_TEXTURE_COPY_LOCATION dst_rb{}; + dst_rb.pResource = readback.p; + dst_rb.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst_rb.PlacedFootprint.Offset = 0; + dst_rb.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + dst_rb.PlacedFootprint.Footprint.Width = 8; + dst_rb.PlacedFootprint.Footprint.Height = 8; + dst_rb.PlacedFootprint.Footprint.Depth = 1; + dst_rb.PlacedFootprint.Footprint.RowPitch = 256; + list->CopyTextureRegion(&dst_rb, 0, 0, 0, &src_tex, nullptr); + + // E2. Copy from dropped mip 0 to readback_dropped: must be gracefully skipped (p.skip = true) + D3D12_TEXTURE_COPY_LOCATION src_dropped{}; + src_dropped.pResource = tex2d.p; + src_dropped.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + src_dropped.SubresourceIndex = 0; // dropped mip + + D3D12_TEXTURE_COPY_LOCATION dst_dropped{}; + dst_dropped.pResource = readback_dropped.p; + dst_dropped.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst_dropped.PlacedFootprint.Offset = 0; + dst_dropped.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + dst_dropped.PlacedFootprint.Footprint.Width = 16; + dst_dropped.PlacedFootprint.Footprint.Height = 16; + dst_dropped.PlacedFootprint.Footprint.Depth = 1; + dst_dropped.PlacedFootprint.Footprint.RowPitch = 256; + list->CopyTextureRegion(&dst_dropped, 0, 0, 0, &src_dropped, nullptr); + + // F. All subresources barrier to PIXEL_SHADER_RESOURCE + D3D12_RESOURCE_BARRIER ball{}; + ball.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + ball.Transition.pResource = tex2d.p; + ball.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + ball.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + ball.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + list->ResourceBarrier(1, &ball); + + EXPECT(SUCCEEDED(list->Close())); + + // 5. ExecuteCommandLists - verify commands after dropped-mip barrier b0 execute cleanly + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + + Ref fence; + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 1))); + + // 6. Descriptor Heap and SRVs (verifying first_mip & mip_count clamping, and ResourceMinLODClamp rebasing) + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{}; + heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + heap_desc.NumDescriptors = 4; + Ref srv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&srv_heap.p)))); + const UINT stride = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + D3D12_CPU_DESCRIPTOR_HANDLE handle = srv_heap->GetCPUDescriptorHandleForHeapStart(); + + // SRV 0: requests original MostDetailedMip = 0, MipLevels = 2 + // With drop 1, mip 0 dropped, so view should start at physical 0 with mip_count = 1 (no bleed into physical 1!) + D3D12_SHADER_RESOURCE_VIEW_DESC srv0{}; + srv0.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv0.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv0.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv0.Texture2D.MostDetailedMip = 0; + srv0.Texture2D.MipLevels = 2; + device->CreateShaderResourceView(tex2d.p, &srv0, handle); + + // SRV 1: requests original MostDetailedMip = 1, MipLevels = 2 + // With drop 1, maps to physical MostDetailedMip = 0, MipLevels = 2. + handle.ptr += stride; + D3D12_SHADER_RESOURCE_VIEW_DESC srv1 = srv0; + srv1.Texture2D.MostDetailedMip = 1; + srv1.Texture2D.MipLevels = 2; + device->CreateShaderResourceView(tex2d.p, &srv1, handle); + + // SRV 2: ResourceMinLODClamp = 2.0f (rebased into physical coordinates without empty-view zero swizzle) + handle.ptr += stride; + D3D12_SHADER_RESOURCE_VIEW_DESC srv2 = srv0; + srv2.Texture2D.MostDetailedMip = 0; + srv2.Texture2D.MipLevels = 3; + srv2.Texture2D.ResourceMinLODClamp = 2.0f; + device->CreateShaderResourceView(tex2d.p, &srv2, handle); + + // Wait for fence + if (fence->GetCompletedValue() < 1) { + HANDLE event = CreateEventA(nullptr, FALSE, FALSE, nullptr); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, event))); + WaitForSingleObject(event, 5000); + CloseHandle(event); + } + EXPECT(fence->GetCompletedValue() >= 1); + + // 7. Verify readback data copied after dropped-mip barrier b0 (proves b0 didn't terminate prepare()) + void* readback_map = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &readback_map))); + EXPECT(readback_map != nullptr); + const auto* rb_bytes = static_cast(readback_map); + EXPECT(rb_bytes[0] == 0xAB); + readback->Unmap(0, nullptr); + + // 7b. Verify that dropped-mip copy to readback_dropped was skipped (sentinel 0xCD untouched) + void* r0_read = nullptr; + EXPECT(SUCCEEDED(readback_dropped->Map(0, nullptr, &r0_read))); + EXPECT(r0_read != nullptr); + const auto* r0_bytes = static_cast(r0_read); + EXPECT(r0_bytes[0] == 0xCD); + readback_dropped->Unmap(0, nullptr); + + // 8. CPU-visible custom heap texture (8x8, 2 mips): + // Under drop 1, mip 0 is dropped and physical image is 4x4, 1 mip. + D3D12_HEAP_PROPERTIES custom_heap{}; + custom_heap.Type = D3D12_HEAP_TYPE_CUSTOM; + custom_heap.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; + custom_heap.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; + + Ref tex_cpu; + const auto desc_cpu = tex2d_desc(8, 8, 2, DXGI_FORMAT_R8G8B8A8_UNORM); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&custom_heap, D3D12_HEAP_FLAG_NONE, &desc_cpu, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&tex_cpu.p)))); + + // ReadFromSubresource on dropped mip 0: must pitch-aware zero-fill without touching trailing padding + unsigned char dest[256]; + std::memset(dest, 0xEE, sizeof(dest)); + EXPECT(SUCCEEDED(tex_cpu->ReadFromSubresource(dest, 32, 256, 0, nullptr))); + EXPECT(dest[0] == 0); + EXPECT(dest[31] == 0); + EXPECT(dest[32] == 0); + EXPECT(dest[255] == 0xEE); + + // WriteToSubresource on dropped mip 0: graceful no-op + unsigned char src_data[256]; + std::memset(src_data, 0x42, sizeof(src_data)); + EXPECT(SUCCEEDED(tex_cpu->WriteToSubresource(0, nullptr, src_data, 32, 256))); + + // Retained mip 1 write & readback: + std::memset(dest, 0, sizeof(dest)); + EXPECT(SUCCEEDED(tex_cpu->WriteToSubresource(1, nullptr, src_data, 16, 256))); + EXPECT(SUCCEEDED(tex_cpu->ReadFromSubresource(dest, 16, 256, 1, nullptr))); + EXPECT(dest[0] == 0x42); + EXPECT(dest[15] == 0x42); + + // Map probe on dropped mip 0 vs pointer rejection + void* map_ptr = nullptr; + EXPECT(FAILED(tex_cpu->Map(0, nullptr, &map_ptr))); + EXPECT(SUCCEEDED(tex_cpu->Map(0, nullptr, nullptr))); + + std::printf("d3d12_texture_mip_drop_test: PASS\n"); + return 0; +} diff --git a/tests/test_command_list_mip_skip.py b/tests/test_command_list_mip_skip.py new file mode 100644 index 0000000000..a9a55ccfbe --- /dev/null +++ b/tests/test_command_list_mip_skip.py @@ -0,0 +1,71 @@ +"""Unit tests for command-list copy skipping and subresource remapping under LEONIDA_TEXTURE_MIP_DROP. + +Verifies that: +1. CopyTextureRegion targeting dropped mips marks p.skip = true. +2. CopyTextureRegion targeting retained mips remaps to physical subresources. +3. Out-of-bounds subresources and sentinels are rejected upfront. +4. CopyResource between differently dropped textures skips without aborting the list. +""" +import unittest + + +class CommandListMipSkipTest(unittest.TestCase): + + def test_buffer_to_image_upload_skip(self): + # 3 mips (0: 8x8, 1: 4x4, 2: 2x2), 1 array layer, drop=1 + orig_mips = 3 + array_layers = 1 + mips_dropped = 1 + physical_mips = orig_mips - mips_dropped # 2 + + all_subresources = 0xFFFFFFFF + total = orig_mips * array_layers + + def prepare_copy(subres): + if subres == all_subresources or subres >= total: + return "invalid_subresource", None + mip = subres % orig_mips + slice_idx = subres // orig_mips + if mip < mips_dropped: + return "skip", None + phys_sub = slice_idx * physical_mips + (mip - mips_dropped) + return "success", phys_sub + + # Mip 0 upload (dropped) -> skip + status0, phys0 = prepare_copy(0) + self.assertEqual(status0, "skip") + self.assertIsNone(phys0) + + # Mip 1 upload (retained) -> physical mip 0 + status1, phys1 = prepare_copy(1) + self.assertEqual(status1, "success") + self.assertEqual(phys1, 0) + + # Mip 2 upload (retained) -> physical mip 1 + status2, phys2 = prepare_copy(2) + self.assertEqual(status2, "success") + self.assertEqual(phys2, 1) + + # Mip 3 (out of bounds) -> invalid_subresource + status3, phys3 = prepare_copy(3) + self.assertEqual(status3, "invalid_subresource") + + # Sentinel 0xFFFFFFFF -> invalid_subresource + status_sentinel, _ = prepare_copy(all_subresources) + self.assertEqual(status_sentinel, "invalid_subresource") + + def test_texture_to_texture_copy_skip(self): + # If either src or dst targets a dropped mip, skip + def check_t2t(dst_mip, src_mip, drop): + if dst_mip < drop or src_mip < drop: + return "skip" + return "success" + + self.assertEqual(check_t2t(0, 0, drop=1), "skip") + self.assertEqual(check_t2t(0, 1, drop=1), "skip") + self.assertEqual(check_t2t(1, 0, drop=1), "skip") + self.assertEqual(check_t2t(1, 1, drop=1), "success") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_texture_mip_drop.py b/tests/test_texture_mip_drop.py new file mode 100644 index 0000000000..38a0acc6da --- /dev/null +++ b/tests/test_texture_mip_drop.py @@ -0,0 +1,529 @@ +"""Unit tests verifying the low-VRAM texture mip-drop logic (LEONIDA_TEXTURE_MIP_DROP). + +Addresses Issue #6043: +Leaves the top N (0..3) mips of sampled textures out of VRAM, halving dimensions per drop and +cutting texture VRAM footprint by ~70-75% for 6 GB and 4 GB GPUs, while strictly preserving +RenderTargets, DepthStencils, UAVs, and single-mip textures at full native resolution. +""" +import os +import unittest + + +class D3D12ResourceFlags: + NONE = 0 + ALLOW_RENDER_TARGET = 1 + ALLOW_DEPTH_STENCIL = 2 + ALLOW_UNORDERED_ACCESS = 4 + DENY_SHADER_RESOURCE = 8 + + +class TextureCreateInfoModel: + """Python reference model of TextureCreateInfo in runtime/shims/d3d12_vulkan_device.cpp.""" + + def __init__(self, width: int, height: int, depth_or_array: int, mip_levels: int, + flags: int = D3D12ResourceFlags.NONE, mip_drop_env: int = 0, is_volume: bool = False): + self.original_width = width + self.original_height = height + self.original_depth_or_array = depth_or_array + self.original_mips = mip_levels + self.flags = flags + self.is_volume = is_volume + + # Guards: Only pure sampled textures can drop mips + is_render_target = bool(flags & D3D12ResourceFlags.ALLOW_RENDER_TARGET) + is_depth_stencil = bool(flags & D3D12ResourceFlags.ALLOW_DEPTH_STENCIL) + is_uav = bool(flags & D3D12ResourceFlags.ALLOW_UNORDERED_ACCESS) + can_drop = not (is_render_target or is_depth_stencil or is_uav) + + # Clamped drop count + configured_drop = max(0, min(3, mip_drop_env)) + if can_drop and mip_levels > 1: + self.mips_dropped = min(configured_drop, mip_levels - 1) + else: + self.mips_dropped = 0 + + # Output extent and mip levels + self.width = max(1, width >> self.mips_dropped) + self.height = max(1, height >> self.mips_dropped) + self.depth = max(1, depth_or_array >> self.mips_dropped) if is_volume else 1 + self.mip_levels = mip_levels - self.mips_dropped + self.array_layers = 1 if is_volume else depth_or_array + + def map_subresource(self, subresource_index: int) -> int | None: + """Maps an incoming D3D12 subresource index to the shrunken Vulkan image subresource. + + Returns None if the subresource was dropped (upload discarded). + Raises ValueError if subresource_index is out of range or all_subresources. + """ + all_subresources = 0xFFFFFFFF + total_subresources = self.original_mips * self.array_layers + if subresource_index == all_subresources or subresource_index >= total_subresources: + raise ValueError("Invalid subresource index") + + orig_mips = self.original_mips + mip = subresource_index % orig_mips + slice_idx = subresource_index // orig_mips + + if mip < self.mips_dropped: + return None # Discarded upload + + mapped_mip = mip - self.mips_dropped + new_mips = self.mip_levels + return slice_idx * new_mips + mapped_mip + + def map_srv_view(self, most_detailed_mip: int, mip_count: int) -> tuple[int, int]: + """Maps an incoming SRV view to the shrunken Vulkan image.""" + if self.mips_dropped == 0: + avail = max(1, self.mip_levels - most_detailed_mip) if self.mip_levels > most_detailed_mip else 1 + count = min(mip_count, avail) if mip_count != 0xFFFFFFFF else self.mip_levels + return most_detailed_mip, count + + drop = self.mips_dropped + if most_detailed_mip >= drop: + first_mip = most_detailed_mip - drop + clamped_count = mip_count + else: + dropped_from_view = drop - most_detailed_mip + first_mip = 0 + if mip_count != 0xFFFFFFFF: + clamped_count = (mip_count - dropped_from_view) if mip_count > dropped_from_view else 1 + else: + clamped_count = 0xFFFFFFFF + + avail = (self.mip_levels - first_mip) if self.mip_levels > first_mip else 1 + if clamped_count != 0xFFFFFFFF and clamped_count > 0: + clamped_count = min(clamped_count, avail) + elif clamped_count == 0xFFFFFFFF: + clamped_count = avail + return first_mip, clamped_count + + if most_detailed_mip < self.mips_dropped: + first_mip = 0 + else: + first_mip = most_detailed_mip - self.mips_dropped + + avail_mips = max(1, self.mip_levels - first_mip) + resolved_count = avail_mips if mip_count in (-1, 0, 0xFFFFFFFF) else min(mip_count, avail_mips) + return first_mip, resolved_count + + +def calculate_texture_bytes_bc7(width: int, height: int, mips: int) -> int: + """Calculates total bytes for a BC7 (16 bytes per 4x4 block) texture chain.""" + total = 0 + w, h = width, height + for _ in range(mips): + bw = max(1, (w + 3) // 4) + bh = max(1, (h + 3) // 4) + total += bw * bh * 16 + w = max(1, w >> 1) + h = max(1, h >> 1) + return total + + +class TestTextureMipDrop(unittest.TestCase): + + def test_default_env_zero_preserves_dimensions(self): + """When LEONIDA_TEXTURE_MIP_DROP is 0 or unset, textures are 100% untouched.""" + t = TextureCreateInfoModel(4096, 2048, 1, 12, flags=D3D12ResourceFlags.NONE, mip_drop_env=0) + self.assertEqual(t.mips_dropped, 0) + self.assertEqual(t.width, 4096) + self.assertEqual(t.height, 2048) + self.assertEqual(t.mip_levels, 12) + + def test_drop_one_halves_resolution_and_drops_one_mip(self): + """Drop 1 cuts 4096x2048 to 2048x1024 and reduces mip count by 1.""" + t = TextureCreateInfoModel(4096, 2048, 1, 12, flags=D3D12ResourceFlags.NONE, mip_drop_env=1) + self.assertEqual(t.mips_dropped, 1) + self.assertEqual(t.width, 2048) + self.assertEqual(t.height, 1024) + self.assertEqual(t.mip_levels, 11) + + def test_vram_savings_match_measured_issue_targets(self): + """Drop 1 saves ~75% VRAM on 2D mip chains, matching Issue #6043 measurements.""" + base_bytes = calculate_texture_bytes_bc7(4096, 4096, 13) + drop1_bytes = calculate_texture_bytes_bc7(2048, 2048, 12) + drop2_bytes = calculate_texture_bytes_bc7(1024, 1024, 11) + + # Baseline: 4096 mip0 = 16 MB. Full chain ~ 21.33 MB. + # Drop 1: 2048 mip0 = 4 MB. Chain ~ 5.33 MB (25% of full, i.e. 75% savings). + ratio_drop1 = drop1_bytes / base_bytes + ratio_drop2 = drop2_bytes / base_bytes + + self.assertAlmostEqual(ratio_drop1, 0.25, delta=0.01) + self.assertAlmostEqual(ratio_drop2, 0.0625, delta=0.01) + + def test_render_targets_are_never_dropped(self): + """RenderTargets must stay at full resolution to prevent viewport/scissor misalignment.""" + t = TextureCreateInfoModel(1920, 1080, 1, 1, flags=D3D12ResourceFlags.ALLOW_RENDER_TARGET, mip_drop_env=2) + self.assertEqual(t.mips_dropped, 0) + self.assertEqual(t.width, 1920) + self.assertEqual(t.height, 1080) + + def test_depth_stencils_are_never_dropped(self): + """Depth/Stencil buffers must remain at exact native viewport resolution.""" + t = TextureCreateInfoModel(1920, 1080, 1, 1, flags=D3D12ResourceFlags.ALLOW_DEPTH_STENCIL, mip_drop_env=2) + self.assertEqual(t.mips_dropped, 0) + self.assertEqual(t.width, 1920) + self.assertEqual(t.height, 1080) + + def test_uav_storage_textures_are_never_dropped(self): + """UAV storage textures used in compute shaders must preserve exact dispatch dimensions.""" + t = TextureCreateInfoModel(512, 512, 1, 1, flags=D3D12ResourceFlags.ALLOW_UNORDERED_ACCESS, mip_drop_env=3) + self.assertEqual(t.mips_dropped, 0) + self.assertEqual(t.width, 512) + self.assertEqual(t.height, 512) + + def test_single_mip_textures_are_never_dropped(self): + """1-mip textures (UI icons, lookup tables) cannot drop mips.""" + t = TextureCreateInfoModel(256, 256, 1, 1, flags=D3D12ResourceFlags.NONE, mip_drop_env=2) + self.assertEqual(t.mips_dropped, 0) + self.assertEqual(t.width, 256) + self.assertEqual(t.height, 256) + self.assertEqual(t.mip_levels, 1) + + def test_subresource_upload_discard_and_remapping(self): + """Subresource uploads targeting dropped mips return None (discarded), rest map correctly.""" + t = TextureCreateInfoModel(2048, 2048, 2, 4, flags=D3D12ResourceFlags.NONE, mip_drop_env=1) + # Original: 4 mips per slice. Slice 0 has subresources 0, 1, 2, 3. + # With drop 1: Mip 0 is dropped. New image has 3 mips per slice (0, 1, 2). + + # Slice 0, Mip 0 -> Discarded + self.assertIsNone(t.map_subresource(0)) + # Slice 0, Mip 1 -> Mapped to Slice 0, Mip 0 + self.assertEqual(t.map_subresource(1), 0) + # Slice 0, Mip 2 -> Mapped to Slice 0, Mip 1 + self.assertEqual(t.map_subresource(2), 1) + + # Slice 1, Mip 0 (Subresource 4) -> Discarded + self.assertIsNone(t.map_subresource(4)) + # Slice 1, Mip 1 (Subresource 5) -> Mapped to Slice 1, Mip 0 (Index 3) + self.assertEqual(t.map_subresource(5), 3) + + def test_srv_view_clamping_and_offset(self): + """SRVs requesting top mip get mapped to mip 0 of the new image.""" + t = TextureCreateInfoModel(4096, 4096, 1, 6, flags=D3D12ResourceFlags.NONE, mip_drop_env=1) + + # View requesting full chain starting at mip 0 + first_mip, mip_count = t.map_srv_view(0, 6) + self.assertEqual(first_mip, 0) + self.assertEqual(mip_count, 5) + + # View requesting mip 2 (which is now mip 1) + first_mip, mip_count = t.map_srv_view(2, 4) + self.assertEqual(first_mip, 1) + self.assertEqual(mip_count, 4) + + def test_retained_mip_whole_copy_extent_derives_from_reduced_binding(self): + """Whole-mip copy (box=None) on retained mip must derive extent from reduced image (P1 fix).""" + # 8x8 texture, 3 mips, drop 1 -> physical image & binding is 4x4, 2 mips. + t = TextureCreateInfoModel(8, 8, 1, 3, flags=D3D12ResourceFlags.NONE, mip_drop_env=1) + self.assertEqual(t.width, 4) + self.assertEqual(t.height, 4) + self.assertEqual(t.mip_levels, 2) + + # Original subresource 1 (orig mip 1) maps to physical subresource 0 (phys mip 0). + phys_subres = t.map_subresource(1) + self.assertEqual(phys_subres, 0) + + # Whole-mip extent for physical mip 0: + phys_mip = phys_subres % t.mip_levels + phys_w = max(1, t.width >> phys_mip) + phys_h = max(1, t.height >> phys_mip) + self.assertEqual((phys_w, phys_h), (4, 4)) + # Total bytes for RGBA8 (4 bytes per texel): 4 * 4 * 4 = 64 bytes (NOT 8 * 8 * 4 = 256) + self.assertEqual(phys_w * phys_h * 4, 64) + + def test_dropped_mip_read_zeros_requested_box_with_pitches(self): + """Reading a dropped mip must zero all rows/slices across supplied pitches (P2 fix).""" + # Simulate reading dropped mip 0 of 8x8 RGBA8 (row_pitch 32, depth_pitch 256) into a 512-byte buffer. + buffer = bytearray([0xCD] * 512) + row_pitch = 32 + depth_pitch = 256 + width, height, depth = 8, 8, 1 + b_left, b_top, b_front = 0, 0, 0 + b_right, b_bottom, b_back = width, height, depth + bpp = 4 + + rows = b_bottom - b_top + row_bytes = (b_right - b_left) * bpp + slices = b_back - b_front + + for z in range(slices): + for y in range(rows): + offset = z * depth_pitch + y * row_pitch + buffer[offset:offset + row_bytes] = b"\x00" * row_bytes + + # First 256 bytes must be zeroed (8 rows * 32 bytes) + self.assertEqual(buffer[:256], b"\x00" * 256) + # Tail bytes (256..512) must remain untouched at 0xCD + self.assertEqual(buffer[256:], b"\xCD" * 256) + + def test_map_and_copy_reject_out_of_range_and_sentinel(self): + """Map and copy queries for subresources beyond total layers/mips or UINT_MAX return E_INVALIDARG.""" + # 1-layer, 3-mip texture: valid subresources are 0, 1, 2. + t = TextureCreateInfoModel(8, 8, 1, 3, flags=D3D12ResourceFlags.NONE, mip_drop_env=1) + # Subresource 0 is dropped (returns None) + self.assertIsNone(t.map_subresource(0)) + # Subresource 1 maps to physical mip 0 + self.assertEqual(t.map_subresource(1), 0) + # Subresource 2 maps to physical mip 1 + self.assertEqual(t.map_subresource(2), 1) + + # Subresource 3 is out of range (only 3 subresources exist: 0, 1, 2) + with self.assertRaises(ValueError): + t.map_subresource(3) + + # Subresource UINT_MAX (all_subresources) is invalid + with self.assertRaises(ValueError): + t.map_subresource(0xFFFFFFFF) + + def test_command_list_copy_texture_region_skips_dropped_mips(self): + """Command-list CopyTextureRegion must mark dropped mips as skip=True and remap retained mips.""" + # 8x8 texture, 3 mips (0, 1, 2), drop=1 -> physical 4x4, 2 mips (0, 1). + t = TextureCreateInfoModel(8, 8, 1, 3, flags=D3D12ResourceFlags.NONE, mip_drop_env=1) + + def prepare_copy(subres: int) -> tuple[str, int | None]: + all_subresources = 0xFFFFFFFF + total = t.original_mips * t.array_layers + if subres == all_subresources or subres >= total: + return "error", None + mip = subres % t.original_mips + slice_idx = subres // t.original_mips + if mip < t.mips_dropped: + return "skip", None + phys_sub = slice_idx * t.mip_levels + (mip - t.mips_dropped) + return "remap", phys_sub + + # Full-chain upload in a single command list: mips 0, 1, 2 + act0, sub0 = prepare_copy(0) + self.assertEqual(act0, "skip") + self.assertIsNone(sub0) + + act1, sub1 = prepare_copy(1) + self.assertEqual(act1, "remap") + self.assertEqual(sub1, 0) # physical mip 0 (4x4) + + act2, sub2 = prepare_copy(2) + self.assertEqual(act2, "remap") + self.assertEqual(sub2, 1) # physical mip 1 (2x2) + + # Out-of-range subresource + act3, sub3 = prepare_copy(3) + self.assertEqual(act3, "error") + + def test_command_list_copy_resource_skip_on_mip_mismatch(self): + """CopyResource between differently dropped textures skips without failing the list.""" + t_dropped = TextureCreateInfoModel(8, 8, 1, 3, flags=D3D12ResourceFlags.NONE, mip_drop_env=1) + t_native = TextureCreateInfoModel(8, 8, 1, 3, flags=D3D12ResourceFlags.NONE, mip_drop_env=0) + self.assertEqual(t_dropped.mip_levels, 2) + self.assertEqual(t_native.mip_levels, 3) + + mismatch_due_to_drop = (t_dropped.mips_dropped > 0 or t_native.mips_dropped > 0) and ( + t_dropped.mip_levels != t_native.mip_levels + ) + self.assertTrue(mismatch_due_to_drop) + + def test_3d_volume_texture_depth_shifted_by_mips_dropped(self): + """3D volume textures must right-shift extent depth by mips_dropped (#6043).""" + # 8x8x4 volume with 3 mips, drop 1 -> physical 4x4x2, 2 mips + vol = TextureCreateInfoModel(8, 8, 4, 3, flags=D3D12ResourceFlags.NONE, mip_drop_env=1, is_volume=True) + self.assertEqual(vol.width, 4) + self.assertEqual(vol.height, 4) + self.assertEqual(vol.depth, 2) + self.assertEqual(vol.mip_levels, 2) + self.assertEqual(vol.array_layers, 1) + + def test_srv_view_first_mip_less_than_drop_no_bleed(self): + """SRV with first_mip < drop must reduce mip_count by (drop - first_mip) to prevent bleeding into lower mips.""" + # 6 mips (0, 1, 2, 3, 4, 5), drop 2 -> physical 4 mips (0, 1, 2, 3 corresponding to original 2, 3, 4, 5) + t = TextureCreateInfoModel(64, 64, 1, 6, flags=D3D12ResourceFlags.NONE, mip_drop_env=2) + self.assertEqual(t.mip_levels, 4) + self.assertEqual(t.mips_dropped, 2) + + # SRV requested original MostDetailedMip=0, MipLevels=3 (original mips 0, 1, 2) + # Original 0 and 1 were dropped; original 2 exists as physical mip 0. + # Exactly 1 requested mip was retained, so mip_count must clamp to 1 (not 3!). + first_mip, count = t.map_srv_view(most_detailed_mip=0, mip_count=3) + self.assertEqual(first_mip, 0) + self.assertEqual(count, 1) + + # SRV requested original MostDetailedMip=1, MipLevels=4 (original mips 1, 2, 3, 4) + # Original 1 was dropped; original 2, 3, 4 exist as physical mips 0, 1, 2. + # Exactly 3 requested mips were retained, so count must clamp to 3. + first_mip, count = t.map_srv_view(most_detailed_mip=1, mip_count=4) + self.assertEqual(first_mip, 0) + self.assertEqual(count, 3) + + # SRV requested full mip chain (MipLevels=UINT_MAX) + first_mip, count = t.map_srv_view(most_detailed_mip=0, mip_count=0xFFFFFFFF) + self.assertEqual(first_mip, 0) + self.assertEqual(count, 4) + + def test_resource_barrier_transition_subresource_remapping_and_skip(self): + """ResourceBarrier transitions must skip dropped mips and remap retained mips.""" + # 8x8 texture, 3 mips (0, 1, 2), drop=1 -> physical 4x4, 2 mips (0, 1) + t = TextureCreateInfoModel(8, 8, 1, 3, flags=D3D12ResourceFlags.NONE, mip_drop_env=1) + + def prepare_transition(subres: int) -> tuple[str, int | None]: + all_subresources = 0xFFFFFFFF + if subres == all_subresources: + return "all", None + total = t.original_mips * t.array_layers + if subres >= total: + return "error", None + mip = subres % t.original_mips + slice_idx = subres // t.original_mips + if mip < t.mips_dropped: + return "skip", None + phys_sub = slice_idx * t.mip_levels + (mip - t.mips_dropped) + return "remap", phys_sub + + # Subresource 0 (mip 0, dropped) -> skipped gracefully + act0, sub0 = prepare_transition(0) + self.assertEqual(act0, "skip") + self.assertIsNone(sub0) + + # Subresource 1 (mip 1, retained) -> remapped to physical 0 + act1, sub1 = prepare_transition(1) + self.assertEqual(act1, "remap") + self.assertEqual(sub1, 0) + + # Subresource 2 (mip 2, retained) -> remapped to physical 1 + act2, sub2 = prepare_transition(2) + self.assertEqual(act2, "remap") + self.assertEqual(sub2, 1) + + # Subresource 3 (out of bounds) -> error + act3, sub3 = prepare_transition(3) + self.assertEqual(act3, "error") + + # Subresource ALL_SUBRESOURCES -> handled as whole-image transition + act_all, sub_all = prepare_transition(0xFFFFFFFF) + self.assertEqual(act_all, "all") + + def test_srv_resource_min_lod_clamp_rebased(self): + """SRV ResourceMinLODClamp must be rebased by mips_dropped (#6043 / #6365 review by jeremygold02).""" + # 4x4 texture, 3 mips (0, 1, 2), drop 1 -> physical 2x2, 2 mips (0, 1) + t = TextureCreateInfoModel(4, 4, 1, 3, flags=D3D12ResourceFlags.NONE, mip_drop_env=1) + self.assertEqual(t.mips_dropped, 1) + self.assertEqual(t.mip_levels, 2) + + def rebase_min_lod(orig_min_lod: float, drop: int) -> float: + if orig_min_lod > 0.0: + return max(0.0, orig_min_lod - float(drop)) + return 0.0 + + # Case 1: clamp 0.0 -> remains 0.0 (all retained mips accessible) + self.assertEqual(rebase_min_lod(0.0, t.mips_dropped), 0.0) + + # Case 2: clamp 2.0 (original mip 2) -> rebased to 1.0 (physical mip 1) + # Original mip 2 is now physical mip 1; clamp 1.0 ensures mip 1 is accessible without swizzling to zero. + self.assertEqual(rebase_min_lod(2.0, t.mips_dropped), 1.0) + + # Case 3: clamp 3.0 (beyond original mips) -> rebased to 2.0 (beyond physical mips, empty view as expected) + self.assertEqual(rebase_min_lod(3.0, t.mips_dropped), 2.0) + + def test_texture_barrier_range_dropped_and_remapped(self): + """Ranged TextureBarrier (mip_count > 0) must skip or remap first_mip and mip_count.""" + # 64x64 texture, 5 mips (0, 1, 2, 3, 4), drop 2 -> physical 16x16, 3 mips (0, 1, 2) + t = TextureCreateInfoModel(64, 64, 1, 5, flags=D3D12ResourceFlags.NONE, mip_drop_env=2) + self.assertEqual(t.mips_dropped, 2) + self.assertEqual(t.mip_levels, 3) + + def prepare_ranged_barrier(first_mip: int, count: int) -> tuple[str, int | None, int | None]: + orig_mips = t.original_mips + if first_mip >= orig_mips or count > orig_mips - first_mip: + return "error", None, None + if first_mip + count <= t.mips_dropped: + return "skip", None, None + if first_mip < t.mips_dropped: + dropped_from_range = t.mips_dropped - first_mip + new_first = 0 + new_count = count - dropped_from_range if count > dropped_from_range else 1 + else: + new_first = first_mip - t.mips_dropped + new_count = count + new_count = min(new_count, t.mip_levels - new_first) + return "remap", new_first, new_count + + # Entirely dropped: original mips 0..1 (first_mip=0, count=2) + act0, f0, c0 = prepare_ranged_barrier(0, 2) + self.assertEqual(act0, "skip") + self.assertIsNone(f0) + + # Spanning dropped and retained: original mips 0..4 (first_mip=0, count=5) + # Mips 0, 1 dropped; retained 2, 3, 4 become physical 0, 1, 2 (count 3) + act1, f1, c1 = prepare_ranged_barrier(0, 5) + self.assertEqual(act1, "remap") + self.assertEqual(f1, 0) + self.assertEqual(c1, 3) + + # Entirely retained: original mips 3..4 (first_mip=3, count=2) + # Becomes physical mips 1..2 (first_mip=1, count=2) + act2, f2, c2 = prepare_ranged_barrier(3, 2) + self.assertEqual(act2, "remap") + self.assertEqual(f2, 1) + self.assertEqual(c2, 2) + + # Out-of-bounds: first_mip=5 + act3, f3, c3 = prepare_ranged_barrier(5, 1) + self.assertEqual(act3, "error") + + def test_barrier_skip_loop_continues_subsequent_commands(self): + """A skipped barrier in prepare() must continue processing subsequent commands (auswhalen999-debug catch).""" + # Emulate the prepare() loop over a command list with: + # [0] dropped-mip barrier + # [1] retained-mip barrier + # [2] retained-mip copy + commands = [ + {"type": "barrier", "mip": 0}, # dropped + {"type": "barrier", "mip": 1}, # retained + {"type": "copy", "mip": 1}, # retained + ] + mips_dropped = 1 + prepared = [] + for cmd in commands: + if cmd["type"] == "barrier" and cmd["mip"] < mips_dropped: + prepared.append({"type": cmd["type"], "skip": True}) + continue # MUST continue, not return! + prepared.append({"type": cmd["type"], "skip": False, "physical_mip": cmd["mip"] - mips_dropped}) + + self.assertEqual(len(prepared), 3) + self.assertTrue(prepared[0]["skip"]) + self.assertFalse(prepared[1]["skip"]) + self.assertEqual(prepared[1]["physical_mip"], 0) + self.assertFalse(prepared[2]["skip"]) + self.assertEqual(prepared[2]["physical_mip"], 0) + + def test_droppable_allocation_strictly_smaller_than_single_mip_texture(self): + """Under drop 1, an 8-mip droppable texture allocates less memory than a 1-mip texture (BatSmacker84 catch).""" + # Baseline without drop: 256x256 8-mip >= 256x256 1-mip (349 KB vs 256 KB) + t_multi_nodrop = TextureCreateInfoModel(256, 256, 1, 8, flags=D3D12ResourceFlags.NONE, mip_drop_env=0) + t_single_nodrop = TextureCreateInfoModel(256, 256, 1, 1, flags=D3D12ResourceFlags.NONE, mip_drop_env=0) + bytes_multi_nodrop = calculate_texture_bytes_bc7(t_multi_nodrop.width, t_multi_nodrop.height, t_multi_nodrop.mip_levels) + bytes_single_nodrop = calculate_texture_bytes_bc7(t_single_nodrop.width, t_single_nodrop.height, t_single_nodrop.mip_levels) + self.assertGreaterEqual(bytes_multi_nodrop, bytes_single_nodrop) + + # Under drop 1: multi-mip shrinks to 128x128 (7 mips), while single-mip stays 256x256 (1 mip) + t_multi_drop = TextureCreateInfoModel(256, 256, 1, 8, flags=D3D12ResourceFlags.NONE, mip_drop_env=1) + t_single_drop = TextureCreateInfoModel(256, 256, 1, 1, flags=D3D12ResourceFlags.NONE, mip_drop_env=1) + self.assertEqual(t_multi_drop.width, 128) + self.assertEqual(t_single_drop.width, 256) + bytes_multi_drop = calculate_texture_bytes_bc7(t_multi_drop.width, t_multi_drop.height, t_multi_drop.mip_levels) + bytes_single_drop = calculate_texture_bytes_bc7(t_single_drop.width, t_single_drop.height, t_single_drop.mip_levels) + self.assertLess(bytes_multi_drop, bytes_single_drop) + + def test_command_list_copy_dropped_mip_readback_skipped(self): + """Command-list CopyTextureRegion from a dropped mip into readback must be skipped.""" + t = TextureCreateInfoModel(16, 16, 1, 4, flags=D3D12ResourceFlags.NONE, mip_drop_env=1) + # Attempting readback from dropped mip 0 + subres = 0 + mip = subres % t.original_mips + is_dropped = mip < t.mips_dropped + self.assertTrue(is_dropped) + skip = is_dropped + self.assertTrue(skip) + + +if __name__ == "__main__": + unittest.main()