diff --git a/README.md b/README.md index 0860ff63f3..8a2c0fe363 100644 --- a/README.md +++ b/README.md @@ -202,10 +202,13 @@ Use `--wave64-emulate on` to force emulation or `--wave64-emulate off` to force Four fallback flags are forwarded to the translator the same way, saved next to the translated shaders, and changing them translates them again: `--no-float-controls` (drop `SignedZeroInfNanPreserve`, for devices whose pipeline check skips a shader without `shaderSignedZeroInfNanPreserveFloat32`; needs PR #664's translator flag), `--bary-fallback` -(read raw barycentrics from an interpolated input, for devices without `VK_KHR_fragment_shader_barycentric`), +(read raw barycentrics from an interpolated input; on by itself when the runtime's GPU lacks +`VK_KHR_fragment_shader_barycentric` with `geometryShader` or has a known `BaryCoordKHR` driver bug, unless +`LEONIDA_BARY_FALLBACK=0`), `--texel-offset-fallback` (fold `image_sample*_o` offsets into the coordinate, for devices without -`VK_KHR_maintenance8`) and `--mesh-compute` (mesh shaders as compute, for devices without `VK_EXT_mesh_shader`; -on by itself on Intel's Windows Vulkan driver, whose native mesh draws crash, BUILD-2202, unless `--native-mesh`). +`VK_KHR_maintenance8`) and `--mesh-compute` (mesh shaders as compute; on by itself when the runtime's GPU has no +`VK_EXT_mesh_shader` / `meshShader` or uses Intel's Windows Vulkan driver, whose native mesh draws crash, BUILD-2202, +unless `--native-mesh`). Each is documented in [docs/design.md](docs/design.md). The build records which llvm-mc command and version produced the disassembly. Changing either, or reusing a work diff --git a/docs/design.md b/docs/design.md index cc0126679b..27074381e3 100644 --- a/docs/design.md +++ b/docs/design.md @@ -366,7 +366,7 @@ How the generated SPIR-V expects the runtime to work: | Optional device features | Shaders may need `fragmentShaderBarycentric`, `fragmentShaderPixelInterlock` and `maintenance8`. All three are present on an RTX 4060 Ti (and an RTX 2060 SUPER), and `runtime/test/vk_harness.cpp` enables them when available, as does the runtime's `create_vulkan_device_standalone`, each with its extension (`VulkanDeviceInfo::fragment_shader_barycentric`, `fragment_shader_interlock`, `maintenance8`; checked by `d3d12_vulkan_device_test`). All three are present on an RTX 4060 Ti, and `runtime/test/vk_harness.cpp` enables them when available. (It is guarded by the header macro `VK_KHR_MAINTENANCE_8_EXTENSION_NAME`, so older Vulkan headers build without it. `vk_texture_test` enables it too, and `shaderImageGatherExtended`.) A device without `fragmentShaderBarycentric` (NVIDIA Pascal) runs the raw-barycentric PS with `--bary-fallback` (below). Shaders translated with `--fma khr` need `VK_KHR_shader_fma` and its `shaderFmaFloat32` feature (`VkPhysicalDeviceShaderFmaFeaturesKHR`): `create_vulkan_device_standalone`, `runtime/test/vk_test_device.h` and the `vk_*` test programs enable it when the device offers it (`VulkanDeviceInfo::shader_fma`), and a test program refuses (exit 77) a module with `OpCapability FMAKHR` on a device without it. | | Wave size | **Most of the game's shaders are wave64: 23,841 of 26,503** (`fssm_header.wave_size()`: FSSM header flags word `u32[0xD4]` bit 5, `0x20` = wave32, `0` = wave64; 0 contradictions against GFX10 code-proven wave32/wave64 instructions across all 26,503 blobs): 10,974 of 12,101 PS, 9,282 of 9,282 mesh shaders, 2,236 of 2,236 VS, 1,154 of 2,689 CS and 195 of 195 GS, against 2,662 wave32 (1,535 CS and 1,127 PS). A full-corpus translation at `ec8ec4c9` marks exactly these 23,841 `wave64` (`subgroup_size` 64) in the index. Before the FSSM flag (#1900) the wave size came from code markers (64-bit EXEC/mask writes, `exec_hi`, `*_saveexec_b64`): at `6a6704df` they made 21,538 of the 26,487 shaders translated then wave64 (the figure quoted here was 21,545). 10,031 PS, 9,282 mesh shaders, 1,179 VS, 851 CS and 195 GS (the 16 shaders refused then are all wave64 CS by the flag; the figure quoted here was 21,545). Against the flag they call 2,287 wave64 shaders wave32 (943 PS, 1,057 VS, 287 CS), whose code has no 64-bit EXEC/mask marker, and none the other way. An older marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS, but it left out the 769 listings whose names start with `.` (616 of them mesh shaders; Python's `glob` skips such names). Over all 26,503, the translator's own marker test (`WAVE64_RE`, or a 64-bit op on EXEC/VCC) on the code `translate()` keeps finds 21,554 wave64: 10,031 PS, 9,282 mesh shaders, 1,179 VS, 867 CS and 195 GS. With the 2,287 above that is exactly the flag's 23,841, and none contradicts it; read raw, 104 more wave32 listings (80 CS, 24 PS) seem to carry a marker, all from embedded data words decoded as instructions. The first marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks, written into this row at `0082ad53`) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS: 20,634 without the GS, so not the 21,545 total either. The translator maps a wave to a subgroup, and NVIDIA subgroups are 32 wide. What that means: (1) lane-independent code, which is most pixel-shader math, is exact; (2) wave-wide branch decisions and reductions are made per 32-lane half, which is exact unless scalar state computed for one half is later consumed by the other; (3) lane indices from `v_mbcnt_lo/hi` and wave IDs from the merged-wave SGPR must be 64-lane values. Mesh and compute shaders build thread IDs as wave_id·64 + mbcnt, so those need a mapping from `LocalInvocationIndex` (lane = index & 63, wave = index >> 6). Full fidelity needs either 64-wide subgroups (AMD GPUs, via `VK_EXT_subgroup_size_control` requiredSubgroupSize = 64) or emulating cross-half ops (ballot, readlane, shuffles across halves) through workgroup memory. | | Mesh shaders | NGG wave64 programs → `VK_EXT_mesh_shader` (`MeshEXT`). **PSV0** (DXBC) gives NumThreads (128×1×1 in the corpus), MaxOutputVertices/Primitives (128/128) and the topology (triangles). System inputs, from Mesa's RADV setup for mesh as NGG on GFX10.3: v5 = first launch vertex ID of the lane (the "vertex_id" slot), `linearGroupIndex * NumThreads + LocalInvocationIndex` with the linear index from WorkgroupId/NumWorkgroups; all 9,282/9,282 corpus mesh shaders read `v5` once with `v_readfirstlane_b32 sX, v5` and use `sX` only via `s_lshr_b32 D, sX, 7` to recover the group index (NumThreads is 128 in the corpus), matching TomBox's mesh ABI (`gid.x * numThreads + gi`) on 1D launches. GPU-checked with `runtime/test/shaders/ms_v5_workgroup.asm` (24/24 groups exact on RTX 4060 Ti and RTX 3080, and on an RTX 4050 Laptop and an AMD Radeon 740M (RADV)); still unverified on Xbox hardware: the low 7 bits of `v5` on lanes 1..127 and whether 3D `DispatchMesh` flattens XYZ or uses X only. The merged-wave-info SGPR (s3 in this ABI) = wave ID << 24, from LocalInvocationIndex >> 6; `v_mbcnt` lanes = LocalInvocationIndex & 63; user data in s16.. as usual. All 9,282 mesh-shader listings of 1.0.2.1 (names starting with `.` included) read exactly v5 before writing anything (`rdna2spirv.read_before_write_vgprs` over the code `translate()` keeps). An earlier sample of 1,500 put 27 aside as adding loop-carried registers; over the corpus no extra read is loop-carried. Read raw, 266 of the 309 listings with embedded data words seem to read more VGPRs, each after a branch (in 101 the register is written after the read); they come from data words decoded as instructions and are gone once the listing is re-anchored to the FSSM code and cut to reachable code, as `translate()` does. 1,473 of 1,500 sampled mesh shaders read exactly v5, and the rest only add loop-carried registers. Exports: on NGG, thread t exports vertex t (`pos0`, `paramN`) and primitive t (`prim`). They're staged per invocation; an all-`off` export is the dummy a wave with no vertices must issue, and writes nothing. `s_sendmsg GS_ALLOC_REQ` (m0 = prims << 12 \| verts, sent by thread 0) stores the counts in a workgroup variable. At shader end, in uniform control flow: workgroup barrier, `OpSetMeshOutputsEXT(min(verts, max), min(prims, max))`, then each thread writes its staged vertex (Position + Location N) and primitive (`PrimitiveTriangleIndicesEXT` = bits [8:0], [18:10], [28:20]; `CullPrimitiveEXT` = bit 31). `pos1..pos3` clip/cull distances are staged per invocation and emitted in a per-vertex `Block` output struct (`Position` + `ClipDistance`/`CullDistance` arrays, `VK_EXT_mesh_shader`) when used, keeping the standalone `%ms_out_pos` layout unchanged for shaders without `pos1+`. The distances are copied to that struct one float at a time, not as a whole array: SPIRV-Cross 1.4.363.0 turns a whole-array store into a mesh output into a C array assignment that Metal rejects (SHADER-155; `ms_clip` then compiles and draws its 2048/4096 pixels in a native Metal mesh draw on an Apple A18 Pro). `%ms_cull` (the `PerPrimitiveEXT` `CullPrimitiveEXT` `Block`) is listed before `%ms_out_vtx` in `OpEntryPoint MeshEXT`'s interface list: AMD's proprietary Windows Vulkan driver `24.10.24` (LLPC) was reported, on one Ryzen 5 7600 iGPU, to segfault (`0xC0000005`) during `vkCreateGraphicsPipelines` when the per-vertex clip/cull `Block` precedes the per-primitive `Block` (even on `glslangValidator` output), while driver `32.0.32029.2010` on an RX 9070 XT and an RX 7900 XT accepts either order; the order has no meaning in SPIR-V, so this one costs nothing on other drivers; reordering the interface list fixes `ms_clip` on AMD Ryzen 5 7600 RDNA2 iGPU (`2048/2048` clipped, `2048/2048` drawn, `4096/4096` culled when `CullPrimitiveEXT = true`, 0 validation errors) while keeping `CullPrimitiveEXT` in its `Block+bool` form for SPIRV-Tools ≤2025.1 (`SHADER-MS-CLIP-IFACE`). GPU-checked with `runtime/test/shaders/ms_tri.asm` (`VKH_MESH=1 vk_harness`), built from the game's own idioms (thread ID from s3 and mbcnt across two waves, thread-0 ALLOC_REQ, per-thread exports): 0 error on every pixel. `Layer` and `ViewportIndex` from the `pos1` misc vector (`z[10:0]`, `z[19:16]`) are per-primitive members of `%ms_cull` (`Gen.export_misc_pos1`): each lane stages the value it exports and writes it to the primitive with its own index. That is exact when the value is the same for all vertices of a primitive; whether the hardware takes it from the primitive's provoking vertex instead is not measured. Confirmed by the translator tests (`tests/test_translate.py`); none of the 1,906 mesh shaders of the corpus that export `pos1` writes either, so the game's mesh shaders only gain unused declarations. Compressed exports (`exp pos1` / `exp param` with `compr`) unpack their two f16 pairs the way the pixel-shader compressed export does (`Gen.export_comps`): LLVM lists each register twice (`v4, v4, v5, v5`), so the pair is operands 1 and 3, each unpacked with `UnpackHalf2x16` into (x, y) and (z, w), and an `off` register leaves its two components unwritten. Before, such an export was refused. Confirmed by the translator tests (`tests/test_translate.py`); none of the 9,282 mesh shaders of the corpus uses one, so the game's translation does not change. | -| Mesh shaders as compute (`--mesh-compute`) | For devices without `VK_EXT_mesh_shader` (NVIDIA Pascal, for one), and on by itself in `make_game.py` on Intel's Windows Vulkan driver (`VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS` with mesh shaders, `runtime_gpu_mesh_draws_crash`): there `vkCmdDrawMeshTasksEXT` crashes (0xC0000409 in `igvk64.dll`) for a mesh shader with a live push-constant load at byte 32 or later, which every corpus mesh shader has, while `--mesh-compute` is exact (BUILD-2202, Arc A770, driver 32.0.101.9175; no fixed version known; `--native-mesh` keeps native mesh shaders). Each mesh shader becomes a `GLCompute` module with the same workgroup size and code; only the epilogue changes. Instead of `OpSetMeshOutputsEXT` and the mesh outputs, after the same barrier lane 0 writes the vertex and primitive counts, lane i < vertex count writes its vertex and lane i < primitive count its primitive into this workgroup's **slot** of an output buffer: slot = linear workgroup index (x + y·nx + z·nx·ny) × `slot_bytes`, computed in 64 bits. The buffer's device address is in push-constant dwords 36–37, so these modules declare 152 bytes. Slot layout (`rdna2spirv.mesh_compute_layout`, recorded per shader as `mesh_compute` in the index), all 16-byte aligned: a header (vertex count, primitive count), then `max_vertices` vertices, each holding the position, the clip and then cull distances padded to whole vec4s, and one vec4 per param location; then `max_primitives` primitives of three vertex indices plus 1 if culled. The modules need no mesh capability, extension or `shaderClipDistance`. `tools/mesh_compute_vs.py` writes the vertex shader that draws the slots with a non-indexed `vkCmdDraw(groups × max_primitives × 3)`: vertex v is workgroup v / (3·max_primitives), primitive (v / 3) mod max_primitives, corner v mod 3. A primitive past the count, or one culled, gets one position outside the clip volume at all three corners and is clipped. Otherwise the corner's index, clamped to `max_vertices` − 1, selects the vertex, and its position, distances and params go out at the mesh shader's locations, so the pixel shader is unchanged. One draw rasterizes in vertex order, which is workgroup then primitive order, as with mesh workgroups. Corpus: all 9,282 mesh shaders are 128×1×1 with 128/128 outputs, wave64, 0–18 params, clip distances in 1,906, cull distances and per-primitive attributes in none, no task shaders. On a 32-wide device combine it with `--wave64-emulate`. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal: no mesh shaders; driver 560.94, Windows 10) with `LEONIDA_MESH_COMPUTE=1 LEONIDA_W64_EMULATE=1`: `ms_tri`, `ms_w64x_ballot` and `ms_wave_info_s3` 4096/4096 pixels exact, `ms_clip` 2048/4096 covered as expected, `ms_v5_workgroup` 24/24 workgroup coordinates, zero Khronos validation messages. Checked in `tests/test_mesh_compute.py`. The runtime side, turning a `DispatchMesh` into that dispatch, a barrier and the draw, is the follow-up (it needs the graphics pipelines of #291). Unused primitives still run the vertex shader; compaction with an indirect draw would avoid that. | +| Mesh shaders as compute (`--mesh-compute`) | On by itself in `make_game.py` for devices without `VK_EXT_mesh_shader` (`meshShader` in `tools/vk_subgroup_info.py`, `runtime_gpu_mesh_shader`; NVIDIA Pascal, AMD RDNA1/GCN, MoltenVK, ...) and on Intel's Windows Vulkan driver (`VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS` with mesh shaders, `runtime_gpu_mesh_draws_crash`): there `vkCmdDrawMeshTasksEXT` crashes (0xC0000409 in `igvk64.dll`) for a mesh shader with a live push-constant load at byte 32 or later, which every corpus mesh shader has, while `--mesh-compute` is exact (BUILD-2202, Arc A770, driver 32.0.101.9175; no fixed version known; `--native-mesh` keeps native mesh shaders). Each mesh shader becomes a `GLCompute` module with the same workgroup size and code; only the epilogue changes. Instead of `OpSetMeshOutputsEXT` and the mesh outputs, after the same barrier lane 0 writes the vertex and primitive counts, lane i < vertex count writes its vertex and lane i < primitive count its primitive into this workgroup's **slot** of an output buffer: slot = linear workgroup index (x + y·nx + z·nx·ny) × `slot_bytes`, computed in 64 bits. The buffer's device address is in push-constant dwords 36–37, so these modules declare 152 bytes. Slot layout (`rdna2spirv.mesh_compute_layout`, recorded per shader as `mesh_compute` in the index), all 16-byte aligned: a header (vertex count, primitive count), then `max_vertices` vertices, each holding the position, the clip and then cull distances padded to whole vec4s, and one vec4 per param location; then `max_primitives` primitives of three vertex indices plus 1 if culled. The modules need no mesh capability, extension or `shaderClipDistance`. `tools/mesh_compute_vs.py` writes the vertex shader that draws the slots with a non-indexed `vkCmdDraw(groups × max_primitives × 3)`: vertex v is workgroup v / (3·max_primitives), primitive (v / 3) mod max_primitives, corner v mod 3. A primitive past the count, or one culled, gets one position outside the clip volume at all three corners and is clipped. Otherwise the corner's index, clamped to `max_vertices` − 1, selects the vertex, and its position, distances and params go out at the mesh shader's locations, so the pixel shader is unchanged. One draw rasterizes in vertex order, which is workgroup then primitive order, as with mesh workgroups. Corpus: all 9,282 mesh shaders are 128×1×1 with 128/128 outputs, wave64, 0–18 params, clip distances in 1,906, cull distances and per-primitive attributes in none, no task shaders. On a 32-wide device combine it with `--wave64-emulate`. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal: no mesh shaders; driver 560.94, Windows 10) with `LEONIDA_MESH_COMPUTE=1 LEONIDA_W64_EMULATE=1`: `ms_tri`, `ms_w64x_ballot` and `ms_wave_info_s3` 4096/4096 pixels exact, `ms_clip` 2048/4096 covered as expected, `ms_v5_workgroup` 24/24 workgroup coordinates, zero Khronos validation messages. Checked in `tests/test_mesh_compute.py`. The runtime side, turning a `DispatchMesh` into that dispatch, a barrier and the draw, is the follow-up (it needs the graphics pipelines of #291). Unused primitives still run the vertex shader; compaction with an indirect draw would avoid that. | | Mesh primitive export and allocation (`exp prim`, `MSG_GS_ALLOC_REQ`) | The GFX10 NGG formats, from Mesa 22.3 `src/amd/llvm/ac_llvm_build.c`: `ac_build_sendmsg_gs_alloc_req` (lines 4475–4477) puts `prim_cnt << 12 \| vtx_cnt` in m0, and `ac_pack_prim_export` (lines 4518–4539) packs index 0, 1 and 2 in bits 0–8, 10–18 and 20–28, the edge flags in bits 9, 19 and 29 and "null primitive (skip)" in bit 31. Thread t exports vertex t and primitive t, only below the vertex and primitive counts (`src/amd/common/ac_nir_lower_ngg.c`, `emit_ms_finale`, lines 4056–4067). Translated: the counts from m0 (each clamped to PSV0's maximum) go to `OpSetMeshOutputsEXT` or the `--mesh-compute` header; `PrimitiveTriangleIndicesEXT` takes the three 9-bit fields without the edge flags, and `CullPrimitiveEXT` (or the slot's culled word) is bit 31; invocations at or past a count write nothing. **Indices stay below the vertex count**: every `exp prim` in the corpus comes from an epilogue that compares each 10-bit field with the vertex count and, when one is at or past it, sets bit 31 and keeps the fields (count over the 1.0.2.1 corpus: all 8,666 listings with `exp prim`), so a null primitive can carry indices up to 511. The hardware skips it, but `VK_EXT_mesh_shader` leaves an index at or past the vertex count undefined even on a culled primitive. The translator writes index k as `null ? 0 : umin(field_k, vertex count - 1)`, as Mesa's mesh lowering clamps them (`ac_nir_lower_ngg.c` line 4112), and a primitive count of 0 when the vertex count is 0 (so `vertex count - 1` never wraps); `CullPrimitiveEXT` is unchanged. Until 2026-11-26 the raw fields were written, a suspected cause of device losses in mesh draws on NVIDIA (not confirmed). Executed for both paths in `tests/semantic/test_ms_prim_export.py` (72 threads in two wave64 waves: odd threads set the edge flags, threads with t & 2 the null bit; and `fixtures/ms_prim_null_clamp.asm`, 128 threads at vertex counts 0, 10, 100 and 128, whose null primitives carry fields 300, 511, 0x3FF and the vertex count itself: its assertions fail on the old translator); `spirv-val` accepts both modules, plain and `--wave64-emulate`. **Not GPU-checked.** | | Geometry shaders | On output stream zero, `GS_OP_EMIT_CUT` emits the staged vertex and ends its strip under the same EXEC guard. The synthetic `gs_emit_cut.asm` checks that six vertices form two separate triangles. [RDNA 2 ISA, S_SENDMSG](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content). All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) programs on LDS rings, with no `exp`, written for wave64 (the FSSM header's wave-size flag says wave64 in 195 of 195, see *Wave size*, and the translator's index marks all 195 `wave64` with `subgroup_size` 64 at `f847748c`; the code agrees: the EXEC prologue that `gs_tri.asm` mirrors compares the thread count with 64 and writes a 64-bit EXEC, the count in #94 finds `v_mbcnt_hi_u32_b32` in all 195, and the translator marks all 195 `wave64`; an earlier version of this row said wave32, TEST-251). Inputs: vertex i sits at the dword offset in v0 lo / v0 hi / v1 lo; an LDS read at vertex base + 4·(4·reg + comp) is input-signature register reg, component comp (checked: SV_Position xyz in dwords 0–2 and TEXCOORD0.xy in 4–5, as ISG1 declares). Outputs: emitted vertex k is dwords [k·4·nreg, (k+1)·4·nreg) of the lane's GSVS area, dword = 4·reg + comp of the output signature (20 dwords = 5 OSG1 registers; every write matches a declared mask). Translation: synthetic offsets (vertex i at dword 64·i), LDS reads → `gl_in[i]` inputs, LDS writes → staged slots, `MSG_GS EMIT` → copy slot (emit count) to the outputs + `OpEmitVertex`, `CUT` → `OpEndPrimitive`, `GS_DONE` → nothing. The prologue's `s_bfm_b64`/`s_cselect` EXEC setup is fed s3 = 64 << 8. GPU-checked with `runtime/test/shaders/gs_tri.asm` (`VKH_GS=… vk_harness`): 0 error. Without a geometry stage (Apple GPUs: Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` guards its record/meta stores and `%gsc_n` increment on `n < OutputVertices` (dropping excess vertices rather than overflowing into the next primitive's slots, and updating `OpPhi` predecessors across split blocks, and rejecting (`Unsupported`) an `OpEmitVertex` in a loop header before its `OpLoopMerge`, which the split would move; SHADER-617, checked on the CPU by `tests/test_spirv_gs_to_compute_bounds.py`), and a meta buffer holds each primitive's vertex count (`<= OutputVertices`) and strip ends, for an ordinary draw afterwards (SHADER-159). Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` writes the outputs to a record buffer, and a meta buffer holds each primitive's vertex count and strip ends, for an ordinary draw afterwards (SHADER-159). `gs_tri` lowered this way, converted with SPIRV-Cross and run natively on an Apple A18 Pro: 195/195 records exact for 65 random triangles, and the captured fullscreen triangle drawn from the records matches all 4096 gradient pixels. Not done: wiring it into a draw path, and GS that use cross-lane operations or more than one invocation. | | Integer clamp | The VOP3 `clamp` bit on `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32` saturates the result to [0, 0xFFFFFFFF], and on `v_add_nc_i32`/`v_sub_nc_i32` to [0x80000000, 0x7FFFFFFF]; without it they wrap. GFX9+ semantics: LLVM selects `uaddsat`/`usubsat` and `saddsat`/`ssubsat` to exactly these ops with clamp set. **Until this change clamp was silently ignored on the unsigned ops** (and the signed ones were `Unsupported`). Checked on the CPU by `tests/semantic/test_alu_add_nc_clamp.py`. The carry-out unsigned ops (`v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with VOP3 `clamp` likewise saturate D to `0xFFFFFFFF` on add carry or `0` on sub borrow while still reporting the real carry/borrow bit in `sdst` (**until 2026-11-22 the translator ignored `clamp` on all six**); confirmed natively on RDNA2 (AMD Radeon 680M `gfx1035` wave32 & wave64 via `tools/hw_oracle`, and independently on `gfx1036` in #1746) and CPU-checked by `tests/semantic/test_alu_add_co_clamp.py`. The 16-bit unsigned add/sub (`v_add_nc_u16`, `v_sub_nc_u16`, and the `v_add_u16`/`v_sub_u16`/`v_subrev_u16` `_e64` names) saturate to [0, 0xFFFF] with `clamp` (llvm-mc 21 gfx1030 encodes the bit on them, and LLVM selects i16 `uaddsat`/`usubsat` to them); **until 2026-11-22 the translator wrapped instead**. `clamp` on any other 16-bit integer op raises `Unsupported`. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), **not GPU-verified**. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), and **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, Windows 11, driver `26.5.1`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all 32-bit and 16-bit `*_nc_*` `clamp` cases (including `op_sel` and kept destination half on u16) match hardware bit-for-bit. **Open divergence measured on the same hardware:** `v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` with `clamp` saturate D (`0xFFFFFFFF` / `0`) while still reporting the real carry/borrow in `sdst`, whereas the translator currently ignores `clamp` on these carry-out ops. | @@ -436,7 +436,7 @@ How the generated SPIR-V expects the runtime to work: | Wave64 leading-bit scans | With `--wave64-emulate`, `s_flbit_i32_b32` and `s_flbit_i32` of a lane mask use the same wave-wide exchange as `s_bcnt1` and `s_ff1`. These reads prevent lane-local EXEC-zero folding and require synchronized scheduling in wave-divergent blocks. Plain scalar inputs still allow the fold. Hand-written compute shaders in `tests/semantic/test_wave64_emulate_opt.py` check EXECZ at 64 and 128 threads and a branch on SCC taken by just one wave at 128 threads. The strict CPU workgroup interpreter observes the unsigned scan of VCC_LO = 8 returning 28 in the expected invocations. Both scan forms pass `spirv-val --target-env vulkan1.2`. | | Wave64 emulation: scalar exits from a folded EXECZ region | A folded lane-local `s_cbranch_execz`/`execnz` region may leave to its join from inside, for example `s_cmp` + `s_cbranch_scc0/scc1` straight to the label that restores EXEC. The ISA then skips the rest of the region for the whole wave. `find_local_exec_folds` in `tools/wave64_emulate_opt.py` builds the region's sub-CFG with an exit node for every edge to the join, so `cfg_structure.structure` puts each later block of the region behind a `%pc` guard; the exit node itself emits nothing. Before this the edge was dropped and the block after the branch ran whenever the lane was active. Confirmed on the CPU against the native wave64 translation and the ISA: `tests/semantic/test_wave64_emulate_opt.py` `test_folded_region_scalar_branch_to_join_skips_the_rest` (taken and not-taken `scc0`/`scc1`, 64 and 128 threads, the region still folded) fails before the change on the four taken cases. **Not GPU-verified.** | | Wave64 emulation: cross-lane reads of missing lanes | With `--wave64-emulate`, a read of another lane's exchange slot (`ds_swizzle_b32`, `ds_bpermute_b32`, `ds_permute_b32`'s targets and data, `v_readlane_b32`, `v_readfirstlane_b32`, DPP and the other reads behind `Gen.x_round`) gives 0 when the source lane doesn't exist in a partial last wave (`Gen.x_lane_word`: `x_wbase + lane < threads`, else 0), as a source lane that isn't running reads 0 on the hardware. The prologue still zeroes those slots, but a read must not depend on it: RADV (Mesa 26.3.1, gfx1036 iGPU and RX 7900 XTX) compiled the store, barrier and load of an exchange behind a branch into `masked_swizzle_amd` with `fetch_inactive` (`RADV_DEBUG=shaders`), so in a 40-thread group lanes 32-39 of `ds_swizzle_b32 offset:swizzle(SWAP,8)` read the missing lanes' registers, garbage that changed between runs. Workgroups whose size is a multiple of 64 emit the same module as before. Confirmed by `runtime/test/shaders/cs_w64x_partial_swizzle.asm` (40 threads: SWAP 8, BROADCAST 16,15 and `ds_bpermute_b32` from lanes 40-47; its 8 words measured natively on gfx1036 through `tools/hw_oracle`): emulated at subgroup 32 (RADV, Mesa 26.3.1), words 2 and 3 wrong before in 20 of 20 runs on the gfx1036 iGPU and 19 of 20 on the RX 7900 XTX, and all 8 words right in 20 of 20 runs on both after; native wave64 and emulated at subgroup 64 right both times. `scripts/run_gpu_tests.py` runs the partial-wave fixtures emulated at subgroup 32, as `check.py` does, since at RADV's default of 64 this fixture passed before the change too; by `crosslane_fuzz.py --wave 64 --ext --dpp --no-maskdata --programs 1000 --seed 48315`, emulated: on the gfx1036 iGPU 993 match and 7 hyp_only (all 40-thread groups, lanes 32-39 reading a swizzle source of 40-47) before, 1000/1000 after, and on the RX 7900 XTX 995 match and 5 hyp_only before, 1000/1000 after; and by `tests/semantic/test_w64x_partial_swizzle.py` (fixture `w64x_partial_swizzle.asm`, 40 and 104 threads, the prologue's zero stores replaced by a poison word in the workgroup interpreter; both cases fail before the change). | -| Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one), and for Mesa ANV's known BaryCoordKHR.i bug (SHADER-925). The raw pair a PS reads comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. `tools/bary_fallback_gs.py` writes a pass-through geometry shader that supplies (1,0,0), (0,1,0), (0,0,1) at the triangle vertices. GPU-checked on NVIDIA Pascal and Intel Arc B580/Mesa ANV: ANV native `ps_uniform_branch` and `ps_scc_mask32` fail with i=0.0, while the fallback passes and `ps_bary` passes natively. `make_game.py` and `scripts/run_gpu_tests.py` select the fallback automatically for Mesa ANV. `LEONIDA_BARY_FALLBACK=1` forces fallback and `LEONIDA_BARY_FALLBACK=0` forces native barycentrics consistently in both entry points; explicit `--bary-fallback` also forces the fallback in `make_game.py`. The standalone `build.py`/`check.py` path follows the same variable/probe rule. Checked in `tests/semantic/test_bary_fallback.py` and the builder/runner wiring tests. | +| Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one), and for Mesa ANV's known BaryCoordKHR.i bug (SHADER-925). The raw pair a PS reads comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. `tools/bary_fallback_gs.py` writes a pass-through geometry shader that supplies (1,0,0), (0,1,0), (0,0,1) at the triangle vertices. GPU-checked on NVIDIA Pascal and Intel Arc B580/Mesa ANV: ANV native `ps_uniform_branch` and `ps_scc_mask32` fail with i=0.0, while the fallback passes and `ps_bary` passes natively. `make_game.py` and `scripts/run_gpu_tests.py` select the fallback automatically when `tools/vk_subgroup_info.py` reports a device without `VK_KHR_fragment_shader_barycentric` (`fragmentShaderBarycentric`) that supports `geometryShader` (NVIDIA Pascal, Intel Gen9.5, ...; MoltenVK lacks `geometryShader` and stays off), as well as for Mesa ANV and AMD Windows on `gfx90c` (#5933). `LEONIDA_BARY_FALLBACK=1` forces fallback and `LEONIDA_BARY_FALLBACK=0` forces native barycentrics consistently in both entry points; explicit `--bary-fallback` also forces the fallback in `make_game.py`. The standalone `build.py`/`check.py` path follows the same variable/probe rule. Checked in `tests/semantic/test_bary_fallback.py` and the builder/runner wiring tests. | | Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64, which the translator emits as per-subgroup code with no cross-half exchange, and for compute/mesh translated with `--wave64-emulate`; the runtime does not use it: it reads `wave64`, `subgroup_size` and `wave64_exchange`), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), `pc_tail` (`--pc-tail-ubo`: the set, binding and size of the uniform block that holds the push-constant tail), and input/output locations. A shader translated with `--wave64-emulate` carries `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none. Otherwise `subgroup_size` (64 for wave64, 32) is what the PSO asks for through `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo` where the device lists the stage in `requiredSubgroupSizeStages` (docs/d3d12_vulkan.md section 3.2): that list is the driver's, not "compute/mesh only". The AMD Windows driver reports FRAGMENT, COMPUTE, TASK and MESH (measured on a Radeon 880M, driver 26.11.2, sizes 32..64), and current Mesa RADV on GFX10+ reports COMPUTE, FRAGMENT and task/mesh (`src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`, Mesa main at 152b9cde; older Mesa: compute only), so wave64 pixel shaders can run exact there. NVIDIA lists every stage but only size 32, so there a native wave64 shader cannot get 64 and wave64 PS/VS/GS stay 2x32. A runtime can create every pipeline at load time from it without parsing SPIR-V. | | Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | | `v_cndmask_b32` source modifiers | `v_cndmask_b32` only moves bits, so a VOP3 `abs` on `src0`/`src1` clears bit 31 and `neg` flips it (`abs` first) as plain bit moves (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`, `Gen.src_u_sign_mods`), never `FAbs`/`OpFNegate`: a signalling NaN stays signalling and a denormal isn't flushed. Until 2026-11-23 the sources went through `Gen.modify`, and the mini interpreter quieted them (`-v1` of `0x7F800001` gave `0xFFC00001`, not `0xFF800001`). **Not measured on hardware for this instruction**: the rule follows the same VOP3 input modifiers measured as sign-bit moves on `v_cmp_class_f32` (gfx1036, all four IEEE/denorm modes, row "Floating-point class compare" above), and LLVM's AMDGPU backend moves `fneg`/`fabs` through a select into `v_cndmask_b32_e64`'s source modifiers (`AMDGPUTargetLowering::foldFreeOpFromSelect`), which is only exact if they are sign-bit moves. Checked on the CPU and with `spirv-val` by `tests/semantic/test_cndmask_sign_mods.py` (15 words including signalling/quiet NaNs, denormals, zeros and infinities x `v`, `-v`, `\|v\|`, `-\|v\|` x both operands). | diff --git a/make_game.py b/make_game.py index f1af5a172d..8b55d5f436 100644 --- a/make_game.py +++ b/make_game.py @@ -2010,8 +2010,8 @@ def runtime_gpu_per_vertex(): def runtime_gpu_barycentric_fallback(): - """Whether the selected Vulkan GPU's driver has a known BaryCoordKHR bug (Mesa ANV, AMD Windows on gfx90c), or None - when it can't be told.""" + """Whether the selected Vulkan GPU needs --bary-fallback (no VK_KHR_fragment_shader_barycentric on a device with + geometryShader, or a known BaryCoordKHR bug on Mesa ANV / AMD Windows gfx90c), or None when it can't be told.""" try: v = runtime_gpu_info().get("barycentric_fallback") return v if isinstance(v, bool) else None @@ -2019,6 +2019,16 @@ def runtime_gpu_barycentric_fallback(): return None +def runtime_gpu_fragment_shader_barycentric(): + """Whether the selected Vulkan GPU exposes VK_KHR_fragment_shader_barycentric (fragmentShaderBarycentric), or None + when tools/vk_subgroup_info.py can't tell.""" + try: + v = runtime_gpu_info().get("fragment_shader_barycentric") + return v if isinstance(v, bool) else None + except (AttributeError, TypeError): + return None + + def barycentric_fallback_override(): """LEONIDA_BARY_FALLBACK=1/0 forces the same barycentric path as the GPU test runner; None leaves it automatic.""" v = (os.environ.get("LEONIDA_BARY_FALLBACK") or "").strip().lower() @@ -2033,6 +2043,16 @@ def barycentric_fallback_override(): VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS = 5 +def runtime_gpu_mesh_shader(): + """Whether the GPU the runtime would use exposes VK_EXT_mesh_shader with meshShader, or None when + tools/vk_subgroup_info.py can't tell.""" + try: + v = runtime_gpu_info().get("mesh_shader") + return v if isinstance(v, bool) else None + except (AttributeError, TypeError): + return None + + def runtime_gpu_mesh_draws_crash(): """True where the GPU the runtime would use is on Intel's Windows Vulkan driver with VK_EXT_mesh_shader: there vkCmdDrawMeshTasksEXT crashes (0xC0000409 in igvk64.dll) for a mesh shader with a live push-constant load at @@ -2042,8 +2062,8 @@ def runtime_gpu_mesh_draws_crash(): info = runtime_gpu_info() if not info or "driver_id" not in info: return None - return info.get("driver_id") == VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS and \ - info.get("mesh_in_supported_stages") is True + has_mesh = info.get("mesh_shader") if "mesh_shader" in info else info.get("mesh_in_supported_stages") + return info.get("driver_id") == VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS and has_mesh is True def runtime_gpu_max_push_constants(): @@ -3143,8 +3163,9 @@ def main() -> int: "shaderSignedZeroInfNanPreserveFloat32 or shaderDenormPreserveFloat16") ap.add_argument("--bary-fallback", action="store_true", help="translate raw barycentric reads from an interpolated vec3 input (with a pass-through " - "geometry shader the runtime draws), for devices without " - "VK_KHR_fragment_shader_barycentric") + "geometry shader the runtime draws); on by itself when the runtime's GPU lacks " + "VK_KHR_fragment_shader_barycentric (with geometryShader) or has a known BaryCoordKHR " + "driver bug (Mesa ANV, AMD Windows on gfx90c)") ap.add_argument("--texel-offset-fallback", action="store_true", help="fold the run-time texel offset of image_sample*_o into the coordinate, for devices " "without VK_KHR_maintenance8") @@ -3152,12 +3173,12 @@ def main() -> int: help="16-bit interpolation from decoded halves the vertex/mesh shader exports instead of " "PerVertexKHR inputs; on by itself when the runtime's GPU can't use them (MoltenVK)") ap.add_argument("--mesh-compute", action="store_true", - help="translate mesh shaders to compute shaders writing an output buffer, for devices " - "without VK_EXT_mesh_shader; on by itself on Intel's Windows Vulkan driver, whose mesh " - "draws crash on the corpus' mesh shaders (BUILD-2202)") + help="translate mesh shaders to compute shaders writing an output buffer; on by itself when " + "the runtime's GPU lacks VK_EXT_mesh_shader (meshShader) or uses Intel's Windows Vulkan " + "driver, whose mesh draws crash on the corpus' mesh shaders (BUILD-2202)") ap.add_argument("--native-mesh", action="store_true", - help="keep native mesh shaders on Intel's Windows Vulkan driver instead of turning on " - "--mesh-compute (for a driver that fixes BUILD-2202's crash)") + help="keep native mesh shaders instead of turning on --mesh-compute automatically (for example " + "to translate for another GPU, or for an Intel Windows driver that fixes BUILD-2202)") ap.add_argument("--pc-tail-ubo", action="store_true", help="keep s0..s31 in 128 push-constant bytes and move heap/code base to a set-1 uniform " "block; on by itself when the runtime's GPU reports maxPushConstantsSize below what " @@ -3229,12 +3250,17 @@ def main() -> int: log(f"{', '.join(WINDOWS_ONLY)}: left out, the cross-build needs {'; '.join(lacking)} " "(or pass --runtime-build)") if "shaders" in stages and not a.mesh_compute and not a.native_mesh: + mesh_shader = runtime_gpu_mesh_shader() crash = runtime_gpu_mesh_draws_crash() - if crash: + if mesh_shader is False: + log("shaders: the GPU the runtime would use has no VK_EXT_mesh_shader (meshShader): " + "translating with --mesh-compute (--native-mesh keeps them native)") + a.mesh_compute = True + elif crash: log("shaders: the GPU the runtime would use is on Intel's Windows Vulkan driver, whose mesh draws crash on " "these mesh shaders (BUILD-2202): translating with --mesh-compute (--native-mesh keeps them native)") a.mesh_compute = True - elif crash is None: + elif mesh_shader is None or crash is None: a.mesh_compute = keep_recorded_fallback("--mesh-compute", work) emulate, keep_emulated = (wave64_settings(a.wave64_emulate, mesh_compute=a.mesh_compute) if "shaders" in stages else (False, a.wave64_emulate == "auto")) @@ -3261,8 +3287,12 @@ def main() -> int: else: bary_fallback = runtime_gpu_barycentric_fallback() if bary_fallback is True: - log("shaders: this GPU's driver has a known BaryCoordKHR bug (Mesa ANV, or AMD's Windows driver " - "on gfx90c): translating with --bary-fallback") + if runtime_gpu_fragment_shader_barycentric() is False: + log("shaders: the GPU the runtime would use has no VK_KHR_fragment_shader_barycentric " + "(fragmentShaderBarycentric): translating with --bary-fallback") + else: + log("shaders: this GPU's driver has a known BaryCoordKHR bug (Mesa ANV, or AMD's Windows " + "driver on gfx90c): translating with --bary-fallback") a.bary_fallback = True elif bary_fallback is None: a.bary_fallback = keep_recorded_fallback("--bary-fallback", work) diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 60e9687830..2259e63a39 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -332,7 +332,8 @@ def run_cmd(cmd: list[str], env: dict | None = None, gpu: bool = True, *, def bary_fallback() -> bool: """LEONIDA_BARY_FALLBACK=1 (or 0): translate raw barycentrics to an ordinary vec3 input and draw it through - tools/bary_fallback_gs.py. Unset, it is on where tools/vk_subgroup_info.py reports a driver with a known + tools/bary_fallback_gs.py. Unset, it is on where tools/vk_subgroup_info.py reports no + VK_KHR_fragment_shader_barycentric with geometryShader (NVIDIA Pascal, ...) or a driver with a known BaryCoordKHR bug: Mesa ANV (SHADER-925) and AMD's Windows driver on gfx90c iGPUs (#5933).""" v = (os.environ.get("LEONIDA_BARY_FALLBACK") or "").strip().lower() if v in ("1", "true", "yes", "on"): diff --git a/tests/test_make_game_argparse.py b/tests/test_make_game_argparse.py index 39d7a5b886..d1c021eb35 100644 --- a/tests/test_make_game_argparse.py +++ b/tests/test_make_game_argparse.py @@ -365,6 +365,7 @@ def test_custom_jobs_forwarded_to_shaders(self): patch("make_game.runtime_gpu_per_vertex", return_value=None), \ patch("make_game.runtime_gpu_barycentric_fallback", return_value=None), \ patch("make_game.runtime_gpu_max_push_constants", return_value=None), \ + patch("make_game.runtime_gpu_mesh_shader", return_value=None), \ patch("make_game.runtime_gpu_mesh_draws_crash", return_value=None): ret = make_game.main() self.assertEqual(ret, 0) diff --git a/tests/test_make_game_translator_flags.py b/tests/test_make_game_translator_flags.py index ffae8710d9..766da01712 100644 --- a/tests/test_make_game_translator_flags.py +++ b/tests/test_make_game_translator_flags.py @@ -191,7 +191,7 @@ class MainWiringTest(unittest.TestCase): """main() parses the fallback flags and hands the same tuple to preflight() and shaders().""" def run_main(self, *extra_argv, per_vertex=None, barycentric_fallback=None, max_push_constants=None, - mesh_crash=False): + mesh_shader=True, mesh_crash=False): # An empty --out: main() reads the flags an existing translation was made with, and the default folder # is the user's own. out = tempfile.TemporaryDirectory() @@ -205,6 +205,7 @@ def run_main(self, *extra_argv, per_vertex=None, barycentric_fallback=None, max_ mock.patch("make_game.runtime_gpu_per_vertex", return_value=per_vertex), \ mock.patch("make_game.runtime_gpu_barycentric_fallback", return_value=barycentric_fallback), \ mock.patch("make_game.runtime_gpu_max_push_constants", return_value=max_push_constants), \ + mock.patch("make_game.runtime_gpu_mesh_shader", return_value=mesh_shader), \ mock.patch("make_game.runtime_gpu_mesh_draws_crash", return_value=mesh_crash), \ mock.patch("make_game.preflight") as preflight, \ mock.patch("make_game.shaders") as shaders, \ @@ -264,6 +265,14 @@ def test_runtime_gpu_barycentric_fallback_requires_a_boolean_probe_result(self): with self.subTest(raw=raw), mock.patch("make_game.runtime_gpu_info", return_value=raw): self.assertIs(make_game.runtime_gpu_barycentric_fallback(), want) + def test_runtime_gpu_fragment_shader_barycentric_requires_a_boolean_probe_result(self): + for raw, want in (({"fragment_shader_barycentric": True}, True), + ({"fragment_shader_barycentric": False}, False), + ({}, None), ({"fragment_shader_barycentric": 0}, None), + ({"fragment_shader_barycentric": "false"}, None)): + with self.subTest(raw=raw), mock.patch("make_game.runtime_gpu_info", return_value=raw): + self.assertIs(make_game.runtime_gpu_fragment_shader_barycentric(), want) + def test_pc_tail_ubo_follows_the_device(self): """On by itself where maxPushConstantsSize is below what the shaders need (144, or 152 with --mesh-compute), not where it fits or can't be read; asked for explicitly, it is on everywhere.""" @@ -277,9 +286,16 @@ def test_pc_tail_ubo_follows_the_device(self): self.assertEqual(self.run_main("--pc-tail-ubo", max_push_constants=256), (("--pc-tail-ubo",),) * 2) def test_mesh_compute_follows_the_device(self): - """On by itself on Intel's Windows Vulkan driver with mesh shaders (BUILD-2202), not elsewhere or where the - probe can't tell; --native-mesh keeps native mesh shaders there, and asked for, it is on everywhere. It - comes before the push-constant check, so 152 bytes are what a 144-byte Intel device is measured against.""" + """On by itself when the GPU lacks VK_EXT_mesh_shader (meshShader) or on Intel's Windows Vulkan driver with + mesh shaders (BUILD-2202), not elsewhere or where the probe can't tell; --native-mesh keeps native mesh + shaders, and asked for, --mesh-compute is on everywhere. It comes before the push-constant check, so 152 + bytes are what a 144-byte device is measured against.""" + self.assertEqual(self.run_main(mesh_shader=False), (("--mesh-compute",),) * 2) + self.assertEqual(self.run_main(mesh_shader=True, mesh_crash=False), ((), ())) + self.assertEqual(self.run_main(mesh_shader=None, mesh_crash=None), ((), ())) + self.assertEqual(self.run_main("--native-mesh", mesh_shader=False), ((), ())) + self.assertEqual(self.run_main(mesh_shader=False, max_push_constants=144), + (("--mesh-compute", "--pc-tail-ubo"),) * 2) self.assertEqual(self.run_main(mesh_crash=True), (("--mesh-compute",),) * 2) self.assertEqual(self.run_main(mesh_crash=False), ((), ())) self.assertEqual(self.run_main(mesh_crash=None), ((), ())) @@ -288,11 +304,23 @@ def test_mesh_compute_follows_the_device(self): self.assertEqual(self.run_main(mesh_crash=True, max_push_constants=144), (("--mesh-compute", "--pc-tail-ubo"),) * 2) + def test_runtime_gpu_mesh_shader_requires_a_boolean_probe_result(self): + for raw, want in (({"mesh_shader": True}, True), + ({"mesh_shader": False}, False), + ({}, None), + ({"mesh_shader": 1}, None), + ({"mesh_shader": "false"}, None)): + with self.subTest(raw=raw), mock.patch("make_game.runtime_gpu_info", return_value=raw): + self.assertIs(make_game.runtime_gpu_mesh_shader(), want) + def test_runtime_gpu_mesh_draws_crash_reads_the_probe(self): intel = make_game.VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS - for raw, want in (({"driver_id": intel, "mesh_in_supported_stages": True}, True), + for raw, want in (({"driver_id": intel, "mesh_shader": True}, True), + ({"driver_id": intel, "mesh_shader": False, "mesh_in_supported_stages": True}, False), + ({"driver_id": intel, "mesh_in_supported_stages": True}, True), ({"driver_id": intel, "mesh_in_supported_stages": False}, False), ({"driver_id": intel}, False), + ({"driver_id": 4, "mesh_shader": True}, False), ({"driver_id": 4, "mesh_in_supported_stages": True}, False), ({"device": "x"}, None), ({}, None)): @@ -318,7 +346,7 @@ class ProbeFailureKeepsAutomaticFlagsTest(RecordedFlagsTest): AUTOMATIC = ("--f16-interp-fallback", "--pc-tail-ubo") - def build(self, *extra_argv, per_vertex, max_push_constants, mesh_crash=False): + def build(self, *extra_argv, per_vertex, max_push_constants, mesh_shader=True, mesh_crash=False): """One `make_game.py --stages shaders` run: (the fallbacks of each translation it started, its log).""" translations, lines = [], [] @@ -344,6 +372,7 @@ def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): mock.patch("make_game.runtime_gpu_per_vertex", return_value=per_vertex), \ mock.patch("make_game.runtime_gpu_barycentric_fallback", return_value=None), \ mock.patch("make_game.runtime_gpu_max_push_constants", return_value=max_push_constants), \ + mock.patch("make_game.runtime_gpu_mesh_shader", return_value=mesh_shader), \ mock.patch("make_game.runtime_gpu_mesh_draws_crash", return_value=mesh_crash), \ mock.patch("make_game.preflight"), \ mock.patch.object(make_game, "py", fake_py), \ @@ -392,12 +421,60 @@ def test_a_failed_probe_adds_no_flag_to_a_folder_translated_without_it(self): self.assertEqual(make_game.recorded_fallback_flags(os.path.join(self.work, "elsewhere")), ()) def test_the_other_flags_are_not_kept_by_a_failed_probe(self): - # Only the two flags the probe decides are kept; one the user stops passing is dropped as before. + # Only the flags the probe decides are kept; one the user stops passing is dropped as before. self.build("--no-float-controls", per_vertex=False, max_push_constants=256) self.assertEqual(self.recorded(), "--no-float-controls --f16-interp-fallback") translations, _ = self.build(per_vertex=None, max_push_constants=None) self.assertEqual(translations, [("--f16-interp-fallback",)]) + def test_mesh_compute_from_missing_extension_is_kept_on_probe_failure(self): + translations, log = self.build(per_vertex=True, max_push_constants=256, mesh_shader=False) + self.assertEqual(translations, [("--mesh-compute",)]) + self.assertIn("no VK_EXT_mesh_shader (meshShader)", log) + self.assertEqual(self.recorded(), "--mesh-compute") + for ms, crash in ((None, None), (None, False), (True, None)): + with self.subTest(mesh_shader=ms, mesh_crash=crash): + translations, log = self.build(per_vertex=True, max_push_constants=256, + mesh_shader=ms, mesh_crash=crash) + self.assertEqual(translations, []) + self.assertIn("whether it needs --mesh-compute; the shaders were translated with it and it stays on", + log) + translations, _ = self.build(per_vertex=True, max_push_constants=256, mesh_shader=True, mesh_crash=False) + self.assertEqual(translations, [()]) + self.assertEqual(self.recorded(), "") + + def test_bary_fallback_logs_missing_extension_and_is_kept_on_probe_failure(self): + with mock.patch("make_game.runtime_gpu_barycentric_fallback", return_value=True), \ + mock.patch("make_game.runtime_gpu_fragment_shader_barycentric", return_value=False): + # build() mocks runtime_gpu_barycentric_fallback=None internally, so call through a helper patch: + pass + out = tempfile.TemporaryDirectory() + self.addCleanup(out.cleanup) + lines = [] + argv = ["make_game.py", "--stages", "shaders", "--out", out.name, "--work", self.work, "--no-tui"] + with mock.patch.object(sys, "argv", argv), \ + mock.patch("make_game.below_normal"), \ + mock.patch("make_game.choose_game", return_value=os.path.join(self.work, "game")), \ + mock.patch("make_game.check", return_value={"expected_exe": "game.exe"}), \ + mock.patch("make_game.wave64_settings", return_value=(True, True)), \ + mock.patch("make_game.runtime_gpu_per_vertex", return_value=False), \ + mock.patch("make_game.runtime_gpu_barycentric_fallback", return_value=True), \ + mock.patch("make_game.runtime_gpu_fragment_shader_barycentric", return_value=False), \ + mock.patch("make_game.runtime_gpu_max_push_constants", return_value=256), \ + mock.patch("make_game.runtime_gpu_mesh_shader", return_value=False), \ + mock.patch("make_game.runtime_gpu_mesh_draws_crash", return_value=False), \ + mock.patch("make_game.preflight") as preflight, \ + mock.patch("make_game.shaders") as shaders, \ + mock.patch.object(make_game, "log", lambda *a: lines.append(" ".join(map(str, a)))): + self.assertEqual(make_game.main(), 0) + joined = "\n".join(lines) + self.assertIn("no VK_KHR_fragment_shader_barycentric (fragmentShaderBarycentric)", joined) + self.assertNotIn("known BaryCoordKHR bug", joined) + self.assertEqual(preflight.call_args.kwargs["fallbacks"], + ("--bary-fallback", "--mesh-compute", "--f16-interp-fallback")) + self.assertEqual(shaders.call_args.kwargs["fallbacks"], + ("--bary-fallback", "--mesh-compute", "--f16-interp-fallback")) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_make_game_wave64.py b/tests/test_make_game_wave64.py index 9ceb87c07f..001512bc35 100644 --- a/tests/test_make_game_wave64.py +++ b/tests/test_make_game_wave64.py @@ -331,6 +331,7 @@ def fake_run(args, **kwargs): mock.patch.object(make_game.subprocess, "run", side_effect=fake_run), \ mock.patch.object(make_game, "runtime_gpu_per_vertex", return_value=True), \ mock.patch.object(make_game, "runtime_gpu_max_push_constants", return_value=256), \ + mock.patch.object(make_game, "runtime_gpu_mesh_shader", return_value=True), \ mock.patch.object(make_game, "runtime_gpu_mesh_draws_crash", return_value=False), \ mock.patch.object(make_game, "shaders") as sh: make_game.main() diff --git a/tests/test_vk_subgroup_info.py b/tests/test_vk_subgroup_info.py index 63ff2fd40a..5f291f2c3b 100644 --- a/tests/test_vk_subgroup_info.py +++ b/tests/test_vk_subgroup_info.py @@ -70,6 +70,9 @@ class FakeDevice: vk_info.VK_SHADER_STAGE_COMPUTE_BIT | vk_info.VK_SHADER_STAGE_MESH_BIT_EXT ) fragment_shader_barycentric: bool = True + geometry_shader: bool = True + task_shader: bool = False + mesh_shader: bool = False max_push_constants_size: int = 256 driver_id: int = 1 # VK_DRIVER_ID_AMD_PROPRIETARY vendor_id: int = 0 @@ -227,7 +230,11 @@ def _get_physical_device_features2(self, phys_dev, p_features): seen_types = set() for stype, node_addr in self._iter_chain(addr): seen_types.add(stype) - if stype == vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES: + if stype == vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2: + ctypes.c_uint32.from_address( + node_addr + vk_info.F2_GEOMETRY_SHADER + ).value = int(dev.geometry_shader) + elif stype == vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES: ctypes.c_uint32.from_address( node_addr + vk_info.F12_SEPARATE_DEPTH_STENCIL_LAYOUTS ).value = int(dev.separate_depth_stencil_layouts) @@ -255,10 +262,17 @@ def _get_physical_device_features2(self, phys_dev, p_features): ctypes.c_uint32.from_address(node_addr + 16).value = int(dev.subgroup_size_control) elif stype == vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR: ctypes.c_uint32.from_address(node_addr + 16).value = int(dev.fragment_shader_barycentric) + elif stype == vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT: + ctypes.c_uint32.from_address(node_addr + 16).value = int(dev.task_shader) + ctypes.c_uint32.from_address(node_addr + 20).value = int(dev.mesh_shader) + ctypes.c_uint32.from_address(node_addr + 24).value = 0 + ctypes.c_uint32.from_address(node_addr + 28).value = 0 + ctypes.c_uint32.from_address(node_addr + 32).value = 0 expected = { vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR, + vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT, } if dev.api_version >= vk_info.VK_API_VERSION_1_3: expected.add(vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES) @@ -336,6 +350,7 @@ def test_vulkan_structure_types(self): self.assertEqual(vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES, 1000225000) self.assertEqual(vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES, 1000196000) self.assertEqual(vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR, 1000203000) + self.assertEqual(vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT, 1000328000) def test_shader_stage_bits(self): self.assertEqual(vk_info.VK_SHADER_STAGE_COMPUTE_BIT, 0x20) @@ -363,15 +378,18 @@ def test_structure_sizes(self): self.assertEqual(vk_info.F12_SIZE, 208) self.assertEqual(vk_info.F13_SIZE, 80) self.assertEqual(vk_info.BARY_FEATURES_SIZE, 24) + self.assertEqual(vk_info.MESH_FEATURES_SIZE, 40) self.assertEqual(vk_info.DRIVER_PROPS_SIZE, 536) self.assertEqual(vk_info.QUEUE_FAMILY_SIZE, 24) def test_feature_and_property_offsets(self): + self.assertEqual(vk_info.F2_GEOMETRY_SHADER, 16 + 4 * 4) self.assertEqual(vk_info.F12_SEPARATE_DEPTH_STENCIL_LAYOUTS, 16 + 4 * 35) self.assertEqual(vk_info.F12_TIMELINE_SEMAPHORE, 16 + 4 * 37) self.assertEqual(vk_info.F13_SUBGROUP_SIZE_CONTROL, 16 + 4 * 7) self.assertEqual(vk_info.F13_SYNCHRONIZATION2, 16 + 4 * 9) self.assertEqual(vk_info.F13_DYNAMIC_RENDERING, 16 + 4 * 12) + self.assertEqual(vk_info.MESH_FEATURES_MESH_SHADER, 20) self.assertEqual(vk_info.PROPS_API_VERSION, 0) self.assertEqual(vk_info.PROPS_VENDOR_ID, 8) self.assertEqual(vk_info.PROPS_DEVICE_ID, 12) @@ -816,6 +834,9 @@ def test_native64_conditions_and_boundaries(self): "mesh_in_supported_stages": True, "native64_compute": want_native64 or label == "missing_mesh_stage_bit", "native64": want_native64, + "mesh_shader": False, + "fragment_shader_barycentric": True, + "geometry_shader": True, "per_vertex_inputs": True, "barycentric_fallback": False, "max_push_constants_size": 256, @@ -826,6 +847,30 @@ def test_native64_conditions_and_boundaries(self): "rdna2_amd_windows": False, }) + def test_mesh_shader_feature_query(self): + """mesh_shader requires VK_EXT_mesh_shader in device extensions and meshShader (offset 20, after taskShader).""" + v12_base = (b"VK_KHR_dynamic_rendering", b"VK_KHR_synchronization2") + cases = ( + ("v13_without_extension", FakeDevice(mesh_shader=True), False), + ("v13_with_extension_and_feature", FakeDevice(extension_names=(b"VK_EXT_mesh_shader",), + mesh_shader=True), True), + ("v13_task_only_mesh_zero", FakeDevice(extension_names=(b"VK_EXT_mesh_shader",), + task_shader=True, mesh_shader=False), False), + ("v12_with_extension_and_feature", FakeDevice(api_version=vk_info.VK_API_VERSION_1_2, + extension_names=v12_base + (b"VK_EXT_mesh_shader",), + mesh_shader=True), True), + ("v12_without_extension", FakeDevice(api_version=vk_info.VK_API_VERSION_1_2, + extension_names=v12_base, + mesh_shader=True), False), + ("v12_task_only_mesh_zero", FakeDevice(api_version=vk_info.VK_API_VERSION_1_2, + extension_names=v12_base + (b"VK_EXT_mesh_shader",), + task_shader=True, mesh_shader=False), False), + ) + for label, dev, want in cases: + with self.subTest(case=label): + res, _vk = self._run_query(dev) + self.assertIs(res["mesh_shader"], want) + def test_max_push_constants_size(self): """limits.maxPushConstantsSize is read from VkPhysicalDeviceProperties (offset 328 on 64-bit).""" for limit in (128, 256, 4096): @@ -880,6 +925,27 @@ def test_barycentric_fallback(self): self.assertIs(res["barycentric_fallback"], want) self.assertEqual(vk_info.VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA, 6) + def test_barycentric_fallback_when_extension_missing_and_geometry_shader_supported(self): + """Devices without VK_KHR_fragment_shader_barycentric take --bary-fallback iff geometryShader is supported + (NVIDIA Pascal, Intel Gen9.5, older GCN; MoltenVK lacks geometryShader and stays False).""" + ext = (vk_info.FRAGMENT_SHADER_BARYCENTRIC_EXTENSION,) + cases = ( + ("pascal_no_ext_with_gs", False, (), True, 4, False, False, True), + ("feature_bit_without_ext_with_gs", True, (), True, 3, False, False, True), + ("ext_listed_feature_zero_with_gs", False, ext, True, 4, False, False, True), + ("moltenvk_with_bary_no_gs", True, ext, False, vk_info.VK_DRIVER_ID_MOLTENVK, True, False, False), + ("moltenvk_without_bary_no_gs", False, (), False, vk_info.VK_DRIVER_ID_MOLTENVK, False, False, False), + ("turing_with_bary_and_gs", True, ext, True, 4, True, True, False), + ) + for label, bary_bit, names, gs, drv, want_bary, want_pv, want_fb in cases: + with self.subTest(case=label): + res, _vk = self._run_query(FakeDevice(fragment_shader_barycentric=bary_bit, extension_names=names, + geometry_shader=gs, driver_id=drv)) + self.assertIs(res["fragment_shader_barycentric"], want_bary) + self.assertIs(res["geometry_shader"], gs) + self.assertIs(res["per_vertex_inputs"], want_pv) + self.assertIs(res["barycentric_fallback"], want_fb) + def test_barycentric_fallback_rejects_an_intel_windows_fake(self): """Intel Windows uses its Windows driver ID, not ANV; the fake must carry Intel's vendor ID.""" res, _vk = self._run_query(FakeDevice(name="Intel Arc", vendor_id=0x8086, device_id=0xE20B, diff --git a/tools/vk_subgroup_info.py b/tools/vk_subgroup_info.py index ca7cd79a6e..c5f5ff8ee6 100644 --- a/tools/vk_subgroup_info.py +++ b/tools/vk_subgroup_info.py @@ -27,6 +27,10 @@ driver. Its shader compiler can crash in vkCreateComputePipelines on emulated wave64 compute shaders with LDS (#857, reported on RX 5000, RX 6000 and RDNA2 iGPUs). make_game.py prefers native wave64 when the GPU can run it. +mesh_shader says whether the device exposes VK_EXT_mesh_shader and sets VkPhysicalDeviceMeshShaderFeaturesEXT.meshShader. +Where it is false (NVIDIA Pascal, AMD RDNA1/GCN, older Intel iGPUs, MoltenVK), make_game.py translates mesh shaders +with --mesh-compute unless --native-mesh is passed. + per_vertex_inputs says whether the device can run a pixel shader with PerVertexKHR inputs (16-bit interpolation, docs/design.md): the fragmentShaderBarycentric feature with VK_KHR_fragment_shader_barycentric in the device's extension list, and a driver other than MoltenVK, whose SPIR-V to MSL conversion rejects the decoration @@ -34,15 +38,15 @@ 26.2.6) fills it with a one on a gfx90c iGPU (Vega 8, PCI 1002:15E7) that doesn't list the extension. Where it is false, the shaders are translated with --f16-interp-fallback. -barycentric_fallback is true for Intel's open-source Mesa driver (ANV). SHADER-925 found that Mesa ANV 26.2.5 -advertises fragmentShaderBarycentric but returns a zero BaryCoordKHR.i for translated pixel shaders on Intel Arc B580; -the pass-through geometry-shader fallback is correct there. The builder therefore selects --bary-fallback for ANV -until the driver issue is fixed. It is also true for gfx90c iGPUs (Renoir, Lucienne, Cezanne, Barcelo; GCN 5) under -AMD's proprietary Windows driver: #5933 found that driver 31.0.21921.13001 on a Vega 8 (PCI 1002:15E7) advertises -fragmentShaderBarycentric but returns a wrong third BaryCoordKHR component (about 0.99 where a small value is -expected) in ps_bary, ps_persp_bary and ps_ij_computed, while the fallback passes and RADV on RDNA 3.5 passes natively. -The check keys on the PCI device ID and the driver ID, not on the driver version, so a fixed driver would still take -the fallback (correct, one geometry-shader stage slower); LEONIDA_BARY_FALLBACK=0 turns it off. +barycentric_fallback is true when the device lacks VK_KHR_fragment_shader_barycentric (fragmentShaderBarycentric) +and supports geometryShader (NVIDIA Pascal, Intel Gen9.5, AMD Polaris/GCN without the extension; MoltenVK lacks +geometryShader and stays false), and for drivers that advertise native barycentrics with a known BaryCoordKHR bug: +Intel's open-source Mesa driver (ANV; SHADER-925 found that Mesa ANV 26.2.5 returns a zero BaryCoordKHR.i for +translated pixel shaders on Intel Arc B580) and gfx90c iGPUs (Renoir, Lucienne, Cezanne, Barcelo; GCN 5) under AMD's +proprietary Windows driver (#5933 found that driver 31.0.21921.13001 on a Vega 8, PCI 1002:15E7, returns a wrong +third BaryCoordKHR component in ps_bary, ps_persp_bary and ps_ij_computed, while the fallback passes and RADV on +RDNA 3.5 passes natively). The driver-bug check keys on the PCI device ID and the driver ID, not on the driver +version; LEONIDA_BARY_FALLBACK=0 turns it off. max_push_constants_size is VkPhysicalDeviceProperties.limits.maxPushConstantsSize in bytes. The default shader contract uses 144 bytes (152 with --mesh-compute); where a device reports less (e.g. 128 on AMD's Windows driver for @@ -68,6 +72,7 @@ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT = 1000225002 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES = 1000196000 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR = 1000203000 +VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT = 1000328000 VK_DRIVER_ID_MOLTENVK = 14 VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA = 6 VK_DRIVER_ID_AMD_PROPRIETARY = 1 @@ -86,6 +91,7 @@ GFX90C_DEVICE_IDS = (0x15E7, 0x1636, 0x1638, 0x164C) DRIVER_PROPS_SIZE = 536 # sizeof(VkPhysicalDeviceDriverProperties): 16 + driverID + 2 x char[256] + version, padded BARY_FEATURES_SIZE = 24 # sizeof(VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR): 16 + one VkBool32 +MESH_FEATURES_SIZE = 40 # sizeof(VkPhysicalDeviceMeshShaderFeaturesEXT): 16 + 5 VkBool32, padded to 8 VK_SHADER_STAGE_COMPUTE_BIT = 0x20 VK_SHADER_STAGE_MESH_BIT_EXT = 0x80 VK_QUEUE_GRAPHICS_BIT = 1 @@ -95,18 +101,21 @@ VK_INCOMPLETE = 5 VULKAN_12_REQUIRED_EXTENSIONS = frozenset((b"VK_KHR_dynamic_rendering", b"VK_KHR_synchronization2")) FRAGMENT_SHADER_BARYCENTRIC_EXTENSION = b"VK_KHR_fragment_shader_barycentric" +MESH_SHADER_EXTENSION = b"VK_EXT_mesh_shader" PROPS_SIZE = 824 # sizeof(VkPhysicalDeviceProperties) on 64-bit FEATURES2_SIZE = 240 # sizeof(VkPhysicalDeviceFeatures2): 16 + 55 VkBool32, padded to 8 F12_SIZE = 208 # sizeof(VkPhysicalDeviceVulkan12Features): 16 + 47 VkBool32, padded to 8 F13_SIZE = 80 # sizeof(VkPhysicalDeviceVulkan13Features): 16 + 15 VkBool32, padded to 8 # Byte offsets of the VkBool32 members read below (16-byte header, then 4 bytes per member in header order) +F2_GEOMETRY_SHADER = 16 + 4 * 4 # geometryShader in VkPhysicalDeviceFeatures2.features F12_SEPARATE_DEPTH_STENCIL_LAYOUTS = 16 + 4 * 35 F12_TIMELINE_SEMAPHORE = 16 + 4 * 37 F12_BUFFER_DEVICE_ADDRESS = 16 + 4 * 38 F13_SUBGROUP_SIZE_CONTROL = 16 + 4 * 7 F13_SYNCHRONIZATION2 = 16 + 4 * 9 F13_DYNAMIC_RENDERING = 16 + 4 * 12 +MESH_FEATURES_MESH_SHADER = 16 + 4 # meshShader follows taskShader in VkPhysicalDeviceMeshShaderFeaturesEXT PROPS_DEVICE_TYPE = 16 # offsets in VkPhysicalDeviceProperties PROPS_VENDOR_ID = 8 PROPS_DEVICE_ID = 12 @@ -188,11 +197,13 @@ def gfx90c_amd_windows(vendor_id: int, device_id: int, driver_id: int) -> bool: and device_id in GFX90C_DEVICE_IDS) -def barycentric_fallback(vendor_id: int, device_id: int, driver_id: int) -> bool: - """Drivers that expose native barycentrics but return wrong BaryCoordKHR values for translated pixel shaders: - Mesa ANV (BaryCoordKHR.i zero on Intel Arc, SHADER-925) and AMD's Windows driver on gfx90c (wrong third - component, #5933).""" - return (driver_id == VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA +def barycentric_fallback(vendor_id: int, device_id: int, driver_id: int, *, + fragment_shader_barycentric: bool = True, geometry_shader: bool = True) -> bool: + """Devices that need --bary-fallback: GPUs without VK_KHR_fragment_shader_barycentric that have geometryShader + (NVIDIA Pascal, Intel Gen9.5, older GCN; not MoltenVK, which has no geometryShader), plus drivers that advertise + native barycentrics with wrong BaryCoordKHR values (Mesa ANV, SHADER-925; AMD Windows on gfx90c, #5933).""" + return ((not fragment_shader_barycentric and geometry_shader) + or driver_id == VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA or gfx90c_amd_windows(vendor_id, device_id, driver_id)) @@ -293,6 +304,8 @@ def query(*, stage_caps=False) -> dict: f13 = block(F13_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES) f12 = block(F12_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES) bary = block(BARY_FEATURES_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR) + mesh = block(MESH_FEATURES_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT) + set_next(bary, mesh) sg_features = None if core13: set_next(f12, f13) @@ -338,7 +351,9 @@ def query(*, stage_caps=False) -> dict: subgroup.subgroupSize, subgroup.supportedStages, sg.minSubgroupSize, sg.maxSubgroupSize, sg.requiredSubgroupSizeStages, sg.maxComputeWorkgroupSubgroups, sgc, - bool(u32(bary, 16)) and u32(drv, 16) != VK_DRIVER_ID_MOLTENVK, + bool(u32(mesh, MESH_FEATURES_MESH_SHADER)), + bool(u32(bary, 16)), + bool(u32(f2, F2_GEOMETRY_SHADER)), int.from_bytes(raw[PROPS_MAX_PUSH_CONSTANTS_SIZE:PROPS_MAX_PUSH_CONSTANTS_SIZE + 4], "little"), int.from_bytes(raw[PROPS_VENDOR_ID:PROPS_VENDOR_ID + 4], "little"), int.from_bytes(raw[PROPS_DEVICE_ID:PROPS_DEVICE_ID + 4], "little"), u32(drv, 16)) @@ -350,12 +365,15 @@ def query(*, stage_caps=False) -> dict: ) raise RuntimeError("no Vulkan 1.3 GPU with the features and graphics queue the runtime needs") (name, subgroup_size, supported_stages, lo, hi, required_stages, max_workgroup_subgroups, - sgc, per_vertex, max_push_constants_size, vendor, device, driver) = chosen - if per_vertex: - # The feature counts only with its extension listed (RADV sets it on gfx90c without one). - # Reuse the Vulkan 1.2 extension set already fetched above, and query Vulkan 1.3 devices only once chosen. + sgc, mesh_shader, has_bary, geometry_shader, max_push_constants_size, vendor, device, driver) = chosen + if mesh_shader or has_bary: + # Extension features count only with their extension listed (RADV sets fragmentShaderBarycentric on gfx90c + # without one). Reuse the Vulkan 1.2 extension set already fetched above, and query Vulkan 1.3 devices only + # once chosen. exts = device_extensions(vk, chosen_d) if chosen_extensions is None else chosen_extensions - per_vertex = FRAGMENT_SHADER_BARYCENTRIC_EXTENSION in exts + mesh_shader = mesh_shader and MESH_SHADER_EXTENSION in exts + has_bary = has_bary and FRAGMENT_SHADER_BARYCENTRIC_EXTENSION in exts + per_vertex = has_bary and driver != VK_DRIVER_ID_MOLTENVK compute_required = bool(required_stages & VK_SHADER_STAGE_COMPUTE_BIT) mesh_required = bool(required_stages & VK_SHADER_STAGE_MESH_BIT_EXT) compute_supported = bool(supported_stages & VK_SHADER_STAGE_COMPUTE_BIT) @@ -376,8 +394,13 @@ def query(*, stage_caps=False) -> dict: "mesh_in_supported_stages": mesh_supported, "native64_compute": compute64, "native64": compute64 and mesh64, + "mesh_shader": mesh_shader, + "fragment_shader_barycentric": has_bary, + "geometry_shader": geometry_shader, "per_vertex_inputs": per_vertex, - "barycentric_fallback": barycentric_fallback(vendor, device, driver), + "barycentric_fallback": barycentric_fallback( + vendor, device, driver, fragment_shader_barycentric=has_bary, geometry_shader=geometry_shader + ), "max_push_constants_size": max_push_constants_size, "vendor_id": vendor, "device_id": device,