From 54567b51d6f11ad13cfc37d81188e6cecb75152b Mon Sep 17 00:00:00 2001 From: Chad Hyatt Date: Thu, 26 Nov 2026 16:40:28 -0600 Subject: [PATCH] shader: lower startup 2D-array image LOD queries Use spatial-only DXIL LOD queries while consuming the guest array address. Preserve derivative and static-sampler validation and extend the source-built raw array mip-view fixture. AI-assisted backport patch from x2w-microlift. --- CMakeLists.txt | 2 +- docs/experiments.md | 9 ++ tests/offscreen_check.cpp | 5 +- tests/startup_gfx2hlsl_image_get_lod_check.py | 106 +++++++++++++----- tests/startup_image_3d.cpp | 16 ++- tests/startup_image_get_lod_view_check.py | 70 ++++++++++-- tools/startup/gfx2hlsl.py | 15 +-- 7 files changed, 175 insertions(+), 48 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8d9886fdfc..d71f4780f3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3729,7 +3729,7 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: a plain image_sample past a uniform join keeps its implicit LOD (Sample, not level 0). add_test(NAME startup_image_sample_implicit_lod_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_implicit_lod_check.py") - # Startup shader translator: image_get_lod on a 2D texture (CalculateLevelOfDetail / Unclamped). + # Startup shader translator: image_get_lod on 2D and 2D-array textures. add_test(NAME startup_gfx2hlsl_image_get_lod_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_image_get_lod_check.py") foreach(adapter IN ITEMS warp hardware) diff --git a/docs/experiments.md b/docs/experiments.md index e0f565a2e9..eda8673718 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15090,6 +15090,15 @@ The two adapters and WARP [measured on the desktop](https://github.com/R0Y00/Xbo differed at exact half-mip boundaries with point mip filtering. The regression uses linear filtering for the fractional lower clamp. Native console readback remains open. +The same startup lowering admits 2D arrays with three guest address registers. +DXIL `CalculateLOD` takes just the two spatial coordinates for a `Texture2DArray`; +the slice is not part of the level calculation. The portable controls verified +both dimensions, including a non-sequential address with a different slice register, +and retained the existing derivative, sampler and mask refusals. +The array-view fixture compares raw translated and direct HLSL readbacks for +two encoded slice values and two gradients against the independent LOD reference. +The array GPU lane was not run on Apple Silicon. + ```powershell ctest --preset dev --no-tests=error -R '^startup_image_get_lod_view_' -V ``` diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index ac4e1b348b..c5e9848c02 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1366,12 +1366,14 @@ OperationResult run_startup_image_3d(const OperationContext& ctx) // --startup-image-2d-view [0|1] prints one RGBA32F pixel. // The optional selector is forwarded as the existing second root constant. +// --startup-image-2d-array-view takes the identical args; argv[2] selects the two-slice 2D-array renderer. OperationResult run_startup_image_2d_view(const OperationContext& ctx) { const std::string_view window = ctx.argv[6]; if (window.size() != 3 || window[1] != '/' || window[0] < '0' || window[0] > '2' || window[2] < '1' || window[2] > '3') return {OutcomeKind::fail, "expected a first/count mip window on a three-mip texture"}; + const bool array = std::strcmp(ctx.argv[2], "--startup-image-2d-array-view") == 0; float selector = 0.0f; if (ctx.argc == 8) { if (std::strcmp(ctx.argv[7], "1") == 0) @@ -1380,7 +1382,7 @@ OperationResult run_startup_image_2d_view(const OperationContext& ctx) return {OutcomeKind::fail, "view selector must be 0 or 1"}; } float color[4]{}; - check_startup_image_3d(ctx.device, ctx.argv[3], ctx.argv[4], selector, color, ctx.argv[5], false, 3, false, true, + check_startup_image_3d(ctx.device, ctx.argv[3], ctx.argv[4], selector, color, ctx.argv[5], array, 3, false, !array, UINT(window[0] - '0'), UINT(window[2] - '0')); std::uint32_t bits[4]; std::memcpy(bits, color, sizeof(bits)); @@ -1726,6 +1728,7 @@ const OperationSpec kOperations[] = { {"--startup-image-1d-mips", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-2d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-2d-view", 7, 8, nullptr, kNoGate, run_startup_image_2d_view}, + {"--startup-image-2d-array-view", 7, 8, nullptr, kNoGate, run_startup_image_2d_view}, {"--startup-image-3d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-store", 7, 7, nullptr, kNoGate, run_startup_image_store}, {"--startup-image-2d-array", 7, 8, nullptr, kNoGate, run_startup_image_3d}, diff --git a/tests/startup_gfx2hlsl_image_get_lod_check.py b/tests/startup_gfx2hlsl_image_get_lod_check.py index f0508e5ad1..c6a13633dc 100644 --- a/tests/startup_gfx2hlsl_image_get_lod_check.py +++ b/tests/startup_gfx2hlsl_image_get_lod_check.py @@ -1,4 +1,4 @@ -"""image_get_lod on a 2D texture in tools/startup/gfx2hlsl.py (M200-01 L). +"""image_get_lod on a 2D texture and a 2D array in tools/startup/gfx2hlsl.py (M200-01 L). image_get_lod returns [0] the LOD a sample would use, clamped, and [1] the computed LOD before the clamp (Mesa nir_texop_lod, emitted by ACO as image_get_lod; GLSL textureQueryLod x/y). It is lowered to HLSL @@ -8,14 +8,23 @@ the read does. The clamped value depends on the sampler's LOD limits and bias, so the sampler must be a constant descriptor under the validation of image_sample_b. +The 2D-array form (dim:SQ_RSRC_IMG_2D_ARRAY) takes a third address dword, the slice, which the decoder reads +back. DXIL CalculateLOD uses two active coordinates (c0, c1) for Texture2DArray -- the slice is not part of the +LOD -- and HLSL's Texture2DArray CalculateLevelOfDetail takes float2, so the slice register is consumed but +dropped from the call: Texture2DArray r0 queried at float2(u, v), exactly the two-component coordinate of +glslang's hlsl.calculatelod.dx10.frag ("LOD queries do not pass array level in coordinate"). + Fixture (synthetic): the recorded c_lz stage of startup_image_sample_c_check with the MIMG opcode set to 0x60 -(image_get_lod; the decoder reads it back with a 2-register address), sampler word 2 loaded from a literal (mip -filter point), and for the second form dmask 0x3. -Checks: dmask 0x1, 0x2 and 0x3 lower to the two calls on the sampler, which carries its LOD limits. A uniform join -before the read is accepted. Controls (refused): dmask 0x4, a 2D array, s_cbranch_vccz/execz before -the read, a sampler LOD bias, a sampler with mipmapping disabled, and the stage without op_image_get_lod -(negative control: refused as on main). - draw [fxc]: also compile the dmask 0x3 stage with dxc ps_6_0 (and fxc ps_5_1). +(image_get_lod; the decoder reads it back with a 2-register, or 3-register for the array, address), sampler +word 2 loaded from a literal (mip filter point), and for the second form dmask 0x3. The array fixture keeps the +original v2 = 1.0 as its slice dword; a variant swaps the slice register pair so the consumed dword is proven +to come from the address position, not the register number. +Checks: dmask 0x1, 0x2 and 0x3 lower to the two calls on the sampler, which carries its LOD limits, on a 2D +texture and a 2D array (Texture2DArray r0, srv tex2da, slice dropped). A uniform join before the read is +accepted on both. Controls (refused): dmask 0x4, a 3D image, s_cbranch_vccz/execz before the read (2D and +array), a sampler LOD bias, a sampler with mipmapping disabled, an array decoded with two address registers, +and the stage without op_image_get_lod (negative control: refused as on main). + draw [fxc]: also compile the dmask 0x3 2D and 2D-array stages with dxc ps_6_0 (and fxc ps_5_1). """ import struct import subprocess @@ -41,15 +50,20 @@ def sopp(op, simm): return struct.pack(' right after the read, back to it (a divergent back edge spanning the read) code = code[:AT + 8] + sopp(back_op, -3) + code[AT + 8:] @@ -97,7 +111,43 @@ def controls(): _, text = ps(stage(join=True)) assert call in text and 'v4 = U(t.x);' in text, text refused(stage(dmask=4), 'image_get_lod form') - refused(stage(dim=5), 'image_get_lod form') # SQ_RSRC_IMG_2D_ARRAY + refused(stage(dim=2), 'image_get_lod form') # SQ_RSRC_IMG_3D + # The 2D-array form: Texture2DArray, the slice consumed and dropped from the float2 coordinate. + array_call = ('t = float4(r0.CalculateLevelOfDetail(q0, float2(F(v0), F(v1))), ' + 'r0.CalculateLevelOfDetailUnclamped(q0, float2(F(v0), F(v1))), 0.0, 0.0);') + listing = [a for _, _, _, a in G.decode(stage(dim=5))] + assert 'image_get_lod v4, v[0:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY' in listing, listing + array_pipe, text = ps(stage(dim=5)) + assert array_call in text and 'v4 = U(t.x);' in text, text + assert 'Texture2DArray r0 : register(t0);' in text and 'Texture2D<' not in text, text + assert 'srv 0 tex2da table 0 0' in array_pipe.manifest(), array_pipe.manifest() + assert 'smpl 0 0x8001012 0x0 0x4000000 0x0' in array_pipe.manifest(), array_pipe.manifest() + _, text = ps(stage(dmask=3, dim=5)) + assert array_call in text and 'v4 = U(t.x);' in text and 'v5 = U(t.y);' in text, text + _, text = ps(stage(dmask=2, dim=5)) + assert array_call in text and 'v4 = U(t.y);' in text and 'U(t.x)' not in text, text + code = stage(dmask=3, dim=5, nsa=[1, 3, 0, 0]) + listing = [a for _, _, _, a in G.decode(code)] + assert 'image_get_lod v[4:5], [v0, v1, v3], s[16:23], s[24:27] dmask:0x3 dim:SQ_RSRC_IMG_2D_ARRAY' in listing, listing + _, text = ps(code) + assert array_call in text and 'F(v2)' not in text and 'F(v3)' not in text, text + _, text = ps(stage(branch=True, dim=5)) + assert array_call in text and 'v4 = U(t.x);' in text, text + _, text = ps(stage(join=True, dim=5)) + assert array_call in text and 'v4 = U(t.x);' in text, text + for op in (7, 9): # vccnz, execnz back edge after the array read + refused(stage(dim=5, back_op=op), 'image_get_lod needs implicit derivatives') + for op in (6, 7, 8, 9): # vccz, vccnz, execz, execnz + refused(stage(dim=5, cf_op=op), 'image_get_lod needs implicit derivatives') + refused(stage(dim=5, word2=MIP_POINT | 1), 'image_get_lod with a sampler LOD bias') + refused(stage(dim=5, word2=0), 'image_get_lod with mipmapping disabled') + # An array decoded with two address registers is refused (the slice dword would be unread). + original = G.D.MIMG_DIMS[5] + G.D.MIMG_DIMS[5] = (original[0], 2, original[2]) + try: + refused(stage(dim=5), 'image_get_lod form') + finally: + G.D.MIMG_DIMS[5] = original _, text = ps(stage(divergent=True)) # a cleared EXEC is an exact per-lane write: the quad program keeps the proof assert call in text, text for op in (7, 9): # vccnz, execnz back edge after the read @@ -112,26 +162,30 @@ def controls(): refused(stage(), 'image_get_lod') finally: G.Stage.op_image_get_lod = saved - print('image_get_lod: CalculateLevelOfDetail / Unclamped for dmask 0x1, 0x2 and 0x3; uniform join/branch before ' - 'the read accepted, also after a cleared EXEC; dmask 0x4, a 2D array, vcc/exec branches, a sampler bias and a ' - 'sampler without mipmapping refused; refused without the handler') + print('image_get_lod: CalculateLevelOfDetail / Unclamped for dmask 0x1, 0x2 and 0x3 on a 2D texture and a 2D ' + 'array (Texture2DArray, slice consumed and dropped from the float2 coordinate, manifest srv tex2da, NSA ' + 'address); uniform join/branch before the read accepted on both, also after a cleared EXEC; dmask 0x4, a ' + '3D image, vcc/exec branches, a sampler bias and a sampler without mipmapping refused on both, an array ' + 'with two address registers refused; refused without the handler') return pipe def compile_check(dxc, fxc=None): - _, text = ps(stage(dmask=3)) with tempfile.TemporaryDirectory() as tmp: - path = Path(tmp) / 'ps.hlsl' - path.write_text(text) - runs = [('dxc', [dxc, '-T', 'ps_6_0', '-E', 'main', '-Fo', str(Path(tmp) / 'a.cso'), str(path)])] - if fxc: - runs.append(('fxc', [fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', str(Path(tmp) / 'b.cso'), - str(path)])) - for kind, args in runs: - r = subprocess.run(args, capture_output=True, text=True, timeout=60) - if r.returncode: - raise AssertionError('%s: %s' % (kind, r.stderr[-1500:])) - print('%s compiles the dmask 0x3 stage' % kind) + for name, text in (('2D', ps(stage(dmask=3))[1]), ('2D array', ps(stage(dmask=3, dim=5))[1])): + slug = name.replace(' ', '_') + path = Path(tmp) / ('ps_%s.hlsl' % slug) + path.write_text(text) + runs = [('dxc', [dxc, '-T', 'ps_6_0', '-E', 'main', '-Fo', str(Path(tmp) / ('%s.cso' % slug)), + str(path)])] + if fxc: + runs.append(('fxc', [fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', + str(Path(tmp) / ('%s_fxc.cso' % slug)), str(path)])) + for kind, args in runs: + r = subprocess.run(args, capture_output=True, text=True, timeout=60) + if r.returncode: + raise AssertionError('%s (%s): %s' % (kind, name, r.stderr[-1500:])) + print('%s compiles the dmask 0x3 %s stage' % (kind, name)) def main(): diff --git a/tests/startup_image_3d.cpp b/tests/startup_image_3d.cpp index ca700aa53c..60dede5d87 100644 --- a/tests/startup_image_3d.cpp +++ b/tests/startup_image_3d.cpp @@ -64,7 +64,7 @@ ComPtr create_root(ID3D12Device* device, const x2w_startup: // array: the same eight texels as two slices of a 2D array (dim:SQ_RSRC_IMG_2D_ARRAY); the default // view of a two-slice texture is a Texture2DArray over both. Multi-mip fixtures use a 4x4 base. -// A nonzero view_levels selects an explicit 2D SRV starting at first_mip. When sampler_line is a +// A nonzero view_levels selects an explicit 2D or 2D-array SRV starting at first_mip. When sampler_line is a // comparison sampler (smpc), the texture uses DXGI_FORMAT_R32_FLOAT holding the red channel as depth. void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const char* pixel_path, float z, float color[4], const char* sampler_line, bool array, UINT levels, bool one_dimensional, @@ -72,7 +72,7 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const { if (levels < 1 || levels > max_levels || (levels > 1 && !array && !two_dimensional && !one_dimensional)) throw std::runtime_error("Unsupported image mip level count"); - if (view_levels && (!two_dimensional || first_mip >= levels || view_levels > levels - first_mip)) + if (view_levels && ((!two_dimensional && !array) || first_mip >= levels || view_levels > levels - first_mip)) throw std::runtime_error("2D mip window exceeds the resource"); const UINT base = levels > 1 ? mip_base : side; const auto vs = read_blob(vertex_path); @@ -177,10 +177,16 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const D3D12_SHADER_RESOURCE_VIEW_DESC view{}; if (view_levels) { view.Format = td.Format; - view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + view.ViewDimension = array ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY : D3D12_SRV_DIMENSION_TEXTURE2D; view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - view.Texture2D.MostDetailedMip = first_mip; - view.Texture2D.MipLevels = view_levels; + if (array) { + view.Texture2DArray.MostDetailedMip = first_mip; + view.Texture2DArray.MipLevels = view_levels; + view.Texture2DArray.ArraySize = td.DepthOrArraySize; + } else { + view.Texture2D.MostDetailedMip = first_mip; + view.Texture2D.MipLevels = view_levels; + } } device->CreateShaderResourceView(texture.Get(), view_levels ? &view : nullptr, views->GetCPUDescriptorHandleForHeapStart()); hd = {D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; diff --git a/tests/startup_image_get_lod_view_check.py b/tests/startup_image_get_lod_view_check.py index e3b6018eeb..133ea3a516 100644 --- a/tests/startup_image_get_lod_view_check.py +++ b/tests/startup_image_get_lod_view_check.py @@ -1,4 +1,4 @@ -"""Draw gfx1013 image_get_lod through the translated static sampler and four views of a 4x4 texture.""" +"""Draw gfx1013 image_get_lod through translated static samplers and 2D/array mip views.""" import re import struct import subprocess @@ -28,6 +28,31 @@ return float4(clamped, raw, clamped, raw); } """ +SLICE_LIT = bytes.fromhex('ff02047e') # v_mov_b32 v2, (VOP1 literal): the slice dword of the array address +DIRECT_ARRAY_PS = DIRECT_PS.replace('Texture2D<', 'Texture2DArray<', 1) + + +def patch_sampler(code, low, high): + # s_mov_b32 s25, literal: sampler word 1 carries the two unsigned 4.8 LOD limits. + at = fixture.W2_AT - 4 + assert code[at:at + 4] == bytes.fromhex('800399be') + limits = int(low * 256) | (int(high * 256) << 12) + return code[:at] + struct.pack('