From c6138d9bc245a8c7c879900b1ba0cce400ddb982 Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:26:31 +0100 Subject: [PATCH 01/53] Match RDNA2 saturating float-to-int conversions --- tools/rdna2spirv.py | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 21c097564..8c37738dd 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -3367,15 +3367,36 @@ class Gen: self.emit(f"{r} = OpConvertUToF %float {m}") self.dst(a[0], self.tou(r)) elif op in ("v_cvt_u32_f32", "v_cvt_i32_f32"): - x = self.src_f(a[1]) - r = self.tmp() + # Compare binary32 words before converting: the raw SPIR-V conversion + # must only see a representable operand, even when its result is discarded. + bits = self.src_u(a[1]) + zero = self.cu(0) + past_inf = self.cu(0x7F800001) + in_range, saturated, safe, converted, result = (self.tmp() for _ in range(5)) if op == "v_cvt_u32_f32": - self.emit(f"{r} = OpConvertFToU %uint {x}") + positive = self.tmp() + self.emit(f"{in_range} = OpULessThan %bool {bits} {self.cu(0x4F800000)}") # +2^32 + # Positive overflow through +inf saturates. Negative values and NaNs give zero. + self.emit(f"{positive} = OpULessThan %bool {bits} {past_inf}") + self.emit(f"{saturated} = OpSelect %uint {positive} {self.cu(0xFFFFFFFF)} {zero}") else: - i = self.tmp() - self.emit(f"{i} = OpConvertFToS %int {x}") - self.emit(f"{r} = OpBitcast %uint {i}") - self.dst(a[0], r) + magnitude, negative, not_nan, bound = (self.tmp() for _ in range(4)) + self.emit(f"{magnitude} = OpBitwiseAnd %uint {bits} {self.cu(0x7FFFFFFF)}") + self.emit(f"{in_range} = OpULessThan %bool {magnitude} {self.cu(0x4F000000)}") # 2^31 + self.emit(f"{negative} = OpINotEqual %bool {bits} {magnitude}") + self.emit(f"{not_nan} = OpULessThan %bool {magnitude} {past_inf}") + self.emit(f"{bound} = OpSelect %uint {negative} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}") + self.emit(f"{saturated} = OpSelect %uint {not_nan} {bound} {zero}") + self.emit(f"{safe} = OpSelect %uint {in_range} {bits} {zero}") + x = self.tof(safe) + if op == "v_cvt_u32_f32": + self.emit(f"{converted} = OpConvertFToU %uint {x}") + else: + signed = self.tmp() + self.emit(f"{signed} = OpConvertFToS %int {x}") + self.emit(f"{converted} = OpBitcast %uint {signed}") + self.emit(f"{result} = OpSelect %uint {in_range} {converted} {saturated}") + self.dst(a[0], result) elif op in U2 or op in S2: x, y = self.src_u(a[1]), self.src_u(a[2]) r = self.tmp() From 6bb3b5330a665e256bfc64cdbbf4cc85a4b00293 Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:27:57 +0100 Subject: [PATCH 02/53] Document RDNA2 float-to-int saturation semantics --- design.md | 342 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 342 insertions(+) create mode 100644 design.md diff --git a/design.md b/design.md new file mode 100644 index 000000000..58762cba7 --- /dev/null +++ b/design.md @@ -0,0 +1,342 @@ +# Design notes + +Groundwork for running the Xbox Series build of GTA VI natively on Windows. The work that does not need the +executable is in place; booting can start as soon as `game_scarlett_master.exe` is available. + +## Ground rules + +- Everything here runs from **your own copy** and stays on **your PC**. Game files, generated code, shader caches and + reports that quote game data are never committed, uploaded or shared. `reports/` is git-ignored for this reason. +- Nothing in this folder decrypts, unpacks or works around Xbox package protection. The tools only read files that + are already plain on disk. + +## Why a loader before a recompiler + +The Xbox Series CPU is x86-64, the same as a PC. Unlike Hookshot, where ARM64 code has to be +translated, most of the game's code can run as-is. The work is everything around it: + +| Layer | Approach | Folder | +|---|---|---| +| CPU code | Map the PE image and run it natively. Patch only what can't run on desktop (privileged instructions, console-only intrinsics). | `runtime/src` | +| Imports (GameOS / GDK / Xbox DLLs) | Every imported `dll!function` goes to a shim. Unimplemented ones log once and return a failure, so the missing surface shows up at runtime. | `runtime/shims` | +| Graphics | Xbox D3D12 (`d3d12_xs`) to Vulkan. Shaders ship as compiled RDNA2 machine code; `tools\rdna2spirv.py` translates all 26,503 to SPIR-V. The D3D12 layer is still to do. | `tools\` (translator), later (D3D12) | +| Assets | `.rpf` archives (RPF9) read through the runtime's file layer. | later | + +## Layout + +``` +tools/ Python analysis tools (no game data inside) + pe_inspect.py PE headers, sections, entropy, imports sorted by where they resolve, .pdata, TLS + rpf_probe.py RPF header survey of a game folder + manifest.py SHA-256 manifest of a game folder, plus a --verify mode +scripts/ + first_look.ps1 run once the exe arrives: the full report set for it +runtime/ C++ native loader (CMake + Ninja, MSVC) + src/ PE mapper, relocations, import binding, TLS + shims/ per-DLL shim tables +reports/ generated output (git-ignored) +docs/ notes +``` + +## Day one, when the exe is here + +```powershell +.\scripts\first_look.ps1 -Exe "\game_scarlett_master.exe" +``` + +This writes `reports/exe/` (JSON plus a readable summary). Check it in this order: + +1. **Section entropy.** Sections near 8.0 bits/byte are still encrypted or compressed. If `.text` is one of them, + nothing else can be done yet. +2. **Import table.** Each DLL is marked `bundled` (in the game folder), `system` (present on this Windows), or + `shim` (needs a reimplementation). The `shim` list is the real to-do list. +3. **.pdata function count.** This gives function boundaries for patching and later analysis. + +Then `runtime\build\gta6rt.exe --dry-run ` maps the image and binds every import to the shim table without +running any game code. It reports what it couldn't bind. + +## Reproduce the shader tests + +Build the hand-written tests where LLVM supports AMDGPU and SPIRV-Tools is available. Run the generated shaders +with the Vulkan test tools on the target GPU. Use the same output folder in both commands. + +```text +python -I runtime/test/shaders/build.py +python -I runtime/test/shaders/check.py [runtime-build-directory] +``` + +The wave-mask fixture checks every lane and the wave64 ballot fixture checks mask counts and first-set lanes +across both halves of a wave. Rebuild `vk_compute_test` before running `check.py`. It uses a full 64-wide compute +subgroup for these two checks, and the summary reports them as skipped if the device cannot provide one. +`cs_exec64` still checks per-lane EXEC writes on 32-wide subgroups. With `LEONIDA_W64_EMULATE=1` in the environment of both commands, `build.py` translates with `--wave64-emulate` and `check.py` runs every wave64 check without asking for a 64-wide subgroup, so a 32-wide GPU runs them all (`scripts/run_gpu_tests.py` honours the same variable). Pick one of several GPUs with the Vulkan loader, e.g. `VK_LOADER_DRIVERS_SELECT='*nv*'` or `'*amd*'`. The flat-input fixture checks both integer +IDs and interpolated UVs. The corpus comparison is a separate test and uses shader files from the local build. + +Run `python -I scripts/run_gpu_tests.py --filter ms_v5_workgroup` to check the mesh workgroup index. The synthetic +shader exports its incoming `v5` from lanes 0, 1 and 31 in the RGB channels of a full-screen triangle. One `vkCmdDrawMeshTasksEXT(2, 3, 4)` +produces 24 triangles. A stencil countdown lets pixel *i* record only triangle *i* in Vulkan rasterization order. +The CPU compares each pixel with `x + 2*y + 6*z`. This checks the translator's register mapping on the host GPU. +SPIRV-Tools 2026.1 validates this fixture. Version 2025.1 reports a known error on `CullPrimitiveEXT`. +[Vulkan mesh rasterization order](https://docs.vulkan.org/features/latest/features/proposals/VK_EXT_mesh_shader.html) · [Validator fix](https://github.com/KhronosGroup/SPIRV-Tools/pull/6155). + +## Build the runtime + +```powershell +.\scripts\build_runtime.ps1 +``` + +It sets up MSVC through `vcvars64.bat` and builds at BelowNormal priority on half the cores, writing to `runtime\build\`. +If VS's "C++ CMake tools" component is installed, it uses CMake and Ninja. Otherwise it calls `cl` directly. That +component may not be installed, and the devkitPro MSYS `cmake` on PATH can't build MSVC projects. When you +add a source file, add it to `runtime\CMakeLists.txt` and to the file list in `build_runtime.ps1`. + +## Asset status (no exe needed) + +| Asset | State | Where | +|---|---|---| +| Archive data | Carved without the encrypted tables of contents. Most archives are 93–99% plain zlib (`levels.rpf` 98.3%, 1.1M files). Not zlib: `audio.rpf` (99.9%), about half of `story000.rpf` and `shared_minigame000.rpf`. | `\carve\\`, `coverage.json` | +| Videos | 797 Bink 2 files (`KB2n`), cut out whole. | `*.bk2` in the carve folders | +| Shaders | 26,503 carved from `shaders.rpf`, native RDNA2 code unpacked (`FSSM`), disassembled, and translated to SPIR-V; all validate (see *Translator status*). | `\shaders\` (`.dxbc`, `fssm\`, `disasm\`, `spirv\`) | +| Textures | **Solved.** Headers are in CPU segments: GPU pointer at q[k], u16 width/height/depth and DXGI format at q[k+4], mip count at byte 2 of q[k+5]. Data is AMD `SW_4K_S` tiled, largest mip first. The GPU segment is the blob run after the CPU blob. On 200 samples, 173 decode at least 1.5× smoother detiled than untiled (median 2.56×). Exports the top mip, slice 0, as DDS. **22,342 exported (1.23 GiB)**: every header whose GPU data follows its CPU blob. World and model textures are handled by the TXD and TTPF exporters below. GPU offsets must be 256-byte aligned, which drops the false headers in `navmeshes`/`anim`. | `tools\tex_headers.py`, `tools\tex_export.py`, `\textures\` | +| Models | **Done: 155,598 models** (levels.rpf 149,811 with 1.9 billion triangles, story000 3,303, data 1,350, shared_minigame000 783, packs 314, core_restofworld 37; 0 failures). Exported with `tools\rpf9dump` (built on breadbbbb/rpf9-explorer's Core; see below). Resources are found at page offset +16 after 16 zero bytes, followed by a zlib system blob with a drawable/fragment header and then the following zlib blocks as graphics data. Positions are quantized: `bias + scale * ((q >> 8) & 0xFFFFFF)`. Output is OBJ (positions, UVs, indices) plus a manifest with real model names (e.g. `cvar_int_grg2b_toys_1`), bounds, per-mesh shader index and material texture references (parameter hash, name hash, 64-bit asset key). My earlier `0x1380`/`0x1601` descriptor notes stand, but the "data not located" blocker was wrong. | `\assets\\models\` | +| Texture dictionaries | Same tool: TXD resources become DDS per texture. | `\assets\\textures\` | +| World textures (TTPF) | **Done: 308,895 textures from all 57 pools, 0 failures, 48,220 entries skipped by the original exporter** (33,507 BCPack, 14,030 compact mapping, 678 arrays/volumes, 5 unsupported format, 0 unmapped). The compact-tail tool resolves 14,011 of the 14,030 layouts and reconstructs 305,264 complete chains (206,661 newly complete, 1,100,865 mips, 4.59 GiB); BCPack remains the hard blocker. 46 pools are in `data\ttdb\**`, 11 in `pack\\data\ttdb\**` (exported under `ttpf_pack\\`). `data\ttdb\**\*.ttpf` (57 pools, 58 GiB) are loose RDS5 texture pools, **not** inside RPFs. rpf9-explorer's `TtpfReader` reads the catalog and detiles them; checked visually (`ttdb_graphics`: scope reticles, clean lines). Names are generated (`texture_N_`); models reference textures by asset key. Some rows are skipped; the measured breakdown and the BCPack next step are in [textures.md](textures.md). | `\assets\ttpf\\` + `manifest.json` | +| Animation | Indexed without the TOC: 130,470 zlib streams (4,203,762,662 stored / 11,593,460,132 inflated), 95.4% readable. New RAGE page directories (`0DRP`, version 122), `MoVE` (version 19), 273 `pack:/` name tables (2,298 paths), and a tail `RBF0` rig-set manager (`rage__crRigSetManager`: 1,126 rig sets, 6,677 source→rig entries, 3,669 distinct rigs; 56 empty). Bone data: one standalone 28-name table and 3 motion-matcher streams with embedded bone tables (30-name union, 19 joaat32 hashes present, 4 motionmatcher paths); no rig→skeleton link was found. No `YCD`/`RSC7` at any stream start. The `rpf9_carve` tail overread is measured in `docs/animation.md`. | `tools\anim_index.py`, `\anim-index\` | +| Audio | `audio.rpf` holds raw (not zlib) **AWC** banks: Opus (codec 0x0B) and XMA2 streams. Exported as whole `.awc` files plus `audio_manifest.json` (stream ids, codec, channels, rate, duration). **Done: 7,162 banks, 27 GiB, 1,603,231 streams, about 1,324 hours** (codec 0x0B Opus 1,601,167; 5: 1,818; 2: 227; 0 PCM: 19). `tools/awc_opus.py` repackages every Opus stream **losslessly** into a standard Ogg Opus file (no re-encode; PCM streams become .wav). The AWC framing is 2048-byte blocks of [u16 length][packet], with a zero length padding the block (as rpf9-explorer's OpusPreview reads it). The final granule is trimmed to the declared sample count. Checked: 300 random streams decode with ffmpeg with no errors, lengths match the declared counts. XMA2 streams (codec 5, 1,818) are written as RIFF XMA2 files by `rpf9dump xma` (rpf9-explorer's `AwcRecovery.WriteXmaWave`) and decoded to PCM WAV by ffmpeg: all 1,818 decode. Streamed music (tag 0x48: chunks with a per-channel record table, each channel's 2048-byte subblocks after the aligned header, and a repeated-prefix skip per chunk) becomes one Ogg Opus per descriptor channel (3,008 banks contain music). The Opus TOC stereo bit gives the packet channel count; a 1-channel descriptor can carry stereo packets, whose interleaved sample count is halved for the end granule. Checked: a 4-channel bank gives four 42.0 s mono channels; 1-channel stereo banks export at the config duration. Output: `\assets\audio\ogg\\.ogg`. **Done: 1,598,051 Opus streams + 3,116 music channels as Ogg Opus (22 GB), 19 PCM16 and 227 codec-2 streams (32-bit float PCM, 4 bytes per sample; values can exceed ±1) as WAV, 1,818 XMA2 as WAV. Every audio stream is converted; all WAVs decode.** `make_game.py --wav` also decodes the Ogg Opus output to 16-bit PCM WAV with `tools/audio_wav.py` (ffmpeg required; existing WAVs are skipped on resume). | `\assets\audio\awc\` | +| World placement | **Full census of `levels.rpf`:** 23,535 map resources / 1,670,442 entities; all maps/entities exact, 36/36 shards, 98.32% stream coverage. Map files occupy a continuous band from ~7.5 to ~62.9 GiB; the earlier 9,918 / 680,228 sample was a 55% lower bound. `0x7a` resources: `CMapData` root, 0x90-byte `CEntityDef` with position/quaternion/scale/archetype/flags/GUID/LOD fields; names and most archetypes are hash-only. | `tools\world_index.py`, `tools\world_census.py`; [world.md](world.md), [world_census.md](world_census.md) | +| Navmeshes | `navmeshes.rpf`: 90,295 zlib streams (6,540,238,392 stored / 20,551,068,624 inflated), 97.5% readable; 9,603 `0DRP` pages and 27,644 `0x00010015` pages, no `NAVM`/`CNavMesh`/`NVMS` magic. `0DRP` is generic RPF paging, not a navmesh container. | `tools\navmesh_index.py`; [navmesh.md](navmesh.md) | +| BVH | `core_bvh4.rpf`: 565,596 streams, 271,627 complete BVH4 streams + 10 eight-MiB split continuations, 269,106 instance records. Header `0x81020006` at +0x100, 64-byte node units, 208-byte instances with a 3x4 transform; prebuilt acceleration data, not source meshes or shaders. | `tools\bvh_index.py`; [bvh.md](bvh.md) | +| RBF0 | 1,263 `data.rpf` resources, 475,461 elements, 44,887 descriptors and 340,859 strings. Inline record stream with no section table; UI/Scaleform (`rage__fwui*`, screens, subtitles, settings). The `anim.rpf` tail uses the same format (`rage__crRigSetManager`). `tools/rbf0_tree.py` decodes every resource to a strict JSON/CSV/XML element, value and text tree. | `tools\rbf0_index.py`, `tools\rbf0_tree.py`; [rbf0.md](rbf0.md) | +| Gamedata | `common.rpf`: 954 streams (5,647,255 stored / 50,231,123 inflated), 85.5% readable; 266 XML documents / 118 roots (time/weather, vehicles/handling, peds/schedules, tuning, manifests, world/navigation). No RBF0/PSIN. | `tools\gamedata_index.py`; [gamedata.md](gamedata.md) | +| PSIN | `script.rpf`: 671 streams start with `PSIN`, 670 complete; sections `LSCH`, `LENM`, `LSNS`, `LGID`, `LRSC`, `CHKS`. `data.rpf`: 2,281 streams, 1,045 complete after joining. `LSNS` is high-entropy; no plaintext scripts or names. | `tools/psin_index.py`; [psin.md](psin.md) | +| Audio config | `audio.rpf` first 19.5 MiB: 837 zlib streams / 54,143,493 inflated bytes. 1,589 music records, 1,589 distinct ids, exact milliseconds; `hash & 0x1fffffff` is the AWC stream id. 1,584/1,589 durations match the AWC manifest / 2; no per-track start offsets. | `tools/audio_config.py`; [audio_config.md](audio_config.md) | +| Page directory | `0DRP`: fixed 0x60-byte header, version 122; `q38` at +0x38 gives 16-byte records `{u32 hash, u32 size, u64 0x50000000 + target}`. `data.rpf`: 15,768 pages / 60,880 records; targets tile with zero overlaps. Names still need the TOC. | `tools/page_index.py`; [page_directory.md](page_directory.md) | +| Story / minigame | `story000.rpf` (18.65 GiB) is mixed: 264 Bink 2 streams (3.33 GB), 225,281 raw `RSC8` headers (v8001), 442 nested RPF9 headers and zlib resource pages. `story000_script.rpf` is 2,309 PSIN streams (2,118 complete), not a named script container; `shared_minigame000` mixes pages, PSIN and XML. | `tools/story_index.py`; [story.md](story.md) | +| Rest-of-world / script | Six archives, 1.57 GB total: `core_restofworld` 1.21 GB (11 Bink 2 streams / 1.24 GB, 37 decoded models, 958 graphics pages, 6 PSIN), `story000_restofworld` 189 MB, `story000_script` 74 MB (2,309 PSIN, 2,118 complete), small `appdata0`/licences. No maps; no validated script container. | `tools/restofworld_index.py`; [restofworld.md](restofworld.md) | +| Audio stations | Audio config `0x762160`: 19 station blocks of `{station hash, u32 boundary, ordered u32 content ids}`; the boundary is a byte offset, not a count. VCRR content ids `0x28F2-0x2941` map exactly to records `0xBD73-0xBDC2` (80/80); other clusters are context-dependent or shared. No per-track start offsets. | [radio_stations.md](radio_stations.md) | +| D3D12 command objects | Measured command queue / command list / fence / `PresentX` surface, split into verified exports and slots, prior-art claims, and open questions. Queue/list/fence creation and barriers are scoped; `PresentX` signature/slot and exact swapchain/plane parameters remain open until the executable is available. | [d3d12_command_objects.md](d3d12_command_objects.md) | + +### rpf9dump (bulk export) + +`tools\rpf9dump` is a small CLI over the Core library from https://github.com/breadbbbb/rpf9-explorer (a friend's tool; source at `third_party\rpf9-explorer`, audited: no keys, no network, no custom build targets). It decrypts nothing. It carves validated resources, as `rpf9_carve.py` does, but with working model and texture decoders. + +``` +dotnet build tools\rpf9dump\rpf9dump.csproj -c Release -o \tools\rpf9dump +rpf9dump models|textures \assets +rpf9dump ttpf \assets\ttpf +rpf9dump audio \assets +python -I make_game.py --stages assets # everything, in order; skips what is done +``` + +Full-scan indexes are also saved to `%LOCALAPPDATA%\RpfPreview\Indexes`, so the rpf9-explorer GUI opens these archives with complete listings instead of its 16 MiB preview scan. + +## Other prepared pieces + +- `tools\shader_profile.py`: across the corpus there are 551 distinct RDNA mnemonics, and 204 of them cover 99% of + all instructions (`\shaders\profile.json`). +- `tools\shader_ir.py`: parses every disassembled instruction into opcode, typed operands (s/v registers and + ranges, NSA register lists, constants, literals, export targets, interpolation attributes), modifiers and + encoding bytes. On 1,000 shaders, 12 of 2.2M operands were left untyped before the last fix. This is the front end + for an RDNA→SPIR-V translator. +- `tools\rtti_scan.py`: MSVC x64 RTTI scanner (class names, bases, vtables). Tested on the bundled DLLs; run it on + the exe first. +- `tools\hashdict.py`: joaat hash→name dictionary (`\hashes.json`, 1.9M entries, checked against + `adder` = 0xB779A091). On day one, rerun with `--extra ` so PSO field and type names resolve. Without the exe + only about 1% do. +- Runtime shims: all of `xmem.dll` is shimmed with the measured argument shapes (`XMemAlloc`, `XMemFree`, + `XMemVirtualQuery(process, address, out64)`, `XMemGetWorkingSetStatistics(out)`). The `d3d12_xs` root-signature + serializer forwards to the PC `d3d12.dll` after clearing the Xbox flag byte; the deserializer forwards unchanged. + `D3D12XboxCreateDevice` returns an Xbox-ABI proxy over the PC device: every PC vtable slot is forwarded with + `this` adjusted, Xbox slot 62 is `CreateComputePipelineState`, and Xbox slot 76 maps resource creation to + `CreateCommittedResource` with the Xbox `0x101`/`0x1` layout word replaced by the PC layout. Slots 9/10 are + `ID3D12DescriptorHeap` methods, not device methods. The PC heap getters take a hidden return pointer (RDX), + while Xbox expects the 8-byte handle in RAX, so slot 14 wraps the heap and slots 9/10 convert it. The heap holds + a reference to the device proxy and its `GetDevice` returns that same proxy. Queues, fences, command lists and + `PresentX` extensions remain unimplemented. +- PSO metadata is a new variant (`PSIN`, `LSCH` schema, `LENM`, `LSNS`, `LGID`, `LRSC`, `CHKS`, little-endian). + CodeWalker's parser reads the container but not the new schema; dump it once the exe gives the field names. + +## Shader translation (RDNA → SPIR-V) + +`tools\rdna2spirv.py` (needs `spirv-as`/`spirv-val` on PATH: Vulkan SDK, or `spirv-tools` in WSL) translates parsed RDNA +code to SPIR-V assembly, assembles it with `spirv-as`, and validates it with `spirv-val` (Vulkan 1.2). It runs one +lane per invocation and keeps VGPRs and SGPRs as uint arrays with exact bit patterns. Version 0 treated EXEC as +all-ones and covered only branch-free vertex and pixel shaders with no memory loads: common float and integer ALU +ops and exports to `gl_Position`, params and MRTs. Unsupported instructions are reported by name, never guessed. +In that version, `VS_Passthrough` and `VS_BlurFilter` translated and validated. Coverage across the corpus +and the blocking instructions are in `\shaders\spirv_run.log`; the former next steps, structured branches +(EXEC masks) and the descriptor/binding model for `s_load`, `s_buffer_load`, `buffer_*` and `image_*`, are now +implemented. Current coverage is in *Translator status* below. + +Also handled: 64-bit scalar moves, per-invocation EXEC reads, whole-quad mode on EXEC, `m0`, SCC, vector and scalar +compares, `v_mul_hi_u32`, `v_cvt_pkrtz_f16_f32` (now exact round-toward-zero; the earlier round-to-nearest version +could overflow to inf), and pixel interpolation (`v_interp_p1/p2/mov` become fragment inputs at their attribute's +location). The float MODE register (`s_setreg`) is skipped, so Vulkan's default denormal and rounding behaviour applies. + +### GPU tests (RTX 4060 Ti) + +`runtime\test\vk_harness.cpp` (build: `runtime\build\test\build_harness.cmd`, MSVC + the Vulkan 1.4 headers from +Hookshot's CPM cache, loading `vulkan-1.dll` at runtime) draws one triangle with a given VS + FS into an RGBA32F +target and dumps the floats. Test shaders are in `\gputest`. + +- **`VS_Passthrough` (translated) is bit-exact.** All 64×64 pixels are written, and `param0.xy` = (u, 1 − v) with max + error **0**, with zw = (0, 1) as exported. This covers the VertexIndex input, integer/float ALU, inline constants, + and position/param exports. +- **400 arithmetic-only translated pixel shaders** (no buffers, descriptors or subgroup ops), driven by a generic + full-screen VS feeding locations 0–15: the driver compiled every pipeline, every draw completed, and every output + was finite. This is a stability check, not a value check (there's no reference for these). +- **Texture path is exact** (`runtime\test\vk_texture_test.cpp`): translated `PS_PassthroughCopy` gives max error + **0.0** over all 64×64 pixels against the expected nearest-sampled 8×8 test texture. That covers push-constant + user data, a heap-relative `s_load_dwordx8` of the T#, the hash-table lookup of the T# and of the shader's + literal S#, bindless sampling, `v_interp`, and the f16 compressed export. **It also caught a translator bug** + that validation can't: compressed exports read the wrong register pair (LLVM prints `v4, v4, v5, v5`), giving + (r,g,r,g). That's fixed. +- After the export fix, 2 of the 400 smoke-test shaders (`PS_ImposterShadow` variants) gave non-finite red values. + The cause was round-to-nearest `pkrtz` overflowing to inf, fixed with exact RTZ. One variant is now fully finite. + The other still has 1 inf and 4 NaN in red, and RTZ can't create those from finite values, so they come from the + shader's own maths on the synthetic test inputs (hardware would pass them through too). That's consistent with + hardware, but unconfirmed without a reference. + +### Translator status and runtime contract + +Full corpus (verified pixel-shader inputs incl. front face, ACO-confirmed 16-bit semantics, `vcc_hi` as an SGPR, +code-embedded data via `s_getpc_b64`, global memory, exact packed-f16 modifiers): **All 26,503 shaders translate and pass `spirv-val`** (Vulkan 1.2 target, `--allow-offset-texture-operand`): 2,236 VS, 12,101 PS, 2,689 CS, 9,282 mesh, 195 geometry. `spirv/index.json` lists each one's requirements. Output: +`\shaders\spirv\` (`.spvasm` + `.spv`), and the log is `\shaders\spirv_run.log`. + +How the generated SPIR-V expects the runtime to work: + +| Piece | Contract | +|---|---| +| Execution model | One invocation = one lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). | +| EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. A pixel lane still inactive at the end is discarded. | +| Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. | +| User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. | +| Xbox GPU addresses | Shaders build Xbox GPU virtual addresses, and some force the high dword to 0 (descriptor tables in the low 4 GB). Every memory access goes to **heap base + Xbox VA**, so the runtime maps the console's GPU address window into one host buffer-device-address allocation. | +| Code-embedded data | 155 VS/PS had "undecodable words". They're **constant tables inside the code range** (float values like 0x3EF7…, plus zeros), read through `s_getpc_b64` + `s_add_u32`/`s_addc_u32` + `s_load` (147 of 155). The translator re-anchors each instruction to its true FSSM offset by matching encodings, translates only code reachable from entry (a branch into data is rejected), and turns `s_getpc_b64` into code base + next-instruction offset. **The runtime uploads each shader's FSSM blob into the heap and passes that VA as the code base.** Re-anchoring compares bytes exactly, except that VOP3P `op_sel_hi[2]` (bit 14) is ignored on two-source packed ops: the compiler stores 0 there, and LLVM prints its default of 1. Data words that decode with ignored fields set are printed re-encoded (e.g. `0xbe8d2242` as `s_rfe_b64` `0xbe802242`), so they can never match. Since the decoder consumed the same length, they are anchored in sequence and marked. A shader that can *reach* a marked word is rejected; none of the corpus does. All 155 now translate. | +| Global memory | `global_load/store_dword*`: address = (64-bit SGPR base + zero-extended 32-bit VGPR offset, or a 64-bit VGPR address) + signed 12-bit offset, translated through the heap base. Inactive lanes don't access memory, and loads merge their previous values with OpPhi. | +| Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. | +| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). The base comes from the 64-bit SGPR pointer or the V# (dword0 \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`): the address is base + sOFF + IMM + 4·i for dword i. Measured on AMD Radeon RX 6800 (gfx1030) by running the instructions as a raw compute kernel: soffset 8 + imm 4 reads +12 (`s_buffer_load_dword`, `x2`, `x4`, `x8`); `s_load_dword*` with both offsets wasn't measured and gets the same rule because it shares the SMEM encoding. The translator used to drop the immediate of that form. The translator's arithmetic is checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemSoffsetImmTranslatorTests`); a GPU test, `runtime/test/shaders/cs_smem_soffset_imm.asm`, is in `check.py` and `scripts/run_gpu_tests.py`. Known remaining differences, from the same measurement of `s_buffer_load*`: the hardware truncates base, sOFF and IMM each to a multiple of 4 and returns 0 past NUM_RECORDS; the translator does neither yet. See *Buffer bounds checking* below for the MUBUF `num_records` checks. | +| Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1/2/4, f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×4, uint8 ×4, unorm16 ×1/2/4, snorm16 ×2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. DST_SEL swizzle is applied. | +| Images and samplers | `image_sample_l` on 2D arrays used to read its LOD from the array layer; it now reads the LOD after all coordinates. `image_get_lod` and `image_gather4_lz` also work on 2D arrays. | +| Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. | +| Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, pad`. The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. | +| Vertex fetch | `s_swappc_b64` at the start of a VS calls a driver-generated fetch program that isn't in the blob. It's replaced by Vulkan vertex inputs: each `ISG1` input-signature element (DXBC container) becomes an input at **location = its D3D input register**, typed by its component type, and is written to **v(4 + 4·register + component)**. That rule was checked over all 788 fetch-calling shaders: in 783 every read-before-write VGPR is predicted by it (715 exact). Reads of components the element doesn't declare (e.g. `.w` of an `xyz` position, 3 VS) are allowed: the fetch returns the format defaults (0, 0, 1), and Vulkan fills a `vec4` input from a narrower format the same way. Inputs are declared as `vec4`. **The runtime must bind vertex buffers by the game's D3D12 input layout, location = input register.** | +| PS system inputs | v0–v1 = barycentrics (consumed by `v_interp`, which becomes attribute inputs). **v2.. = the `SV_Position` components the shader reads, packed in order**. Verified on 2,531 of 3,000 PS: the VGPRs they read before writing equal exactly the position components their input signature reads. Filled from `FragCoord`: xy/z directly, and **w directly too**, because AMD's position-w register holds 1/w (Mesa lowers `load_frag_coord_w_rcp` straight to `frag_pos[3]`, `ac_nir_lower_intrinsics_to_args.c`), the same as Vulkan's `FragCoord.w`. **Front face** follows the used position components when the signature declares `SV_IsFrontFace`, as ±1.0 (Mesa: `load_front_face` = `front_face > 0`). Only enabled inputs are packed, in hardware order (Mesa `radv_shader_args.c`: barycentric pairs, POS_X/Y/Z/W, FRONT_FACE, ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT). That explains the earlier "unverified" shaders: 102 read pos.xy + front face, and 76 read pos.x/y/w + front face. **Raw barycentric reads** (321 PS, e.g. `v_readfirstlane_b32 s41, v1`): AMD interpolates P = P0 + i(P1 − P0) + j(P2 − P0), so i/j are the weights of vertices 1/2, which is `BaryCoordKHR.y`/`.z` (`VK_KHR_fragment_shader_barycentric`). GPU-checked with `runtime/test/shaders/ps_bary.asm`: raw i/j equal the interpolated weights on every pixel. This assumes the pair is perspective-center, the only pair this layout models. A PS that reads any other unexplained register inside the system-input range is still rejected (none left in the corpus). Reads past the last hardware input are values undefined on some path, so zero stands in for them. All register arrays start at zero, so translated shaders are deterministic. | +| Inputs and outputs | VS: `v0` = `VertexIndex` (**unverified**: if the console runs vertex shaders as NGG, the input VGPR layout differs). `exp pos0` → `Position`, `exp pos1..pos3` → `ClipDistance` / `CullDistance` (and `Layer`/`ViewportIndex` in VS when `pos1` is the misc vector), `exp paramN` → location N. RDNA2/GFX10 packs clip distances before cull distances contiguously across 4-component `pos` exports (up to 8 floats total), starting at `pos2` when a misc vector (`PointSize`, `EdgeFlag`, `ShadingRate`, `Layer`, `ViewportIndex`; GFX9+ packs `Layer` in `z[10:0]` and `ViewportIndex` in `z[19:16]`) occupies `pos1`, and at `pos1` otherwise (Mesa `src/amd/common/nir/ac_nir_prerast_utils.c`: `ac_nir_export_position`; AMD LLPC `lgc/lowering/LowerInOut.cpp`: `LowerInOut::visitReturnInst`). Slot assignment follows the DXBC `OSG1` signature (`SV_ClipDistance` = 2, `SV_CullDistance` = 3, `SV_RenderTargetArrayIndex` = 4, `SV_ViewportArrayIndex` = 5, `SV_ShadingRate` = 23), ordered by `(semantic_index, register, component)` with clip before cull; when `OSG1` is absent (or declares none of those system values), `pos1..pos3` exports are discarded. PS: `v_interp_*` attribute N → input location N. `exp mrtN` → location N, `exp mrtz` x → `FragDepth`. | +| 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/mul/max/min_f16`, `v_fmac_f16`, `v_cvt_f16_f32`, f16 unary) and **opsel-capable VOP3 ops** (`v_fma_f16`, `_e64` forms of the 16-bit integer ops) are **partial writes that keep the high half**. The **VOP2 (`_e32`) 16-bit integer ops** (`v_lshrrev_b16`…) define the whole register, so the high half is modelled as zero. An op_sel destination bit writes the high half. The translator used to clear the high half on f16 ops; that's fixed. **op_sel on f16 VOP3 ops** (`v_fma_f16`, `v_med3_f16`, `v_add/sub/mul/max/min_f16`, f16 unary, `v_fmac_f16`): bit i (i < number of sources) reads the high half of source i, the last bit writes the high half of the destination; neg/abs apply to the selected half. Source: Mesa ACO `can_use_opsel` and the RDNA2 ISA VOP3 `OP_SEL` field. Checked by the structural tests in `tests/test_f16_op_sel.py` (which half is read, where the result goes); **not yet GPU-verified**. | +| POPS | Primitive-ordered pixel shading (10 PS, `src_pops_exiting_wave_id` wait loop, `s_sleep`, `MSG_ORDERED_PS_DONE`) becomes **fragment-shader interlock** (`PixelInterlockOrderedEXT`). It begins at the end of the entry block and ends at shader exit: a longer critical section with the same ordering. `src_pops_exiting_wave_id` reads 0, and **the runtime must put 0 (no collision, bit 31 clear) in the POPS collision SGPR**, so the hardware wait loop is skipped. Needs `VK_EXT_fragment_shader_interlock` (`fragmentShaderPixelInterlock`). | +| Texel offsets | `image_sample*_o`: the first address dword packs signed 6-bit offsets (x [5:0], y [13:8], z [21:16]), which become the SPIR-V `Offset` operand. A non-constant `Offset` outside gather needs **`VK_KHR_maintenance8`**, and is validated with `spirv-val --allow-offset-texture-operand`. Not yet GPU-tested. | +| Optional device features | Shaders may need `fragmentShaderBarycentric`, `fragmentShaderPixelInterlock` and `maintenance8`. All three are present on an RTX 4060 Ti, and `runtime/test/vk_harness.cpp` enables them when available. | +| Wave size | **Most of the game's shaders are wave64: 21,545 of 26,503.** An earlier marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks) counted 9,930 of 12,101 PS, 8,666 of 9,282 mesh shaders, 1,115 of 2,236 VS and 923 of 2,689 CS. 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; the game reads it with `v_readfirstlane_b32 s2, v5` and shifts it right by 7 to get the group index (NumThreads is 128 in the corpus), as TomBox's mesh ABI does too (`gid.x * numThreads + gi`). Not hardware-verified; 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. 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+`. 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. | +| Geometry shaders | All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. 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. | +| SCC from scalar ALU | `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32` and `s_lshl/lshr_b32` set SCC = result ≠ 0, `s_add/sub_i32` and `s_addk_i32` set it to signed overflow, `s_min_u32`/`s_max_u32` to S0 < S1 / S0 > S1. **Before this fix these ops left SCC unchanged**, so a following `s_cbranch_scc*` read a stale flag. 32-bit scalar shifts now mask the amount to 5 bits. GPU-checked with `runtime/test/shaders/ps_scc.asm`. | +| Far branches | `s_getpc_b64; s_add_u32 K; s_addc_u32 0/−1; s_setpc_b64` on the same pair is a branch beyond `s_branch`'s ±32K-dword range. It's folded into one branch to (address after `s_getpc`) + K before CFG construction. | +| Buffer format stores | `buffer_store_format_*` and `_d16_*` encode every format the loads decode (the same FORMATS table: f32/u32, f16, unorm/snorm 8/16/10-10-10-2, uint 8/16). 1–2-byte elements are merged into their dword with atomic and/or so neighbours are kept. d16 data is unpacked first (f16 → float for float kinds, 16-bit integers for integer kinds). Before this, only four f32 formats, rgba16f and rgba8 unorm were stored, and everything else silently stored nothing. GPU-checked with `runtime/test/shaders/cs_store.asm` (rgba8 unorm, 10:10:10:2, two r16f halves of one dword, d16 rgba16f: exact, neighbours untouched). `buffer_load_format_d16_*` packs pairs the same way. | +| Other additions | `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at mip round(LOD) in gather order, coordinates clamped to the edge (**approximation**: the sampler's wrap/mirror isn't reproduced at the border). `image_gather4_lz_o`: `OpImageGather … Offset`. `image_store` on 1D (bindings 17–19, `Image1D`) and with a16 coordinates. `ds_swizzle BITMASK_PERM` ("pippi" masks; GPU-checked). `v_add_f64`, `v_cvt_f32_f64` (`Float64`). `v_mul/mad_i32_i24`, `v_alignbyte_b32`, `v_xnor_b32`, `v_ffbh_i32`, `v_swap_b32`, `s_abs_i32`, `s_bfm_b32/b64`, 64-bit ordered and `v_cmpx` compares, 16-bit compares, 8/16-bit global loads, `neg(…)` constant operands (GPU-checked where listed in `runtime/test/shaders`). | +| Ray tracing | `image_bvh_intersect_ray` / `image_bvh64_intersect_ray` (64 CS: RT shadows) are one traversal step against AMD's hardware BVH node format. The traversal loop lives in the game's shader. The step is emulated over buffer reads following Mesa RADV's software path (`radv_nir_rt_common.c`, `intersect_ray_amd_software_box/_tri`; node layouts from `bvh_defines.h`). Node id = address >> 3 \| type (0–3 triangle, 4 box16, 5 box32). Box nodes give the four child ids, with misses and NaN boxes = `0xFFFFFFFF`, sorted by entry distance when descriptor bit 63 (box_sort_enable) is set. Triangle nodes use the watertight test with RADV's shared edge/vertex tie-breaks and give (t/\|det\|, sign(det), v/\|det\|, w/\|det\|), or (inf, 1, 0, 0) on a miss. The game's code divides by `.y` exactly as for the hardware's numerator/denominator. Address = descriptor base + ((node & ~7) << 3), base = descriptor bits [39:0] in 256-byte units (**assumption**: RADV only uses base 0). **The runtime must build the game's acceleration structures in this AMD node format** (RADV's GPU BVH builder produces it) wherever the game's D3D12 calls build them. Far branches with `s_sub_u32`/`s_subb_u32` (backward) are folded too. GPU-checked with `runtime/test/shaders/cs_bvh.asm`: sorted box children and the triangle result are exact. | +| Coverage | Every shader in the corpus translates. The remaining fidelity gap is wave64 cross-half code on 32-wide subgroups in VS/PS/GS; compute and mesh shaders are exact there with `--wave64-emulate` (see the wave-size and wave64 rows). | +| Flat pixel inputs | A pixel input location read only by `v_interp_mov_f32` is declared `Flat`. Locations read with `v_interp_p1/p2` remain interpolated. The `ps_flat` GPU test passes integer IDs through the first vertex alongside interpolated UVs. | +| Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. | +| Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. Instructions that explicitly fuse multiply-add still emit `Fma`. | +| Wave64 handling | Wave size is detected per shader from the code (64-bit EXEC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`; mesh shaders are always wave64). The hardware lane is exact in compute and mesh shaders (LocalInvocationIndex mod 64 or 32) and is used by `v_mbcnt` and EXEC writes. In other stages it's the subgroup lane. Constant EXEC writes (`s_mov_b32 exec_lo/exec_hi, K`) set each lane from its own bit of K; before, any non-zero constant turned every lane on. A register written to `exec_hi` sets lanes 32–63 only. GPU-checked with `runtime/test/shaders/cs_exec64.asm`: lanes 16–47 enabled from two constants, exact on a 32-wide-subgroup GPU. Still approximate on 32-wide subgroups: cross-lane ops between the two halves of a wave64 (readlane/permlane/DPP/shuffles across lane 31/32, wave-wide reductions). The metadata index marks every wave64 shader so a runtime can request `requiredSubgroupSize = 64` where supported (AMD), which makes those exact too. | +| Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do; not ordered: scalar loads of memory the wave wrote, and sampling an image it wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 35/36 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 37/37 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). | +| 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, …), `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: 64-wide subgroups can only be requested for compute/mesh, so graphics wave64 stays emulated 2x32 until cross-half ops go through LDS; also true for compute/mesh translated with `--wave64-emulate`, which then carry `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none), `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, and input/output locations. A runtime can create every pipeline at load time from it without parsing SPIR-V. | +| Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. | +| Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. This was checked against what all 2,689 CS read before writing: 2,281 match exactly, and the rest overshoot only through loop-carried registers in the straight-line check. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. Shaders with TG_SIZE_EN are rejected for now. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | +| LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `d16`/`d16_hi`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. In wave64 the permute runs as two wave32s (RDNA ISA §10.4.4): each half reads lanes of its own half, and a source lane that is off in EXEC reads 0. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. | +| Compute workgroup IDs Y/Z | With four user SGPRs and only TGID_Y and TGID_Z enabled (RSRC2 `0x308`), s4 receives Y and s5 receives Z. The synthetic `cs_workgroup_yz.asm` fixture checks a 2 × 3 × 4 dispatch and each of its 24 origins against a CPU reference. | +| Typed image stores | `image_store` (2D, 2D array, 3D) writes the dmask components (missing ones = 0). The image's numeric type lives in the T# (word 1 FORMAT [28:20], 512 GFX10 formats), so it is decided at run time. A 512-bit table built from `tools/gfx10_formats.json` (30 UINT and 15 SINT formats) picks a **sint**, **uint** or **float** view (bindings 8 + 3·dim + class; dim 0 = 2D, 1 = 2D array, 2 = 3D; class 0 float, 1 uint, 2 sint). Views have Unknown format (`shaderStorageImageWriteWithoutFormat`). **The runtime binds every storage image into all three arrays of its dimension, or at least the one matching its format.** The earlier path wrote only component 0 as `r32ui`, which was wrong for every other format. GPU-checked with `runtime/test/shaders/cs_imgstore.asm` through `runtime/test/vk_store_test.cpp`: rgba8 unorm, r32 uint and r32 sint images, every texel correct. | +| Typed image loads | `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores: UINT/SINT formats are read with `OpImageRead` through the uint/sint storage views (`shaderStorageImageReadWithoutFormat`), everything else with `OpImageFetch` through the float sampled view as before. Results are the raw bits of the dmask components. **The runtime binds integer-format images into the uint/sint storage arrays of their dimension** (bindings 8–19), as for stores. Before this, every load went through the float view, which is undefined for integer formats. GPU-checked with `runtime/test/shaders/cs_imgload.asm` (r32 uint read back exactly). | +| SDWA | `_sdwa` forms: each source is narrowed to `src0_sel`/`src1_sel` (BYTE_n/WORD_n, zero-extended, or sign-extended under `sext()`) **before** neg/abs and the op. A VGPR result goes to `dst_sel`, with `dst_unused` setting the other bits: PAD = 0, SEXT = sign copies above the field, PRESERVE = old bits kept. VOPC has no `dst_sel`, and GFX10 `v_cmpx` has no written destination. **Until 2026-11-20 the selects were silently ignored.** That affected 3,826 of the 13,926 translated shaders: they passed `spirv-val` but computed wrong values. GPU-checked with `runtime/test/shaders/ps_sdwa.asm` and `ps_ops.asm` (also `v_pk_fma_f16`, `v_min3_u32`, `v_max3_i32`, `v_bfe_i32`): byte/word source selects, `sext()`, `UNUSED_PRESERVE` into WORD_1 and `UNUSED_SEXT` at BYTE_2 all match on every pixel. | +| Byte permute | `v_perm_b32`: result byte i = BYTE_PERMUTE({src0, src1}, selector byte i), src1 = bytes 0–3 (AMD "RDNA 2" ISA reference, VOP3 opcode 836 V_PERM_B32, `byte_permute` pseudocode, page 189 of the PDF). Selector 0–7 picks that byte; **8, 9, 10, 11 give 0xff if bit 7 of byte 1, 3, 5, 7 is set, else 0x00**; 12 gives 0x00; 13 and above give 0xff. **Until 2026-11-21 selectors 8–11 gave 0x00 regardless of the sign bit**. How many corpus shaders use selectors 8–11 is not counted yet. GPU-checked with `runtime/test/shaders/ps_ops7.asm` (also `v_alignbit_b32` with a shift of 36, `v_med3_i32` vs `v_med3_u32`) and `ps_ops8.asm` (`v_mul_hi_u32/i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32` of 0, `v_xad_u32`, `v_add3_u32`), 4096/4096 pixels on an AMD Radeon iGPU (Ryzen 7 9800X3D, RDNA2, AMD driver 25.10.36) and an NVIDIA GeForce RTX 5070 (driver 621.24); before the fix `ps_ops7` gave 0x00000000 for the sign-selector word on both. Also executed by `tests/semantic/test_value_semantics.py`. | +| Float-to-int saturation | `v_cvt_u32_f32` and `v_cvt_i32_f32` truncate toward zero, saturate out-of-range values (including infinities) to the destination bounds, and return zero for NaN. The conversion operand is kept in range before emitting SPIR-V `OpConvertFToU`/`OpConvertFToS`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf), §12.8, VOP1 opcodes 7 and 8. The synthetic `cs_cvt_f32_sat.asm` fixture is checked bit-for-bit by `tests/semantic/test_float_to_int.py`. | +| Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode. The MODE register (`s_setreg`) is ignored, so denormal and rounding behaviour is Vulkan's default. Whole-quad mode on non-EXEC masks is the identity. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | +| Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2): raw buffers (`stride == 0`) check the starting byte offset (`offset < num_records`; per-dword tail bounds on multi-dword accesses aren't split yet), and structured buffers (`stride != 0`) check `index < num_records` (`idxen`) or `offset < num_records * stride`. Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0. GPU-checked with `runtime/test/shaders/cs_bounds.asm` on AMD Radeon RX 9070 XT. | +| Wave64 mask ballot | `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, and `s_bfm_b64` bitfields). `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, and `s_bitcmp0/1_b32/b64` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. Known remaining gaps: `s_cmp_eq/lg_u32` comparing opposite halves (lo vs hi) falls back to a whole-wave vote. GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py` and `tests/semantic/test_scalar_alu_shifts.py`. | +| Mesh/compute input registers (historical measurement) | An early read-before-write analysis over all compute and mesh shaders found **compute** v0 (880), v0–v1 (614), v0–v2 (50), consistent with AMD's local thread ID x/y/z in v0/v1/v2, and scalar inputs centred on a pointer at s[4:5] and s6/s7. **Mesh:** every one of 2,969 reads exactly **v5**, plus s3 (always arithmetic), s[16:17] and s19–s23. The early pass also read FSSM 0x13C as the group width and compared the first SGPR multiply against it (82 match, 151 don't, 1,447 no simple multiply) and wrongly concluded that 0x13C was not the group width; the matching register varied by shader (s6/s10/s7/s9…). PSV0 gave the real thread-group sizes (32×1×1 for 1,253, 8×8×1 for 416, …). **Superseded:** 0x13C/0x140/0x144 are the thread-group size, `COMPUTE_PGM_RSRC2` at 0x138 gives the per-shader user-SGPR count and enabled workgroup IDs, and mesh takes NumThreads, limits and topology from PSV0 with v5 as the workgroup index. All 2,689 CS and 9,282 mesh shaders translate now (see the Compute shaders and Mesh shaders rows). | +| Formerly untranslated | Mesh (9,282), geometry (195) and compute (2,689) now translate; `s_swappc_b64` is replaced by Vulkan vertex inputs (see *Vertex fetch*) and the `tbuffer_load_format_*` forms use the instruction's format. A few rare ops are still reported by name rather than guessed. | + +**Main blocker at the time (superseded): descriptor loads.** On a 3,000-shader sample, `s_load_dwordx4`/`x8` stop over half of them. Shaders +load texture, buffer and sampler descriptors through user-data SGPR pointers, and how the game's root signatures +map onto those SGPRs is set up by game code. Reading that mapping from the exe (root signature creation plus the +FSSM user-data metadata) before building the binding layer was the next step; guessing it would give silent +rendering bugs. The translator now handles those loads against the push-constant user-data contract (*User data*, +*Scalar/buffer memory* and the descriptor rows); the D3D12 layer still has to supply the root-signature mapping. +The other blockers listed then (mesh, the vertex-fetch call, geometry, compute and compressed exports) are closed +for the corpus: all 26,503 shaders translate (see *Translator status*). The remaining fidelity gap is wave64 +cross-half code on 32-wide subgroups. + +## Day one, in order + +1. `scripts\first_look.ps1 -Exe ...` checks the exe is plain, lists the imports to shim, and does a dry run. +2. Find the RPF9 table-of-contents key and decryption in the exe, then add a table reader to `rpf9_carve.py`. Carved + blobs then get real names and types, and the remaining unread data shows what it is. +3. Find the texture and mesh resource structures in the exe (their loaders give exact field layouts), which turns + carved blobs into named textures and meshes. +4. Shader translation: already complete for all 26,503 shaders (see *Translator status*); the day-one work is + validating them through the runtime. + +## Disassembling shaders + +The AMDGPU disassembler needs LLVM 21+ built with the AMDGPU target (`llvm-mc`; on Linux the `llvm-21` package +installs it at `/usr/lib/llvm-21/bin/llvm-mc`). The official Windows LLVM build has no AMDGPU target and ships no +`llvm-mc.exe`. On Windows, either build a native one or run it from WSL. + +Native: `scripts\build_llvm_mc.ps1` fetches the LLVM sources the tool needs (sparse, shallow), builds `llvm-mc` alone +with `LLVM_TARGETS_TO_BUILD=AMDGPU`, static CRT and the DIA SDK off (its headers need ATL, which the C++ build tools +don't always include), checks it disassembles an `s_endpgm` for `gfx1013`, keeps only `llvm-mc.exe` (by default in +`%LOCALAPPDATA%\Leonida\llvm-mc`) and sets `LLVM_MC` for the user. It needs git, Python and Visual Studio with the C++ +x64 tools, about 2 GB of temporary space and 20-40 minutes. `-Dest`, `-NoEnv`, `-Keep` and `-Version` change the +defaults. + +``` +powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 +python -I make_game.py --game "D:\path\to\your\package" --stages shaders +``` + +WSL: install `llvm-21` and give `LLVM_MC` the whole command: + +``` +set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc +python -I make_game.py --game "D:\path\to\your\package" --stages shaders +``` + +The same form works in every tool that reads `LLVM_MC`. `tools/mc_command.py` splits it for `shader_disasm.py`, +the tests, `runtime/test/shaders/build.py` and `scripts/run_gpu_tests.py`; the assembler callers pass the assembly +on stdin, so a WSL command never receives a Windows file path. + +`shader_disasm.py` disassembles one `s_endpgm` before starting, so a missing tool or AMDGPU target stops the run +with that reason instead of writing empty `.s` files. To disassemble by hand inside WSL: + +``` +LLVM_MC=/usr/lib/llvm-21/bin/llvm-mc python3 -I /tools/shader_disasm.py /shaders/fssm +``` + +Code starts at the u32 at FSSM offset 0xC0 (the code-section offset) plus 0x28 bytes into that section, and ends at the +last `s_endpgm`. Use `--mcpu gfx1013`. On 300 random shaders it decoded 284 cleanly (134 invalid words in total), +against 201 clean and 6,560 invalid for gfx1030 and 283 clean for gfx1010–1012. + +## Pixel-shader inputs + +`tools/fssm_header.py` decodes the FSSM input table: 8-byte records from 0x138 while the first byte is 6. +Byte 1 is the semantic id, byte 2 the component mask, byte 3 the running index, byte 6 the parameter slot, +and byte 7 holds flags (bit 4 = 16-bit interpolant). The record's position is the `v_interp attr` number. +`interpolants()` returns the count and a fp16 bitmask by position; a translator can use both, but +`rdna2spirv.py` does not yet. Measured on the 26,503-blob corpus: 25,643 satisfy +`u32[0x120] + u32[0x12C] == u32[0x130]` (the 860 that do not store 0xDEADBEEF at 0x130); 12,101 are PS, +10,307 with a non-empty table (55,791 records, 11,199 of them 16-bit). The count equals the number of +distinct `v_interp attr` numbers in 11,316/12,101 PS (93.5%); 300 more declare one unread input, 475 +declare two or more, and the 10 undercounts are one family whose first record at 0x138 has kind 7. A +200-PS spot check agreed on 187/200. Flag bit 4 matches the `*_f16` interpolation opcodes in +12,067/12,101 (99.7%). + +## Baseline already recorded + +- `reports/manifest.json`: SHA-256 of all 108 files in `Documents\GTA6` (208.5 GiB). Run + `python -I tools\manifest.py verify ` to check a copy against it. +- `reports/rpf_probe.json`: all 22 archives are **RPF9**. Five have tables that look packed or encrypted (`levels`, + `movies`, `core_bvh4`, `navmeshes`, `data`). +- `reports/pe/`: the 16 bundled DLLs are plain x86-64 PE with no encrypted sections. Through the loader their + `xmem.dll` imports and two `d3d12_xs.dll` root-signature calls bind to shims. Every other import resolves on + desktop Windows. The proxy covers the measured device slots and forwards the rest in PC vtable order; the Xbox + queue/fence/command-list extensions and `PresentX` remain unknown. From a831d1a5480169760eeb0f25b1c2f833f3351889 Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:28:11 +0100 Subject: [PATCH 03/53] Test saturated conversions in the SPIR-V interpreter --- tests/regen_fixtures.py | 54 ++++ tests/spirv_mini_interp.py | 540 +++++++++++++++++++++++++++++++++++++ tests/test_float_to_int.py | 44 +++ 3 files changed, 638 insertions(+) create mode 100644 tests/regen_fixtures.py create mode 100644 tests/spirv_mini_interp.py create mode 100644 tests/test_float_to_int.py diff --git a/tests/regen_fixtures.py b/tests/regen_fixtures.py new file mode 100644 index 000000000..50faab5a8 --- /dev/null +++ b/tests/regen_fixtures.py @@ -0,0 +1,54 @@ +"""Regenerate (or check) the translator input fixtures in tests/semantic/fixtures/disasm/ from the hand-written assembly +sources in runtime/test/shaders/. + + python tests/semantic/regen_fixtures.py # rewrite the fixtures + python tests/semantic/regen_fixtures.py --check # exit 1 if a fixture differs from what would be generated + +The translator (tools/rdna2spirv.py) reads one instruction per tab-indented line and skips the first line. For +straight-line code it does not need the `; encoding:` comments, so a fixture is the .asm instruction text, +unchanged, under a one-line header. No assembler is involved, which keeps the tests free of any LLVM version. +(The .asm syntax itself was written for `llvm-mc -mcpu=gfx1013`; see the comment at the top of each file.) +""" +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +ASM_DIR = os.path.join(ROOT, "runtime", "test", "shaders") +FIXTURE_DIR = os.path.join(HERE, "fixtures", "disasm") +SHADERS = ("ps_sdwa", "ps_ops", "ps_ops2", "ps_ops3", "ps_ops4", "ps_ops5", "ps_ops6", "ps_ops7", "ps_ops8", "ps_legacy_mul", + "ps_vcc_x2", "ps_flat", "cs_bounds", "cs_cvt_f32_sat") + + +def render(name): + """Fixture text for one shader: header line, then each instruction line indented with a tab.""" + with open(os.path.join(ASM_DIR, name + ".asm"), encoding="utf-8") as f: + insns = [ln.strip() for ln in f.read().splitlines() if ln.strip() and not ln.lstrip().startswith(";")] + head = f"; {name} test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/{name}.asm\n" + return head + "".join("\t" + ln + "\n" for ln in insns) + + +def main(argv): + check = "--check" in argv + bad = 0 + for name in SHADERS: + path = os.path.join(FIXTURE_DIR, name + ".s") + want = render(name) + if check: + have = "" + if os.path.isfile(path): + with open(path, encoding="utf-8", newline="") as f: + have = f.read().replace("\r\n", "\n") + if have != want: + print(f"{name}: fixture is stale or missing") + bad += 1 + else: + os.makedirs(FIXTURE_DIR, exist_ok=True) + with open(path, "w", encoding="utf-8", newline="\n") as f: + f.write(want) + print(f"wrote {os.path.relpath(path, ROOT)}") + return 1 if bad else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tests/spirv_mini_interp.py b/tests/spirv_mini_interp.py new file mode 100644 index 000000000..377d41449 --- /dev/null +++ b/tests/spirv_mini_interp.py @@ -0,0 +1,540 @@ +"""A deliberately tiny interpreter for the SPIR-V assembly that tools/rdna2spirv.py emits for branch-free pixel +shaders and simple structured compute shaders. It exists so tests can check *computed values*, not just that the +module validates. + +Design rules (see tests/semantic/README.md): + * Written from the SPIR-V and GLSL.std.450 specifications. It shares no code with the translator. + * Strict: any opcode, extended instruction, type or storage class not listed below raises + UnsupportedConstruct. Nothing is skipped or approximated silently, so a translator change that starts + emitting something new makes the test error out instead of passing. + * One invocation (one lane). Control flow is the forward-only discard test and the forward merge/dynamic-bounds + branches the translator emits: OpBranch / OpBranchConditional to a later label plus OpPhi at the merge block. + Backward branches, loops, calls and switches are rejected. Function/Output/Input variables live in Python + boxes; PushConstant reads can be seeded with a word list; physical-storage-buffer loads/stores use a flat + address -> word dictionary. Workgroup storage and images are rejected. + * A default run sees zero push constants, no inputs and empty memory, so tests that do not care about them + keep the old behaviour. + +Values: uint/int are Python ints in [0, 2**32) or [0, 2**64) for 64-bit types (signedness is applied by the +operation, as in SPIR-V); float is a Python float rounded to binary32; vectors are tuples; arrays are lists; +bool is bool. +""" +import math +import re +import struct + +MASK = 0xFFFFFFFF + + +class UnsupportedConstruct(NotImplementedError): + """The module uses something this interpreter deliberately does not model.""" + + +# Instructions that carry no runtime semantics for a single-entry-point, straight-line module. +_IGNORED = frozenset({ + "OpCapability", "OpExtension", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", "OpExecutionMode", + "OpDecorate", "OpMemberDecorate", "OpTypeVoid", "OpTypeFunction", "OpLabel", "OpSelectionMerge", + "OpReturn", "OpFunctionEnd", "OpName", "OpSource", +}) + +_LINE = re.compile(r"^(?:(%\S+)\s*=\s*)?(Op\w+)\s*(.*)$") + + +def f32(x): + """Round a Python float to binary32 (overflow to infinity).""" + try: + return struct.unpack(" 0 else float("-inf") + + +def f32_bits(x): + try: + return struct.unpack(" 0 else 0xFF800000 + + +def bits_f32(b): + return struct.unpack(" 0 else 0xFC00 + + +def _s32(x): + x &= MASK + return x - (1 << 32) if x >> 31 else x + + +class _Types: + def __init__(self): + self.t = {} + + def zero(self, name): + k = self.t[name] + if k[0] == "int": + return 0 + if k[0] == "float": + return 0.0 + if k[0] == "bool": + return False + if k[0] == "vec": + return tuple(self.zero(k[1]) for _ in range(k[2])) + if k[0] == "arr": + return [self.zero(k[1]) for _ in range(k[2])] + raise UnsupportedConstruct(f"zero value of type {name} ({k[0]})") + + def size(self, name): + """Byte size of a concrete type. Runtime arrays have no size of their own; the element size is used.""" + k = self.t[name] + if k[0] in ("int", "float"): + return 4 + if k[0] == "vec": + return 4 * k[2] + if k[0] == "arr": + return self.size(k[1]) * k[2] + if k[0] == "rarr": + return self.size(k[1]) + if k[0] == "struct": + return sum(self.size(t) for t in k[1]) + raise UnsupportedConstruct(f"size of type {name} ({k[0]})") + + def bits(self, name): + k = self.t[name] + if k[0] != "int": + raise UnsupportedConstruct(f"integer width of type {name} ({k[0]})") + return k[1] + + +def run_fragment(text, inputs=None, push_constants=None, memory=None): + """Execute the entry point of `text` once and return the words written to every Output variable. + + `inputs` maps an Input variable name (for example "%in_attr1") to its value (a tuple for vectors). + `push_constants` is a list of 32-bit words at byte offsets 0, 4, 8, ... of the PushConstant block + (missing words read as zero). `memory` is a mutable {byte_address: word} mapping used for + PhysicalStorageBuffer loads and stores. + + Returns {output_variable_name: tuple_of_32bit_words}. Float outputs are returned as their bit patterns. + """ + inputs = inputs or {} + push_constants = list(push_constants or []) + memory = {} if memory is None else memory + types = _Types() + values = {} # id -> value (constants and results) + constants = {} # id -> value, kept apart so zero-initialised arrays can be built + ptr_types = {} # pointer type id -> (storage class, pointee type id) + var_class = {} # variable id -> storage class + var_box = {} # variable id -> [value] + pointers = {} # id -> (container list, index) / ("pc", offset) / ("psb", address) + pc_type = {} # id -> pointee type id of a PushConstant pointer + in_body = False + body = [] + outputs = [] + + def val(x): + if x in values: + return values[x] + raise UnsupportedConstruct(f"use of undefined id {x}") + + def walk(type_id, indices): + """Byte offset and element type after selecting `indices` in an aggregate type.""" + off, cur = 0, type_id + for idx in indices: + k = types.t[cur] + if k[0] == "struct": + for m in range(idx): + off += types.size(k[1][m]) + cur = k[1][idx] + elif k[0] in ("arr", "rarr", "vec"): + off += types.size(k[1]) * idx + cur = k[1] + else: + raise UnsupportedConstruct(f"OpAccessChain into {k[0]}") + return off, cur + + for raw in text.splitlines(): + line = raw.strip() + if not line: + continue + m = _LINE.match(line) + if not m: + raise UnsupportedConstruct(f"cannot parse line: {line!r}") + res, op, rest = m.groups() + a = rest.split() + if in_body: + body.append((res, op, a, line)) + continue + if op == "OpFunction": + in_body = True + continue + if op in _IGNORED: + continue + if op == "OpTypeInt": + bits = int(a[0]) + if bits not in (32, 64): + raise UnsupportedConstruct("integer type that is not 32 or 64 bits") + types.t[res] = ("int", bits, int(a[1])) + elif op == "OpTypeFloat": + if int(a[0]) != 32: + raise UnsupportedConstruct("non-32-bit float type") + types.t[res] = ("float",) + elif op == "OpTypeBool": + types.t[res] = ("bool",) + elif op == "OpTypeVector": + types.t[res] = ("vec", a[0], int(a[1])) + elif op == "OpTypeArray": + types.t[res] = ("arr", a[0], int(constants[a[1]])) + elif op == "OpTypeRuntimeArray": + types.t[res] = ("rarr", a[0]) + elif op == "OpTypeStruct": + types.t[res] = ("struct", a) + elif op == "OpTypePointer": + ptr_types[res] = (a[0], a[1]) + elif op == "OpConstant": + k = types.t[a[0]] + if k[0] == "float": + constants[res] = values[res] = f32(float(a[1])) + elif k[0] == "int": + constants[res] = values[res] = int(a[1]) & ((1 << k[1]) - 1) + else: + raise UnsupportedConstruct(f"OpConstant of type {k[0]}") + elif op == "OpConstantTrue": + constants[res] = values[res] = True + elif op == "OpConstantFalse": + constants[res] = values[res] = False + elif op == "OpConstantNull": + constants[res] = values[res] = types.zero(a[0]) + elif op == "OpVariable": + cls, pointee = ptr_types[a[0]] + if a[1] != cls: + raise UnsupportedConstruct("OpVariable storage class mismatch") + var_class[res] = cls + if cls == "PushConstant": + var_box[res] = [None] # reads come from push_constants, see OpLoad + pc_type[res] = pointee + elif cls == "Input": + init = inputs.get(res, types.zero(pointee)) + var_box[res] = [list(init) if isinstance(init, (list, tuple)) else init] + elif cls in ("Function", "Output"): + if len(a) > 2: + init = values[a[2]] + var_box[res] = [list(init) if isinstance(init, list) else init] + else: + var_box[res] = [types.zero(pointee)] + if cls == "Output": + outputs.append(res) + else: + raise UnsupportedConstruct(f"storage class {cls}") + pointers[res] = ("pc", 0) if cls == "PushConstant" else (var_box[res], 0) + else: + raise UnsupportedConstruct(f"{op} in module header") + if not in_body: + raise UnsupportedConstruct("no function body") + + def deref(p): + box, i = p + return box[i] + + def wmask(type_id): + return (1 << types.bits(type_id)) - 1 + + def signed(v, bits): + v &= (1 << bits) - 1 + return v - (1 << bits) if v >> (bits - 1) else v + + labels = {res: idx for idx, (res, op, _, _) in enumerate(body) if op == "OpLabel" and res} + pc = 0 + killed = False + cur_label = prev_label = None + while pc < len(body): + res, op, a, line = body[pc] + pc += 1 + if op == "OpLabel": + prev_label, cur_label = cur_label, res + continue + if op in _IGNORED: + continue + if op == "OpKill": + killed = True + break + if op == "OpBranch": + if a[0] not in labels or labels[a[0]] < pc: + raise UnsupportedConstruct("non-forward branch") + pc = labels[a[0]] + continue + if op == "OpBranchConditional": + cond = val(a[0]) + if not isinstance(cond, bool): + raise UnsupportedConstruct("OpBranchConditional with a non-bool condition") + target = a[1] if cond else a[2] + if target not in labels or labels[target] < pc: + raise UnsupportedConstruct("non-forward branch") + pc = labels[target] + continue + if op == "OpPhi": + incoming = [a[i] for i in range(1, len(a) - 1, 2) if a[i + 1] == prev_label] + if len(incoming) != 1: + raise UnsupportedConstruct("OpPhi with an unknown predecessor") + values[res] = val(incoming[0]) + continue + if op == "OpVariable": + cls, pointee = ptr_types[a[0]] + if cls != "Function": + raise UnsupportedConstruct("non-Function variable in body") + var_box[res] = [list(values[a[2]]) if len(a) > 2 and isinstance(values[a[2]], list) + else (values[a[2]] if len(a) > 2 else types.zero(pointee))] + pointers[res] = (var_box[res], 0) + elif op == "OpAccessChain": + base = a[1] + if base not in pointers: + raise UnsupportedConstruct("OpAccessChain on non-pointer") + p = pointers[base] + if p[0] == "pc": + off, cur = walk(pc_type[base], [values[i] for i in a[2:]]) + pointers[res] = ("pc", p[1] + off) + pc_type[res] = cur + var_class[res] = "PushConstant" + continue + if p[0] == "psb": + if len(a) != 3: + raise UnsupportedConstruct("multi-index physical-storage-buffer access chain") + elem = ptr_types[a[0]][1] + if types.t[elem][0] == "rarr": + stride = types.size(types.t[elem][1]) + elif types.t[elem][0] in ("int", "float", "vec"): + stride = types.size(elem) + else: + raise UnsupportedConstruct(f"physical-storage-buffer access chain into {types.t[elem][0]}") + pointers[res] = ("psb", p[1] + stride * values[a[2]]) + continue + for idx_id in a[2:]: + idx = values[idx_id] + container = deref(p) + if not isinstance(container, (list, tuple)) or not 0 <= idx < len(container): + raise UnsupportedConstruct("OpAccessChain into non-array or out of range") + p = (container, idx) + pointers[res] = p + elif op == "OpLoad": + p = pointers[a[1]] + if p[0] == "pc": + w = p[1] // 4 + values[res] = push_constants[w] if 0 <= w < len(push_constants) else 0 + elif p[0] == "psb": + values[res] = memory.get(p[1], 0) + else: + v = deref(p) + values[res] = list(v) if isinstance(v, list) else v + elif op == "OpStore": + p = pointers[a[0]] + if p[0] == "pc": + raise UnsupportedConstruct("store to PushConstant") + if p[0] == "psb": + memory[p[1]] = val(a[1]) + else: + p[0][p[1]] = val(a[1]) + elif op == "OpSelect": + if not isinstance(val(a[1]), bool): + raise UnsupportedConstruct("OpSelect with a non-scalar-bool condition") + values[res] = val(a[2]) if val(a[1]) else val(a[3]) + elif op == "OpCopyObject": + values[res] = val(a[1]) + elif op == "OpBitcast": + k, v = types.t[a[0]], val(a[1]) + if k[0] == "float" and isinstance(v, int): + values[res] = bits_f32(v) + elif k[0] == "int" and isinstance(v, float): + values[res] = f32_bits(v) + elif k[0] == "int" and isinstance(v, int): + values[res] = v & wmask(a[0]) + else: + raise UnsupportedConstruct("OpBitcast between these types") + elif op in ("OpConvertFToS", "OpConvertFToU"): + source = val(a[1]) + if not math.isfinite(source): + raise UnsupportedConstruct(f"{op} with a non-finite operand") + value = math.trunc(source) + bits = types.bits(a[0]) + lo, hi = (-(1 << (bits - 1)), (1 << (bits - 1)) - 1) if op == "OpConvertFToS" else (0, wmask(a[0])) + if not lo <= value <= hi: + raise UnsupportedConstruct(f"{op} result out of range (undefined in SPIR-V)") + values[res] = value & wmask(a[0]) + elif op == "OpCompositeExtract": + v = val(a[1]) + for i in a[2:]: + v = v[int(i)] + values[res] = v + elif op == "OpCompositeConstruct": + values[res] = tuple(val(x) for x in a[1:]) + elif op == "OpBitwiseAnd": + values[res] = (val(a[1]) & val(a[2])) & wmask(a[0]) + elif op == "OpBitwiseOr": + values[res] = (val(a[1]) | val(a[2])) & wmask(a[0]) + elif op == "OpBitwiseXor": + values[res] = (val(a[1]) ^ val(a[2])) & wmask(a[0]) + elif op == "OpNot": + values[res] = (~val(a[1])) & wmask(a[0]) + elif op == "OpShiftLeftLogical": + bits = types.bits(a[0]) + if val(a[2]) >= bits: + raise UnsupportedConstruct(f"shift amount >= {bits} (undefined in SPIR-V)") + values[res] = (val(a[1]) << val(a[2])) & wmask(a[0]) + elif op == "OpShiftRightLogical": + bits = types.bits(a[0]) + if val(a[2]) >= bits: + raise UnsupportedConstruct(f"shift amount >= {bits} (undefined in SPIR-V)") + values[res] = (val(a[1]) & wmask(a[0])) >> val(a[2]) + elif op == "OpShiftRightArithmetic": + bits = types.bits(a[0]) + if val(a[2]) >= bits: + raise UnsupportedConstruct(f"shift amount >= {bits} (undefined in SPIR-V)") + values[res] = (signed(val(a[1]), bits) >> val(a[2])) & wmask(a[0]) + elif op == "OpIAdd": + values[res] = (val(a[1]) + val(a[2])) & wmask(a[0]) + elif op == "OpISub": + values[res] = (val(a[1]) - val(a[2])) & wmask(a[0]) + elif op == "OpIMul": + values[res] = (val(a[1]) * val(a[2])) & wmask(a[0]) + elif op == "OpUConvert": + values[res] = val(a[1]) & wmask(a[0]) + elif op == "OpBitCount": + values[res] = (val(a[1]) & wmask(a[0])).bit_count() + elif op == "OpISubBorrow": + x, y = val(a[1]) & MASK, val(a[2]) & MASK + values[res] = ((x - y) & MASK, 1 if x < y else 0) + elif op in ("OpUMulExtended", "OpSMulExtended"): + # Result struct {low, high} of the full 64-bit product (SPIR-V spec, 32-bit scalars only). + x, y = val(a[1]) & MASK, val(a[2]) & MASK + if op == "OpSMulExtended": + x, y = _s32(x), _s32(y) + p = (x * y) & 0xFFFFFFFFFFFFFFFF + values[res] = (p & MASK, p >> 32) + elif op == "OpIEqual": + values[res] = val(a[1]) == val(a[2]) + elif op == "OpINotEqual": + values[res] = val(a[1]) != val(a[2]) + elif op == "OpSLessThan": + values[res] = _s32(val(a[1])) < _s32(val(a[2])) + elif op == "OpULessThan": + values[res] = val(a[1]) < val(a[2]) + elif op == "OpUGreaterThanEqual": + values[res] = val(a[1]) >= val(a[2]) + elif op == "OpLogicalAnd": + x, y = val(a[1]), val(a[2]) + if not (isinstance(x, bool) and isinstance(y, bool)): + raise UnsupportedConstruct("OpLogicalAnd on non-bool") + values[res] = x and y + elif op == "OpLogicalOr": + x, y = val(a[1]), val(a[2]) + if not (isinstance(x, bool) and isinstance(y, bool)): + raise UnsupportedConstruct("OpLogicalOr on non-bool") + values[res] = x or y + elif op == "OpLogicalNot": + values[res] = not val(a[1]) + elif op in ("OpFAdd", "OpFSub", "OpFMul"): + x, y = val(a[1]), val(a[2]) + if not (isinstance(x, float) and isinstance(y, float)): + raise UnsupportedConstruct(f"{op} on non-float") + values[res] = f32(x + y if op == "OpFAdd" else x - y if op == "OpFSub" else x * y) + elif op == "OpFNegate": + values[res] = f32(-val(a[1])) + elif op in ("OpFOrdEqual", "OpFOrdLessThan", "OpFOrdGreaterThan", "OpFOrdGreaterThanEqual", + "OpFOrdLessThanEqual", "OpFUnordNotEqual"): + x, y = val(a[1]), val(a[2]) + if not (isinstance(x, float) and isinstance(y, float)): + raise UnsupportedConstruct(f"{op} on non-float") + if op == "OpFUnordNotEqual": + values[res] = not (x == y) # true when unordered, unlike OpFOrdNotEqual + else: + values[res] = {"OpFOrdEqual": x == y, "OpFOrdLessThan": x < y, + "OpFOrdGreaterThan": x > y, "OpFOrdGreaterThanEqual": x >= y, + "OpFOrdLessThanEqual": x <= y}[op] + elif op in ("OpBitFieldUExtract", "OpBitFieldSExtract"): + base, off, cnt = val(a[1]), val(a[2]), val(a[3]) + if off + cnt > 32: + raise UnsupportedConstruct("bit-field extract beyond 32 bits (undefined in SPIR-V)") + field = (base >> off) & ((1 << cnt) - 1) + if op == "OpBitFieldSExtract" and cnt and field >> (cnt - 1): + field -= 1 << cnt + values[res] = field & MASK + elif op == "OpBitFieldInsert": + base, ins, off, cnt = (val(x) for x in a[1:5]) + if off + cnt > 32: + raise UnsupportedConstruct("bit-field insert beyond 32 bits (undefined in SPIR-V)") + mk = ((1 << cnt) - 1) << off + values[res] = ((base & ~mk) | ((ins << off) & mk)) & MASK + elif op == "OpConvertUToPtr": + values[res] = ("psb", val(a[1])) + pointers[res] = values[res] + elif op == "OpExtInst": + if len(a) < 3 or a[1] != "%glsl": + raise UnsupportedConstruct("extended instruction set") + name, args = a[2], [val(x) for x in a[3:]] + if name == "UnpackHalf2x16": + values[res] = (half_to_float(args[0]), half_to_float(args[0] >> 16)) + elif name == "PackHalf2x16": + values[res] = float_to_half(args[0][0]) | (float_to_half(args[0][1]) << 16) + elif name == "Fma": + # Exact product and sum in double, one rounding to binary32. Not a true fused operation in + # general, but exact for the f16-derived operands the tests use (see tests/semantic/README.md). + x, y, z = args + if isinstance(x, tuple): + values[res] = tuple(f32(p * q + s) for p, q, s in zip(x, y, z)) + else: + values[res] = f32(x * y + z) + elif name in ("Sin", "Cos"): + values[res] = f32(math.sin(args[0]) if name == "Sin" else math.cos(args[0])) + elif name == "FAbs": + values[res] = f32(abs(args[0])) + elif name == "UMin": + values[res] = min(args) + elif name == "UMax": + values[res] = max(args) + elif name == "SMax": + values[res] = max(args, key=_s32) + elif name == "SMin": + values[res] = min(args, key=_s32) + elif name in ("UClamp", "SClamp"): + # min(max(x, minVal), maxVal) (GLSL.std.450; undefined if minVal > maxVal, which raises here). + key = _s32 if name == "SClamp" else (lambda v: v) + x, lo, hi = args + if key(lo) > key(hi): + raise UnsupportedConstruct(f"{name} with minVal > maxVal (undefined)") + values[res] = min(max(x, lo, key=key), hi, key=key) + elif name == "FindILsb": + # Bit number of the least significant 1 bit, -1 if the value is 0 (GLSL.std.450). + x = args[0] & MASK + values[res] = (x & -x).bit_length() - 1 & MASK if x else MASK + elif name == "FindUMsb": + # Bit number of the most significant 1 bit, -1 if the value is 0 (GLSL.std.450). + x = args[0] & MASK + values[res] = x.bit_length() - 1 if x else MASK + elif name == "FindSMsb": + x = _s32(args[0]) + if x in (0, -1): + values[res] = MASK + elif x > 0: + values[res] = x.bit_length() - 1 + else: + values[res] = (~x).bit_length() - 1 + else: + raise UnsupportedConstruct(f"GLSL.std.450 {name}") + else: + raise UnsupportedConstruct(op) + + if killed: + return {} + result = {} + for name in outputs: + v = var_box[name][0] + flat = v if isinstance(v, tuple) else (v,) + result[name] = tuple(f32_bits(x) if isinstance(x, float) else x & MASK for x in flat) + return result diff --git a/tests/test_float_to_int.py b/tests/test_float_to_int.py new file mode 100644 index 000000000..99a9bd106 --- /dev/null +++ b/tests/test_float_to_int.py @@ -0,0 +1,44 @@ +"""VOP1 conversions with known binary32 inputs and integer output words.""" +import struct +import unittest + +import support + + +# Input bits, unsigned result, signed result (as an untyped 32-bit word). +CASES = ( + (0x00000000, 0, 0), # +0 + (0x80000000, 0, 0), # -0 + (0x00000001, 0, 0), # subnormal + (0x3FC00000, 1, 1), # +1.5 + (0xBFC00000, 0, 0xFFFFFFFF), # -1.5 + (0x4EFFFFFF, 0x7FFFFF80, 0x7FFFFF80), # largest binary32 below +2^31 + (0x4F000000, 0x80000000, 0x7FFFFFFF), # +2^31 + (0x4F7FFFFF, 0xFFFFFF00, 0x7FFFFFFF), # largest binary32 below +2^32 + (0x4F800000, 0xFFFFFFFF, 0x7FFFFFFF), # +2^32 + (0xCEFFFFFF, 0, 0x80000080), # -(2^31 - 128) + (0xCF000000, 0, 0x80000000), # -2^31 + (0xCF000001, 0, 0x80000000), # next binary32 below -2^31 + (0x7F800000, 0xFFFFFFFF, 0x7FFFFFFF), # +infinity + (0xFF800000, 0, 0x80000000), # -infinity + (0x7F800001, 0, 0), # first positive NaN encoding + (0xFFC00000, 0, 0), # negative quiet NaN +) + + +class FloatToIntTest(unittest.TestCase): + def test_saturating_conversions(self): + # Five user SGPRs, with s4 carrying the input after the output V#. + fssm = bytes(0x138) + struct.pack("<4I", 0x808A, 1, 1, 1) + spv = support.translate_fixture("cs_cvt_f32_sat", fssm=fssm) + for bits, unsigned, signed in CASES: + with self.subTest(bits=f"{bits:08x}"): + memory = {} + support.run_fragment( + spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, + push_constants=[0, 0, 8, 0, bits] + [0] * 27, memory=memory) + self.assertEqual(memory, {0: unsigned, 4: signed}) + + +if __name__ == "__main__": + unittest.main() From ac3bf8ae79654ada5a8b12856b38b5f4884d0dde Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:29:48 +0100 Subject: [PATCH 04/53] Document RDNA2 conversion in the translator contract --- docs/design.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/design.md b/docs/design.md index a7f9ae1ad..58762cba7 100644 --- a/docs/design.md +++ b/docs/design.md @@ -249,6 +249,7 @@ How the generated SPIR-V expects the runtime to work: | Typed image loads | `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores: UINT/SINT formats are read with `OpImageRead` through the uint/sint storage views (`shaderStorageImageReadWithoutFormat`), everything else with `OpImageFetch` through the float sampled view as before. Results are the raw bits of the dmask components. **The runtime binds integer-format images into the uint/sint storage arrays of their dimension** (bindings 8–19), as for stores. Before this, every load went through the float view, which is undefined for integer formats. GPU-checked with `runtime/test/shaders/cs_imgload.asm` (r32 uint read back exactly). | | SDWA | `_sdwa` forms: each source is narrowed to `src0_sel`/`src1_sel` (BYTE_n/WORD_n, zero-extended, or sign-extended under `sext()`) **before** neg/abs and the op. A VGPR result goes to `dst_sel`, with `dst_unused` setting the other bits: PAD = 0, SEXT = sign copies above the field, PRESERVE = old bits kept. VOPC has no `dst_sel`, and GFX10 `v_cmpx` has no written destination. **Until 2026-11-20 the selects were silently ignored.** That affected 3,826 of the 13,926 translated shaders: they passed `spirv-val` but computed wrong values. GPU-checked with `runtime/test/shaders/ps_sdwa.asm` and `ps_ops.asm` (also `v_pk_fma_f16`, `v_min3_u32`, `v_max3_i32`, `v_bfe_i32`): byte/word source selects, `sext()`, `UNUSED_PRESERVE` into WORD_1 and `UNUSED_SEXT` at BYTE_2 all match on every pixel. | | Byte permute | `v_perm_b32`: result byte i = BYTE_PERMUTE({src0, src1}, selector byte i), src1 = bytes 0–3 (AMD "RDNA 2" ISA reference, VOP3 opcode 836 V_PERM_B32, `byte_permute` pseudocode, page 189 of the PDF). Selector 0–7 picks that byte; **8, 9, 10, 11 give 0xff if bit 7 of byte 1, 3, 5, 7 is set, else 0x00**; 12 gives 0x00; 13 and above give 0xff. **Until 2026-11-21 selectors 8–11 gave 0x00 regardless of the sign bit**. How many corpus shaders use selectors 8–11 is not counted yet. GPU-checked with `runtime/test/shaders/ps_ops7.asm` (also `v_alignbit_b32` with a shift of 36, `v_med3_i32` vs `v_med3_u32`) and `ps_ops8.asm` (`v_mul_hi_u32/i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32` of 0, `v_xad_u32`, `v_add3_u32`), 4096/4096 pixels on an AMD Radeon iGPU (Ryzen 7 9800X3D, RDNA2, AMD driver 25.10.36) and an NVIDIA GeForce RTX 5070 (driver 621.24); before the fix `ps_ops7` gave 0x00000000 for the sign-selector word on both. Also executed by `tests/semantic/test_value_semantics.py`. | +| Float-to-int saturation | `v_cvt_u32_f32` and `v_cvt_i32_f32` truncate toward zero, saturate out-of-range values (including infinities) to the destination bounds, and return zero for NaN. The conversion operand is kept in range before emitting SPIR-V `OpConvertFToU`/`OpConvertFToS`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf), §12.8, VOP1 opcodes 7 and 8. The synthetic `cs_cvt_f32_sat.asm` fixture is checked bit-for-bit by `tests/semantic/test_float_to_int.py`. | | Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode. The MODE register (`s_setreg`) is ignored, so denormal and rounding behaviour is Vulkan's default. Whole-quad mode on non-EXEC masks is the identity. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | | Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2): raw buffers (`stride == 0`) check the starting byte offset (`offset < num_records`; per-dword tail bounds on multi-dword accesses aren't split yet), and structured buffers (`stride != 0`) check `index < num_records` (`idxen`) or `offset < num_records * stride`. Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0. GPU-checked with `runtime/test/shaders/cs_bounds.asm` on AMD Radeon RX 9070 XT. | | Wave64 mask ballot | `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, and `s_bfm_b64` bitfields). `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, and `s_bitcmp0/1_b32/b64` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. Known remaining gaps: `s_cmp_eq/lg_u32` comparing opposite halves (lo vs hi) falls back to a whole-wave vote. GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py` and `tests/semantic/test_scalar_alu_shifts.py`. | From c29faa4899ee14d2cf2371649935db2abaf31299 Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:30:27 +0100 Subject: [PATCH 05/53] Add bit-exact CPU regression coverage under tests/semantic --- tests/semantic/regen_fixtures.py | 2 +- tests/semantic/spirv_mini_interp.py | 10 +++++++ tests/semantic/test_float_to_int.py | 44 +++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 tests/semantic/test_float_to_int.py diff --git a/tests/semantic/regen_fixtures.py b/tests/semantic/regen_fixtures.py index a488c49aa..50faab5a8 100644 --- a/tests/semantic/regen_fixtures.py +++ b/tests/semantic/regen_fixtures.py @@ -17,7 +17,7 @@ ROOT = os.path.dirname(os.path.dirname(HERE)) ASM_DIR = os.path.join(ROOT, "runtime", "test", "shaders") FIXTURE_DIR = os.path.join(HERE, "fixtures", "disasm") SHADERS = ("ps_sdwa", "ps_ops", "ps_ops2", "ps_ops3", "ps_ops4", "ps_ops5", "ps_ops6", "ps_ops7", "ps_ops8", "ps_legacy_mul", - "ps_vcc_x2", "ps_flat", "cs_bounds") + "ps_vcc_x2", "ps_flat", "cs_bounds", "cs_cvt_f32_sat") def render(name): diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index 2741d2acb..377d41449 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py @@ -357,6 +357,16 @@ def run_fragment(text, inputs=None, push_constants=None, memory=None): values[res] = v & wmask(a[0]) else: raise UnsupportedConstruct("OpBitcast between these types") + elif op in ("OpConvertFToS", "OpConvertFToU"): + source = val(a[1]) + if not math.isfinite(source): + raise UnsupportedConstruct(f"{op} with a non-finite operand") + value = math.trunc(source) + bits = types.bits(a[0]) + lo, hi = (-(1 << (bits - 1)), (1 << (bits - 1)) - 1) if op == "OpConvertFToS" else (0, wmask(a[0])) + if not lo <= value <= hi: + raise UnsupportedConstruct(f"{op} result out of range (undefined in SPIR-V)") + values[res] = value & wmask(a[0]) elif op == "OpCompositeExtract": v = val(a[1]) for i in a[2:]: diff --git a/tests/semantic/test_float_to_int.py b/tests/semantic/test_float_to_int.py new file mode 100644 index 000000000..99a9bd106 --- /dev/null +++ b/tests/semantic/test_float_to_int.py @@ -0,0 +1,44 @@ +"""VOP1 conversions with known binary32 inputs and integer output words.""" +import struct +import unittest + +import support + + +# Input bits, unsigned result, signed result (as an untyped 32-bit word). +CASES = ( + (0x00000000, 0, 0), # +0 + (0x80000000, 0, 0), # -0 + (0x00000001, 0, 0), # subnormal + (0x3FC00000, 1, 1), # +1.5 + (0xBFC00000, 0, 0xFFFFFFFF), # -1.5 + (0x4EFFFFFF, 0x7FFFFF80, 0x7FFFFF80), # largest binary32 below +2^31 + (0x4F000000, 0x80000000, 0x7FFFFFFF), # +2^31 + (0x4F7FFFFF, 0xFFFFFF00, 0x7FFFFFFF), # largest binary32 below +2^32 + (0x4F800000, 0xFFFFFFFF, 0x7FFFFFFF), # +2^32 + (0xCEFFFFFF, 0, 0x80000080), # -(2^31 - 128) + (0xCF000000, 0, 0x80000000), # -2^31 + (0xCF000001, 0, 0x80000000), # next binary32 below -2^31 + (0x7F800000, 0xFFFFFFFF, 0x7FFFFFFF), # +infinity + (0xFF800000, 0, 0x80000000), # -infinity + (0x7F800001, 0, 0), # first positive NaN encoding + (0xFFC00000, 0, 0), # negative quiet NaN +) + + +class FloatToIntTest(unittest.TestCase): + def test_saturating_conversions(self): + # Five user SGPRs, with s4 carrying the input after the output V#. + fssm = bytes(0x138) + struct.pack("<4I", 0x808A, 1, 1, 1) + spv = support.translate_fixture("cs_cvt_f32_sat", fssm=fssm) + for bits, unsigned, signed in CASES: + with self.subTest(bits=f"{bits:08x}"): + memory = {} + support.run_fragment( + spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, + push_constants=[0, 0, 8, 0, bits] + [0] * 27, memory=memory) + self.assertEqual(memory, {0: unsigned, 4: signed}) + + +if __name__ == "__main__": + unittest.main() From b33cfa9e8cc1c350743fa73de34c0e3ff877e246 Mon Sep 17 00:00:00 2001 From: NWX10 <179748639+NWX10@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:31:03 +0300 Subject: [PATCH 06/53] pe_inspect.py: report a truncated image instead of stopping the run with struct.error A file cut off inside the optional header, the export directory, the TLS directory or an import lookup table raised struct.error. main() catches only PeFormatError and OSError, so a run over several images ended in a traceback at that file and the rest were never inspected. The optional header's fixed fields are now length-checked, and inspect() turns any remaining struct.error into PeFormatError, which main() reports as "not a PE image (...)" before moving on. The two export loops also ran to NumberOfFunctions / NumberOfNames as read from the file, so a corrupt count near 2^32 kept a run busy indefinitely. They are now capped at MAX_ENTRIES like the import, thunk and TLS loops, whose comment already says that is what the cap is for. Tests: TruncatedImageTest in tests/test_pe_inspect.py (each table cut short, a sweep over cut lengths for PE32 and PE32+, a CLI run that keeps going after a truncated file, and a 0xFFFFFFFF export count). Co-Authored-By: Claude Opus 5.5 --- tests/test_pe_inspect.py | 64 ++++++++++++++++++++++++++++++++++++++++ tools/pe_inspect.py | 15 ++++++++-- 2 files changed, 77 insertions(+), 2 deletions(-) diff --git a/tests/test_pe_inspect.py b/tests/test_pe_inspect.py index cae2837ee..70ee3913f 100644 --- a/tests/test_pe_inspect.py +++ b/tests/test_pe_inspect.py @@ -283,5 +283,69 @@ class PeInspectTest(unittest.TestCase): self.assertIn("not a PE image", err.getvalue()) +class TruncatedImageTest(unittest.TestCase): + """A file cut off inside a header or table is a bad image, not a struct.error that stops the run.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.dir = self.tmp.name + + def write(self, name: str, data: bytes) -> str: + path = os.path.join(self.dir, name) + with open(path, "wb") as f: + f.write(data) + return path + + def cut_inside(self, full: bytes, index: int, into: int) -> bytes: + """The image cut `into` bytes after the start of data directory `index`.""" + rva, _size = pe_inspect.PeImage(full).directory(index) + return full[:pe_inspect.PeImage(full).offset(rva) + into] + + def test_each_table_cut_short_is_a_pe_format_error(self): + for is64 in (True, False): + full = build_image(is64=is64) + cases = { + "optional header": full[:0x58 + 2 + 16], # magic present, AddressOfEntryPoint cut off + "export directory": self.cut_inside(full, pe_inspect.DIR_EXPORT, 10), + "tls directory": self.cut_inside(full, pe_inspect.DIR_TLS, 20 if is64 else 10), + } + for what, data in cases.items(): + with self.subTest(is64=is64, cut=what): + path = self.write("cut.dll", data) + with self.assertRaises(pe_inspect.PeFormatError): + pe_inspect.inspect(path, None) + + def test_every_cut_length_gives_a_report_or_a_pe_format_error(self): + for is64 in (True, False): + full = build_image(is64=is64) + for n in range(0, len(full), 16): + with self.subTest(is64=is64, length=n): + path = self.write("sweep.dll", full[:n]) + try: + pe_inspect.inspect(path, None) + except pe_inspect.PeFormatError: + pass + + def test_cli_reports_a_truncated_file_and_keeps_going(self): + cut = self.write("cut.dll", build_image()[:0x58 + 2 + 16]) + good = self.write("good.dll", build_image()) + out = os.path.join(self.dir, "reports") + err = io.StringIO() + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): + self.assertEqual(pe_inspect.main([cut, good, "--out", out]), 1) + self.assertIn("cut.dll: not a PE image (truncated optional header)", err.getvalue()) + self.assertEqual(sorted(os.listdir(out)), ["good.json", "good.md"]) + + def test_export_counts_past_the_table_cap_do_not_run_away(self): + full = bytearray(build_image()) + img = pe_inspect.PeImage(bytes(full)) + at = img.offset(img.directory(pe_inspect.DIR_EXPORT)[0]) + struct.pack_into(" len(data): # the fixed fields read below end with DllCharacteristics at +70 + raise PeFormatError("truncated optional header") self.is64 = magic == 0x20B self.entry_rva = struct.unpack_from(" list[str]: addr_names, addr_ordinals) = struct.unpack_from(" list[str]: symbol = img.string_at(struct.unpack_from(" str: def inspect(path: str, game_dir: str | None) -> dict: + """The report for one image. A file cut off inside a table raises PeFormatError like any other bad image; + the struct.error it used to raise escaped main() and stopped a multi-file run at that file.""" + try: + return _inspect(path, game_dir) + except struct.error as e: + raise PeFormatError(f"truncated or corrupt table: {e}") from None + + +def _inspect(path: str, game_dir: str | None) -> dict: with open(path, "rb") as f: img = PeImage(f.read()) sections = [] From 71b0122c197e75b0d7ed6db4ad2f23b01a928c78 Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:31:07 +0100 Subject: [PATCH 07/53] Add the generated disassembly for the synthetic shader --- tests/semantic/fixtures/disasm/cs_cvt_f32_sat.s | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 tests/semantic/fixtures/disasm/cs_cvt_f32_sat.s diff --git a/tests/semantic/fixtures/disasm/cs_cvt_f32_sat.s b/tests/semantic/fixtures/disasm/cs_cvt_f32_sat.s new file mode 100644 index 000000000..c22f609b5 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_cvt_f32_sat.s @@ -0,0 +1,7 @@ +; cs_cvt_f32_sat test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_cvt_f32_sat.asm + v_mov_b32_e32 v0, s4 + v_mov_b32_e32 v1, 0 + v_cvt_u32_f32_e32 v2, v0 + v_cvt_i32_f32_e32 v3, v0 + buffer_store_dwordx2 v[2:3], v1, s[0:3], 0 offen + s_endpgm From 2c3f21738eb9b38e41fa6cfe05c2796fe86e2b56 Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:31:57 +0100 Subject: [PATCH 08/53] Remove duplicate documentation uploaded to the root --- design.md | 342 ------------------------------------------------------ 1 file changed, 342 deletions(-) delete mode 100644 design.md diff --git a/design.md b/design.md deleted file mode 100644 index 58762cba7..000000000 --- a/design.md +++ /dev/null @@ -1,342 +0,0 @@ -# Design notes - -Groundwork for running the Xbox Series build of GTA VI natively on Windows. The work that does not need the -executable is in place; booting can start as soon as `game_scarlett_master.exe` is available. - -## Ground rules - -- Everything here runs from **your own copy** and stays on **your PC**. Game files, generated code, shader caches and - reports that quote game data are never committed, uploaded or shared. `reports/` is git-ignored for this reason. -- Nothing in this folder decrypts, unpacks or works around Xbox package protection. The tools only read files that - are already plain on disk. - -## Why a loader before a recompiler - -The Xbox Series CPU is x86-64, the same as a PC. Unlike Hookshot, where ARM64 code has to be -translated, most of the game's code can run as-is. The work is everything around it: - -| Layer | Approach | Folder | -|---|---|---| -| CPU code | Map the PE image and run it natively. Patch only what can't run on desktop (privileged instructions, console-only intrinsics). | `runtime/src` | -| Imports (GameOS / GDK / Xbox DLLs) | Every imported `dll!function` goes to a shim. Unimplemented ones log once and return a failure, so the missing surface shows up at runtime. | `runtime/shims` | -| Graphics | Xbox D3D12 (`d3d12_xs`) to Vulkan. Shaders ship as compiled RDNA2 machine code; `tools\rdna2spirv.py` translates all 26,503 to SPIR-V. The D3D12 layer is still to do. | `tools\` (translator), later (D3D12) | -| Assets | `.rpf` archives (RPF9) read through the runtime's file layer. | later | - -## Layout - -``` -tools/ Python analysis tools (no game data inside) - pe_inspect.py PE headers, sections, entropy, imports sorted by where they resolve, .pdata, TLS - rpf_probe.py RPF header survey of a game folder - manifest.py SHA-256 manifest of a game folder, plus a --verify mode -scripts/ - first_look.ps1 run once the exe arrives: the full report set for it -runtime/ C++ native loader (CMake + Ninja, MSVC) - src/ PE mapper, relocations, import binding, TLS - shims/ per-DLL shim tables -reports/ generated output (git-ignored) -docs/ notes -``` - -## Day one, when the exe is here - -```powershell -.\scripts\first_look.ps1 -Exe "\game_scarlett_master.exe" -``` - -This writes `reports/exe/` (JSON plus a readable summary). Check it in this order: - -1. **Section entropy.** Sections near 8.0 bits/byte are still encrypted or compressed. If `.text` is one of them, - nothing else can be done yet. -2. **Import table.** Each DLL is marked `bundled` (in the game folder), `system` (present on this Windows), or - `shim` (needs a reimplementation). The `shim` list is the real to-do list. -3. **.pdata function count.** This gives function boundaries for patching and later analysis. - -Then `runtime\build\gta6rt.exe --dry-run ` maps the image and binds every import to the shim table without -running any game code. It reports what it couldn't bind. - -## Reproduce the shader tests - -Build the hand-written tests where LLVM supports AMDGPU and SPIRV-Tools is available. Run the generated shaders -with the Vulkan test tools on the target GPU. Use the same output folder in both commands. - -```text -python -I runtime/test/shaders/build.py -python -I runtime/test/shaders/check.py [runtime-build-directory] -``` - -The wave-mask fixture checks every lane and the wave64 ballot fixture checks mask counts and first-set lanes -across both halves of a wave. Rebuild `vk_compute_test` before running `check.py`. It uses a full 64-wide compute -subgroup for these two checks, and the summary reports them as skipped if the device cannot provide one. -`cs_exec64` still checks per-lane EXEC writes on 32-wide subgroups. With `LEONIDA_W64_EMULATE=1` in the environment of both commands, `build.py` translates with `--wave64-emulate` and `check.py` runs every wave64 check without asking for a 64-wide subgroup, so a 32-wide GPU runs them all (`scripts/run_gpu_tests.py` honours the same variable). Pick one of several GPUs with the Vulkan loader, e.g. `VK_LOADER_DRIVERS_SELECT='*nv*'` or `'*amd*'`. The flat-input fixture checks both integer -IDs and interpolated UVs. The corpus comparison is a separate test and uses shader files from the local build. - -Run `python -I scripts/run_gpu_tests.py --filter ms_v5_workgroup` to check the mesh workgroup index. The synthetic -shader exports its incoming `v5` from lanes 0, 1 and 31 in the RGB channels of a full-screen triangle. One `vkCmdDrawMeshTasksEXT(2, 3, 4)` -produces 24 triangles. A stencil countdown lets pixel *i* record only triangle *i* in Vulkan rasterization order. -The CPU compares each pixel with `x + 2*y + 6*z`. This checks the translator's register mapping on the host GPU. -SPIRV-Tools 2026.1 validates this fixture. Version 2025.1 reports a known error on `CullPrimitiveEXT`. -[Vulkan mesh rasterization order](https://docs.vulkan.org/features/latest/features/proposals/VK_EXT_mesh_shader.html) · [Validator fix](https://github.com/KhronosGroup/SPIRV-Tools/pull/6155). - -## Build the runtime - -```powershell -.\scripts\build_runtime.ps1 -``` - -It sets up MSVC through `vcvars64.bat` and builds at BelowNormal priority on half the cores, writing to `runtime\build\`. -If VS's "C++ CMake tools" component is installed, it uses CMake and Ninja. Otherwise it calls `cl` directly. That -component may not be installed, and the devkitPro MSYS `cmake` on PATH can't build MSVC projects. When you -add a source file, add it to `runtime\CMakeLists.txt` and to the file list in `build_runtime.ps1`. - -## Asset status (no exe needed) - -| Asset | State | Where | -|---|---|---| -| Archive data | Carved without the encrypted tables of contents. Most archives are 93–99% plain zlib (`levels.rpf` 98.3%, 1.1M files). Not zlib: `audio.rpf` (99.9%), about half of `story000.rpf` and `shared_minigame000.rpf`. | `\carve\\`, `coverage.json` | -| Videos | 797 Bink 2 files (`KB2n`), cut out whole. | `*.bk2` in the carve folders | -| Shaders | 26,503 carved from `shaders.rpf`, native RDNA2 code unpacked (`FSSM`), disassembled, and translated to SPIR-V; all validate (see *Translator status*). | `\shaders\` (`.dxbc`, `fssm\`, `disasm\`, `spirv\`) | -| Textures | **Solved.** Headers are in CPU segments: GPU pointer at q[k], u16 width/height/depth and DXGI format at q[k+4], mip count at byte 2 of q[k+5]. Data is AMD `SW_4K_S` tiled, largest mip first. The GPU segment is the blob run after the CPU blob. On 200 samples, 173 decode at least 1.5× smoother detiled than untiled (median 2.56×). Exports the top mip, slice 0, as DDS. **22,342 exported (1.23 GiB)**: every header whose GPU data follows its CPU blob. World and model textures are handled by the TXD and TTPF exporters below. GPU offsets must be 256-byte aligned, which drops the false headers in `navmeshes`/`anim`. | `tools\tex_headers.py`, `tools\tex_export.py`, `\textures\` | -| Models | **Done: 155,598 models** (levels.rpf 149,811 with 1.9 billion triangles, story000 3,303, data 1,350, shared_minigame000 783, packs 314, core_restofworld 37; 0 failures). Exported with `tools\rpf9dump` (built on breadbbbb/rpf9-explorer's Core; see below). Resources are found at page offset +16 after 16 zero bytes, followed by a zlib system blob with a drawable/fragment header and then the following zlib blocks as graphics data. Positions are quantized: `bias + scale * ((q >> 8) & 0xFFFFFF)`. Output is OBJ (positions, UVs, indices) plus a manifest with real model names (e.g. `cvar_int_grg2b_toys_1`), bounds, per-mesh shader index and material texture references (parameter hash, name hash, 64-bit asset key). My earlier `0x1380`/`0x1601` descriptor notes stand, but the "data not located" blocker was wrong. | `\assets\\models\` | -| Texture dictionaries | Same tool: TXD resources become DDS per texture. | `\assets\\textures\` | -| World textures (TTPF) | **Done: 308,895 textures from all 57 pools, 0 failures, 48,220 entries skipped by the original exporter** (33,507 BCPack, 14,030 compact mapping, 678 arrays/volumes, 5 unsupported format, 0 unmapped). The compact-tail tool resolves 14,011 of the 14,030 layouts and reconstructs 305,264 complete chains (206,661 newly complete, 1,100,865 mips, 4.59 GiB); BCPack remains the hard blocker. 46 pools are in `data\ttdb\**`, 11 in `pack\\data\ttdb\**` (exported under `ttpf_pack\\`). `data\ttdb\**\*.ttpf` (57 pools, 58 GiB) are loose RDS5 texture pools, **not** inside RPFs. rpf9-explorer's `TtpfReader` reads the catalog and detiles them; checked visually (`ttdb_graphics`: scope reticles, clean lines). Names are generated (`texture_N_`); models reference textures by asset key. Some rows are skipped; the measured breakdown and the BCPack next step are in [textures.md](textures.md). | `\assets\ttpf\\` + `manifest.json` | -| Animation | Indexed without the TOC: 130,470 zlib streams (4,203,762,662 stored / 11,593,460,132 inflated), 95.4% readable. New RAGE page directories (`0DRP`, version 122), `MoVE` (version 19), 273 `pack:/` name tables (2,298 paths), and a tail `RBF0` rig-set manager (`rage__crRigSetManager`: 1,126 rig sets, 6,677 source→rig entries, 3,669 distinct rigs; 56 empty). Bone data: one standalone 28-name table and 3 motion-matcher streams with embedded bone tables (30-name union, 19 joaat32 hashes present, 4 motionmatcher paths); no rig→skeleton link was found. No `YCD`/`RSC7` at any stream start. The `rpf9_carve` tail overread is measured in `docs/animation.md`. | `tools\anim_index.py`, `\anim-index\` | -| Audio | `audio.rpf` holds raw (not zlib) **AWC** banks: Opus (codec 0x0B) and XMA2 streams. Exported as whole `.awc` files plus `audio_manifest.json` (stream ids, codec, channels, rate, duration). **Done: 7,162 banks, 27 GiB, 1,603,231 streams, about 1,324 hours** (codec 0x0B Opus 1,601,167; 5: 1,818; 2: 227; 0 PCM: 19). `tools/awc_opus.py` repackages every Opus stream **losslessly** into a standard Ogg Opus file (no re-encode; PCM streams become .wav). The AWC framing is 2048-byte blocks of [u16 length][packet], with a zero length padding the block (as rpf9-explorer's OpusPreview reads it). The final granule is trimmed to the declared sample count. Checked: 300 random streams decode with ffmpeg with no errors, lengths match the declared counts. XMA2 streams (codec 5, 1,818) are written as RIFF XMA2 files by `rpf9dump xma` (rpf9-explorer's `AwcRecovery.WriteXmaWave`) and decoded to PCM WAV by ffmpeg: all 1,818 decode. Streamed music (tag 0x48: chunks with a per-channel record table, each channel's 2048-byte subblocks after the aligned header, and a repeated-prefix skip per chunk) becomes one Ogg Opus per descriptor channel (3,008 banks contain music). The Opus TOC stereo bit gives the packet channel count; a 1-channel descriptor can carry stereo packets, whose interleaved sample count is halved for the end granule. Checked: a 4-channel bank gives four 42.0 s mono channels; 1-channel stereo banks export at the config duration. Output: `\assets\audio\ogg\\.ogg`. **Done: 1,598,051 Opus streams + 3,116 music channels as Ogg Opus (22 GB), 19 PCM16 and 227 codec-2 streams (32-bit float PCM, 4 bytes per sample; values can exceed ±1) as WAV, 1,818 XMA2 as WAV. Every audio stream is converted; all WAVs decode.** `make_game.py --wav` also decodes the Ogg Opus output to 16-bit PCM WAV with `tools/audio_wav.py` (ffmpeg required; existing WAVs are skipped on resume). | `\assets\audio\awc\` | -| World placement | **Full census of `levels.rpf`:** 23,535 map resources / 1,670,442 entities; all maps/entities exact, 36/36 shards, 98.32% stream coverage. Map files occupy a continuous band from ~7.5 to ~62.9 GiB; the earlier 9,918 / 680,228 sample was a 55% lower bound. `0x7a` resources: `CMapData` root, 0x90-byte `CEntityDef` with position/quaternion/scale/archetype/flags/GUID/LOD fields; names and most archetypes are hash-only. | `tools\world_index.py`, `tools\world_census.py`; [world.md](world.md), [world_census.md](world_census.md) | -| Navmeshes | `navmeshes.rpf`: 90,295 zlib streams (6,540,238,392 stored / 20,551,068,624 inflated), 97.5% readable; 9,603 `0DRP` pages and 27,644 `0x00010015` pages, no `NAVM`/`CNavMesh`/`NVMS` magic. `0DRP` is generic RPF paging, not a navmesh container. | `tools\navmesh_index.py`; [navmesh.md](navmesh.md) | -| BVH | `core_bvh4.rpf`: 565,596 streams, 271,627 complete BVH4 streams + 10 eight-MiB split continuations, 269,106 instance records. Header `0x81020006` at +0x100, 64-byte node units, 208-byte instances with a 3x4 transform; prebuilt acceleration data, not source meshes or shaders. | `tools\bvh_index.py`; [bvh.md](bvh.md) | -| RBF0 | 1,263 `data.rpf` resources, 475,461 elements, 44,887 descriptors and 340,859 strings. Inline record stream with no section table; UI/Scaleform (`rage__fwui*`, screens, subtitles, settings). The `anim.rpf` tail uses the same format (`rage__crRigSetManager`). `tools/rbf0_tree.py` decodes every resource to a strict JSON/CSV/XML element, value and text tree. | `tools\rbf0_index.py`, `tools\rbf0_tree.py`; [rbf0.md](rbf0.md) | -| Gamedata | `common.rpf`: 954 streams (5,647,255 stored / 50,231,123 inflated), 85.5% readable; 266 XML documents / 118 roots (time/weather, vehicles/handling, peds/schedules, tuning, manifests, world/navigation). No RBF0/PSIN. | `tools\gamedata_index.py`; [gamedata.md](gamedata.md) | -| PSIN | `script.rpf`: 671 streams start with `PSIN`, 670 complete; sections `LSCH`, `LENM`, `LSNS`, `LGID`, `LRSC`, `CHKS`. `data.rpf`: 2,281 streams, 1,045 complete after joining. `LSNS` is high-entropy; no plaintext scripts or names. | `tools/psin_index.py`; [psin.md](psin.md) | -| Audio config | `audio.rpf` first 19.5 MiB: 837 zlib streams / 54,143,493 inflated bytes. 1,589 music records, 1,589 distinct ids, exact milliseconds; `hash & 0x1fffffff` is the AWC stream id. 1,584/1,589 durations match the AWC manifest / 2; no per-track start offsets. | `tools/audio_config.py`; [audio_config.md](audio_config.md) | -| Page directory | `0DRP`: fixed 0x60-byte header, version 122; `q38` at +0x38 gives 16-byte records `{u32 hash, u32 size, u64 0x50000000 + target}`. `data.rpf`: 15,768 pages / 60,880 records; targets tile with zero overlaps. Names still need the TOC. | `tools/page_index.py`; [page_directory.md](page_directory.md) | -| Story / minigame | `story000.rpf` (18.65 GiB) is mixed: 264 Bink 2 streams (3.33 GB), 225,281 raw `RSC8` headers (v8001), 442 nested RPF9 headers and zlib resource pages. `story000_script.rpf` is 2,309 PSIN streams (2,118 complete), not a named script container; `shared_minigame000` mixes pages, PSIN and XML. | `tools/story_index.py`; [story.md](story.md) | -| Rest-of-world / script | Six archives, 1.57 GB total: `core_restofworld` 1.21 GB (11 Bink 2 streams / 1.24 GB, 37 decoded models, 958 graphics pages, 6 PSIN), `story000_restofworld` 189 MB, `story000_script` 74 MB (2,309 PSIN, 2,118 complete), small `appdata0`/licences. No maps; no validated script container. | `tools/restofworld_index.py`; [restofworld.md](restofworld.md) | -| Audio stations | Audio config `0x762160`: 19 station blocks of `{station hash, u32 boundary, ordered u32 content ids}`; the boundary is a byte offset, not a count. VCRR content ids `0x28F2-0x2941` map exactly to records `0xBD73-0xBDC2` (80/80); other clusters are context-dependent or shared. No per-track start offsets. | [radio_stations.md](radio_stations.md) | -| D3D12 command objects | Measured command queue / command list / fence / `PresentX` surface, split into verified exports and slots, prior-art claims, and open questions. Queue/list/fence creation and barriers are scoped; `PresentX` signature/slot and exact swapchain/plane parameters remain open until the executable is available. | [d3d12_command_objects.md](d3d12_command_objects.md) | - -### rpf9dump (bulk export) - -`tools\rpf9dump` is a small CLI over the Core library from https://github.com/breadbbbb/rpf9-explorer (a friend's tool; source at `third_party\rpf9-explorer`, audited: no keys, no network, no custom build targets). It decrypts nothing. It carves validated resources, as `rpf9_carve.py` does, but with working model and texture decoders. - -``` -dotnet build tools\rpf9dump\rpf9dump.csproj -c Release -o \tools\rpf9dump -rpf9dump models|textures \assets -rpf9dump ttpf \assets\ttpf -rpf9dump audio \assets -python -I make_game.py --stages assets # everything, in order; skips what is done -``` - -Full-scan indexes are also saved to `%LOCALAPPDATA%\RpfPreview\Indexes`, so the rpf9-explorer GUI opens these archives with complete listings instead of its 16 MiB preview scan. - -## Other prepared pieces - -- `tools\shader_profile.py`: across the corpus there are 551 distinct RDNA mnemonics, and 204 of them cover 99% of - all instructions (`\shaders\profile.json`). -- `tools\shader_ir.py`: parses every disassembled instruction into opcode, typed operands (s/v registers and - ranges, NSA register lists, constants, literals, export targets, interpolation attributes), modifiers and - encoding bytes. On 1,000 shaders, 12 of 2.2M operands were left untyped before the last fix. This is the front end - for an RDNA→SPIR-V translator. -- `tools\rtti_scan.py`: MSVC x64 RTTI scanner (class names, bases, vtables). Tested on the bundled DLLs; run it on - the exe first. -- `tools\hashdict.py`: joaat hash→name dictionary (`\hashes.json`, 1.9M entries, checked against - `adder` = 0xB779A091). On day one, rerun with `--extra ` so PSO field and type names resolve. Without the exe - only about 1% do. -- Runtime shims: all of `xmem.dll` is shimmed with the measured argument shapes (`XMemAlloc`, `XMemFree`, - `XMemVirtualQuery(process, address, out64)`, `XMemGetWorkingSetStatistics(out)`). The `d3d12_xs` root-signature - serializer forwards to the PC `d3d12.dll` after clearing the Xbox flag byte; the deserializer forwards unchanged. - `D3D12XboxCreateDevice` returns an Xbox-ABI proxy over the PC device: every PC vtable slot is forwarded with - `this` adjusted, Xbox slot 62 is `CreateComputePipelineState`, and Xbox slot 76 maps resource creation to - `CreateCommittedResource` with the Xbox `0x101`/`0x1` layout word replaced by the PC layout. Slots 9/10 are - `ID3D12DescriptorHeap` methods, not device methods. The PC heap getters take a hidden return pointer (RDX), - while Xbox expects the 8-byte handle in RAX, so slot 14 wraps the heap and slots 9/10 convert it. The heap holds - a reference to the device proxy and its `GetDevice` returns that same proxy. Queues, fences, command lists and - `PresentX` extensions remain unimplemented. -- PSO metadata is a new variant (`PSIN`, `LSCH` schema, `LENM`, `LSNS`, `LGID`, `LRSC`, `CHKS`, little-endian). - CodeWalker's parser reads the container but not the new schema; dump it once the exe gives the field names. - -## Shader translation (RDNA → SPIR-V) - -`tools\rdna2spirv.py` (needs `spirv-as`/`spirv-val` on PATH: Vulkan SDK, or `spirv-tools` in WSL) translates parsed RDNA -code to SPIR-V assembly, assembles it with `spirv-as`, and validates it with `spirv-val` (Vulkan 1.2). It runs one -lane per invocation and keeps VGPRs and SGPRs as uint arrays with exact bit patterns. Version 0 treated EXEC as -all-ones and covered only branch-free vertex and pixel shaders with no memory loads: common float and integer ALU -ops and exports to `gl_Position`, params and MRTs. Unsupported instructions are reported by name, never guessed. -In that version, `VS_Passthrough` and `VS_BlurFilter` translated and validated. Coverage across the corpus -and the blocking instructions are in `\shaders\spirv_run.log`; the former next steps, structured branches -(EXEC masks) and the descriptor/binding model for `s_load`, `s_buffer_load`, `buffer_*` and `image_*`, are now -implemented. Current coverage is in *Translator status* below. - -Also handled: 64-bit scalar moves, per-invocation EXEC reads, whole-quad mode on EXEC, `m0`, SCC, vector and scalar -compares, `v_mul_hi_u32`, `v_cvt_pkrtz_f16_f32` (now exact round-toward-zero; the earlier round-to-nearest version -could overflow to inf), and pixel interpolation (`v_interp_p1/p2/mov` become fragment inputs at their attribute's -location). The float MODE register (`s_setreg`) is skipped, so Vulkan's default denormal and rounding behaviour applies. - -### GPU tests (RTX 4060 Ti) - -`runtime\test\vk_harness.cpp` (build: `runtime\build\test\build_harness.cmd`, MSVC + the Vulkan 1.4 headers from -Hookshot's CPM cache, loading `vulkan-1.dll` at runtime) draws one triangle with a given VS + FS into an RGBA32F -target and dumps the floats. Test shaders are in `\gputest`. - -- **`VS_Passthrough` (translated) is bit-exact.** All 64×64 pixels are written, and `param0.xy` = (u, 1 − v) with max - error **0**, with zw = (0, 1) as exported. This covers the VertexIndex input, integer/float ALU, inline constants, - and position/param exports. -- **400 arithmetic-only translated pixel shaders** (no buffers, descriptors or subgroup ops), driven by a generic - full-screen VS feeding locations 0–15: the driver compiled every pipeline, every draw completed, and every output - was finite. This is a stability check, not a value check (there's no reference for these). -- **Texture path is exact** (`runtime\test\vk_texture_test.cpp`): translated `PS_PassthroughCopy` gives max error - **0.0** over all 64×64 pixels against the expected nearest-sampled 8×8 test texture. That covers push-constant - user data, a heap-relative `s_load_dwordx8` of the T#, the hash-table lookup of the T# and of the shader's - literal S#, bindless sampling, `v_interp`, and the f16 compressed export. **It also caught a translator bug** - that validation can't: compressed exports read the wrong register pair (LLVM prints `v4, v4, v5, v5`), giving - (r,g,r,g). That's fixed. -- After the export fix, 2 of the 400 smoke-test shaders (`PS_ImposterShadow` variants) gave non-finite red values. - The cause was round-to-nearest `pkrtz` overflowing to inf, fixed with exact RTZ. One variant is now fully finite. - The other still has 1 inf and 4 NaN in red, and RTZ can't create those from finite values, so they come from the - shader's own maths on the synthetic test inputs (hardware would pass them through too). That's consistent with - hardware, but unconfirmed without a reference. - -### Translator status and runtime contract - -Full corpus (verified pixel-shader inputs incl. front face, ACO-confirmed 16-bit semantics, `vcc_hi` as an SGPR, -code-embedded data via `s_getpc_b64`, global memory, exact packed-f16 modifiers): **All 26,503 shaders translate and pass `spirv-val`** (Vulkan 1.2 target, `--allow-offset-texture-operand`): 2,236 VS, 12,101 PS, 2,689 CS, 9,282 mesh, 195 geometry. `spirv/index.json` lists each one's requirements. Output: -`\shaders\spirv\` (`.spvasm` + `.spv`), and the log is `\shaders\spirv_run.log`. - -How the generated SPIR-V expects the runtime to work: - -| Piece | Contract | -|---|---| -| Execution model | One invocation = one lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). | -| EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. A pixel lane still inactive at the end is discarded. | -| Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. | -| User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. | -| Xbox GPU addresses | Shaders build Xbox GPU virtual addresses, and some force the high dword to 0 (descriptor tables in the low 4 GB). Every memory access goes to **heap base + Xbox VA**, so the runtime maps the console's GPU address window into one host buffer-device-address allocation. | -| Code-embedded data | 155 VS/PS had "undecodable words". They're **constant tables inside the code range** (float values like 0x3EF7…, plus zeros), read through `s_getpc_b64` + `s_add_u32`/`s_addc_u32` + `s_load` (147 of 155). The translator re-anchors each instruction to its true FSSM offset by matching encodings, translates only code reachable from entry (a branch into data is rejected), and turns `s_getpc_b64` into code base + next-instruction offset. **The runtime uploads each shader's FSSM blob into the heap and passes that VA as the code base.** Re-anchoring compares bytes exactly, except that VOP3P `op_sel_hi[2]` (bit 14) is ignored on two-source packed ops: the compiler stores 0 there, and LLVM prints its default of 1. Data words that decode with ignored fields set are printed re-encoded (e.g. `0xbe8d2242` as `s_rfe_b64` `0xbe802242`), so they can never match. Since the decoder consumed the same length, they are anchored in sequence and marked. A shader that can *reach* a marked word is rejected; none of the corpus does. All 155 now translate. | -| Global memory | `global_load/store_dword*`: address = (64-bit SGPR base + zero-extended 32-bit VGPR offset, or a 64-bit VGPR address) + signed 12-bit offset, translated through the heap base. Inactive lanes don't access memory, and loads merge their previous values with OpPhi. | -| Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. | -| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). The base comes from the 64-bit SGPR pointer or the V# (dword0 \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`): the address is base + sOFF + IMM + 4·i for dword i. Measured on AMD Radeon RX 6800 (gfx1030) by running the instructions as a raw compute kernel: soffset 8 + imm 4 reads +12 (`s_buffer_load_dword`, `x2`, `x4`, `x8`); `s_load_dword*` with both offsets wasn't measured and gets the same rule because it shares the SMEM encoding. The translator used to drop the immediate of that form. The translator's arithmetic is checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemSoffsetImmTranslatorTests`); a GPU test, `runtime/test/shaders/cs_smem_soffset_imm.asm`, is in `check.py` and `scripts/run_gpu_tests.py`. Known remaining differences, from the same measurement of `s_buffer_load*`: the hardware truncates base, sOFF and IMM each to a multiple of 4 and returns 0 past NUM_RECORDS; the translator does neither yet. See *Buffer bounds checking* below for the MUBUF `num_records` checks. | -| Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1/2/4, f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×4, uint8 ×4, unorm16 ×1/2/4, snorm16 ×2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. DST_SEL swizzle is applied. | -| Images and samplers | `image_sample_l` on 2D arrays used to read its LOD from the array layer; it now reads the LOD after all coordinates. `image_get_lod` and `image_gather4_lz` also work on 2D arrays. | -| Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. | -| Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, pad`. The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. | -| Vertex fetch | `s_swappc_b64` at the start of a VS calls a driver-generated fetch program that isn't in the blob. It's replaced by Vulkan vertex inputs: each `ISG1` input-signature element (DXBC container) becomes an input at **location = its D3D input register**, typed by its component type, and is written to **v(4 + 4·register + component)**. That rule was checked over all 788 fetch-calling shaders: in 783 every read-before-write VGPR is predicted by it (715 exact). Reads of components the element doesn't declare (e.g. `.w` of an `xyz` position, 3 VS) are allowed: the fetch returns the format defaults (0, 0, 1), and Vulkan fills a `vec4` input from a narrower format the same way. Inputs are declared as `vec4`. **The runtime must bind vertex buffers by the game's D3D12 input layout, location = input register.** | -| PS system inputs | v0–v1 = barycentrics (consumed by `v_interp`, which becomes attribute inputs). **v2.. = the `SV_Position` components the shader reads, packed in order**. Verified on 2,531 of 3,000 PS: the VGPRs they read before writing equal exactly the position components their input signature reads. Filled from `FragCoord`: xy/z directly, and **w directly too**, because AMD's position-w register holds 1/w (Mesa lowers `load_frag_coord_w_rcp` straight to `frag_pos[3]`, `ac_nir_lower_intrinsics_to_args.c`), the same as Vulkan's `FragCoord.w`. **Front face** follows the used position components when the signature declares `SV_IsFrontFace`, as ±1.0 (Mesa: `load_front_face` = `front_face > 0`). Only enabled inputs are packed, in hardware order (Mesa `radv_shader_args.c`: barycentric pairs, POS_X/Y/Z/W, FRONT_FACE, ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT). That explains the earlier "unverified" shaders: 102 read pos.xy + front face, and 76 read pos.x/y/w + front face. **Raw barycentric reads** (321 PS, e.g. `v_readfirstlane_b32 s41, v1`): AMD interpolates P = P0 + i(P1 − P0) + j(P2 − P0), so i/j are the weights of vertices 1/2, which is `BaryCoordKHR.y`/`.z` (`VK_KHR_fragment_shader_barycentric`). GPU-checked with `runtime/test/shaders/ps_bary.asm`: raw i/j equal the interpolated weights on every pixel. This assumes the pair is perspective-center, the only pair this layout models. A PS that reads any other unexplained register inside the system-input range is still rejected (none left in the corpus). Reads past the last hardware input are values undefined on some path, so zero stands in for them. All register arrays start at zero, so translated shaders are deterministic. | -| Inputs and outputs | VS: `v0` = `VertexIndex` (**unverified**: if the console runs vertex shaders as NGG, the input VGPR layout differs). `exp pos0` → `Position`, `exp pos1..pos3` → `ClipDistance` / `CullDistance` (and `Layer`/`ViewportIndex` in VS when `pos1` is the misc vector), `exp paramN` → location N. RDNA2/GFX10 packs clip distances before cull distances contiguously across 4-component `pos` exports (up to 8 floats total), starting at `pos2` when a misc vector (`PointSize`, `EdgeFlag`, `ShadingRate`, `Layer`, `ViewportIndex`; GFX9+ packs `Layer` in `z[10:0]` and `ViewportIndex` in `z[19:16]`) occupies `pos1`, and at `pos1` otherwise (Mesa `src/amd/common/nir/ac_nir_prerast_utils.c`: `ac_nir_export_position`; AMD LLPC `lgc/lowering/LowerInOut.cpp`: `LowerInOut::visitReturnInst`). Slot assignment follows the DXBC `OSG1` signature (`SV_ClipDistance` = 2, `SV_CullDistance` = 3, `SV_RenderTargetArrayIndex` = 4, `SV_ViewportArrayIndex` = 5, `SV_ShadingRate` = 23), ordered by `(semantic_index, register, component)` with clip before cull; when `OSG1` is absent (or declares none of those system values), `pos1..pos3` exports are discarded. PS: `v_interp_*` attribute N → input location N. `exp mrtN` → location N, `exp mrtz` x → `FragDepth`. | -| 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/mul/max/min_f16`, `v_fmac_f16`, `v_cvt_f16_f32`, f16 unary) and **opsel-capable VOP3 ops** (`v_fma_f16`, `_e64` forms of the 16-bit integer ops) are **partial writes that keep the high half**. The **VOP2 (`_e32`) 16-bit integer ops** (`v_lshrrev_b16`…) define the whole register, so the high half is modelled as zero. An op_sel destination bit writes the high half. The translator used to clear the high half on f16 ops; that's fixed. **op_sel on f16 VOP3 ops** (`v_fma_f16`, `v_med3_f16`, `v_add/sub/mul/max/min_f16`, f16 unary, `v_fmac_f16`): bit i (i < number of sources) reads the high half of source i, the last bit writes the high half of the destination; neg/abs apply to the selected half. Source: Mesa ACO `can_use_opsel` and the RDNA2 ISA VOP3 `OP_SEL` field. Checked by the structural tests in `tests/test_f16_op_sel.py` (which half is read, where the result goes); **not yet GPU-verified**. | -| POPS | Primitive-ordered pixel shading (10 PS, `src_pops_exiting_wave_id` wait loop, `s_sleep`, `MSG_ORDERED_PS_DONE`) becomes **fragment-shader interlock** (`PixelInterlockOrderedEXT`). It begins at the end of the entry block and ends at shader exit: a longer critical section with the same ordering. `src_pops_exiting_wave_id` reads 0, and **the runtime must put 0 (no collision, bit 31 clear) in the POPS collision SGPR**, so the hardware wait loop is skipped. Needs `VK_EXT_fragment_shader_interlock` (`fragmentShaderPixelInterlock`). | -| Texel offsets | `image_sample*_o`: the first address dword packs signed 6-bit offsets (x [5:0], y [13:8], z [21:16]), which become the SPIR-V `Offset` operand. A non-constant `Offset` outside gather needs **`VK_KHR_maintenance8`**, and is validated with `spirv-val --allow-offset-texture-operand`. Not yet GPU-tested. | -| Optional device features | Shaders may need `fragmentShaderBarycentric`, `fragmentShaderPixelInterlock` and `maintenance8`. All three are present on an RTX 4060 Ti, and `runtime/test/vk_harness.cpp` enables them when available. | -| Wave size | **Most of the game's shaders are wave64: 21,545 of 26,503.** An earlier marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks) counted 9,930 of 12,101 PS, 8,666 of 9,282 mesh shaders, 1,115 of 2,236 VS and 923 of 2,689 CS. 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; the game reads it with `v_readfirstlane_b32 s2, v5` and shifts it right by 7 to get the group index (NumThreads is 128 in the corpus), as TomBox's mesh ABI does too (`gid.x * numThreads + gi`). Not hardware-verified; 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. 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+`. 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. | -| Geometry shaders | All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. 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. | -| SCC from scalar ALU | `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32` and `s_lshl/lshr_b32` set SCC = result ≠ 0, `s_add/sub_i32` and `s_addk_i32` set it to signed overflow, `s_min_u32`/`s_max_u32` to S0 < S1 / S0 > S1. **Before this fix these ops left SCC unchanged**, so a following `s_cbranch_scc*` read a stale flag. 32-bit scalar shifts now mask the amount to 5 bits. GPU-checked with `runtime/test/shaders/ps_scc.asm`. | -| Far branches | `s_getpc_b64; s_add_u32 K; s_addc_u32 0/−1; s_setpc_b64` on the same pair is a branch beyond `s_branch`'s ±32K-dword range. It's folded into one branch to (address after `s_getpc`) + K before CFG construction. | -| Buffer format stores | `buffer_store_format_*` and `_d16_*` encode every format the loads decode (the same FORMATS table: f32/u32, f16, unorm/snorm 8/16/10-10-10-2, uint 8/16). 1–2-byte elements are merged into their dword with atomic and/or so neighbours are kept. d16 data is unpacked first (f16 → float for float kinds, 16-bit integers for integer kinds). Before this, only four f32 formats, rgba16f and rgba8 unorm were stored, and everything else silently stored nothing. GPU-checked with `runtime/test/shaders/cs_store.asm` (rgba8 unorm, 10:10:10:2, two r16f halves of one dword, d16 rgba16f: exact, neighbours untouched). `buffer_load_format_d16_*` packs pairs the same way. | -| Other additions | `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at mip round(LOD) in gather order, coordinates clamped to the edge (**approximation**: the sampler's wrap/mirror isn't reproduced at the border). `image_gather4_lz_o`: `OpImageGather … Offset`. `image_store` on 1D (bindings 17–19, `Image1D`) and with a16 coordinates. `ds_swizzle BITMASK_PERM` ("pippi" masks; GPU-checked). `v_add_f64`, `v_cvt_f32_f64` (`Float64`). `v_mul/mad_i32_i24`, `v_alignbyte_b32`, `v_xnor_b32`, `v_ffbh_i32`, `v_swap_b32`, `s_abs_i32`, `s_bfm_b32/b64`, 64-bit ordered and `v_cmpx` compares, 16-bit compares, 8/16-bit global loads, `neg(…)` constant operands (GPU-checked where listed in `runtime/test/shaders`). | -| Ray tracing | `image_bvh_intersect_ray` / `image_bvh64_intersect_ray` (64 CS: RT shadows) are one traversal step against AMD's hardware BVH node format. The traversal loop lives in the game's shader. The step is emulated over buffer reads following Mesa RADV's software path (`radv_nir_rt_common.c`, `intersect_ray_amd_software_box/_tri`; node layouts from `bvh_defines.h`). Node id = address >> 3 \| type (0–3 triangle, 4 box16, 5 box32). Box nodes give the four child ids, with misses and NaN boxes = `0xFFFFFFFF`, sorted by entry distance when descriptor bit 63 (box_sort_enable) is set. Triangle nodes use the watertight test with RADV's shared edge/vertex tie-breaks and give (t/\|det\|, sign(det), v/\|det\|, w/\|det\|), or (inf, 1, 0, 0) on a miss. The game's code divides by `.y` exactly as for the hardware's numerator/denominator. Address = descriptor base + ((node & ~7) << 3), base = descriptor bits [39:0] in 256-byte units (**assumption**: RADV only uses base 0). **The runtime must build the game's acceleration structures in this AMD node format** (RADV's GPU BVH builder produces it) wherever the game's D3D12 calls build them. Far branches with `s_sub_u32`/`s_subb_u32` (backward) are folded too. GPU-checked with `runtime/test/shaders/cs_bvh.asm`: sorted box children and the triangle result are exact. | -| Coverage | Every shader in the corpus translates. The remaining fidelity gap is wave64 cross-half code on 32-wide subgroups in VS/PS/GS; compute and mesh shaders are exact there with `--wave64-emulate` (see the wave-size and wave64 rows). | -| Flat pixel inputs | A pixel input location read only by `v_interp_mov_f32` is declared `Flat`. Locations read with `v_interp_p1/p2` remain interpolated. The `ps_flat` GPU test passes integer IDs through the first vertex alongside interpolated UVs. | -| Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. | -| Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. Instructions that explicitly fuse multiply-add still emit `Fma`. | -| Wave64 handling | Wave size is detected per shader from the code (64-bit EXEC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`; mesh shaders are always wave64). The hardware lane is exact in compute and mesh shaders (LocalInvocationIndex mod 64 or 32) and is used by `v_mbcnt` and EXEC writes. In other stages it's the subgroup lane. Constant EXEC writes (`s_mov_b32 exec_lo/exec_hi, K`) set each lane from its own bit of K; before, any non-zero constant turned every lane on. A register written to `exec_hi` sets lanes 32–63 only. GPU-checked with `runtime/test/shaders/cs_exec64.asm`: lanes 16–47 enabled from two constants, exact on a 32-wide-subgroup GPU. Still approximate on 32-wide subgroups: cross-lane ops between the two halves of a wave64 (readlane/permlane/DPP/shuffles across lane 31/32, wave-wide reductions). The metadata index marks every wave64 shader so a runtime can request `requiredSubgroupSize = 64` where supported (AMD), which makes those exact too. | -| Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do; not ordered: scalar loads of memory the wave wrote, and sampling an image it wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 35/36 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 37/37 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). | -| 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, …), `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: 64-wide subgroups can only be requested for compute/mesh, so graphics wave64 stays emulated 2x32 until cross-half ops go through LDS; also true for compute/mesh translated with `--wave64-emulate`, which then carry `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none), `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, and input/output locations. A runtime can create every pipeline at load time from it without parsing SPIR-V. | -| Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. | -| Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. This was checked against what all 2,689 CS read before writing: 2,281 match exactly, and the rest overshoot only through loop-carried registers in the straight-line check. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. Shaders with TG_SIZE_EN are rejected for now. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | -| LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `d16`/`d16_hi`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. In wave64 the permute runs as two wave32s (RDNA ISA §10.4.4): each half reads lanes of its own half, and a source lane that is off in EXEC reads 0. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. | -| Compute workgroup IDs Y/Z | With four user SGPRs and only TGID_Y and TGID_Z enabled (RSRC2 `0x308`), s4 receives Y and s5 receives Z. The synthetic `cs_workgroup_yz.asm` fixture checks a 2 × 3 × 4 dispatch and each of its 24 origins against a CPU reference. | -| Typed image stores | `image_store` (2D, 2D array, 3D) writes the dmask components (missing ones = 0). The image's numeric type lives in the T# (word 1 FORMAT [28:20], 512 GFX10 formats), so it is decided at run time. A 512-bit table built from `tools/gfx10_formats.json` (30 UINT and 15 SINT formats) picks a **sint**, **uint** or **float** view (bindings 8 + 3·dim + class; dim 0 = 2D, 1 = 2D array, 2 = 3D; class 0 float, 1 uint, 2 sint). Views have Unknown format (`shaderStorageImageWriteWithoutFormat`). **The runtime binds every storage image into all three arrays of its dimension, or at least the one matching its format.** The earlier path wrote only component 0 as `r32ui`, which was wrong for every other format. GPU-checked with `runtime/test/shaders/cs_imgstore.asm` through `runtime/test/vk_store_test.cpp`: rgba8 unorm, r32 uint and r32 sint images, every texel correct. | -| Typed image loads | `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores: UINT/SINT formats are read with `OpImageRead` through the uint/sint storage views (`shaderStorageImageReadWithoutFormat`), everything else with `OpImageFetch` through the float sampled view as before. Results are the raw bits of the dmask components. **The runtime binds integer-format images into the uint/sint storage arrays of their dimension** (bindings 8–19), as for stores. Before this, every load went through the float view, which is undefined for integer formats. GPU-checked with `runtime/test/shaders/cs_imgload.asm` (r32 uint read back exactly). | -| SDWA | `_sdwa` forms: each source is narrowed to `src0_sel`/`src1_sel` (BYTE_n/WORD_n, zero-extended, or sign-extended under `sext()`) **before** neg/abs and the op. A VGPR result goes to `dst_sel`, with `dst_unused` setting the other bits: PAD = 0, SEXT = sign copies above the field, PRESERVE = old bits kept. VOPC has no `dst_sel`, and GFX10 `v_cmpx` has no written destination. **Until 2026-11-20 the selects were silently ignored.** That affected 3,826 of the 13,926 translated shaders: they passed `spirv-val` but computed wrong values. GPU-checked with `runtime/test/shaders/ps_sdwa.asm` and `ps_ops.asm` (also `v_pk_fma_f16`, `v_min3_u32`, `v_max3_i32`, `v_bfe_i32`): byte/word source selects, `sext()`, `UNUSED_PRESERVE` into WORD_1 and `UNUSED_SEXT` at BYTE_2 all match on every pixel. | -| Byte permute | `v_perm_b32`: result byte i = BYTE_PERMUTE({src0, src1}, selector byte i), src1 = bytes 0–3 (AMD "RDNA 2" ISA reference, VOP3 opcode 836 V_PERM_B32, `byte_permute` pseudocode, page 189 of the PDF). Selector 0–7 picks that byte; **8, 9, 10, 11 give 0xff if bit 7 of byte 1, 3, 5, 7 is set, else 0x00**; 12 gives 0x00; 13 and above give 0xff. **Until 2026-11-21 selectors 8–11 gave 0x00 regardless of the sign bit**. How many corpus shaders use selectors 8–11 is not counted yet. GPU-checked with `runtime/test/shaders/ps_ops7.asm` (also `v_alignbit_b32` with a shift of 36, `v_med3_i32` vs `v_med3_u32`) and `ps_ops8.asm` (`v_mul_hi_u32/i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32` of 0, `v_xad_u32`, `v_add3_u32`), 4096/4096 pixels on an AMD Radeon iGPU (Ryzen 7 9800X3D, RDNA2, AMD driver 25.10.36) and an NVIDIA GeForce RTX 5070 (driver 621.24); before the fix `ps_ops7` gave 0x00000000 for the sign-selector word on both. Also executed by `tests/semantic/test_value_semantics.py`. | -| Float-to-int saturation | `v_cvt_u32_f32` and `v_cvt_i32_f32` truncate toward zero, saturate out-of-range values (including infinities) to the destination bounds, and return zero for NaN. The conversion operand is kept in range before emitting SPIR-V `OpConvertFToU`/`OpConvertFToS`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf), §12.8, VOP1 opcodes 7 and 8. The synthetic `cs_cvt_f32_sat.asm` fixture is checked bit-for-bit by `tests/semantic/test_float_to_int.py`. | -| Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode. The MODE register (`s_setreg`) is ignored, so denormal and rounding behaviour is Vulkan's default. Whole-quad mode on non-EXEC masks is the identity. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | -| Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2): raw buffers (`stride == 0`) check the starting byte offset (`offset < num_records`; per-dword tail bounds on multi-dword accesses aren't split yet), and structured buffers (`stride != 0`) check `index < num_records` (`idxen`) or `offset < num_records * stride`. Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0. GPU-checked with `runtime/test/shaders/cs_bounds.asm` on AMD Radeon RX 9070 XT. | -| Wave64 mask ballot | `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, and `s_bfm_b64` bitfields). `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, and `s_bitcmp0/1_b32/b64` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. Known remaining gaps: `s_cmp_eq/lg_u32` comparing opposite halves (lo vs hi) falls back to a whole-wave vote. GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py` and `tests/semantic/test_scalar_alu_shifts.py`. | -| Mesh/compute input registers (historical measurement) | An early read-before-write analysis over all compute and mesh shaders found **compute** v0 (880), v0–v1 (614), v0–v2 (50), consistent with AMD's local thread ID x/y/z in v0/v1/v2, and scalar inputs centred on a pointer at s[4:5] and s6/s7. **Mesh:** every one of 2,969 reads exactly **v5**, plus s3 (always arithmetic), s[16:17] and s19–s23. The early pass also read FSSM 0x13C as the group width and compared the first SGPR multiply against it (82 match, 151 don't, 1,447 no simple multiply) and wrongly concluded that 0x13C was not the group width; the matching register varied by shader (s6/s10/s7/s9…). PSV0 gave the real thread-group sizes (32×1×1 for 1,253, 8×8×1 for 416, …). **Superseded:** 0x13C/0x140/0x144 are the thread-group size, `COMPUTE_PGM_RSRC2` at 0x138 gives the per-shader user-SGPR count and enabled workgroup IDs, and mesh takes NumThreads, limits and topology from PSV0 with v5 as the workgroup index. All 2,689 CS and 9,282 mesh shaders translate now (see the Compute shaders and Mesh shaders rows). | -| Formerly untranslated | Mesh (9,282), geometry (195) and compute (2,689) now translate; `s_swappc_b64` is replaced by Vulkan vertex inputs (see *Vertex fetch*) and the `tbuffer_load_format_*` forms use the instruction's format. A few rare ops are still reported by name rather than guessed. | - -**Main blocker at the time (superseded): descriptor loads.** On a 3,000-shader sample, `s_load_dwordx4`/`x8` stop over half of them. Shaders -load texture, buffer and sampler descriptors through user-data SGPR pointers, and how the game's root signatures -map onto those SGPRs is set up by game code. Reading that mapping from the exe (root signature creation plus the -FSSM user-data metadata) before building the binding layer was the next step; guessing it would give silent -rendering bugs. The translator now handles those loads against the push-constant user-data contract (*User data*, -*Scalar/buffer memory* and the descriptor rows); the D3D12 layer still has to supply the root-signature mapping. -The other blockers listed then (mesh, the vertex-fetch call, geometry, compute and compressed exports) are closed -for the corpus: all 26,503 shaders translate (see *Translator status*). The remaining fidelity gap is wave64 -cross-half code on 32-wide subgroups. - -## Day one, in order - -1. `scripts\first_look.ps1 -Exe ...` checks the exe is plain, lists the imports to shim, and does a dry run. -2. Find the RPF9 table-of-contents key and decryption in the exe, then add a table reader to `rpf9_carve.py`. Carved - blobs then get real names and types, and the remaining unread data shows what it is. -3. Find the texture and mesh resource structures in the exe (their loaders give exact field layouts), which turns - carved blobs into named textures and meshes. -4. Shader translation: already complete for all 26,503 shaders (see *Translator status*); the day-one work is - validating them through the runtime. - -## Disassembling shaders - -The AMDGPU disassembler needs LLVM 21+ built with the AMDGPU target (`llvm-mc`; on Linux the `llvm-21` package -installs it at `/usr/lib/llvm-21/bin/llvm-mc`). The official Windows LLVM build has no AMDGPU target and ships no -`llvm-mc.exe`. On Windows, either build a native one or run it from WSL. - -Native: `scripts\build_llvm_mc.ps1` fetches the LLVM sources the tool needs (sparse, shallow), builds `llvm-mc` alone -with `LLVM_TARGETS_TO_BUILD=AMDGPU`, static CRT and the DIA SDK off (its headers need ATL, which the C++ build tools -don't always include), checks it disassembles an `s_endpgm` for `gfx1013`, keeps only `llvm-mc.exe` (by default in -`%LOCALAPPDATA%\Leonida\llvm-mc`) and sets `LLVM_MC` for the user. It needs git, Python and Visual Studio with the C++ -x64 tools, about 2 GB of temporary space and 20-40 minutes. `-Dest`, `-NoEnv`, `-Keep` and `-Version` change the -defaults. - -``` -powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 -python -I make_game.py --game "D:\path\to\your\package" --stages shaders -``` - -WSL: install `llvm-21` and give `LLVM_MC` the whole command: - -``` -set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc -python -I make_game.py --game "D:\path\to\your\package" --stages shaders -``` - -The same form works in every tool that reads `LLVM_MC`. `tools/mc_command.py` splits it for `shader_disasm.py`, -the tests, `runtime/test/shaders/build.py` and `scripts/run_gpu_tests.py`; the assembler callers pass the assembly -on stdin, so a WSL command never receives a Windows file path. - -`shader_disasm.py` disassembles one `s_endpgm` before starting, so a missing tool or AMDGPU target stops the run -with that reason instead of writing empty `.s` files. To disassemble by hand inside WSL: - -``` -LLVM_MC=/usr/lib/llvm-21/bin/llvm-mc python3 -I /tools/shader_disasm.py /shaders/fssm -``` - -Code starts at the u32 at FSSM offset 0xC0 (the code-section offset) plus 0x28 bytes into that section, and ends at the -last `s_endpgm`. Use `--mcpu gfx1013`. On 300 random shaders it decoded 284 cleanly (134 invalid words in total), -against 201 clean and 6,560 invalid for gfx1030 and 283 clean for gfx1010–1012. - -## Pixel-shader inputs - -`tools/fssm_header.py` decodes the FSSM input table: 8-byte records from 0x138 while the first byte is 6. -Byte 1 is the semantic id, byte 2 the component mask, byte 3 the running index, byte 6 the parameter slot, -and byte 7 holds flags (bit 4 = 16-bit interpolant). The record's position is the `v_interp attr` number. -`interpolants()` returns the count and a fp16 bitmask by position; a translator can use both, but -`rdna2spirv.py` does not yet. Measured on the 26,503-blob corpus: 25,643 satisfy -`u32[0x120] + u32[0x12C] == u32[0x130]` (the 860 that do not store 0xDEADBEEF at 0x130); 12,101 are PS, -10,307 with a non-empty table (55,791 records, 11,199 of them 16-bit). The count equals the number of -distinct `v_interp attr` numbers in 11,316/12,101 PS (93.5%); 300 more declare one unread input, 475 -declare two or more, and the 10 undercounts are one family whose first record at 0x138 has kind 7. A -200-PS spot check agreed on 187/200. Flag bit 4 matches the `*_f16` interpolation opcodes in -12,067/12,101 (99.7%). - -## Baseline already recorded - -- `reports/manifest.json`: SHA-256 of all 108 files in `Documents\GTA6` (208.5 GiB). Run - `python -I tools\manifest.py verify ` to check a copy against it. -- `reports/rpf_probe.json`: all 22 archives are **RPF9**. Five have tables that look packed or encrypted (`levels`, - `movies`, `core_bvh4`, `navmeshes`, `data`). -- `reports/pe/`: the 16 bundled DLLs are plain x86-64 PE with no encrypted sections. Through the loader their - `xmem.dll` imports and two `d3d12_xs.dll` root-signature calls bind to shims. Every other import resolves on - desktop Windows. The proxy covers the measured device slots and forwards the rest in PC vtable order; the Xbox - queue/fence/command-list extensions and `PresentX` remain unknown. From 70ae4c0eb40fdba5e5e2c5ce84d0ecadbbe9c2a5 Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:32:12 +0100 Subject: [PATCH 09/53] Remove duplicate tests/regen_fixtures.py from the test root --- tests/regen_fixtures.py | 54 ----------------------------------------- 1 file changed, 54 deletions(-) delete mode 100644 tests/regen_fixtures.py diff --git a/tests/regen_fixtures.py b/tests/regen_fixtures.py deleted file mode 100644 index 50faab5a8..000000000 --- a/tests/regen_fixtures.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Regenerate (or check) the translator input fixtures in tests/semantic/fixtures/disasm/ from the hand-written assembly -sources in runtime/test/shaders/. - - python tests/semantic/regen_fixtures.py # rewrite the fixtures - python tests/semantic/regen_fixtures.py --check # exit 1 if a fixture differs from what would be generated - -The translator (tools/rdna2spirv.py) reads one instruction per tab-indented line and skips the first line. For -straight-line code it does not need the `; encoding:` comments, so a fixture is the .asm instruction text, -unchanged, under a one-line header. No assembler is involved, which keeps the tests free of any LLVM version. -(The .asm syntax itself was written for `llvm-mc -mcpu=gfx1013`; see the comment at the top of each file.) -""" -import os -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -ASM_DIR = os.path.join(ROOT, "runtime", "test", "shaders") -FIXTURE_DIR = os.path.join(HERE, "fixtures", "disasm") -SHADERS = ("ps_sdwa", "ps_ops", "ps_ops2", "ps_ops3", "ps_ops4", "ps_ops5", "ps_ops6", "ps_ops7", "ps_ops8", "ps_legacy_mul", - "ps_vcc_x2", "ps_flat", "cs_bounds", "cs_cvt_f32_sat") - - -def render(name): - """Fixture text for one shader: header line, then each instruction line indented with a tab.""" - with open(os.path.join(ASM_DIR, name + ".asm"), encoding="utf-8") as f: - insns = [ln.strip() for ln in f.read().splitlines() if ln.strip() and not ln.lstrip().startswith(";")] - head = f"; {name} test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/{name}.asm\n" - return head + "".join("\t" + ln + "\n" for ln in insns) - - -def main(argv): - check = "--check" in argv - bad = 0 - for name in SHADERS: - path = os.path.join(FIXTURE_DIR, name + ".s") - want = render(name) - if check: - have = "" - if os.path.isfile(path): - with open(path, encoding="utf-8", newline="") as f: - have = f.read().replace("\r\n", "\n") - if have != want: - print(f"{name}: fixture is stale or missing") - bad += 1 - else: - os.makedirs(FIXTURE_DIR, exist_ok=True) - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(want) - print(f"wrote {os.path.relpath(path, ROOT)}") - return 1 if bad else 0 - - -if __name__ == "__main__": - sys.exit(main(sys.argv[1:])) From 7f7e94c595d5050e525e8b7efdad7417d4343eda Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:32:39 +0100 Subject: [PATCH 10/53] Remove duplicate tests/spirv_mini_interp.py from the test root --- tests/spirv_mini_interp.py | 540 ------------------------------------- 1 file changed, 540 deletions(-) delete mode 100644 tests/spirv_mini_interp.py diff --git a/tests/spirv_mini_interp.py b/tests/spirv_mini_interp.py deleted file mode 100644 index 377d41449..000000000 --- a/tests/spirv_mini_interp.py +++ /dev/null @@ -1,540 +0,0 @@ -"""A deliberately tiny interpreter for the SPIR-V assembly that tools/rdna2spirv.py emits for branch-free pixel -shaders and simple structured compute shaders. It exists so tests can check *computed values*, not just that the -module validates. - -Design rules (see tests/semantic/README.md): - * Written from the SPIR-V and GLSL.std.450 specifications. It shares no code with the translator. - * Strict: any opcode, extended instruction, type or storage class not listed below raises - UnsupportedConstruct. Nothing is skipped or approximated silently, so a translator change that starts - emitting something new makes the test error out instead of passing. - * One invocation (one lane). Control flow is the forward-only discard test and the forward merge/dynamic-bounds - branches the translator emits: OpBranch / OpBranchConditional to a later label plus OpPhi at the merge block. - Backward branches, loops, calls and switches are rejected. Function/Output/Input variables live in Python - boxes; PushConstant reads can be seeded with a word list; physical-storage-buffer loads/stores use a flat - address -> word dictionary. Workgroup storage and images are rejected. - * A default run sees zero push constants, no inputs and empty memory, so tests that do not care about them - keep the old behaviour. - -Values: uint/int are Python ints in [0, 2**32) or [0, 2**64) for 64-bit types (signedness is applied by the -operation, as in SPIR-V); float is a Python float rounded to binary32; vectors are tuples; arrays are lists; -bool is bool. -""" -import math -import re -import struct - -MASK = 0xFFFFFFFF - - -class UnsupportedConstruct(NotImplementedError): - """The module uses something this interpreter deliberately does not model.""" - - -# Instructions that carry no runtime semantics for a single-entry-point, straight-line module. -_IGNORED = frozenset({ - "OpCapability", "OpExtension", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", "OpExecutionMode", - "OpDecorate", "OpMemberDecorate", "OpTypeVoid", "OpTypeFunction", "OpLabel", "OpSelectionMerge", - "OpReturn", "OpFunctionEnd", "OpName", "OpSource", -}) - -_LINE = re.compile(r"^(?:(%\S+)\s*=\s*)?(Op\w+)\s*(.*)$") - - -def f32(x): - """Round a Python float to binary32 (overflow to infinity).""" - try: - return struct.unpack(" 0 else float("-inf") - - -def f32_bits(x): - try: - return struct.unpack(" 0 else 0xFF800000 - - -def bits_f32(b): - return struct.unpack(" 0 else 0xFC00 - - -def _s32(x): - x &= MASK - return x - (1 << 32) if x >> 31 else x - - -class _Types: - def __init__(self): - self.t = {} - - def zero(self, name): - k = self.t[name] - if k[0] == "int": - return 0 - if k[0] == "float": - return 0.0 - if k[0] == "bool": - return False - if k[0] == "vec": - return tuple(self.zero(k[1]) for _ in range(k[2])) - if k[0] == "arr": - return [self.zero(k[1]) for _ in range(k[2])] - raise UnsupportedConstruct(f"zero value of type {name} ({k[0]})") - - def size(self, name): - """Byte size of a concrete type. Runtime arrays have no size of their own; the element size is used.""" - k = self.t[name] - if k[0] in ("int", "float"): - return 4 - if k[0] == "vec": - return 4 * k[2] - if k[0] == "arr": - return self.size(k[1]) * k[2] - if k[0] == "rarr": - return self.size(k[1]) - if k[0] == "struct": - return sum(self.size(t) for t in k[1]) - raise UnsupportedConstruct(f"size of type {name} ({k[0]})") - - def bits(self, name): - k = self.t[name] - if k[0] != "int": - raise UnsupportedConstruct(f"integer width of type {name} ({k[0]})") - return k[1] - - -def run_fragment(text, inputs=None, push_constants=None, memory=None): - """Execute the entry point of `text` once and return the words written to every Output variable. - - `inputs` maps an Input variable name (for example "%in_attr1") to its value (a tuple for vectors). - `push_constants` is a list of 32-bit words at byte offsets 0, 4, 8, ... of the PushConstant block - (missing words read as zero). `memory` is a mutable {byte_address: word} mapping used for - PhysicalStorageBuffer loads and stores. - - Returns {output_variable_name: tuple_of_32bit_words}. Float outputs are returned as their bit patterns. - """ - inputs = inputs or {} - push_constants = list(push_constants or []) - memory = {} if memory is None else memory - types = _Types() - values = {} # id -> value (constants and results) - constants = {} # id -> value, kept apart so zero-initialised arrays can be built - ptr_types = {} # pointer type id -> (storage class, pointee type id) - var_class = {} # variable id -> storage class - var_box = {} # variable id -> [value] - pointers = {} # id -> (container list, index) / ("pc", offset) / ("psb", address) - pc_type = {} # id -> pointee type id of a PushConstant pointer - in_body = False - body = [] - outputs = [] - - def val(x): - if x in values: - return values[x] - raise UnsupportedConstruct(f"use of undefined id {x}") - - def walk(type_id, indices): - """Byte offset and element type after selecting `indices` in an aggregate type.""" - off, cur = 0, type_id - for idx in indices: - k = types.t[cur] - if k[0] == "struct": - for m in range(idx): - off += types.size(k[1][m]) - cur = k[1][idx] - elif k[0] in ("arr", "rarr", "vec"): - off += types.size(k[1]) * idx - cur = k[1] - else: - raise UnsupportedConstruct(f"OpAccessChain into {k[0]}") - return off, cur - - for raw in text.splitlines(): - line = raw.strip() - if not line: - continue - m = _LINE.match(line) - if not m: - raise UnsupportedConstruct(f"cannot parse line: {line!r}") - res, op, rest = m.groups() - a = rest.split() - if in_body: - body.append((res, op, a, line)) - continue - if op == "OpFunction": - in_body = True - continue - if op in _IGNORED: - continue - if op == "OpTypeInt": - bits = int(a[0]) - if bits not in (32, 64): - raise UnsupportedConstruct("integer type that is not 32 or 64 bits") - types.t[res] = ("int", bits, int(a[1])) - elif op == "OpTypeFloat": - if int(a[0]) != 32: - raise UnsupportedConstruct("non-32-bit float type") - types.t[res] = ("float",) - elif op == "OpTypeBool": - types.t[res] = ("bool",) - elif op == "OpTypeVector": - types.t[res] = ("vec", a[0], int(a[1])) - elif op == "OpTypeArray": - types.t[res] = ("arr", a[0], int(constants[a[1]])) - elif op == "OpTypeRuntimeArray": - types.t[res] = ("rarr", a[0]) - elif op == "OpTypeStruct": - types.t[res] = ("struct", a) - elif op == "OpTypePointer": - ptr_types[res] = (a[0], a[1]) - elif op == "OpConstant": - k = types.t[a[0]] - if k[0] == "float": - constants[res] = values[res] = f32(float(a[1])) - elif k[0] == "int": - constants[res] = values[res] = int(a[1]) & ((1 << k[1]) - 1) - else: - raise UnsupportedConstruct(f"OpConstant of type {k[0]}") - elif op == "OpConstantTrue": - constants[res] = values[res] = True - elif op == "OpConstantFalse": - constants[res] = values[res] = False - elif op == "OpConstantNull": - constants[res] = values[res] = types.zero(a[0]) - elif op == "OpVariable": - cls, pointee = ptr_types[a[0]] - if a[1] != cls: - raise UnsupportedConstruct("OpVariable storage class mismatch") - var_class[res] = cls - if cls == "PushConstant": - var_box[res] = [None] # reads come from push_constants, see OpLoad - pc_type[res] = pointee - elif cls == "Input": - init = inputs.get(res, types.zero(pointee)) - var_box[res] = [list(init) if isinstance(init, (list, tuple)) else init] - elif cls in ("Function", "Output"): - if len(a) > 2: - init = values[a[2]] - var_box[res] = [list(init) if isinstance(init, list) else init] - else: - var_box[res] = [types.zero(pointee)] - if cls == "Output": - outputs.append(res) - else: - raise UnsupportedConstruct(f"storage class {cls}") - pointers[res] = ("pc", 0) if cls == "PushConstant" else (var_box[res], 0) - else: - raise UnsupportedConstruct(f"{op} in module header") - if not in_body: - raise UnsupportedConstruct("no function body") - - def deref(p): - box, i = p - return box[i] - - def wmask(type_id): - return (1 << types.bits(type_id)) - 1 - - def signed(v, bits): - v &= (1 << bits) - 1 - return v - (1 << bits) if v >> (bits - 1) else v - - labels = {res: idx for idx, (res, op, _, _) in enumerate(body) if op == "OpLabel" and res} - pc = 0 - killed = False - cur_label = prev_label = None - while pc < len(body): - res, op, a, line = body[pc] - pc += 1 - if op == "OpLabel": - prev_label, cur_label = cur_label, res - continue - if op in _IGNORED: - continue - if op == "OpKill": - killed = True - break - if op == "OpBranch": - if a[0] not in labels or labels[a[0]] < pc: - raise UnsupportedConstruct("non-forward branch") - pc = labels[a[0]] - continue - if op == "OpBranchConditional": - cond = val(a[0]) - if not isinstance(cond, bool): - raise UnsupportedConstruct("OpBranchConditional with a non-bool condition") - target = a[1] if cond else a[2] - if target not in labels or labels[target] < pc: - raise UnsupportedConstruct("non-forward branch") - pc = labels[target] - continue - if op == "OpPhi": - incoming = [a[i] for i in range(1, len(a) - 1, 2) if a[i + 1] == prev_label] - if len(incoming) != 1: - raise UnsupportedConstruct("OpPhi with an unknown predecessor") - values[res] = val(incoming[0]) - continue - if op == "OpVariable": - cls, pointee = ptr_types[a[0]] - if cls != "Function": - raise UnsupportedConstruct("non-Function variable in body") - var_box[res] = [list(values[a[2]]) if len(a) > 2 and isinstance(values[a[2]], list) - else (values[a[2]] if len(a) > 2 else types.zero(pointee))] - pointers[res] = (var_box[res], 0) - elif op == "OpAccessChain": - base = a[1] - if base not in pointers: - raise UnsupportedConstruct("OpAccessChain on non-pointer") - p = pointers[base] - if p[0] == "pc": - off, cur = walk(pc_type[base], [values[i] for i in a[2:]]) - pointers[res] = ("pc", p[1] + off) - pc_type[res] = cur - var_class[res] = "PushConstant" - continue - if p[0] == "psb": - if len(a) != 3: - raise UnsupportedConstruct("multi-index physical-storage-buffer access chain") - elem = ptr_types[a[0]][1] - if types.t[elem][0] == "rarr": - stride = types.size(types.t[elem][1]) - elif types.t[elem][0] in ("int", "float", "vec"): - stride = types.size(elem) - else: - raise UnsupportedConstruct(f"physical-storage-buffer access chain into {types.t[elem][0]}") - pointers[res] = ("psb", p[1] + stride * values[a[2]]) - continue - for idx_id in a[2:]: - idx = values[idx_id] - container = deref(p) - if not isinstance(container, (list, tuple)) or not 0 <= idx < len(container): - raise UnsupportedConstruct("OpAccessChain into non-array or out of range") - p = (container, idx) - pointers[res] = p - elif op == "OpLoad": - p = pointers[a[1]] - if p[0] == "pc": - w = p[1] // 4 - values[res] = push_constants[w] if 0 <= w < len(push_constants) else 0 - elif p[0] == "psb": - values[res] = memory.get(p[1], 0) - else: - v = deref(p) - values[res] = list(v) if isinstance(v, list) else v - elif op == "OpStore": - p = pointers[a[0]] - if p[0] == "pc": - raise UnsupportedConstruct("store to PushConstant") - if p[0] == "psb": - memory[p[1]] = val(a[1]) - else: - p[0][p[1]] = val(a[1]) - elif op == "OpSelect": - if not isinstance(val(a[1]), bool): - raise UnsupportedConstruct("OpSelect with a non-scalar-bool condition") - values[res] = val(a[2]) if val(a[1]) else val(a[3]) - elif op == "OpCopyObject": - values[res] = val(a[1]) - elif op == "OpBitcast": - k, v = types.t[a[0]], val(a[1]) - if k[0] == "float" and isinstance(v, int): - values[res] = bits_f32(v) - elif k[0] == "int" and isinstance(v, float): - values[res] = f32_bits(v) - elif k[0] == "int" and isinstance(v, int): - values[res] = v & wmask(a[0]) - else: - raise UnsupportedConstruct("OpBitcast between these types") - elif op in ("OpConvertFToS", "OpConvertFToU"): - source = val(a[1]) - if not math.isfinite(source): - raise UnsupportedConstruct(f"{op} with a non-finite operand") - value = math.trunc(source) - bits = types.bits(a[0]) - lo, hi = (-(1 << (bits - 1)), (1 << (bits - 1)) - 1) if op == "OpConvertFToS" else (0, wmask(a[0])) - if not lo <= value <= hi: - raise UnsupportedConstruct(f"{op} result out of range (undefined in SPIR-V)") - values[res] = value & wmask(a[0]) - elif op == "OpCompositeExtract": - v = val(a[1]) - for i in a[2:]: - v = v[int(i)] - values[res] = v - elif op == "OpCompositeConstruct": - values[res] = tuple(val(x) for x in a[1:]) - elif op == "OpBitwiseAnd": - values[res] = (val(a[1]) & val(a[2])) & wmask(a[0]) - elif op == "OpBitwiseOr": - values[res] = (val(a[1]) | val(a[2])) & wmask(a[0]) - elif op == "OpBitwiseXor": - values[res] = (val(a[1]) ^ val(a[2])) & wmask(a[0]) - elif op == "OpNot": - values[res] = (~val(a[1])) & wmask(a[0]) - elif op == "OpShiftLeftLogical": - bits = types.bits(a[0]) - if val(a[2]) >= bits: - raise UnsupportedConstruct(f"shift amount >= {bits} (undefined in SPIR-V)") - values[res] = (val(a[1]) << val(a[2])) & wmask(a[0]) - elif op == "OpShiftRightLogical": - bits = types.bits(a[0]) - if val(a[2]) >= bits: - raise UnsupportedConstruct(f"shift amount >= {bits} (undefined in SPIR-V)") - values[res] = (val(a[1]) & wmask(a[0])) >> val(a[2]) - elif op == "OpShiftRightArithmetic": - bits = types.bits(a[0]) - if val(a[2]) >= bits: - raise UnsupportedConstruct(f"shift amount >= {bits} (undefined in SPIR-V)") - values[res] = (signed(val(a[1]), bits) >> val(a[2])) & wmask(a[0]) - elif op == "OpIAdd": - values[res] = (val(a[1]) + val(a[2])) & wmask(a[0]) - elif op == "OpISub": - values[res] = (val(a[1]) - val(a[2])) & wmask(a[0]) - elif op == "OpIMul": - values[res] = (val(a[1]) * val(a[2])) & wmask(a[0]) - elif op == "OpUConvert": - values[res] = val(a[1]) & wmask(a[0]) - elif op == "OpBitCount": - values[res] = (val(a[1]) & wmask(a[0])).bit_count() - elif op == "OpISubBorrow": - x, y = val(a[1]) & MASK, val(a[2]) & MASK - values[res] = ((x - y) & MASK, 1 if x < y else 0) - elif op in ("OpUMulExtended", "OpSMulExtended"): - # Result struct {low, high} of the full 64-bit product (SPIR-V spec, 32-bit scalars only). - x, y = val(a[1]) & MASK, val(a[2]) & MASK - if op == "OpSMulExtended": - x, y = _s32(x), _s32(y) - p = (x * y) & 0xFFFFFFFFFFFFFFFF - values[res] = (p & MASK, p >> 32) - elif op == "OpIEqual": - values[res] = val(a[1]) == val(a[2]) - elif op == "OpINotEqual": - values[res] = val(a[1]) != val(a[2]) - elif op == "OpSLessThan": - values[res] = _s32(val(a[1])) < _s32(val(a[2])) - elif op == "OpULessThan": - values[res] = val(a[1]) < val(a[2]) - elif op == "OpUGreaterThanEqual": - values[res] = val(a[1]) >= val(a[2]) - elif op == "OpLogicalAnd": - x, y = val(a[1]), val(a[2]) - if not (isinstance(x, bool) and isinstance(y, bool)): - raise UnsupportedConstruct("OpLogicalAnd on non-bool") - values[res] = x and y - elif op == "OpLogicalOr": - x, y = val(a[1]), val(a[2]) - if not (isinstance(x, bool) and isinstance(y, bool)): - raise UnsupportedConstruct("OpLogicalOr on non-bool") - values[res] = x or y - elif op == "OpLogicalNot": - values[res] = not val(a[1]) - elif op in ("OpFAdd", "OpFSub", "OpFMul"): - x, y = val(a[1]), val(a[2]) - if not (isinstance(x, float) and isinstance(y, float)): - raise UnsupportedConstruct(f"{op} on non-float") - values[res] = f32(x + y if op == "OpFAdd" else x - y if op == "OpFSub" else x * y) - elif op == "OpFNegate": - values[res] = f32(-val(a[1])) - elif op in ("OpFOrdEqual", "OpFOrdLessThan", "OpFOrdGreaterThan", "OpFOrdGreaterThanEqual", - "OpFOrdLessThanEqual", "OpFUnordNotEqual"): - x, y = val(a[1]), val(a[2]) - if not (isinstance(x, float) and isinstance(y, float)): - raise UnsupportedConstruct(f"{op} on non-float") - if op == "OpFUnordNotEqual": - values[res] = not (x == y) # true when unordered, unlike OpFOrdNotEqual - else: - values[res] = {"OpFOrdEqual": x == y, "OpFOrdLessThan": x < y, - "OpFOrdGreaterThan": x > y, "OpFOrdGreaterThanEqual": x >= y, - "OpFOrdLessThanEqual": x <= y}[op] - elif op in ("OpBitFieldUExtract", "OpBitFieldSExtract"): - base, off, cnt = val(a[1]), val(a[2]), val(a[3]) - if off + cnt > 32: - raise UnsupportedConstruct("bit-field extract beyond 32 bits (undefined in SPIR-V)") - field = (base >> off) & ((1 << cnt) - 1) - if op == "OpBitFieldSExtract" and cnt and field >> (cnt - 1): - field -= 1 << cnt - values[res] = field & MASK - elif op == "OpBitFieldInsert": - base, ins, off, cnt = (val(x) for x in a[1:5]) - if off + cnt > 32: - raise UnsupportedConstruct("bit-field insert beyond 32 bits (undefined in SPIR-V)") - mk = ((1 << cnt) - 1) << off - values[res] = ((base & ~mk) | ((ins << off) & mk)) & MASK - elif op == "OpConvertUToPtr": - values[res] = ("psb", val(a[1])) - pointers[res] = values[res] - elif op == "OpExtInst": - if len(a) < 3 or a[1] != "%glsl": - raise UnsupportedConstruct("extended instruction set") - name, args = a[2], [val(x) for x in a[3:]] - if name == "UnpackHalf2x16": - values[res] = (half_to_float(args[0]), half_to_float(args[0] >> 16)) - elif name == "PackHalf2x16": - values[res] = float_to_half(args[0][0]) | (float_to_half(args[0][1]) << 16) - elif name == "Fma": - # Exact product and sum in double, one rounding to binary32. Not a true fused operation in - # general, but exact for the f16-derived operands the tests use (see tests/semantic/README.md). - x, y, z = args - if isinstance(x, tuple): - values[res] = tuple(f32(p * q + s) for p, q, s in zip(x, y, z)) - else: - values[res] = f32(x * y + z) - elif name in ("Sin", "Cos"): - values[res] = f32(math.sin(args[0]) if name == "Sin" else math.cos(args[0])) - elif name == "FAbs": - values[res] = f32(abs(args[0])) - elif name == "UMin": - values[res] = min(args) - elif name == "UMax": - values[res] = max(args) - elif name == "SMax": - values[res] = max(args, key=_s32) - elif name == "SMin": - values[res] = min(args, key=_s32) - elif name in ("UClamp", "SClamp"): - # min(max(x, minVal), maxVal) (GLSL.std.450; undefined if minVal > maxVal, which raises here). - key = _s32 if name == "SClamp" else (lambda v: v) - x, lo, hi = args - if key(lo) > key(hi): - raise UnsupportedConstruct(f"{name} with minVal > maxVal (undefined)") - values[res] = min(max(x, lo, key=key), hi, key=key) - elif name == "FindILsb": - # Bit number of the least significant 1 bit, -1 if the value is 0 (GLSL.std.450). - x = args[0] & MASK - values[res] = (x & -x).bit_length() - 1 & MASK if x else MASK - elif name == "FindUMsb": - # Bit number of the most significant 1 bit, -1 if the value is 0 (GLSL.std.450). - x = args[0] & MASK - values[res] = x.bit_length() - 1 if x else MASK - elif name == "FindSMsb": - x = _s32(args[0]) - if x in (0, -1): - values[res] = MASK - elif x > 0: - values[res] = x.bit_length() - 1 - else: - values[res] = (~x).bit_length() - 1 - else: - raise UnsupportedConstruct(f"GLSL.std.450 {name}") - else: - raise UnsupportedConstruct(op) - - if killed: - return {} - result = {} - for name in outputs: - v = var_box[name][0] - flat = v if isinstance(v, tuple) else (v,) - result[name] = tuple(f32_bits(x) if isinstance(x, float) else x & MASK for x in flat) - return result From 23f5a514e96a9d2fd37eb738eb35ea19d842788e Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:32:43 +0100 Subject: [PATCH 11/53] Remove duplicate tests/test_float_to_int.py from the test root --- tests/test_float_to_int.py | 44 -------------------------------------- 1 file changed, 44 deletions(-) delete mode 100644 tests/test_float_to_int.py diff --git a/tests/test_float_to_int.py b/tests/test_float_to_int.py deleted file mode 100644 index 99a9bd106..000000000 --- a/tests/test_float_to_int.py +++ /dev/null @@ -1,44 +0,0 @@ -"""VOP1 conversions with known binary32 inputs and integer output words.""" -import struct -import unittest - -import support - - -# Input bits, unsigned result, signed result (as an untyped 32-bit word). -CASES = ( - (0x00000000, 0, 0), # +0 - (0x80000000, 0, 0), # -0 - (0x00000001, 0, 0), # subnormal - (0x3FC00000, 1, 1), # +1.5 - (0xBFC00000, 0, 0xFFFFFFFF), # -1.5 - (0x4EFFFFFF, 0x7FFFFF80, 0x7FFFFF80), # largest binary32 below +2^31 - (0x4F000000, 0x80000000, 0x7FFFFFFF), # +2^31 - (0x4F7FFFFF, 0xFFFFFF00, 0x7FFFFFFF), # largest binary32 below +2^32 - (0x4F800000, 0xFFFFFFFF, 0x7FFFFFFF), # +2^32 - (0xCEFFFFFF, 0, 0x80000080), # -(2^31 - 128) - (0xCF000000, 0, 0x80000000), # -2^31 - (0xCF000001, 0, 0x80000000), # next binary32 below -2^31 - (0x7F800000, 0xFFFFFFFF, 0x7FFFFFFF), # +infinity - (0xFF800000, 0, 0x80000000), # -infinity - (0x7F800001, 0, 0), # first positive NaN encoding - (0xFFC00000, 0, 0), # negative quiet NaN -) - - -class FloatToIntTest(unittest.TestCase): - def test_saturating_conversions(self): - # Five user SGPRs, with s4 carrying the input after the output V#. - fssm = bytes(0x138) + struct.pack("<4I", 0x808A, 1, 1, 1) - spv = support.translate_fixture("cs_cvt_f32_sat", fssm=fssm) - for bits, unsigned, signed in CASES: - with self.subTest(bits=f"{bits:08x}"): - memory = {} - support.run_fragment( - spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=[0, 0, 8, 0, bits] + [0] * 27, memory=memory) - self.assertEqual(memory, {0: unsigned, 4: signed}) - - -if __name__ == "__main__": - unittest.main() From 89b74d8e409ba124082d43549f3548c194dcf7a7 Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:32:57 +0100 Subject: [PATCH 12/53] Add the hand-written RDNA2 conversion shader --- runtime/test/shaders/cs_cvt_f32_sat.asm | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 runtime/test/shaders/cs_cvt_f32_sat.asm diff --git a/runtime/test/shaders/cs_cvt_f32_sat.asm b/runtime/test/shaders/cs_cvt_f32_sat.asm new file mode 100644 index 000000000..52227367f --- /dev/null +++ b/runtime/test/shaders/cs_cvt_f32_sat.asm @@ -0,0 +1,13 @@ +; s[0:3] is the output V#, s4 is one binary32 input as a raw word. +; RDNA 2 ISA, VOP1 opcodes 7 and 8: truncate toward zero, saturate to +; the destination range, and return zero for NaN. +; At offset 0: unsigned result. At offset 4: signed result, as raw bits. +; Example s4 = 0x4f000000 (+2^31): out = 0x80000000, 0x7fffffff. +; group: 1,1,1 +; rsrc2: 0x808a +v_mov_b32_e32 v0, s4 +v_mov_b32_e32 v1, 0 +v_cvt_u32_f32_e32 v2, v0 +v_cvt_i32_f32_e32 v3, v0 +buffer_store_dwordx2 v[2:3], v1, s[0:3], 0 offen +s_endpgm From fa8beb755abba416260ada0cd073371e580d9784 Mon Sep 17 00:00:00 2001 From: mrb-eel <323506043+mrb-eel@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:35:42 +0100 Subject: [PATCH 13/53] Translate v_cmpx_class_f32 as an EXEC-only compare --- docs/design.md | 1 + runtime/test/shaders/check.py | 3 +++ runtime/test/shaders/cs_cmpx_class_f32.asm | 28 ++++++++++++++++++++++ scripts/run_gpu_tests.py | 9 ++++--- tests/test_shader_checks.py | 4 +++- tools/rdna2spirv.py | 12 ++++++---- 6 files changed, 47 insertions(+), 10 deletions(-) create mode 100644 runtime/test/shaders/cs_cmpx_class_f32.asm diff --git a/docs/design.md b/docs/design.md index a7f9ae1ad..6f3ae0cca 100644 --- a/docs/design.md +++ b/docs/design.md @@ -238,6 +238,7 @@ How the generated SPIR-V expects the runtime to work: | Flat pixel inputs | A pixel input location read only by `v_interp_mov_f32` is declared `Flat`. Locations read with `v_interp_p1/p2` remain interpolated. The `ps_flat` GPU test passes integer IDs through the first vertex alongside interpolated UVs. | | Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. | | Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. Instructions that explicitly fuse multiply-add still emit `Fma`. | +| Floating-point class compare | `v_cmp_class_f32` writes the selected class to a lane mask. `v_cmpx_class_f32` intersects the existing EXEC with that same predicate and preserves VCC, as specified in [AMD's RDNA2 ISA §12.9](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf). `cs_cmpx_class_f32` checks both encodings with quiet NaN, positive infinity and signed zero, and verifies that a previously inactive lane stays inactive. GPU-checked on an RTX 4070 SUPER (driver 616.92). | | Wave64 handling | Wave size is detected per shader from the code (64-bit EXEC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`; mesh shaders are always wave64). The hardware lane is exact in compute and mesh shaders (LocalInvocationIndex mod 64 or 32) and is used by `v_mbcnt` and EXEC writes. In other stages it's the subgroup lane. Constant EXEC writes (`s_mov_b32 exec_lo/exec_hi, K`) set each lane from its own bit of K; before, any non-zero constant turned every lane on. A register written to `exec_hi` sets lanes 32–63 only. GPU-checked with `runtime/test/shaders/cs_exec64.asm`: lanes 16–47 enabled from two constants, exact on a 32-wide-subgroup GPU. Still approximate on 32-wide subgroups: cross-lane ops between the two halves of a wave64 (readlane/permlane/DPP/shuffles across lane 31/32, wave-wide reductions). The metadata index marks every wave64 shader so a runtime can request `requiredSubgroupSize = 64` where supported (AMD), which makes those exact too. | | Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do; not ordered: scalar loads of memory the wave wrote, and sampling an image it wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 35/36 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 37/37 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). | | 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, …), `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: 64-wide subgroups can only be requested for compute/mesh, so graphics wave64 stays emulated 2x32 until cross-half ops go through LDS; also true for compute/mesh translated with `--wave64-emulate`, which then carry `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none), `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, and input/output locations. A runtime can create every pipeline at load time from it without parsing SPIR-V. | diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 65182ff28..84b6c7f45 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -36,6 +36,7 @@ CS_DUMPS = [("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM), ("cs_wave6 ("cs_wm_bfm64", [16, 8, 8, 40]), ("cs_wm_scc_rfl", [55, 48])] # num_records bounds check (cs_bounds.asm): one thread, so no 64-wide subgroup requirement. BOUNDS = [("cs_bounds", [0x12345678, 0x12345678, 0x00000000, 0xEEEEEEEE])] +CMPX_CLASS_WORDS = [0xEEEEEEEE] * 3 + [0x22] + [0x11] * 4 # Cross-half wave64 tests (x = cross-half): exact results need 64 lanes, or an emulation of them on narrower subgroups. W64_EMULATED = os.environ.get("LEONIDA_W64_EMULATE") == "1" W64X_DUMPS = [("cs_w64x_readlane", [121, 121, 16, 97, 16, 100, 100, 121]), @@ -283,6 +284,8 @@ def main(): expected_words=want))) for name, want in BOUNDS: results.append((name, compute_test(tools, spirv, name, "1", "dump", expected_words=want))) + results.append(("cs_cmpx_class_f32", compute_test(tools, spirv, "cs_cmpx_class_f32", "1", "dump", + expected_words=CMPX_CLASS_WORDS))) for name, want in W64X_DUMPS: # without --require-wave64 when LEONIDA_W64_EMULATE=1 results.append((name, compute_test(tools, spirv, name, "1", "dump", require_wave64=not W64_EMULATED, expected_words=want))) diff --git a/runtime/test/shaders/cs_cmpx_class_f32.asm b/runtime/test/shaders/cs_cmpx_class_f32.asm new file mode 100644 index 000000000..75dcdd4be --- /dev/null +++ b/runtime/test/shaders/cs_cmpx_class_f32.asm @@ -0,0 +1,28 @@ +; group: 8,1,1 +; mattr: +wavefrontsize32,-wavefrontsize64 +; CMPX class keeps qNaN and +0 across both compares. E32 (mask 0x242) drops -0, E64 (mask 0x62) +; drops +infinity. Neither compare can reactivate lane 0, which was disabled even though it holds qNaN. +; VCC selects the distinctive value in lane 3 and must survive both EXEC-only compares. +; Run: vk_compute_test cs_cmpx_class_f32.spv 1 dump +; out[0..7] = EEEEEEEE EEEEEEEE EEEEEEEE 00000022 00000011 00000011 00000011 00000011 (hex) +v_mov_b32_e32 v1, 0x7fc00000 +v_mov_b32_e32 v2, 0x7f800000 +v_cmp_eq_u32_e32 vcc_lo, 1, v0 +v_cndmask_b32_e32 v1, v1, v2, vcc_lo +v_mov_b32_e32 v2, 0x80000000 +v_cmp_eq_u32_e32 vcc_lo, 2, v0 +v_cndmask_b32_e32 v1, v1, v2, vcc_lo +v_mov_b32_e32 v2, 0 +v_cmp_eq_u32_e32 vcc_lo, 3, v0 +v_cndmask_b32_e32 v1, v1, v2, vcc_lo +v_mov_b32_e32 v2, 0x242 +v_mov_b32_e32 v7, 0x62 +v_mov_b32_e32 v3, 0x11 +v_mov_b32_e32 v4, 0x22 +v_lshlrev_b32_e32 v5, 2, v0 +v_cmpx_ne_u32_e32 0, v0 +v_cmpx_class_f32_e32 v1, v2 +v_cmpx_class_f32_e64 v1, v7 +v_cndmask_b32_e32 v6, v3, v4, vcc_lo +buffer_store_dword v6, v5, s[0:3], 0 offen +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 27a605598..7073acdb4 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -23,7 +23,7 @@ sys.path.insert(0, os.path.join(ROOT, "tools")) import mc_command # noqa: E402 sys.path.insert(0, SHADER_DIR) from compute_fixture import compute_header -from check import Skip, mesh_v5_test +from check import CMPX_CLASS_WORDS, Skip, mesh_v5_test def make_dxbc(chunks: list[tuple[bytes, bytes]]) -> bytes: @@ -477,11 +477,10 @@ def run_suite(a, work: str) -> int: elif name == "cs_bvh": rc, msg = run_cmd([vk_compute, spv, "1", "bvh"], env=cs_env) results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) - elif name == "cs_bounds": - # num_records bounds check (cs_bounds.asm): the out-of-bounds store is dropped and the out-of-bounds - # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement. + elif name in ("cs_bounds", "cs_cmpx_class_f32"): + # These per-lane results do not require a particular subgroup width. rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env) - want = [0x12345678, 0x12345678, 0, 0xEEEEEEEE] + want = CMPX_CLASS_WORDS if name == "cs_cmpx_class_f32" else [0x12345678, 0x12345678, 0, 0xEEEEEEEE] dump = next((ln for ln in msg.splitlines() if "out[0..7] =" in ln), "") vals = [int(x) for x in dump.partition("=")[2].split()[:len(want)]] if dump else [] results.append((name, rc == 0 and vals == want, diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py index dd01212ed..41780ae1b 100644 --- a/tests/test_shader_checks.py +++ b/tests/test_shader_checks.py @@ -22,7 +22,7 @@ PARTIAL = {n for n, _ in check.W64X_PARTIAL} # every test check.py runs: compute, cs_wavemask, the dumps (#73, #152 cross-half, partial), the two store # tests, pixel tests, and two mesh fixtures (skipped here: build.py does not build mesh shaders) TOTAL = (len(check.COMPUTE) + 1 + len(check.CS_DUMPS) + len(check.W64X_DUMPS) + len(check.W64X_PARTIAL) + 2 - + len(check.PIXEL_TESTS) + 2 + len(check.BOUNDS)) + + len(check.PIXEL_TESTS) + 2 + len(check.BOUNDS) + 1) # also cs_cmpx_class_f32 class Wave64Checks(unittest.TestCase): @@ -59,6 +59,8 @@ class Wave64Checks(unittest.TestCase): if name == "cs_bounds": # 0x12345678, the in-bounds reload, the OOB load's 0, then the untouched 0xEEEEEEEE fill. return 0, "out[0..7] = 305419896 305419896 0 4008636142 4008636142 4008636142 4008636142 4008636142\n" + if name == "cs_cmpx_class_f32": + return 0, "out[0..7] = " + " ".join(map(str, check.CMPX_CLASS_WORDS)) + "\n" if name == "cs_store": return 0, "out[0..7] = 1073774847 3758097407 1006649344 4008636142 1073757184 3154130944 0 0\n" if name == "cs_smem_soffset_imm": diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 21c097564..3fcf8cce2 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -1171,8 +1171,8 @@ class Gen: self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") - def cmp_class(self, a): - """v_cmp_class_f32 dst, x, mask: true if x's class bit is set in mask. + def cmp_class(self, a, exec_only=False): + """Test x's class against the mask and write the result to VCC/SGPR or EXEC. Bits: 0 sNaN, 1 qNaN, 2 -inf, 3 -normal, 4 -denormal, 5 -0, 6 +0, 7 +denormal, 8 +normal, 9 +inf.""" x, mask = self.src_f(a[-2]), self.src_u(a[-1]) u = self.tou(x) @@ -1212,6 +1212,10 @@ class Gen: hit = b(f"OpLogicalAnd %bool {on} {c}") acc = b(f"OpLogicalOr %bool {acc} {hit}") acc = b(f"OpLogicalAnd %bool {acc} {self.active_b()}") # inactive lanes write 0 + if exec_only: + self.emit(f"OpStore %active {acc}") + self.uses_active = True + return r = b(f"OpSelect %uint {acc} {self.cu(0xFFFFFFFF)} {self.cu(0)}") d = a[0] if len(a) == 2 or (d["k"] == "special" and d["t"] in ("vcc", "vcc_lo")): @@ -1980,8 +1984,8 @@ class Gen: self.emit(f"{hi} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {hi}") self.dst(a[0], r) - elif op == "v_cmp_class_f32": - self.cmp_class(a) + elif op in ("v_cmp_class_f32", "v_cmpx_class_f32"): + self.cmp_class(a, exec_only=op == "v_cmpx_class_f32") elif op in ("v_ffbl_b32", "v_ffbh_u32", "s_flbit_i32_b32") or \ (op == "s_ff1_i32_b32" and not self.holds_lane_mask(a[1])): # of a lane mask: further down x = self.src_u(a[1]) From 321635899b32c9fbc579ed1d31375b06e2954208 Mon Sep 17 00:00:00 2001 From: S1m0ne1997 <347981799+S1m0ne1997@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:59:24 +0100 Subject: [PATCH 14/53] Tools: feature_scan.py, a corpus scan for D3D12-layer features (SHADER-16) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Counts, from what the shaders stage leaves in /shaders, the features docs/d3d12_vulkan.md §8.2 #10 and #14 ask about: the DXIL program kind of every shader (hull, domain, amplification), the SFI0 D3D_SHADER_REQUIRES_* flags (values from the Windows SDK's d3d12shader.h, among them WAVE_MMA and SHADING_RATE), output-signature streams other than 0, native v_mfma/v_wmma and GDS/ordered-count instructions in the disassembly, and uses_code_base per stage from spirv/index.json. Prints counts only. tests/test_feature_scan.py checks it on a synthetic work folder (hand-built DXBC parts, listings and index). AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- tests/test_feature_scan.py | 105 ++++++++++++++++++++ tools/feature_scan.py | 194 +++++++++++++++++++++++++++++++++++++ 2 files changed, 299 insertions(+) create mode 100644 tests/test_feature_scan.py create mode 100644 tools/feature_scan.py diff --git a/tests/test_feature_scan.py b/tests/test_feature_scan.py new file mode 100644 index 000000000..070d44246 --- /dev/null +++ b/tests/test_feature_scan.py @@ -0,0 +1,105 @@ +"""feature_scan: stage census, SFI0 flags, output streams, MMA/GDS opcodes and code-base counts on a synthetic work folder. + + python -I tests/test_feature_scan.py + +Every input is built here: tiny DXBC containers with only the parts the scanner reads, three hand-written .s +listings and a two-entry spirv/index.json. No game data. +""" +import json +import os +import struct +import subprocess +import sys +import tempfile + +TOOLS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools") +sys.path.insert(0, TOOLS) +import feature_scan as F # noqa: E402 + +failures = 0 + + +def check(cond, what): + global failures + print(("PASS " if cond else "FAIL ") + what) + failures += not cond + + +def signature(streams): + """ISG1/OSG1 payload: count, first-element offset, 32-byte elements with the stream index first.""" + body = struct.pack(" Vulkan layer may need (docs/d3d12_vulkan.md §8.2 #10 and #14). + + python -I tools/feature_scan.py /shaders [--out feature_scan.json] + +Reads what the shaders stage of make_game.py leaves in /shaders, and prints counts only: + +- dxbc/index.json and the .dxbc files: the DXIL program kind of every shader (hull, domain and amplification + stages would show up here), the SFI0 feature flags (D3D_SHADER_REQUIRES_* from the Windows SDK's d3d12shader.h, + among them WAVE_MMA and SHADING_RATE), and the output-signature (OSG1) stream index of every element: stream + output to a stream other than 0 needs a geometry shader writing that stream. +- dxbc/disasm/*.s (shader_disasm.py): the native RDNA2 instructions that mean wave MMA (v_mfma*, v_wmma*, + v_smfmac*) or GDS / ordered-count traffic (the hardware path NGG stream output uses on RDNA2). +- spirv/index.json (rdna2spirv.py): uses_code_base per stage. A graphics PSO can only need two code bases + (§5.2) if two of its stages use one; this gives the per-stage counts. Which stages are paired in one PSO is in + the executable, not in shaders.rpf. + +Standard library only. Nothing from the game is printed or written: names, code and data stay in the work folder. +""" +import argparse +import json +import os +import re +import struct +import sys +from collections import Counter, defaultdict + +# d3d12shader.h (Windows SDK 10.0.26100.0), D3D_SHADER_REQUIRES_*: the SFI0 part is this 64-bit mask. +SFI0_FLAGS = { + 0x1: "DOUBLES", 0x2: "EARLY_DEPTH_STENCIL", 0x4: "UAVS_AT_EVERY_STAGE", 0x8: "64_UAVS", + 0x10: "MINIMUM_PRECISION", 0x20: "11_1_DOUBLE_EXTENSIONS", 0x40: "11_1_SHADER_EXTENSIONS", + 0x80: "LEVEL_9_COMPARISON_FILTERING", 0x100: "TILED_RESOURCES", 0x200: "STENCIL_REF", 0x400: "INNER_COVERAGE", + 0x800: "TYPED_UAV_LOAD_ADDITIONAL_FORMATS", 0x1000: "ROVS", + 0x2000: "VIEWPORT_AND_RT_ARRAY_INDEX_FROM_ANY_SHADER_FEEDING_RASTERIZER", 0x4000: "WAVE_OPS", + 0x8000: "INT64_OPS", 0x10000: "VIEW_ID", 0x20000: "BARYCENTRICS", 0x40000: "NATIVE_16BIT_OPS", + 0x80000: "SHADING_RATE", 0x100000: "RAYTRACING_TIER_1_1", 0x200000: "SAMPLER_FEEDBACK", + 0x400000: "ATOMIC_INT64_ON_TYPED_RESOURCE", 0x800000: "ATOMIC_INT64_ON_GROUP_SHARED", + 0x1000000: "DERIVATIVES_IN_MESH_AND_AMPLIFICATION_SHADERS", 0x2000000: "RESOURCE_DESCRIPTOR_HEAP_INDEXING", + 0x4000000: "SAMPLER_DESCRIPTOR_HEAP_INDEXING", 0x8000000: "WAVE_MMA", + 0x10000000: "ATOMIC_INT64_ON_DESCRIPTOR_HEAP_RESOURCE", 0x20000000: "ADVANCED_TEXTURE_OPS", + 0x40000000: "WRITEABLE_MSAA_TEXTURES", 0x80000000: "SAMPLE_CMP_GRADIENT_OR_BIAS", + 0x100000000: "EXTENDED_COMMAND_INFO", +} +# The ones §8.2 #10 asks about; always printed, also when zero. +WATCHED = ("WAVE_MMA", "SHADING_RATE", "VIEW_ID", "ROVS", "STENCIL_REF", "INNER_COVERAGE", "SAMPLER_FEEDBACK", + "RAYTRACING_TIER_1_1") +ALL_STAGES = ("vs", "ps", "gs", "hs", "ds", "cs", "ms", "as", "lib") + +MMA = re.compile(r"^\s*(v_mfma\w*|v_wmma\w*|v_smfmac\w*)\b") +ORDERED = re.compile(r"^\s*(ds_ordered_count|ds_gws_\w+|ds_append|ds_consume|ds_add_gs_reg\w*|ds_sub_gs_reg\w*)\b") +GDS = re.compile(r"^\s*ds_\w+\b[^;]*\bgds\b") + + +def parts(d: bytes) -> dict: + """DXBC part fourcc -> payload.""" + out = {} + for k in range(struct.unpack_from(" set: + """Stream index of every element of an ISG1/OSG1 signature (32-byte elements, stream first).""" + if len(sig) < 8: + return set() + count, first = struct.unpack_from(" dict: + stages = Counter() + flags = defaultdict(Counter) # flag -> stage -> shaders + gs_streams = Counter() + non_zero_stream = Counter() # stage -> shaders with an output element on a stream other than 0 + missing = 0 + for e in index: + stage = e.get("stage") or "?" + stages[stage] += 1 + path = os.path.join(dxbc_dir, e["file"]) + try: + with open(path, "rb") as f: + p = parts(f.read()) + except (OSError, struct.error): + missing += 1 + continue + if len(p.get("SFI0", b"")) >= 8: + mask = struct.unpack_from(" dict: + mma, ordered, gds = Counter(), Counter(), Counter() + mma_ops, ordered_ops = Counter(), Counter() + files = 0 + for fn in os.listdir(disasm_dir): + if not fn.endswith(".s"): + continue + files += 1 + stage = stage_of.get(fn[:-2], "?") + seen_mma = seen_ord = seen_gds = False + with open(os.path.join(disasm_dir, fn), encoding="utf-8", errors="replace") as f: + for line in f: + m = MMA.match(line) + if m: + mma_ops[m.group(1)] += 1 + seen_mma = True + m = ORDERED.match(line) + if m: + ordered_ops[m.group(1)] += 1 + seen_ord = True + if GDS.match(line): + seen_gds = True + mma[stage] += seen_mma + ordered[stage] += seen_ord + gds[stage] += seen_gds + nz = lambda c: {k: v for k, v in c.items() if v} + return {"files": files, "wave_mma_shaders": nz(mma), "wave_mma_ops": dict(mma_ops), + "ordered_or_gws_shaders": nz(ordered), "ordered_or_gws_ops": dict(ordered_ops), "gds_shaders": nz(gds)} + + +def scan_spirv(spirv_index: str) -> dict: + with open(spirv_index, encoding="utf-8") as f: + idx = json.load(f) + entries = idx.values() if isinstance(idx, dict) else idx + total, code_base = Counter(), Counter() + for m in entries: + if not isinstance(m, dict): + continue + stage = m.get("stage", "?") + total[stage] += 1 + code_base[stage] += bool(m.get("uses_code_base")) + return {"translated": dict(total), "uses_code_base": {k: v for k, v in code_base.items() if v}} + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("shaders", help="/shaders from make_game.py") + ap.add_argument("--out", help="also write the counts as JSON") + a = ap.parse_args() + + dxbc_dir = os.path.join(a.shaders, "dxbc") + with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8") as f: + index = json.load(f) + result = {"shaders": len(index), "dxbc": scan_dxbc(dxbc_dir, index)} + stage_of = {os.path.splitext(e["file"])[0]: e.get("stage") or "?" for e in index} + stage_of |= {e["name"]: e.get("stage") or "?" for e in index} + disasm = os.path.join(dxbc_dir, "disasm") + if os.path.isdir(disasm): + result["disasm"] = scan_disasm(disasm, stage_of) + spirv = os.path.join(a.shaders, "spirv", "index.json") + if os.path.isfile(spirv): + result["spirv"] = scan_spirv(spirv) + + d = result["dxbc"] + print(f"{result['shaders']} shaders") + print("DXIL stages:", ", ".join(f"{s} {n}" for s, n in d["stages"].items())) + for name in WATCHED: + print(f"SFI0 {name}: {sum(d['sfi0'].get(name, {}).values())} {d['sfi0'].get(name, {})}") + print("SFI0, every flag set anywhere:", {n: sum(v.values()) for n, v in d["sfi0"].items()}) + print("GS output-signature stream counts:", d["gs_output_stream_count"], + "| shaders with an output on a stream other than 0:", d["output_on_stream_other_than_0"] or 0) + if "disasm" in result: + s = result["disasm"] + print(f"disasm: {s['files']} files | wave MMA shaders {s['wave_mma_shaders'] or 0} | ordered-count/GWS shaders " + f"{s['ordered_or_gws_shaders'] or 0} {s['ordered_or_gws_ops'] or ''} | GDS shaders {s['gds_shaders'] or 0}") + else: + print("disasm: not there yet (run the shaders stage)") + if "spirv" in result: + s = result["spirv"] + print("uses_code_base by stage:", s["uses_code_base"], "of", s["translated"]) + else: + print("spirv/index.json: not there yet (run the shaders stage)") + if d["unreadable"]: + print(f"{d['unreadable']} .dxbc files could not be read") + if a.out: + with open(a.out, "w", encoding="utf-8") as f: + json.dump(result, f, indent=1) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 40a7edaef3f85e7b7f465b5dd22c6d93f0fd8d3a Mon Sep 17 00:00:00 2001 From: NWX10 <179748639+NWX10@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:38:00 +0300 Subject: [PATCH 15/53] world_census: reject --shard-size and --jobs below 1 --shard-size 0 (or a negative size) never finished planning shards: pos never advanced, so the list grew until memory ran out. --jobs 0 crashed with a ValueError traceback from ProcessPoolExecutor. Both flags now take a positive_int, so argparse exits 2 with "must be at least 1". _expected_shards also raises ValueError for a size below 1, for callers that skip the CLI. Tests: the CLI cases run in a subprocess with a timeout, and the planner case counts additions, so a regression fails instead of hanging. Co-Authored-By: Claude Opus 5.5 --- tests/test_world_census.py | 42 ++++++++++++++++++++++++++++++++++++++ tools/world_census.py | 17 +++++++++++++-- 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/tests/test_world_census.py b/tests/test_world_census.py index 23fa5eb23..0c6d79d5e 100644 --- a/tests/test_world_census.py +++ b/tests/test_world_census.py @@ -6,6 +6,8 @@ import importlib.util import json import os import struct +import subprocess +import sys import tempfile import unittest import zlib @@ -102,5 +104,45 @@ class WorldCensusTest(unittest.TestCase): self.assertGreater(WC.required_len(blob[:0x150]), 0x150) +class CensusArgumentTest(unittest.TestCase): + """--shard-size 0 planned shards forever (memory grew without bound); --jobs 0 crashed in ProcessPoolExecutor.""" + + def test_expected_shards_rejects_a_size_below_one(self): + self.assertEqual(WC._expected_shards(0, 10, 4), + [{"index": 0, "start": 0, "end": 4}, {"index": 1, "start": 4, "end": 8}, + {"index": 2, "start": 8, "end": 10}]) + + class Counted(int): + """Counts pos + shard_size, so a missing guard fails here instead of looping forever.""" + adds = 0 + + def __radd__(self, other): + Counted.adds += 1 + if Counted.adds > 1000: + raise RuntimeError("shard planning never finished") + return other + int(self) + + for size in (0, -5): + Counted.adds = 0 + with self.subTest(size=size), self.assertRaises(ValueError): + WC._expected_shards(0, 10, Counted(size)) + + def test_cli_rejects_shard_size_and_jobs_below_one(self): + with tempfile.TemporaryDirectory() as tmp: + arc = os.path.join(tmp, "sample.rpf") + make_archive(arc) + out = os.path.join(tmp, "out") + tool = os.path.join(ROOT, "tools", "world_census.py") + for flag, value in (("--shard-size", "0"), ("--shard-size", "-1"), ("--jobs", "0")): + with self.subTest(flag=flag, value=value): + # A subprocess with a timeout, so the old endless loop fails the test instead of hanging it. + p = subprocess.run([sys.executable, "-I", tool, arc, "--out", out, flag, value], + capture_output=True, text=True, timeout=10) + self.assertEqual(p.returncode, 2, p.stderr) + self.assertIn("must be at least 1", p.stderr) + self.assertNotIn("Traceback", p.stderr) + self.assertFalse(os.path.exists(out)) + + if __name__ == "__main__": unittest.main() diff --git a/tools/world_census.py b/tools/world_census.py index 651733473..e63eef84b 100644 --- a/tools/world_census.py +++ b/tools/world_census.py @@ -495,6 +495,8 @@ def _audit_gap(m, a, b, result, allow_zlib): def _expected_shards(start, end, shard_size): + if shard_size < 1: # pos would never advance, and the list would grow until memory ran out + raise ValueError(f"shard_size must be at least 1, not {shard_size}") out = [] index = 0 pos = start @@ -626,12 +628,23 @@ def summarize(archive, outdir, start, end, shard_size, data_start): return summary +def positive_int(text): + """--shard-size 0 or less never finished planning shards, and --jobs 0 made ProcessPoolExecutor raise.""" + try: + value = int(text) + except ValueError: + raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None + if value < 1: + raise argparse.ArgumentTypeError("must be at least 1") + return value + + def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("archive") ap.add_argument("--out", default=os.path.join("work", "world", "census")) - ap.add_argument("--shard-size", type=int, default=2 << 30) - ap.add_argument("--jobs", type=int, default=max(1, min(12, (os.cpu_count() or 2) // 2))) + ap.add_argument("--shard-size", type=positive_int, default=2 << 30) + ap.add_argument("--jobs", type=positive_int, default=max(1, min(12, (os.cpu_count() or 2) // 2))) ap.add_argument("--start", type=int) ap.add_argument("--limit", type=int) ap.add_argument("--resume", action="store_true") From e8a07da4ffc3053043ca56c1f700b079a68b7f60 Mon Sep 17 00:00:00 2001 From: S1m0ne1997 <347981799+S1m0ne1997@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:12:07 +0100 Subject: [PATCH 16/53] =?UTF-8?q?feature=5Fscan:=20count=20s=5Fgetpc=5Fb64?= =?UTF-8?q?=20kept=20for=20code-embedded=20data=20per=20stage;=20d3d12=5Fv?= =?UTF-8?q?ulkan.md:=20answer=20=C2=A78.2=20#10,=20per-stage=20counts=20fo?= =?UTF-8?q?r=20#14,=20tiled=20resources=20for=20#18?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 14 ++++++++++---- tests/test_feature_scan.py | 9 +++++++-- tools/feature_scan.py | 17 +++++++++++++++-- 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 0ef4012c9..e052cbfd8 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -802,7 +802,7 @@ to be recovered from call sites (or the NDA GDK headers, if a developer has acce | PresentX / present planes | Public game-streaming docs | Compose planes into the swapchain; stub until the trace shows the call. **Open** slot/layout. | | VRS | Public `D3D12_SHADING_RATE` / `D3D12_AXIS_SHADING_RATE` | `VK_KHR_fragment_shading_rate`; `RSSetShadingRate`/image-based rate map to `vkCmdSetFragmentShadingRateKHR`. | | Mesh shader tier | Public `D3D12_MESH_SHADER_TIER` | `VK_EXT_mesh_shader`; the 9,282 translated mesh shaders make this a hard requirement for any content that uses them. | -| Wave MMA | Public `D3D12_WAVE_MMA_TIER` | If shaders use `v_mfma`, map to `VK_KHR_cooperative_matrix` or emulate. Not seen in the translator's coverage list; **Open**. | +| Wave MMA | Public `D3D12_WAVE_MMA_TIER` | Not used: no shader sets `WAVE_MMA` in SFI0 and none contains `v_mfma`/`v_wmma` (all 26,503, `tools/feature_scan.py`). Answer the tier query truthfully; no cooperative-matrix mapping is needed. | | Enhanced barriers | Public Xbox Series `D3D12_BARRIER_GROUP` | `VK_KHR_synchronization2`; implement directly. | | XDXR batched/streaming BVH | `XboxBvhBuilder.dll` exports | See 4.8. | @@ -879,8 +879,14 @@ contract, not a runtime bug: adds a descriptor binding and a load per `s_getpc`, but avoids growing push constants. Decide after measuring how many real PSOs have two code-base stages. +Measured per stage (all 26,503, `tools/feature_scan.py`): `s_getpc_b64` is kept to read code-embedded data in 54 +VS, 93 PS, 266 MS and 263 CS (0 GS); the 147 VS/PS match the translator's own note. Both stages of a VS+PS or +MS+PS pipeline can therefore need a code base. + **Measured:** across the GPU test fleet (Issue #166), desktop NVIDIA (Turing, Ampere, Ada, Blackwell: 256 bytes), desktop AMD (RDNA2: 256 bytes) and Apple Silicon (MoltenVK: 4096 bytes) all satisfy the 144-byte contract natively (`maxPushConstantsSize >= 144`). On Intel Arc (Alchemist, Battlemage), Vulkan exposes the 128-byte specification minimum (`maxPushConstantsSize == 128`), which cannot fit the 16-byte tail (dwords 32–35: heap base and code base) inside push constants. The runtime detects `maxPushConstantsSize < 144` at device creation (`d3d12_vulkan_device.cpp`) and flags `push_constants_need_fallback` for the uniform-buffer fallback. +**Open:** the exact count of such PSOs; the pairing is in the executable, not in `shaders.rpf`. + ### 5.3 Descriptor T#/S# parsing The runtime needs a C++ decoder for the structures the shaders read. The fields it needs: @@ -1057,15 +1063,15 @@ Xodus is LGPL-2.1 and is cited only for its coverage number, not as a code sourc | 7 | Does the game build acceleration structures through the standard D3D12 calls or through `XboxBvhBuilder`'s own compute path? | Log `BuildRaytracingAccelerationStructure`, `CopyRaytracingAccelerationStructure`, `Emit...PostbuildInfo`, and the builder's command-list method calls on the first RT frame. The builder's 53 shaders are Xbox DXIL; 44/53 fail the PC compiler and 22 have been lowered. If the builder path is used, the layer needs a DXIL plan. | | 8 | What are the layouts of `D3D12XBOX_XDXR_STREAM_DESC`, the batched build desc, and the offline statistics desc? | Recover from the builder's call sites, or use the NDA GDK headers if available. Do not guess; a wrong layout corrupts memory. | | 9 | Xbox texture creation is device slot 76 with layout `0x101` (tiled) or `0x1` (row-major). What is the tiled data layout, and does the game upload console-tiled or DCC data? | Trace slot 76, `CopyTextureRegion` and the resource descs. If the game uploads console-tiled data, add a detile step or a matching layout. | -| 10 | Does the game use binning, DCC, VRS, wave MMA, stream output, tessellation, or amplification shaders? | Scan the PSO/stream subobjects and the shader corpus. Ignore binning for correctness; implement VRS/mesh if present; map WMMA only if `v_mfma` appears. | +| 10 | Does the game use binning, DCC, VRS, wave MMA, stream output, tessellation, or amplification shaders? | **Shaders: answered** by `tools/feature_scan.py` over all 26,503 (1.0.2.1): no hull, domain or amplification shader (DXIL program kinds: 2,236 VS, 12,101 PS, 195 GS, 2,689 CS, 9,282 MS); no `WAVE_MMA` or `SHADING_RATE` in any SFI0, and no `v_mfma`/`v_wmma`/`v_smfmac` in the disassembly; no output-signature element on a stream other than 0 (all 195 GS write stream 0 only) and no GDS / `ds_ordered_count` / GWS instruction, so no stream-output path. Also from SFI0: 10 PS need ROVs (pixel interlock), 30 shaders `TILED_RESOURCES` (see #18), 685 `ATOMIC_INT64_ON_TYPED_RESOURCE`. Binning and DCC are not shader-visible; they stay open for the PSO/stream subobjects. | | 11 | What should `CheckFeatureSupport` answer for UMA, resource binding tier, mesh tier, RT tier? | **Implemented** (D3D-11). Reports truthful host architecture (discrete desktop GPU: non-UMA), ResourceBindingTier 3 (descriptor indexing / bindless support), 48-bit GPU virtual address support matching the arena, and maps `D3D12_FEATURE_FORMAT_SUPPORT` directly to `vkGetPhysicalDeviceFormatProperties`. | | 12 | Does the game rely on async compute or copy queues for correctness? | Trace queue creation and cross-queue fences. If only performance, serialize on one queue for boot. | | 13 | Is 144 bytes of push constants available on all target GPUs? | **Resolved / Measured** (D3D-14). Checked at device creation in `runtime/shims/d3d12_vulkan_device.cpp`. Measured across the test fleet (#166): NVIDIA (256 B), AMD (256 B), and Apple M1/MoltenVK (4096 B) satisfy 144 B natively; Intel Arc exposes only the core minimum 128 B (`maxPushConstantsSize == 128`). Below 144 B, the device logs a warning and marks `push_constants_need_fallback`, routing the 16-byte tail (dwords 32..35: heap base and code base) to a uniform-buffer fallback. | -| 14 | Are there PSOs with two code-base stages? | Count from the PSO/shader hash table and the index metadata. If yes, implement per-stage code-base slots (section 5.2). | +| 14 | Are there PSOs with two code-base stages? | Count from the PSO/shader hash table and the index metadata. If yes, implement per-stage code-base slots (section 5.2). **Per stage, measured** (`tools/feature_scan.py`, `s_getpc_b64` kept for data rather than a far branch): 54 VS, 93 PS, 266 MS, 263 CS, 0 GS. So VS+PS and MS+PS pipelines with two code-base stages are possible; whether any exists depends on which shaders a PSO pairs, which is in the executable, not in `shaders.rpf`. | | 15 | Is `ExecuteIndirect` used with signatures Vulkan cannot express directly? | Trace `CreateCommandSignature` and `ExecuteIndirect`; implement simple signatures first, expand the complex ones with compute. | | 16 | Does the game use append/consume UAV counters or typed buffer formats the translator does not model? | Trace UAV descs and shader `buffer_*` ops; extend the translator/runtime together. | | 17 | Do upload/readback resources ever reach shaders (as vertex/index buffers or descriptors), and does the `-heap_base` bias work for them? | Trace `CreateCommittedResource` heap types and every VB/IB/descriptor that points at an upload resource; test the bias with a synthetic draw. | -| 18 | Does the game alias buffers/images in a heap, or use reserved/tiled resources? | Trace `CreatePlacedResource` ranges, aliasing barriers, `CreateReservedResource` and tile mappings. If yes, implement shared memory per heap range or fall back to linear allocations with a clear log. | +| 18 | Does the game alias buffers/images in a heap, or use reserved/tiled resources? | Trace `CreatePlacedResource` ranges, aliasing barriers, `CreateReservedResource` and tile mappings. If yes, implement shared memory per heap range or fall back to linear allocations with a clear log. Shaders: 30 declare `TILED_RESOURCES` in SFI0 (`tools/feature_scan.py`), so reserved/tiled resources are likely used. | | 19 | What do the `0x03000000` root-signature flag bits mean? | Masking them on a copy works around the PC serializer; the semantics remain unknown. Compare against the public flag enum and observe the game's behaviour with and without the mask. | | 20 | Which of the BVH builder's 53 Xbox DXIL shaders does the game actually use, and can the 31 raw-address shaders be lowered without a reference? | Dump the slot-62 compute PSOs on the first RT frame; lower and compile each; compare against the builder's CPU validation (`CpuValidateResultX`) or a captured reference. | diff --git a/tests/test_feature_scan.py b/tests/test_feature_scan.py index 070d44246..d165ef9f1 100644 --- a/tests/test_feature_scan.py +++ b/tests/test_feature_scan.py @@ -56,6 +56,9 @@ def build(root): ("b_gs", "gs", 0, [0, 1], "\tds_ordered_count v0, v1 offset:772 gds\n\ts_endpgm\n"), ("c_cs", "cs", 0x8000000, [], "\tv_mfma_f32_32x32x8f16 a[0:15], v[0:1], v[2:3], a[0:15]\n\ts_endpgm\n"), ("d_vs", "vs", 0, [0], None), + # s_getpc for data (the address is kept and offset), and s_getpc for a far branch (setpc follows) + ("e_vs", "vs", 0, [0], "\ts_getpc_b64 s[4:5]\n\ts_add_u32 s4, s4, 0x40\n\ts_load_dword s6, s[4:5], 0x0\n\ts_endpgm\n"), + ("f_ps", "ps", 0, [0], "\ts_getpc_b64 s[4:5]\n\ts_add_u32 s4, s4, 0x40\n\ts_addc_u32 s5, s5, 0\n\ts_setpc_b64 s[4:5]\n"), ] index = [] for name, stage, mask, streams, listing in shaders: @@ -76,7 +79,7 @@ def build(root): with tempfile.TemporaryDirectory() as tmp: sh, index = build(tmp) d = F.scan_dxbc(os.path.join(sh, "dxbc"), index) - check(d["stages"]["ps"] == 1 and d["stages"]["gs"] == 1 and d["stages"]["hs"] == 0 and d["stages"]["as"] == 0, + check(d["stages"]["ps"] == 2 and d["stages"]["gs"] == 1 and d["stages"]["hs"] == 0 and d["stages"]["as"] == 0, "stage census counts each stage and lists the absent ones as 0") check(d["sfi0"].get("ROVS") == {"ps": 1} and d["sfi0"].get("SHADING_RATE") == {"ps": 1}, "SFI0 bits 0x1000 and 0x80000 decode to ROVS and SHADING_RATE") @@ -86,7 +89,9 @@ with tempfile.TemporaryDirectory() as tmp: stage_of = {e["name"]: e["stage"] for e in index} s = F.scan_disasm(os.path.join(sh, "dxbc", "disasm"), stage_of) - check(s["files"] == 3, "three listings scanned") + check(s["files"] == 5, "five listings scanned") + check(s["getpc_for_data_shaders"] == {"vs": 1}, + "s_getpc kept for data counts as a code base, s_getpc into s_setpc (far branch) does not") check(s["wave_mma_shaders"] == {"cs": 1} and "v_mfma_f32_32x32x8f16" in s["wave_mma_ops"], "v_mfma is found") check(s["ordered_or_gws_shaders"] == {"gs": 1} and s["gds_shaders"] == {"gs": 1}, "ds_ordered_count with gds is found") diff --git a/tools/feature_scan.py b/tools/feature_scan.py index 626dcea78..32f385e94 100644 --- a/tools/feature_scan.py +++ b/tools/feature_scan.py @@ -100,8 +100,14 @@ def scan_dxbc(dxbc_dir: str, index: list) -> dict: "unreadable": missing} +def getpc_for_data(ops: list) -> bool: + """s_getpc_b64 not followed within three instructions by s_setpc_b64: the address is used to read data + embedded in the code (a code base), not for a far branch (getpc; add/sub; addc/subb; setpc).""" + return any(op == "s_getpc_b64" and "s_setpc_b64" not in ops[i + 1:i + 4] for i, op in enumerate(ops)) + + def scan_disasm(disasm_dir: str, stage_of: dict) -> dict: - mma, ordered, gds = Counter(), Counter(), Counter() + mma, ordered, gds, code_data = Counter(), Counter(), Counter(), Counter() mma_ops, ordered_ops = Counter(), Counter() files = 0 for fn in os.listdir(disasm_dir): @@ -110,8 +116,12 @@ def scan_disasm(disasm_dir: str, stage_of: dict) -> dict: files += 1 stage = stage_of.get(fn[:-2], "?") seen_mma = seen_ord = seen_gds = False + ops = [] with open(os.path.join(disasm_dir, fn), encoding="utf-8", errors="replace") as f: for line in f: + head = line.split(None, 1) + if head and not head[0].startswith((";", ".")): + ops.append(head[0]) m = MMA.match(line) if m: mma_ops[m.group(1)] += 1 @@ -125,9 +135,11 @@ def scan_disasm(disasm_dir: str, stage_of: dict) -> dict: mma[stage] += seen_mma ordered[stage] += seen_ord gds[stage] += seen_gds + code_data[stage] += getpc_for_data(ops) nz = lambda c: {k: v for k, v in c.items() if v} return {"files": files, "wave_mma_shaders": nz(mma), "wave_mma_ops": dict(mma_ops), - "ordered_or_gws_shaders": nz(ordered), "ordered_or_gws_ops": dict(ordered_ops), "gds_shaders": nz(gds)} + "ordered_or_gws_shaders": nz(ordered), "ordered_or_gws_ops": dict(ordered_ops), "gds_shaders": nz(gds), + "getpc_for_data_shaders": nz(code_data)} def scan_spirv(spirv_index: str) -> dict: @@ -175,6 +187,7 @@ def main() -> int: s = result["disasm"] print(f"disasm: {s['files']} files | wave MMA shaders {s['wave_mma_shaders'] or 0} | ordered-count/GWS shaders " f"{s['ordered_or_gws_shaders'] or 0} {s['ordered_or_gws_ops'] or ''} | GDS shaders {s['gds_shaders'] or 0}") + print("s_getpc_b64 used for code-embedded data (not a far branch), by stage:", s["getpc_for_data_shaders"] or 0) else: print("disasm: not there yet (run the shaders stage)") if "spirv" in result: From 1f48889812bf22ec2d416735d70318efd2d727b9 Mon Sep 17 00:00:00 2001 From: S1m0ne1997 <347981799+S1m0ne1997@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:24:43 +0100 Subject: [PATCH 17/53] d3d12_vulkan.md: the translator's uses_code_base confirms the per-stage code-base counts AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e052cbfd8..db12c0ad1 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1067,7 +1067,7 @@ Xodus is LGPL-2.1 and is cited only for its coverage number, not as a code sourc | 11 | What should `CheckFeatureSupport` answer for UMA, resource binding tier, mesh tier, RT tier? | **Implemented** (D3D-11). Reports truthful host architecture (discrete desktop GPU: non-UMA), ResourceBindingTier 3 (descriptor indexing / bindless support), 48-bit GPU virtual address support matching the arena, and maps `D3D12_FEATURE_FORMAT_SUPPORT` directly to `vkGetPhysicalDeviceFormatProperties`. | | 12 | Does the game rely on async compute or copy queues for correctness? | Trace queue creation and cross-queue fences. If only performance, serialize on one queue for boot. | | 13 | Is 144 bytes of push constants available on all target GPUs? | **Resolved / Measured** (D3D-14). Checked at device creation in `runtime/shims/d3d12_vulkan_device.cpp`. Measured across the test fleet (#166): NVIDIA (256 B), AMD (256 B), and Apple M1/MoltenVK (4096 B) satisfy 144 B natively; Intel Arc exposes only the core minimum 128 B (`maxPushConstantsSize == 128`). Below 144 B, the device logs a warning and marks `push_constants_need_fallback`, routing the 16-byte tail (dwords 32..35: heap base and code base) to a uniform-buffer fallback. | -| 14 | Are there PSOs with two code-base stages? | Count from the PSO/shader hash table and the index metadata. If yes, implement per-stage code-base slots (section 5.2). **Per stage, measured** (`tools/feature_scan.py`, `s_getpc_b64` kept for data rather than a far branch): 54 VS, 93 PS, 266 MS, 263 CS, 0 GS. So VS+PS and MS+PS pipelines with two code-base stages are possible; whether any exists depends on which shaders a PSO pairs, which is in the executable, not in `shaders.rpf`. | +| 14 | Are there PSOs with two code-base stages? | Count from the PSO/shader hash table and the index metadata. If yes, implement per-stage code-base slots (section 5.2). **Per stage, measured** (`tools/feature_scan.py`, `s_getpc_b64` kept for data rather than a far branch): 54 VS, 93 PS, 266 MS, 263 CS, 0 GS; the translator's `uses_code_base` gives the same counts (with LLVM 23 that needs #223, without which these 1,471 shaders are rejected). So VS+PS and MS+PS pipelines with two code-base stages are possible; whether any exists depends on which shaders a PSO pairs, which is in the executable, not in `shaders.rpf`. | | 15 | Is `ExecuteIndirect` used with signatures Vulkan cannot express directly? | Trace `CreateCommandSignature` and `ExecuteIndirect`; implement simple signatures first, expand the complex ones with compute. | | 16 | Does the game use append/consume UAV counters or typed buffer formats the translator does not model? | Trace UAV descs and shader `buffer_*` ops; extend the translator/runtime together. | | 17 | Do upload/readback resources ever reach shaders (as vertex/index buffers or descriptors), and does the `-heap_base` bias work for them? | Trace `CreateCommittedResource` heap types and every VB/IB/descriptor that points at an upload resource; test the bias with a synthetic draw. | From b08051bcbc0c2a2c74983dcb58a79a3f447e55bb Mon Sep 17 00:00:00 2001 From: S1m0ne1997 <347981799+S1m0ne1997@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:29:24 +0100 Subject: [PATCH 18/53] test_feature_scan: run as a pytest test as well as a script (pytest collection hit the module-level sys.exit) AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- tests/test_feature_scan.py | 65 ++++++++++++++++++++++---------------- 1 file changed, 37 insertions(+), 28 deletions(-) diff --git a/tests/test_feature_scan.py b/tests/test_feature_scan.py index d165ef9f1..0744f9c55 100644 --- a/tests/test_feature_scan.py +++ b/tests/test_feature_scan.py @@ -76,35 +76,44 @@ def build(root): return sh, index -with tempfile.TemporaryDirectory() as tmp: - sh, index = build(tmp) - d = F.scan_dxbc(os.path.join(sh, "dxbc"), index) - check(d["stages"]["ps"] == 2 and d["stages"]["gs"] == 1 and d["stages"]["hs"] == 0 and d["stages"]["as"] == 0, - "stage census counts each stage and lists the absent ones as 0") - check(d["sfi0"].get("ROVS") == {"ps": 1} and d["sfi0"].get("SHADING_RATE") == {"ps": 1}, - "SFI0 bits 0x1000 and 0x80000 decode to ROVS and SHADING_RATE") - check(d["sfi0"].get("WAVE_MMA") == {"cs": 1}, "SFI0 bit 0x8000000 decodes to WAVE_MMA") - check(d["output_on_stream_other_than_0"] == {"gs": 1} and d["gs_output_stream_count"] == {2: 1}, - "an OSG1 element on stream 1 is counted, stream 0 alone is not") +def test_feature_scan(): + """Runs under pytest (CI's translator-tests job) and as a plain script.""" + with tempfile.TemporaryDirectory() as tmp: + sh, index = build(tmp) + d = F.scan_dxbc(os.path.join(sh, "dxbc"), index) + check(d["stages"]["ps"] == 2 and d["stages"]["gs"] == 1 and d["stages"]["hs"] == 0 and d["stages"]["as"] == 0, + "stage census counts each stage and lists the absent ones as 0") + check(d["sfi0"].get("ROVS") == {"ps": 1} and d["sfi0"].get("SHADING_RATE") == {"ps": 1}, + "SFI0 bits 0x1000 and 0x80000 decode to ROVS and SHADING_RATE") + check(d["sfi0"].get("WAVE_MMA") == {"cs": 1}, "SFI0 bit 0x8000000 decodes to WAVE_MMA") + check(d["output_on_stream_other_than_0"] == {"gs": 1} and d["gs_output_stream_count"] == {2: 1}, + "an OSG1 element on stream 1 is counted, stream 0 alone is not") - stage_of = {e["name"]: e["stage"] for e in index} - s = F.scan_disasm(os.path.join(sh, "dxbc", "disasm"), stage_of) - check(s["files"] == 5, "five listings scanned") - check(s["getpc_for_data_shaders"] == {"vs": 1}, - "s_getpc kept for data counts as a code base, s_getpc into s_setpc (far branch) does not") - check(s["wave_mma_shaders"] == {"cs": 1} and "v_mfma_f32_32x32x8f16" in s["wave_mma_ops"], "v_mfma is found") - check(s["ordered_or_gws_shaders"] == {"gs": 1} and s["gds_shaders"] == {"gs": 1}, - "ds_ordered_count with gds is found") - check("ps" not in s["wave_mma_shaders"] and "ps" not in s["gds_shaders"], "a plain listing has neither") + stage_of = {e["name"]: e["stage"] for e in index} + s = F.scan_disasm(os.path.join(sh, "dxbc", "disasm"), stage_of) + check(s["files"] == 5, "five listings scanned") + check(s["getpc_for_data_shaders"] == {"vs": 1}, + "s_getpc kept for data counts as a code base, s_getpc into s_setpc (far branch) does not") + check(s["wave_mma_shaders"] == {"cs": 1} and "v_mfma_f32_32x32x8f16" in s["wave_mma_ops"], "v_mfma is found") + check(s["ordered_or_gws_shaders"] == {"gs": 1} and s["gds_shaders"] == {"gs": 1}, + "ds_ordered_count with gds is found") + check("ps" not in s["wave_mma_shaders"] and "ps" not in s["gds_shaders"], "a plain listing has neither") - sp = F.scan_spirv(os.path.join(sh, "spirv", "index.json")) - check(sp["uses_code_base"] == {"ps": 1} and sp["translated"] == {"ps": 1, "vs": 1}, "uses_code_base per stage") + sp = F.scan_spirv(os.path.join(sh, "spirv", "index.json")) + check(sp["uses_code_base"] == {"ps": 1} and sp["translated"] == {"ps": 1, "vs": 1}, "uses_code_base per stage") - r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "feature_scan.py"), sh, "--out", - os.path.join(tmp, "out.json")], capture_output=True, text=True) - check(r.returncode == 0 and "SFI0 WAVE_MMA: 1" in r.stdout and "hs 0" in r.stdout, "the CLI prints the summary") - check(os.path.isfile(os.path.join(tmp, "out.json")), "--out writes the JSON") - check("a_ps" not in r.stdout and "b_gs" not in r.stdout, "the summary prints counts, not shader names") + r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "feature_scan.py"), sh, "--out", + os.path.join(tmp, "out.json")], capture_output=True, text=True) + check(r.returncode == 0 and "SFI0 WAVE_MMA: 1" in r.stdout and "hs 0" in r.stdout, "the CLI prints the summary") + check(os.path.isfile(os.path.join(tmp, "out.json")), "--out writes the JSON") + check("a_ps" not in r.stdout and "b_gs" not in r.stdout, "the summary prints counts, not shader names") + assert failures == 0, f"{failures} feature_scan check(s) failed" -print(f"test_feature_scan: {'OK' if not failures else 'FAILED'} ({failures} failure{'s' if failures != 1 else ''})") -sys.exit(1 if failures else 0) + +if __name__ == "__main__": + try: + test_feature_scan() + except AssertionError: + pass + print(f"test_feature_scan: {'OK' if not failures else 'FAILED'} ({failures} failure{'s' if failures != 1 else ''})") + sys.exit(1 if failures else 0) From 186d8793cddc7a017d83e17294a99361baf8760e Mon Sep 17 00:00:00 2001 From: S1m0ne1997 <347981799+S1m0ne1997@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:39:19 +0100 Subject: [PATCH 19/53] feature_scan: say which DS counter ops the ordered/GWS group includes AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- tools/feature_scan.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/feature_scan.py b/tools/feature_scan.py index 32f385e94..1becef3a7 100644 --- a/tools/feature_scan.py +++ b/tools/feature_scan.py @@ -46,6 +46,8 @@ WATCHED = ("WAVE_MMA", "SHADING_RATE", "VIEW_ID", "ROVS", "STENCIL_REF", "INNER_ ALL_STAGES = ("vs", "ps", "gs", "hs", "ds", "cs", "ms", "as", "lib") MMA = re.compile(r"^\s*(v_mfma\w*|v_wmma\w*|v_smfmac\w*)\b") +# Ordered count, GWS and the GS-register adds are the GDS-side instructions NGG stream output relies on. ds_append / +# ds_consume are included as the other counter-style DS ops (LDS unless they carry `gds`, which GDS below catches). ORDERED = re.compile(r"^\s*(ds_ordered_count|ds_gws_\w+|ds_append|ds_consume|ds_add_gs_reg\w*|ds_sub_gs_reg\w*)\b") GDS = re.compile(r"^\s*ds_\w+\b[^;]*\bgds\b") From 44a94f35ca53fd5621fd7ce7cf2a72b913b4fd7b Mon Sep 17 00:00:00 2001 From: Luis Baker <57847961+luisbaker@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:40:45 +0100 Subject: [PATCH 20/53] Runtime: widen enhanced-barrier stages so every access has a stage that can perform it D3D12 lets an access be named with a sync scope whose Vulkan stages cannot perform it: SYNC_ALL_SHADING with ACCESS_VERTEX_BUFFER is valid D3D12, but VERTEX_ATTRIBUTE_READ needs VERTEX_ATTRIBUTE_INPUT. Vulkan rejects such barriers (docs/d3d12_vulkan.md listed it as a known gap). vulkan_barrier_scope maps each side of a global, buffer or texture barrier and adds the narrowest stage that supports any access left without one (the synchronization2 "supported access types" table). The access is never dropped, so the dependency still covers everything the application named. CLEAR only writes, and ALL_GRAPHICS holds no transfer stage, so transfer reads get ALL_TRANSFER. vk_command_replay_test part D records all 360 D3D12 sync/access pairs as global, buffer and texture barriers: 462 validation errors before, 0 after, on Intel(R) Graphics. d3d12_state_map_test checks that stages only grow, accesses never change, and pairs Vulkan already accepts are left alone. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 21 ++++- runtime/src/vulkan_replay.h | 104 ++++++++++++++++++++++-- runtime/test/d3d12_state_map_test.cpp | 40 +++++++++ runtime/test/vk_command_replay_test.cpp | 76 ++++++++++++++++- 4 files changed, 229 insertions(+), 12 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 0ef4012c9..8524e2696 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -243,8 +243,7 @@ Known gaps: shader-resource, UAV and constant-buffer views, samplers, root signa views, placed and reserved resources, `GetGPUVirtualAddress` (the shared buffer arena), depth-stencil resolves and `ResolveSubresourceRegion`, 1D textures and the swapchain; default-heap buffers are not zero-filled yet; a fence cannot be signalled to a lower value (Vulkan timelines only -increase; such a signal is reported and dropped); enhanced-barrier access bits are not filtered against the -sync scope, so a combination D3D12 accepts but Vulkan does not would show up as a validation error; the GCL8 +increase; such a signal is reported and dropped); the GCL8 front/back stencil references are recorded but not applied, because there is no pipeline or draw path for them to affect. @@ -266,6 +265,9 @@ and any validation error fails them. and read back; a 4x multisampled target cleared and resolved; and the copies and resolves that must be refused (a z range past the volume or its footprint, a footprint past the buffer, a resolve from a single-sampled texture or into another size, a multisampled texture copied to a footprint or to another sample count). +- `vk_command_replay_test`, part D: every D3D12 sync bit against every access bit (360 pairs), each as a global, + a buffer and a texture barrier. Under the validation layer none may be rejected; before + `vulkan_barrier_scope` there were 462 validation errors on Intel(R) Graphics. - `vk_bindless_test` (run by `runtime/test/shaders/check.py` and `scripts/run_gpu_tests.py`): the translator's own lookup against the table and the set. `ps_tex.asm`, a hand-written RDNA2 pixel shader built by `build.py`, loads a T# and an S# from a descriptor table and samples. The test draws the gradient with the T# at the fourth @@ -681,6 +683,21 @@ mapped stages/accesses, and if no single layout serves all uses, use `GENERAL` a `VkPipelineStageFlags2`, `VkAccessFlags2` and `VkImageLayout` (`vulkan_sync`, `vulkan_barrier_access`, `vulkan_layout`). Queue-specific layouts map like their generic forms; ray tracing, video and split scopes use `ALL_COMMANDS`; `LayoutBefore = UNDEFINED` or the discard flag becomes `oldLayout = UNDEFINED`. +- Access bits and sync scopes are not one-to-one. D3D12 lets an access be named with a sync scope whose Vulkan + stages cannot perform it: `SYNC_ALL_SHADING` with `ACCESS_VERTEX_BUFFER` is valid D3D12, but + `VK_ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT` needs `VERTEX_ATTRIBUTE_INPUT`, which shading stages are not. Vulkan + rejects such a barrier. `vulkan_barrier_scope` therefore widens each side's stages by the narrowest stage that + can perform each access without one. The table is the synchronization2 chapter's "supported access types". The + stages it adds: + - `DRAW_INDIRECT` for indirect arguments; + - `INDEX_INPUT` and `VERTEX_ATTRIBUTE_INPUT` for index and vertex buffers; + - all shading for constant buffers, SRVs and UAVs; + - `COLOR_ATTACHMENT_OUTPUT` for render targets; + - the fragment tests for depth/stencil; + - `ALL_TRANSFER` for copies and resolves. `CLEAR` alone cannot read, and `ALL_GRAPHICS` contains no transfer stage. + + The access itself is never dropped, so the dependency still covers everything the application named, over a + slightly larger scope. - Render passes: `BeginRenderPass`/`EndRenderPass` map to `vkCmdBeginRendering`/`vkCmdEndRendering` (dynamic rendering). The `D3D12_RENDER_PASS_BEGINNING_ACCESS`/`ENDING_ACCESS` types give the load/store ops and resolve targets. Suspending/resuming passes have no direct Vulkan equivalent; split them into two rendering scopes with diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 1bcee80a3..db77635c3 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -225,6 +225,90 @@ inline VkAccessFlags2 vulkan_barrier_access(std::uint32_t access) { return out; } +// For one VkAccessFlagBits2 that vulkan_barrier_access produces: the stages Vulkan lets perform it (the "supported +// access types" table of the synchronization2 chapter, with the meta stages that contain them), and the narrowest +// stage to add when a barrier's stages have none of those. MEMORY_READ/WRITE are valid in every stage. +struct AccessStages { + VkAccessFlags2 access; + VkPipelineStageFlags2 supported; + VkPipelineStageFlags2 narrowest; +}; + +inline constexpr VkPipelineStageFlags2 shader_stages2 = + VK_PIPELINE_STAGE_2_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_2_TESSELLATION_CONTROL_SHADER_BIT | + VK_PIPELINE_STAGE_2_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_2_GEOMETRY_SHADER_BIT | + VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT | + VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | + VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT; + +inline constexpr AccessStages access_stages[] = { + {VK_ACCESS_2_INDIRECT_COMMAND_READ_BIT, + VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT}, + {VK_ACCESS_2_INDEX_READ_BIT, + VK_PIPELINE_STAGE_2_INDEX_INPUT_BIT | VK_PIPELINE_STAGE_2_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | + VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_INDEX_INPUT_BIT}, + {VK_ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT, + VK_PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT | VK_PIPELINE_STAGE_2_VERTEX_INPUT_BIT | + VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT}, + // Shader accesses: D3D12 does not say which shader stage, so every one that can run (all shading). + {VK_ACCESS_2_UNIFORM_READ_BIT, shader_stages2, + VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | + VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, + {VK_ACCESS_2_SHADER_READ_BIT, shader_stages2, + VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | + VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, + {VK_ACCESS_2_SHADER_WRITE_BIT, shader_stages2, + VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | + VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, + {VK_ACCESS_2_COLOR_ATTACHMENT_READ_BIT, + VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | + VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, + {VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT, + VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | + VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, + {VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT, + VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT | + VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, + {VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT | + VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, + // Transfers: ALL_GRAPHICS does not contain the transfer stages, and CLEAR only writes. + {VK_ACCESS_2_TRANSFER_READ_BIT, + VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_BLIT_BIT | VK_PIPELINE_STAGE_2_RESOLVE_BIT | + VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT}, + {VK_ACCESS_2_TRANSFER_WRITE_BIT, + VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_BLIT_BIT | VK_PIPELINE_STAGE_2_RESOLVE_BIT | + VK_PIPELINE_STAGE_2_CLEAR_BIT | VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT}, +}; + +// One side of an enhanced barrier: D3D12 sync and access to a Vulkan stage mask and access mask that Vulkan accepts +// together. D3D12 lets an access be named with a sync scope whose Vulkan stages cannot perform it (SYNC_ALL_SHADING +// with ACCESS_VERTEX_BUFFER is valid D3D12, but VERTEX_ATTRIBUTE_READ needs VERTEX_ATTRIBUTE_INPUT). The stages are +// widened by the narrowest stage that can, never the access dropped: the dependency still covers every access the +// application named, only over a slightly larger scope. With no stages (SYNC_NONE) there is no access either. +struct BarrierScope { + VkPipelineStageFlags2 stages; + VkAccessFlags2 access; +}; + +inline BarrierScope vulkan_barrier_scope(std::uint32_t sync, std::uint32_t access) { + BarrierScope out{vulkan_sync(sync), 0}; + if (!out.stages) return out; + out.access = vulkan_barrier_access(access); + for (const AccessStages& entry : access_stages) + if ((out.access & entry.access) && !(out.stages & entry.supported)) out.stages |= entry.narrowest; + return out; +} + // D3D12_BARRIER_LAYOUT -> VkImageLayout. Queue-specific layouts map like their generic forms. inline VkImageLayout vulkan_layout(std::uint32_t layout, bool presentable) { namespace l = d3d12_layout; @@ -963,11 +1047,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c return {}; }, command); + const BarrierScope src = vulkan_barrier_scope(sync_before, access_before); + const BarrierScope dst = vulkan_barrier_scope(sync_after, access_after); VkMemoryBarrier2 barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER_2}; - barrier.srcStageMask = vulkan_sync(sync_before); - barrier.dstStageMask = vulkan_sync(sync_after); - barrier.srcAccessMask = barrier.srcStageMask ? vulkan_barrier_access(access_before) : 0; - barrier.dstAccessMask = barrier.dstStageMask ? vulkan_barrier_access(access_after) : 0; + barrier.srcStageMask = src.stages; + barrier.dstStageMask = dst.stages; + barrier.srcAccessMask = src.access; + barrier.dstAccessMask = dst.access; VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; dependency.memoryBarrierCount = 1; dependency.pMemoryBarriers = &barrier; @@ -987,13 +1073,15 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c pieces = detail::current(tracker, id, range, before); detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); } + const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before); + const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after); std::vector barriers; for (const auto& piece : pieces) { VkImageMemoryBarrier2 b{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2}; - b.srcStageMask = vulkan_sync(texture->sync_before); - b.dstStageMask = vulkan_sync(texture->sync_after); - b.srcAccessMask = b.srcStageMask ? vulkan_barrier_access(texture->access_before) : 0; - b.dstAccessMask = b.dstStageMask ? vulkan_barrier_access(texture->access_after) : 0; + b.srcStageMask = src.stages; + b.dstStageMask = dst.stages; + b.srcAccessMask = src.access; + b.dstAccessMask = dst.access; b.oldLayout = piece.layout; b.newLayout = new_layout; b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; diff --git a/runtime/test/d3d12_state_map_test.cpp b/runtime/test/d3d12_state_map_test.cpp index 49d52d6be..1983dbad2 100644 --- a/runtime/test/d3d12_state_map_test.cpp +++ b/runtime/test/d3d12_state_map_test.cpp @@ -255,6 +255,46 @@ int main() { CHECK(vulkan_barrier_access(a::common) == (VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT)); CHECK(vulkan_barrier_access(a::copy_source | a::shader_resource) == (VK_ACCESS_2_TRANSFER_READ_BIT | VK_ACCESS_2_SHADER_READ_BIT)); + + // vulkan_barrier_scope: the stages are widened until every access has one that can perform it; the access is + // never dropped. (vk_command_replay_test part C checks every pair against the validation layer.) + { + const auto scope = [](std::uint32_t sync, std::uint32_t access) { return vulkan_barrier_scope(sync, access); }; + // Valid D3D12, invalid as mapped before: vertex-buffer reads under SYNC_ALL_SHADING. + BarrierScope widened = scope(y::all_shading, a::vertex_buffer); + CHECK(widened.access == VK_ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT); + CHECK(widened.stages == (vulkan_sync(y::all_shading) | VK_PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT)); + widened = scope(y::non_pixel_shading, a::index_buffer); + CHECK(widened.stages & VK_PIPELINE_STAGE_2_INDEX_INPUT_BIT); + widened = scope(y::clear_unordered_access_view, a::copy_source); // CLEAR only writes + CHECK(widened.stages & VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT); + widened = scope(y::copy, a::unordered_access); + CHECK(widened.stages == (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | + VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT)); + // Pairs Vulkan already accepts are left exactly as vulkan_sync / vulkan_barrier_access map them. + const std::pair unchanged[] = { + {y::copy, a::copy_dest}, {y::pixel_shading, a::shader_resource}, + {y::render_target, a::render_target}, {y::depth_stencil, a::depth_stencil_write}, + {y::draw, a::vertex_buffer}, {y::vertex_shading, a::vertex_buffer}, + {y::index_input, a::index_buffer}, {y::execute_indirect, a::indirect_argument}, + {y::all, a::common}, {y::compute_shading, a::unordered_access}, + {y::clear_unordered_access_view, a::unordered_access}}; + for (const auto& [sync, access] : unchanged) { + const BarrierScope same = scope(sync, access); + CHECK(same.stages == vulkan_sync(sync) && same.access == vulkan_barrier_access(access)); + } + // No stages, no access (SYNC_NONE pairs with ACCESS_NO_ACCESS in D3D12). + CHECK(scope(y::none, a::no_access).stages == 0 && scope(y::none, a::no_access).access == 0); + CHECK(scope(y::none, a::shader_resource).access == 0); + // Every single sync bit against every single access bit: the stages only grow, the access never changes. + for (std::uint32_t s_bit = 1; s_bit; s_bit <<= 1) { + for (std::uint32_t a_bit = 1; a_bit; a_bit <<= 1) { + const BarrierScope any = scope(s_bit, a_bit); + CHECK((any.stages & vulkan_sync(s_bit)) == vulkan_sync(s_bit)); + CHECK(any.access == (vulkan_sync(s_bit) ? vulkan_barrier_access(a_bit) : 0)); + } + } + } CHECK(vulkan_layout(l::undefined, false) == VK_IMAGE_LAYOUT_UNDEFINED); CHECK(vulkan_layout(l::common, false) == VK_IMAGE_LAYOUT_GENERAL); CHECK(vulkan_layout(l::present, true) == VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); diff --git a/runtime/test/vk_command_replay_test.cpp b/runtime/test/vk_command_replay_test.cpp index 29a87f50e..e0813c840 100644 --- a/runtime/test/vk_command_replay_test.cpp +++ b/runtime/test/vk_command_replay_test.cpp @@ -2,7 +2,8 @@ // Part A uses only Vulkan 1.0 functions and no layout tracker. Part B uses the tracker with separate depth/stencil // layouts: rectangle clears, a depth clear while the stencil plane is in another state, a texture used after // implicit promotion from common, and enhanced barriers. Part C copies a volume (footprint, box and whole) and -// resolves a multisampled target. +// resolves a multisampled target. Part D records every D3D12 sync/access pair as enhanced barriers, which the +// validation layer must accept. // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test. #include "vk_test_device.h" #include "../src/vulkan_replay.h" @@ -460,12 +461,83 @@ int part_c(vktest::Device& d) { return 0; } +// Part D: every D3D12 sync bit against every access bit, as global, buffer and texture barriers. Whatever pair the +// application names, the Vulkan barrier must be valid, so every access has a stage in its scope that can perform it +// (vulkan_barrier_scope). Under LEONIDA_VK_VALIDATION=1 a pair that breaks that rule is a validation error. The +// image is simultaneous-access, so it stays in GENERAL, which every access may use: only the stage/access rule is +// under test. +int part_d(vktest::Device& d) { + namespace y = d3d12_sync; + namespace a = d3d12_access; + namespace l = d3d12_layout; + const VkImage image = d.image(VK_FORMAT_R8G8B8A8_UNORM, 4, 4, 1, + VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); + EXPECT(image); + constexpr ResourceId image_id = 30, buffer_id = 31; + ResourceBinding image_binding{}; + image_binding.image = image; + image_binding.format = VK_FORMAT_R8G8B8A8_UNORM; + image_binding.width = image_binding.height = 4; + image_binding.simultaneous_access = true; + const ResourceBinding buffer_binding{}; // a buffer: no image + const auto resolve = [&](ResourceId id) -> const ResourceBinding* { + if (id == image_id) return &image_binding; + return id == buffer_id ? &buffer_binding : nullptr; + }; + ReplayFunctions vk{}; + vk.pipeline_barrier = d.fn("vkCmdPipelineBarrier"); + vk.clear_color_image = d.fn("vkCmdClearColorImage"); + vk.clear_depth_stencil_image = d.fn("vkCmdClearDepthStencilImage"); + vk.pipeline_barrier2 = d.fn("vkCmdPipelineBarrier2"); + vk.separate_depth_stencil_layouts = true; + LayoutTracker tracker(true); + tracker.track(image_id, image_binding, VK_IMAGE_LAYOUT_GENERAL); + + // Ray-tracing, video and split syncs map to ALL_COMMANDS, which every access accepts; they are kept anyway. + const std::uint32_t syncs[] = {y::all, y::draw, y::index_input, y::vertex_shading, y::pixel_shading, + y::depth_stencil, y::render_target, y::compute_shading, y::raytracing, y::copy, + y::resolve, y::execute_indirect, y::all_shading, y::non_pixel_shading, + y::emit_raytracing_acceleration_structure_postbuild_info, + y::clear_unordered_access_view, y::video_decode, + y::build_raytracing_acceleration_structure}; + const std::uint32_t accesses[] = {a::common, a::vertex_buffer, a::constant_buffer, a::index_buffer, + a::render_target, a::unordered_access, a::depth_stencil_write, + a::depth_stencil_read, a::shader_resource, a::stream_output, + a::indirect_argument, a::copy_dest, a::copy_source, a::resolve_dest, + a::resolve_source, a::raytracing_acceleration_structure_read, + a::raytracing_acceleration_structure_write, a::shading_rate_source, + a::video_decode_read, a::no_access}; + const BarrierSubresourceRange all{all_subresources, 0, 0, 0, 0, 0}; + CommandList list; + unsigned pairs = 0; + for (const std::uint32_t sync : syncs) { + for (const std::uint32_t access : accesses) { + EXPECT(list.barrier(GlobalBarrier{sync, sync, access, access})); + EXPECT(list.barrier(BufferBarrier{sync, sync, access, access, buffer_id})); + EXPECT(list.barrier(TextureBarrier{sync, sync, access, access, l::common, l::common, image_id, all, 0})); + ++pairs; + } + } + EXPECT(list.close()); + const unsigned errors_before = d.validation_errors(); + const bool ok = d.run([&](VkCommandBuffer cb) { + d.initial_layout(cb, image, VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_IMAGE_LAYOUT_GENERAL); + return replay(list, cb, resolve, vk, &tracker) == ReplayResult::success; + }); + EXPECT(ok); + const unsigned errors = d.validation_errors() - errors_before; + std::printf("D: %u sync/access pairs as global, buffer and texture barriers%s\n", pairs, + d.validation ? (errors ? ": validation errors" : ", no validation errors") : " (validation off)"); + return 0; +} + } // namespace int main() { vktest::Device device; EXPECT(device.create()); - if (part_a(device) || part_b(device) || part_c(device)) return 1; + if (part_a(device) || part_b(device) || part_c(device) || part_d(device)) return 1; if (g_mismatches) return 1; if (device.validation_errors()) { std::fprintf(stderr, "%u validation errors\n", device.validation_errors()); From 80fb7f2e416af9b1289c889b259f39dc7fb5a2b4 Mon Sep 17 00:00:00 2001 From: Tim Elery Date: Sat, 21 Nov 2026 14:44:27 -0800 Subject: [PATCH 21/53] Textures: add clean-room BCPack decoder (rANS + BC1/BC3/BC4/BC5) --- docs/textures.md | 220 +++++++++----- tests/test_bcpack.py | 542 +++++++++++++++++++++++++++++++++++ tests/test_ttpf_mips.py | 121 ++++++++ tools/bcpack.py | 617 ++++++++++++++++++++++++++++++++++++++++ tools/bcpack_tables.py | 463 ++++++++++++++++++++++++++++++ tools/ttpf_mips.py | 136 ++++++--- 6 files changed, 1995 insertions(+), 104 deletions(-) create mode 100644 tests/test_bcpack.py create mode 100644 tools/bcpack.py create mode 100644 tools/bcpack_tables.py diff --git a/docs/textures.md b/docs/textures.md index 15c17a462..478169218 100644 --- a/docs/textures.md +++ b/docs/textures.md @@ -15,16 +15,23 @@ field. | exported at least one mip | 308,895 | | skipped | 48,220 | -**Bottom line:** the gap is measurable and the codec mapping is certain, but BCPack itself is -not decodable from public facts. No BCPack decoder is added. The compact mip chain, which the -first measurement called the next tractable work, is now decoded and validated below; the -remaining gap is BCPack. +**Bottom line:** the compact mip chain is decoded and validated below, and a clean-room +stdlib-only BCPack decoder (`tools/bcpack.py`, `tools/bcpack_tables.py`) now decodes the +rANS entropy layer for all six active modes (BC1, BC3, BC4, BC5, BC6H, BC7) and rebuilds +BC1, BC3, BC4 and BC5 blocks (95.0% of all BCPack chunks, 89.6% of BCPack bytes). BC6H and +BC7 block rebuilders are left for the follow-up PR; `rpf9dump`'s C# `TtpfReader` still uses +the baseline zlib/raw path until ported. The compact layout rule moves 206,661 textures into complete exports and 1,218 more into -partial exports. After it, the totals are 305,264 complete, 16,419 partial and 35,432 skipped -(48,220 − 12,788). The complete count equals the 305,264 all-zlib/raw textures in the storage -table below, which is the consistency check: every texture with no BCPack mip now exports its -whole chain. +partial exports. After it (zlib/raw only), the totals are 305,264 complete, 16,419 partial +and 35,432 skipped (48,220 − 12,788). The complete count equals the 305,264 all-zlib/raw +textures in the storage table below, which is the consistency check: every texture with no +BCPack mip exports its whole chain. + +Adding BCPack BC1, BC3, BC4 and BC5 in `tools/ttpf_mips.py` unlocks **47,882** more complete +chains across the 57 pools, bringing the projected split to **353,146 complete** (98.9% of +catalog entries), **2,515 partial** and **1,454 skipped** (702 non-BCPack layout/format cases +plus 752 remaining BC6H/BC7 BCPack skips). This is the same 308,895 / 48,220 total already recorded in `docs/design.md`. The recount splits the 48,220 by cause: the old "(BCPack or unmapped)" label hides 14,713 skips whose @@ -432,95 +439,170 @@ table above and the container descriptors are the readable facts. |---|---|---| | [DSTORAGE_BCPACK_MODE](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/dstorage/enums/dstorage_bcpack_mode) | Modes 1–7 are BC1, BC2, BC3, BC4, BC5, BC6H, BC7; Xbox Series only | [Microsoft Learn Terms of Use](https://learn.microsoft.com/en-us/legal/termsofuse): informational, personal/non-commercial use; linked and paraphrased, no text or code copied | | [DirectStorage overview](https://learn.microsoft.com/en-us/gaming/gdk/docs/features/console/storage/directstorage/directstorage-overview) | BCPack is a custom entropy coder for BCn data; colour endpoints are separated from palette indices and coded with rANS; decompression order is DEFLATE, BCPack, swizzle | Same Microsoft Learn terms; linked and paraphrased | -| [SixNG, `formats/06-bcpack.md`](https://github.com/walkthestars/GTA6-Asset-Info/blob/main/formats/06-bcpack.md) | Independent notes: 0% decoded, no public specification or decoder, lane/header observations, open unknowns | [GPL-3.0](https://github.com/walkthestars/GTA6-Asset-Info/blob/main/LICENSE); notes only, no code copied | +| [US Patent 11,234,023](https://patents.google.com/patent/US11234023B2) | Public rANS architecture, banded exponential frequency model structure, and reference table check | Public patent disclosure; concepts only | +| [Khronos Data Format Specification (BPTC / S3TC / RGTC)](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html) | Standard BC1, BC3, BC4, BC5, BC6H and BC7 block layouts | Public specification | +| [SixNG, `formats/06-bcpack.md`](https://github.com/walkthestars/GTA6-Asset-Info/blob/main/formats/06-bcpack.md) | Independent container/header observations and the exact-end-state hard check | [GPL-3.0](https://github.com/walkthestars/GTA6-Asset-Info/blob/main/LICENSE); notes only, no code copied | | [SixNG, `formats/05-ttpf.md`](https://github.com/walkthestars/GTA6-Asset-Info/blob/main/formats/05-ttpf.md) | Independent codec-id table and pool structure | GPL-3.0; notes only | | [rpf9-explorer](https://github.com/breadbbbb/rpf9-explorer) | The `TtpfReader` catalog checks and limitation strings measured here | [MIT](https://github.com/breadbbbb/rpf9-explorer/blob/main/README.md) | -| [GitHub repository search `bcpack`](https://github.com/search?q=bcpack&type=repositories) | No BCPack decoder; the only GTA VI result is the GPL-3.0 notes above | Search on 2026-11-21 | -Microsoft's documentation gives the algorithm class and the mode enum, not the bitstream. -The public enum is documented for Xbox Series consoles; this note does not cover an Xbox One -variant. No public bitstream specification and no open-source BCPack decoder were found: the -SixNG notes are documentation, and the only open code found for this format is the container -parser (`rpf9-explorer`, MIT). The SixNG notes reach the same conclusion from the data: the -rANS coder and stream layout are partly mapped, there is no decoder, and BC1 is the only mode -studied beyond its headers. +## Clean-room BCPack bitstream specification and decoder -## Why there is no decoder in this change +The five unknowns noted in the first measurement are resolved in `tools/bcpack.py` and +`tools/bcpack_tables.py` (pure Python standard library, no GDK/NDA code, no keys, no game +assets). The console-side hardware decompressor and GDK implementation are not linked, +copied or referenced; only plain retail chunk bytes were analysed against public BCn and +rANS specifications. -A clean-room decoder needs a published bitstream description or a reference implementation -under a compatible licence. Neither was found publicly. The public facts stop well short of a -block decoder: +### 1. Entropy layer (all six active codecs) -1. **Models.** The rANS frequency tables for the endpoint planes and the adaptive models for - the index lanes are not published. Without them the symbol stream cannot be decoded. -2. **Record layout.** Varying plane and extension lanes have no understood byte-length field; - the constant lanes do, but they are only the easy case. -3. **Lane semantics.** What lane 0 codes, how the four index lanes map to 2-bit indices, and - how extension lanes are ordered are unknown. -4. **Block order and timing.** Whether blocks are linear or swizzled, and exactly when a lane - reads versus decodes within a round, are not settled. -5. **Modes.** Public notes only studied BC1; BC4, BC5 and BC7 streams are unstudied beyond - their headers. +Each BCPack chunk encodes `N = decoded_size / 8` synchronized lane elements across `nl` +interleaved 16-bit rANS lanes (`nl = 12` for BC1/BC3/BC4/BC5; `nl = 16` for BC6H/BC7). +16-byte block formats (BC3, BC5, BC6H, BC7) consume two lane elements per BC block. -The payload is **not** a documented BC7 or BC6H variant. BCPack decompresses *to* standard -BC1–BC7 blocks; the compressed stream is a separate entropy-coded representation. A decoder -built from synthetic blocks would test our guesses, not the format. +Each lane reads one or more fragments until it has emitted `N` symbols: -The console-side decompressor is hardware; the GDK implementation is not public source and -is not usable in a GPL-3.0 program. This change does not link it, copy it or work around it. -No DRM, key or protection work was done; only already-plain chunk bytes were read. +``` +hdr0 = z:2 | h3:1 | flush:1 | q:4 +hdr1 n = hdr1 + 1 (h3 = 0) +hdr1, hdr2 n = hdr1 + 256*hdr2 + 257 (h3 = 1) +``` -**What is missing, in one line:** the rANS models, the varying/extension lane record -layouts, lane-0/index-lane semantics, block order, and the BC4/5/6H/7 streams. The container -and the algorithm class are known; the bitstream is not. +- Symbol width `w = default_width[lane] - z` (`1 <= w <= 10`). +- `q` (`0..15`) selects the banded exponential probability model for width `w`: band `0` + covers symbol `0` and band `p >= 1` covers `[2^(p-1), 2^p)`, with total weight `65536`. + `q = 0` is uniform; `q = 15` concentrates mass on symbol `0`. All 160 tables live in + `tools/bcpack_tables.py`. +- rANS state: 32-bit unsigned integer with lower bound `L = 1 << 24`. Slot `0` is reserved + as the end marker (symbol `0` owns cumulative range `[1, f0)`). While `state < L`, one + byte is merged (`state = (state << 8) | byte`); while `state > L`, one symbol is decoded + via `cf = state & 0xFFFF` and advanced via `f * (state >> 16) + cf - c`. +- `flush = 1`: terminates the fragment's rANS stream. Trailing zero bytes are omitted from + the payload; once `n` bytes are consumed, the decoder shifts in up to 8 virtual zero + bytes until `state >= L`, continues decoding, and requires the fragment to land on the + exact home state `state == L`. The next fragment starts from `state = 0`. +- `flush = 0`: once `n` bytes are consumed and `state < L`, the next fragment header is + read and decoding continues with the carried-over state under the new `(w, q)` model. +- After all lanes finish, any remaining bytes in the chunk must be zero. + +### 2. Lane-array prefetch timing + +Byte-to-lane interleaving is fixed by a deterministic per-cycle scheduler: + +1. A lane holding a decoded symbol whose output slot is still full is output-stalled. +2. Non-stalled lanes in `PROC` advance their rANS state for any held symbol. +3. Lanes with an empty 1-byte input buffer request one byte (header or payload bytes while + `in_rem > 0`). At most **8 bytes per cycle** are served in lane index order. +4. Any lane that requested a byte and received none freezes for the cycle (no state merge, + no symbol release). +5. Served lanes (and lanes needing no byte) release any held symbol to their output slot, + merge at most one byte when `state < L`, and decode the next symbol when `state > L`. +6. Once every active lane has a symbol in its output slot, one synchronized element is + emitted and all slots clear. + +### 3. Per-codec lane layouts and block rebuilders + +| Codec | Format | Lanes | Default lane widths | Elements / block | Block rebuilder | +|---:|---|---:|---|---:|---| +| 1 | BC1 | 12 | `8 8 5 6 5 5 6 5 8 8 8 8` | 1 (8 B) | Implemented (`tools/bcpack.py`) | +| 3 | BC3 | 12 | `4 4 8 6 6 6 6 5 6 5 8 8` | 2 (16 B) | Implemented (`tools/bcpack.py`) | +| 4 | BC4 | 12 | `8 8 8 8 6 6 6 6 6 6 6 6` | 1 (8 B) | Implemented (`tools/bcpack.py`) | +| 5 | BC5 | 12 | `4 4 8 8 6 6 6 6 6 6 6 6` | 2 (16 B) | Implemented (`tools/bcpack.py`) | +| 6 | BC6H | 16 | `4 4 8 8 8 5 5 5 6 6 6 8 8 8 8 5` | 2 (16 B) | Entropy only (follow-up PR) | +| 7 | BC7 | 16 | `4 4 8 8 8 8 8 7 7 5 6 8 8 8 8 5` | 2 (16 B) | Entropy only (follow-up PR) | + +For BC1, BC3, BC4 and BC5: + +- **Lane 0** encodes a signed 8-bit backward distance `d` (zig-zag coded; split into two + bit-interleaved 4-bit nibbles for 2-element formats BC3/BC5). `d = 0` predicts from the + format's zero/midpoint default (`0` for RGB, `128` for 8-bit alpha/RG); `0 < d <= i` + references previously decoded block `i - d`; `d > i` references entry `256 + i - d` of + the format's fixed 256-entry built-in endpoint history. +- **Lane 1** is zero in all observed BC1/BC3/BC4/BC5 chunks (non-zero is rejected). +- **Endpoint lanes** store zig-zag deltas modulo each channel's bit depth (`32`/`64` for + RGB565, `256` for 8-bit BC3 alpha / BC4 / BC5 endpoints). +- **Index lanes** store ranks into fixed codec lookup tables: 256-entry 2×2 quadrant tables + for BC1 colour and BC3 colour, and 64-entry 3-bit index-pair tables for BC3 alpha, BC4 + and BC5. +- Blocks are decoded in the surface's native tiled memory order, so standard AMD Gfx10 + detiling (`tools/ttpf_mips.py`) applies unchanged after BCPack decompression. + +### 4. Built-in codec history tables (strict vs. provisional) + +The 256-entry built-in initial endpoint history tables and symbol-rank tables are fixed +codec constants shared by all DirectStorage BCPack streams, not game texture data. They +were recovered clean-room by algebraic and statistical fitting against independently +decodable blocks and mip-chain consistency on a retail copy, and stored without corpus +metadata in `tools/bcpack_tables.py`: + +| Format | Confirmed history entries | Provisional history entries | Notes | +|---|---:|---:|---| +| BC1 | 248 | 7 | Entry 0 unreferenced; provisional entries (6, 9, 67, 68, 71, 74, 122) uncertain by ≤1 green step | +| BC3 | 0 | 35 | All 256 colour-quadrant and 64 alpha-pair rank entries populated; history entries provisional | +| BC4 | 0 | 55 | 64 pair entries populated; UI pool chunks reference additional unfitted history entries | +| BC5 | 3 | 211 | 64 pair entries populated; remaining history entries provisional | + +`tools/bcpack.py` and `tools/ttpf_mips.py` run in **strict mode by default**: any chunk +referencing an unconfirmed or unknown built-in history entry raises +`BcpackProvisionalError`. Pass `--allow-provisional` to opt in. + +### 5. Validation on the 57-pool corpus + +- **Full-corpus projection (`tools/ttpf_mips.py scan` across all 57 pools):** + - Baseline (layout rule, zlib/raw only): **305,264** complete, **16,419** partial, **35,432** skipped. + - With BCPack BC1/BC3/BC4/BC5: **353,146** complete (**+47,882**, 98.9% of catalog entries), **2,515** partial, **1,454** skipped (702 non-BCPack + 752 remaining BC6H/BC7). +- **Previously skipped examples above (`tools/ttpf_mips.py check`, strict mode):** + - `graphics/ttdb_graphics.ttpf` #309 (128×128 BC1, 8 mips): **pass** (`max_error = 0.67`, `tail_origin_control = 102.3`). + - `ui/ttdb_ui.ttpf` #0 (512×512 BC1, 1 mip): **pass**. + - `terrain/ttdb_terrain_0_7.ttpf` #1537 (512×1024 BC7, 8 mips): blocked cleanly as unsupported codec 7 (deferred to the BC6H/BC7 follow-up PR). +- **Sampled cross-codec check:** 20/20 BC1 strict (`median_err = 0.68`), 7/7 BC3 provisional (`median_err = 1.44`, `max_err = 4.18`), 2/2 fitted BC4 provisional (`max_err = 0.43`; unfitted UI entries cleanly refused), 10/10 BC5 provisional (`median_err = 0.17`, `max_err = 0.85`), plus 5/5 BC6H and 10/10 BC7 chunks passing exact rANS entropy termination. ## Next step -1. **Port the rule to `TtpfReader`.** The rule is implemented and tested in - `tools/tex_headers.py`; in the reader, select `tile = 65536` when `((mode >> 1) & 0xF) == 0` - and 4096 otherwise, replace `ValidatedCompactProfile` with the allocation-span check, and - set `UsableMipLimit` to the computed `FirstTail` (or `mips` when the tail tile is - zlib/raw). On this install that completes 206,661 textures without touching BCPack. -2. **Decode BC6H/BC7 in the validator.** `tools/ttpf_mips.py` decodes BC1/3/4/5; the BC7 - samples were checked with an external decoder. The layout is the same formula (16-byte - elements), so this is validation breadth, not a new mapping. -3. **Identify DXGI 156/199/211/226 (19 records) and validate uncompressed tiling (formats +1. **Add BC6H and BC7 block rebuilders (ASSET-5 follow-up PR).** The rANS entropy layer + already decodes both 16-lane formats; adding the BC6H/BC7 block rebuilders and history + tables covers the remaining 5,435 BCPack chunks (752 skipped + remaining partial textures). +2. **Port the compact layout rule and BCPack decoder to `TtpfReader` (`rpf9-explorer` / + `tools/rpf9dump`).** In C#, select `tile = 65536` when `((mode >> 1) & 0xF) == 0` and + 4096 otherwise, replace `ValidatedCompactProfile` with the allocation-span check, set + `UsableMipLimit` to `FirstTail` (or `mips` when the tail tile is decodable), and wire + BCPack behind `TtpfReader.DecodeChunk`. +3. **Decode BC6H/BC7 in `tools/ttpf_mips.py` `check`.** `tools/ttpf_mips.py` currently + decodes BC1/3/4/5 pixels for the downsample check; adding BC6H/BC7 pixel decoders extends + chain-error validation to those two formats. +4. **Identify DXGI 156/199/211/226 (19 records) and validate uncompressed tiling (formats 11, 28, 49, 56).** These are the remaining non-BCPack blockers besides arrays. -4. **Arrays/volumes: 678 descriptors.** 567 use tile modes 9–12 and 111 are 2-slice; no +5. **Arrays/volumes: 678 descriptors.** 567 use tile modes 9–12 and 111 are 2-slice; no validated slice layout exists yet. -5. **Do not fake a BCPack decoder.** The current fallback (export the largest lower mip that - is zlib/raw) is used by 5,845 textures and should stay. If a public decoder or bitstream - spec appears under a compatible licence, add it behind `TtpfReader.DecodeChunk`; the - container already carries the mode (codec id) and decoded size, so no index work is - needed. -6. **If someone resumes the BCPack reverse engineering,** use the hard check the SixNG notes - propose: every lane must consume exactly its byte budget and finish at the rANS lower - bound, with a fixed symbol count. Reference blocks are the missing input; none are public. ## Reproduce -`tools/ttpf_mips.py` is the read-only measurement and decode tool: +`tools/ttpf_mips.py` is the read-only measurement and decode tool (with `tools/bcpack.py` +enabled in strict confirmed-history mode by default): ``` python -I tools/ttpf_mips.py scan --json scan.json [--tuples] python -I tools/ttpf_mips.py layout -python -I tools/ttpf_mips.py check -python -I tools/ttpf_mips.py export +python -I tools/ttpf_mips.py check [--allow-provisional] +python -I tools/ttpf_mips.py export [--allow-provisional] +python -I tests/test_bcpack.py python -I tests/test_tex_headers.py python -I tests/test_ttpf_mips.py ``` -`scan` reproduces the 357,115 / 98,603 / 210,292 / 48,220 split of this note, reports the -projected `after_full` / `after_partial` / `after_skip` split, and adds the layout and -recovery counters; `--tuples` adds the 84 known-size rejected tuples. `check` reports the -per-mip downsample error. `export` writes a full BC chain only when every source mip is -zlib/raw. The tool writes no texture data. `tests/test_tex_headers.py` tests the layout rule -on synthetic headers and `tests/test_ttpf_mips.py` builds a synthetic RDS5 pool, so neither -test needs game files. +`scan` reproduces the 357,115 / 98,603 / 210,292 / 48,220 baseline split, reports both the +zlib/raw layout projection (`after_full` / `after_partial` / `after_skip`) and the BCPack +BC1/BC3/BC4/BC5 projection (`after_bcpack_full` / `after_bcpack_partial` / +`after_bcpack_skip`), and adds the layout and recovery counters; `--tuples` adds the 84 +known-size rejected tuples. `check` reports the per-mip downsample error. `export` writes a +full BC chain when every source mip uses a supported codec. None of the tests need game +files: `tests/test_bcpack.py` builds synthetic rANS BCPack streams from scratch, +`tests/test_tex_headers.py` tests the layout rule on synthetic headers, and +`tests/test_ttpf_mips.py` builds synthetic zlib and BCPack RDS5 pools. `rpf9dump ttpf` writes one `manifest.json` per pool with a `Limitation` field for every catalog record, and its summary line has the same `ok` / `skip` totals. The first split above came from a read-only mirror of `TtpfReader`'s catalog checks: it mmapped each pool and read only the 24-byte RDS5 header, the chunk table, the ETPF records and the chunk ranges, and it wrote no texture data. `tools/ttpf_mips.py scan` is that mirror, now committed with the -compact-layout work; it reproduces the split and adds the recovery columns. +compact-layout and BCPack work; it reproduces the baseline split and adds the recovery +columns. diff --git a/tests/test_bcpack.py b/tests/test_bcpack.py new file mode 100644 index 000000000..b86485f66 --- /dev/null +++ b/tests/test_bcpack.py @@ -0,0 +1,542 @@ +"""Tests for tools/bcpack.py and tools/bcpack_tables.py using synthetic streams. + +Builds genuine BCPack rANS streams from scratch with a self-contained test +encoder — no game files or texture bytes are used. + + python -I tests/test_bcpack.py +""" +import importlib.util +import os +import struct +import sys +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tools")) + +import bcpack # noqa: E402 +import bcpack_tables as tables # noqa: E402 + + +# --- Synthetic BCPack rANS encoder (test helper only) ---------------------- + +def _zig(v): + """Inverse of bcpack._unzig for signed integer deltas.""" + return (-2 * v - 1) if v < 0 else (2 * v) + + +def _deint4(v): + """Inverse of bcpack._inter8: split 8-bit integer into two 4-bit nibbles.""" + a = b = 0 + for k in range(4): + a |= ((v >> (2 * k)) & 1) << k + b |= ((v >> (2 * k + 1)) & 1) << k + return a, b + + +def _encode_rans_syms(syms, model, x): + """Reverse-encode `syms` starting from end state `x`, returning `(new_x, bytes_reversed)`.""" + buf = [] + for s in reversed(syms): + p = s.bit_length() + f = model.freq[p] + c = model.base[p] + f * (s - (0 if p == 0 else 1 << (p - 1))) + if c == 0: + f, c = f - 1, 1 + limit = f << 16 + while x >= limit: + buf.append(x & 0xFF) + x >>= 8 + q_div, r_mod = divmod(x, f) + x = (q_div << 16) + c + r_mod + return x, buf + + +def _make_hdr(default_w, w, q, flush, n): + z = default_w - w + assert 0 <= z <= 3 and n >= 1 + if n <= 256: + return [((z & 3) << 6) | ((1 if flush else 0) << 4) | (q & 15), n - 1] + n2 = n - 257 + return [ + ((z & 3) << 6) | (1 << 5) | ((1 if flush else 0) << 4) | (q & 15), + n2 & 0xFF, + (n2 >> 8) & 0xFF, + ] + + +def _encode_fragment(syms, default_w, w, q, *, flush=True, strip_zeros=True): + """Encode `syms` into one standalone flush fragment (header + rANS payload).""" + assert flush + model = bcpack._get_model(w, q) + assert model is not None + x, buf = _encode_rans_syms(syms, model, bcpack.RANS_L) + payload = [(x >> 24) & 0xFF, (x >> 16) & 0xFF, (x >> 8) & 0xFF, x & 0xFF] + list(reversed(buf)) + if strip_zeros: + stripped = 0 + while len(payload) > 1 and payload[-1] == 0 and stripped < bcpack.MAX_VIRTUAL_ZEROS: + payload.pop() + stripped += 1 + return bytes(_make_hdr(default_w, w, q, True, len(payload)) + payload), 0 + + +def _encode_lane_stream(fragments, default_w): + """Chain one or more `(syms, w, q, flush)` fragments for a single lane. + + The final fragment must have `flush=True`. For a non-flush fragment followed + by another fragment, the boundary state is shifted below `RANS_L` so the + decoder finishes fragment `i` at `st < RANS_L` and renormalizes from fragment `i+1`. + """ + encoded = [None] * len(fragments) + x = bcpack.RANS_L + for idx in range(len(fragments) - 1, -1, -1): + syms, w, q, flush = fragments[idx] + model = bcpack._get_model(w, q) + assert model is not None + if flush: + x = bcpack.RANS_L + x, buf = _encode_rans_syms(syms, model, x) + prev_flush = True if idx == 0 else fragments[idx - 1][3] + if prev_flush: + # This fragment starts from state 0: prepend all 4 initial state bytes. + payload = [(x >> 24) & 0xFF, (x >> 16) & 0xFF, (x >> 8) & 0xFF, x & 0xFF] + list(reversed(buf)) + if flush: + stripped = 0 + while len(payload) > 1 and payload[-1] == 0 and stripped < bcpack.MAX_VIRTUAL_ZEROS: + payload.pop() + stripped += 1 + else: + # Previous fragment is non-flush: emit renormalization bytes into this + # fragment until `x < RANS_L` so the previous fragment hands off `x < RANS_L`. + while x >= bcpack.RANS_L: + buf.append(x & 0xFF) + x >>= 8 + payload = list(reversed(buf)) + encoded[idx] = bytes(_make_hdr(default_w, w, q, flush, len(payload)) + payload) + return b"".join(encoded) + + +def interleave_lanes(lane_streams, widths, nsym): + """Interleave per-lane byte streams according to the BCPack 8-byte/cycle scheduler.""" + nl = len(widths) + HDR0, HDR1, HDR2, PROC = 0, 1, 2, 3 + L = bcpack.RANS_L + ctrl = [HDR0] * nl + out_rem = [nsym] * nl + w = [0] * nl + q = [0] * nl + h3 = [0] * nl + flush = [0] * nl + done = [nsym <= 0] * nl + full = [False] * nl + held = [False] * nl + vz = [0] * nl + inbuf = [0] * nl + sym = [0] * nl + in_rem = [0] * nl + p0 = [0] * nl + p1 = [0] * nl + model = [None] * nl + slotfull = [False] * nl + stall = [False] * nl + lpos = [0] * nl + interleaved = bytearray() + max_cycles = max(1000, nsym * 64 + sum(len(s) for s in lane_streams) * 8) + + for _ in range(max_cycles): + if all(done[i] and not slotfull[i] for i in range(nl)): + for i in range(nl): + assert lpos[i] == len(lane_streams[i]), f"lane {i} left {len(lane_streams[i]) - lpos[i]} bytes" + return bytes(interleaved) + left = bcpack.PREFETCH_BUDGET + for i in range(nl): + if done[i] or (held[i] and slotfull[i]): + stall[i] = True + continue + stall[i] = False + if ctrl[i] == PROC: + p0[i] = model[i].advance(sym[i], p1[i]) if held[i] else p1[i] + if not full[i] and (ctrl[i] != PROC or in_rem[i] > 0): + if left == 0: + stall[i] = True + continue + b = lane_streams[i][lpos[i]] + lpos[i] += 1 + interleaved.append(b) + inbuf[i] = b + full[i] = True + left -= 1 + if held[i]: + slotfull[i] = True + held[i] = False + for i in range(nl): + if done[i] or stall[i]: + continue + c = ctrl[i] + if c == HDR0: + if not full[i]: + continue + h = inbuf[i] + q[i] = h & 15 + flush[i] = (h >> 4) & 1 + h3[i] = (h >> 5) & 1 + w[i] = widths[i] - (h >> 6) + full[i] = False + ctrl[i] = HDR1 + vz[i] = 0 + elif c == HDR1: + if not full[i]: + continue + full[i] = False + model[i] = bcpack._get_model(w[i], q[i]) + if h3[i]: + in_rem[i] = inbuf[i] + ctrl[i] = HDR2 + else: + in_rem[i] = inbuf[i] + 1 + ctrl[i] = PROC + elif c == HDR2: + if not full[i]: + continue + in_rem[i] = ((inbuf[i] << 8) | (in_rem[i] & 0xFF)) + 257 + ctrl[i] = PROC + full[i] = False + else: + st = p0[i] + if st < L: + if in_rem[i] > 0: + if full[i]: + st = (st << 8) | inbuf[i] + in_rem[i] -= 1 + full[i] = False + if in_rem[i] == 0 and flush[i]: + while st < L and st != 0 and vz[i] < bcpack.MAX_VIRTUAL_ZEROS: + st <<= 8 + vz[i] += 1 + elif flush[i]: + while st < L and st != 0 and vz[i] < bcpack.MAX_VIRTUAL_ZEROS: + st <<= 8 + vz[i] += 1 + else: + p1[i] = st + if out_rem[i] > 0: + ctrl[i] = HDR0 + else: + done[i] = True + continue + nxt = st > L and out_rem[i] > 0 + if nxt: + sym[i] = model[i].lookup(st & 0xFFFF) + out_rem[i] -= 1 + held[i] = nxt + p1[i] = st + if in_rem[i] == 0: + if flush[i]: + if st == L: + if out_rem[i] > 0: + ctrl[i] = HDR0 + p0[i] = 0 + p1[i] = 0 + else: + done[i] = True + elif out_rem[i] == 0 and not nxt: + done[i] = True + ready = True + anyfull = False + for i in range(nl): + if slotfull[i]: + anyfull = True + elif not (done[i] and not held[i]): + ready = False + break + if ready and anyfull: + for i in range(nl): + slotfull[i] = False + for i in range(nl): + if done[i] and held[i] and not slotfull[i]: + slotfull[i] = True + held[i] = False + raise AssertionError("interleave_lanes exceeded max_cycles") + + +def encode_lanes(lanes, codec, *, q=0): + """Encode per-lane symbol lists into a complete BCPack chunk.""" + widths = bcpack.LANE_WIDTHS[codec] + nsym = len(lanes[0]) + streams = [] + for i, (syms, dw) in enumerate(zip(lanes, widths)): + qi = q[i] if isinstance(q, (list, tuple)) else q + frag, _ = _encode_fragment(syms, dw, dw, qi, flush=True) + streams.append(frag) + return interleave_lanes(streams, widths, nsym) + + +def encode_bc1_blocks(blocks, *, ref_dists=None): + """Encode raw BC1 blocks (8 bytes each) into a valid codec-1 BCPack chunk.""" + n = len(blocks) // 8 + inv_quad = {v: i for i, v in enumerate(tables.BC1_QUADRANT)} + mods = (32, 64, 32, 32, 64, 32) + lanes = [[] for _ in range(12)] + hist = [] + for i in range(n): + c0, c1, r0, r1, r2, r3 = struct.unpack_from("> 11) & 31, (c0 >> 5) & 63, c0 & 31, + (c1 >> 11) & 31, (c1 >> 5) & 63, c1 & 31) + d = 0 if ref_dists is None else ref_dists[i] + if d == 0: + base = (0, 0, 0, 0, 0, 0) + elif i - d >= 0: + base = hist[i - d] + else: + entry = 256 + i - d + base = tables.BC1_HISTORY_CONFIRMED.get(entry) or tables.BC1_HISTORY_PROVISIONAL.get(entry) or (0, 0, 0, 0, 0, 0) + signed_d = d if d < 128 else d - 256 + lanes[0].append(_zig(signed_d)) + lanes[1].append(0) + for k in range(6): + delta = (e[k] - base[k]) % mods[k] + if delta >= mods[k] // 2: + delta -= mods[k] + lanes[2 + k].append(_zig(delta)) + hist.append(e) + qa = (r0 & 15) | ((r1 & 15) << 4) + qb = (r0 >> 4) | ((r1 >> 4) << 4) + qc = (r2 & 15) | ((r3 & 15) << 4) + qd = (r2 >> 4) | ((r3 >> 4) << 4) + lanes[8].append(inv_quad[qa]) + lanes[9].append(inv_quad[qb]) + lanes[10].append(inv_quad[qc]) + lanes[11].append(inv_quad[qd]) + return encode_lanes(lanes, 1) + + +# --- Unit tests ------------------------------------------------------------ + +class ProbTablesTest(unittest.TestCase): + def test_all_160_tables_valid_and_invertible(self): + self.assertEqual(len(tables.PROB_TABLES), 160) + for w in range(1, 11): + for q in range(16): + m = bcpack._get_model(w, q) + self.assertIsNotNone(m) + # Verify boundary symbols (0, 1, mid, max) invert cleanly. + for s in {0, 1, (1 << (w - 1)), (1 << w) - 1}: + p = s.bit_length() + f = m.freq[p] + c = m.base[p] + f * (s - (0 if p == 0 else 1 << (p - 1))) + if c == 0: + f, c = f - 1, 1 + x = (256 << 16) + c + self.assertEqual(m.lookup(x & 0xFFFF), s) + self.assertEqual(m.advance(s, x), 256 * f) + + +class EntropyLayerTest(unittest.TestCase): + def test_round_trip_12_and_16_lanes(self): + for codec in (1, 3, 4, 5, 6, 7): + widths = bcpack.LANE_WIDTHS[codec] + nsym = 24 + lanes = [[((i * 13 + j * 7) & ((1 << dw) - 1)) for j in range(nsym)] + for i, dw in enumerate(widths)] + qs = [(i * 3) % 15 for i in range(len(widths))] + raw = encode_lanes(lanes, codec, q=qs) + decoded, used = bcpack.decode_lanes(raw + b"\x00\x00\x00", codec, nsym * 8) + self.assertEqual(used, len(raw)) + self.assertEqual(decoded, lanes) + + def test_multi_fragment_flush_and_non_flush_and_3byte_header(self): + codec = 1 + widths = bcpack.LANE_WIDTHS[codec] + # 400 symbols forces a >256-byte fragment (3-byte header, h3=1) on 8-bit lanes. + nsym = 400 + lanes = [[((i * 29 + j * 17) & ((1 << dw) - 1)) for j in range(nsym)] + for i, dw in enumerate(widths)] + streams = [] + for i, (syms, dw) in enumerate(zip(lanes, widths)): + if i == 0: + # Two flush fragments with reduced width on the second half. + s1 = [x & 0x3F for x in syms[:100]] + s2 = [x & 0x1F for x in syms[100:]] + lanes[0] = s1 + s2 + streams.append(_encode_lane_stream([ + (s1, dw - 2, 2, True), + (s2, dw - 3, 5, True), + ], dw)) + elif i == 2: + # Chained non-flush -> flush fragments with a model change mid-stream. + streams.append(_encode_lane_stream([ + (syms[:150], dw, 1, False), + (syms[150:], dw, 4, True), + ], dw)) + else: + # Single large flush fragment (3-byte header on 8-bit lanes). + streams.append(_encode_lane_stream([(syms, dw, 0, True)], dw)) + raw = interleave_lanes(streams, widths, nsym) + decoded, used = bcpack.decode_lanes(raw, codec, nsym * 8) + self.assertEqual(used, len(raw)) + self.assertEqual(decoded, lanes) + + def test_rejects_corrupt_and_trailing_data(self): + lanes = [[0] * 8 for _ in range(12)] + raw = encode_lanes(lanes, 1) + with self.assertRaises(bcpack.BcpackError): + bcpack.decode_lanes(raw + b"\x01", 1, 64) + with self.assertRaises(bcpack.BcpackError): + bcpack.decode_lanes(raw[:-2], 1, 64) + flipped = bytearray(raw) + flipped[-1] ^= 0xFF + with self.assertRaises(bcpack.BcpackError): + bcpack.decode_lanes(bytes(flipped), 1, 64) + with self.assertRaises(bcpack.BcpackError): + bcpack.decode_lanes(raw, 99, 64) + with self.assertRaises(bcpack.BcpackError): + bcpack.decode_lanes(raw, 1, 60) + + def test_unsupported_codec_rebuild_raises(self): + lanes = [[0] * 4 for _ in range(16)] + raw = encode_lanes(lanes, 7) + # Entropy layer succeeds for BC7... + dec, _ = bcpack.decode_lanes(raw, 7, 32) + self.assertEqual(dec, lanes) + # ...while block rebuild raises BcpackUnsupportedCodec in PR 1. + with self.assertRaises(bcpack.BcpackUnsupportedCodec): + bcpack.decode(raw, 7, 32) + + +class BlockRebuildTest(unittest.TestCase): + def test_bc1_confirmed_and_provisional_history(self): + # Block 0: d=0 (zero base); Block 1: dynamic ref to block 0 (d=1); + # Block 2: confirmed built-in preset 1 (256 + 2 - d == 1 => d=257? no, 256+2-255=3, use entry 255 -> d=3). + blocks = b"".join([ + struct.pack(" 256 + 2 - 3 = 255 (confirmed in BC1_HISTORY_CONFIRMED). + self.assertIn(255, tables.BC1_HISTORY_CONFIRMED) + raw = encode_bc1_blocks(blocks, ref_dists=[0, 1, 3]) + out, prov = bcpack.decode_with_info(raw, 1, len(blocks)) + self.assertEqual(out, blocks) + self.assertEqual(prov, set()) + + # Reference provisional entry 6 from block 0: 256 + 0 - d = 6 => d = 250. + self.assertIn(6, tables.BC1_HISTORY_PROVISIONAL) + raw_prov = encode_bc1_blocks(blocks[:8], ref_dists=[250]) + with self.assertRaises(bcpack.BcpackProvisionalError): + bcpack.decode(raw_prov, 1, 8) + out_p, prov_p = bcpack.decode_with_info(raw_prov, 1, 8, allow_provisional=True) + self.assertEqual(out_p, blocks[:8]) + self.assertEqual(prov_p, {"BC1 history 6"}) + + def test_bc4_round_trip(self): + inv_pair = {p: i for i, p in enumerate(tables.BC4_PAIR)} + # Build 2 BC4 blocks: block 0 uses d=0 (base 128,128), block 1 refs block 0 (d=1). + b0_bits = sum(((r + p) & 7) << (3 * (4 * r + p)) for r in range(4) for p in range(4)) + b1_bits = sum(((7 - r - p) & 7) << (3 * (4 * r + p)) for r in range(4) for p in range(4)) + expected = ( + bytes([130, 120]) + b0_bits.to_bytes(6, "little") + + bytes([140, 110]) + b1_bits.to_bytes(6, "little") + ) + lanes = [[] for _ in range(12)] + for i, (d, base, (a0, a1), bits) in enumerate([ + (0, (128, 128), (130, 120), b0_bits), + (1, (130, 120), (140, 110), b1_bits), + ]): + lanes[0].append(_zig(d)) + lanes[1].append(0) + lanes[2].append(_zig(a0 - base[0])) + lanes[3].append(_zig(a1 - base[1])) + for r in range(4): + row = (bits >> (12 * r)) & 0xFFF + lanes[4 + 2 * r].append(inv_pair[(row & 7, (row >> 3) & 7)]) + lanes[4 + 2 * r + 1].append(inv_pair[((row >> 6) & 7, (row >> 9) & 7)]) + raw = encode_lanes(lanes, 4) + self.assertEqual(bcpack.decode(raw, 4, len(expected)), expected) + + # Provisional BC4 history entry (entry 25 -> block 0 uses d = 231). + self.assertIn(25, tables.BC4_HISTORY_PROVISIONAL) + prov_a0, prov_a1 = tables.BC4_HISTORY_PROVISIONAL[25] + lanes_p = [[_zig(231 - 256)], [0], [0], [0]] + [[0]] * 8 + raw_p = encode_lanes(lanes_p, 4) + with self.assertRaises(bcpack.BcpackProvisionalError): + bcpack.decode(raw_p, 4, 8) + out_p, info_p = bcpack.decode_with_info(raw_p, 4, 8, allow_provisional=True) + self.assertEqual((out_p[0], out_p[1]), (prov_a0, prov_a1)) + self.assertEqual(info_p, {"BC4 history 25"}) + + def test_bc5_round_trip(self): + inv_pair = {p: i for i, p in enumerate(tables.BC5_PAIR)} + # Block 0 uses confirmed BC5 entry if present, plus block 1 dynamic ref. + confirmed_entry = next(iter(sorted(tables.BC5_HISTORY_CONFIRMED))) + base0 = tables.BC5_HISTORY_CONFIRMED[confirmed_entry] + d0 = 256 - confirmed_entry # block 0: 256 + 0 - d0 == confirmed_entry + e0 = ((base0[0] + 2) & 255, (base0[1] - 3) & 255, (base0[2] + 1) & 255, (base0[3] - 1) & 255) + e1 = ((e0[0] + 5) & 255, (e0[1] - 4) & 255, (e0[2] + 3) & 255, (e0[3] + 2) & 255) + bits = [ + (0x0123456789AB, 0xFEDCBA987654), + (0x112233445566, 0x778899AABBCC), + ] + expected = bytearray() + for e, (br, bg) in zip((e0, e1), bits): + expected += bytes([e[0], e[1]]) + br.to_bytes(6, "little") + expected += bytes([e[2], e[3]]) + bg.to_bytes(6, "little") + lanes = [[] for _ in range(12)] + for d, base, e, (br, bg) in ((d0, base0, e0, bits[0]), (1, e0, e1, bits[1])): + sd = d if d < 128 else d - 256 + da, db = _deint4(_zig(sd)) + lanes[0].extend([da, db]) + lanes[1].extend([0, 0]) + for lane_idx, (c_a, c_b, b_a, b_b) in ((2, (e[0], e[1], base[0], base[1])), + (3, (e[2], e[3], base[2], base[3]))): + d_a = (c_a - b_a + 128) % 256 - 128 + d_b = (c_b - b_b + 128) % 256 - 128 + lanes[lane_idx].extend([_zig(d_a), _zig(d_b)]) + for ch, bval in enumerate((br, bg)): + for r in range(4): + row = (bval >> (12 * r)) & 0xFFF + lanes[4 + 4 * ch + r].extend([ + inv_pair[(row & 7, (row >> 3) & 7)], + inv_pair[((row >> 6) & 7, (row >> 9) & 7)], + ]) + raw = encode_lanes(lanes, 5) + out, prov = bcpack.decode_with_info(raw, 5, len(expected)) + self.assertEqual(out, bytes(expected)) + self.assertEqual(prov, set()) + + def test_bc3_round_trip(self): + inv_pair = {p: i for i, p in enumerate(tables.BC3_ALPHA_PAIR)} + inv_quad = {v: i for i, v in enumerate(tables.BC3_COLOUR_QUADRANT)} + # Block 0 with d=0: base is (128, 128, 0, 0, 0, 0, 0, 0). + a0, a1 = 135, 120 + abits = 0x0123456789AB + c0 = (5 << 11) | (10 << 5) | 3 + c1 = (2 << 11) | (6 << 5) | 1 + r0, r1, r2, r3 = 0x12, 0x34, 0x56, 0x78 + expected = bytes([a0, a1]) + abits.to_bytes(6, "little") + struct.pack("> (12 * r)) & 0xFFF + lanes[3 + r].extend([ + inv_pair[(row & 7, (row >> 3) & 7)], + inv_pair[((row >> 6) & 7, (row >> 9) & 7)], + ]) + lanes[7].extend([_zig(5), _zig(2)]) + lanes[8].extend([_zig(10), _zig(6)]) + lanes[9].extend([_zig(3), _zig(1)]) + qa = (r0 & 15) | ((r1 & 15) << 4) + qb = (r0 >> 4) | ((r1 >> 4) << 4) + qc = (r2 & 15) | ((r3 & 15) << 4) + qd = (r2 >> 4) | ((r3 >> 4) << 4) + lanes[10].extend([inv_quad[qa], inv_quad[qb]]) + lanes[11].extend([inv_quad[qc], inv_quad[qd]]) + raw = encode_lanes(lanes, 3) + out, prov = bcpack.decode_with_info(raw, 3, len(expected)) + self.assertEqual(out, expected) + self.assertEqual(prov, set()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_ttpf_mips.py b/tests/test_ttpf_mips.py index 9079061f9..039f286cf 100644 --- a/tests/test_ttpf_mips.py +++ b/tests/test_ttpf_mips.py @@ -344,5 +344,126 @@ class SyntheticPoolTest(unittest.TestCase): self.assertEqual(total["after_skip"], 1) +def build_bc1_bcpack_pool(path, width=64, height=64, mips=5, non_tail=1, mode=4, + meta=0x103, extra=0, packed=4, ref_dists=None): + """Build a synthetic RDS5 pool whose chunk is encoded with BCPack codec 1 (BC1).""" + sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + import test_bcpack as tb + layout = ttpf.surface_layout(width, height, 71, mips, ttpf.tile_bytes(mode)) + linear = solid_chain(layout, 71) + payload = bytearray(layout["size"]) + for mip in layout["mips"]: + retile_to(layout, mip, linear[mip["index"]], payload) + packed_payload = tb.encode_bc1_blocks(bytes(payload), ref_dists=ref_dists) + pad = (-len(packed_payload)) % 256 + count = 3 + table_end = 24 + (count - 1) * 8 + etpf = ttpf.align(table_end, 256) + metadata = 16 + 24 + 32 + padded = ttpf.align(metadata, 4096) + source = etpf + padded + chunk_end = source + len(packed_payload) + pad + virt = padded + vsize = virt + layout["size"] + entry = (source // 256) | (1 << 26) | ((virt // 4096) << 30) | (pad << 52) + sentinel = (chunk_end // 256) | ((vsize // 4096) << 30) + header = bytearray(24) + header[0:4] = b"RDS5" + struct.pack_into(" 0 and cf < base[p]: + p -= 1 + return 0 if p == 0 else (1 << (p - 1)) + (cf - base[p]) // self.freq[p] + + def advance(self, s, x): + p = s.bit_length() + f = self.freq[p] + c = self.base[p] + f * (s - (0 if p == 0 else 1 << (p - 1))) + if c == 0: + f, c = f - 1, 1 + return f * (x >> 16) + (x & 0xFFFF) - c + + +_MODEL_CACHE = {} + + +def _get_model(w, q): + key = (w, q) + m = _MODEL_CACHE.get(key) + if m is None: + freq = _tables.PROB_TABLES.get(key) + if freq is None: + return None + m = _Model(w, freq) + _MODEL_CACHE[key] = m + return m + + +def _decode_lanes_raw(raw, widths, nsym): + """Decode the interleaved rANS lane array into one symbol list per lane. + + Returns `(lanes, bytes_used)`. Raises `BcpackError` if any fragment fails + to land at the exact rANS lower bound `RANS_L`, runs out of input, or + produces an out-of-range symbol. + """ + nl = len(widths) + HDR0, HDR1, HDR2, PROC = 0, 1, 2, 3 + L = RANS_L + ctrl = [HDR0] * nl + out_rem = [nsym] * nl + w = [0] * nl + q = [0] * nl + h3 = [0] * nl + flush = [0] * nl + done = [nsym <= 0] * nl + full = [False] * nl + held = [False] * nl + vz = [0] * nl + inbuf = [0] * nl + sym = [0] * nl + in_rem = [0] * nl + p0 = [0] * nl + p1 = [0] * nl + model = [None] * nl + slotfull = [False] * nl + slotval = [0] * nl + stall = [False] * nl + out = [[] for _ in range(nl)] + pos = 0 + nraw = len(raw) + + def fail(msg, lane): + raise BcpackError( + f"lane {lane} (width {w[lane]}, q {q[lane]}) at input byte {pos}: {msg}" + ) + + while True: + if all(done[i] and not slotfull[i] for i in range(nl)): + return out, pos + + # Phase 1: state update, prefetch arbitration (at most 8 bytes/cycle), + # and symbol release for non-stalled lanes. + left = PREFETCH_BUDGET + for i in range(nl): + if done[i]: + stall[i] = True + continue + if held[i] and slotfull[i]: + stall[i] = True + continue + stall[i] = False + if ctrl[i] == PROC: + p0[i] = model[i].advance(sym[i], p1[i]) if held[i] else p1[i] + if not full[i] and (ctrl[i] != PROC or in_rem[i] > 0): + if left == 0: + stall[i] = True + continue + if pos >= nraw: + fail("input ran out", i) + inbuf[i] = raw[pos] + pos += 1 + full[i] = True + left -= 1 + if held[i]: + slotfull[i] = True + slotval[i] = sym[i] + held[i] = False + + # Phase 2: header parsing, byte merge, virtual zero fill on flush, and symbol lookup. + for i in range(nl): + if done[i] or stall[i]: + continue + c = ctrl[i] + if c == HDR0: + if not full[i]: + continue + h = inbuf[i] + q[i] = h & 15 + flush[i] = (h >> 4) & 1 + h3[i] = (h >> 5) & 1 + w[i] = widths[i] - (h >> 6) + full[i] = False + ctrl[i] = HDR1 + vz[i] = 0 + elif c == HDR1: + if not full[i]: + continue + full[i] = False + wi = w[i] + if not 1 <= wi <= MAX_WIDTH: + fail("symbol width out of range", i) + m = _get_model(wi, q[i]) + if m is None: + fail("probability table for this width and q is not known", i) + model[i] = m + if h3[i]: + in_rem[i] = inbuf[i] + ctrl[i] = HDR2 + else: + in_rem[i] = inbuf[i] + 1 + ctrl[i] = PROC + elif c == HDR2: + if not full[i]: + continue + in_rem[i] = ((inbuf[i] << 8) | (in_rem[i] & 0xFF)) + 257 + ctrl[i] = PROC + full[i] = False + else: + st = p0[i] + if st < L: + if in_rem[i] > 0: + if full[i]: + st = (st << 8) | inbuf[i] + in_rem[i] -= 1 + full[i] = False + if in_rem[i] == 0 and flush[i]: + while st < L and st != 0 and vz[i] < MAX_VIRTUAL_ZEROS: + st <<= 8 + vz[i] += 1 + elif flush[i]: + if st == 0 or vz[i] >= MAX_VIRTUAL_ZEROS: + fail("fragment did not end at its home state", i) + while st < L and st != 0 and vz[i] < MAX_VIRTUAL_ZEROS: + st <<= 8 + vz[i] += 1 + else: + p1[i] = st + if out_rem[i] > 0: + ctrl[i] = HDR0 + else: + done[i] = True + continue + nxt = st > L and out_rem[i] > 0 + if nxt: + s = model[i].lookup(st & 0xFFFF) + sym[i] = s + out_rem[i] -= 1 + if s >> w[i]: + fail("symbol outside its width", i) + held[i] = nxt + p1[i] = st + if in_rem[i] == 0: + if flush[i]: + if st == L: + if out_rem[i] > 0: + ctrl[i] = HDR0 + p0[i] = 0 + p1[i] = 0 + else: + done[i] = True + elif st > L and not nxt: + fail("fragment did not end at its home state", i) + elif out_rem[i] == 0 and not nxt: + done[i] = True + elif st == L or (out_rem[i] == 0 and not nxt and st > L): + fail("fragment did not end at its home state", i) + + # Phase 3: emit one synchronized element when every active lane has filled its slot. + ready = True + anyfull = False + for i in range(nl): + if slotfull[i]: + anyfull = True + elif not (done[i] and not held[i]): + ready = False + break + if ready and anyfull: + for i in range(nl): + if slotfull[i]: + out[i].append(slotval[i]) + slotfull[i] = False + for i in range(nl): + if done[i] and held[i] and not slotfull[i]: + slotfull[i] = True + slotval[i] = sym[i] + held[i] = False + + +def decode_lanes(raw, codec, out_size): + """Entropy layer: decode `raw` into per-lane symbol lists and bytes consumed. + + Works for all six active codecs (`1, 3, 4, 5, 6, 7`). Trailing non-zero + bytes after the last lane finishes are rejected. + """ + if codec not in LANE_WIDTHS: + raise BcpackError(f"unsupported BCPack codec id: {codec}") + if out_size < 0 or out_size % BLOCK_BYTES[codec] != 0: + raise BcpackError( + f"decoded size {out_size} is not a whole number of {CODEC_NAMES[codec]} blocks" + ) + nsym = out_size // ELEMENT_BYTES + data = memoryview(raw) + lanes, used = _decode_lanes_raw(data, LANE_WIDTHS[codec], nsym) + if any(data[used:]): + raise BcpackError("non-zero data left over after the last lane finished") + return lanes, used + + +def _unzig(v): + return -((v + 1) >> 1) if (v & 1) else (v >> 1) + + +def _inter8(a, b): + d = 0 + for k in range(4): + d |= (((a >> k) & 1) << (2 * k)) | (((b >> k) & 1) << (2 * k + 1)) + return d + + +def _loose_limit(nblocks): + """Maximum undetermined blocks permitted in provisional mode (1 in 1,024, min 2).""" + return max(2, nblocks // 1024) + + +def _bc1_blocks(lanes, nblocks, provisional): + if any(lanes[1]): + raise BcpackError("BC1 lane 1 is non-zero (unexpected)") + quad = _tables.BC1_QUADRANT + confirmed = _tables.BC1_HISTORY_CONFIRMED + loose = _tables.BC1_HISTORY_PROVISIONAL + out = bytearray(nblocks * 8) + hist = [None] * nblocks + mods = (32, 64, 32, 32, 64, 32) + l0 = lanes[0] + cols = lanes[2:8] + q0, q1, q2, q3 = lanes[8:12] + for i in range(nblocks): + v = l0[i] + d = 256 - ((v + 1) >> 1) if (v & 1) else (v >> 1) + if d == 0: + base = (0, 0, 0, 0, 0, 0) + elif i - d >= 0: + base = hist[i - d] + else: + entry = 256 + i - d + base = confirmed.get(entry) + if base is None: + if provisional is not None and entry in loose: + base = loose[entry] + provisional.add(f"BC1 history {entry}") + else: + state = "unconfirmed" if entry in loose else "unknown" + raise BcpackProvisionalError( + f"BC1 block {i} references {state} built-in history entry {entry}" + ) + e0 = (base[0] + _unzig(cols[0][i])) % mods[0] + e1 = (base[1] + _unzig(cols[1][i])) % mods[1] + e2 = (base[2] + _unzig(cols[2][i])) % mods[2] + e3 = (base[3] + _unzig(cols[3][i])) % mods[3] + e4 = (base[4] + _unzig(cols[4][i])) % mods[4] + e5 = (base[5] + _unzig(cols[5][i])) % mods[5] + hist[i] = (e0, e1, e2, e3, e4, e5) + c0 = (e0 << 11) | (e1 << 5) | e2 + c1 = (e3 << 11) | (e4 << 5) | e5 + a, b, c, dd = quad[q0[i]], quad[q1[i]], quad[q2[i]], quad[q3[i]] + # Quadrant byte: pixels TL, TR, BL, BR in bits 0-1, 2-3, 4-5, 6-7. + struct.pack_into( + "> 4) | ((b >> 4) << 4), + (c & 15) | ((dd & 15) << 4), + (c >> 4) | ((dd >> 4) << 4), + ) + return bytes(out) + + +_BC3_MODS = (256, 256, 32, 64, 32, 32, 64, 32) +_BC3_NONE = (128, 128, 0, 0, 0, 0, 0, 0) + + +def _bc3_blocks(lanes, nblocks, provisional): + if any(lanes[1]): + raise BcpackError("BC3 lane 1 is non-zero (unexpected)") + pairs = _tables.BC3_ALPHA_PAIR + quads = _tables.BC3_COLOUR_QUADRANT + confirmed = _tables.BC3_HISTORY_CONFIRMED + loose = _tables.BC3_HISTORY_PROVISIONAL + out = bytearray(nblocks * 16) + hist = [None] * nblocks + lost = [False] * nblocks + l0, alpha = lanes[0], lanes[2] + rows = lanes[3:7] + lr, lg, lb = lanes[7], lanes[8], lanes[9] + top, bottom = lanes[10], lanes[11] + unknown = set() + mods = _BC3_MODS + for i in range(nblocks): + a, b = 2 * i, 2 * i + 1 + d = _unzig(_inter8(l0[a], l0[b])) & 255 + if d == 0: + base = _BC3_NONE + elif i - d >= 0: + base = hist[i - d] + lost[i] = lost[i - d] + else: + entry = 256 + i - d + base = confirmed.get(entry) + if base is None and entry in loose: + if provisional is None: + raise BcpackProvisionalError( + f"BC3 block {i} references unconfirmed built-in history entry {entry}" + ) + base = loose[entry] + provisional.add(f"BC3 history {entry}") + if base is None: + if provisional is None: + raise BcpackProvisionalError( + f"BC3 block {i} references unknown built-in history entry {entry}" + ) + base = _BC3_NONE + lost[i] = True + unknown.add(entry) + dz = (alpha[a], alpha[b], lr[a], lg[a], lb[a], lr[b], lg[b], lb[b]) + e = tuple((base[k] + _unzig(dz[k])) % mods[k] for k in range(8)) + hist[i] = e + bits = 0 + for r in range(4): + left, right = pairs[rows[r][a]], pairs[rows[r][b]] + bits |= (left[0] | (left[1] << 3) | (right[0] << 6) | (right[1] << 9)) << (12 * r) + at = i * 16 + out[at] = e[0] + out[at + 1] = e[1] + out[at + 2:at + 8] = bits.to_bytes(6, "little") + c0 = (e[2] << 11) | (e[3] << 5) | e[4] + c1 = (e[5] << 11) | (e[6] << 5) | e[7] + qa, qb = quads[top[a]], quads[top[b]] + qc, qd = quads[bottom[a]], quads[bottom[b]] + struct.pack_into( + "> 4) | ((qb >> 4) << 4), + (qc & 15) | ((qd & 15) << 4), + (qc >> 4) | ((qd >> 4) << 4), + ) + if unknown: + total = sum(lost) + if total > _loose_limit(nblocks): + raise BcpackProvisionalError( + f"BC3 chunk has {total}/{nblocks} blocks from unknown built-in history entries" + ) + provisional.add(f"BC3 unknown history {sorted(unknown)} ({total} blocks)") + return bytes(out) + + +def _bc4_blocks(lanes, nblocks, provisional): + if any(lanes[1]): + raise BcpackError("BC4 lane 1 is non-zero (unexpected)") + pairs = _tables.BC4_PAIR + confirmed = _tables.BC4_HISTORY_CONFIRMED + loose = _tables.BC4_HISTORY_PROVISIONAL + out = bytearray(nblocks * 8) + hist = [None] * nblocks + l0, l2, l3 = lanes[0], lanes[2], lanes[3] + rows = lanes[4:12] + for i in range(nblocks): + v = l0[i] + d = 256 - ((v + 1) >> 1) if (v & 1) else (v >> 1) + if d == 0: + base = (128, 128) + elif i - d >= 0: + base = hist[i - d] + else: + entry = 256 + i - d + base = confirmed.get(entry) + if base is None: + if provisional is not None and entry in loose: + base = loose[entry] + provisional.add(f"BC4 history {entry}") + else: + state = "unconfirmed" if entry in loose else "unknown" + raise BcpackProvisionalError( + f"BC4 block {i} references {state} built-in history entry {entry}" + ) + a0 = (base[0] + _unzig(l2[i])) & 255 + a1 = (base[1] + _unzig(l3[i])) & 255 + hist[i] = (a0, a1) + bits = 0 + for r in range(4): + left, right = pairs[rows[2 * r][i]], pairs[rows[2 * r + 1][i]] + bits |= (left[0] | (left[1] << 3) | (right[0] << 6) | (right[1] << 9)) << (12 * r) + at = i * 8 + out[at] = a0 + out[at + 1] = a1 + out[at + 2:at + 8] = bits.to_bytes(6, "little") + return bytes(out) + + +def _bc5_blocks(lanes, nblocks, provisional): + if any(lanes[1]): + raise BcpackError("BC5 lane 1 is non-zero (unexpected)") + pairs = _tables.BC5_PAIR + confirmed = _tables.BC5_HISTORY_CONFIRMED + loose = _tables.BC5_HISTORY_PROVISIONAL + out = bytearray(nblocks * 16) + hist = [None] * nblocks + lost = [False] * nblocks + l0, red, green = lanes[0], lanes[2], lanes[3] + rows = lanes[4:12] + unknown = set() + for i in range(nblocks): + a, b = 2 * i, 2 * i + 1 + d = _unzig(_inter8(l0[a], l0[b])) & 255 + if d == 0: + base = (128, 128, 128, 128) + elif i - d >= 0: + base = hist[i - d] + lost[i] = lost[i - d] + else: + entry = 256 + i - d + base = confirmed.get(entry) + if base is None and entry in loose: + if provisional is None: + raise BcpackProvisionalError( + f"BC5 block {i} references unconfirmed built-in history entry {entry}" + ) + base = loose[entry] + provisional.add(f"BC5 history {entry}") + if base is None: + if provisional is None: + raise BcpackProvisionalError( + f"BC5 block {i} references unknown built-in history entry {entry}" + ) + base = (128, 128, 128, 128) + lost[i] = True + unknown.add(entry) + e = ( + (base[0] + _unzig(red[a])) & 255, + (base[1] + _unzig(red[b])) & 255, + (base[2] + _unzig(green[a])) & 255, + (base[3] + _unzig(green[b])) & 255, + ) + hist[i] = e + at = i * 16 + for ch in range(2): + bits = 0 + for r in range(4): + left, right = pairs[rows[4 * ch + r][a]], pairs[rows[4 * ch + r][b]] + bits |= (left[0] | (left[1] << 3) | (right[0] << 6) | (right[1] << 9)) << (12 * r) + out[at + 8 * ch] = e[2 * ch] + out[at + 8 * ch + 1] = e[2 * ch + 1] + out[at + 8 * ch + 2:at + 8 * ch + 8] = bits.to_bytes(6, "little") + if unknown: + total = sum(lost) + if total > _loose_limit(nblocks): + raise BcpackProvisionalError( + f"BC5 chunk has {total}/{nblocks} blocks from unknown built-in history entries" + ) + provisional.add(f"BC5 unknown history {sorted(unknown)} ({total} blocks)") + return bytes(out) + + +_REBUILDERS = { + 1: _bc1_blocks, + 3: _bc3_blocks, + 4: _bc4_blocks, + 5: _bc5_blocks, +} + + +def decode_with_info(raw, codec, out_size, *, allow_provisional=False): + """Decode one BCPack chunk, returning `(decoded_bytes, provisional_labels)`. + + When `allow_provisional` is False (strict mode), any unconfirmed or unknown + built-in history reference raises `BcpackProvisionalError` and the returned + set is always empty. + """ + rebuilder = _REBUILDERS.get(codec) + if rebuilder is None: + name = CODEC_NAMES.get(codec, str(codec)) + raise BcpackUnsupportedCodec(f"BCPack block rebuilder for codec {codec} ({name}) is not implemented yet") + lanes, _ = decode_lanes(raw, codec, out_size) + nblocks = out_size // BLOCK_BYTES[codec] + prov = set() if allow_provisional else None + data = rebuilder(lanes, nblocks, prov) + return data, (prov if prov is not None else set()) + + +def decode(raw, codec, out_size, *, allow_provisional=False): + """Decode one BCPack chunk into `out_size` bytes of standard BCn blocks.""" + data, _ = decode_with_info(raw, codec, out_size, allow_provisional=allow_provisional) + return data diff --git a/tools/bcpack_tables.py b/tools/bcpack_tables.py new file mode 100644 index 000000000..fe1b17cc4 --- /dev/null +++ b/tools/bcpack_tables.py @@ -0,0 +1,463 @@ +"""Fixed codec constant tables for the clean-room BCPack decoder. + +All values here are codec-level constants (rANS exponential probability models, +symbol-rank tables, and built-in initial endpoint history entries), not game +texture assets. Recovered clean-room from public specifications (US patent +11,234,023 and BCn block formats) and statistical/algebraic fitting; confirmed +and provisional built-in history entries are kept strictly separate so callers +can refuse unconfirmed entries by default. +""" + +# (symbol_width, q) -> per-band rANS frequencies (band 0 is symbol 0; +# band p >= 1 covers symbols [2^(p-1), 2^p)); total weight is 65536. +PROB_TABLES = { + (1, 0): (32768, 32768), + (1, 1): (38761, 26775), + (1, 2): (44484, 21052), + (1, 3): (49818, 15718), + (1, 4): (54623, 10913), + (1, 5): (58721, 6815), + (1, 6): (61911, 3625), + (1, 7): (64036, 1500), + (1, 8): (65121, 415), + (1, 9): (65477, 59), + (1, 10): (65534, 2), + (1, 11): (65535, 1), + (1, 12): (65535, 1), + (1, 13): (65535, 1), + (1, 14): (65535, 1), + (1, 15): (65535, 1), + (2, 0): (16384, 16384, 16384), + (2, 1): (21168, 17592, 13388), + (2, 2): (26354, 18130, 10526), + (2, 3): (31900, 17918, 7859), + (2, 4): (37750, 16874, 5456), + (2, 5): (43800, 14920, 3408), + (2, 6): (49850, 12062, 1812), + (2, 7): (55537, 8499, 750), + (2, 8): (60308, 4812, 208), + (2, 9): (63575, 1901, 30), + (2, 10): (65132, 402, 1), + (2, 11): (65511, 23, 1), + (2, 12): (65533, 1, 1), + (2, 13): (65533, 1, 1), + (2, 14): (65533, 1, 1), + (2, 15): (65533, 1, 1), + (3, 0): (8192, 8192, 8192, 8192), + (3, 1): (11073, 10095, 8796, 6694), + (3, 2): (14406, 11948, 9065, 5263), + (3, 3): (18234, 13666, 8958, 3930), + (3, 4): (22624, 15126, 8437, 2728), + (3, 5): (27657, 16143, 7460, 1704), + (3, 6): (33414, 16436, 6031, 906), + (3, 7): (39920, 15616, 4250, 375), + (3, 8): (47024, 13284, 2406, 104), + (3, 9): (54201, 9375, 950, 15), + (3, 10): (60388, 4744, 200, 1), + (3, 11): (64250, 1262, 10, 1), + (3, 12): (65456, 74, 1, 1), + (3, 13): (65529, 1, 1, 1), + (3, 14): (65529, 1, 1, 1), + (3, 15): (65529, 1, 1, 1), + (4, 0): (4096, 4096, 4096, 4096, 4096), + (4, 1): (5665, 5407, 5048, 4398, 3347), + (4, 2): (7539, 6867, 5973, 4532, 2632), + (4, 3): (9773, 8461, 6833, 4479, 1965), + (4, 4): (12447, 10177, 7564, 4218, 1364), + (4, 5): (15679, 11977, 8072, 3730, 852), + (4, 6): (19640, 13774, 8217, 3016, 453), + (4, 7): (24559, 15361, 7808, 2124, 188), + (4, 8): (30704, 16320, 6642, 1203, 52), + (4, 9): (38280, 15920, 4688, 476, 7), + (4, 10): (47169, 13219, 2372, 99, 1), + (4, 11): (56354, 7896, 631, 4, 1), + (4, 12): (63248, 2208, 34, 1, 1), + (4, 13): (65465, 57, 1, 1, 1), + (4, 14): (65521, 1, 1, 1, 1), + (4, 15): (65521, 1, 1, 1, 1), + (5, 0): (2048, 2048, 2048, 2048, 2048, 2048), + (5, 1): (2865, 2799, 2704, 2524, 2200, 1673), + (5, 2): (3858, 3682, 3434, 2986, 2266, 1316), + (5, 3): (5063, 4709, 4230, 3418, 2240, 982), + (5, 4): (6536, 5912, 5088, 3782, 2109, 682), + (5, 5): (8366, 7314, 5988, 4036, 1865, 426), + (5, 6): (10688, 8952, 6888, 4108, 1507, 227), + (5, 7): (13713, 10847, 7680, 3904, 1062, 94), + (5, 8): (17758, 12946, 8160, 3320, 602, 26), + (5, 9): (23272, 15008, 7960, 2344, 237, 4), + (5, 10): (30841, 16327, 6610, 1187, 48, 1), + (5, 11): (41006, 15348, 3947, 316, 1, 1), + (5, 12): (53291, 9957, 1104, 14, 1, 1), + (5, 13): (63380, 2084, 22, 1, 1, 1), + (5, 14): (65505, 1, 1, 1, 1, 1), + (5, 15): (65505, 1, 1, 1, 1, 1), + (6, 0): (1024, 1024, 1024, 1024, 1024, 1024, 1024), + (6, 1): (1441, 1423, 1400, 1352, 1262, 1099, 837), + (6, 2): (1951, 1907, 1841, 1717, 1493, 1133, 658), + (6, 3): (2577, 2487, 2354, 2115, 1709, 1120, 491), + (6, 4): (3350, 3186, 2956, 2544, 1890, 1055, 341), + (6, 5): (4324, 4042, 3657, 2994, 2019, 932, 213), + (6, 6): (5581, 5107, 4476, 3444, 2055, 754, 113), + (6, 7): (7258, 6454, 5424, 3840, 1952, 531, 47), + (6, 8): (9579, 8179, 6473, 4080, 1660, 301, 13), + (6, 9): (12907, 10365, 7504, 3980, 1171, 119, 2), + (6, 10): (17852, 12988, 8164, 3304, 594, 23, 1), + (6, 11): (25441, 15565, 7673, 1974, 155, 1, 1), + (6, 12): (37208, 16084, 4978, 552, 4, 1, 1), + (6, 13): (53649, 9731, 1042, 4, 1, 1, 1), + (6, 14): (65147, 327, 1, 1, 1, 1, 1), + (6, 15): (65473, 1, 1, 1, 1, 1, 1), + (7, 0): (512, 512, 512, 512, 512, 512, 512, 512), + (7, 1): (722, 718, 712, 700, 676, 632, 550, 418), + (7, 2): (981, 971, 952, 920, 858, 748, 566, 329), + (7, 3): (1300, 1276, 1244, 1178, 1058, 854, 559, 246), + (7, 4): (1696, 1654, 1593, 1478, 1272, 946, 526, 171), + (7, 5): (2198, 2126, 2022, 1828, 1498, 1009, 467, 106), + (7, 6): (2852, 2728, 2554, 2238, 1721, 1028, 376, 57), + (7, 7): (3736, 3522, 3227, 2712, 1920, 977, 266, 23), + (7, 8): (4979, 4601, 4090, 3236, 2040, 831, 151, 6), + (7, 9): (6807, 6101, 5182, 3752, 1991, 586, 59, 1), + (7, 10): (9634, 8218, 6494, 4082, 1652, 296, 11, 1), + (7, 11): (14275, 11165, 7784, 3836, 988, 74, 1, 1), + (7, 12): (22449, 14759, 8042, 2489, 272, 1, 1, 1), + (7, 13): (37625, 16023, 4866, 509, 1, 1, 1, 1), + (7, 14): (60485, 4663, 132, 1, 1, 1, 1, 1), + (7, 15): (65409, 1, 1, 1, 1, 1, 1, 1), + (8, 0): (256, 256, 256, 256, 256, 256, 256, 256, 256), + (8, 1): (362, 360, 359, 356, 350, 338, 316, 275, 209), + (8, 2): (492, 488, 486, 476, 460, 429, 374, 284, 164), + (8, 3): (653, 647, 638, 622, 589, 529, 426, 280, 123), + (8, 4): (853, 843, 828, 796, 739, 636, 473, 264, 85), + (8, 5): (1108, 1090, 1063, 1011, 914, 748, 504, 234, 53), + (8, 6): (1442, 1410, 1364, 1277, 1120, 860, 514, 189, 28), + (8, 7): (1895, 1841, 1760, 1614, 1356, 961, 488, 132, 12), + (8, 8): (2538, 2442, 2300, 2045, 1618, 1021, 414, 76, 3), + (8, 9): (3497, 3311, 3050, 2591, 1875, 996, 292, 29, 1), + (8, 10): (5008, 4626, 4109, 3247, 2041, 826, 149, 4, 1), + (8, 11): (7575, 6701, 5582, 3892, 1918, 494, 34, 1, 1), + (8, 12): (12397, 10051, 7380, 4020, 1245, 129, 1, 1, 1), + (8, 13): (22767, 14857, 8012, 2432, 240, 1, 1, 1, 1), + (8, 14): (47343, 13141, 2332, 35, 1, 1, 1, 1, 1), + (8, 15): (65281, 1, 1, 1, 1, 1, 1, 1, 1), + (9, 0): (128, 128, 128, 128, 128, 128, 128, 128, 128, 128), + (9, 1): (181, 181, 179, 180, 178, 175, 169, 157, 137, 105), + (9, 2): (246, 246, 244, 243, 238, 231, 214, 187, 142, 82), + (9, 3): (327, 325, 324, 319, 310, 294, 265, 213, 141, 61), + (9, 4): (428, 424, 422, 414, 397, 370, 319, 236, 131, 43), + (9, 5): (557, 551, 546, 530, 506, 457, 374, 252, 116, 27), + (9, 6): (725, 717, 705, 683, 638, 560, 430, 256, 95, 14), + (9, 7): (955, 941, 920, 880, 807, 677, 481, 244, 66, 6), + (9, 8): (1282, 1256, 1219, 1150, 1023, 810, 510, 207, 37, 2), + (9, 9): (1772, 1724, 1656, 1524, 1295, 938, 498, 147, 13, 1), + (9, 10): (2554, 2454, 2312, 2054, 1625, 1020, 414, 74, 1, 1), + (9, 11): (3904, 3672, 3350, 2791, 1946, 959, 247, 14, 1, 1), + (9, 12): (6523, 5873, 5026, 3690, 2011, 621, 58, 1, 1, 1), + (9, 13): (12593, 10175, 7428, 4006, 1216, 105, 1, 1, 1, 1), + (9, 14): (31009, 16335, 6572, 1136, 1, 1, 1, 1, 1, 1), + (9, 15): (65025, 1, 1, 1, 1, 1, 1, 1, 1, 1), + (10, 0): (64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64), + (10, 1): (91, 89, 90, 90, 90, 90, 88, 85, 79, 69, 52), + (10, 2): (123, 123, 123, 123, 121, 120, 115, 108, 93, 71, 41), + (10, 3): (164, 164, 162, 161, 160, 155, 148, 131, 108, 69, 31), + (10, 4): (214, 214, 212, 211, 206, 199, 184, 160, 117, 67, 21), + (10, 5): (279, 277, 276, 273, 265, 252, 229, 187, 126, 59, 13), + (10, 6): (364, 360, 358, 352, 342, 319, 280, 215, 129, 47, 7), + (10, 7): (479, 477, 470, 460, 441, 404, 339, 240, 122, 33, 3), + (10, 8): (644, 638, 627, 610, 576, 511, 405, 254, 105, 18, 1), + (10, 9): (892, 880, 862, 828, 763, 647, 469, 248, 73, 6, 1), + (10, 10): (1290, 1264, 1227, 1156, 1028, 812, 510, 207, 34, 1, 1), + (10, 11): (1982, 1922, 1836, 1674, 1396, 972, 481, 123, 4, 1, 1), + (10, 12): (3347, 3177, 2936, 2513, 1846, 1004, 311, 22, 1, 1, 1), + (10, 13): (6632, 5962, 5087, 3714, 2003, 609, 37, 1, 1, 1, 1), + (10, 14): (17963, 13041, 8168, 3285, 506, 1, 1, 1, 1, 1, 1), + (10, 15): (64513, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), +} + +# BC1 index lanes: symbol -> 2x2 quadrant byte (TL, TR, BL, BR in bits 0-1, 2-3, 4-5, 6-7). +BC1_QUADRANT = bytes([ + 0xaa, 0xff, 0x00, 0x55, 0xfa, 0xaf, 0xfb, 0xbf, 0xfe, 0xef, 0xbb, 0xee, 0xdf, 0xba, 0x5a, 0xae, + 0x7f, 0xea, 0xab, 0xf7, 0xfd, 0xa5, 0x5f, 0xf5, 0xdd, 0x77, 0x66, 0x99, 0x2a, 0x8a, 0xa2, 0x50, + 0x05, 0xa8, 0x11, 0x9a, 0x44, 0x3f, 0xa6, 0xa9, 0xcf, 0xbe, 0xfc, 0xf3, 0x6a, 0xeb, 0x7e, 0xe7, + 0xdb, 0xbd, 0x7a, 0xa7, 0xda, 0x0f, 0xad, 0x57, 0xd5, 0x0a, 0x5d, 0x75, 0x2f, 0x6e, 0xf0, 0x8f, + 0xf8, 0xe6, 0x3d, 0xf2, 0xb9, 0x25, 0x7c, 0x9b, 0x3b, 0x85, 0xce, 0xec, 0x58, 0xb3, 0xd3, 0xa0, + 0x52, 0xde, 0x7b, 0x2b, 0xb7, 0x5e, 0xc7, 0xed, 0x5b, 0xb2, 0x8e, 0xcc, 0x6f, 0x19, 0xf6, 0x9f, + 0x64, 0xe8, 0xe5, 0x29, 0xf9, 0x33, 0x46, 0x22, 0xb5, 0xd7, 0x2d, 0x78, 0x56, 0x86, 0x88, 0x68, + 0x91, 0x95, 0x92, 0xd2, 0x87, 0x7d, 0x76, 0x67, 0x9d, 0x59, 0x65, 0xd9, 0x15, 0x37, 0x93, 0x5c, + 0xc6, 0x35, 0x6c, 0xcd, 0x39, 0x45, 0xdc, 0x54, 0x73, 0x51, 0x53, 0xc5, 0x2e, 0x8b, 0x8d, 0x27, + 0xe2, 0x1f, 0xf4, 0x1d, 0xd8, 0xf1, 0x72, 0xa3, 0x4f, 0x74, 0xb8, 0xca, 0x3a, 0xac, 0xd1, 0x89, + 0x47, 0x26, 0x62, 0x98, 0x70, 0x0d, 0xa1, 0x1a, 0x4a, 0x6b, 0x1b, 0xd0, 0xa4, 0xe9, 0x07, 0xb1, + 0x9e, 0xb6, 0xe4, 0x4e, 0xbc, 0xe3, 0x3e, 0xcb, 0x82, 0x31, 0x02, 0x28, 0x4c, 0x13, 0xc4, 0x20, + 0x0e, 0x0b, 0x08, 0x96, 0x80, 0xe0, 0x09, 0xb0, 0x69, 0x60, 0x06, 0x90, 0x23, 0x97, 0x8c, 0xd6, + 0x21, 0x6d, 0x79, 0x32, 0xc8, 0x48, 0x84, 0x17, 0x12, 0xd4, 0x4d, 0x71, 0x01, 0x36, 0x63, 0x9c, + 0xc9, 0x40, 0x04, 0x10, 0xe1, 0x16, 0x94, 0x49, 0x4b, 0x1e, 0xb4, 0x61, 0x03, 0x0c, 0xc0, 0x42, + 0x81, 0x18, 0x30, 0x24, 0xc3, 0x3c, 0xc2, 0x41, 0x14, 0x83, 0x2c, 0x38, 0x43, 0x34, 0x1c, 0xc1, +]) + +# BC1 built-in 256-entry endpoint history: index -> (r0, g0, b0, r1, g1, b1). +BC1_HISTORY_CONFIRMED = { + 1: (7, 29, 6, 8, 30, 7), 2: (15, 29, 15, 16, 36, 17), 3: (20, 38, 14, 3, 5, 2), + 4: (12, 27, 13, 6, 12, 6), 5: (10, 22, 11, 6, 14, 7), 7: (12, 26, 12, 7, 14, 7), + 8: (22, 36, 15, 20, 32, 14), 10: (23, 5, 30, 9, 5, 30), 11: (11, 22, 11, 7, 15, 7), + 12: (17, 22, 7, 10, 11, 3), 13: (12, 25, 12, 7, 16, 7), 14: (13, 28, 8, 5, 11, 3), + 15: (11, 20, 8, 16, 31, 14), 16: (23, 32, 30, 17, 12, 29), 17: (8, 44, 30, 6, 26, 30), + 18: (10, 24, 30, 6, 45, 30), 19: (10, 12, 4, 8, 8, 2), 20: (16, 23, 30, 14, 6, 26), + 21: (12, 25, 13, 10, 22, 12), 22: (19, 27, 10, 12, 15, 5), 23: (11, 24, 12, 4, 11, 6), + 24: (29, 60, 29, 6, 13, 6), 25: (17, 31, 11, 1, 2, 1), 26: (26, 54, 24, 12, 24, 10), + 27: (23, 49, 30, 20, 36, 30), 28: (16, 23, 10, 10, 14, 6), 29: (11, 24, 10, 6, 13, 5), + 30: (18, 52, 30, 14, 22, 30), 31: (14, 51, 30, 9, 34, 30), 32: (2, 3, 1, 19, 37, 16), + 33: (14, 15, 30, 9, 31, 30), 34: (29, 57, 27, 27, 52, 25), 35: (13, 29, 15, 8, 20, 11), + 36: (13, 17, 5, 9, 10, 3), 37: (18, 50, 29, 15, 10, 29), 38: (11, 25, 13, 8, 19, 10), + 39: (17, 32, 12, 6, 11, 4), 40: (22, 18, 30, 19, 41, 30), 41: (10, 22, 11, 8, 18, 9), + 42: (18, 30, 31, 10, 44, 30), 43: (25, 50, 24, 2, 4, 1), 44: (11, 30, 31, 7, 15, 29), + 45: (12, 19, 8, 11, 16, 7), 46: (19, 29, 30, 14, 55, 28), 47: (9, 20, 10, 4, 10, 5), + 48: (12, 24, 10, 7, 13, 5), 49: (26, 53, 25, 6, 13, 6), 50: (19, 27, 31, 11, 19, 30), + 51: (21, 31, 30, 22, 31, 30), 52: (10, 19, 5, 11, 21, 6), 53: (30, 50, 3, 29, 46, 2), + 54: (15, 9, 30, 7, 9, 30), 55: (14, 18, 6, 11, 14, 4), 56: (28, 56, 26, 4, 7, 3), + 57: (9, 20, 10, 5, 13, 7), 58: (28, 58, 26, 15, 32, 14), 59: (11, 19, 8, 6, 9, 4), + 60: (16, 22, 9, 13, 17, 7), 61: (1, 2, 1, 14, 28, 12), 62: (22, 45, 30, 9, 15, 30), + 63: (19, 22, 30, 16, 23, 31), 64: (25, 50, 24, 21, 43, 20), 65: (6, 11, 4, 16, 31, 13), + 66: (13, 25, 8, 3, 6, 1), 69: (20, 38, 16, 13, 25, 10), 70: (18, 35, 15, 5, 9, 3), + 72: (11, 21, 7, 7, 13, 4), 73: (20, 39, 16, 11, 20, 8), 75: (22, 41, 30, 18, 23, 30), + 76: (24, 50, 24, 9, 19, 8), 77: (3, 12, 7, 4, 16, 8), 78: (18, 27, 12, 16, 22, 10), + 79: (24, 49, 23, 13, 28, 12), 80: (24, 50, 24, 18, 37, 18), 81: (17, 33, 12, 14, 27, 9), + 82: (20, 10, 31, 13, 10, 31), 83: (7, 8, 2, 5, 5, 1), 84: (1, 2, 1, 10, 21, 9), + 85: (10, 18, 6, 1, 1, 0), 86: (22, 46, 21, 1, 3, 1), 87: (11, 20, 8, 8, 14, 5), + 88: (17, 35, 31, 14, 14, 29), 89: (16, 22, 31, 12, 40, 31), 90: (12, 22, 9, 8, 15, 6), + 91: (18, 15, 30, 15, 33, 31), 92: (19, 32, 30, 15, 43, 31), 93: (18, 35, 15, 8, 15, 5), + 94: (21, 43, 20, 18, 37, 17), 95: (10, 17, 6, 9, 15, 6), 96: (14, 27, 12, 7, 13, 5), + 97: (8, 16, 7, 12, 25, 11), 98: (18, 37, 17, 1, 1, 0), 99: (17, 45, 30, 15, 33, 31), + 100: (13, 25, 11, 8, 16, 7), 101: (23, 47, 22, 16, 32, 15), 102: (18, 33, 13, 11, 21, 8), + 103: (4, 10, 4, 8, 17, 7), 104: (1, 2, 1, 3, 7, 3), 105: (11, 22, 9, 6, 11, 4), + 106: (16, 29, 11, 13, 23, 9), 107: (12, 24, 12, 6, 12, 6), 108: (23, 47, 22, 7, 14, 6), + 109: (11, 32, 30, 11, 31, 30), 110: (14, 26, 11, 10, 18, 7), 111: (20, 41, 19, 1, 3, 1), + 112: (14, 28, 12, 8, 16, 6), 113: (11, 21, 9, 8, 15, 6), 114: (1, 2, 1, 7, 13, 6), + 115: (19, 35, 14, 16, 29, 12), 116: (13, 27, 13, 7, 15, 7), 117: (15, 33, 16, 8, 18, 9), + 118: (15, 42, 31, 11, 22, 30), 119: (23, 48, 23, 4, 9, 4), 120: (22, 45, 21, 11, 22, 10), + 121: (31, 62, 30, 31, 61, 29), 123: (19, 39, 19, 9, 20, 10), 124: (7, 14, 2, 6, 12, 2), + 125: (21, 42, 20, 3, 7, 3), 126: (10, 17, 7, 8, 13, 5), 127: (11, 20, 8, 9, 17, 7), + 128: (19, 33, 31, 12, 31, 31), 129: (21, 43, 20, 5, 11, 5), 130: (10, 20, 9, 7, 13, 6), + 131: (10, 21, 10, 6, 13, 6), 132: (15, 29, 12, 11, 20, 8), 133: (21, 43, 20, 9, 18, 8), + 134: (3, 8, 3, 5, 11, 5), 135: (16, 31, 13, 9, 17, 7), 136: (11, 22, 11, 6, 12, 6), + 137: (10, 21, 10, 7, 15, 7), 138: (27, 3, 1, 26, 1, 0), 139: (18, 37, 18, 16, 32, 16), + 140: (12, 23, 10, 9, 17, 7), 141: (12, 25, 12, 8, 17, 8), 142: (11, 21, 9, 2, 4, 1), + 143: (7, 15, 7, 8, 18, 9), 144: (17, 33, 15, 13, 24, 11), 145: (9, 19, 9, 7, 15, 7), + 146: (21, 43, 20, 13, 27, 12), 147: (17, 36, 17, 2, 4, 2), 148: (10, 20, 9, 6, 12, 5), + 149: (20, 41, 19, 7, 14, 7), 150: (3, 9, 6, 2, 8, 5), 151: (13, 24, 10, 11, 20, 8), + 152: (18, 38, 18, 4, 7, 3), 153: (19, 38, 18, 8, 17, 8), 154: (16, 35, 17, 4, 10, 4), + 155: (11, 23, 11, 10, 21, 10), 156: (17, 36, 17, 7, 14, 7), 157: (13, 27, 13, 6, 12, 6), + 158: (9, 15, 4, 8, 13, 4), 159: (10, 19, 7, 5, 9, 3), 160: (19, 40, 19, 11, 24, 11), + 161: (11, 23, 11, 8, 17, 8), 162: (14, 29, 14, 7, 15, 7), 163: (12, 22, 9, 5, 8, 3), + 164: (10, 20, 9, 8, 17, 8), 165: (21, 42, 19, 15, 31, 14), 166: (14, 29, 13, 1, 1, 0), + 167: (8, 16, 8, 7, 14, 7), 168: (9, 18, 8, 8, 16, 7), 169: (10, 17, 7, 3, 4, 1), + 170: (14, 28, 13, 2, 4, 1), 171: (14, 30, 14, 3, 6, 3), 172: (19, 38, 18, 5, 11, 5), + 173: (12, 26, 12, 1, 2, 1), 174: (9, 16, 6, 8, 13, 5), 175: (8, 13, 4, 7, 11, 4), + 176: (16, 34, 16, 3, 7, 3), 177: (13, 28, 13, 4, 9, 4), 178: (15, 31, 15, 6, 13, 6), + 179: (12, 24, 11, 9, 19, 9), 180: (9, 19, 8, 7, 14, 6), 181: (14, 28, 13, 5, 10, 4), + 182: (10, 20, 7, 4, 6, 2), 183: (16, 34, 17, 11, 25, 12), 184: (15, 30, 15, 8, 16, 8), + 185: (13, 27, 13, 10, 20, 10), 186: (9, 20, 9, 0, 1, 0), 187: (16, 32, 15, 2, 4, 2), + 188: (13, 27, 12, 3, 6, 3), 189: (13, 26, 12, 12, 23, 11), 190: (12, 25, 12, 5, 10, 5), + 191: (11, 23, 11, 5, 11, 5), 192: (16, 34, 16, 6, 12, 5), 193: (16, 35, 31, 15, 25, 31), + 194: (16, 33, 16, 7, 15, 7), 195: (13, 27, 13, 8, 18, 8), 196: (18, 36, 17, 11, 22, 10), + 197: (18, 37, 18, 13, 27, 13), 198: (12, 25, 12, 4, 8, 4), 199: (9, 18, 7, 6, 11, 4), + 200: (15, 30, 14, 9, 19, 9), 201: (17, 35, 16, 9, 18, 9), 202: (11, 24, 11, 2, 4, 2), + 203: (16, 33, 16, 0, 1, 0), 204: (15, 31, 15, 4, 9, 4), 205: (16, 31, 15, 14, 27, 13), + 206: (14, 29, 14, 13, 25, 12), 207: (11, 23, 11, 3, 6, 3), 208: (16, 32, 16, 10, 21, 10), + 209: (11, 22, 11, 4, 9, 4), 210: (11, 22, 10, 1, 2, 0), 211: (8, 14, 5, 2, 4, 1), + 212: (9, 16, 6, 6, 10, 4), 213: (10, 21, 10, 9, 19, 9), 214: (14, 30, 14, 11, 22, 11), + 215: (9, 18, 8, 6, 13, 6), 216: (6, 13, 6, 5, 11, 5), 217: (7, 14, 6, 0, 1, 0), + 218: (4, 7, 2, 3, 4, 1), 219: (10, 20, 9, 4, 8, 4), 220: (9, 17, 7, 5, 9, 3), + 221: (7, 14, 7, 1, 2, 1), 222: (10, 20, 10, 5, 10, 5), 223: (8, 15, 5, 4, 6, 2), + 224: (8, 17, 8, 1, 2, 1), 225: (10, 20, 10, 3, 6, 3), 226: (7, 10, 3, 6, 8, 3), + 227: (8, 15, 7, 6, 12, 6), 228: (9, 19, 9, 2, 4, 2), 229: (6, 11, 4, 3, 4, 1), + 230: (6, 11, 4, 0, 1, 0), 231: (8, 16, 7, 2, 4, 2), 232: (16, 34, 16, 15, 29, 15), + 233: (7, 16, 7, 5, 10, 5), 234: (8, 14, 5, 5, 9, 3), 235: (9, 18, 8, 4, 8, 4), + 236: (5, 9, 3, 4, 7, 2), 237: (9, 18, 8, 5, 10, 5), 238: (6, 12, 6, 2, 4, 2), + 239: (7, 12, 5, 4, 7, 3), 240: (5, 11, 5, 1, 2, 1), 241: (8, 17, 8, 3, 6, 3), + 242: (16, 31, 31, 16, 32, 31), 243: (7, 14, 7, 3, 6, 3), 244: (5, 11, 6, 4, 9, 4), + 245: (7, 15, 7, 4, 8, 4), 246: (2, 4, 2, 0, 0, 1), 247: (5, 11, 5, 3, 6, 3), + 248: (4, 8, 4, 1, 1, 1), 249: (3, 6, 3, 1, 2, 1), 250: (2, 4, 1, 1, 2, 1), + 251: (4, 8, 4, 3, 6, 3), 252: (3, 6, 3, 2, 4, 2), 253: (4, 9, 4, 2, 4, 2), + 254: (17, 27, 31, 15, 34, 31), 255: (0, 0, 1, 0, 0, 0), +} + +BC1_HISTORY_PROVISIONAL = { + 6: (12, 24, 11, 7, 14, 6), 9: (14, 23, 8, 1, 2, 1), 67: (5, 9, 3, 12, 24, 10), + 68: (16, 29, 13, 7, 13, 5), 71: (13, 25, 11, 6, 11, 4), 74: (16, 31, 12, 4, 8, 2), + 122: (13, 26, 11, 5, 8, 3), +} + +# BC3 3-bit alpha index pair rank table (64 entries) and colour quadrant rank table (256 entries). +BC3_ALPHA_PAIR = ( + (0, 0), (1, 1), (6, 6), (4, 4), (3, 3), (5, 5), (7, 7), (1, 6), + (6, 1), (0, 1), (1, 0), (7, 1), (1, 7), (0, 3), (3, 0), (0, 2), + (2, 0), (2, 2), (5, 4), (3, 4), (4, 3), (4, 5), (1, 5), (5, 1), + (0, 4), (4, 0), (2, 3), (3, 2), (5, 3), (3, 5), (6, 5), (5, 6), + (6, 7), (7, 6), (5, 7), (4, 6), (6, 4), (7, 5), (6, 0), (0, 6), + (4, 2), (2, 4), (4, 1), (1, 4), (5, 0), (0, 5), (6, 3), (3, 6), + (3, 1), (5, 2), (1, 3), (2, 5), (7, 4), (4, 7), (7, 3), (3, 7), + (2, 6), (6, 2), (2, 1), (1, 2), (0, 7), (7, 0), (2, 7), (7, 2), +) + +BC3_COLOUR_QUADRANT = bytes([ + 0x55, 0xaa, 0xff, 0x00, 0x50, 0x05, 0xaf, 0xfa, 0xae, 0xea, 0xab, 0xba, 0xee, 0xbb, 0xfe, 0xbf, + 0xef, 0xfb, 0xa5, 0x5a, 0xf0, 0x11, 0x0f, 0x44, 0xf5, 0x5f, 0xa0, 0x0a, 0x8a, 0xa2, 0xa8, 0x2a, + 0x7f, 0xf7, 0x77, 0xdf, 0xfd, 0xdd, 0x66, 0x99, 0x88, 0xbe, 0xeb, 0x22, 0xcc, 0x33, 0x8f, 0xf8, + 0x57, 0x75, 0xd5, 0x5d, 0x2f, 0xf2, 0x7a, 0x85, 0xa7, 0xda, 0x58, 0x25, 0xad, 0x52, 0x3f, 0xf3, + 0xcf, 0xe8, 0xfc, 0x8e, 0x2b, 0x7e, 0x6a, 0xa6, 0x9a, 0x70, 0x07, 0x0d, 0xa9, 0x78, 0x80, 0x08, + 0x02, 0xe7, 0xb2, 0x20, 0xdb, 0xd0, 0x87, 0x5e, 0xbd, 0x7c, 0x2d, 0xe5, 0xc7, 0xec, 0xce, 0x5b, + 0xb3, 0xd2, 0x2e, 0xb5, 0x3b, 0xe0, 0xe6, 0x6e, 0x68, 0x8b, 0x9b, 0xe2, 0xb9, 0x0e, 0xb8, 0x0b, + 0x3d, 0xd3, 0x51, 0x86, 0x27, 0x45, 0x15, 0xde, 0x54, 0x8d, 0xb7, 0xed, 0x7b, 0xb0, 0xd8, 0x29, + 0x72, 0x92, 0x7d, 0xd7, 0x35, 0xa3, 0xc5, 0x82, 0x37, 0x53, 0x28, 0x5c, 0x56, 0x65, 0x76, 0x95, + 0x59, 0xcd, 0x9f, 0x3a, 0x73, 0x89, 0xca, 0xac, 0x67, 0x9d, 0xf6, 0xd9, 0xf9, 0x91, 0x19, 0xdc, + 0x98, 0x6c, 0x46, 0x64, 0x6f, 0x26, 0x39, 0x62, 0xc6, 0x93, 0x09, 0x23, 0x06, 0x60, 0x8c, 0xc8, + 0x90, 0x32, 0x03, 0x3e, 0xc0, 0x13, 0x31, 0xe3, 0x4c, 0x9e, 0x0c, 0xc4, 0xcb, 0xbc, 0xb6, 0xe9, + 0x30, 0x6b, 0x1f, 0xf1, 0x1d, 0xd1, 0x47, 0x74, 0x4f, 0x10, 0x40, 0xf4, 0x01, 0x04, 0xa1, 0x1a, + 0xa4, 0x1b, 0x4a, 0xb1, 0xe4, 0x4e, 0x36, 0xc9, 0x9c, 0x63, 0x97, 0x71, 0x79, 0x17, 0x48, 0x69, + 0x21, 0x12, 0x3c, 0x84, 0x83, 0x6d, 0xd6, 0x96, 0xc3, 0x38, 0x1e, 0x4d, 0xe1, 0xd4, 0xc2, 0x2c, + 0x18, 0x81, 0xb4, 0x4b, 0x16, 0x61, 0xc1, 0x24, 0x1c, 0x49, 0x14, 0x42, 0x94, 0x41, 0x34, 0x43, +]) + +# BC3 built-in endpoint history: index -> (a0, a1, r0, g0, b0, r1, g1, b1). +BC3_HISTORY_CONFIRMED = {} + +BC3_HISTORY_PROVISIONAL = { + 2: (177, 134, 27, 55, 24, 14, 54, 24), 26: (255, 255, 21, 34, 8, 15, 22, 3), + 29: (220, 109, 17, 35, 17, 15, 30, 15), 30: (219, 96, 2, 53, 14, 2, 59, 16), + 35: (95, 65, 16, 31, 16, 15, 31, 15), 37: (136, 13, 16, 33, 16, 15, 32, 15), + 47: (146, 108, 18, 37, 18, 13, 26, 13), 52: (255, 255, 20, 38, 16, 3, 5, 2), + 71: (200, 51, 17, 34, 17, 15, 31, 15), 76: (170, 150, 2, 60, 20, 1, 61, 20), + 78: (248, 10, 3, 4, 2, 0, 1, 0), 95: (237, 229, 26, 51, 25, 1, 3, 1), + 98: (255, 0, 19, 38, 18, 14, 29, 13), 104: (255, 6, 13, 27, 13, 8, 17, 8), + 109: (254, 4, 15, 27, 11, 3, 4, 2), 112: (117, 39, 21, 41, 21, 1, 3, 1), + 126: (170, 119, 16, 31, 16, 15, 30, 15), 138: (122, 121, 14, 29, 14, 13, 27, 13), + 139: (247, 1, 15, 28, 13, 9, 16, 7), 153: (105, 126, 2, 7, 4, 1, 3, 2), + 154: (93, 100, 20, 40, 20, 15, 30, 15), 166: (91, 99, 17, 35, 17, 15, 30, 15), + 167: (155, 99, 16, 33, 16, 15, 31, 15), 177: (255, 255, 13, 24, 12, 11, 23, 10), + 185: (254, 255, 10, 17, 7, 2, 3, 1), 197: (253, 255, 11, 20, 9, 6, 11, 4), + 210: (254, 255, 5, 10, 5, 1, 2, 1), 220: (255, 255, 11, 20, 9, 9, 18, 7), + 225: (106, 113, 24, 39, 23, 0, 13, 0), 226: (1, 255, 8, 15, 7, 5, 10, 4), + 230: (1, 2, 0, 1, 1, 0, 0, 0), 232: (140, 131, 16, 31, 16, 15, 34, 16), + 237: (255, 254, 5, 11, 5, 4, 9, 3), 244: (255, 255, 1, 1, 1, 0, 0, 0), + 246: (253, 254, 3, 5, 2, 1, 2, 1), +} + +# BC4 3-bit index pair rank table (64 entries) and built-in endpoint history: index -> (a0, a1). +BC4_PAIR = ( + (1, 1), (0, 0), (3, 3), (6, 6), (4, 4), (5, 5), (3, 0), (0, 3), + (6, 1), (1, 6), (7, 7), (2, 2), (6, 3), (3, 6), (1, 0), (0, 1), + (4, 1), (1, 4), (3, 1), (1, 3), (6, 0), (0, 6), (4, 2), (7, 5), + (5, 7), (2, 4), (0, 5), (5, 0), (6, 4), (4, 6), (5, 3), (3, 5), + (4, 0), (0, 4), (1, 5), (5, 1), (3, 4), (4, 3), (2, 6), (6, 2), + (7, 3), (3, 7), (1, 2), (2, 1), (0, 7), (7, 0), (2, 5), (5, 2), + (7, 4), (4, 7), (4, 5), (5, 4), (3, 2), (2, 3), (0, 2), (2, 0), + (1, 7), (7, 1), (6, 5), (5, 6), (6, 7), (7, 6), (2, 7), (7, 2), +) + +BC4_HISTORY_CONFIRMED = {} + +BC4_HISTORY_PROVISIONAL = { + 25: (81, 50), 33: (58, 31), 77: (164, 124), 84: (204, 140), + 93: (208, 61), 101: (171, 137), 102: (212, 125), 116: (77, 34), + 119: (193, 127), 121: (178, 118), 126: (138, 108), 127: (132, 115), + 131: (165, 52), 142: (142, 80), 145: (74, 16), 148: (150, 124), + 154: (195, 103), 157: (71, 51), 163: (55, 33), 172: (139, 119), + 173: (42, 15), 178: (91, 47), 179: (48, 8), 184: (72, 34), + 185: (158, 136), 187: (105, 12), 188: (142, 38), 190: (43, 25), + 197: (133, 133), 200: (55, 17), 202: (82, 43), 207: (127, 129), + 208: (39, 9), 209: (134, 27), 211: (39, 23), 213: (19, 41), + 214: (39, 17), 217: (115, 21), 218: (118, 60), 221: (47, 17), + 223: (64, 25), 224: (119, 33), 227: (33, 16), 232: (78, 5), + 234: (33, 60), 235: (57, 24), 236: (69, 2), 239: (105, 24), + 240: (96, 34), 241: (111, 44), 243: (47, 25), 244: (84, 23), + 247: (22, 17), 252: (27, 8), 254: (12, 6), +} + +# BC5 3-bit index pair rank table (64 entries) and built-in endpoint history: index -> (r0, r1, g0, g1). +BC5_PAIR = ( + (0, 0), (1, 1), (4, 4), (3, 3), (6, 6), (7, 7), (4, 0), (0, 4), + (0, 1), (2, 2), (1, 0), (3, 0), (0, 3), (5, 5), (2, 0), (0, 2), + (1, 6), (6, 1), (4, 3), (1, 7), (3, 4), (1, 4), (7, 1), (6, 0), + (0, 6), (6, 3), (6, 4), (3, 6), (3, 2), (4, 6), (1, 5), (1, 3), + (2, 3), (5, 4), (5, 3), (5, 0), (4, 1), (7, 6), (4, 5), (4, 2), + (3, 1), (3, 5), (5, 1), (6, 7), (2, 4), (7, 5), (7, 4), (0, 5), + (6, 5), (4, 7), (5, 7), (7, 0), (5, 6), (0, 7), (7, 3), (3, 7), + (5, 2), (2, 5), (1, 2), (6, 2), (2, 1), (2, 6), (7, 2), (2, 7), +) + +BC5_HISTORY_CONFIRMED = { + 182: (133, 126, 124, 55), 183: (128, 126, 116, 112), 222: (131, 128, 123, 37), +} + +BC5_HISTORY_PROVISIONAL = { + 3: (130, 218, 45, 192), 4: (172, 109, 158, 94), 5: (183, 136, 113, 69), + 6: (125, 129, 86, 34), 7: (171, 196, 33, 82), 9: (142, 149, 102, 118), + 14: (82, 62, 26, 23), 15: (100, 94, 32, 32), 16: (97, 123, 61, 97), + 19: (133, 140, 118, 123), 20: (206, 194, 128, 123), 22: (147, 145, 64, 66), + 24: (76, 189, 55, 171), 27: (94, 115, 86, 102), 28: (163, 38, 152, 29), + 29: (143, 133, 89, 80), 30: (197, 67, 172, 50), 31: (164, 218, 130, 127), + 32: (141, 145, 111, 132), 33: (177, 125, 131, 32), 34: (49, 113, 26, 94), + 36: (173, 169, 40, 28), 38: (117, 125, 43, 50), 39: (139, 111, 99, 72), + 40: (123, 93, 83, 49), 41: (189, 166, 135, 116), 42: (198, 97, 178, 73), + 43: (205, 201, 76, 86), 44: (172, 174, 73, 72), 46: (157, 210, 136, 188), + 47: (126, 149, 115, 129), 48: (158, 67, 137, 41), 49: (214, 120, 131, 80), + 51: (147, 150, 119, 119), 52: (169, 107, 135, 65), 54: (231, 168, 223, 154), + 55: (115, 144, 99, 120), 56: (74, 104, 50, 83), 57: (220, 132, 32, 123), + 58: (150, 136, 110, 96), 60: (139, 147, 124, 108), 61: (121, 124, 78, 94), + 63: (169, 151, 124, 103), 64: (120, 106, 103, 88), 65: (134, 147, 110, 109), + 67: (133, 125, 103, 107), 68: (160, 133, 118, 123), 69: (175, 78, 163, 68), + 70: (229, 133, 166, 121), 71: (233, 147, 224, 134), 72: (127, 142, 104, 121), + 73: (134, 150, 99, 121), 74: (110, 149, 83, 129), 75: (175, 187, 129, 141), + 77: (115, 124, 96, 104), 78: (164, 128, 141, 109), 79: (129, 85, 114, 22), + 80: (246, 131, 241, 125), 82: (168, 186, 145, 165), 83: (192, 133, 158, 100), + 84: (107, 143, 105, 133), 85: (201, 212, 172, 181), 86: (124, 138, 116, 121), + 87: (92, 60, 71, 40), 88: (203, 134, 149, 126), 90: (61, 123, 25, 114), + 91: (123, 160, 113, 145), 92: (150, 169, 135, 150), 93: (134, 139, 101, 109), + 94: (253, 94, 255, 63), 95: (123, 87, 106, 67), 96: (238, 133, 121, 121), + 98: (24, 18, 15, 10), 99: (117, 41, 97, 25), 100: (123, 121, 70, 67), + 101: (64, 59, 51, 49), 102: (11, 103, 12, 88), 103: (144, 133, 111, 123), + 104: (189, 200, 65, 52), 105: (219, 153, 195, 135), 106: (150, 110, 138, 98), + 107: (118, 142, 60, 117), 108: (139, 145, 114, 118), 109: (216, 225, 191, 200), + 110: (46, 46, 38, 33), 111: (91, 132, 85, 126), 112: (154, 178, 115, 132), + 114: (131, 127, 125, 17), 115: (136, 134, 15, 123), 116: (131, 129, 105, 123), + 119: (132, 215, 122, 149), 120: (129, 138, 112, 111), 123: (136, 145, 119, 131), + 124: (179, 196, 165, 183), 125: (126, 125, 111, 92), 126: (136, 150, 122, 123), + 127: (168, 158, 136, 126), 128: (146, 153, 129, 134), 129: (127, 130, 85, 124), + 130: (132, 241, 120, 126), 131: (155, 124, 125, 85), 132: (121, 115, 115, 108), + 133: (106, 72, 89, 51), 134: (136, 155, 118, 137), 135: (121, 145, 106, 133), + 136: (119, 220, 102, 209), 137: (179, 136, 150, 122), 138: (120, 133, 102, 113), + 139: (145, 142, 111, 112), 140: (130, 108, 123, 62), 141: (121, 132, 37, 122), + 142: (157, 142, 135, 119), 143: (80, 201, 59, 191), 144: (130, 133, 122, 104), + 145: (138, 136, 112, 120), 146: (131, 107, 123, 37), 147: (122, 120, 107, 119), + 148: (126, 181, 121, 146), 149: (143, 141, 137, 135), 150: (134, 178, 121, 161), + 151: (103, 135, 55, 126), 152: (193, 132, 128, 123), 153: (141, 129, 111, 114), + 154: (79, 77, 53, 51), 155: (133, 72, 127, 64), 157: (102, 101, 83, 80), + 159: (92, 137, 39, 125), 160: (108, 136, 87, 122), 161: (102, 97, 65, 57), + 162: (163, 149, 151, 134), 163: (133, 17, 121, 15), 165: (179, 162, 153, 133), + 166: (119, 132, 98, 125), 167: (175, 132, 130, 124), 169: (132, 92, 124, 81), + 170: (40, 31, 27, 19), 171: (188, 211, 180, 202), 172: (139, 121, 117, 101), + 173: (150, 125, 130, 106), 174: (129, 184, 123, 131), 175: (132, 158, 126, 148), + 176: (130, 155, 126, 129), 177: (131, 167, 124, 127), 178: (155, 131, 132, 125), + 179: (198, 139, 170, 124), 180: (200, 196, 190, 186), 184: (173, 157, 163, 147), + 185: (197, 175, 158, 137), 186: (102, 129, 98, 126), 187: (131, 216, 121, 198), + 188: (127, 135, 115, 130), 189: (139, 196, 94, 111), 190: (132, 106, 123, 94), + 191: (219, 130, 193, 116), 192: (212, 133, 127, 124), 193: (196, 176, 173, 151), + 194: (56, 192, 15, 27), 195: (129, 198, 124, 131), 196: (131, 124, 125, 99), + 197: (176, 130, 169, 126), 198: (137, 127, 121, 111), 199: (144, 137, 131, 123), + 200: (132, 130, 114, 120), 201: (182, 165, 169, 153), 202: (138, 136, 113, 109), + 203: (185, 172, 179, 164), 204: (131, 127, 123, 81), 205: (124, 141, 121, 137), + 206: (173, 131, 136, 92), 208: (120, 133, 108, 123), 209: (147, 134, 123, 110), + 210: (130, 142, 125, 129), 211: (136, 137, 122, 131), 212: (130, 119, 127, 114), + 214: (117, 136, 111, 131), 215: (199, 181, 187, 167), 216: (132, 215, 124, 125), + 217: (135, 138, 120, 114), 218: (131, 85, 123, 45), 219: (197, 131, 193, 126), + 221: (69, 206, 57, 195), 223: (161, 156, 96, 92), 225: (130, 136, 123, 121), + 226: (126, 60, 118, 46), 227: (139, 137, 120, 124), 228: (140, 130, 124, 123), + 229: (122, 127, 118, 123), 231: (130, 141, 127, 138), 232: (54, 205, 50, 185), + 233: (75, 74, 69, 68), 234: (223, 130, 217, 125), 235: (111, 129, 108, 127), + 236: (160, 129, 157, 126), 237: (129, 217, 126, 217), 238: (148, 128, 146, 126), + 239: (130, 129, 127, 118), 241: (60, 200, 50, 200), 242: (131, 130, 120, 124), + 243: (123, 132, 116, 127), 244: (132, 135, 130, 132), 245: (129, 41, 126, 37), + 246: (122, 133, 120, 133), 247: (118, 128, 116, 126), 248: (136, 128, 133, 126), + 249: (128, 133, 123, 131), 250: (82, 81, 78, 77), 251: (124, 130, 122, 128), + 252: (130, 130, 125, 124), 253: (128, 128, 127, 127), 254: (127, 126, 126, 125), + 255: (129, 127, 128, 126), +} diff --git a/tools/ttpf_mips.py b/tools/ttpf_mips.py index 15c295883..5c0db936b 100644 --- a/tools/ttpf_mips.py +++ b/tools/ttpf_mips.py @@ -6,20 +6,23 @@ first. `TtpfReader` only trusts a hand-validated tuple table and stops at the descriptor's `nonTail` field, which is not the layout boundary. The layout rule lives in `tex_headers.py` (`compact_surface_layout` and the helpers around it); this tool supplies the RDS5 reader, decoders and commands. It computes the layout from the -descriptor, validates it against the native allocation span, then decodes the mips -that are zlib/raw (no BCPack backend is used or guessed). +descriptor, validates it against the native allocation span, then decodes zlib/raw +mips and supported BCPack codecs (BC1, BC3, BC4 and BC5 via `bcpack.py`, strict +confirmed-history mode by default; pass `--allow-provisional` to opt into unconfirmed +built-in history entries). Read-only: no texture bytes are printed or committed. `scan` emits aggregate -counters only. `layout` prints descriptor fields and offsets. `check` prints the -BC block-average error against a 2x2 downsample of the parent mip; it decodes -BC1, BC3, BC4_UNORM and BC5_UNORM (BC2, the SNORM BC4/5 variants, BC6H and BC7 -are sized but not decoded, and uncompressed tiling is not validated). `export` -writes a full BC chain only when every source mip is zlib/raw. +counters only (both the zlib/raw baseline and the BCPack-enabled projection). +`layout` prints descriptor fields and offsets. `check` prints the BC block-average +error against a 2x2 downsample of the parent mip; it decodes BC1, BC3, BC4_UNORM +and BC5_UNORM (BC2, the SNORM BC4/5 variants, BC6H and BC7 are sized but not +decoded, and uncompressed tiling is not validated). `export` writes a full BC chain +when every source mip uses a supported codec. python -I tools/ttpf_mips.py scan [--json out] [--tuples] python -I tools/ttpf_mips.py layout - python -I tools/ttpf_mips.py check - python -I tools/ttpf_mips.py export [--mips N] [--force] + python -I tools/ttpf_mips.py check [--allow-provisional] + python -I tools/ttpf_mips.py export [--mips N] [--force] [--allow-provisional] Standard library only. The RDS5/ETPF checks mirror rpf9-explorer's `TtpfReader` (MIT); the tile patterns and tail formula are the AMD Gfx10 4 KiB/64 KiB layouts @@ -35,6 +38,7 @@ import sys import zlib sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import bcpack # noqa: E402 from tex_headers import ( # noqa: E402 compact_surface_layout, gfx10_tile_bytes, gfx10_tile_mode, parse_etpf_texture_record, @@ -242,10 +246,10 @@ def decode_pixels(fmt, data, blocks_w, blocks_h): elif fmt in (77, 78): blk = decode_bc1_block(data, at + 8) elif fmt in (80,): - blk = decode_bc4_block(data, (by * blocks_w + bx) * 8, False) + blk = decode_bc4_block(data, (by * blocks_w + bx) * 8) elif fmt in (83,): - a = decode_bc4_block(data, at, False) - b = decode_bc4_block(data, at + 8, False) + a = decode_bc4_block(data, at) + b = decode_bc4_block(data, at + 8) blk = [(p[0], q[0], 0.0) for p, q in zip(a, b)] else: return None @@ -393,22 +397,31 @@ class Pool: def codecs(self, start, size): return {c[4] for c in self.chunks_for(start, size)} - def readable(self, start, size): - return self.codecs(start, size) <= {0, 8} + def readable(self, start, size, *, allow_bcpack=False): + allowed = ({0, 8} | bcpack.SUPPORTED_REBUILD_CODECS) if allow_bcpack else {0, 8} + return self.codecs(start, size) <= allowed - def read_range(self, start, size, cache=None): + def read_range(self, start, size, cache=None, *, bcpack_mode="strict"): + if bcpack_mode not in ("strict", "provisional", "off"): + raise ValueError(f"invalid bcpack_mode: {bcpack_mode!r}") cache = {} if cache is None else cache out = bytearray(size) for virt, csize, src, packed, codec, pad in self.chunks_for(start, size): - key = (src, packed, codec) + key = (src, packed, codec, bcpack_mode if codec not in (0, 8) else "raw") if key not in cache: raw = self.data[src:src + packed] if codec == 0: cache[key] = bytes(raw) elif codec == 8: cache[key] = zlib.decompress(raw) + elif bcpack_mode != "off" and codec in bcpack.SUPPORTED_REBUILD_CODECS: + cache[key] = bcpack.decode( + raw, codec, csize, allow_provisional=(bcpack_mode == "provisional") + ) else: - raise BcpackRequired("range touches a BCPack chunk") + raise BcpackRequired( + f"range touches a BCPack chunk (codec {codec})" + ) if len(cache[key]) != csize: raise ValueError("decoded chunk length disagrees with its range") lo, hi = max(start, virt), min(start + size, virt + csize) @@ -445,7 +458,7 @@ def validated_aux(desc): ELEMENT_BYTES.get(desc["format"]) == a["bytes_b"]))) -def analyze(pool, index): +def analyze(pool, index, *, allow_bcpack=True): """Descriptor + layout + per-mip codec availability for one texture.""" d = pool.descriptor(index) out = dict(descriptor=d, tile_mode=tile_mode(d["mode"]), tile=tile_bytes(d["mode"])) @@ -469,13 +482,19 @@ def analyze(pool, index): out["blocked"] = "layout does not match the allocation span" return out avail = [] + mip_codecs = [] for mip in layout["mips"]: try: - avail.append(pool.readable(d["base"] + mip["offset"], mip["region"])) + codecs = sorted(pool.codecs(d["base"] + mip["offset"], mip["region"])) + mip_codecs.append(codecs) + avail.append(pool.readable(d["base"] + mip["offset"], mip["region"], + allow_bcpack=allow_bcpack)) except ValueError: avail = [] + mip_codecs = [] break out["available"] = avail + out["mip_codecs"] = mip_codecs if avail: limit = d["non_tail"] if compact_row(d) else d["mips"] limit = max(0, min(limit, len(avail))) @@ -518,8 +537,10 @@ def scan_pools(paths, as_json=None, include_tuples=False): compact_rows_measured=0, compact_non_tail_before_tail=0, compact_standalone_beyond_limit=0, compact_standalone_decodable_beyond_limit=0, - compact_full_rows=0, tile_modes={}) + compact_full_rows=0, after_bcpack_full=0, + after_bcpack_partial=0, tile_modes={}) gated_tuples = {} + bcpack_allowed = {0, 8} | bcpack.SUPPORTED_REBUILD_CODECS for path in paths: pool = Pool(path) try: @@ -564,18 +585,36 @@ def scan_pools(paths, as_json=None, include_tuples=False): total["gated_span_mismatch"] += 1 continue avail = [] + avail_bc = [] for mip in layout["mips"]: try: - avail.append(pool.readable(d["base"] + mip["offset"], mip["region"])) + cs = pool.codecs(d["base"] + mip["offset"], mip["region"]) except ValueError: avail = [] + avail_bc = [] break + avail.append(cs <= {0, 8}) + avail_bc.append(cs <= bcpack_allowed) if not avail: total["layout_mismatch"] += 1 if gated: total["whitelist_gated"] += 1 total["gated_unreadable_range"] += 1 continue + if all(avail_bc): + total["after_bcpack_full"] += 1 + else: + ft = layout["first_tail"] + usable_tail_bc = (ft < d["mips"] and all(avail_bc[ft:])) + lim_bc = (d["mips"] if (not compact_row(d) or usable_tail_bc) + else min(ft, len(avail_bc))) + bm_bc = next((k for k in range(lim_bc) if avail_bc[k]), None) + exp_bc = 0 + if bm_bc is not None: + while bm_bc + exp_bc < lim_bc and avail_bc[bm_bc + exp_bc]: + exp_bc += 1 + if exp_bc: + total["after_bcpack_partial"] += 1 if gated: total["whitelist_gated"] += 1 total["gated_layout_ok"] += 1 @@ -665,6 +704,9 @@ def scan_pools(paths, as_json=None, include_tuples=False): total["after_partial"] = (total["reader_partial"] - total["compact_full_rows"] + total["gated_partial"]) total["after_skip"] = total["entries"] - total["after_full"] - total["after_partial"] + total["after_bcpack_skip"] = (total["entries"] - total["after_bcpack_full"] - + total["after_bcpack_partial"]) + total["bcpack_unlocked_full"] = total["after_bcpack_full"] - total["after_full"] if include_tuples: total["gated_tuples"] = [ {"tuple": list(key), "count": count} @@ -689,9 +731,11 @@ def describe(pool, index): out["allocation_span"] = a.get("allocation_span") out["span_matches"] = a.get("span_matches") out["first_tail_mip"] = a["layout"]["first_tail"] + mip_codecs = a.get("mip_codecs") or [] out["mips_detail"] = [ dict(index=m["index"], blocks=[m["blocks_w"], m["blocks_h"]], offset=m["offset"], - region=m["region"], tail=m["in_tail"], tile_origin=[m["tile_x"], m["tile_y"]]) + region=m["region"], tail=m["in_tail"], tile_origin=[m["tile_x"], m["tile_y"]], + **({"codecs": mip_codecs[m["index"]]} if m["index"] < len(mip_codecs) else {})) for m in a["layout"]["mips"]] if "available" in a: out["available"] = a["available"] @@ -703,7 +747,7 @@ def describe(pool, index): return out -def check(pool, index): +def check(pool, index, *, allow_provisional=False): a = analyze(pool, index) if "layout" not in a: print(json.dumps(dict(index=index, blocked=a.get("blocked")), indent=1)) @@ -711,10 +755,17 @@ def check(pool, index): layout = a["layout"] d = a["descriptor"] cache = {} + bcpack_mode = "provisional" if allow_provisional else "strict" try: - tiled = pool.read_range(d["base"], layout["size"], cache) - except BcpackRequired: - print(json.dumps(dict(index=index, blocked="BCPack in allocation"), indent=1)) + tiled = pool.read_range(d["base"], layout["size"], cache, bcpack_mode=bcpack_mode) + except BcpackRequired as exc: + print(json.dumps(dict(index=index, blocked=str(exc)), indent=1)) + return 2 + except bcpack.BcpackProvisionalError as exc: + print(json.dumps(dict( + index=index, + blocked=f"provisional BCPack history required ({exc}); pass --allow-provisional", + ), indent=1)) return 2 decoded, means = [], [] for mip in layout["mips"]: @@ -770,7 +821,7 @@ def dds_bytes(width, height, fmt, mips, linear, payload): return bytes(hdr) + struct.pack(" d["mips"]: @@ -790,10 +841,20 @@ def export(pool, index, out_path, mips=None, force=False): return 2 layout = a["layout"] cache = {} + bcpack_mode = "provisional" if allow_provisional else "strict" payload = bytearray() - for mip in layout["mips"][:count]: - tiled = pool.read_range(d["base"] + mip["offset"], mip["region"], cache) - payload += detile(layout, mip, tiled) + try: + for mip in layout["mips"][:count]: + tiled = pool.read_range(d["base"] + mip["offset"], mip["region"], cache, + bcpack_mode=bcpack_mode) + payload += detile(layout, mip, tiled) + except BcpackRequired as exc: + print(f"texture {index}: {exc}", file=sys.stderr) + return 2 + except bcpack.BcpackProvisionalError as exc: + print(f"texture {index}: provisional BCPack history required ({exc}); " + "pass --allow-provisional", file=sys.stderr) + return 2 if 148 + len(payload) > MAX_OUTPUT: print("DDS exceeds the 256 MiB output limit", file=sys.stderr) return 2 @@ -824,12 +885,16 @@ def main(argv=None): pc = sub.add_parser("check", help="decode a chain and report downsample error") pc.add_argument("pool") pc.add_argument("index", type=int) - pe = sub.add_parser("export", help="write the full zlib/raw chain as DDS") + pc.add_argument("--allow-provisional", action="store_true", + help="allow unconfirmed built-in BCPack history entries") + pe = sub.add_parser("export", help="write the full chain as DDS") pe.add_argument("pool") pe.add_argument("index", type=int) pe.add_argument("out") pe.add_argument("--mips", type=int) pe.add_argument("--force", action="store_true") + pe.add_argument("--allow-provisional", action="store_true", + help="allow unconfirmed built-in BCPack history entries") a = ap.parse_args(argv) if a.cmd == "scan": pools = [] @@ -843,8 +908,9 @@ def main(argv=None): print(json.dumps(describe(pool, a.index), indent=1)) return 0 if a.cmd == "check": - return check(pool, a.index) - return export(pool, a.index, a.out, a.mips, a.force) + return check(pool, a.index, allow_provisional=a.allow_provisional) + return export(pool, a.index, a.out, a.mips, a.force, + allow_provisional=a.allow_provisional) finally: pool.close() From b933118d32049ad91c9a1d34a95b295090e153ba Mon Sep 17 00:00:00 2001 From: crastinator Date: Sun, 22 Nov 2026 00:44:48 +0200 Subject: [PATCH 22/53] GPU tests: run ps_vcc_x2 on the GPU with a seeded V# and heap in vk_harness (TEST-19) ps_vcc_x2 reads two dwords through the V# in s[0:3], but vk_harness pushed zeros and bound no memory, so on the GPU it read address 0 and lost the device; run_gpu_tests.py skipped it and check.py left it out. vk_harness now takes VKH_SGPRS (user SGPRs, decimal or 0x hex) and VKH_HEAP (addr=word seeds in a 64 KiB device-address heap, passed as the heap base). bufferDeviceAddress and shaderInt64 are enabled only then; a device without them gets "unsupported: ..." and exit 77, which both runners report as SKIP. Both runners give ps_vcc_x2 the V# and words tests/semantic uses and expect 0x11223344 0x55667788 0 0. --- runtime/test/shaders/check.py | 8 ++- runtime/test/vk_harness.cpp | 97 +++++++++++++++++++++++++++++++++-- scripts/run_gpu_tests.py | 15 +++--- tests/test_shader_checks.py | 36 +++++++++++++ 4 files changed, 144 insertions(+), 12 deletions(-) diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 707dda242..7378b8fd5 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -61,7 +61,11 @@ PIXEL_BITS = {"ps_legacy_mul": (0, 0, 0, 0x40c00000), "ps_ops6": (0xf800ffff, 0x01000010, 0x00800800, 0x8000fff0), "ps_ops7": (0x00ff8077, 0xff0000ff, 0x89abcdef, 0x00070003), "ps_ops8": (0x80000000, 0xffffffff, 0x000f100e, 0x0f0f0f1f), - "ps_scc": (1, 1, 3, 0x80000000), "ps_sdwa": (0x000000f1, 0xfffefff2, 0x3c003344, 0xfff70000)} + "ps_scc": (1, 1, 3, 0x80000000), "ps_sdwa": (0x000000f1, 0xfffefff2, 0x3c003344, 0xfff70000), + "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0)} +# Pixel shaders that read memory: vk_harness puts this V# in s[0:3] and seeds the heap it points at, as +# tests/semantic/test_value_semantics.py does for the interpreter. +PIXEL_ENV = {"ps_vcc_x2": {"VKH_SGPRS": "0x1000,0,16,0", "VKH_HEAP": "0x1000=0x11223344,0x1004=0x55667788"}} PIXEL_TESTS = sorted((*PIXEL_BITS, "ps_bary", "ps_flat", "ps_bitmask_perm", "ps_uniform_branch")) @@ -230,6 +234,8 @@ def pixels(tools, spirv, name, fmt): # (RADV's default on RDNA1) reads lanes it was never written for. sg = subgroup_size(spirv, name) env = dict(os.environ, VKH_SUBGROUP_SIZE=str(sg)) if sg else None + if name in PIXEL_ENV: + env = dict(env or os.environ, **PIXEL_ENV[name]) with tempfile.TemporaryDirectory(prefix="leonida-pixels-") as tmp: raw = Path(tmp) / "pixels.raw" code, out = run(os.path.join(tools, "vk_harness" + EXE), os.path.join(spirv, "vs_ids.spv"), diff --git a/runtime/test/vk_harness.cpp b/runtime/test/vk_harness.cpp index 56cbda978..5f7089fd6 100644 --- a/runtime/test/vk_harness.cpp +++ b/runtime/test/vk_harness.cpp @@ -5,14 +5,21 @@ // vk_harness --mesh-group-readback X Y Z // The latter captures one full-screen triangle per mesh workgroup, in Vulkan rasterization order. // +// Push constants follow the contract in docs/design.md: s0..s31, then the heap base lo/hi. They are zero unless +// VKH_SGPRS=w0,w1,... sets s0, s1, ... (decimal or 0x hex) +// VKH_HEAP=addr=word,... allocates a zeroed 64 KiB heap (Xbox VA 0 = its device address), writes each word at +// its address and passes the heap base, so a V# in VKH_SGPRS can point into it. +// #define VK_NO_PROTOTYPES #include "vulkan_loader.h" +#include #include #include #include #include #include +#include #include static PFN_vkGetInstanceProcAddr gipa; @@ -34,6 +41,40 @@ static std::vector read_spv(const char* path) { return w; } +static bool parse_u32(const char*& s, uint32_t& v) { + const bool hex = s[0] == '0' && (s[1] == 'x' || s[1] == 'X'); + const char* digits = hex ? s + 2 : s; + if (!(hex ? std::isxdigit(uint8_t(*digits)) : std::isdigit(uint8_t(*digits)))) return false; // no sign or space + char* end; + unsigned long long x = std::strtoull(digits, &end, hex ? 16 : 10); + if (x > 0xFFFFFFFFull) return false; + v = uint32_t(x); s = end; + return true; +} + +// A list separator must be followed by another item: "1,2," is rejected. +static bool next_item(const char*& s) { + if (!*s) return true; + return *s++ == ',' && *s; +} + +static bool parse_sgprs(const char* s, uint32_t* sgprs) { + for (uint32_t i = 0; *s; i++) { + if (i == 32 || !parse_u32(s, sgprs[i]) || !next_item(s)) return false; + } + return true; +} + +static bool parse_heap(const char* s, std::vector>& words, uint32_t heap_bytes) { + while (*s) { + uint32_t addr, word; + if (!parse_u32(s, addr) || *s++ != '=' || !parse_u32(s, word) || !next_item(s)) return false; + if (addr % 4 || addr > heap_bytes - 4) return false; + words.emplace_back(addr, word); + } + return true; +} + int main(int argc, char** argv) { if (argc < 4) { std::fprintf(stderr, "usage: vk_harness vs.spv fs.spv out.raw [w h]\n" @@ -62,6 +103,21 @@ int main(int argc, char** argv) { } else if (argc > 5) { W = atoi(argv[4]); H = atoi(argv[5]); } + uint32_t pc[36] = {}; + const char* sgprs_env = std::getenv("VKH_SGPRS"); + if (sgprs_env && !parse_sgprs(sgprs_env, pc)) { + std::fprintf(stderr, "VKH_SGPRS: expected up to 32 comma-separated words, got \"%s\"\n", sgprs_env); + return 2; + } + const uint32_t heap_bytes = 64 * 1024; + const char* heap_env = std::getenv("VKH_HEAP"); + if (heap_env && !*heap_env) heap_env = nullptr; + std::vector> heap_words; + if (heap_env && !parse_heap(heap_env, heap_words, heap_bytes)) { + std::fprintf(stderr, "VKH_HEAP: expected addr=word pairs, 4-byte aligned below 0x%x, got \"%s\"\n", + heap_bytes, heap_env); + return 2; + } gipa = load_vulkan(); if (!gipa) return 1; VkInstance inst = VK_NULL_HANDLE; @@ -166,7 +222,9 @@ int main(int argc, char** argv) { m8.maintenance8 = VK_TRUE; m8.pNext = chain; chain = &m8; } #endif + VkPhysicalDeviceVulkan12Features f12q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; VkPhysicalDeviceVulkan13Features f13q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; + f13q.pNext = &f12q; VkPhysicalDeviceFeatures2 f2q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2q.pNext = &f13q; vkGetPhysicalDeviceFeatures2(pd, &f2q); @@ -176,6 +234,14 @@ int main(int argc, char** argv) { f13.pNext = chain; chain = &f13; } + VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; + if (heap_env) { + // 77 is the "this device cannot run the test" code that check.py and run_gpu_tests.py report as SKIP. + if (!f12q.bufferDeviceAddress) { std::fprintf(stderr, "unsupported: VKH_HEAP needs bufferDeviceAddress\n"); return 77; } + f12.bufferDeviceAddress = VK_TRUE; + f12.pNext = chain; + chain = &f12; + } for (auto e : enable) std::fprintf(stderr, "enabled %s\n", e); VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; @@ -191,6 +257,10 @@ int main(int argc, char** argv) { feats.geometryShader = gs_path ? VK_TRUE : VK_FALSE; feats.shaderClipDistance = f2q.features.shaderClipDistance; feats.shaderCullDistance = f2q.features.shaderCullDistance; + if (heap_env) { + if (!f2q.features.shaderInt64) { std::fprintf(stderr, "unsupported: VKH_HEAP needs shaderInt64\n"); return 77; } + feats.shaderInt64 = VK_TRUE; // heap addresses are 64-bit + } dci.pEnabledFeatures = &feats; VkDevice dev; CHECK(vkCreateDevice(pd, &dci, nullptr, &dev)); @@ -320,7 +390,7 @@ int main(int argc, char** argv) { VkPipelineColorBlendAttachmentState cba{}; cba.colorWriteMask = 0xF; VkPipelineColorBlendStateCreateInfo cb{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; cb.attachmentCount = 1; cb.pAttachments = &cba; - // Translated shaders declare a 136-byte push-constant block (user SGPRs + heap base); zeros here. + // Translated shaders declare a 136-byte push-constant block (user SGPRs + heap base); see VKH_SGPRS / VKH_HEAP. const VkShaderStageFlags pcs = (mesh ? VK_SHADER_STAGE_MESH_BIT_EXT : VK_SHADER_STAGE_VERTEX_BIT) | VK_SHADER_STAGE_FRAGMENT_BIT | (gs_path ? VK_SHADER_STAGE_GEOMETRY_BIT : 0); VkPushConstantRange pcr{pcs, 0, 144}; @@ -353,6 +423,28 @@ int main(int argc, char** argv) { bai.memoryTypeIndex = memtype(br.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); VkDeviceMemory bmem; CHECK(vkAllocateMemory(dev, &bai, nullptr, &bmem)); CHECK(vkBindBufferMemory(dev, buf, bmem, 0)); + if (heap_env) { + LOADD(vkGetBufferDeviceAddress); + VkBufferCreateInfo hbi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + hbi.size = heap_bytes; + hbi.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + VkBuffer heap; CHECK(vkCreateBuffer(dev, &hbi, nullptr, &heap)); + VkMemoryRequirements hr; vkGetBufferMemoryRequirements(dev, heap, &hr); + VkMemoryAllocateFlagsInfo haf{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; + haf.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; + VkMemoryAllocateInfo hai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + hai.pNext = &haf; hai.allocationSize = hr.size; + hai.memoryTypeIndex = memtype(hr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + VkDeviceMemory hmem; CHECK(vkAllocateMemory(dev, &hai, nullptr, &hmem)); + CHECK(vkBindBufferMemory(dev, heap, hmem, 0)); + void* hp; CHECK(vkMapMemory(dev, hmem, 0, heap_bytes, 0, &hp)); + std::memset(hp, 0, heap_bytes); + for (auto [addr, word] : heap_words) std::memcpy(static_cast(hp) + addr, &word, 4); + VkBufferDeviceAddressInfo hda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + hda.buffer = heap; + const uint64_t base = vkGetBufferDeviceAddress(dev, &hda); + pc[32] = uint32_t(base); pc[33] = uint32_t(base >> 32); + } VkCommandPoolCreateInfo cpi{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; cpi.queueFamilyIndex = qi; VkCommandPool pool; CHECK(vkCreateCommandPool(dev, &cpi, nullptr, &pool)); VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; @@ -376,9 +468,8 @@ int main(int argc, char** argv) { std::fprintf(stderr, "mesh workgroups: %u x %u x %u\n", groups[0], groups[1], groups[2]); } vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe); - uint32_t zeros[36] = {}; reinterpret_cast(vkGetDeviceProcAddr(dev, "vkCmdPushConstants"))( - cmd, pl, pcs, 0, sizeof(zeros), zeros); + cmd, pl, pcs, 0, sizeof(pc), pc); if (mesh) reinterpret_cast(vkGetDeviceProcAddr(dev, "vkCmdDrawMeshTasksEXT"))(cmd, groups[0], groups[1], groups[2]); else diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 69fccee0c..77b11fa53 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -261,9 +261,9 @@ def check_bitmask_perm(raw_path: str) -> tuple[bool, str]: return (bad == 0 and judged > 0), (first if bad else f"{judged}/{judged} pixels in lanes 0-31 exact") -# Test shaders that need memory or push constants only the semantic-test interpreter sets up (tests/semantic). -# On the GPU harness they would read an unset descriptor; ps_vcc_x2 loses the device that way. -INTERPRETER_ONLY = {"ps_vcc_x2": "needs the seeded V# memory of tests/semantic; checked there"} +# Pixel shaders that read memory: vk_harness puts this V# in s[0:3] and seeds the heap it points at, as +# tests/semantic/test_value_semantics.py does for the interpreter (same table as check.py). +PIXEL_ENV = {"ps_vcc_x2": {"VKH_SGPRS": "0x1000,0,16,0", "VKH_HEAP": "0x1000=0x11223344,0x1004=0x55667788"}} def check_flat(raw_path: str) -> tuple[bool, str]: @@ -455,9 +455,6 @@ def run_suite(a, work: str) -> int: results: list[tuple[str, bool, str]] = [] for fname in asm_files: name = os.path.splitext(fname)[0] - if name in INTERPRETER_ONLY: - results.append((name, None, "SKIP (" + INTERPRETER_ONLY[name] + ")")) - continue spv = os.path.join(spirv_dir, f"{name}.spv") if not os.path.isfile(spv): results.append((name, False, "missing .spv (translation failed)")) @@ -580,9 +577,10 @@ def run_suite(a, work: str) -> int: elif name.startswith("ps_"): raw = os.path.join(raw_dir, f"{name}.raw") vs = os.path.join(spirv_dir, "vs_ids.spv") if name == "ps_flat" else vs_tri # check.py draws ps_flat with vs_ids - rc, msg = run_cmd([vk_harness, vs, spv, raw], env=gfx_env) + env = dict(gfx_env or os.environ, **PIXEL_ENV[name]) if name in PIXEL_ENV else gfx_env + rc, msg = run_cmd([vk_harness, vs, spv, raw], env=env) if rc == 77: # vk_harness: the device lacks a feature this shader needs (e.g. barycentrics) - results.append((name, None, "SKIP (unsupported device)")) + results.append((name, None, unsupported_skip(msg))) continue if rc != 0: results.append((name, False, msg)) @@ -599,6 +597,7 @@ def run_suite(a, work: str) -> int: "ps_ops6": (0xF800FFFF, 0x01000010, 0x00800800, 0x8000FFF0), "ps_ops7": (0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003), "ps_ops8": (0x80000000, 0xFFFFFFFF, 0x000F100E, 0x0F0F0F1F), + "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), } if name in const_wants: ok, detail = check_pixel_const(raw, const_wants[name]) diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py index 66038d875..a802ad7be 100644 --- a/tests/test_shader_checks.py +++ b/tests/test_shader_checks.py @@ -3,6 +3,7 @@ import contextlib import io import struct from pathlib import Path +import struct import sys import tempfile import unittest @@ -184,5 +185,40 @@ class PixelDeviceLimits(unittest.TestCase): self.assertEqual(self.run_pixel("ps_bitmask_perm", 0, out, data=self.bitmask_pixels(32)), "") +class SeededPixelTests(unittest.TestCase): + """ps_vcc_x2 reads a V# from s[0:3]; check.py hands vk_harness that V# and the heap words behind it (TEST-19).""" + + def run_pixel_test(self, words, code=0, out=""): + seen = {} + + def harness(_tool, _vs, _fs, raw, env=None): + seen["env"] = env + if not code: + Path(raw).write_bytes(struct.pack("<4I", *words) * (64 * 64)) + return code, out + + with tempfile.TemporaryDirectory() as tmp: + (Path(tmp) / "ps_vcc_x2.spv").touch() + with patch.object(check, "run", side_effect=harness): + problem = check.pixel_test(tmp, tmp, "ps_vcc_x2") + return problem, seen["env"] or {} + + def test_v_sharp_and_heap_reach_the_harness(self): + problem, env = self.run_pixel_test((0x11223344, 0x55667788, 0, 0)) + self.assertEqual(problem, "") + self.assertEqual(env.get("VKH_SGPRS"), "0x1000,0,16,0") + self.assertEqual(env.get("VKH_HEAP"), "0x1000=0x11223344,0x1004=0x55667788") + + def test_unseeded_result_fails(self): + problem, _ = self.run_pixel_test((0, 0, 0, 0)) + self.assertIn("4096 of 4096 pixels differ", problem) + + def test_device_without_buffer_addresses_skips(self): + problem, _ = self.run_pixel_test((), code=77, out="unsupported: VKH_HEAP needs bufferDeviceAddress\n") + self.assertIsInstance(problem, check.Skip) + self.assertIn("needs bufferDeviceAddress", problem) + + + if __name__ == "__main__": unittest.main() From b262056ac7ec18916ab2a13328412fe80800de6d Mon Sep 17 00:00:00 2001 From: Kam471 <115741199+Kam471@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:47:20 +0000 Subject: [PATCH 23/53] Tools: measure the common.rpf content-set graph Add gamedata_graph.py, which rebuilds the XML payloads from a carve and measures document -> content-set -> target edges. Include ids are joined only on exact equality; missing ids stay dangling and common:/ is not normalized to $(common)/. Add synthetic tests for includes, a cycle, reachability, prefix classification, unparsed payloads and output redaction. Add a measured docs page linked from the index. --- docs/README.md | 1 + docs/gamedata.md | 6 +- docs/gamedata_graph.md | 133 +++++++++ tests/test_gamedata_graph.py | 271 +++++++++++++++++++ tools/gamedata_graph.py | 509 +++++++++++++++++++++++++++++++++++ 5 files changed, 918 insertions(+), 2 deletions(-) create mode 100644 docs/gamedata_graph.md create mode 100644 tests/test_gamedata_graph.py create mode 100644 tools/gamedata_graph.py diff --git a/docs/README.md b/docs/README.md index 67df06387..25056b8f0 100644 --- a/docs/README.md +++ b/docs/README.md @@ -23,6 +23,7 @@ method, scope and caveats. No game data is included. | [bvh.md](bvh.md) | 565,596 `core_bvh4.rpf` streams; 271,627 BVH4 streams and 269,106 instances, prebuilt acceleration data. | | [rbf0.md](rbf0.md) | 1,263 RBF0 resources, 475,461 elements; UI/Scaleform definitions, not a sectioned container; strict JSON/CSV/XML tree decoder. | | [gamedata.md](gamedata.md) | `common.rpf`: 954 streams, 266 XML documents / 118 roots; 0 RBF0/PSIN. | +| [gamedata_graph.md](gamedata_graph.md) | `common.rpf` mount graph: 25 manifest documents, 30 content-set ids, 14 include refs (12 resolve), 3,386 target refs, 0 cycles. | | [world.md](world.md) | `levels.rpf` placement: 9,918 map files / 680,228 entities measured in 55% of the archive (lower bound; estimate 16k-39.6k / 1.03M-2.64M); `0x7a` resource layout. | | [world_census.md](world_census.md) | Full `levels.rpf` pass: 23,535 maps / 1,670,442 entities, 98.32% stream coverage, sharded and exact. | | [page_directory.md](page_directory.md) | RPF9 `0DRP`: 0x60-byte header, `q38` 16-byte records; 15,768 pages / 60,880 records in `data.rpf`; targets and sizes, names still TOC-only. | diff --git a/docs/gamedata.md b/docs/gamedata.md index 88b8f57e6..05efaa2dd 100644 --- a/docs/gamedata.md +++ b/docs/gamedata.md @@ -225,8 +225,10 @@ four prefix rules and a content-set/mount walk, not a general include processor. A runtime dispatcher needs the 118-root table (or an RTTI class bridge), the 12 category buckets, the 318-value `type` registry, the 33-name attribute whitelist, the `content=` array decoders and a streaming reader for the -14 MB document. It also needs to mark the 9 tail-only documents and the one rootless block as incomplete -evidence: `gamedata_xml.py --check` is the reference for that split. The catalog is a local work product. Only +14 MB document. The mount/reference half of that layer is measured separately in +[gamedata_graph.md](gamedata_graph.md): 25 manifest documents, 30 content-set ids, 12 resolved include edges +and 3,343 reachable target references. It also needs to mark the 9 tail-only documents and the one rootless +block as incomplete evidence: `gamedata_xml.py --check` is the reference for that split. The catalog is a local work product. Only aggregate counts and schema/root/element/attribute names belong in git; the CSV/JSON, the element values, the `type`/`content` values and per-file paths stay on the local machine. The tests are synthetic. diff --git a/docs/gamedata_graph.md b/docs/gamedata_graph.md new file mode 100644 index 000000000..1bb9a9b8a --- /dev/null +++ b/docs/gamedata_graph.md @@ -0,0 +1,133 @@ +# The `common.rpf` content-set graph + +This note measures the mount/reference graph in the XML documents recovered from `common.rpf` in the +Xbox Series 1.0.2.1 package. It extends [gamedata.md](gamedata.md), which counts the documents and +reference tokens, and uses the same local carve. Only aggregate counts, root/category names and +reference-prefix names are recorded here. No archive, carved file, XML value, content-set id, entry +name or target path is committed. + +`tools/gamedata_graph.py` rebuilds the documents with `gamedata_index.py` and +`gamedata_xml.load_documents`, then keeps the reference strings long enough to join them. It is +standard-library only and reads the same carve as the index and catalog. + +## Graph model + +| Node | Count | What it represents | +|---|---:|---| +| document | 267 | one XML payload, including the unparsed ones | +| content set | 30 | every ``, plus every `` id | +| target | 3,364 | every distinct ``, ``, `parentPath` and `parentFile` value | +| **total** | **3,661** | | + +| Edge | Count | Meaning | +|---|---:|---| +| `defines` | 28 | document to its top-level or nested `` id | +| `includes` | 14 | document to an `` id (12 resolve to a document) | +| `contains_file` | 3,315 | set (or document) to a `` target | +| `loads_changeset` | 28 | document to an `/` target | +| `parent_path` / `parent_file` | 40 / 3 | document to a `parentPath` / `parentFile` locator | +| **total** | **3,428** | | + +The document/content-set part is 42 edges; the target part is 3,386 edges. An include becomes a +document-to-document edge only when its text exactly equals a set id. There is no fuzzy match and +no prefix normalization. Missing ids stay dangling content-set nodes, so a spelling difference is +visible as an unresolved include instead of becoming an invented document edge. + +## Measured shape + +| Measure | Value | +|---|---:| +| XML payloads | 267 | +| Complete documents | 266 | +| Parsed documents | 259 | +| Unparsed payloads | 8 (7 truncated, 1 rootless) | +| Named roots (+ one unattributed) | 118 (+1) | +| Manifest documents | 25 (23 `CDataFileMgr__ContentChangeSetDef`, 2 `CDataFileMgr__ContentDef`) | +| Content-set ids | 30 (28 defined, 2 dangling) | +| Duplicate set ids | 0 | +| Reference sites | 3,400 (3,386 target + 14 include) | +| Distinct target strings | 3,364 | +| Include sites / document edges | 14 / 12 | +| Cycles in the include graph | 0 | +| Include-graph roots (in-degree zero) | 13 | +| Reachable documents from those roots | 25 of 25 manifest documents | +| Maximum include depth | 1 | +| Reachable content sets | 30 | +| Reachable target sites | 3,343 | +| Reachable distinct targets | 3,343 | + +The manifest layer is closed at the document level: all 12 resolved includes point at documents that +are already among the 25 manifests, so no non-manifest document is reachable by an id. The graph +therefore measures the mount walk, not a general include system. The 21 distinct targets outside the +reachable set are the `parentPath`/`parentFile` locators in the two non-manifest documents. + +## Prefix rules + +The four documented rules cover 3,312 of the 3,386 target sites. `common:/` also occurs but is not +one of those rules, so it is reported separately and is not rewritten to `$(common)/`. + +| Reference form | Sites | Resolution in this catalog | +|---|---:|---| +| `$(common)/` | 587 | common archive namespace; the TOC name is missing | +| `$(target)/` | 23 | target data namespace; the TOC name is missing | +| `$(root)/` | 28 | changeset root; not a document in this archive | +| `platform:/levels/` | 2,346 | levels namespace; the TOC name is missing | +| other `platform:/` | 328 | other platform namespace; the TOC name is missing | +| `common:/` | 31 | unrecognized scheme alias; left unresolved | +| relative locator | 43 | `parentPath` / `parentFile`, not an archive path | +| **total** | **3,386** | | + +`parentPath` values are XPath-like locators, not mount paths, and `parentFile` is a relative name. +The 43 locator sites are 21 distinct strings in 2 non-manifest documents. None of them is used to +invent a document edge. + +## Unresolved references + +| Bucket | Sites | Note | +|---|---:|---| +| Recognized archive namespace, no document identity | 3,312 | `$(common)` 587, `$(target)` 23, `$(root)` 28, `platform:/levels` 2,346, other `platform:/` 328 | +| Unrecognized scheme (`common:/`) | 31 | not one of the four prefix rules | +| Relative locator | 43 | 21 distinct `parentPath`/`parentFile` values | +| Include id with no exact definition | 2 | one differs only by the `common:/` vs `$(common)/` spelling; one has no exact set id | +| **total** | **3,388** | excludes the 12 resolved include edges | + +The first bucket is not a failure by itself: the table of contents is encrypted, so an archive path +cannot be mapped to a carved document or to an entry name. It remains a target node. Only the two +include ids are unresolved content-set joins. Both are kept dangling rather than normalized. + +## Runtime use + +A mount resolver can follow the same shape: read a manifest, take its `` and ``, +resolve the four prefixes to archive namespaces, and follow `` only on an exact id. The +measured walk from the 13 in-degree-zero manifests reaches all 25 manifest documents and 30 set ids +in this archive, at depth 1. It does not reach any of the other 242 XML payloads, because those are +not mounted through content-set ids in this catalog. + +This is not a runtime schema. The catalog knows 118 root names, 5,293 element names and 33 attribute +names, but not field types. It also cannot supply names for the archive targets: that needs a +documented TOC reader, which is outside this work. + +## Limits + +- The table of contents is encrypted, so target paths are namespaces and strings, not document ids. + No path is joined to a carved document. +- Eight payloads are unparsed (seven truncated at the start, one rootless). Their references are + unknown and contribute no edges. +- Content-set joining is exact string equality. `common:/`, `$(common)/`, case and slash variants + are not normalized; the 31 `common:/` entries stay unresolved. +- `parentPath` and `parentFile` are locators, not mounts. They are counted, not followed. +- Only `filename`, `loadPath`, `includedSets`, `parentPath` and `parentFile` are modeled. No + XInclude occurs in the corpus, and no general include processor is implemented. +- The counts are for this version's `common.rpf`; another package can differ. + +## Reproduce + +```powershell +python -I tools/rpf9_carve.py common.rpf \carve\common +python -I tools/gamedata_graph.py \carve\common --json \graph.json +python -I tests/test_gamedata_graph.py +``` + +The JSON is an aggregate work product: counts, root names, category names and prefix names. It +contains no target strings, content-set ids, offsets or per-file names, so it can be reviewed +without copying game data. diff --git a/tests/test_gamedata_graph.py b/tests/test_gamedata_graph.py new file mode 100644 index 000000000..650976550 --- /dev/null +++ b/tests/test_gamedata_graph.py @@ -0,0 +1,271 @@ +"""gamedata_graph.py must measure a synthetic content-set graph without game data. + + python -I tests/test_gamedata_graph.py + +The fixtures are hand-written manifests: two change-set documents that include each other, one +content definition that includes the first, a missing set id, all four documented prefix rules, an +unknown ``common:/`` scheme, two parent locators, a tail-only document and a malformed document. +No game data is used. +""" +import json +import os +import subprocess +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOL = os.path.join(ROOT, "tools", "gamedata_graph.py") +TOOLS = os.path.join(ROOT, "tools") +if TOOLS not in sys.path: + sys.path.insert(0, TOOLS) +import gamedata_graph as gg # noqa: E402 + +ALPHA = ( + b'\n' + b'\n' + b' set.alpha\n' + b' \n' + b' $(common)/fixture/a.bk2\n' + b' platform:/levels/fixture/a.rpf\n' + b' $(target)/fixture/a\n' + b' common:/FIXTURE/A.XML\n' + b' \n' + b' set.betamissing.set\n' + b'' +) +BETA = ( + b'\n' + b' set.beta\n' + b' platform:/data/fixture\n' + b' set.alpha\n' + b'' +) +GAMMA = ( + b'\n' + b'\n' + b' \n' + b' set.gamma' + b'$(common)/fixture/g.xml' + b'\n' + b' \n' + b' set.alpha\n' + b' $(root)/fixture/g.meta' + b'\n' + b'' +) +DELTA = ( + b'' +) +PLAIN = b'' +TAIL = b'\n' +BAD = b'' + + +class GamedataGraphTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = self.tmp.name + self.carve = os.path.join(self.root, "carve") + os.makedirs(self.carve) + self.rows = [] + self.next_off = 0x1000 + + def tearDown(self): + self.tmp.cleanup() + + def add(self, payload, parts=None): + parts = parts if parts is not None else [payload] + for part in parts: + offset = self.next_off + self.next_off += 0x1000 + with open(os.path.join(self.carve, f"{offset:012x}.bin"), "wb") as f: + f.write(part) + self.rows.append({ + "off": offset, + "stored": len(part), + "size": len(part), + "head": part[:16].hex(), + "pre": "", + }) + + def finish(self): + with open(os.path.join(self.carve, "index.json"), "w", encoding="utf-8") as f: + json.dump({"summary": {"archive": "synthetic", "files": len(self.rows)}, "files": self.rows}, f) + + def run_tool(self, *args): + return subprocess.run([sys.executable, "-I", TOOL, *args], cwd=self.root, + capture_output=True, text=True, encoding="utf-8", errors="replace") + + def test_carve_graph_counts_cycles_reachability_and_no_leak(self): + self.add(ALPHA) + self.add(BETA) + split = GAMMA.index(b"") + self.add(GAMMA, [GAMMA[:split], GAMMA[split:]]) + self.add(DELTA) + self.add(PLAIN) + self.add(TAIL) + self.add(BAD) + self.finish() + + out = os.path.join(self.root, "graph.json") + p = self.run_tool(self.carve, "--json", out) + self.assertEqual(p.returncode, 0, p.stdout + p.stderr) + with open(out, encoding="utf-8") as f: + data = json.load(f) + s = data["summary"] + + self.assertEqual(s["mode"], "carve") + self.assertEqual(s["payloads"], 7) + self.assertEqual(s["documents"], 6) + self.assertEqual(s["parsed"], 5) + self.assertEqual(s["unparsed"], 2) + self.assertEqual(s["root_count"], 6) + self.assertEqual(s["rootless"], 0) + self.assertEqual(s["manifest_documents"], 3) + self.assertEqual(s["content_sets"], 4) + self.assertEqual(s["defined_content_sets"], 3) + self.assertEqual(s["dangling_content_sets"], 1) + self.assertEqual(s["duplicate_set_ids"], 0) + self.assertEqual(s["reference_sites"], 13) + self.assertEqual(s["target_sites"], 9) + self.assertEqual(s["include_sites"], 4) + self.assertEqual(s["references"], { + "filename": 6, "includedSets": 4, "loadPath": 1, "parentFile": 1, "parentPath": 1, + }) + self.assertEqual(s["prefixes"], { + "$(common)": 2, "$(root)": 1, "$(target)": 1, "common:/": 1, + "platform:/levels": 1, "platform:/other": 1, "relative/locator": 2, + }) + self.assertEqual(s["resolution"], { + "document": 3, "document_unmapped": 6, "include_id_missing": 1, + "relative_locator": 2, "unrecognized_prefix": 1, + }) + self.assertEqual(s["unique"], { + "targets": 9, + "targets_by_namespace": { + "$(common)": 2, "$(root)": 1, "$(target)": 1, "common:/": 1, + "platform:/levels": 1, "platform:/other": 1, "relative/locator": 2, + }, + "document_unmapped": 6, + "unknown_macro": 0, + "unrecognized_prefix": 1, + "relative_locator": 2, + "content_set_ids": 4, + "include_ids": 3, + }) + self.assertEqual(s["nodes"], {"documents": 7, "content_sets": 4, "targets": 9, "total": 20}) + self.assertEqual(s["edges"], { + "total": 16, "defines": 3, "includes": 4, "contains_file": 6, + "loads_changeset": 1, "parent_path": 1, "parent_file": 1, + "document_edges": 7, "target_edges": 9, + }) + self.assertEqual(s["content_graph"], { + "include_edges": 3, + "documents_with_incoming_includes": 2, + "documents_with_outgoing_includes": 3, + "root_documents": 1, + "root_fallback": False, + "reachable_documents": 3, + "max_depth": 2, + "cycles": 1, + "cycle_nodes": 2, + }) + self.assertEqual(s["reachable"], { + "documents": 3, "content_sets": 4, "targets": 7, "target_sites": 7, + }) + + mount = s["categories"]["mount / content manifests"] + self.assertEqual(mount["documents"], 3) + self.assertEqual(mount["manifest_documents"], 3) + self.assertEqual(mount["content_sets"], 3) + self.assertEqual(mount["include_references"], 4) + self.assertEqual(mount["target_references"], 7) + self.assertEqual(mount["references"], 11) + self.assertEqual(mount["roots"], 2) + unknown = s["categories"]["uncatalogued"] + self.assertEqual(unknown["documents"], 4) + self.assertEqual(unknown["target_references"], 2) + self.assertEqual(unknown["references"], 2) + self.assertEqual(unknown["roots"], 4) + + change_set = s["roots"]["CDataFileMgr__ContentChangeSetDef"] + self.assertEqual(change_set["documents"], 2) + self.assertEqual(change_set["content_sets"], 2) + self.assertEqual(change_set["include_references"], 3) + self.assertEqual(change_set["target_references"], 5) + self.assertEqual(change_set["references"], 8) + self.assertEqual(change_set["manifest_documents"], 2) + content_def = s["roots"]["CDataFileMgr__ContentDef"] + self.assertEqual(content_def["documents"], 1) + self.assertEqual(content_def["content_sets"], 1) + self.assertEqual(content_def["include_references"], 1) + self.assertEqual(content_def["target_references"], 2) + self.assertEqual(content_def["references"], 3) + + self.assertEqual(data["unresolved"], { + "document_unmapped": { + "$(common)": 2, "$(root)": 1, "$(target)": 1, + "platform:/levels": 1, "platform:/other": 1, + }, + "unknown_macro": {}, + "unrecognized_prefix": {"common:/": 1}, + "relative_locator": 2, + "include_id_missing": 1, + "total_sites": 10, + }) + + # Values, ids, locators and per-file names must not leak into the aggregate output. + with open(out, encoding="utf-8") as f: + blob = f.read() + for value in ("a.bk2", "fixture/a.rpf", "FIXTURE/A.XML", "set.alpha", "set.beta", + "missing.set", "../Item", "parent.dat", "fixture/g.meta", + "alpha.xml", "g.xml"): + self.assertNotIn(value, blob) + + def test_file_mode_keeps_manifest_documents_and_missing_ids(self): + alpha = os.path.join(self.root, "alpha.xml") + gamma = os.path.join(self.root, "gamma.xml") + delta = os.path.join(self.root, "delta.xml") + for path, payload in ((alpha, ALPHA), (gamma, GAMMA), (delta, DELTA)): + with open(path, "wb") as f: + f.write(payload) + + out = os.path.join(self.root, "files.json") + p = self.run_tool(alpha, gamma, delta, "--json", out) + self.assertEqual(p.returncode, 0, p.stdout + p.stderr) + with open(out, encoding="utf-8") as f: + data = json.load(f) + s = data["summary"] + self.assertEqual(s["mode"], "files") + self.assertEqual(s["payloads"], 3) + self.assertEqual(s["parsed"], 3) + self.assertEqual(s["manifest_documents"], 2) + self.assertEqual(s["content_sets"], 4) # alpha, beta, gamma and the second missing id + self.assertEqual(s["defined_content_sets"], 2) + self.assertEqual(s["dangling_content_sets"], 2) + self.assertEqual(s["resolution"]["document"], 1) + self.assertEqual(s["resolution"]["include_id_missing"], 2) + self.assertEqual(s["content_graph"]["include_edges"], 1) + self.assertEqual(s["content_graph"]["reachable_documents"], 2) + self.assertEqual(s["content_graph"]["cycles"], 0) + + def test_prefix_classification_keeps_unknown_schemes_unresolved(self): + self.assertEqual(gg.classify_target("$(common)/fixture/a.bk2"), + ("$(common)", "fixture/a.bk2", "document_unmapped")) + self.assertEqual(gg.classify_target("$(root)/fixture/x.meta"), + ("$(root)", "fixture/x.meta", "document_unmapped")) + self.assertEqual(gg.classify_target("platform:/levels/fixture/a.rpf"), + ("platform:/levels", "levels/fixture/a.rpf", "document_unmapped")) + self.assertEqual(gg.classify_target("platform:/data/fixture"), + ("platform:/other", "data/fixture", "document_unmapped")) + self.assertEqual(gg.classify_target("common:/FIXTURE/A.XML"), + ("common:/", "FIXTURE/A.XML", "unrecognized_prefix")) + self.assertEqual(gg.classify_target("$(future)/a"), + ("$(future)", "a", "unknown_macro")) + self.assertEqual(gg.classify_target("../Item[@key='X']"), + ("relative/locator", "../Item[@key='X']", "relative_locator")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/gamedata_graph.py b/tools/gamedata_graph.py new file mode 100644 index 000000000..8d76c4a11 --- /dev/null +++ b/tools/gamedata_graph.py @@ -0,0 +1,509 @@ +"""Build a content-set and reference graph for the ``common.rpf`` XML catalog. + +``gamedata_xml.py`` catalogs the XML documents recovered from an RPF9 carve and counts reference +tokens, but it drops the target strings. This tool keeps them long enough to build and measure a +directed graph: + + python -I gamedata_graph.py [--json FILE] + python -I gamedata_graph.py [ ...] [--json FILE] + +A carve directory is read through ``gamedata_xml.load_documents``, so multi-stream documents are +rebuilt the same way as the index and catalog. For each parsed document the graph has: + +* a document node; +* a content-set node for every ```` (a top-level id or an id inside ````); +* a target node for every ````, ````, ``parentPath`` and ``parentFile`` value. + +Edges are ``defines`` (document to its sets), ``includes`` (document to an ```` id), +``contains_file`` (set or document to a filename target), ``loads_changeset`` (document to a +```` target), and ``parent_path`` / ``parent_file`` for the two attributes. An include is +joined to a document only when its text equals a set id exactly. Missing ids become dangling +content-set nodes. They are never guessed from a similar spelling. + +The four documented prefix rules are measured: ``$(common)``, ``$(root)``, ``$(target)``, and +``platform:/`` split into ``levels`` and everything else. ``common:/`` occurs in the corpus but is +not one of those rules, so it is reported as an unrecognized scheme and is not normalized to +``$(common)``. ``parentPath`` values are XPath-like locators, not archive paths. + +The output is aggregate and schema-only: counts, root names, category names and reference prefixes. +Target strings, ids, offsets, source names and element values are never written. This keeps the JSON reviewable without copying game data, and the tests are +synthetic. The encrypted RPF9 table of contents is still the reason an archive path cannot be +mapped to a carved document; those targets remain target nodes rather than invented document +edges. This is a mount/reference graph, not a full runtime schema: the catalog carries names and +categories, not field types. +""" +import argparse +import json +import os +import re +import sys +import xml.etree.ElementTree as ET +from collections import Counter, defaultdict, deque + +ROOT = os.path.dirname(os.path.abspath(__file__)) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) +import gamedata_xml as gx # noqa: E402 + +MANIFEST_ROOTS = ("CDataFileMgr__ContentChangeSetDef", "CDataFileMgr__ContentDef") +MANIFEST_ROOT_SET = frozenset(MANIFEST_ROOTS) +KNOWN_MACROS = frozenset(("common", "target", "root")) +PARENT_ATTRIBUTES = ("parentPath", "parentFile") + +MACRO_REF = re.compile(r"^\$\(([A-Za-z_][\w.-]*)\)(.*)$", re.S) +PLATFORM_REF = re.compile(r"^platform:/([^/]*)(.*)$", re.I | re.S) +SCHEME_REF = re.compile(r"^([A-Za-z][\w.-]*):/(.*)$", re.S) +RELATIVE = "relative/locator" + + +def classify_target(text: str) -> tuple: + """Return (namespace, remainder, resolution reason) for one reference string.""" + value = text.strip() + match = MACRO_REF.match(value) + if match: + name = match.group(1) + namespace = "$(" + name + ")" + remainder = match.group(2).lstrip("/") + if name.lower() in KNOWN_MACROS: + return namespace, remainder, "document_unmapped" + return namespace, remainder, "unknown_macro" + match = PLATFORM_REF.match(value) + if match: + first = (match.group(1) or "").lower() + namespace = "platform:/levels" if first == "levels" else "platform:/other" + return namespace, (match.group(1) or "") + match.group(2), "document_unmapped" + match = SCHEME_REF.match(value) + if match: + return match.group(1).lower() + ":/", match.group(2), "unrecognized_prefix" + return RELATIVE, value, "relative_locator" + + +def _text(element) -> str: + return (element.text or "").strip() if element is not None else "" + + +def _direct_id(element) -> str: + for child in element: + if child.tag == "id": + value = _text(child) + if value: + return value + return "" + + +def _add_filename_refs(report: dict, file_list, owner: str) -> None: + if file_list is None: + return + for filename in file_list.iter("filename"): + value = _text(filename) + if value: + report["refs"].append({"kind": "filename", "target": value, "owner": owner}) + + +def scan_document(doc: dict) -> dict: + """Parse one payload and keep only the graph-relevant names and reference strings.""" + report = { + "root": "", + "parsed": False, + "complete": bool(doc.get("complete", False)), + "sets": [], + "refs": [], + "includes": [], + } + try: + root = ET.fromstring(doc["data"]) + except (ET.ParseError, ValueError): + # A truncated tail can still carry a closing-root hint from the index. It is a named but + # unparsed document, not a rootless fragment; only an empty hint is rootless. + report["root"] = doc.get("root_hint") or "" + return report + report["parsed"] = True + report["root"] = root.tag + report["complete"] = bool(doc.get("complete", True)) + + own = _direct_id(root) + if own: + report["sets"].append(own) + + content_sets = root.find("contentSets") + if content_sets is not None: + for item in content_sets: + set_id = _direct_id(item) + if set_id: + report["sets"].append(set_id) + + seen = set() + report["sets"] = [set_id for set_id in report["sets"] + if not (set_id in seen or seen.add(set_id))] + + _add_filename_refs(report, root.find("fileList"), own) + + if content_sets is not None: + for item in content_sets: + set_id = _direct_id(item) + if set_id: + _add_filename_refs(report, item.find("fileList"), set_id) + + changesets = root.find("includedChangesets") + if changesets is not None: + for load_path in changesets.iter("loadPath"): + value = _text(load_path) + if value: + report["refs"].append({"kind": "loadPath", "target": value, "owner": ""}) + + included = root.find("includedSets") + if included is not None: + for item in included: + value = "".join(item.itertext()).strip() + if value: + report["includes"].append(value) + + for element in root.iter(): + for attribute in PARENT_ATTRIBUTES: + value = (element.attrib.get(attribute) or "").strip() + if value: + report["refs"].append({"kind": attribute, "target": value, "owner": ""}) + return report + + +def _strongly_connected(nodes: list, adjacency: dict) -> list: + """Tarjan's algorithm; recursion depth is bounded by the document count.""" + index = {} + low = {} + stack = [] + on_stack = set() + components = [] + counter = 0 + + def visit(node): + nonlocal counter + index[node] = low[node] = counter + counter += 1 + stack.append(node) + on_stack.add(node) + for neighbour in adjacency.get(node, ()): + if neighbour not in index: + visit(neighbour) + low[node] = min(low[node], low[neighbour]) + elif neighbour in on_stack: + low[node] = min(low[node], index[neighbour]) + if low[node] == index[node]: + component = [] + while True: + member = stack.pop() + on_stack.discard(member) + component.append(member) + if member == node: + break + components.append(component) + + for node in nodes: + if node not in index: + visit(node) + return components + + +def build_graph(documents: list) -> dict: + """Build nodes, edges, unresolved buckets and aggregates from scanned documents.""" + reports = [scan_document(doc) for doc in documents] + set_docs = defaultdict(list) + all_set_ids = set() + for index, report in enumerate(reports): + for set_id in report["sets"]: + set_docs[set_id].append(index) + all_set_ids.add(set_id) + for set_id in report["includes"]: + all_set_ids.add(set_id) + + target_ids = {} + for report in reports: + for ref in report["refs"]: + namespace, remainder, _ = classify_target(ref["target"]) + key = (namespace, remainder) + if key not in target_ids: + target_ids[key] = len(target_ids) + + edges = Counter() + references = Counter() + prefixes = Counter() + resolution = Counter() + unresolved_sites = Counter() + unresolved_namespaces = defaultdict(Counter) + unique_resolution = defaultdict(set) + target_edges = [] + include_edges = [] + dangling_sets = set() + + for index, report in enumerate(reports): + for set_id in report["sets"]: + edges["defines"] += 1 + for set_id in report["includes"]: + references["includedSets"] += 1 + edges["includes"] += 1 + if set_id in set_docs: + resolution["document"] += 1 + for target_doc in set_docs[set_id]: + include_edges.append((index, target_doc)) + else: + resolution["include_id_missing"] += 1 + unresolved_sites["include_id_missing"] += 1 + dangling_sets.add(set_id) + + for ref in report["refs"]: + kind = ref["kind"] + namespace, remainder, reason = classify_target(ref["target"]) + references[kind] += 1 + prefixes[namespace] += 1 + resolution[reason] += 1 + unique_resolution[reason].add((namespace, remainder)) + if reason == "document_unmapped": + unresolved_sites["document_unmapped"] += 1 + unresolved_namespaces["document_unmapped"][namespace] += 1 + elif reason == "unrecognized_prefix": + unresolved_sites["unrecognized_prefix"] += 1 + unresolved_namespaces["unrecognized_prefix"][namespace] += 1 + elif reason == "unknown_macro": + unresolved_sites["unknown_macro"] += 1 + unresolved_namespaces["unknown_macro"][namespace] += 1 + elif reason == "relative_locator": + unresolved_sites["relative_locator"] += 1 + if kind == "filename": + edges["contains_file"] += 1 + edge_kind = "contains_file" + elif kind == "loadPath": + edges["loads_changeset"] += 1 + edge_kind = "loads_changeset" + elif kind == "parentPath": + edges["parent_path"] += 1 + edge_kind = "parent_path" + else: + edges["parent_file"] += 1 + edge_kind = "parent_file" + target_edges.append((index, ref["owner"], edge_kind, (namespace, remainder))) + + include_edges = sorted(set(include_edges)) + adjacency = defaultdict(set) + for source, target in include_edges: + adjacency[source].add(target) + in_degree = Counter() + for _, target in include_edges: + in_degree[target] += 1 + + manifest_documents = [index for index, report in enumerate(reports) + if report["parsed"] and report["root"] in MANIFEST_ROOT_SET] + roots = [index for index in manifest_documents if in_degree[index] == 0] + root_fallback = False + if not roots and manifest_documents: + roots = list(manifest_documents) + root_fallback = True + + depth = {index: 0 for index in roots} + queue = deque(roots) + reachable_docs = set() + while queue: + source = queue.popleft() + if source in reachable_docs: + continue + reachable_docs.add(source) + for target in adjacency.get(source, ()): + if target not in depth: + depth[target] = depth[source] + 1 + queue.append(target) + + components = _strongly_connected(list(range(len(reports))), adjacency) + cycle_components = [component for component in components + if len(component) > 1 or component[0] in adjacency.get(component[0], ())] + cycle_nodes = sum(len(component) for component in cycle_components) + + reachable_sets = set() + reachable_targets = set() + reachable_target_sites = 0 + for index in reachable_docs: + report = reports[index] + reachable_sets.update(report["sets"]) + reachable_sets.update(report["includes"]) + for index, owner, _, key in target_edges: + if index in reachable_docs and (not owner or owner in reachable_sets): + reachable_target_sites += 1 + reachable_targets.add(key) + + category_stats = defaultdict(Counter) + root_stats = defaultdict(Counter) + for report in reports: + root = report["root"] + category = gx.category_for(root) if root else gx.UNCATALOGUED + for stats in (category_stats[category], root_stats[root]): + stats["documents"] += 1 + stats["parsed"] += int(report["parsed"]) + stats["complete"] += int(report["complete"]) + stats["content_sets"] += len(report["sets"]) + stats["include_references"] += len(report["includes"]) + stats["target_references"] += len(report["refs"]) + stats["references"] += len(report["refs"]) + len(report["includes"]) + if root in MANIFEST_ROOT_SET: + category_stats[category]["manifest_documents"] += 1 + root_stats[root]["manifest_documents"] += 1 + + # Root names are stable schema names; category is the only derived label. + for root, stats in root_stats.items(): + stats["category"] = gx.category_for(root) if root else gx.UNCATALOGUED + + unique_by_namespace = Counter() + for namespace, _ in target_ids: + unique_by_namespace[namespace] += 1 + + summary = { + "mode": "", + "payloads": len(reports), + "documents": sum(1 for report in reports if report["complete"]), + "parsed": sum(1 for report in reports if report["parsed"]), + "unparsed": sum(1 for report in reports if not report["parsed"]), + "root_count": len([root for root in root_stats if root]), + "rootless": sum(1 for report in reports if not report["root"]), + "manifest_documents": len(manifest_documents), + "manifest_roots": len(MANIFEST_ROOTS), + "content_sets": len(all_set_ids), + "defined_content_sets": len(set_docs), + "dangling_content_sets": len(dangling_sets), + "duplicate_set_ids": sum(1 for indexes in set_docs.values() if len(indexes) > 1), + "reference_sites": sum(references.values()), + "target_sites": sum(references[kind] for kind in + ("filename", "loadPath", "parentPath", "parentFile")), + "include_sites": references["includedSets"], + "references": dict(sorted(references.items())), + "prefixes": dict(sorted(prefixes.items())), + "resolution": dict(sorted(resolution.items())), + "unique": { + "targets": len(target_ids), + "targets_by_namespace": dict(sorted(unique_by_namespace.items())), + "document_unmapped": len(unique_resolution["document_unmapped"]), + "unknown_macro": len(unique_resolution["unknown_macro"]), + "unrecognized_prefix": len(unique_resolution["unrecognized_prefix"]), + "relative_locator": len(unique_resolution["relative_locator"]), + "content_set_ids": len(all_set_ids), + "include_ids": len({set_id for report in reports for set_id in report["includes"]}), + }, + "nodes": { + "documents": len(reports), + "content_sets": len(all_set_ids), + "targets": len(target_ids), + "total": len(reports) + len(all_set_ids) + len(target_ids), + }, + "edges": { + "total": sum(edges.values()), + "defines": edges["defines"], + "includes": edges["includes"], + "contains_file": edges["contains_file"], + "loads_changeset": edges["loads_changeset"], + "parent_path": edges["parent_path"], + "parent_file": edges["parent_file"], + "document_edges": edges["defines"] + edges["includes"], + "target_edges": (edges["contains_file"] + edges["loads_changeset"] + + edges["parent_path"] + edges["parent_file"]), + }, + "content_graph": { + "include_edges": len(include_edges), + "documents_with_incoming_includes": len(in_degree), + "documents_with_outgoing_includes": sum(1 for report in reports + if report["includes"]), + "root_documents": len(roots), + "root_fallback": root_fallback, + "reachable_documents": len(reachable_docs), + "max_depth": max(depth.values(), default=0), + "cycles": len(cycle_components), + "cycle_nodes": cycle_nodes, + }, + "reachable": { + "documents": len(reachable_docs), + "content_sets": len(reachable_sets), + "targets": len(reachable_targets), + "target_sites": reachable_target_sites, + }, + "categories": dict(sorted(category_stats.items(), key=lambda kv: (-kv[1]["documents"], + kv[0]))), + "roots": dict(sorted(root_stats.items(), key=lambda kv: (-kv[1]["documents"], kv[0]))), + } + # Count roots per category from the root table, not from documents. A root belongs to exactly + # one category, so this also checks that the category totals line up with the 118 named roots. + for category, stats in summary["categories"].items(): + stats["roots"] = sum(1 for root in summary["roots"] + if (gx.category_for(root) if root else gx.UNCATALOGUED) == category) + stats.setdefault("manifest_documents", 0) + for stats in summary["roots"].values(): + stats.setdefault("manifest_documents", 0) + stats.setdefault("category", gx.UNCATALOGUED) + + return { + "summary": summary, + "unresolved": { + "document_unmapped": dict(sorted(unresolved_namespaces["document_unmapped"].items())), + "unknown_macro": dict(sorted(unresolved_namespaces["unknown_macro"].items())), + "unrecognized_prefix": dict(sorted(unresolved_namespaces["unrecognized_prefix"].items())), + "relative_locator": unresolved_sites["relative_locator"], + "include_id_missing": unresolved_sites["include_id_missing"], + "total_sites": sum(unresolved_sites.values()), + }, + } + + +def print_summary(graph: dict) -> None: + summary = graph["summary"] + print(f'{summary["payloads"]} payloads ({summary["documents"]} complete, ' + f'{summary["parsed"]} parsed), {summary["manifest_documents"]} manifest documents') + print(f'{summary["content_sets"]} content-set ids ' + f'({summary["defined_content_sets"]} defined, ' + f'{summary["dangling_content_sets"]} dangling, ' + f'{summary["duplicate_set_ids"]} duplicate)') + print(f'{summary["reference_sites"]:,} reference sites: ' + f'{summary["references"].get("filename", 0):,} filename, ' + f'{summary["references"].get("loadPath", 0)} loadPath, ' + f'{summary["references"].get("parentPath", 0)} parentPath, ' + f'{summary["references"].get("parentFile", 0)} parentFile, ' + f'{summary["include_sites"]} includedSets') + prefixes = ", ".join(f"{name} {count:,}" for name, count in summary["prefixes"].items()) + print(f'prefixes: {prefixes}') + print(f'resolution: {summary["resolution"]}') + print(f'graph: {summary["nodes"]["total"]:,} nodes, {summary["edges"]["total"]:,} edges ' + f'({summary["edges"]["defines"]} defines, {summary["edges"]["includes"]} includes, ' + f'{summary["edges"]["contains_file"]:,} file, ' + f'{summary["edges"]["loads_changeset"]} changeset, ' + f'{summary["edges"]["parent_path"]} parentPath, ' + f'{summary["edges"]["parent_file"]} parentFile)') + content = summary["content_graph"] + print(f'content graph: {content["root_documents"]} roots, ' + f'{content["reachable_documents"]} reachable documents, ' + f'{summary["reachable"]["content_sets"]} sets, depth {content["max_depth"]}, ' + f'{content["cycles"]} cycles') + print(f'reachable: {summary["reachable"]["targets"]:,} unique targets ' + f'({summary["reachable"]["target_sites"]:,} sites)') + unresolved = graph["unresolved"] + print(f'unresolved: {unresolved["total_sites"]:,} sites ' + f'({len(unresolved["document_unmapped"])} archive namespaces, ' + f'{sum(unresolved["unrecognized_prefix"].values())} unknown scheme, ' + f'{unresolved["relative_locator"]} relative, ' + f'{unresolved["include_id_missing"]} missing include id)') + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("targets", nargs="+", help="carve directory or XML file(s)") + parser.add_argument("--json", help="write the aggregate graph summary to this JSON") + args = parser.parse_args() + + try: + documents = list(gx.load_documents(args.targets)) + except FileNotFoundError as exc: + print(f"not found: {exc}", file=sys.stderr) + return 2 + graph = build_graph(documents) + graph["summary"]["mode"] = gx.document_mode(args.targets) + print_summary(graph) + if args.json: + with open(args.json, "w", encoding="utf-8") as f: + json.dump(graph, f, indent=1) + print("wrote", args.json) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 5da04fd204dc62a84f81e2de5a445802a9e7db0d Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:48:40 +0100 Subject: [PATCH 24/53] Validate world manifests before viewer startup --- viewer/index.html | 70 ++++++++++++++++++++++++++++++++++------------- 1 file changed, 51 insertions(+), 19 deletions(-) diff --git a/viewer/index.html b/viewer/index.html index e3996cdc6..ed5d80495 100644 --- a/viewer/index.html +++ b/viewer/index.html @@ -25,7 +25,11 @@
- +
W A S D move · Q/E down/up · Shift fast · Ctrl slow · wheel: speed
F wireframe · T textures/clay · G chunk bounds · R back to spawn · Esc release mouse @@ -44,26 +48,55 @@ import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"; // ---------- world description ---------- // world/world.json: { "spawn": [x,y,z], "chunks": [ { "id", "url", "bounds": [minx,miny,minz,maxx,maxy,maxz] } ] } -// Each chunk is a .glb in world space (Y up, metres). When no world.json exists the viewer -// generates TEST terrain locally and says so on screen. -async function loadWorld() { - if (new URLSearchParams(location.search).has("test")) return testWorld(); - try { - const r = await fetch("world/world.json", { cache: "no-store" }); - if (!r.ok) throw new Error(r.status); - const w = await r.json(); - w.test = false; - return w; - } catch { return testWorld(); } +// Each chunk is a .glb in world space (Y up, metres). Validate the manifest before +// the camera and streaming code use its coordinates and chunk identifiers. +function manifestError(world) { + const isPosition = (value, length) => + Array.isArray(value) && value.length === length && value.every(Number.isFinite); + const isNonemptyString = value => typeof value === "string" && value.trim().length > 0; + if (!isPosition(world?.spawn, 3)) return "spawn must contain three finite coordinates"; + if (!Array.isArray(world.chunks)) return "chunks must be an array"; + const ids = new Set(); + for (const [i, chunk] of world.chunks.entries()) { + if (!isNonemptyString(chunk?.id) || ids.has(chunk.id)) return `chunks[${i}].id must be a unique, nonempty string`; + if (!isNonemptyString(chunk.url)) return `chunks[${i}].url must be a nonempty string`; + const b = chunk.bounds; + if (!isPosition(b, 6) || b[0] > b[3] || b[1] > b[4] || b[2] > b[5]) + return `chunks[${i}].bounds must contain six finite, ordered coordinates`; + ids.add(chunk.id); + } + return null; } -function testWorld() { +async function loadWorld() { + if (new URLSearchParams(location.search).has("test")) return testWorld("Test mode was requested."); + let response; + try { + response = await fetch("world/world.json", { cache: "no-store" }); + } catch { + return testWorld("world/world.json could not be loaded."); + } + if (response.status === 404) return testWorld("world/world.json was not found."); + if (!response.ok) return testWorld(`world/world.json returned HTTP ${response.status}.`); + + let world; + try { + world = await response.json(); + } catch { + return testWorld("world/world.json could not be read as valid JSON."); + } + const error = manifestError(world); + if (error) return testWorld(`Invalid world/world.json: ${error}.`); + return { ...world, test: false }; +} + +function testWorld(reason) { const size = 256, n = 24, chunks = []; for (let z = -n / 2; z < n / 2; z++) for (let x = -n / 2; x < n / 2; x++) chunks.push({ id: `test_${x}_${z}`, test: [x, z, size], bounds: [x * size, -50, z * size, (x + 1) * size, 200, (z + 1) * size] }); - return { test: true, spawn: [0, 120, 0], chunks }; + return { test: true, reason, spawn: [0, 120, 0], chunks }; } // Deterministic test terrain: rolling hills plus a grid of boxes. Nothing here comes from the game. @@ -252,11 +285,10 @@ function stream(now = performance.now()) { // ---------- main loop ---------- const world = await loadWorld(); camera.position.fromArray(world.spawn); -const banner = document.getElementById("banner"); -if (world.test) banner.innerHTML = "TEST TERRAIN: generated in the browser. No world/world.json found.
" + - "Build chunks with python -I tools/world_build.py <work>\\assets --out <work>\\world and serve with " + - "python -I viewer/serve.py --world <work>\\world."; -else banner.classList.add("hidden"); +if (world.test) { + document.getElementById("world-status").textContent = world.reason; + document.getElementById("banner").classList.remove("hidden"); +} for (const c of world.chunks) { const b = c.bounds, box = new THREE.Box3(new THREE.Vector3(b[0], b[1], b[2]), new THREE.Vector3(b[3], b[4], b[5])); boundsGroup.add(new THREE.Box3Helper(box, 0x5fb3ff)); From 526e123878b2ad8eed552dd2831205e7b698d0ad Mon Sep 17 00:00:00 2001 From: Kam471 Date: Sat, 21 Nov 2026 22:30:15 +0000 Subject: [PATCH 25/53] Docs: measure the BCPack block structure and limits Record the 48-byte lane header, block counts, the exact BC1/BC4 constant-lane check, and the 200-chunk entropy convergence. A public BC1 candidate is mip-consistent on 40/200 chunks but has no byte-exact plaintext check and an unpublished predictor window, so no decoder is added. Also record that no shipped DLL contains a BCPack/BCn/DStorage decoder or dispatcher. --- docs/textures.md | 46 ++++++++++++++++++++++++++-------------------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/docs/textures.md b/docs/textures.md index b27e41bff..93fa3c1f0 100644 --- a/docs/textures.md +++ b/docs/textures.md @@ -457,11 +457,11 @@ The full corpus: | BC4 | 77 | 1 | 77 | The record's block count is `N/k`; the `k > 1` cases are a subset of the 131,072-, 262,144- -and 524,288-block chunks, consistent with `k` equal streams. No BC1 or BC4 chunk failed the -check. BC3 and BC5 use `0xdb` (`K = 2`), but the record is constant in only 7/35 and 39/333 -chunks (BC5: 36 at `N`, 3 at `N/4`); BC6H and BC7 had no matching constant lane 1 for -`K` in {2, 4, 8, 16, 32}. The exact result is therefore a BC1/BC4 header check, not a general -BCPack header parser. +and 524,288-block chunks, consistent with `k` equal streams. No BC1 or BC4 first record failed +the check. BC3 and BC5 use `0xdb` (`K = 2`), but the first lane-1 record matches the constant +model in only 7/35 and 39/333 chunks (BC5: 36 at `N`, 3 at `N/4`); BC6H and BC7 had no matching +constant lane 1 for `K` in {2, 4, 8, 16, 32}. The exact result is therefore a BC1/BC4 header +check, not a general BCPack header parser. Padding is zero-filled: every padding run starts with zero bytes (checked `min(16, pad)` bytes of all 108,229 padded BCPack chunks: 102,368 BC1, 35 BC3, 76 BC4, 332 BC5, 268 BC6H, 5,150 @@ -496,10 +496,10 @@ tables above and the container descriptors are the readable facts. ### Entropy framing and the pixel subset -The public MDU tables and a research lockstep lane schedule reproduce the entropy layer -without guessing pixel semantics. The test set is 200 textures whose mip 0 is exactly one BC1 -BCPack chunk and whose mip 1 is fully zlib/raw, in store order. All 200 chunks passed the hard -check: +The public MDU tables and a research lockstep lane schedule reproduce the entropy layer on the +200-chunk test set without guessing pixel semantics. The set is 200 textures whose mip 0 is +exactly one BC1 BCPack chunk and whose mip 1 is fully zlib/raw, in store order. All 200 chunks +passed the hard check: - all 12 lanes finished with exactly `N` symbols; - every lane ended at `L`, `L >> 8` or `L >> 16`; @@ -507,9 +507,9 @@ check: This is a byte-exact convergence check of the entropy layer; it does not identify the endpoint or index semantics. A public research repository, [`bcpack-rs`](https://github.com/Ahmet-Dedeler/bcpack-rs) -(MIT OR Apache-2.0), publishes candidate BC1 endpoint and index rules. An independent run of -that code on the same 200 chunks gives (PSNR: each 2×2 mip0 quadrant against the mip1 pixel at -that position): +(MIT OR Apache-2.0), publishes candidate BC1 endpoint and index rules. An independent +implementation of that rule, using the public MDU tables and its published codebook, on the +same 200 chunks gives (PSNR: each 2×2 mip0 quadrant against the mip1 pixel at that position): | Subset | Chunks | Candidate BC1 vs mip 1 (PSNR) | Flat mip 1 | |---|---:|---|---:| @@ -518,14 +518,14 @@ that position): | two or more | 116 | not decoded | — | This is **mip consistency, not a byte-exact decode**. The 160 chunks with a pre-start reference -need the fixed 256-slot predictor window; the research branches fit only part of it and the -full table is not published. The 40 clean chunks agree with mip 1 at 31–46 dB, which is strong -evidence the candidate rule is close; this is not a held-out score, and mip 1 is a downsampled -image, not the source blocks. No plaintext BCPack/BC block pair was found publicly. The -repository's own `master` (commit `3534739`, read 2026-11-21) claims BC1 decodes at 36.6 dB -median on held-out textures and says 621 of 3,276 pair textures are fully known; the gap is -the unpublished window and the unresolved codebook entries, not a byte-exact validation. The -code is not adopted here. +need the fixed 256-slot predictor window for a full decode; the research branches fit only +part of it and the full table is not published. The 40 clean chunks agree with mip 1 at 31–46 +dB, which is strong evidence the candidate rule is close; this is not a held-out score, and +mip 1 is a downsampled image, not the source blocks. No plaintext BCPack/BC block pair was +found publicly. The repository's own `master` (commit `3534739`, read 2026-11-21) claims BC1 +decodes at 36.6 dB median on held-out textures and says 621 of 3,276 pair textures are fully +known; the gap is the unpublished window and the unresolved codebook entries, not a +byte-exact validation. The code is not adopted here. A decoder still needs: @@ -653,6 +653,12 @@ bytes of each BCPack chunk. The 200-chunk entropy check used the public MDU tabl `silicon-rans` on the same mip-pair selection. The probes are not committed because they duplicate `Pool` and add no decoder; they write no texture data. +The BCPack counts above come from a read-only aggregation over the same `Pool` parser: it +mmaps each pool, reads the RDS5 header, chunk table and ETPF records, then reads the first 64 +bytes of each BCPack chunk. The 200-chunk entropy check used the public MDU tables from +`silicon-rans` on the same mip-pair selection. The probes are not committed because they +duplicate `Pool` and add no decoder; they write no texture data. + `rpf9dump ttpf` writes one `manifest.json` per pool with a `Limitation` field for every catalog record, and its summary line has the same `ok` / `skip` totals. The first split above came from a read-only mirror of `TtpfReader`'s catalog checks: it mmapped each pool and read From 024dc0ecddbd6b5f09be385f2e6a2a291a6c7cd2 Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:49:26 +0100 Subject: [PATCH 26/53] Cover malformed and missing viewer manifests --- tests/test_viewer_streaming.cjs | 59 ++++++++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/tests/test_viewer_streaming.cjs b/tests/test_viewer_streaming.cjs index b0ae6cbd0..48764ffef 100644 --- a/tests/test_viewer_streaming.cjs +++ b/tests/test_viewer_streaming.cjs @@ -4,8 +4,65 @@ const { join } = require('node:path'); const vm = require('node:vm'); const { test } = require('node:test'); -// Exercise the viewer's actual streaming code without WebGL, a network or game data. +// Exercise the viewer's actual loading and streaming code without WebGL, a network or game data. const html = readFileSync(join(__dirname, '..', 'viewer', 'index.html'), 'utf8'); +const worldBegin = html.indexOf('// ---------- world description ----------'); +const worldEnd = html.indexOf('// Deterministic test terrain:', worldBegin); +assert(worldBegin >= 0 && worldEnd > worldBegin, 'viewer world description section must exist'); +const worldSource = html.slice(worldBegin, worldEnd); + +function loadWorld(fetch, search = '') { + return vm.runInNewContext(worldSource + '\nloadWorld()', { fetch, location: { search }, URLSearchParams }); +} + +function manifestResponse(manifest) { + return async () => ({ ok: true, json: async () => manifest }); +} + +const worldChunk = { id: 'cell', url: 'world/chunks/cell.glb', bounds: [-1, -2, -3, 1, 2, 3] }; + +test('a valid manifest is used, including an intentionally empty world', async () => { + for (const chunks of [[worldChunk], []]) { + const world = await loadWorld(manifestResponse({ spawn: [1, 2, 3], chunks })); + assert.equal(world.test, false); + assert.equal(world.spawn.join(','), '1,2,3'); + assert.deepEqual(world.chunks, chunks); + } +}); + +test('malformed manifests keep the viewer usable and identify the invalid field', async t => { + const cases = [ + ['missing spawn', {}, /spawn/], + ['non-finite spawn', { spawn: [0, Infinity, 0], chunks: [] }, /spawn/], + ['invalid chunks array', { spawn: [0, 0, 0], chunks: {} }, /chunks/], + ['missing chunk', { spawn: [0, 0, 0], chunks: [null] }, /chunks\[0\]\.id/], + ['missing URL', { spawn: [0, 0, 0], chunks: [{ ...worldChunk, url: '' }] }, /chunks\[0\]\.url/], + ['bad bounds', { spawn: [0, 0, 0], chunks: [{ ...worldChunk, bounds: [0, 0, 0, -1, 1, 1] }] }, + /chunks\[0\]\.bounds/], + ['duplicate chunk ID', { spawn: [0, 0, 0], chunks: [worldChunk, worldChunk] }, /chunks\[1\]\.id/], + ]; + for (const [label, manifest, field] of cases) { + await t.test(label, async () => { + const world = await loadWorld(manifestResponse(manifest)); + assert.equal(world.test, true); + assert.ok(world.chunks.length > 0); + assert.match(world.reason, field); + }); + } +}); + +test('test mode, a missing manifest, and an unreadable manifest have distinct messages', async () => { + const explicit = await loadWorld(async () => assert.fail('test mode must not fetch'), '?test'); + const missing = await loadWorld(async () => ({ ok: false, status: 404 })); + const invalid = await loadWorld(async () => ({ ok: true, json: async () => { throw new SyntaxError(); } })); + const unreachable = await loadWorld(async () => { throw new TypeError(); }); + for (const world of [explicit, missing, invalid, unreachable]) assert.equal(world.test, true); + assert.match(explicit.reason, /requested/); + assert.match(missing.reason, /not found/); + assert.match(invalid.reason, /valid JSON/); + assert.match(unreachable.reason, /could not be loaded/); +}); + const begin = html.indexOf('// ---------- chunk streaming ----------'); const end = html.indexOf('// ---------- main loop ----------', begin); assert(begin >= 0 && end > begin, 'viewer streaming section must exist'); From 4dfdbc3f0efbf63d0aa14b0d2f8c3414b35dc3ea Mon Sep 17 00:00:00 2001 From: Vonsek <45567075+Vonsek@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:50:12 +0100 Subject: [PATCH 27/53] fix: build the vertex shader for filtered cube tests The cube harness loads vs_ids at runtime, so a standalone fragment filter needs the same draw dependency as the ordinary texture fixture. --- scripts/run_gpu_tests.py | 5 ++--- tests/test_run_gpu_tests_paths.py | 4 ++++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 1ce87832b..710723023 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -396,9 +396,8 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool, return ok, detail -# Shaders a selected test draws with, built even when the filter leaves them out (#192): ps_flat and -# ps_texture_sample (vk_texture_test) are drawn with vs_ids. -DRAWN_WITH = {"ps_flat": "vs_ids.asm", "ps_texture_sample": "vs_ids.asm"} +# Shaders a selected test draws with, built even when the filter leaves them out (#192). +DRAWN_WITH = {"ps_flat": "vs_ids.asm", "ps_texture_sample": "vs_ids.asm", "ps_cube_sample": "vs_ids.asm"} def with_draw_shaders(asm_files: list[str]) -> list[str]: diff --git a/tests/test_run_gpu_tests_paths.py b/tests/test_run_gpu_tests_paths.py index 6dd8fd8c1..d18818517 100644 --- a/tests/test_run_gpu_tests_paths.py +++ b/tests/test_run_gpu_tests_paths.py @@ -17,6 +17,10 @@ class DrawShaders(unittest.TestCase): self.assertEqual(run_gpu_tests.with_draw_shaders(["ps_texture_sample.asm"]), ["ps_texture_sample.asm", "vs_ids.asm"]) + def test_cube_sample_brings_vs_ids(self): + self.assertEqual(run_gpu_tests.with_draw_shaders(["ps_cube_sample.asm"]), + ["ps_cube_sample.asm", "vs_ids.asm"]) + def test_flat_still_brings_vs_ids(self): self.assertEqual(run_gpu_tests.with_draw_shaders(["ps_flat.asm"]), ["ps_flat.asm", "vs_ids.asm"]) From 0ca9bb8bc034ac2f5f322ce5b428af964bffca4e Mon Sep 17 00:00:00 2001 From: IAmNotSiob <273832158+IAmNotSiob@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:50:12 +0100 Subject: [PATCH 28/53] Runtime: gta6rt --run, and a stand-in game executable run through the loader gta6rt --run [-- args] maps and binds the executable, initialises its modules and calls its entry point on a game thread. shims/process.cpp answers the process-level imports through the game's own import table: argv/argc and GetCommandLine are the game's (UCRT api-set/ucrtbase and msvcrt forms), and exit/_exit/quick_exit/ExitProcess/abort end the run with that exit code instead of the host. gta6rt then exits with the game's code directly, so the game's atexit handlers don't run during host shutdown. tiny_game.exe (CTest run_tiny_game, run_tiny_game_exit_code) does what a title does in its first second: arguments, a static initializer, a 4 MiB allocation, a file round trip, a thread, and xgameruntime.dll imports, which the shim registry answers instead of the link-time stub. thread_local and a C++ exception are opt-in (LEONIDA_RUN_TLS / LEONIDA_RUN_EH) until #93 and #176. --- README.md | 2 +- runtime/CMakeLists.txt | 25 +++ runtime/README.md | 2 + runtime/shims/process.cpp | 199 ++++++++++++++++++++ runtime/shims/process.h | 17 ++ runtime/src/main.cpp | 48 +++-- runtime/test/fixtures/tiny_game.cpp | 106 +++++++++++ runtime/test/fixtures/xgameruntime_stub.cpp | 10 + 8 files changed, 397 insertions(+), 12 deletions(-) create mode 100644 runtime/shims/process.cpp create mode 100644 runtime/shims/process.h create mode 100644 runtime/test/fixtures/tiny_game.cpp create mode 100644 runtime/test/fixtures/xgameruntime_stub.cpp diff --git a/README.md b/README.md index cc51cc5e9..d68d2d296 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ work on booting can start as soon as one is available to a developer. | Texture dictionaries and world texture pools (DDS) | ✅ Exported. Some pool entries (BCPack) are skipped | | Audio banks (AWC: Opus, XMA2) | ✅ Exported whole. Opus repackaged **losslessly** as Ogg Opus; PCM (codec 0/2) as WAV; XMA2 decoded with ffmpeg. `--wav` adds 16-bit PCM WAV ([notes](docs/audio.md)) | | Music/radio config | ? Measured. **1,589** audio-config records with exact durations and AWC stream ids; station grouping and content-id lists; no per-track start offsets ([notes](docs/audio_config.md)) | -| PE loader and import shims | ⚠️ Skeleton. Untested against the real executable | +| PE loader and import shims | ⚠️ Runs a stand-in executable end to end (`gta6rt --run`: CRT startup, statics, heap, files, threads, GDK imports through the shims, exit code back). Untested against the real executable | | Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, views and committed resources; barriers, clears, uploads and copies (BC included) run on Vulkan, checked on one GPU. No shader views, pipelines, draws or swapchain yet ([plan](docs/d3d12_vulkan.md)) | | Booting, story mode, anything playable | ❌ No | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 529db697b..04dc0276b 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -59,6 +59,7 @@ if(WIN32) shims/d3d12_xs.cpp shims/d3d12_xs_device.cpp shims/xgameruntime.cpp + shims/process.cpp ) target_compile_definitions(gta6rt PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) target_compile_options(gta6rt PRIVATE /W4 /permissive- /utf-8) @@ -210,6 +211,24 @@ if(BUILD_TESTING) target_link_options(pe_loader_test PRIVATE /OPT:NOREF) target_link_libraries(pe_loader_test PRIVATE gta6rt_d3d12_xs_rootsig psapi) add_dependencies(pe_loader_test tiny_dll tiny_exe) + + # `gta6rt --run` rehearsal: a stand-in game EXE (CRT startup, statics, heap, files, threads) that imports + # xgameruntime.dll from a link-time stub; under --run the shim registry answers those imports instead. + add_library(xgameruntime_stub SHARED test/fixtures/xgameruntime_stub.cpp) + target_compile_definitions(xgameruntime_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + set_target_properties(xgameruntime_stub PROPERTIES + OUTPUT_NAME xgameruntime + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) + add_executable(tiny_game test/fixtures/tiny_game.cpp) + target_link_libraries(tiny_game PRIVATE xgameruntime_stub) + target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_game PRIVATE /W4 /permissive- /utf-8 /EHsc) + set_target_properties(tiny_game PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) add_test(NAME pe_loader COMMAND pe_loader_test "$" "$") endif() @@ -258,6 +277,12 @@ if(BUILD_TESTING) if(WIN32 AND TARGET xgameruntime_test) add_test(NAME xgameruntime COMMAND xgameruntime_test) endif() + if(WIN32 AND TARGET gta6rt AND TARGET tiny_game) + # The stand-in game passes only with its own arguments; with others it exits 1, which --run passes through. + add_test(NAME run_tiny_game COMMAND gta6rt --run $ -- hello 42) + add_test(NAME run_tiny_game_exit_code COMMAND gta6rt --run $ -- wrong args) + set_tests_properties(run_tiny_game_exit_code PROPERTIES WILL_FAIL TRUE) + endif() if(WIN32 AND TARGET root_signature_test) add_test(NAME root_signature COMMAND root_signature_test) endif() diff --git a/runtime/README.md b/runtime/README.md index 0b5bdea00..ae59ca0e3 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -111,6 +111,8 @@ the files in place and never copy or commit game data. ## Current limits +`gta6rt --run [-- args]` runs an executable's entry point inside the runtime (`shims/process.cpp` gives it its +own command line and turns its `exit` into the end of the run); CTest's `run_tiny_game` does that with a stand-in game. The game does not boot yet. The missing executable blocks the import-driven work: the real device entry point, command-list/queue/fence extensions, `PresentX`, and most of the `xgameruntime` surface (an offline shim covers `XGameRuntimeInitialize`, device/console queries, `XTaskQueue` and `XAsync`; see `xgameruntime_test`). The diff --git a/runtime/shims/process.cpp b/runtime/shims/process.cpp new file mode 100644 index 000000000..79fb73de9 --- /dev/null +++ b/runtime/shims/process.cpp @@ -0,0 +1,199 @@ +// Process-level imports of a mapped executable: its command line and its way out. +// +// `gta6rt --run` calls a mapped EXE's entry point inside the gta6rt process. The EXE's CRT startup asks for its +// arguments and finally calls exit(); both go through the EXE's own import table, so they can be answered here: +// - argv/argc and the command line are the game's (set by run_entry), not gta6rt's; +// - exit(), _exit(), quick_exit(), ExitProcess() and abort() from the game end the game's run, not the host: +// the exit code is recorded, the run is signalled as finished and the calling thread ends. atexit handlers +// and static destructors of the game are not run (its CRT shares the host's, whose process-wide atexit table +// also holds gta6rt's own). +// Covered CRTs: the Universal CRT (api-ms-win-crt-runtime-l1-1-0.dll / ucrtbase.dll, what MSVC links) and +// msvcrt.dll (MinGW). Calls made inside host DLLs, not through the game's imports, are not seen here. +#include + +#include +#include +#include +#include +#include +#include + +#include "process.h" +#include "shims.h" + +namespace rt::process { +namespace { + +std::vector g_args; +std::vector g_wargs; +std::vector g_argv; +std::vector g_wargv; +std::string g_cmdline; +std::wstring g_wcmdline; +int g_argc = 0; +char** g_argv_ptr = nullptr; +wchar_t** g_wargv_ptr = nullptr; +char** g_env = nullptr; +wchar_t** g_wenv = nullptr; + +std::atomic g_exited{false}; +std::atomic g_exit_code{0}; +HANDLE g_done = nullptr; + +std::string quote(const std::string& a) { + if (!a.empty() && a.find_first_of(" \t\"") == std::string::npos) return a; + std::string out = "\""; + for (char c : a) { + if (c == '"') out += '\\'; + out += c; + } + return out + "\""; +} + +std::wstring widen(const std::string& s) { + int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, nullptr, 0); + std::wstring w(n > 0 ? n - 1 : 0, L'\0'); + if (n > 1) MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, w.data(), n); + return w; +} + +[[noreturn]] void end_run(int code) { + bool expected = false; + if (g_exited.compare_exchange_strong(expected, true)) { + g_exit_code = code; + if (g_done) SetEvent(g_done); + ExitThread(static_cast(code)); + } + // The run is already over: this is game code running during host shutdown (an atexit handler the game + // registered with the shared CRT calling exit again). Finish the process with the game's exit code; ending + // just this thread here would make the host's last thread, and so the process, exit with `code` instead. + ExitProcess(static_cast(g_exit_code.load())); +} + +// ---- the way out +void __cdecl game_exit(int code) { end_run(code); } +void __stdcall game_exit_process(UINT code) { end_run(static_cast(code)); } +void __cdecl game_abort() { + std::fprintf(stderr, "[rt] process: the game called abort()\n"); + end_run(3); // the CRT's abort exit code +} + +// ---- arguments +int* __cdecl game_p_argc() { return &g_argc; } +char*** __cdecl game_p_argv() { return &g_argv_ptr; } +wchar_t*** __cdecl game_p_wargv() { return &g_wargv_ptr; } +int __cdecl game_configure_argv(int) { return 0; } // already parsed: run_entry set them +LPSTR __stdcall game_get_command_line_a() { return g_cmdline.data(); } +LPWSTR __stdcall game_get_command_line_w() { return g_wcmdline.data(); } +char** __cdecl game_p_acmdln_storage() { + static char* p = nullptr; + p = g_cmdline.data(); + return &p; +} +wchar_t** __cdecl game_p_wcmdln_storage() { + static wchar_t* p = nullptr; + p = g_wcmdline.data(); + return &p; +} + +// msvcrt.dll: int __getmainargs(int* argc, char*** argv, char*** env, int expand, void* startinfo) +int __cdecl game_getmainargs(int* argc, char*** argv, char*** env, int, void*) { + *argc = g_argc; + *argv = g_argv_ptr; + if (env) *env = g_env; + return 0; +} +int __cdecl game_wgetmainargs(int* argc, wchar_t*** argv, wchar_t*** env, int, void*) { + *argc = g_argc; + *argv = g_wargv_ptr; + if (env) *env = g_wenv; + return 0; +} + +struct EntryCall { + void* entry; +}; + +DWORD WINAPI game_thread(void* p) { + auto* call = static_cast(p); + // An EXE entry point (mainCRTStartup and friends) takes the PEB pointer and returns the process exit code. + auto entry = reinterpret_cast(call->entry); + const DWORD code = entry(nullptr); + end_run(static_cast(code)); // returning from the entry point is an exit too +} + +} // namespace + +void set_command_line(const std::string& program, const std::vector& args) { + g_args.clear(); + g_args.push_back(program); + g_args.insert(g_args.end(), args.begin(), args.end()); + g_wargs.clear(); + g_cmdline.clear(); + for (auto& a : g_args) { + g_wargs.push_back(widen(a)); + if (!g_cmdline.empty()) g_cmdline += ' '; + g_cmdline += quote(a); + } + g_wcmdline = widen(g_cmdline); + g_argv.clear(); + g_wargv.clear(); + for (auto& a : g_args) g_argv.push_back(a.data()); + for (auto& a : g_wargs) g_wargv.push_back(a.data()); + g_argv.push_back(nullptr); + g_wargv.push_back(nullptr); + g_argc = static_cast(g_args.size()); + g_argv_ptr = g_argv.data(); + g_wargv_ptr = g_wargv.data(); + g_env = _environ; + g_wenv = _wenviron; +} + +int run_entry(void* entry, size_t stack_bytes) { + g_exited = false; + g_exit_code = 0; + g_done = CreateEventW(nullptr, TRUE, FALSE, nullptr); + EntryCall call{entry}; + HANDLE thread = CreateThread(nullptr, stack_bytes, game_thread, &call, STACK_SIZE_PARAM_IS_A_RESERVATION, nullptr); + if (!thread) { + CloseHandle(g_done); + g_done = nullptr; + return -1; + } + // The run ends when any game thread exits the process (exit/ExitProcess/abort) or the entry point returns. + HANDLE waits[] = {g_done, thread}; + WaitForMultipleObjects(2, waits, FALSE, INFINITE); + CloseHandle(thread); + CloseHandle(g_done); + g_done = nullptr; + return g_exit_code.load(); +} + +} // namespace rt::process + +namespace { +using namespace rt::process; +#define UCRT(dll) \ + {dll, "exit", reinterpret_cast(&game_exit)}, {dll, "_exit", reinterpret_cast(&game_exit)}, \ + {dll, "_Exit", reinterpret_cast(&game_exit)}, {dll, "quick_exit", reinterpret_cast(&game_exit)}, \ + {dll, "abort", reinterpret_cast(&game_abort)}, {dll, "__p___argc", reinterpret_cast(&game_p_argc)}, \ + {dll, "__p___argv", reinterpret_cast(&game_p_argv)}, \ + {dll, "__p___wargv", reinterpret_cast(&game_p_wargv)}, \ + {dll, "_configure_narrow_argv", reinterpret_cast(&game_configure_argv)}, \ + {dll, "_configure_wide_argv", reinterpret_cast(&game_configure_argv)}, \ + {dll, "__p__acmdln", reinterpret_cast(&game_p_acmdln_storage)}, \ + {dll, "__p__wcmdln", reinterpret_cast(&game_p_wcmdln_storage)} +} // namespace + +SHIM_TABLE(process, + UCRT("api-ms-win-crt-runtime-l1-1-0.dll"), + UCRT("ucrtbase.dll"), + {"msvcrt.dll", "exit", reinterpret_cast(&game_exit)}, + {"msvcrt.dll", "_exit", reinterpret_cast(&game_exit)}, + {"msvcrt.dll", "abort", reinterpret_cast(&game_abort)}, + {"msvcrt.dll", "__getmainargs", reinterpret_cast(&game_getmainargs)}, + {"msvcrt.dll", "__wgetmainargs", reinterpret_cast(&game_wgetmainargs)}, + {"kernel32.dll", "ExitProcess", reinterpret_cast(&game_exit_process)}, + {"kernel32.dll", "GetCommandLineA", reinterpret_cast(&game_get_command_line_a)}, + {"kernel32.dll", "GetCommandLineW", reinterpret_cast(&game_get_command_line_w)}, +); diff --git a/runtime/shims/process.h b/runtime/shims/process.h new file mode 100644 index 000000000..62bc828c3 --- /dev/null +++ b/runtime/shims/process.h @@ -0,0 +1,17 @@ +// The game's command line and exit, for `gta6rt --run` (shims/process.cpp). +#pragma once +#include +#include +#include + +namespace rt::process { + +// What the game sees as argv[0..] and GetCommandLine: `program` then `args`, quoted where needed. +void set_command_line(const std::string& program, const std::vector& args); + +// Runs a mapped EXE's entry point on a new thread with `stack_bytes` of reserved stack and returns the game's +// exit code: the entry point's return value, or what it passed to exit/ExitProcess (3 for abort). Returns when +// the first of those happens; other game threads are left running (the host process ends them when it exits). +int run_entry(void* entry, std::size_t stack_bytes = 8u << 20); + +} // namespace rt::process diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 4477c4a69..d79ff97dc 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -6,13 +6,21 @@ // // gta6rt --init [--game-dir DIR] // The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run. +// +// gta6rt --run [--game-dir DIR] [-- game arguments...] +// The same, then the EXE's own TLS callbacks and its entry point, on a game thread. The game's argv and +// command line are plus the arguments after "--"; exit/ExitProcess from the game end the run +// (shims/process.cpp). gta6rt prints the binding report first and returns the game's exit code. #include #include #include #include +#include #include "pe_loader.h" +#include "../shims/process.h" +#include "../shims/shims.h" namespace { @@ -28,7 +36,8 @@ const char* binding_name(rt::Binding b) { int usage() { std::fprintf(stderr, "usage: gta6rt --dry-run [--game-dir DIR]\n" - " gta6rt --init [--game-dir DIR]\n"); + " gta6rt --init [--game-dir DIR]\n" + " gta6rt --run [--game-dir DIR] [-- game arguments...]\n"); return 2; } @@ -36,28 +45,29 @@ int usage() { int wmain(int argc, wchar_t** argv) { std::filesystem::path image, game_dir; - bool dry_run = false, init = false; + bool dry_run = false, init = false, run = false; + std::vector game_args; for (int i = 1; i < argc; ++i) { std::wstring a = argv[i]; + if (a == L"--") { + for (++i; i < argc; ++i) game_args.push_back(std::filesystem::path(argv[i]).string()); + break; + } if (a == L"--dry-run") dry_run = true; else if (a == L"--init") init = true; + else if (a == L"--run") run = true; else if (a == L"--game-dir" && i + 1 < argc) game_dir = argv[++i]; else if (image.empty()) image = a; else return usage(); } if (image.empty()) return usage(); - if (!dry_run && !init) { - std::fprintf(stderr, - "Only --dry-run and --init exist so far: running game code needs the shims listed by " - "--dry-run first.\n"); - return 2; - } + if (!dry_run && !init && !run) return usage(); if (game_dir.empty()) game_dir = image.parent_path(); try { rt::Loader loader(game_dir); - loader.load(image); - if (init) { + rt::Module& main_module = loader.load(image); + if (init || run) { loader.initialise(); std::printf("%zu module(s) initialised\n", loader.modules().size()); } @@ -76,7 +86,23 @@ int wmain(int argc, wchar_t** argv) { } } std::printf("%zu module(s) mapped, %d unimplemented import(s)\n", loader.modules().size(), unimplemented); - return 0; + if (!run) return 0; + if (!main_module.entry_rva) { + std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str()); + return 1; + } + rt::process::set_command_line(image.filename().string(), game_args); + std::printf("running %s\n", main_module.name.c_str()); + std::fflush(stdout); + const int code = rt::process::run_entry(main_module.base + main_module.entry_rva); + std::fflush(stdout); + std::printf("game exited with code %d\n", code); + rt::shims::report_called_unimplemented(); + std::fflush(stdout); + std::fflush(stderr); + // Not `return`: a normal host exit runs the CRT's atexit table, which the game shares with gta6rt (its + // handlers would run against a game that has stopped) and whose last word decides the exit status. + ExitProcess(static_cast(code)); } catch (const std::exception& e) { std::fprintf(stderr, "error: %s\n", e.what()); return 1; diff --git a/runtime/test/fixtures/tiny_game.cpp b/runtime/test/fixtures/tiny_game.cpp new file mode 100644 index 000000000..3cb08937f --- /dev/null +++ b/runtime/test/fixtures/tiny_game.cpp @@ -0,0 +1,106 @@ +// A stand-in game executable for `gta6rt --run`: what a real title does in its first second, run through the +// loader instead of the Windows one. Test code, not game content. Run as +// gta6rt --run tiny_game.exe -- hello 42 +// It checks its arguments, a static initializer, the heap, a file round trip, a second thread, and the +// xgameruntime.dll imports (answered by the shim registry: the stub DLL it links against would fail them), then +// calls exit() with 0 when everything held. thread_local and a C++ exception need static TLS (#93) and unwind +// registration (#176) in the loader; LEONIDA_RUN_TLS=1 / LEONIDA_RUN_EH=1 turn those checks on. +#include + +#include +#include +#include +#include +#include +#include +#include + +extern "C" __declspec(dllimport) HRESULT __stdcall XGameRuntimeInitialize(); +extern "C" __declspec(dllimport) void __stdcall XGameRuntimeUninitialize(); +extern "C" __declspec(dllimport) uint32_t __stdcall XSystemGetDeviceType(); + +namespace { + +int g_failures = 0; + +void check(bool ok, const char* what) { + std::printf("tiny_game: %s %s\n", ok ? "PASS" : "FAIL", what); + if (!ok) ++g_failures; +} + +struct StaticInit { + int value; + StaticInit() : value(1234) {} +}; +StaticInit g_static; + +bool env_on(const char* name) { + char buf[8] = {}; + return GetEnvironmentVariableA(name, buf, sizeof buf) > 0 && buf[0] == '1'; +} + +thread_local int t_counter = 5; + +} // namespace + +int main(int argc, char** argv) { + std::printf("tiny_game: started, argc=%d\n", argc); + check(argc == 3 && std::strcmp(argv[1], "hello") == 0 && std::strcmp(argv[2], "42") == 0, + "argv is the game's command line (\"hello\" \"42\"), not gta6rt's"); + check(std::strstr(GetCommandLineA(), "hello 42") != nullptr, "GetCommandLineA is the game's command line"); + check(g_static.value == 1234, "a static initializer ran before main"); + + std::vector v(1 << 20); + for (size_t i = 0; i < v.size(); ++i) v[i] = int(i); + check(v[123456] == 123456, "a 4 MiB heap allocation works"); + + char tmp[MAX_PATH] = {}; + GetTempPathA(MAX_PATH, tmp); + std::string path = std::string(tmp) + "leonida_tiny_game_" + std::to_string(GetCurrentProcessId()) + ".txt"; + bool file_ok = false; + if (FILE* f = std::fopen(path.c_str(), "wb")) { + std::fputs("leonida", f); + std::fclose(f); + char back[16] = {}; + if (FILE* r = std::fopen(path.c_str(), "rb")) { + std::fread(back, 1, 7, r); + std::fclose(r); + file_ok = std::strcmp(back, "leonida") == 0; + } + std::remove(path.c_str()); + } + check(file_ok, "a file round trip through the CRT works"); + + long long sum = 0; + std::thread worker([&] { for (int i = 1; i <= 1000; ++i) sum += i; }); + worker.join(); + check(sum == 500500, "a second thread ran and joined"); + + check(XGameRuntimeInitialize() == S_OK, "XGameRuntimeInitialize is answered by the gta6rt shim (S_OK)"); + check(XSystemGetDeviceType() == 7, "XSystemGetDeviceType is answered by the gta6rt shim (Series X)"); + XGameRuntimeUninitialize(); + + if (env_on("LEONIDA_RUN_TLS")) { + int seen = -1; + std::thread t([&] { seen = t_counter; t_counter = 9; }); + t.join(); + check(t_counter == 5 && seen == 5, "thread_local starts at its initializer on each thread"); + } else { + std::printf("tiny_game: SKIP thread_local (needs static TLS, #93; LEONIDA_RUN_TLS=1)\n"); + } + if (env_on("LEONIDA_RUN_EH")) { + bool caught = false; + try { + throw std::string("boom"); + } catch (const std::string& e) { + caught = e == "boom"; + } + check(caught, "a C++ exception is thrown and caught inside the image"); + } else { + std::printf("tiny_game: SKIP C++ exception (needs unwind registration, #176; LEONIDA_RUN_EH=1)\n"); + } + + std::printf("tiny_game: %s\n", g_failures ? "FAILED" : "OK"); + std::fflush(stdout); + std::exit(g_failures ? 1 : 0); // through the shimmed exit(): ends the run, not gta6rt +} diff --git a/runtime/test/fixtures/xgameruntime_stub.cpp b/runtime/test/fixtures/xgameruntime_stub.cpp new file mode 100644 index 000000000..749eda8fc --- /dev/null +++ b/runtime/test/fixtures/xgameruntime_stub.cpp @@ -0,0 +1,10 @@ +// Link-time stand-in for the GDK's xgameruntime.dll, so tiny_game.exe gets real imports of these names. Under +// `gta6rt --run` the shim registry answers them first and this DLL never loads; run directly, these failing answers +// are what tiny_game would see. Test code, not game content. +#include + +#include + +extern "C" __declspec(dllexport) HRESULT __stdcall XGameRuntimeInitialize() { return E_FAIL; } +extern "C" __declspec(dllexport) void __stdcall XGameRuntimeUninitialize() {} +extern "C" __declspec(dllexport) uint32_t __stdcall XSystemGetDeviceType() { return 0; } From 307d5e4c1aa618568c0803038ba09dad41549f0d Mon Sep 17 00:00:00 2001 From: Koert Lichtendonk Date: Sat, 21 Nov 2026 23:50:59 +0100 Subject: [PATCH 29/53] Docs: a guide to running the GPU tests Collects what testers in #166 needed to find out themselves: llvm-mc with the AMDGPU target per OS, building the test programs, the two ways to run the suite, wave64 emulation on 32-wide GPUs (set LEONIDA_W64_EMULATE for build.py too), choosing a GPU, and the problems reported so far with their fixes. Linked from CONTRIBUTING.md and the docs index. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 1 + docs/README.md | 1 + docs/testing.md | 101 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+) create mode 100644 docs/testing.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 24f2627e2..d5a6e2a6b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,6 +36,7 @@ asked to rebase or close. GPU test results go in [#166](https://github.com/ItsNo - GPU tests are small hand-written RDNA2 programs in `runtime/test/shaders`. `build.py` there turns them into SPIR-V (it needs `llvm-mc`, so WSL or a Linux container), and `check.py` runs them on your GPU and compares the results. A new test gets its expected values in the comment at its top and a check in `check.py`. + [docs/testing.md](docs/testing.md) has the setup per OS and the problems testers have run into. - Say what you tested and on which GPU in the pull request. - Run the translator tests with `python -m unittest discover -s tests/semantic -v` (see `tests/semantic/README.md`). A new translator rule should come with a small hand-written `.asm` fixture and its expected output words. diff --git a/docs/README.md b/docs/README.md index 3a885352a..8a7da793c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -11,6 +11,7 @@ method, scope and caveats. No game data is included. | [design.md](design.md) | Overall project design, asset status, translator contract and open blockers. | | [related_projects.md](related_projects.md) | Prior art we may read and the licence boundaries on it. | | [rpf.md](rpf.md) | RPF9 archive layout, the carve tools and the unreadable encrypted TOC. | +| [testing.md](testing.md) | Running the GPU tests on your own GPU: setup per OS, wave64 emulation, and known problems. | ## Archives and assets diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 000000000..3953497a3 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,101 @@ +# Running the GPU tests + +The GPU tests are small hand-written RDNA2 programs in `runtime/test/shaders`. They are translated to SPIR-V and run +on your GPU, and the results are compared with what the RDNA2 hardware gives. They need no game files, and every +result helps: post it in [#166](https://github.com/ItsNotRexed/Leonida/issues/166), one comment per GPU and driver. +If your GPU is already covered there, testing an open pull request from the review queue in +[#156](https://github.com/ItsNotRexed/Leonida/issues/156) helps more. + +This page collects the setup steps and the problems testers have run into so far. + +## What you need + +- **Python 3.11+.** `scripts/run_gpu_tests.py` needs at least 3.10. +- **`llvm-mc` with the AMDGPU target** (LLVM 21+). The official LLVM Windows release has no AMDGPU target. On + Windows, use one of: + - `scripts\build_llvm_mc.ps1`, which builds a native `llvm-mc.exe` (needs git and the Visual Studio C++ tools); + - conda-forge's `llvm-tools` package, whose Windows build includes the AMDGPU target; + - `llvm-21` in WSL, with `LLVM_MC` set to the whole command: + `LLVM_MC="wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"`. + + On Linux and macOS, the distribution's or Homebrew's `llvm-mc` on `PATH` is enough. +- **SPIRV-Tools** (`spirv-as`, `spirv-val`): part of the Vulkan SDK, or a distribution package. +- **A C++20 compiler, CMake and the Vulkan headers** to build the test programs: + - Windows: Visual Studio 2022 with "Desktop development with C++" and the Vulkan SDK. + - Linux: CMake 3.24+, GCC or Clang, and the Vulkan headers and loader. The headers should be recent enough + for `VK_KHR_maintenance8`; older ones still build, but skip what needs it. + - macOS: `brew install llvm molten-vk vulkan-headers vulkan-loader spirv-tools vulkan-tools`. The test programs + load MoltenVK directly; set `LEONIDA_VULKAN_LOADER` to use the Vulkan loader instead. + +## Build the test programs + +Windows, from a "Developer PowerShell for VS 2022" or a plain shell: + +```powershell +scripts\build_runtime.ps1 # CMake + Ninja into runtime\build +``` + +If you configure with CMake's Visual Studio generator instead, the programs end up in `runtime\build\Release` (or +`RelWithDebInfo`); pass that folder to `--build` below. + +Linux and macOS: + +```sh +cmake -S runtime -B runtime/build/linux +cmake --build runtime/build/linux --parallel +``` + +On macOS, add `-DVulkan_INCLUDE_DIR=/opt/homebrew/include` to the first command. + +## Run them + +The whole suite, assembled, translated and run in one go: + +```sh +python -I scripts/run_gpu_tests.py --build runtime/build/linux # Windows: the default runtime\build +``` + +`--filter ` runs only matching tests, and `--work ` keeps the intermediate files. + +The two-step form, which `CONTRIBUTING.md` describes: + +```sh +python -I runtime/test/shaders/build.py +python -I runtime/test/shaders/check.py +``` + +## GPUs with 32-wide subgroups (NVIDIA, Intel, Apple) + +The game's shaders are mostly wave64. A GPU that can't run 64-wide compute subgroups skips the wave64 tests +(`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`, `cs_w64x_*`, `ms_w64x_ballot`); that's expected, not a failure. + +To test the wave64 emulation that makes them exact on these GPUs, set `LEONIDA_W64_EMULATE=1`, **for both +`build.py` and `check.py`**: `build.py` translates with emulation only when it's set. If you set it only for +`check.py`, the shaders are checked against the emulated expectations without being emulated, and every wave64 test +fails. + +## Choosing the GPU + +With more than one GPU, pick one through the Vulkan loader, for example +`VK_LOADER_DRIVERS_SELECT=*amd*` or `VK_LOADER_DRIVERS_SELECT=nv-vk*` (or `VK_DRIVER_FILES=`). +`vulkaninfo --summary` shows which devices the loader then sees. + +## Known problems + +| What you see | Cause | What to do | +|---|---|---| +| Windows refuses to start freshly built test programs ("An Application Control policy has blocked this file"), and the runner stops with a traceback | Smart App Control on Windows 11 | Turn Smart App Control off for the run | +| Validation errors without a VUID, or messages from a layer you didn't ask for | An implicit Vulkan layer from other software (Rockstar Social Club, ReShade, MangoHud, an overlay) | Set `VK_LOADER_LAYERS_DISABLE=~implicit~` | +| Every test crashes inside `libnvidia-eglcore.so` | NVIDIA's 535 server driver (Ubuntu 24.04's default) | Use driver 615 or newer | +| `build.py`: 0 translated, reason `.text` | An old `build.py` with LLVM 19 | Update to current `main` | +| `vk_harness` doesn't compile: `VK_KHR_maintenance8` names unknown | Vulkan headers older than the SDK the code was written against | Update to current `main` (the code now builds without it), or use current Khronos Vulkan-Headers; conda-forge's package is too old | +| `ps_bary` and `ps_uniform_branch` fail by about 0.9 | The GPU runs pixel shaders wave64 without fragment barycentrics (GCN3 and RDNA1 on RADV), or an old AMD Windows driver (22.40) | Current `main` skips them on such devices; on Windows, update the driver | +| `gs_tri` and `ms_tri` fail on a Mac | MoltenVK has no geometry stage and no `VK_EXT_mesh_shader` | Current `main` reports them as skipped | +| `run_gpu_tests.py` fails on a `dict \| None` annotation | Python older than 3.10 | Use Python 3.11+ | + +## Posting your result + +Use the template at the top of [#166](https://github.com/ItsNotRexed/Leonida/issues/166): GPU, driver, subgroup +range, OS, the commit you built, the tool versions and the counts each script printed. Post counts and pass/fail +lines only, never shaders or logs from the game. A failure that isn't in the table above gets its own issue, linked +from your entry. From 2fde230ea2b58df24b9f5c87bf741d30536cf75a Mon Sep 17 00:00:00 2001 From: DiazE117 <230450176+DiazE117@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:32:51 -0600 Subject: [PATCH 30/53] tests: run wave64 cross-half lane ops across 64 lanes of the translated SPIR-V spirv_mini_interp gains run_workgroup: invocations run in lockstep and meet at OpGroupNonUniformShuffle (Subgroup scope), with an explicit subgroup size. A shuffle from a lane outside the subgroup raises UndefinedResult, or wraps mod the subgroup size on request (the issue #94 symptom, a model and not the spec). A shift by at least the bit width is now an undefined value that only raises when used: v_mbcnt computes 1 << lane for lanes >= 32 and selects it away, which is valid SPIR-V. test_wave64_cross_half translates cs_w64x_readlane, cs_w64x_writelane and cs_w64x_bpermute (no --wave64-emulate): - one 64-wide subgroup: all 24 words equal check.py's GPU values; - two 32-wide subgroups: bpermute and the writelane writes stay exact, a cross-half readlane is undefined; the wrap model gives the words a 32-wide GPU without emulation is predicted to show; - SPIR-V sabotages (readlane lane & 31, bpermute without its half base) must change the 64-wide result. CPU only (Windows 11, Python 3.11.9): 382 semantic tests pass. Not yet measured on a GPU. AI-assisted. Co-Authored-By: Claude Opus 5.5 --- tests/semantic/README.md | 13 +- .../fixtures/disasm/cs_w64x_bpermute.s | 60 ++++++ .../fixtures/disasm/cs_w64x_readlane.s | 51 ++++++ .../fixtures/disasm/cs_w64x_writelane.s | 56 ++++++ tests/semantic/regen_fixtures.py | 3 +- tests/semantic/spirv_mini_interp.py | 115 +++++++++++- tests/semantic/test_wave64_cross_half.py | 173 ++++++++++++++++++ 7 files changed, 464 insertions(+), 7 deletions(-) create mode 100644 tests/semantic/fixtures/disasm/cs_w64x_bpermute.s create mode 100644 tests/semantic/fixtures/disasm/cs_w64x_readlane.s create mode 100644 tests/semantic/fixtures/disasm/cs_w64x_writelane.s create mode 100644 tests/semantic/test_wave64_cross_half.py diff --git a/tests/semantic/README.md b/tests/semantic/README.md index bf8b9a81e..de16d264c 100644 --- a/tests/semantic/README.md +++ b/tests/semantic/README.md @@ -22,6 +22,14 @@ What they check (`tools/rdna2spirv.py`, pixel shaders plus one compute shader): - `test_interp.py` tests the interpreter against the SPIR-V / GLSL.std.450 definitions. The interpreter raises `UnsupportedConstruct` for anything it does not model instead of approximating it. It can seed Input variables, PushConstant words and a flat physical-address memory map for the tests above. +- `test_wave64_cross_half.py` translates the GPU tests `cs_w64x_readlane`, `cs_w64x_writelane` and + `cs_w64x_bpermute` (no `--wave64-emulate`) and runs all 64 lanes in lockstep with + `spirv_mini_interp.run_workgroup`. On one 64-wide subgroup the 24 words must equal the GPU check's values + (`runtime/test/shaders/check.py`). On two 32-wide subgroups (NVIDIA without emulation) `ds_bpermute` stays + exact, `v_writelane` writes stay exact, and a `v_readlane` from the other half is a shuffle from lane >= 32, + undefined in SPIR-V (`UndefinedResult`); a "lane mod 32" model of issue #94 gives the words a 32-wide GPU is + predicted to show. Two SPIR-V sabotages (readlane lane & 31, bpermute without its half base) must change the + 64-wide result. - `test_negative_controls.py` sabotages the translated SPIR-V text and requires the result to change. - `test_mutations.py` sabotages a temporary copy of `tools/` (13 regressions across SDWA, min3/max3, `v_bfe_i32`, `v_pk_fma_f16`, `v_fma_f16 op_sel`, `v_subrev_co_ci_u32`, `v_cmpx_eq_u64`, `v_mul_i32_i24`, `v_ffbh_i32`, @@ -30,9 +38,10 @@ What they check (`tools/rdna2spirv.py`, pixel shaders plus one compute shader): - `test_fixtures.py` checks `tests/semantic/fixtures/disasm/*.s` equals what `regen_fixtures.py` makes from `runtime/test/shaders/*.asm` (`python tests/semantic/regen_fixtures.py` rewrites them). -Limits: single lane, forward-only structured control flow (the fragment-exit discard test and the compute +Limits: single lane (or lanes in lockstep that meet only at `OpGroupNonUniformShuffle`), forward-only structured control flow (the fragment-exit discard test and the compute dynamic-bounds merge; no backward branches, loops, calls or switches), no texture access. PushConstant words, -Input variables and a flat physical-address `{address: word}` map can be supplied per run. Values that pass +Input variables and a flat physical-address `{address: word}` map can be supplied per run. A shift by at least the bit width is an undefined value: arithmetic on it stays +undefined and any other use (store, branch or select condition, shuffle, output) raises. Values that pass through a float op lose NaN payloads (Python floats), so expected output words avoid NaN bit patterns. `Fma` is computed in double precision then rounded to binary32 (exact for the f16-derived operands used). The `.asm` sources are written for `llvm-mc -mcpu=gfx1013`; these tests do not assemble them, so assembler syntax is not diff --git a/tests/semantic/fixtures/disasm/cs_w64x_bpermute.s b/tests/semantic/fixtures/disasm/cs_w64x_bpermute.s new file mode 100644 index 000000000..808a80645 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_w64x_bpermute.s @@ -0,0 +1,60 @@ +; cs_w64x_bpermute test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w64x_bpermute.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_mad_u32_u24 v2, v1, 7, 1 + v_add_nc_u32_e32 v3, 5, v1 + v_lshlrev_b32_e32 v3, 2, v3 + ds_bpermute_b32 v4, v3, v2 + v_and_b32_e32 v5, 31, v1 + v_sub_nc_u32_e32 v5, 63, v5 + v_lshlrev_b32_e32 v5, 2, v5 + ds_bpermute_b32 v5, v5, v2 + s_waitcnt lgkmcnt(0) + v_mov_b32_e32 v6, 99 + v_add_nc_u32_e32 v7, 14, v1 + v_lshlrev_b32_e32 v7, 2, v7 + s_mov_b32 exec_lo, -1 + s_mov_b32 exec_hi, 0xffff0000 + ds_bpermute_b32 v6, v7, v2 + s_waitcnt lgkmcnt(0) + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 0 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 40, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 4 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 8 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, v5 + v_mov_b32_e32 v21, 12 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 33, v1 + v_mov_b32_e32 v20, v5 + v_mov_b32_e32 v21, 16 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_mov_b32_e32 v20, v5 + v_mov_b32_e32 v21, 20 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 50, v1 + v_mov_b32_e32 v20, v6 + v_mov_b32_e32 v21, 24 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 49, v1 + v_mov_b32_e32 v20, v6 + v_mov_b32_e32 v21, 28 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_w64x_readlane.s b/tests/semantic/fixtures/disasm/cs_w64x_readlane.s new file mode 100644 index 000000000..bf27ecde5 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_w64x_readlane.s @@ -0,0 +1,51 @@ +; cs_w64x_readlane test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w64x_readlane.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_mad_u32_u24 v2, v1, 3, 1 + v_readlane_b32 s6, v2, 40 + v_readlane_b32 s7, v2, 5 + v_readlane_b32 s8, v2, 32 + s_mov_b32 s10, 97 + v_readlane_b32 s9, v2, s10 + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, s6 + v_mov_b32_e32 v21, 0 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 33, v1 + v_mov_b32_e32 v20, s6 + v_mov_b32_e32 v21, 4 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_mov_b32_e32 v20, s7 + v_mov_b32_e32 v21, 8 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, s8 + v_mov_b32_e32 v21, 12 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 45, v1 + v_mov_b32_e32 v20, s7 + v_mov_b32_e32 v21, 16 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 7, v1 + v_mov_b32_e32 v20, s9 + v_mov_b32_e32 v21, 20 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 60, v1 + v_mov_b32_e32 v20, s9 + v_mov_b32_e32 v21, 24 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_readlane_b32 s11, v2, 40 + v_mov_b32_e32 v20, s11 + v_mov_b32_e32 v21, 28 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_w64x_writelane.s b/tests/semantic/fixtures/disasm/cs_w64x_writelane.s new file mode 100644 index 000000000..fa4eb732f --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_w64x_writelane.s @@ -0,0 +1,56 @@ +; cs_w64x_writelane test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w64x_writelane.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_mov_b32_e32 v10, 0 + s_mov_b32 s6, 0x1234 + s_mov_b32 s7, 77 + s_mov_b32 s8, 99 + s_mov_b32 s11, 0xabc + s_mov_b32 s9, 96 + v_writelane_b32 v10, s6, 40 + v_writelane_b32 v10, s7, 3 + v_writelane_b32 v10, s8, 63 + v_writelane_b32 v10, s11, s9 + v_readlane_b32 s12, v10, 40 + v_readlane_b32 s13, v10, 63 + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 40, v1 + v_mov_b32_e32 v20, v10 + v_mov_b32_e32 v21, 0 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 3, v1 + v_mov_b32_e32 v20, v10 + v_mov_b32_e32 v21, 4 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_mov_b32_e32 v20, v10 + v_mov_b32_e32 v21, 8 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 32, v1 + v_mov_b32_e32 v20, v10 + v_mov_b32_e32 v21, 12 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 39, v1 + v_mov_b32_e32 v20, v10 + v_mov_b32_e32 v21, 16 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 41, v1 + v_mov_b32_e32 v20, v10 + v_mov_b32_e32 v21, 20 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, s12 + v_mov_b32_e32 v21, 24 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 8, v1 + v_mov_b32_e32 v20, s13 + v_mov_b32_e32 v21, 28 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/regen_fixtures.py b/tests/semantic/regen_fixtures.py index 22f859766..f9061258f 100644 --- a/tests/semantic/regen_fixtures.py +++ b/tests/semantic/regen_fixtures.py @@ -17,7 +17,8 @@ ROOT = os.path.dirname(os.path.dirname(HERE)) ASM_DIR = os.path.join(ROOT, "runtime", "test", "shaders") FIXTURE_DIR = os.path.join(HERE, "fixtures", "disasm") SHADERS = ("ps_sdwa", "ps_ops", "ps_ops2", "ps_ops3", "ps_ops4", "ps_ops5", "ps_ops6", "ps_ops7", "ps_ops8", - "ps_legacy_mul", "ps_vcc_x2", "ps_flat", "cs_bounds", "cs_fmt_1010102") + "ps_legacy_mul", "ps_vcc_x2", "ps_flat", "cs_bounds", "cs_fmt_1010102", + "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_bpermute") def render(name): diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index 85a8a485a..2cde0ea5a 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py @@ -7,7 +7,8 @@ Design rules (see tests/semantic/README.md): * Strict: any opcode, extended instruction, type or storage class not listed below raises UnsupportedConstruct. Nothing is skipped or approximated silently, so a translator change that starts emitting something new makes the test error out instead of passing. - * One invocation (one lane). Control flow is the forward-only discard test and the forward merge/dynamic-bounds + * One invocation (one lane), or with run_workgroup several in lockstep, which meet only at + OpGroupNonUniformShuffle (the one subgroup operation modelled). Control flow is the forward-only discard test and the forward merge/dynamic-bounds branches the translator emits: OpBranch / OpBranchConditional to a later label plus OpPhi at the merge block. Backward branches, loops, calls and switches are rejected. Function/Output/Input variables live in Python boxes; PushConstant reads can be seeded with a word list; physical-storage-buffer loads/stores use a flat @@ -40,6 +41,26 @@ _IGNORED = frozenset({ _LINE = re.compile(r"^(?:(%\S+)\s*=\s*)?(Op\w+)\s*(.*)$") +class _Undef: + """An undefined value (SPIR-V: a shift by at least the bit width). Pure arithmetic on it gives another + undefined value; any other use (a store, a branch or select condition, a subgroup operation, an output) + raises, so a result that does not depend on it, such as the unselected side of OpSelect, is still exact.""" + + def __repr__(self): + return "" + + +UNDEF = _Undef() + +# Operations whose result is undefined when an operand is (they have no side effect and no control). +_PURE = frozenset({ + "OpBitwiseAnd", "OpBitwiseOr", "OpBitwiseXor", "OpNot", "OpShiftLeftLogical", "OpShiftRightLogical", + "OpShiftRightArithmetic", "OpIAdd", "OpISub", "OpIMul", "OpUConvert", "OpBitCount", "OpIEqual", + "OpINotEqual", "OpSLessThan", "OpULessThan", "OpUGreaterThanEqual", "OpCopyObject", "OpBitcast", + "OpBitFieldUExtract", "OpBitFieldSExtract", "OpBitFieldInsert", +}) + + def f32(x): """Round a Python float to binary32 (overflow to infinity).""" try: @@ -124,7 +145,79 @@ def run_fragment(text, inputs=None, push_constants=None, memory=None): PhysicalStorageBuffer loads and stores. Returns {output_variable_name: tuple_of_32bit_words}. Float outputs are returned as their bit patterns. + A module with a subgroup operation is rejected here; see run_workgroup. """ + gen = _invocation(text, inputs, push_constants, memory) + try: + req = next(gen) + except StopIteration as done: + return done.value + gen.close() + raise UnsupportedConstruct(f"{req[0]} in a single invocation (use run_workgroup)") + + +class UndefinedResult(Exception): + """A subgroup operation whose result SPIR-V leaves undefined (for example a shuffle from a lane that is not in + the subgroup). Raised instead of inventing a value.""" + + +def run_workgroup(text, invocations, subgroup_size, inputs_for=None, push_constants=None, memory=None, + out_of_range="raise"): + """Execute `invocations` invocations of `text` in lockstep and return the shared `memory`. + + Invocation i is subgroup i // subgroup_size, lane i % subgroup_size (a 1-D workgroup split into subgroups in + invocation order). `inputs_for(i)` gives invocation i's Input values (see run_fragment); push constants and + the physical-address memory are shared. Every invocation must reach every subgroup operation, in the same + order (the translator emits them in uniform control flow and models EXEC with a variable, so a lane that is + off in EXEC still executes them). + + OpGroupNonUniformShuffle (Subgroup scope) returns the value of lane Id of the caller's own subgroup. An Id at + or past `subgroup_size` is undefined in SPIR-V: `out_of_range="raise"` raises UndefinedResult; + `out_of_range="wrap"` takes lane Id mod subgroup_size instead, a model of one observed driver behaviour + and not of the specification (Leonida issue #94: on a 32-wide NVIDIA subgroup lane 40 read lane 8). + """ + if out_of_range not in ("raise", "wrap"): + raise ValueError(f"out_of_range: {out_of_range!r}") + if invocations % subgroup_size: + raise UnsupportedConstruct("a partial subgroup") + memory = {} if memory is None else memory + gens = [_invocation(text, (inputs_for(i) if inputs_for else None), push_constants, memory) + for i in range(invocations)] + pending = [None] * invocations + live = set() + for i, g in enumerate(gens): + try: + pending[i] = next(g) + live.add(i) + except StopIteration: + pass + while live: + if len(live) != invocations or len({pending[i][1] for i in live}) != 1: + raise UnsupportedConstruct("subgroup operation not reached by every invocation at the same point") + results = [] + for i in range(invocations): + kind, _, _value, ident = pending[i] + if kind != "OpGroupNonUniformShuffle": + raise UnsupportedConstruct(kind) + if not 0 <= ident < subgroup_size: + if out_of_range == "raise": + raise UndefinedResult(f"invocation {i}: shuffle from lane {ident} of a {subgroup_size}-wide " + f"subgroup") + ident %= subgroup_size + src = (i // subgroup_size) * subgroup_size + ident + results.append(pending[src][2]) + for i in range(invocations): + try: + pending[i] = gens[i].send(results[i]) + except StopIteration: + live.discard(i) + pending[i] = None + return memory + + +def _invocation(text, inputs, push_constants, memory): + """One invocation as a generator. It yields (opcode, instruction index, value, id) at each subgroup operation + and expects that operation's result back; it returns run_fragment's result.""" inputs = inputs or {} push_constants = list(push_constants or []) memory = {} if memory is None else memory @@ -297,6 +390,12 @@ def run_fragment(text, inputs=None, push_constants=None, memory=None): raise UnsupportedConstruct("OpPhi with an unknown predecessor") values[res] = val(incoming[0]) continue + if op in _PURE and any(values.get(x) is UNDEF for x in a[1:]): + values[res] = UNDEF + continue + used = a[1:2] if op == "OpSelect" else a # OpSelect may pass the chosen undefined value on + if any(values.get(x) is UNDEF for x in used): + raise UnsupportedConstruct(f"{op} uses an undefined value: {line}") if op == "OpVariable": cls, pointee = ptr_types[a[0]] if cls != "Function": @@ -386,17 +485,20 @@ def run_fragment(text, inputs=None, push_constants=None, memory=None): elif op == "OpShiftLeftLogical": bits = types.bits(a[0]) if val(a[2]) >= bits: - raise UnsupportedConstruct(f"shift amount >= {bits} (undefined in SPIR-V)") + values[res] = UNDEF # undefined in SPIR-V; raises only if it is used + continue values[res] = (val(a[1]) << val(a[2])) & wmask(a[0]) elif op == "OpShiftRightLogical": bits = types.bits(a[0]) if val(a[2]) >= bits: - raise UnsupportedConstruct(f"shift amount >= {bits} (undefined in SPIR-V)") + values[res] = UNDEF # undefined in SPIR-V; raises only if it is used + continue values[res] = (val(a[1]) & wmask(a[0])) >> val(a[2]) elif op == "OpShiftRightArithmetic": bits = types.bits(a[0]) if val(a[2]) >= bits: - raise UnsupportedConstruct(f"shift amount >= {bits} (undefined in SPIR-V)") + values[res] = UNDEF # undefined in SPIR-V; raises only if it is used + continue values[res] = (signed(val(a[1]), bits) >> val(a[2])) & wmask(a[0]) elif op == "OpIAdd": values[res] = (val(a[1]) + val(a[2])) & wmask(a[0]) @@ -445,6 +547,11 @@ def run_fragment(text, inputs=None, push_constants=None, memory=None): values[res] = val(a[1]) > val(a[2]) elif op == "OpUGreaterThanEqual": values[res] = val(a[1]) >= val(a[2]) + elif op == "OpGroupNonUniformShuffle": + # OpGroupNonUniformShuffle ; the scope must be Subgroup (3). + if types.t[a[0]][0] != "int" or val(a[1]) != 3: + raise UnsupportedConstruct("OpGroupNonUniformShuffle other than a Subgroup-scope integer") + values[res] = yield (op, pc - 1, val(a[2]), val(a[3])) elif op == "OpLogicalAnd": x, y = val(a[1]), val(a[2]) if not (isinstance(x, bool) and isinstance(y, bool)): diff --git a/tests/semantic/test_wave64_cross_half.py b/tests/semantic/test_wave64_cross_half.py new file mode 100644 index 000000000..055d84541 --- /dev/null +++ b/tests/semantic/test_wave64_cross_half.py @@ -0,0 +1,173 @@ +"""Wave64 cross-half lane operations, executed across all 64 lanes of the translated SPIR-V. + +The inputs are the GPU tests runtime/test/shaders/cs_w64x_readlane, cs_w64x_writelane and cs_w64x_bpermute +(hand-written, no game data; fixtures from regen_fixtures.py). Each is translated without --wave64-emulate and run +by spirv_mini_interp.run_workgroup as one 64-thread workgroup, in two layouts: + +* one 64-wide subgroup (AMD with requiredSubgroupSize = 64). The eight output words must equal the values the + GPU check expects (runtime/test/shaders/check.py W64X_DUMPS, scripts/run_gpu_tests.py), derived in each .asm + header from the RDNA2 ISA: v_readlane/v_writelane select lane S1 % 64 and ignore EXEC; ds_bpermute_b32 works + on each 32-lane half as an independent wave32 (ISA 10.4.4) and reads 0 from a lane that is off in EXEC. +* two 32-wide subgroups, invocations 0-31 and 32-63 (NVIDIA, e.g. an RTX 4070 Super, without emulation). This is + the documented gap in docs/design.md ("Wave64 handling": cross-lane ops between the two halves stay approximate + on 32-wide subgroups). The tests pin which results stay exact there and which do not: + - ds_bpermute_b32 never crosses halves, so all eight words stay exact; + - v_writelane_b32 writes the right lane in both halves (the wave lane comes from LocalInvocationIndex); + - a v_readlane_b32 from the other half shuffles from lane >= 32 of a 32-wide subgroup, which SPIR-V leaves + undefined. Strictly that is UndefinedResult. Under the wrap model (lane Id mod 32, the symptom in issue + #94, an observation and not the specification) the expected words below are what a 32-wide GPU without + --wave64-emulate would show; they are a prediction to measure, not a requirement. + +Limits: --wave64-emulate output uses Workgroup memory and a round loop, which the interpreter rejects, so the +emulated path is covered only by the GPU tests. The subgroup layout (invocation i in subgroup i // 32) is the +usual one for a 1-D workgroup but Vulkan does not guarantee it. +""" +import re +import struct +import unittest + +import support +import spirv_mini_interp as si + +# 4 user SGPRs (the output V#), workgroup id in s4, 512 bytes of LDS, 64x1x1 threads: build.py's default header. +FSSM = bytearray(0x148) +struct.pack_into("<4I", FSSM, 0x138, 0x8088, 64, 1, 1) +FSSM = bytes(FSSM) +# V# in s[0:3]: base 0, stride 0, num_records 0x1000 bytes. out[k] is the dword at byte 4k. +VSHARP = [0, 0, 0x1000, 0] + +# Expected on a 64-wide subgroup: the GPU check's values (check.py W64X_DUMPS). +GPU_EXPECTED = { + "cs_w64x_readlane": [121, 121, 16, 97, 16, 100, 100, 121], + "cs_w64x_writelane": [4660, 77, 99, 2748, 0, 0, 4660, 99], + "cs_w64x_bpermute": [36, 316, 253, 218, 435, 225, 0, 442], +} + +# Two 32-wide subgroups, wrap model. readlane: v2 = 3 * lane + 1 and each subgroup reads lane (S1 % 64) % 32 of +# its own half. The low half reads lane 8 for lane 40 (25), lane 0 for 32 (1) and lane 1 for 33 (4); the upper +# half reads lane 32 + 5 = 37 for lane 5 (112). Words stored by lanes of the half the source lane is in stay right: +# out[0] lane 0: s6 = v2[8] = 25 out[1] lane 33: s6 = v2[40] = 121 out[2] lane 63: s7 = v2[37] = 112 +# out[3] lane 0: s8 = v2[0] = 1 out[4] lane 45: s7 = v2[37] = 112 out[5] lane 7: s9 = v2[1] = 4 +# out[6] lane 60: s9 = v2[33] = 100 out[7] lane 63: v2[40] = 121 +# writelane: the writes are exact, the two readlanes from lanes 0 and 8 read lanes 8 and 31 of the low half, +# which nobody wrote (0). +WRAP32_EXPECTED = { + "cs_w64x_readlane": [25, 121, 112, 1, 112, 4, 100, 121], + "cs_w64x_writelane": [4660, 77, 99, 2748, 0, 0, 0, 0], + "cs_w64x_bpermute": GPU_EXPECTED["cs_w64x_bpermute"], +} + + +def translate(name): + return support.translate_fixture(name, fssm=FSSM) + + +def run(spv, subgroup_size, out_of_range="raise"): + """Run one 64-thread workgroup; return out[0..7] and check nothing was written past them.""" + memory = si.run_workgroup( + spv, 64, subgroup_size, + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size}, + push_constants=VSHARP + [0] * 28, memory={}, out_of_range=out_of_range) + stray = sorted(a for a in memory if not 0 <= a < 32 or a % 4) + if stray: + raise AssertionError(f"stores outside out[0..7]: {stray}") + return [memory.get(4 * k) for k in range(8)] + + +class Wave64OnSubgroup64(unittest.TestCase): + """Exact on a 64-wide subgroup: the values the GPU check expects.""" + + def test_each_shader(self): + for name, want in GPU_EXPECTED.items(): + with self.subTest(shader=name): + self.assertEqual(run(translate(name), 64), want) + + +class Wave64OnTwoSubgroups32(unittest.TestCase): + """The same modules on two 32-wide subgroups, no --wave64-emulate.""" + + def test_bpermute_stays_exact(self): + spv = translate("cs_w64x_bpermute") + self.assertEqual(run(spv, 32), GPU_EXPECTED["cs_w64x_bpermute"]) + + def test_cross_half_readlane_is_undefined(self): + for name in ("cs_w64x_readlane", "cs_w64x_writelane"): + with self.subTest(shader=name): + with self.assertRaisesRegex(si.UndefinedResult, r"lane 40 of a 32-wide subgroup"): + run(translate(name), 32) + + def test_wrap_model_prediction(self): + for name, want in WRAP32_EXPECTED.items(): + with self.subTest(shader=name): + got = run(translate(name), 32, out_of_range="wrap") + self.assertEqual(got, want) + wrong = [k for k in range(8) if got[k] != GPU_EXPECTED[name][k]] + self.assertEqual(bool(wrong), name != "cs_w64x_bpermute", f"{name}: words {wrong} differ") + + def test_writelane_writes_are_exact(self): + # out[0..5] are the written lanes and their untouched neighbours; only the readlanes (out[6..7]) cross. + got = run(translate("cs_w64x_writelane"), 32, out_of_range="wrap") + self.assertEqual(got[:6], GPU_EXPECTED["cs_w64x_writelane"][:6]) + + +class NegativeControls(unittest.TestCase): + """Sabotage the translated SPIR-V the way a translator regression would; the 64-wide result must change.""" + + def sabotage(self, name, pattern, repl, count): + spv = translate(name) + bad, n = re.subn(pattern, repl, spv) + self.assertEqual(n, count, f"anchor {pattern!r} matched {n} times in {name}") + got = run(bad, 64) + self.assertNotEqual(got, GPU_EXPECTED[name]) + return got + + def test_readlane_lane_select_mod_32(self): + # v_readlane lane = S1 & 31 instead of & 63 (the issue #94 symptom, moved into the translator). + got = self.sabotage("cs_w64x_readlane", + r"(OpBitwiseAnd %uint \S+ )%c3f(\n\s*%\w+ = OpGroupNonUniformShuffle)", r"\1%c1f\2", 5) + self.assertEqual(got[0], 25) # lane 40 -> lane 8 + + def test_bpermute_upper_half_reads_low_half(self): + # The half base from the subgroup lane dropped (the bug fixed on 2026-11-21, see docs/design.md "LDS"). + got = self.sabotage("cs_w64x_bpermute", + r"(= OpLoad %uint %sg_lane\n\s*%\w+ = OpBitwiseAnd %uint %\w+ )%c20", r"\1%c0", 3) + self.assertEqual(got[1], 7 * 13 + 1) # lane 40 reads lane 13 of the low half instead of lane 45 + + +_SHIFT_MODULE = """ +%uint = OpTypeInt 32 0 +%bool = OpTypeBool +%c1 = OpConstant %uint 1 +%c7 = OpConstant %uint 7 +%c40 = OpConstant %uint 40 +%true = OpConstantTrue %bool +%false = OpConstantFalse %bool +%_ptr_Output_uint = OpTypePointer Output %uint +%out = OpVariable %_ptr_Output_uint Output +%main = OpFunction +%entry = OpLabel +%big = OpShiftLeftLogical %uint %c1 %c40 +%dec = OpISub %uint %big %c1 +%pick = OpSelect %uint {cond} %c7 %dec +OpStore %out %pick +OpReturn +OpFunctionEnd +""" + + +class InterpreterContract(unittest.TestCase): + def test_undefined_shift_only_fails_when_used(self): + # 1 << 40 on a 32-bit type is undefined; the translator's v_mbcnt computes it for lanes >= 32 and selects + # it away. The unselected side is fine, storing it is not. + self.assertEqual(si.run_fragment(_SHIFT_MODULE.format(cond="%true")), {"%out": (7,)}) + with self.assertRaisesRegex(si.UnsupportedConstruct, "undefined value"): + si.run_fragment(_SHIFT_MODULE.format(cond="%false")) + + def test_single_invocation_rejects_a_shuffle(self): + with self.assertRaisesRegex(si.UnsupportedConstruct, "run_workgroup"): + si.run_fragment(translate("cs_w64x_readlane"), + inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, push_constants=VSHARP) + + +if __name__ == "__main__": + unittest.main() From 87c56d2d8a08fcb1ae374332e71317fc261c224f Mon Sep 17 00:00:00 2001 From: DiazE117 <230450176+DiazE117@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:48:28 -0600 Subject: [PATCH 31/53] tests: record the RTX 4070 SUPER measurement of the wave64 wrap model Without --wave64-emulate, vk_compute_test on cs_w64x_readlane, _writelane and _bpermute (NVIDIA GeForce RTX 4070 SUPER, subgroup 32, driver 610.88, Vulkan SDK 1.4.363.0, llvm-mc 21.1.8 in WSL) wrote exactly WRAP32_EXPECTED: 24 of 24 words. With LEONIDA_W64_EMULATE=1, scripts/run_gpu_tests.py passes 42/44 on the same GPU (cs_wavemask and ps_vcc_x2 skip). Co-Authored-By: Claude Opus 5.5 --- tests/semantic/README.md | 4 ++-- tests/semantic/test_wave64_cross_half.py | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/semantic/README.md b/tests/semantic/README.md index de16d264c..1e691281f 100644 --- a/tests/semantic/README.md +++ b/tests/semantic/README.md @@ -27,8 +27,8 @@ What they check (`tools/rdna2spirv.py`, pixel shaders plus one compute shader): `spirv_mini_interp.run_workgroup`. On one 64-wide subgroup the 24 words must equal the GPU check's values (`runtime/test/shaders/check.py`). On two 32-wide subgroups (NVIDIA without emulation) `ds_bpermute` stays exact, `v_writelane` writes stay exact, and a `v_readlane` from the other half is a shuffle from lane >= 32, - undefined in SPIR-V (`UndefinedResult`); a "lane mod 32" model of issue #94 gives the words a 32-wide GPU is - predicted to show. Two SPIR-V sabotages (readlane lane & 31, bpermute without its half base) must change the + undefined in SPIR-V (`UndefinedResult`); a "lane mod 32" model of issue #94 gives the words a 32-wide GPU + shows (all 24 matched on an RTX 4070 SUPER, driver 610.88, without `--wave64-emulate`). Two SPIR-V sabotages (readlane lane & 31, bpermute without its half base) must change the 64-wide result. - `test_negative_controls.py` sabotages the translated SPIR-V text and requires the result to change. - `test_mutations.py` sabotages a temporary copy of `tools/` (13 regressions across SDWA, min3/max3, `v_bfe_i32`, diff --git a/tests/semantic/test_wave64_cross_half.py b/tests/semantic/test_wave64_cross_half.py index 055d84541..903fc1545 100644 --- a/tests/semantic/test_wave64_cross_half.py +++ b/tests/semantic/test_wave64_cross_half.py @@ -16,7 +16,9 @@ by spirv_mini_interp.run_workgroup as one 64-thread workgroup, in two layouts: - a v_readlane_b32 from the other half shuffles from lane >= 32 of a 32-wide subgroup, which SPIR-V leaves undefined. Strictly that is UndefinedResult. Under the wrap model (lane Id mod 32, the symptom in issue #94, an observation and not the specification) the expected words below are what a 32-wide GPU without - --wave64-emulate would show; they are a prediction to measure, not a requirement. + --wave64-emulate shows. Measured: NVIDIA GeForce RTX 4070 SUPER (subgroup 32), driver 610.88, Vulkan SDK + 1.4.363.0, `vk_compute_test .spv 1 dump` on the non-emulated build of run_gpu_tests.py: all 24 + words equal WRAP32_EXPECTED. That is one driver's behaviour, not a requirement. Limits: --wave64-emulate output uses Workgroup memory and a round loop, which the interpreter rejects, so the emulated path is covered only by the GPU tests. The subgroup layout (invocation i in subgroup i // 32) is the From 55f8387f9832570b637dd084abba717894256394 Mon Sep 17 00:00:00 2001 From: DiazE117 <230450176+DiazE117@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:00:29 -0600 Subject: [PATCH 32/53] tests: model OpGroupNonUniformBallot for the wave64 ds_bpermute guard 21cef25 keeps a wave64 ds_bpermute result only where a ballot of the running invocations has the source lane. run_workgroup now answers OpGroupNonUniformBallot per subgroup, and OpGroupNonUniformBallotBitExtract is evaluated per lane. Rebased on 3fae38a: 395 semantic tests pass. RTX 4070 SUPER, driver 610.88: LEONIDA_W64_EMULATE=1 run_gpu_tests.py 45/47 (cs_wavemask and ps_vcc_x2 skip); without emulation the three cs_w64x dumps still match the wrap model, 24/24 words. Co-Authored-By: Claude Opus 5.5 --- tests/semantic/README.md | 2 +- tests/semantic/spirv_mini_interp.py | 23 ++++++++++++++++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/tests/semantic/README.md b/tests/semantic/README.md index 1e691281f..6668b4d13 100644 --- a/tests/semantic/README.md +++ b/tests/semantic/README.md @@ -38,7 +38,7 @@ What they check (`tools/rdna2spirv.py`, pixel shaders plus one compute shader): - `test_fixtures.py` checks `tests/semantic/fixtures/disasm/*.s` equals what `regen_fixtures.py` makes from `runtime/test/shaders/*.asm` (`python tests/semantic/regen_fixtures.py` rewrites them). -Limits: single lane (or lanes in lockstep that meet only at `OpGroupNonUniformShuffle`), forward-only structured control flow (the fragment-exit discard test and the compute +Limits: single lane (or lanes in lockstep that meet only at `OpGroupNonUniformShuffle` and `OpGroupNonUniformBallot`), forward-only structured control flow (the fragment-exit discard test and the compute dynamic-bounds merge; no backward branches, loops, calls or switches), no texture access. PushConstant words, Input variables and a flat physical-address `{address: word}` map can be supplied per run. A shift by at least the bit width is an undefined value: arithmetic on it stays undefined and any other use (store, branch or select condition, shuffle, output) raises. Values that pass diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index 2cde0ea5a..9ae409ca4 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py @@ -8,7 +8,8 @@ Design rules (see tests/semantic/README.md): UnsupportedConstruct. Nothing is skipped or approximated silently, so a translator change that starts emitting something new makes the test error out instead of passing. * One invocation (one lane), or with run_workgroup several in lockstep, which meet only at - OpGroupNonUniformShuffle (the one subgroup operation modelled). Control flow is the forward-only discard test and the forward merge/dynamic-bounds + OpGroupNonUniformShuffle and OpGroupNonUniformBallot (the subgroup operations modelled, with + BallotBitExtract). Control flow is the forward-only discard test and the forward merge/dynamic-bounds branches the translator emits: OpBranch / OpBranchConditional to a later label plus OpPhi at the merge block. Backward branches, loops, calls and switches are rejected. Function/Output/Input variables live in Python boxes; PushConstant reads can be seeded with a word list; physical-storage-buffer loads/stores use a flat @@ -175,6 +176,8 @@ def run_workgroup(text, invocations, subgroup_size, inputs_for=None, push_consta or past `subgroup_size` is undefined in SPIR-V: `out_of_range="raise"` raises UndefinedResult; `out_of_range="wrap"` takes lane Id mod subgroup_size instead, a model of one observed driver behaviour and not of the specification (Leonida issue #94: on a 32-wide NVIDIA subgroup lane 40 read lane 8). + OpGroupNonUniformBallot sets bit l for each lane l of the caller's subgroup whose predicate is true (every + invocation of the workgroup is running). """ if out_of_range not in ("raise", "wrap"): raise ValueError(f"out_of_range: {out_of_range!r}") @@ -197,6 +200,12 @@ def run_workgroup(text, invocations, subgroup_size, inputs_for=None, push_consta results = [] for i in range(invocations): kind, _, _value, ident = pending[i] + if kind == "OpGroupNonUniformBallot": + # Bit l of the 128-bit mask = lane l of this subgroup is running with a true predicate. + base = (i // subgroup_size) * subgroup_size + bits = sum(1 << l for l in range(subgroup_size) if pending[base + l][2]) + results.append(tuple((bits >> (32 * w)) & MASK for w in range(4))) + continue if kind != "OpGroupNonUniformShuffle": raise UnsupportedConstruct(kind) if not 0 <= ident < subgroup_size: @@ -552,6 +561,18 @@ def _invocation(text, inputs, push_constants, memory): if types.t[a[0]][0] != "int" or val(a[1]) != 3: raise UnsupportedConstruct("OpGroupNonUniformShuffle other than a Subgroup-scope integer") values[res] = yield (op, pc - 1, val(a[2]), val(a[3])) + elif op == "OpGroupNonUniformBallot": + # OpGroupNonUniformBallot + k = types.t[a[0]] + if k[0] != "vec" or k[2] != 4 or val(a[1]) != 3 or not isinstance(val(a[2]), bool): + raise UnsupportedConstruct("OpGroupNonUniformBallot other than a Subgroup-scope uvec4") + values[res] = yield (op, pc - 1, val(a[2]), None) + elif op == "OpGroupNonUniformBallotBitExtract": + # OpGroupNonUniformBallotBitExtract : needs no other lane. + ballot, idx = val(a[2]), val(a[3]) + if val(a[1]) != 3 or not 0 <= idx < 128: + raise UnsupportedConstruct("OpGroupNonUniformBallotBitExtract scope or index") + values[res] = bool((ballot[idx // 32] >> (idx % 32)) & 1) elif op == "OpLogicalAnd": x, y = val(a[1]), val(a[2]) if not (isinstance(x, bool) and isinstance(y, bool)): From 56c4594243a99f81a284bc8f96f473a9d9e46468 Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:52:00 +0100 Subject: [PATCH 33/53] Use the float conversion opcodes now supported on main --- tests/semantic/spirv_mini_interp.py | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index 44ad9e515..85a8a485a 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py @@ -368,16 +368,6 @@ def run_fragment(text, inputs=None, push_constants=None, memory=None): values[res] = v & wmask(a[0]) else: raise UnsupportedConstruct("OpBitcast between these types") - elif op in ("OpConvertFToS", "OpConvertFToU"): - source = val(a[1]) - if not math.isfinite(source): - raise UnsupportedConstruct(f"{op} with a non-finite operand") - value = math.trunc(source) - bits = types.bits(a[0]) - lo, hi = (-(1 << (bits - 1)), (1 << (bits - 1)) - 1) if op == "OpConvertFToS" else (0, wmask(a[0])) - if not lo <= value <= hi: - raise UnsupportedConstruct(f"{op} result out of range (undefined in SPIR-V)") - values[res] = value & wmask(a[0]) elif op == "OpCompositeExtract": v = val(a[1]) for i in a[2:]: From 6005d7e2f0371e4849166fc6604945a5b98175ad Mon Sep 17 00:00:00 2001 From: DiazE117 <230450176+DiazE117@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:36:35 -0600 Subject: [PATCH 34/53] tests: eight more wave64 mask and vote GPU tests across 64 lanes on the CPU run_workgroup now steps every invocation one instruction per round, so a load after a store sees all lanes' stores as in a SIMD wave (cs_w64x_load_ ballot_load read a later store before), allows a partial last subgroup, and answers OpGroupNonUniformAny, All and BitwiseOr Reduce; BallotFindLSB, IAddCarry and UGreaterThan are per lane. A shuffle from a lane that is not running is an undefined value. test_wave64_subgroup_ops runs cs_w64x_ballot, _readfirstlane, _load_ballot_load, _partial, cs_wave64_ballot, cs_wm_bfm64, cs_wm_half_cmp and cs_wavemask without --wave64-emulate: - one 64-wide subgroup: every word equals check.py (cs_wavemask: all 64 lanes); - two 32-wide subgroups: the pinned words equal what an RTX 4070 SUPER (driver 610.88) wrote, three runs each; cs_wavemask 64 mismatches with lane 0 = 0x00081021 on both; - removing 21cef25's ballot guard makes cs_w64x_partial use an undefined value. 403 semantic tests pass (397 before). AI-assisted. Co-Authored-By: Claude Opus 5.5 --- tests/semantic/README.md | 8 +- .../semantic/fixtures/disasm/cs_w64x_ballot.s | 14 ++ .../disasm/cs_w64x_load_ballot_load.s | 62 ++++++++ .../fixtures/disasm/cs_w64x_partial.s | 62 ++++++++ .../fixtures/disasm/cs_w64x_readfirstlane.s | 73 +++++++++ .../fixtures/disasm/cs_wave64_ballot.s | 34 +++++ tests/semantic/fixtures/disasm/cs_wavemask.s | 54 +++++++ tests/semantic/fixtures/disasm/cs_wm_bfm64.s | 22 +++ .../semantic/fixtures/disasm/cs_wm_half_cmp.s | 27 ++++ tests/semantic/regen_fixtures.py | 4 +- tests/semantic/spirv_mini_interp.py | 125 ++++++++++------ tests/semantic/test_wave64_subgroup_ops.py | 138 ++++++++++++++++++ 12 files changed, 580 insertions(+), 43 deletions(-) create mode 100644 tests/semantic/fixtures/disasm/cs_w64x_ballot.s create mode 100644 tests/semantic/fixtures/disasm/cs_w64x_load_ballot_load.s create mode 100644 tests/semantic/fixtures/disasm/cs_w64x_partial.s create mode 100644 tests/semantic/fixtures/disasm/cs_w64x_readfirstlane.s create mode 100644 tests/semantic/fixtures/disasm/cs_wave64_ballot.s create mode 100644 tests/semantic/fixtures/disasm/cs_wavemask.s create mode 100644 tests/semantic/fixtures/disasm/cs_wm_bfm64.s create mode 100644 tests/semantic/fixtures/disasm/cs_wm_half_cmp.s create mode 100644 tests/semantic/test_wave64_subgroup_ops.py diff --git a/tests/semantic/README.md b/tests/semantic/README.md index 6668b4d13..0aeb6d456 100644 --- a/tests/semantic/README.md +++ b/tests/semantic/README.md @@ -30,6 +30,11 @@ What they check (`tools/rdna2spirv.py`, pixel shaders plus one compute shader): undefined in SPIR-V (`UndefinedResult`); a "lane mod 32" model of issue #94 gives the words a 32-wide GPU shows (all 24 matched on an RTX 4070 SUPER, driver 610.88, without `--wave64-emulate`). Two SPIR-V sabotages (readlane lane & 31, bpermute without its half base) must change the 64-wide result. +- `test_wave64_subgroup_ops.py` runs eight more wave64 GPU tests the same way (`cs_w64x_ballot`, + `_readfirstlane`, `_load_ballot_load`, `_partial`, `cs_wave64_ballot`, `cs_wm_bfm64`, `cs_wm_half_cmp`, + `cs_wavemask`): on one 64-wide subgroup every word equals the GPU check; on two 32-wide subgroups the + words pinned there are the ones an RTX 4070 SUPER (driver 610.88) wrote without `--wave64-emulate`. The + cs_w64x tests with branches need llvm-mc encodings and are not covered. - `test_negative_controls.py` sabotages the translated SPIR-V text and requires the result to change. - `test_mutations.py` sabotages a temporary copy of `tools/` (13 regressions across SDWA, min3/max3, `v_bfe_i32`, `v_pk_fma_f16`, `v_fma_f16 op_sel`, `v_subrev_co_ci_u32`, `v_cmpx_eq_u64`, `v_mul_i32_i24`, `v_ffbh_i32`, @@ -38,7 +43,8 @@ What they check (`tools/rdna2spirv.py`, pixel shaders plus one compute shader): - `test_fixtures.py` checks `tests/semantic/fixtures/disasm/*.s` equals what `regen_fixtures.py` makes from `runtime/test/shaders/*.asm` (`python tests/semantic/regen_fixtures.py` rewrites them). -Limits: single lane (or lanes in lockstep that meet only at `OpGroupNonUniformShuffle` and `OpGroupNonUniformBallot`), forward-only structured control flow (the fragment-exit discard test and the compute +Limits: single lane (or lanes in lockstep, one instruction per lane per round, that exchange values only through +`OpGroupNonUniformShuffle`, `Ballot`, `Any`, `All` and `BitwiseOr` Reduce), forward-only structured control flow (the fragment-exit discard test and the compute dynamic-bounds merge; no backward branches, loops, calls or switches), no texture access. PushConstant words, Input variables and a flat physical-address `{address: word}` map can be supplied per run. A shift by at least the bit width is an undefined value: arithmetic on it stays undefined and any other use (store, branch or select condition, shuffle, output) raises. Values that pass diff --git a/tests/semantic/fixtures/disasm/cs_w64x_ballot.s b/tests/semantic/fixtures/disasm/cs_w64x_ballot.s new file mode 100644 index 000000000..f44905677 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_w64x_ballot.s @@ -0,0 +1,14 @@ +; cs_w64x_ballot test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w64x_ballot.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_and_b32_e32 v2, 7, v1 + v_cmp_eq_u32_e64 s[4:5], 5, v2 + s_bcnt1_i32_b64 s6, s[4:5] + v_mbcnt_lo_u32_b32 v3, s4, 0 + v_mbcnt_hi_u32_b32 v3, s5, v3 + v_lshlrev_b32_e32 v4, 2, v3 + s_lshl_b32 s7, s6, 8 + v_add_nc_u32_e32 v5, s7, v1 + s_mov_b64 exec, s[4:5] + buffer_store_dword v5, v4, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_w64x_load_ballot_load.s b/tests/semantic/fixtures/disasm/cs_w64x_load_ballot_load.s new file mode 100644 index 000000000..d4bb28149 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_w64x_load_ballot_load.s @@ -0,0 +1,62 @@ +; cs_w64x_load_ballot_load test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w64x_load_ballot_load.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_add_nc_u32_e32 v2, 10, v1 + v_lshlrev_b32_e32 v3, 2, v1 + buffer_store_dword v2, v3, s[0:3], 0 offen + s_waitcnt_vscnt null, 0x0 + s_waitcnt vmcnt(0) + v_xor_b32_e32 v7, 32, v1 + v_lshlrev_b32_e32 v7, 2, v7 + buffer_load_dword v4, v7, s[0:3], 0 offen + s_waitcnt vmcnt(0) + v_cmp_gt_u32_e64 s[4:5], v4, 41 + s_bcnt1_i32_b64 s6, s[4:5] + v_add_nc_u32_e32 v8, 1, v1 + v_and_b32_e32 v8, 63, v8 + v_lshlrev_b32_e32 v8, 2, v8 + buffer_load_dword v5, v8, s[0:3], 0 offen + s_waitcnt vmcnt(0) + v_add_nc_u32_e32 v6, s6, v5 + buffer_store_dword v6, v3, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, v6 + v_mov_b32_e32 v21, 0 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 31, v1 + v_mov_b32_e32 v20, v6 + v_mov_b32_e32 v21, 4 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 32, v1 + v_mov_b32_e32 v20, v6 + v_mov_b32_e32 v21, 8 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_mov_b32_e32 v20, v6 + v_mov_b32_e32 v21, 12 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 16 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 40, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 20 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 24 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 5, v1 + v_mov_b32_e32 v20, s6 + v_mov_b32_e32 v21, 28 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_w64x_partial.s b/tests/semantic/fixtures/disasm/cs_w64x_partial.s new file mode 100644 index 000000000..5630b590c --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_w64x_partial.s @@ -0,0 +1,62 @@ +; cs_w64x_partial test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w64x_partial.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_add_nc_u32_e32 v2, 500, v1 + s_mov_b64 s[6:7], exec + s_bcnt1_i32_b64 s8, exec + v_cmp_eq_u32_e64 s[4:5], v1, v1 + s_bcnt1_i32_b64 s11, s[4:5] + v_add_nc_u32_e32 v3, 8, v1 + v_lshlrev_b32_e32 v3, 2, v3 + ds_bpermute_b32 v4, v3, v2 + v_xor_b32_e32 v6, 1, v1 + v_lshlrev_b32_e32 v6, 2, v6 + ds_bpermute_b32 v5, v6, v2 + s_waitcnt lgkmcnt(0) + v_cmpx_lt_u32_e32 31, v1 + v_readfirstlane_b32 s9, v2 + s_bcnt1_i32_b64 s10, exec + s_mov_b64 exec, s[6:7] + s_lshl_b32 s10, s10, 16 + s_add_u32 s9, s9, s10 + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, s8 + v_mov_b32_e32 v21, 0 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 39, v1 + v_mov_b32_e32 v20, s11 + v_mov_b32_e32 v21, 4 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 20, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 8 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 33, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 12 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 39, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 16 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 33, v1 + v_mov_b32_e32 v20, v5 + v_mov_b32_e32 v21, 20 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 38, v1 + v_mov_b32_e32 v20, v5 + v_mov_b32_e32 v21, 24 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 2, v1 + v_mov_b32_e32 v20, s9 + v_mov_b32_e32 v21, 28 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_w64x_readfirstlane.s b/tests/semantic/fixtures/disasm/cs_w64x_readfirstlane.s new file mode 100644 index 000000000..c00007de9 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_w64x_readfirstlane.s @@ -0,0 +1,73 @@ +; cs_w64x_readfirstlane test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w64x_readfirstlane.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_add_nc_u32_e32 v2, 100, v1 + s_mov_b32 exec_lo, 0 + s_mov_b32 exec_hi, 0xffffff00 + v_readfirstlane_b32 s6, v2 + s_mov_b64 exec, -1 + s_mov_b32 exec_lo, 0 + s_mov_b32 exec_hi, 0x80000000 + v_readfirstlane_b32 s7, v2 + s_mov_b64 exec, -1 + s_mov_b32 exec_lo, 0 + s_mov_b32 exec_hi, 1 + v_readfirstlane_b32 s8, v2 + s_mov_b64 exec, -1 + s_mov_b32 exec_lo, 0 + s_mov_b32 exec_hi, 0 + v_readfirstlane_b32 s9, v2 + s_mov_b64 exec, -1 + s_mov_b32 exec_lo, 0x20 + s_mov_b32 exec_hi, 0xe + v_readfirstlane_b32 s10, v2 + s_mov_b64 exec, -1 + s_mov_b32 exec_lo, 0 + s_mov_b32 exec_hi, 0xe + v_readfirstlane_b32 s11, v2 + s_mov_b64 exec, -1 + s_mov_b32 exec_lo, 0 + s_mov_b32 exec_hi, 0xffff0000 + v_readfirstlane_b32 s12, v1 + s_mov_b64 exec, -1 + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, s6 + v_mov_b32_e32 v21, 0 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_mov_b32_e32 v20, s6 + v_mov_b32_e32 v21, 4 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 5, v1 + v_mov_b32_e32 v20, s7 + v_mov_b32_e32 v21, 8 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_mov_b32_e32 v20, s8 + v_mov_b32_e32 v21, 12 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 40, v1 + v_mov_b32_e32 v20, s9 + v_mov_b32_e32 v21, 16 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 34, v1 + v_mov_b32_e32 v20, s10 + v_mov_b32_e32 v21, 20 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, s11 + v_mov_b32_e32 v21, 24 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 49, v1 + v_mov_b32_e32 v20, s12 + v_mov_b32_e32 v21, 28 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_wave64_ballot.s b/tests/semantic/fixtures/disasm/cs_wave64_ballot.s new file mode 100644 index 000000000..6b353b44f --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_wave64_ballot.s @@ -0,0 +1,34 @@ +; cs_wave64_ballot test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_wave64_ballot.asm + v_cmp_ge_u32_e64 s[4:5], v0, 16 + v_cmp_lt_u32_e64 s[6:7], v0, 48 + s_and_b64 s[4:5], s[4:5], s[6:7] + s_bcnt1_i32_b64 s8, s[4:5] + s_ff1_i32_b64 s9, s[4:5] + v_cmp_ge_u32_e64 s[10:11], v0, 40 + s_bcnt1_i32_b64 s12, s[10:11] + s_ff1_i32_b64 s13, s[10:11] + s_mov_b32 exec_lo, 0 + s_mov_b32 exec_hi, 0x00ff0000 + s_bcnt1_i32_b64 s14, exec + s_ff1_i32_b64 s15, exec + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v0 + v_mov_b32_e32 v1, s8 + v_mov_b32_e32 v2, s9 + v_mov_b32_e32 v3, s12 + v_mov_b32_e32 v4, s13 + v_mov_b32_e32 v5, s14 + v_mov_b32_e32 v6, s15 + v_mov_b32_e32 v10, 0 + v_mov_b32_e32 v11, 4 + v_mov_b32_e32 v12, 8 + v_mov_b32_e32 v13, 12 + v_mov_b32_e32 v14, 16 + v_mov_b32_e32 v15, 20 + buffer_store_dword v1, v10, s[0:3], 0 offen + buffer_store_dword v2, v11, s[0:3], 0 offen + buffer_store_dword v3, v12, s[0:3], 0 offen + buffer_store_dword v4, v13, s[0:3], 0 offen + buffer_store_dword v5, v14, s[0:3], 0 offen + buffer_store_dword v6, v15, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_wavemask.s b/tests/semantic/fixtures/disasm/cs_wavemask.s new file mode 100644 index 000000000..e88ed1ae3 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_wavemask.s @@ -0,0 +1,54 @@ +; cs_wavemask test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_wavemask.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_lshlrev_b32_e32 v3, 2, v1 + v_mov_b32_e32 v4, 0 + s_mov_b32 exec_lo, 0xffff0000 + s_mov_b32 exec_hi, 0xffff + s_mov_b64 s[6:7], exec + s_bcnt1_i32_b64 s8, exec + s_bcnt1_i32_b64 s10, s[6:7] + s_add_i32 s8, s8, s10 + s_cmp_lg_u32 s6, 0 + s_cselect_b32 s14, 1, 0 + s_add_i32 s8, s8, s14 + s_cmp_eq_u64 s[6:7], 0 + s_cselect_b32 s14, 2, 0 + s_add_i32 s8, s8, s14 + s_ff1_i32_b64 s9, exec + v_cmp_gt_u32_e32 vcc_lo, 24, v1 + s_bcnt1_i32_b64 s11, vcc + v_mbcnt_lo_u32_b32 v4, s6, 0 + v_mbcnt_hi_u32_b32 v4, s7, v4 + v_mov_b32_e32 v6, s6 + v_or3_b32 v6, s6, s6, v6 + v_readfirstlane_b32 s12, v6 + v_mov_b32_e32 v6, s7 + v_readfirstlane_b32 s13, v6 + v_writelane_b32 v10, s6, 0 + v_writelane_b32 v10, s7, 1 + s_mov_b32 exec_lo, -1 + s_mov_b32 exec_hi, -1 + s_mov_b32 s6, 0 + s_mov_b32 s7, 0 + v_mov_b32_e32 v5, 0 + v_readlane_b32 s6, v10, 0 + v_readlane_b32 s7, v10, 1 + s_mov_b64 exec, s[6:7] + v_mov_b32_e32 v5, 0x80 + s_mov_b32 exec_lo, -1 + s_mov_b32 exec_hi, -1 + v_mov_b32_e32 v7, 0 + s_mov_b64 exec, s[12:13] + v_mov_b32_e32 v7, 0x40 + s_mov_b32 exec_lo, -1 + s_mov_b32 exec_hi, -1 + s_lshl_b32 s9, s9, 8 + s_lshl_b32 s11, s11, 16 + s_or_b32 s8, s8, s9 + s_or_b32 s8, s8, s11 + v_or3_b32 v4, v4, v5, v7 + v_lshlrev_b32_e32 v4, 24, v4 + v_or_b32_e32 v2, s8, v4 + buffer_store_dword v2, v3, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_wm_bfm64.s b/tests/semantic/fixtures/disasm/cs_wm_bfm64.s new file mode 100644 index 000000000..3535dca66 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_wm_bfm64.s @@ -0,0 +1,22 @@ +; cs_wm_bfm64 test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_wm_bfm64.asm + s_mov_b64 exec, -1 + s_bfm_b64 s[6:7], 16, 8 + s_bcnt1_i32_b64 s8, s[6:7] + s_ff1_i32_b64 s9, s[6:7] + s_bfm_b64 s[10:11], 8, 40 + s_bcnt1_i32_b64 s12, s[10:11] + s_ff1_i32_b64 s13, s[10:11] + v_cmpx_eq_u32_e32 0, v0 + v_mov_b32_e32 v1, s8 + v_mov_b32_e32 v2, 0 + buffer_store_dword v1, v2, s[0:3], 0 offen + v_mov_b32_e32 v1, s9 + v_mov_b32_e32 v2, 4 + buffer_store_dword v1, v2, s[0:3], 0 offen + v_mov_b32_e32 v1, s12 + v_mov_b32_e32 v2, 8 + buffer_store_dword v1, v2, s[0:3], 0 offen + v_mov_b32_e32 v1, s13 + v_mov_b32_e32 v2, 12 + buffer_store_dword v1, v2, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_wm_half_cmp.s b/tests/semantic/fixtures/disasm/cs_wm_half_cmp.s new file mode 100644 index 000000000..bed78213b --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_wm_half_cmp.s @@ -0,0 +1,27 @@ +; cs_wm_half_cmp test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_wm_half_cmp.asm + s_mov_b32 exec_lo, 0 + s_mov_b32 exec_hi, 0xffff + s_mov_b64 s[6:7], exec + s_cmp_eq_u32 s6, 0 + s_cselect_b32 s8, 1, 0 + s_cmp_lg_u32 s6, 0 + s_cselect_b32 s9, 1, 0 + s_cmp_lg_u32 s7, 0 + s_cselect_b32 s10, 1, 0 + s_cmp_eq_u32 exec_lo, 0 + s_cselect_b32 s11, 1, 0 + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v0 + v_mov_b32_e32 v1, s8 + v_mov_b32_e32 v2, 0 + buffer_store_dword v1, v2, s[0:3], 0 offen + v_mov_b32_e32 v1, s9 + v_mov_b32_e32 v2, 4 + buffer_store_dword v1, v2, s[0:3], 0 offen + v_mov_b32_e32 v1, s10 + v_mov_b32_e32 v2, 8 + buffer_store_dword v1, v2, s[0:3], 0 offen + v_mov_b32_e32 v1, s11 + v_mov_b32_e32 v2, 12 + buffer_store_dword v1, v2, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/regen_fixtures.py b/tests/semantic/regen_fixtures.py index f9061258f..cf010862e 100644 --- a/tests/semantic/regen_fixtures.py +++ b/tests/semantic/regen_fixtures.py @@ -18,7 +18,9 @@ ASM_DIR = os.path.join(ROOT, "runtime", "test", "shaders") FIXTURE_DIR = os.path.join(HERE, "fixtures", "disasm") SHADERS = ("ps_sdwa", "ps_ops", "ps_ops2", "ps_ops3", "ps_ops4", "ps_ops5", "ps_ops6", "ps_ops7", "ps_ops8", "ps_legacy_mul", "ps_vcc_x2", "ps_flat", "cs_bounds", "cs_fmt_1010102", - "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_bpermute") + "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_bpermute", + "cs_w64x_ballot", "cs_w64x_readfirstlane", "cs_w64x_load_ballot_load", "cs_w64x_partial", + "cs_wave64_ballot", "cs_wm_bfm64", "cs_wm_half_cmp", "cs_wavemask") def render(name): diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index 9ae409ca4..7a4f1fe43 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py @@ -8,8 +8,8 @@ Design rules (see tests/semantic/README.md): UnsupportedConstruct. Nothing is skipped or approximated silently, so a translator change that starts emitting something new makes the test error out instead of passing. * One invocation (one lane), or with run_workgroup several in lockstep, which meet only at - OpGroupNonUniformShuffle and OpGroupNonUniformBallot (the subgroup operations modelled, with - BallotBitExtract). Control flow is the forward-only discard test and the forward merge/dynamic-bounds + subgroup operations (Shuffle, Ballot, Any, All, BitwiseOr Reduce; BallotBitExtract and BallotFindLSB + are per lane). Control flow is the forward-only discard test and the forward merge/dynamic-bounds branches the translator emits: OpBranch / OpBranchConditional to a later label plus OpPhi at the merge block. Backward branches, loops, calls and switches are rejected. Function/Output/Input variables live in Python boxes; PushConstant reads can be seeded with a word list; physical-storage-buffer loads/stores use a flat @@ -57,7 +57,8 @@ UNDEF = _Undef() _PURE = frozenset({ "OpBitwiseAnd", "OpBitwiseOr", "OpBitwiseXor", "OpNot", "OpShiftLeftLogical", "OpShiftRightLogical", "OpShiftRightArithmetic", "OpIAdd", "OpISub", "OpIMul", "OpUConvert", "OpBitCount", "OpIEqual", - "OpINotEqual", "OpSLessThan", "OpULessThan", "OpUGreaterThanEqual", "OpCopyObject", "OpBitcast", + "OpINotEqual", "OpSLessThan", "OpULessThan", "OpUGreaterThan", "OpUGreaterThanEqual", "OpCopyObject", + "OpBitcast", "OpBitFieldUExtract", "OpBitFieldSExtract", "OpBitFieldInsert", }) @@ -167,66 +168,89 @@ def run_workgroup(text, invocations, subgroup_size, inputs_for=None, push_consta """Execute `invocations` invocations of `text` in lockstep and return the shared `memory`. Invocation i is subgroup i // subgroup_size, lane i % subgroup_size (a 1-D workgroup split into subgroups in - invocation order). `inputs_for(i)` gives invocation i's Input values (see run_fragment); push constants and - the physical-address memory are shared. Every invocation must reach every subgroup operation, in the same - order (the translator emits them in uniform control flow and models EXEC with a variable, so a lane that is - off in EXEC still executes them). + invocation order). When `invocations` is not a multiple of `subgroup_size` the last subgroup is partial: its + missing lanes are not running. `inputs_for(i)` gives invocation i's Input values (see run_fragment); push + constants and the physical-address memory are shared. Every invocation must reach every subgroup operation, + in the same order (the translator emits them in uniform control flow and models EXEC with a variable, so a + lane that is off in EXEC still executes them). - OpGroupNonUniformShuffle (Subgroup scope) returns the value of lane Id of the caller's own subgroup. An Id at - or past `subgroup_size` is undefined in SPIR-V: `out_of_range="raise"` raises UndefinedResult; - `out_of_range="wrap"` takes lane Id mod subgroup_size instead, a model of one observed driver behaviour - and not of the specification (Leonida issue #94: on a 32-wide NVIDIA subgroup lane 40 read lane 8). - OpGroupNonUniformBallot sets bit l for each lane l of the caller's subgroup whose predicate is true (every - invocation of the workgroup is running). + Subgroup operations (Subgroup scope), over the running lanes of the caller's subgroup: + * OpGroupNonUniformShuffle returns the value of lane Id. An Id at or past `subgroup_size` is undefined in + SPIR-V: `out_of_range="raise"` raises UndefinedResult; `out_of_range="wrap"` takes lane Id mod + subgroup_size instead, a model of one observed driver behaviour and not of the specification (Leonida + issue #94: on a 32-wide NVIDIA subgroup lane 40 read lane 8). An Id inside the subgroup whose lane is not + running gives an undefined value (raises only if used, see _Undef). + * OpGroupNonUniformBallot sets bit l for each running lane l whose predicate is true. + * OpGroupNonUniformAny / All: the predicate of any / every running lane. + * OpGroupNonUniformBitwiseOr Reduce: the OR of every running lane's value. """ if out_of_range not in ("raise", "wrap"): raise ValueError(f"out_of_range: {out_of_range!r}") - if invocations % subgroup_size: - raise UnsupportedConstruct("a partial subgroup") memory = {} if memory is None else memory - gens = [_invocation(text, (inputs_for(i) if inputs_for else None), push_constants, memory) + gens = [_invocation(text, (inputs_for(i) if inputs_for else None), push_constants, memory, step=True) for i in range(invocations)] - pending = [None] * invocations - live = set() - for i, g in enumerate(gens): + pending = [None] * invocations # what each invocation yielded last; None once it has returned + + def advance(i, value): try: - pending[i] = next(g) - live.add(i) + pending[i] = gens[i].send(value) except StopIteration: - pass - while live: + pending[i] = None + + for i in range(invocations): + advance(i, None) + while True: + # One instruction per invocation per round, in invocation order: invocations at the same instruction + # execute it one after the other before any goes on, as the lanes of a SIMD wave do, so a load that + # follows a store in program order sees every lane's store and none from a later instruction. + while any(req is not None and req[0] == "tick" for req in pending): + for i in range(invocations): + if pending[i] is not None and pending[i][0] == "tick": + advance(i, None) + live = [i for i in range(invocations) if pending[i] is not None] + if not live: + break if len(live) != invocations or len({pending[i][1] for i in live}) != 1: raise UnsupportedConstruct("subgroup operation not reached by every invocation at the same point") results = [] for i in range(invocations): kind, _, _value, ident = pending[i] + base = (i // subgroup_size) * subgroup_size + group = [pending[j] for j in range(base, min(base + subgroup_size, invocations))] if kind == "OpGroupNonUniformBallot": # Bit l of the 128-bit mask = lane l of this subgroup is running with a true predicate. - base = (i // subgroup_size) * subgroup_size - bits = sum(1 << l for l in range(subgroup_size) if pending[base + l][2]) + bits = sum(1 << l for l, req in enumerate(group) if req[2]) results.append(tuple((bits >> (32 * w)) & MASK for w in range(4))) - continue - if kind != "OpGroupNonUniformShuffle": + elif kind == "OpGroupNonUniformAny": + results.append(any(req[2] for req in group)) + elif kind == "OpGroupNonUniformAll": + results.append(all(req[2] for req in group)) + elif kind == "OpGroupNonUniformBitwiseOr": + acc = 0 + for req in group: + acc |= req[2] + results.append(acc) + elif kind == "OpGroupNonUniformShuffle": + if not 0 <= ident < subgroup_size: + if out_of_range == "raise": + raise UndefinedResult(f"invocation {i}: shuffle from lane {ident} of a " + f"{subgroup_size}-wide subgroup") + ident %= subgroup_size + results.append(group[ident][2] if ident < len(group) else UNDEF) + else: raise UnsupportedConstruct(kind) - if not 0 <= ident < subgroup_size: - if out_of_range == "raise": - raise UndefinedResult(f"invocation {i}: shuffle from lane {ident} of a {subgroup_size}-wide " - f"subgroup") - ident %= subgroup_size - src = (i // subgroup_size) * subgroup_size + ident - results.append(pending[src][2]) for i in range(invocations): - try: - pending[i] = gens[i].send(results[i]) - except StopIteration: - live.discard(i) - pending[i] = None + advance(i, results[i]) return memory -def _invocation(text, inputs, push_constants, memory): +_TICK = ("tick", None, None, None) + + +def _invocation(text, inputs, push_constants, memory, step=False): """One invocation as a generator. It yields (opcode, instruction index, value, id) at each subgroup operation - and expects that operation's result back; it returns run_fragment's result.""" + and expects that operation's result back; with `step` it also yields _TICK before each instruction. It + returns run_fragment's result.""" inputs = inputs or {} push_constants = list(push_constants or []) memory = {} if memory is None else memory @@ -367,6 +391,8 @@ def _invocation(text, inputs, push_constants, memory): killed = False cur_label = prev_label = None while pc < len(body): + if step: + yield _TICK res, op, a, line = body[pc] pc += 1 if res and a: @@ -567,6 +593,23 @@ def _invocation(text, inputs, push_constants, memory): if k[0] != "vec" or k[2] != 4 or val(a[1]) != 3 or not isinstance(val(a[2]), bool): raise UnsupportedConstruct("OpGroupNonUniformBallot other than a Subgroup-scope uvec4") values[res] = yield (op, pc - 1, val(a[2]), None) + elif op in ("OpGroupNonUniformAny", "OpGroupNonUniformAll"): + # + if val(a[1]) != 3 or not isinstance(val(a[2]), bool): + raise UnsupportedConstruct(f"{op} other than a Subgroup-scope bool") + values[res] = yield (op, pc - 1, val(a[2]), None) + elif op == "OpGroupNonUniformBitwiseOr": + # : only Reduce over a 32-bit integer. + if val(a[1]) != 3 or a[2] != "Reduce" or types.t[a[0]][:2] != ("int", 32): + raise UnsupportedConstruct("OpGroupNonUniformBitwiseOr other than a Subgroup-scope 32-bit Reduce") + values[res] = yield (op, pc - 1, val(a[3]) & MASK, None) + elif op == "OpGroupNonUniformBallotFindLSB": + # : the lowest set bit; undefined when no bit is set. + ballot = val(a[2]) + if val(a[1]) != 3: + raise UnsupportedConstruct("OpGroupNonUniformBallotFindLSB scope") + bits = sum(w << (32 * k) for k, w in enumerate(ballot)) + values[res] = (bits & -bits).bit_length() - 1 if bits else UNDEF elif op == "OpGroupNonUniformBallotBitExtract": # OpGroupNonUniformBallotBitExtract : needs no other lane. ballot, idx = val(a[2]), val(a[3]) diff --git a/tests/semantic/test_wave64_subgroup_ops.py b/tests/semantic/test_wave64_subgroup_ops.py new file mode 100644 index 000000000..e7c5b39f0 --- /dev/null +++ b/tests/semantic/test_wave64_subgroup_ops.py @@ -0,0 +1,138 @@ +"""Wave64 whole-wave mask and vote tests, run across every lane of the translated SPIR-V. + +Eight GPU tests from runtime/test/shaders (hand-written, no game data; fixtures from regen_fixtures.py), translated +without --wave64-emulate and run by spirv_mini_interp.run_workgroup the way vk_compute_test runs them: one group +of the size in the .asm header (64 threads, 40 for cs_w64x_partial), a heap filled with 0xEE bytes, s[0:3] = a V# +with base 0 and num_records 0xFFFFFFFF. + +* One 64-wide subgroup: every word equals the GPU check's value (check.py CS_DUMPS, W64X_DUMPS, W64X_PARTIAL; for + cs_wavemask the per-lane formula of vk_compute_test's "wavemask" mode). This covers ballots and s_bcnt1 / + s_ff1 of 64-bit masks, readfirstlane with only upper lanes on, the votes behind wave-uniform branches, and the + missing lanes of a partial wave (21cef25's ds_bpermute guard: a shuffle from them is undefined and must be + selected away). +* Two 32-wide subgroups (NVIDIA without emulation): the words differ, and WAVE32_EXPECTED pins them. Measured: + NVIDIA GeForce RTX 4070 SUPER (subgroup 32), driver 610.88, `vk_compute_test .spv 1 dump` on + run_gpu_tests.py's non-emulated build, three runs each: every word equals WAVE32_EXPECTED, and cs_wavemask + reports 64 mismatches with lane 0 = 0x00081021, as here. These follow from SPIR-V (each subgroup votes over its + own 32 lanes) except cs_w64x_load_ballot_load, whose loads read the other subgroup's stores: the order between + subgroups is not specified, and the interpreter's (subgroup 0's instruction, then subgroup 1's) is the order + that GPU showed. + +Not covered: the cs_w64x tests with branches (branch, sbarrier, wg128_branches, and cs_wm_half_ops / +cs_wm_scc_rfl), because the translator needs llvm-mc's encodings for branch targets and these fixtures are +unassembled; and the --wave64-emulate output (Workgroup memory and a round loop). +""" +import os +import re +import struct +import sys +import unittest + +import support +import spirv_mini_interp as si + +sys.path.insert(0, os.path.join(support.ROOT, "runtime", "test", "shaders")) +import check # noqa: E402 (the GPU check's expected words) +from compute_fixture import compute_header # noqa: E402 + +ASM_DIR = os.path.join(support.ROOT, "runtime", "test", "shaders") +GPU_DUMPS = dict(check.CS_DUMPS + check.W64X_DUMPS + check.W64X_PARTIAL) +DUMPS = ("cs_w64x_ballot", "cs_w64x_readfirstlane", "cs_w64x_load_ballot_load", "cs_w64x_partial", + "cs_wave64_ballot", "cs_wm_bfm64", "cs_wm_half_cmp") +HEAP_FILL = 0xEEEEEEEE +VSHARP = [0, 0, 0xFFFFFFFF, 0] + +# Two 32-wide subgroups: each half votes, counts and picks its first lane on its own. +WAVE32_EXPECTED = { + "cs_w64x_ballot": [1061, 1069, 1077, 1085] + [HEAP_FILL] * 4, + "cs_w64x_readfirstlane": [100, 140, 100, 132, 132, 133, 100, 48], + "cs_w64x_load_ballot_load": [43, 74, 43, 10, 42, 18, 41, 32], + "cs_w64x_partial": [32, 8, 528, 0, 0, 532, 539, 500], + "cs_wave64_ballot": [16, 16, 0, 0xFFFFFFFF, 0, 0xFFFFFFFF], + "cs_wm_bfm64": [16, 8, 0, 0xFFFFFFFF], + "cs_wm_half_cmp": [1, 0, 0, 1], +} + + +class Heap(dict): + """vk_compute_test's heap: every byte starts as 0xEE.""" + + def get(self, key, default=None): + return super().get(key, HEAP_FILL) + + +def wavemask_want(lane): + # vk_compute_test.cpp "wavemask": lanes 16-47 come back on after the parked mask (0x80) and the one through a + # VGPR (0x40), plus how many set lanes are below this one. + top = 0xC0 + lane - 16 if 16 <= lane < 48 else 0 + return 65 | 16 << 8 | 8 << 16 | top << 24 + + +def run(name, subgroup_size): + header = compute_header(os.path.join(ASM_DIR, name + ".asm")) + threads = struct.unpack_from(" Date: Sat, 21 Nov 2026 18:53:21 -0400 Subject: [PATCH 35/53] Runtime: convert UINT render-target clear values numerically --- docs/d3d12_vulkan.md | 8 ++ runtime/CMakeLists.txt | 12 ++ runtime/README.md | 14 +++ runtime/src/vulkan_replay.h | 30 ++++- runtime/test/clear_color_test.cpp | 81 ++++++++++++ runtime/test/d3d12_uint_clear_test.cpp | 166 +++++++++++++++++++++++++ 6 files changed, 309 insertions(+), 2 deletions(-) create mode 100644 runtime/test/clear_color_test.cpp create mode 100644 runtime/test/d3d12_uint_clear_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 2dc43ac00..f616550b9 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -643,6 +643,14 @@ The trace will enumerate them. - Clears: a full-subresource clear maps to `vkCmdClearColorImage`/`vkCmdClearDepthStencilImage` (UAV buffers to `vkCmdFillBuffer`); a rect clear uses `vkCmdClearAttachments` inside the rendering scope. UAV image clears use `vkCmdClearColorImage` in `GENERAL`; non-32-bit buffer patterns need a compute clear. +- **Typed UINT RTV clears:** `ClearRenderTargetView` still takes `FLOAT[4]`. For the currently exposed + `R8G8B8A8_UINT`, `R32_UINT` and `R32G32B32A32_UINT` resources, convert those values numerically into + `VkClearColorValue::uint32` for both image and rectangle clears; copying float bits gives incorrect stored + integers without a Vulkan validation error. **Measured:** Windows D3D12 on WARP and AMD RX 5700 XT clamps + negatives/NaN to zero, positive overflow/infinity to the component maximum, and truncates fractions. + `d3d12_uint_clear_test` compares full and rectangular D3D12 readbacks with WARP over seven input sets on all + three formats; `clear_color_test` checks both replay paths without a GPU, including unchanged float values. + This does not add typed-view reinterpretation of typeless resources or new integer formats. - `D3D12XBOX_RESOURCE_FLAG_FORCE_TEXTURE_COMPATIBILITY` (public release note) and DCC: ignore the flag, let the Vulkan driver choose compression, and fail loudly if the game aliases a buffer over a compressed image or reads raw DCC metadata. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 529db697b..136cb565b 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -340,6 +340,12 @@ if(Vulkan_FOUND) target_compile_definitions(d3d12_descriptor_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(d3d12_descriptor_test PRIVATE /W4 /permissive- /utf-8) + # Differential regression: run explicitly (requires Vulkan hardware and Windows WARP). + add_executable(d3d12_uint_clear_test test/d3d12_uint_clear_test.cpp) + target_link_libraries(d3d12_uint_clear_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_uint_clear_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_uint_clear_test PRIVATE /W4 /permissive- /utf-8) + # The loader can create this device instead of the host's (D3D12XboxCreateDevice, LEONIDA_D3D12=vulkan). if(TARGET gta6rt) target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com) @@ -351,6 +357,12 @@ if(Vulkan_FOUND) # Needs only the Vulkan headers, not a GPU. if(BUILD_TESTING) + add_executable(clear_color_test test/clear_color_test.cpp) + target_link_libraries(clear_color_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(clear_color_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME clear_color COMMAND clear_color_test) add_executable(d3d12_state_map_test test/d3d12_state_map_test.cpp) target_link_libraries(d3d12_state_map_test PRIVATE Vulkan::Headers) if(WIN32) diff --git a/runtime/README.md b/runtime/README.md index 0b5bdea00..ec4fe4a45 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -120,3 +120,17 @@ in [docs/design.md](../docs/design.md), and the differential-validation design i work. No game data, keys, or extracted assets belong in this directory or in the repository. + +### Typed UINT clear regression + +`clear_color_test` checks numeric UINT conversion and unchanged float clears without a GPU. +`d3d12_uint_clear_test` compares 21 full/rectangle readbacks with Windows WARP across the three +currently supported typed UINT render-target formats. Fixtures are synthetic; no shaders or game data are needed. +The GPU test runs explicitly, while the CPU test is registered in CTest. + +```powershell +ctest --test-dir runtime/build -C RelWithDebInfo -R '^clear_color$' --output-on-failure +$env:LEONIDA_VK_VALIDATION = '1' +$env:VK_VALIDATION_VALIDATE_SYNC = '1' +.\runtime\build\RelWithDebInfo\d3d12_uint_clear_test.exe +``` diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 1bcee80a3..91b2d2d23 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -499,6 +500,32 @@ struct Prepared { VkImageResolve resolve{}; // resolves }; +// ClearRenderTargetView takes FLOATs even for integer RTVs. For the UINT formats currently exposed by +// the device, Windows D3D12 (WARP and AMD) clamps to the component range and truncates fractions. Vulkan +// instead interprets the matching union member as an integer already; copying float bits changes the value. +inline VkClearColorValue render_target_clear_color(VkFormat format, const ClearColor& input) { + std::uint32_t maximum = 0; + switch (format) { + case VK_FORMAT_R8G8B8A8_UINT: maximum = 255; break; + case VK_FORMAT_R32_UINT: + case VK_FORMAT_R32G32B32A32_UINT: maximum = std::numeric_limits::max(); break; + default: break; + } + VkClearColorValue value{}; + for (std::size_t i = 0; i < input.size(); ++i) { + if (!maximum) { + value.float32[i] = input[i]; + } else if (!(input[i] > 0.0f)) { + value.uint32[i] = 0; // NaN, negative values and either zero; no out-of-range float-to-int cast. + } else if (double(input[i]) >= double(maximum)) { + value.uint32[i] = maximum; // Includes +infinity; UINT32_MAX itself is not representable as float. + } else { + value.uint32[i] = static_cast(input[i]); + } + } + return value; +} + inline bool view_range(const ResourceBinding& resource, const TargetView& view, VkImageAspectFlags aspects, VkImageSubresourceRange& out) { if (view.mip >= resource.mip_levels) return false; @@ -1012,8 +1039,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); auto pieces = detail::current(tracker, id, p.range, image_layout(p.binding, state.layout)); detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); - VkClearColorValue color{}; - std::copy(color_clear->color.begin(), color_clear->color.end(), color.float32); + const VkClearColorValue color = detail::render_target_clear_color(p.binding.format, color_clear->color); if (p.rects.empty()) { detail::round_trip(vk, command_buffer, p.binding.image, pieces, image_layout(p.binding, transfer_dst.layout), state, transfer_dst.access, transfer_dst.stages, [&] { diff --git a/runtime/test/clear_color_test.cpp b/runtime/test/clear_color_test.cpp new file mode 100644 index 000000000..8da8c9eef --- /dev/null +++ b/runtime/test/clear_color_test.cpp @@ -0,0 +1,81 @@ +// Value-level replay regression: full and rectangular UINT clears must carry integer values, not float bits. +// No Vulkan loader, GPU, shaders or game data. Expected conversions also match the WARP differential GPU test. +#include "../src/vulkan_replay.h" +#include +#include +#include +#include + +namespace { +VkClearColorValue captured{}; +unsigned calls = 0; +VKAPI_ATTR void VKAPI_CALL barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, + std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, + std::uint32_t, const VkImageMemoryBarrier*) {} +VKAPI_ATTR void VKAPI_CALL clear(VkCommandBuffer, VkImage, VkImageLayout, const VkClearColorValue* color, + std::uint32_t, const VkImageSubresourceRange*) { captured = *color; ++calls; } +VKAPI_ATTR void VKAPI_CALL begin(VkCommandBuffer, const VkRenderingInfo*) {} +VKAPI_ATTR void VKAPI_CALL end(VkCommandBuffer) {} +VKAPI_ATTR void VKAPI_CALL attachments(VkCommandBuffer, std::uint32_t n, const VkClearAttachment* a, + std::uint32_t, const VkClearRect*) { if (n == 1) { captured = a[0].clearValue.color; ++calls; } } + +bool replay_color(VkFormat format, const leonida::ClearColor& color, bool rectangle) { + leonida::CommandList list; + const leonida::Rect rect{1, 1, 3, 3}; + if (!list.clear_render_target({1, 0, 0, 1}, color, + rectangle ? std::span(&rect, 1) : std::span{}) || !list.close()) return false; + leonida::ResourceBinding binding{}; + binding.image = reinterpret_cast(std::uintptr_t{1}); + binding.format = format; + binding.width = binding.height = 4; + leonida::ReplayFunctions vk{}; + vk.pipeline_barrier = barrier; + vk.clear_color_image = clear; + vk.begin_rendering = begin; + vk.end_rendering = end; + vk.clear_attachments = attachments; + vk.image_view = [](const auto&, const auto&) { return reinterpret_cast(std::uintptr_t{1}); }; + calls = 0; + return leonida::replay(list, VK_NULL_HANDLE, [&](auto) { return &binding; }, vk) == leonida::ReplayResult::success && calls == 1; +} +} // namespace + +int main() { + const float nan = std::numeric_limits::quiet_NaN(), inf = std::numeric_limits::infinity(); + struct Case { leonida::ClearColor color; std::array u8, u32; }; + const Case cases[] = { + {{1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}}, + {{1.5f, 2.5f, 3.5f, 4.5f}, {1, 2, 3, 4}, {1, 2, 3, 4}}, + {{-1, -0.0f, 254.5f, 255.5f}, {0, 0, 254, 255}, {0, 0, 254, 255}}, + {{256, 65536, 16777216, 4294967296.0f}, {255, 255, 255, 255}, {256, 65536, 16777216, 0xffffffffu}}, + {{nan, inf, -inf, 0.5f}, {0, 255, 0, 0}, {0, 0xffffffffu, 0, 0}}, + {{0.499f, 0.501f, 1.499f, 1.501f}, {0, 0, 1, 1}, {0, 0, 1, 1}}, + {{4294967040.0f, std::numeric_limits::max(), 255, 0}, {255, 255, 255, 0}, {0xffffff00u, 0xffffffffu, 255, 0}}, + }; + unsigned checks = 0; + for (const auto& c : cases) { + for (const VkFormat format : {VK_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R32_UINT, VK_FORMAT_R32G32B32A32_UINT}) { + for (const bool rect : {false, true}) { + const auto& expected = format == VK_FORMAT_R8G8B8A8_UINT ? c.u8 : c.u32; + if (!replay_color(format, c.color, rect)) return 1; + for (unsigned i = 0; i < 4; ++i) { + if (captured.uint32[i] != expected[i]) { + std::fprintf(stderr, "UINT clear: format %d rect %d channel %u: got %u, expected %u\n", + int(format), int(rect), i, captured.uint32[i], expected[i]); + return 1; + } + } + ++checks; + } + } + for (const VkFormat format : {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R32_SFLOAT}) { + for (const bool rect : {false, true}) { + if (!replay_color(format, c.color, rect) || std::memcmp(captured.float32, c.color.data(), sizeof(captured)) != 0) + return 1; + ++checks; + } + } + } + std::printf("clear_color_test: %u full/rectangle UINT and float replay checks passed\n", checks); + return 0; +} diff --git a/runtime/test/d3d12_uint_clear_test.cpp b/runtime/test/d3d12_uint_clear_test.cpp new file mode 100644 index 000000000..b2f157a4a --- /dev/null +++ b/runtime/test/d3d12_uint_clear_test.cpp @@ -0,0 +1,166 @@ + +// Compare integer RTV clears against native Windows D3D12/WARP, through D3D12 clear/copy/Map on both sides. +// No game data or shaders. Run explicitly (needs Vulkan hardware); LEONIDA_VK_VALIDATION=1 checks Vulkan usage. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include +#include +#include +#include +#include +#define CHECK(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ +} while (0) + +namespace { +template +struct Ref { + T* p = nullptr; + ~Ref() { if (p) p->Release(); } + T* operator->() const { return p; } +}; +struct Event { + HANDLE handle = CreateEventW(nullptr, FALSE, FALSE, nullptr); + ~Event() { if (handle) CloseHandle(handle); } +}; + +bool clear_and_read(ID3D12Device* device, DXGI_FORMAT format, unsigned bytes, const FLOAT* full, const FLOAT* part, + std::vector& pixels) { + Ref queue; + Ref allocator; + Ref list; + Ref fence; + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + constexpr UINT width = 5, height = 3; // Odd dimensions expose incorrect treatment of footprint padding. + Ref image, readback; + D3D12_HEAP_PROPERTIES heap_properties{}; + heap_properties.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_RESOURCE_DESC texture{}; + texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture.Width = width; + texture.Height = height; + texture.DepthOrArraySize = texture.MipLevels = 1; + texture.Format = format; + texture.SampleDesc.Count = 1; + texture.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + CHECK(SUCCEEDED(device->CreateCommittedResource(&heap_properties, D3D12_HEAP_FLAG_NONE, &texture, + D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, IID_PPV_ARGS(&image.p)))); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT placed{}; + UINT64 total = 0; + device->GetCopyableFootprints(&texture, 0, 1, 0, &placed, nullptr, nullptr, &total); + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = total; + buffer.Height = buffer.SampleDesc.Count = 1; + buffer.DepthOrArraySize = buffer.MipLevels = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + heap_properties.Type = D3D12_HEAP_TYPE_READBACK; + CHECK(SUCCEEDED(device->CreateCommittedResource(&heap_properties, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p)))); + Ref heap; + const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&heap.p)))); + const auto handle = heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(image.p, nullptr, handle); + list->ClearRenderTargetView(handle, full, 0, nullptr); + const D3D12_RECT rect{1, 1, 4, 3}; + list->ClearRenderTargetView(handle, part, 1, &rect); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = image.p; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &barrier); + D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; + src.pResource = image.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = placed; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + CHECK(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(queue->Signal(fence.p, 1))); + Event event; + CHECK(event.handle); + CHECK(SUCCEEDED(fence->SetEventOnCompletion(1, event.handle))); + CHECK(WaitForSingleObject(event.handle, 5000) == WAIT_OBJECT_0); + void* mapped = nullptr; + const D3D12_RANGE range{0, SIZE_T(total)}; + CHECK(SUCCEEDED(readback->Map(0, &range, &mapped)) && mapped); + pixels.resize(width * height * bytes); + for (UINT y = 0; y < height; ++y) + std::memcpy(pixels.data() + y * width * bytes, + static_cast(mapped) + y * placed.Footprint.RowPitch, width * bytes); + const D3D12_RANGE none{}; + readback->Unmap(0, &none); + return true; +} +} // namespace + +int main() { + vktest::Device vk; + if (!vk.create()) return 1; + const unsigned errors_before = vk.validation_errors(); + unsigned cases_checked = 0; + { + Ref ours, host; + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; + Ref factory; + Ref warp; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) || + FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p))) || + FAILED(D3D12CreateDevice(warp.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) { + std::fprintf(stderr, "WARP reference unavailable: differential test cannot run\n"); + return 1; + } + const float nan = std::numeric_limits::quiet_NaN(), inf = std::numeric_limits::infinity(); + const std::array values[] = { + {1, 2, 3, 4}, {1.5f, 2.5f, 3.5f, 4.5f}, {-1, -0.0f, 254.5f, 255.5f}, + {256, 65536, 16777216, 4294967296.0f}, {nan, inf, -inf, 0.5f}, + {0.499f, 0.501f, 1.499f, 1.501f}, {4294967040.0f, std::numeric_limits::max(), 255, 0} + }; + const std::pair formats[] = { + {DXGI_FORMAT_R8G8B8A8_UINT, 4}, {DXGI_FORMAT_R32_UINT, 4}, {DXGI_FORMAT_R32G32B32A32_UINT, 16} + }; + for (const auto& [format, bytes] : formats) { + for (unsigned i = 0; i < std::size(values); ++i) { + // Different colours outside and inside the rectangle exercise both Vulkan clear paths. + const auto& full = values[i]; + const auto& part = values[(i + 1) % std::size(values)]; + std::vector actual, expected; + if (!clear_and_read(ours.p, format, bytes, full.data(), part.data(), actual) || + !clear_and_read(host.p, format, bytes, full.data(), part.data(), expected)) return 1; + if (actual != expected) { + for (std::size_t b = 0; b < actual.size(); ++b) { + if (actual[b] != expected[b]) { + std::fprintf(stderr, "format %d case %u byte %zu: Vulkan %02x, WARP %02x\n", + int(format), i, b, unsigned(actual[b]), unsigned(expected[b])); + break; + } + } + return 1; + } + ++cases_checked; + } + } + } // Destroy the D3D12 objects before checking the Vulkan validation counter. + if (vk.validation_errors() != errors_before) return 1; + std::printf("UINT RTV clears: %u full/rectangle readbacks matched WARP on three formats\n", cases_checked); + return 0; +} From fe8cd6bc729c8d02e8f6f7858d37f12cdcdf1583 Mon Sep 17 00:00:00 2001 From: Rayhan Robin Date: Sat, 21 Nov 2026 16:53:41 -0600 Subject: [PATCH 36/53] Tools: reject out-of-range --start/--limit in RPF index tools Adds the #283 argparse validators to anim_index, rbf0_index, restofworld_index and rpf9_carve: --start >= 0, --limit >= 1 (decimal or 0x hex), and --max-inflate >= 1 in restofworld_index. Bad ranges now exit 2 before any scan or output instead of silently scanning everything, less, or nothing. Synthetic CLI tests in all four test files; docs notes for each tool. New item claimed in #156. AI-assisted (OpenCode). --- docs/animation.md | 4 +++- docs/rbf0.md | 3 +++ docs/restofworld.md | 3 +++ docs/rpf.md | 3 +++ tests/test_anim_index.py | 12 ++++++++++++ tests/test_rbf0_index.py | 28 ++++++++++++++++++++++++++++ tests/test_restofworld_index.py | 13 +++++++++++++ tests/test_rpf9_carve.py | 27 +++++++++++++++++++++++++++ tools/anim_index.py | 26 ++++++++++++++++++++++++-- tools/rbf0_index.py | 26 ++++++++++++++++++++++++-- tools/restofworld_index.py | 28 +++++++++++++++++++++++++--- tools/rpf9_carve.py | 26 ++++++++++++++++++++++++-- 12 files changed, 189 insertions(+), 10 deletions(-) diff --git a/docs/animation.md b/docs/animation.md index 8d082eb24..8fa1a27dc 100644 --- a/docs/animation.md +++ b/docs/animation.md @@ -390,7 +390,9 @@ python -I tools/anim_index.py \anim-carve \anim-index.json ``` `tools/anim_index.py` reports `MoVE`, `0DRP`, `pack:/`, `SKEL_`, `RBF0`, `PSIN`, type-hash and 2/3 clip headers, -plus `raw:` for anything it does not recognise. It writes no payloads. +plus `raw:` for anything it does not recognise. It writes no payloads. `--start` must be 0 or more and +`--limit` at least 1 (decimal or `0x` hex); an out-of-range value stops with a one-line error and exit code 2 +before an index is written. ## No-sharing rule diff --git a/docs/rbf0.md b/docs/rbf0.md index 6c2dcfd1a..5ccdb5a8a 100644 --- a/docs/rbf0.md +++ b/docs/rbf0.md @@ -470,6 +470,9 @@ python -I tests/test_rbf0_index.py python -I tests/test_rbf0_tree.py ``` +`--start` must be 0 or more and `--limit` at least 1 (decimal or `0x` hex); an out-of-range value stops with a +one-line error and exit code 2 before an index is written. + The JSON summary carries the corpus totals used above (`streams`, `compressed_bytes`, `inflated_bytes`, `rbf0.resources`, `rbf0.multi_chunk`, `rbf0.by_root`, `rbf0.size_buckets`, record counts, string categories and keyword occurrences), so the numbers can be re-measured without committing an index. `--all-strings` writes the diff --git a/docs/restofworld.md b/docs/restofworld.md index 2c1a3058b..8ed52bd44 100644 --- a/docs/restofworld.md +++ b/docs/restofworld.md @@ -338,6 +338,9 @@ python -I tools/restofworld_index.py \index.json python -I tests/test_restofworld_index.py ``` +`--start` must be 0 or more, and `--limit` and `--max-inflate` at least 1 (decimal or `0x` hex). An out-of-range +value stops with a one-line error and exit code 2 before an index is written. + For the map/meta split, run the `world_index.py` from `docs/world.md` over the same archive; it reports `maps`, `meta`, `entities` and the `0x7a` version without decoding geometry. The index tool walks readable streams; the nine `RSC8` headers in the story-rest unread gap come from a raw-file scan, not from the diff --git a/docs/rpf.md b/docs/rpf.md index 883da7331..daabf3aab 100644 --- a/docs/rpf.md +++ b/docs/rpf.md @@ -25,6 +25,9 @@ The walker starts at `--start` or the header's data offset, finds a zlib header magic, inflates the stream, and continues after the bytes it actually consumed. `--index-only` records the streams without writing the inflated files; `--limit` bounds a sample; `--start` starts at a known offset. +`--start` must be 0 or more and `--limit` at least 1 (decimal or `0x` hex). An out-of-range value stops with a +one-line error and exit code 2 before any output is written, rather than silently scanning everything or nothing. + `/index.json` contains: - `summary`: archive, files, compressed/inflated bytes, Bink 2 bytes/files, zero padding, unread bytes, span; diff --git a/tests/test_anim_index.py b/tests/test_anim_index.py index 59fce7191..0e59e4d06 100644 --- a/tests/test_anim_index.py +++ b/tests/test_anim_index.py @@ -239,6 +239,18 @@ class ArchiveTest(unittest.TestCase): self.assertEqual(doc["summary"]["files"], len(PAYLOADS)) self.assertEqual(len(doc["files"]), len(PAYLOADS)) + def test_bad_scan_arguments_fail_before_an_index_is_written(self): + for flag, value, message in (("--start", "-1", "must be 0 or more"), + ("--limit", "0", "must be at least 1"), + ("--limit", "-100", "must be at least 1")): + out = os.path.join(self.root, "bad.json") + p = subprocess.run([sys.executable, "-I", TOOL, self.rpf, out, "--quiet", flag, value], + capture_output=True, text=True, encoding="utf-8", errors="replace") + self.assertEqual(p.returncode, 2, p.stderr) + self.assertIn(message, p.stderr) + self.assertNotIn("Traceback", p.stderr) + self.assertFalse(os.path.exists(out)) + def test_cli(self): out = os.path.join(self.root, "cli.json") p = subprocess.run([sys.executable, "-I", TOOL, self.rpf, out, "--quiet"], diff --git a/tests/test_rbf0_index.py b/tests/test_rbf0_index.py index d4d8ababa..e5faa0991 100644 --- a/tests/test_rbf0_index.py +++ b/tests/test_rbf0_index.py @@ -7,6 +7,7 @@ Every byte here is built by the test. No game file, game asset path or game name import csv import json import os +import subprocess import struct import sys import tempfile @@ -14,6 +15,7 @@ import unittest import zlib ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOL = os.path.join(ROOT, "tools", "rbf0_index.py") sys.path.insert(0, os.path.join(ROOT, "tools")) import rbf0_index # noqa: E402 @@ -201,6 +203,32 @@ class JoinTest(unittest.TestCase): self.assertEqual(summary["streams"], 2) +class ArgumentTest(unittest.TestCase): + """Out-of-range scan arguments are refused before anything is written.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = self.tmp.name + self.rpf = os.path.join(self.root, "one.rpf") + with open(self.rpf, "wb") as f: + f.write(b"RBF0" + struct.pack(" int: ap = argparse.ArgumentParser() ap.add_argument("archive") ap.add_argument("out") - ap.add_argument("--start", type=int) - ap.add_argument("--limit", type=int) + ap.add_argument("--start", type=offset) + ap.add_argument("--limit", type=byte_count) ap.add_argument("--index-only", action="store_true") a = ap.parse_args() below_normal() From 02c89a380b9271af7683009040651b9b45165c88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20K=C5=99=C3=AD=C5=BE?= <76481827+patrikloveicyl@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:48:02 +0100 Subject: [PATCH 37/53] bink_index.py: one line end per CSV row on stdout; a missing target is an error, not a traceback The CSV written to stdout (the default output) used csv's "\r\n" on a text stream that already turns "\n" into the platform line end, so every row ended "\r\r\n" on Windows and a redirected index read as one blank row after each row. The stdout writer now uses lineterminator="\n", as awc_manifest.py does; --out files were already right. A target that does not exist ended in a FileNotFoundError traceback from os.path.getsize; it now prints an error and exits 2, as awc_manifest.py does. Tests: a stdout stream that writes "\r\n" like Windows' (so the check also runs on Linux CI) and the missing-target exit code; both fail without the fix. --- tests/test_bink_index.py | 33 +++++++++++++++++++++++++++++++++ tools/bink_index.py | 7 ++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/tests/test_bink_index.py b/tests/test_bink_index.py index 20f7ca146..7e2514ee4 100644 --- a/tests/test_bink_index.py +++ b/tests/test_bink_index.py @@ -2,8 +2,10 @@ python -I tests/test_bink_index.py """ +import contextlib import csv import importlib.util +import io import json import os import struct @@ -116,5 +118,36 @@ class TestScanAndWrite(unittest.TestCase): self.assertNotIn("decodes", doc["streams"][0]) +class TestCommandLine(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.path = os.path.join(self.tmp.name, "one.bk2") + with open(self.path, "wb") as fh: + fh.write(make_stream(frames=7)) + + def tearDown(self): + self.tmp.cleanup() + + def test_csv_on_stdout_has_one_line_end_per_row(self): + # A text stream that writes "\n" as "\r\n", as Windows' stdout does, on any platform. + raw = io.BytesIO() + out = io.TextIOWrapper(raw, encoding="utf-8", newline="\r\n") + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(bink.main([self.path]), 0) + out.flush() + data = raw.getvalue() + self.assertNotIn(b"\r\r\n", data) + rows = list(csv.reader(io.StringIO(data.decode("utf-8"), newline=""))) + self.assertEqual(len(rows), 2) # header and the one stream, no blank rows + self.assertEqual(rows[0][:len(bink.BASE_FIELDS)], bink.BASE_FIELDS) + + def test_missing_target_is_an_error_not_a_traceback(self): + missing = os.path.join(self.tmp.name, "nonexistent.bk2") + err = io.StringIO() + with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(bink.main([missing]), 2) + self.assertIn("no such file or directory", err.getvalue()) + + if __name__ == "__main__": unittest.main() diff --git a/tools/bink_index.py b/tools/bink_index.py index 5d633c4c7..92597ea2e 100644 --- a/tools/bink_index.py +++ b/tools/bink_index.py @@ -282,6 +282,9 @@ def main(argv=None): ap.add_argument("--format", choices=["csv", "json"], help="inferred from --out if omitted") ap.add_argument("--probe", action="store_true", help="run ffprobe on each stream") a = ap.parse_args(argv) + if not os.path.exists(a.target): + print(f"bink_index: error: {a.target}: no such file or directory", file=sys.stderr) + return 2 rows, summary = scan_target(a.target) probe = False @@ -309,7 +312,9 @@ def main(argv=None): "streams": [_flat(r, fields) for r in rows]}, indent=1)) else: fields = BASE_FIELDS + (PROBE_FIELDS if probe else []) - writer = csv.DictWriter(sys.stdout, fieldnames=fields) + # stdout is a text stream that already turns "\n" into the platform's line end; + # csv's default "\r\n" would come out as "\r\r\n" on Windows + writer = csv.DictWriter(sys.stdout, fieldnames=fields, lineterminator="\n") writer.writeheader() for row in rows: writer.writerow(_flat(row, fields)) From ff45269e683add2660ca7441f9642701ed6d897f Mon Sep 17 00:00:00 2001 From: IAmNotSiob <273832158+IAmNotSiob@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:54:13 +0100 Subject: [PATCH 38/53] tiny_game: _CRT_SECURE_NO_WARNINGS for its plain fopen (MSVC C4996) --- runtime/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 04dc0276b..4f16f35dc 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -224,7 +224,7 @@ if(BUILD_TESTING) ) add_executable(tiny_game test/fixtures/tiny_game.cpp) target_link_libraries(tiny_game PRIVATE xgameruntime_stub) - target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) # plain fopen, as games use target_compile_options(tiny_game PRIVATE /W4 /permissive- /utf-8 /EHsc) set_target_properties(tiny_game PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" From 9ef27a905987d5f1ea85dbdef29f04c3249cc8a3 Mon Sep 17 00:00:00 2001 From: fearkov <289226582+fearkov@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:53:30 -0400 Subject: [PATCH 39/53] Translator: s_min_i32 and s_max_i32 leave SCC at 0 on a tie --- tools/rdna2spirv.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index f4df058a5..b9e2bd526 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -2677,10 +2677,12 @@ class Gen: r = self.tmp() self.emit(f"{r} = OpExtInst %uint %glsl {'SMin' if 'min' in op else 'SMax'} {x} {y}") self.dst(a[0], r) - # SCC = (src0 selected) per ISA; select-src0 iff src0 <= src1 (min) / >= (max) + # SCC = 1 when S0 is the one chosen: the ISA's D = S0 < S1 ? S0 : S1 (min) / S0 > S1 ? S0 : S1 (max) + # picks S1 on a tie, so SCC = S0 < S1 / S0 > S1, compared signed (as s_min_u32/s_max_u32 do unsigned). + # Until 2026-11-21 equal operands set SCC to 1. c, z = self.tmp(), self.tmp() xi, yi = self.as_int(x), self.as_int(y) - self.emit(f"{c} = {'OpSLessThanEqual' if 'min' in op else 'OpSGreaterThanEqual'} %bool {xi} {yi}") + self.emit(f"{c} = {'OpSLessThan' if 'min' in op else 'OpSGreaterThan'} %bool {xi} {yi}") self.emit(f"{z} = OpSelect %uint {c} {self.cu(1)} {self.cu(0)}") self.emit(f"OpStore %scc {z}") elif op == "v_fma_f16": From adbe6fd42e38e0d1109b550962b691414ccb500d Mon Sep 17 00:00:00 2001 From: fearkov <289226582+fearkov@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:53:30 -0400 Subject: [PATCH 40/53] Tests: ps_scc_minmax checks SCC of s_min and s_max on a tie --- runtime/test/shaders/check.py | 3 +- runtime/test/shaders/ps_scc_minmax.asm | 47 +++++++++++++++++++ scripts/run_gpu_tests.py | 1 + tests/semantic/README.md | 3 +- .../semantic/fixtures/disasm/ps_scc_minmax.s | 43 +++++++++++++++++ tests/semantic/regen_fixtures.py | 2 +- tests/semantic/test_value_semantics.py | 25 ++++++++++ 7 files changed, 121 insertions(+), 3 deletions(-) create mode 100644 runtime/test/shaders/ps_scc_minmax.asm create mode 100644 tests/semantic/fixtures/disasm/ps_scc_minmax.s diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 2b3fed284..092834407 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -65,7 +65,8 @@ PIXEL_BITS = {"ps_legacy_mul": (0, 0, 0, 0x40c00000), "ps_ops7": (0x00ff8077, 0xff0000ff, 0x89abcdef, 0x00070003), "ps_ops8": (0x80000000, 0xffffffff, 0x000f100e, 0x0f0f0f1f), "ps_scc": (1, 1, 3, 0x80000000), "ps_sdwa": (0x000000f1, 0xfffefff2, 0x3c003344, 0xfff70000), - "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0)} + "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), + "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203)} # Pixel shaders that read memory: vk_harness puts this V# in s[0:3] and seeds the heap it points at, as # tests/semantic/test_value_semantics.py does for the interpreter. PIXEL_ENV = {"ps_vcc_x2": {"VKH_SGPRS": "0x1000,0,16,0", "VKH_HEAP": "0x1000=0x11223344,0x1004=0x55667788"}} diff --git a/runtime/test/shaders/ps_scc_minmax.asm b/runtime/test/shaders/ps_scc_minmax.asm new file mode 100644 index 000000000..c14c1f5db --- /dev/null +++ b/runtime/test/shaders/ps_scc_minmax.asm @@ -0,0 +1,47 @@ +; SCC from s_min_i32/s_max_i32 (signed) and s_min_u32/s_max_u32: 1 only when S0 is strictly smaller (min) or larger +; (max), since D = S0 < S1 ? S0 : S1 picks S1 on a tie. Per word: byte 0 = the op's result on equal operands, +; byte 1 = s_cselect 1/2 after that tie (2: SCC 0), byte 2 = s_cselect 3/4 after a pair that -1 vs 1 decides by +; signedness (3: SCC 1). A tie that set SCC gives byte 1 = 1, a compare of the wrong signedness byte 2 = 4. +; Expected mrt0 bits: 0x00030205, 0x00030207, 0x00030209, 0x00030203 +s_mov_b32 s0, 5 +s_min_i32 s1, s0, 5 +s_cselect_b32 s2, 1, 2 +s_min_i32 s3, -1, 1 +s_cselect_b32 s4, 3, 4 +s_lshl_b32 s2, s2, 8 +s_lshl_b32 s4, s4, 16 +s_or_b32 s1, s1, s2 +s_or_b32 s1, s1, s4 +s_mov_b32 s0, 7 +s_max_i32 s5, s0, 7 +s_cselect_b32 s6, 1, 2 +s_max_i32 s7, 1, -1 +s_cselect_b32 s8, 3, 4 +s_lshl_b32 s6, s6, 8 +s_lshl_b32 s8, s8, 16 +s_or_b32 s5, s5, s6 +s_or_b32 s5, s5, s8 +s_mov_b32 s0, 9 +s_min_u32 s9, s0, 9 +s_cselect_b32 s10, 1, 2 +s_min_u32 s11, 1, -1 +s_cselect_b32 s12, 3, 4 +s_lshl_b32 s10, s10, 8 +s_lshl_b32 s12, s12, 16 +s_or_b32 s9, s9, s10 +s_or_b32 s9, s9, s12 +s_mov_b32 s0, 3 +s_max_u32 s13, s0, 3 +s_cselect_b32 s14, 1, 2 +s_max_u32 s15, -1, 1 +s_cselect_b32 s16, 3, 4 +s_lshl_b32 s14, s14, 8 +s_lshl_b32 s16, s16, 16 +s_or_b32 s13, s13, s14 +s_or_b32 s13, s13, s16 +v_mov_b32_e32 v0, s1 +v_mov_b32_e32 v1, s5 +v_mov_b32_e32 v2, s9 +v_mov_b32_e32 v3, s13 +exp mrt0 v0, v1, v2, v3 done vm +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 1ce87832b..f884a4734 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -666,6 +666,7 @@ def run_suite(a, work: str) -> int: "ps_ops7": (0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003), "ps_ops8": (0x80000000, 0xFFFFFFFF, 0x000F100E, 0x0F0F0F1F), "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), + "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203), } if name in const_wants: ok, detail = check_pixel_const(raw, const_wants[name]) diff --git a/tests/semantic/README.md b/tests/semantic/README.md index bf8b9a81e..47621dc55 100644 --- a/tests/semantic/README.md +++ b/tests/semantic/README.md @@ -18,7 +18,8 @@ What they check (`tools/rdna2spirv.py`, pixel shaders plus one compute shader): are also asserted there, duplicating the matching `test_ps_semantics.py` cases. As above, constants are written by hand and recomputed by plain-Python references checked against each other. `cs_fmt_1010102` runs as compute too and asserts 16 dwords: 10:10:10:2 words read through formats 50 and 44 (from the V# and from - tbuffer's own format) and stored in both. + tbuffer's own format) and stored in both. `ps_scc_minmax` asserts SCC after `s_min`/`s_max` `_i32`/`_u32`: + 0 on a tie, and 1 on a pair (-1 against 1) that only the right signedness orders that way. - `test_interp.py` tests the interpreter against the SPIR-V / GLSL.std.450 definitions. The interpreter raises `UnsupportedConstruct` for anything it does not model instead of approximating it. It can seed Input variables, PushConstant words and a flat physical-address memory map for the tests above. diff --git a/tests/semantic/fixtures/disasm/ps_scc_minmax.s b/tests/semantic/fixtures/disasm/ps_scc_minmax.s new file mode 100644 index 000000000..033ac4416 --- /dev/null +++ b/tests/semantic/fixtures/disasm/ps_scc_minmax.s @@ -0,0 +1,43 @@ +; ps_scc_minmax test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/ps_scc_minmax.asm + s_mov_b32 s0, 5 + s_min_i32 s1, s0, 5 + s_cselect_b32 s2, 1, 2 + s_min_i32 s3, -1, 1 + s_cselect_b32 s4, 3, 4 + s_lshl_b32 s2, s2, 8 + s_lshl_b32 s4, s4, 16 + s_or_b32 s1, s1, s2 + s_or_b32 s1, s1, s4 + s_mov_b32 s0, 7 + s_max_i32 s5, s0, 7 + s_cselect_b32 s6, 1, 2 + s_max_i32 s7, 1, -1 + s_cselect_b32 s8, 3, 4 + s_lshl_b32 s6, s6, 8 + s_lshl_b32 s8, s8, 16 + s_or_b32 s5, s5, s6 + s_or_b32 s5, s5, s8 + s_mov_b32 s0, 9 + s_min_u32 s9, s0, 9 + s_cselect_b32 s10, 1, 2 + s_min_u32 s11, 1, -1 + s_cselect_b32 s12, 3, 4 + s_lshl_b32 s10, s10, 8 + s_lshl_b32 s12, s12, 16 + s_or_b32 s9, s9, s10 + s_or_b32 s9, s9, s12 + s_mov_b32 s0, 3 + s_max_u32 s13, s0, 3 + s_cselect_b32 s14, 1, 2 + s_max_u32 s15, -1, 1 + s_cselect_b32 s16, 3, 4 + s_lshl_b32 s14, s14, 8 + s_lshl_b32 s16, s16, 16 + s_or_b32 s13, s13, s14 + s_or_b32 s13, s13, s16 + v_mov_b32_e32 v0, s1 + v_mov_b32_e32 v1, s5 + v_mov_b32_e32 v2, s9 + v_mov_b32_e32 v3, s13 + exp mrt0 v0, v1, v2, v3 done vm + s_endpgm diff --git a/tests/semantic/regen_fixtures.py b/tests/semantic/regen_fixtures.py index 22f859766..bdc316c6f 100644 --- a/tests/semantic/regen_fixtures.py +++ b/tests/semantic/regen_fixtures.py @@ -17,7 +17,7 @@ ROOT = os.path.dirname(os.path.dirname(HERE)) ASM_DIR = os.path.join(ROOT, "runtime", "test", "shaders") FIXTURE_DIR = os.path.join(HERE, "fixtures", "disasm") SHADERS = ("ps_sdwa", "ps_ops", "ps_ops2", "ps_ops3", "ps_ops4", "ps_ops5", "ps_ops6", "ps_ops7", "ps_ops8", - "ps_legacy_mul", "ps_vcc_x2", "ps_flat", "cs_bounds", "cs_fmt_1010102") + "ps_legacy_mul", "ps_vcc_x2", "ps_flat", "ps_scc_minmax", "cs_bounds", "cs_fmt_1010102") def render(name): diff --git a/tests/semantic/test_value_semantics.py b/tests/semantic/test_value_semantics.py index c7ea121b9..34db5ac9b 100644 --- a/tests/semantic/test_value_semantics.py +++ b/tests/semantic/test_value_semantics.py @@ -25,6 +25,7 @@ ISA semantics used (AMD RDNA2 ISA reference, VALU/VOP3/VOP3P chapters): v_bcnt_u32_b32 D = popcount(S0) + S1. v_ffbl_b32/ffbh_u32 index of the lowest set bit / count of leading zeros; 0xffffffff when S0 = 0. v_xad_u32/add3_u32 D = (S0 ^ S1) + S2 / D = S0 + S1 + S2, both mod 2^32. + s_min/max_i32/u32 D = S0 < S1 ? S0 : S1 (max: >), SCC = 1 when S0 is chosen, so a tie gives S1 and SCC 0. The appended cases for ps_ops5/ps_ops6 also pin the op_sel source-half selection for packed shifts, which the GPU-checked ps_ops4 does not exercise. cs_bounds (compute) pins the buffer num_records bounds checks: an @@ -47,6 +48,7 @@ EXPECTED_OPS7 = [0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003] EXPECTED_OPS8 = [0x80000000, 0xFFFFFFFF, 0x000F100E, 0x0F0F0F1F] EXPECTED_VCC_X2 = [0x11223344, 0x55667788, 0x00000000, 0x00000000] EXPECTED_FLAT = [0x00000101, 0x00000102, 0x3F000000, 0x3E800000] +EXPECTED_SCC_MINMAX = [0x00030205, 0x00030207, 0x00030209, 0x00030203] EXPECTED_BOUNDS = {0x00: 0x12345678, 0x04: 0x12345678, 0x08: 0x00000000, 0x0C: 0xEEEEEEEE} EXPECTED_FMT_1010102 = {0x00: 0x00000000, 0x04: 0x3F800000, 0x08: 0x00000000, 0x0C: 0x3F800000, 0x10: 0x3F800000, 0x14: 0x00000000, 0x18: 0x3F800000, 0x1C: 0x00000000, @@ -163,6 +165,23 @@ def reference_ops8(): (xad + 16 + m) & m] # v_ffbh_u32(0) = 0xffffffff +def reference_scc_minmax(): + def minmax(op, x, y): + """(D, SCC) of s_min/s_max _i32/_u32 on 32-bit words: SCC = 1 only when S0 is the one chosen.""" + kx, ky = (_s(x), _s(y)) if op.endswith("i32") else (x, y) + pick = kx < ky if op.startswith("min") else kx > ky + return x if pick else y, int(pick) + + words = [] + m1 = 0xFFFFFFFF # the inline constant -1 as a register word + for op, tie, strict in (("min_i32", 5, (m1, 1)), ("max_i32", 7, (1, m1)), + ("min_u32", 9, (1, m1)), ("max_u32", 3, (m1, 1))): + d, scc_tie = minmax(op, tie, tie) + _, scc_strict = minmax(op, *strict) + words.append(d | ((1 if scc_tie else 2) << 8) | ((3 if scc_strict else 4) << 16)) + return words + + def reference_vcc_x2(): return [0x11223344, 0x55667788, 0, 0] @@ -247,6 +266,7 @@ class OracleTests(unittest.TestCase): self.assertEqual(reference_ops8(), EXPECTED_OPS8) self.assertEqual(reference_vcc_x2(), EXPECTED_VCC_X2) self.assertEqual(reference_flat(), EXPECTED_FLAT) + self.assertEqual(reference_scc_minmax(), EXPECTED_SCC_MINMAX) self.assertEqual(reference_bounds(), EXPECTED_BOUNDS) self.assertEqual(reference_fmt_1010102(), EXPECTED_FMT_1010102) @@ -287,6 +307,11 @@ class TranslatorValueSemantics(unittest.TestCase): # v_ffbh_u32(0) = -1 feeding a wrapping v_add3_u32, and v_xad_u32. self.check("ps_ops8", EXPECTED_OPS8) + def test_s_min_max_scc_on_a_tie(self): + # Equal operands give S1 and SCC 0 for s_min/s_max _i32 and _u32; -1 vs 1 sets SCC only when compared + # with the op's own signedness. A tie that set SCC turns byte 1 of a word from 2 into 1. + self.check("ps_scc_minmax", EXPECTED_SCC_MINMAX) + def test_s_buffer_load_dwordx2_into_vcc(self): # The V# in s[0:3] points at 0x1000; the two dwords must come back in vcc_lo and vcc_hi, not be lost. push = [0x1000, 0, 16, 0] + [0] * 28 From dd4c763c111c659291696ff421906058cb1b60c1 Mon Sep 17 00:00:00 2001 From: fearkov <289226582+fearkov@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:53:39 -0400 Subject: [PATCH 41/53] Docs: the SCC row covers s_min_i32 and s_max_i32 --- docs/design.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design.md b/docs/design.md index 0cdfbb858..d6b4b5d2f 100644 --- a/docs/design.md +++ b/docs/design.md @@ -239,7 +239,7 @@ How the generated SPIR-V expects the runtime to work: | Wave size | **Most of the game's shaders are wave64: 21,545 of 26,503.** An earlier marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks) counted 9,930 of 12,101 PS, 8,666 of 9,282 mesh shaders, 1,115 of 2,236 VS and 923 of 2,689 CS. 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); 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. 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+`. 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. | | Geometry shaders | All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. 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. | -| SCC from scalar ALU | `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32` and `s_lshl/lshr_b32` set SCC = result ≠ 0, `s_add/sub_i32` and `s_addk_i32` set it to signed overflow, `s_min_u32`/`s_max_u32` to S0 < S1 / S0 > S1. **Before this fix these ops left SCC unchanged**, so a following `s_cbranch_scc*` read a stale flag. 32-bit scalar shifts now mask the amount to 5 bits. GPU-checked with `runtime/test/shaders/ps_scc.asm`. | +| SCC from scalar ALU | `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32` and `s_lshl/lshr_b32` set SCC = result ≠ 0, `s_add/sub_i32` and `s_addk_i32` set it to signed overflow, `s_min_u32`/`s_max_u32` to S0 < S1 / S0 > S1, and `s_min_i32`/`s_max_i32` to the same compared signed: SCC is 1 when S0 is the one chosen, and a tie chooses S1 (RDNA2 ISA, S_MIN_I32: D = S0 < S1 ? S0 : S1, SCC = 1 if S0 is chosen). **Before this fix these ops left SCC unchanged**, so a following `s_cbranch_scc*` read a stale flag, and until 2026-11-21 `s_min_i32`/`s_max_i32` set SCC on a tie. 32-bit scalar shifts now mask the amount to 5 bits. GPU-checked with `runtime/test/shaders/ps_scc.asm` and `ps_scc_minmax.asm` (NVIDIA GeForce RTX 2060 SUPER, Linux, driver 620.70.06: 4096/4096 pixels exact, and all 4096 differ with the old translator). | | Far branches | `s_getpc_b64; s_add_u32 K; s_addc_u32 0/−1; s_setpc_b64` on the same pair is a branch beyond `s_branch`'s ±32K-dword range. It's folded into one branch to (address after `s_getpc`) + K before CFG construction. | | Buffer format stores | `buffer_store_format_*` and `_d16_*` encode every format the loads decode (the same FORMATS table: f32/u32, f16, unorm/snorm 8/16/10-10-10-2, uint 8/16). 1–2-byte elements are merged into their dword with atomic and/or so neighbours are kept. d16 data is unpacked first (f16 → float for float kinds, 16-bit integers for integer kinds). Before this, only four f32 formats, rgba16f and rgba8 unorm were stored, and everything else silently stored nothing. GPU-checked with `runtime/test/shaders/cs_store.asm` (rgba8 unorm, R10G10B10A2 (`2_10_10_10`), two r16f halves of one dword, d16 rgba16f: exact, neighbours untouched). `buffer_load_format_d16_*` packs pairs the same way. | | Other additions | `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at mip round(LOD) in gather order, coordinates clamped to the edge (**approximation**: the sampler's wrap/mirror isn't reproduced at the border). `image_gather4_lz_o`: `OpImageGather … Offset`. `image_store` on 1D (bindings 17–19, `Image1D`) and with a16 coordinates. `ds_swizzle BITMASK_PERM` ("pippi" masks; GPU-checked). `v_add_f64`, `v_cvt_f32_f64` (`Float64`). `v_mul/mad_i32_i24`, `v_alignbyte_b32`, `v_xnor_b32`, `v_ffbh_i32`, `v_swap_b32`, `s_abs_i32`, `s_bfm_b32/b64`, 64-bit ordered and `v_cmpx` compares, 16-bit compares, 8/16-bit global loads, `neg(…)` constant operands (GPU-checked where listed in `runtime/test/shaders`). | From 257e3856cc62ce5fad18d8d7f48f585bf635f93e Mon Sep 17 00:00:00 2001 From: Parakeet-Wheat <227350947+Parakeet-Wheat@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:54:18 +1100 Subject: [PATCH 42/53] Runtime: GetResourceAllocationInfo on the Vulkan device (D3D-23) GetResourceAllocationInfo, GetResourceAllocationInfo1 and GetResourceAllocationInfo2 were generated stubs. Buffers take their width rounded up to 64 KiB. A texture's size is what its VkImage needs (vkGetDeviceImageMemoryRequirements, or a throwaway image without it), rounded up to its D3D12 alignment: 64 KiB, 4 MiB with MSAA, or the small alignment the description asks for. A 4 KiB request that doesn't qualify is invalid, as on the PC runtime; the MSAA 64 KiB one has no size limit there. Texture creation and these queries share one VkImageCreateInfo. d3d12_vulkan_device_test compares buffer sizes, alignments and invalid descriptions with the host PC runtime, and checks the per-resource layout of the Device4/Device8 variants. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 10 +- runtime/shims/d3d12_vulkan_device.cpp | 224 +++++++++++++++++++--- runtime/test/d3d12_vulkan_device_test.cpp | 137 ++++++++++++- 3 files changed, 334 insertions(+), 37 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 2dc43ac00..d7602dfb2 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -602,7 +602,15 @@ The trace will enumerate them. arena's limits, not the console's. - `GetResourceAllocationInfo` and `GetCopyableFootprints`: implement D3D12's rules locally; the game uses them to suballocate and to lay out uploads. They are deterministic and public. Validate against a host D3D12 device in - tests if one is available; do not require one at runtime. + tests if one is available; do not require one at runtime. `GetResourceAllocationInfo` (and `1`/`2`): a buffer + takes its width rounded up to 64 KiB, aligned to 64 KiB. A texture's size is the memory its `VkImage` needs + (`vkGetDeviceImageMemoryRequirements`), rounded up to its D3D12 alignment. That alignment is 64 KiB, or 4 MiB with + MSAA. The small alignments (4 KiB, or 64 KiB with MSAA) apply only when the application asks for them. 4 KiB + also needs the texture to fit in 64 KiB and not be a render target or depth buffer; if it doesn't qualify, the + description is invalid (`UINT64_MAX`), as the PC runtime answers. The MSAA 64 KiB alignment has no size limit + on the PC runtime, so none here either. Texture sizes are the driver's on both runtimes, so only buffer sizes, + alignments and invalid descriptions are compared with the host. One known difference: a mip count beyond the + full chain is invalid here (Vulkan can't create it), while the PC runtime still answers with a size. ### 4.2 Resources, heaps, placed and reserved diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e3def8865..13f30ac8b 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -1,7 +1,8 @@ // A Vulkan-backed ID3D12Device (PC ABI) for the Xbox-ABI device proxy (d3d12_xs_device.cpp) to forward to. // Implemented: queues, allocators, command lists, fences, descriptor heaps, render-target and depth-stencil views, -// committed buffers and textures (2D, multisampled 2D, 3D), a few feature queries. Everything else is a generated stub that reports -// itself once. See docs/d3d12_vulkan.md section 4.1/4.2 for what each answer means and what is still open. +// committed buffers and textures (2D, multisampled 2D, 3D), allocation info, a few feature queries. Everything +// else is a generated stub that reports itself once. See docs/d3d12_vulkan.md section 4.1/4.2 for what each answer +// means and what is still open. #include "d3d12_com.h" #include "d3d12_stubs.h" // generated @@ -105,6 +106,33 @@ Format vulkan_format(DXGI_FORMAT format, bool depth) { } } +// The full mip chain's length for a texture this size. +UINT16 full_mips(UINT64 width, UINT height, UINT depth) { + UINT16 mips = 0; + for (UINT64 size = std::max({width, height, depth}); size; size >>= 1) ++mips; + return mips; +} + +// 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. +VkImageCreateInfo texture_create_info(const D3D12_RESOURCE_DESC& desc, const Format& format) { + const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; + info.flags = format.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0; + info.imageType = volume ? VK_IMAGE_TYPE_3D : VK_IMAGE_TYPE_2D; + info.format = format.format; + info.extent = {std::uint32_t(desc.Width), desc.Height, volume ? UINT(desc.DepthOrArraySize) : 1u}; + info.mipLevels = desc.MipLevels; + 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; + if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; + if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; + if (!(desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; + return info; +} + // What a device's children need from it, kept apart from the COM class so children can hold a plain pointer. struct DeviceState { VulkanDeviceInfo info; @@ -112,6 +140,7 @@ struct DeviceState { VkPhysicalDeviceMemoryProperties memory{}; PFN_vkGetPhysicalDeviceFormatProperties format_properties = nullptr; PFN_vkGetPhysicalDeviceImageFormatProperties image_format_properties = nullptr; + PFN_vkGetDeviceImageMemoryRequirements image_requirements = nullptr; // Vulkan 1.3 or VK_KHR_maintenance4 bool depth_usable(VkFormat format) const { VkFormatProperties properties{}; @@ -127,6 +156,42 @@ struct DeviceState { (properties.sampleCounts & image.samples); } + // The format a texture description is created with, D24S8's fallback included. + Format texture_format(const D3D12_RESOURCE_DESC& desc) const { + Format format = vulkan_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !depth_usable(format.format)) { + log_once("D24_UNORM_S8_UINT unavailable, using D32_SFLOAT_S8_UINT; format", desc.Format); + format.format = VK_FORMAT_D32_SFLOAT_S8_UINT; + } + return format; + } + + // The memory an image made from `create` needs, or false if the device can't make that image. + bool memory_requirements(const VkImageCreateInfo& create, VkMemoryRequirements& out) const { + VkImageFormatProperties limits{}; + if (!image_format_properties || + image_format_properties(info.physical, create.format, create.imageType, VK_IMAGE_TILING_OPTIMAL, + create.usage, create.flags, &limits) != VK_SUCCESS || + create.extent.width > limits.maxExtent.width || create.extent.height > limits.maxExtent.height || + create.extent.depth > limits.maxExtent.depth || create.mipLevels > limits.maxMipLevels || + create.arrayLayers > limits.maxArrayLayers || !(limits.sampleCounts & create.samples)) + return false; + if (image_requirements) { + VkDeviceImageMemoryRequirements query{VK_STRUCTURE_TYPE_DEVICE_IMAGE_MEMORY_REQUIREMENTS}; + query.pCreateInfo = &create; + VkMemoryRequirements2 result{VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; + image_requirements(info.device, &query, &result); + out = result.memoryRequirements; + return true; + } + auto& vk = context->vk; // without the query, a throwaway image + VkImage image = VK_NULL_HANDLE; + if (vk.vkCreateImage(info.device, &create, nullptr, &image) != VK_SUCCESS) return false; + vk.vkGetImageMemoryRequirements(info.device, image, &out); + vk.vkDestroyImage(info.device, image, nullptr); + return true; + } + // The first memory type with `required`, preferring one that also has `preferred`. VkDeviceMemory allocate(const VkMemoryRequirements& requirements, VkMemoryPropertyFlags required, VkMemoryPropertyFlags preferred) const { @@ -228,30 +293,9 @@ public: auto& vk = device_.context->vk; const bool volume = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const UINT depth = volume ? desc_.DepthOrArraySize : 1; - if (desc_.MipLevels == 0) { - UINT64 size = std::max({desc_.Width, desc_.Height, depth}); - UINT16 mips = 1; - while (size > 1) { - size >>= 1; - ++mips; - } - desc_.MipLevels = mips; - } - VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - info.flags = format.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0; - info.imageType = volume ? VK_IMAGE_TYPE_3D : VK_IMAGE_TYPE_2D; - info.format = format.format; - info.extent = {std::uint32_t(desc_.Width), desc_.Height, depth}; - info.mipLevels = desc_.MipLevels; - info.arrayLayers = volume ? 1 : desc_.DepthOrArraySize; - const std::uint32_t samples = std::max(1, desc_.SampleDesc.Count); - info.samples = VkSampleCountFlagBits(samples); - info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - if (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - if (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) - info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; - if (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; - if (!(desc_.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; + if (desc_.MipLevels == 0) desc_.MipLevels = full_mips(desc_.Width, desc_.Height, depth); + const VkImageCreateInfo info = texture_create_info(desc_, format); + const std::uint32_t samples = info.samples; if (samples > 1 && !device_.samples_usable(info)) { log_once("sample count not supported by the GPU for this format:", int(samples)); return E_INVALIDARG; @@ -343,6 +387,10 @@ public: info.get_instance_proc(info.instance, "vkGetPhysicalDeviceMemoryProperties")); if (!get_device || !state_.format_properties || !state_.image_format_properties || !memory_properties) return; memory_properties(info.physical, &state_.memory); + for (const char* name : {"vkGetDeviceImageMemoryRequirements", "vkGetDeviceImageMemoryRequirementsKHR"}) + if (!state_.image_requirements) + state_.image_requirements = + reinterpret_cast(get_device(info.device, name)); if (state_.info.max_push_constants_size == 0 && info.physical && info.get_instance_proc) { const auto get_props = reinterpret_cast( @@ -537,11 +585,7 @@ public: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)))) { hr = E_INVALIDARG; // D3D12: a multisampled texture is a single-mip 2D render target or depth-stencil } else { - Format format = vulkan_format(desc->Format, desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); - if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !state_.depth_usable(format.format)) { - log_once("D24_UNORM_S8_UINT unavailable, using D32_SFLOAT_S8_UINT; format", desc->Format); - format.format = VK_FORMAT_D32_SFLOAT_S8_UINT; - } + const Format format = state_.texture_format(*desc); if (format.format == VK_FORMAT_UNDEFINED) { log_once("texture format not supported yet:", desc->Format); hr = E_INVALIDARG; @@ -629,6 +673,33 @@ public: if (total) *total = end - base; } + // How much heap memory resources need and how to align them, for applications that suballocate heaps (section + // 4.1). Buffers follow D3D12's fixed rule. A texture's size is what the Vulkan image it becomes needs, rounded up + // to D3D12's alignment for it; the alignment itself is D3D12's, since placed textures bind their own memory + // (section 4.2). Several resources are laid out one after another, each at its own alignment. An invalid + // description gives SizeInBytes = UINT64_MAX, as on D3D12. d3d12_vulkan_device_test compares with the PC runtime. + D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo( + UINT, UINT count, const D3D12_RESOURCE_DESC* descs) override { + return place(count, descs, [&](UINT i) { return descs[i]; }, nullptr); + } + D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo1( + UINT, UINT count, const D3D12_RESOURCE_DESC* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) override { + return place(count, descs, [&](UINT i) { return descs[i]; }, each); + } + D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo2( + UINT, UINT count, const D3D12_RESOURCE_DESC1* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) override { + return place(count, descs, [&](UINT i) { + const D3D12_RESOURCE_DESC1& d = descs[i]; + if (d.SamplerFeedbackMipRegion.Width || d.SamplerFeedbackMipRegion.Height || + d.SamplerFeedbackMipRegion.Depth) { + log_once("GetResourceAllocationInfo2 sampler feedback not supported, format", d.Format); + return D3D12_RESOURCE_DESC{}; // an unknown dimension: invalid + } + return D3D12_RESOURCE_DESC{d.Dimension, d.Alignment, d.Width, d.Height, d.DepthOrArraySize, + d.MipLevels, d.Format, d.SampleDesc, d.Layout, d.Flags}; + }, each); + } + HRESULT STDMETHODCALLTYPE CheckFeatureSupport(D3D12_FEATURE feature, void* data, UINT size) override { log_once("CheckFeatureSupport feature", feature); if (!data) return E_INVALIDARG; @@ -755,6 +826,97 @@ public: private: IUnknown* identity() { return outer_ ? outer_ : static_cast(this); } + static constexpr D3D12_RESOURCE_ALLOCATION_INFO kInvalidAllocation{UINT64_MAX, + D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT}; + static UINT64 align_up(UINT64 value, UINT64 to) { return (value + to - 1) / to * to; } + + // Lays `count` resources out one after another; `each` (optional) gets every resource's offset, size and alignment. + template + D3D12_RESOURCE_ALLOCATION_INFO place(UINT count, const Desc* descs, Get get, + D3D12_RESOURCE_ALLOCATION_INFO1* each) { + D3D12_RESOURCE_ALLOCATION_INFO total{0, 0}; + bool failed = count && !descs; + for (UINT i = 0; i < count; ++i) { + const D3D12_RESOURCE_ALLOCATION_INFO one = failed ? kInvalidAllocation : allocation(get(i)); + failed = failed || one.SizeInBytes == UINT64_MAX; + if (failed) { + if (each) each[i] = {UINT64_MAX, one.Alignment, UINT64_MAX}; + continue; + } + const UINT64 offset = align_up(total.SizeInBytes, one.Alignment); + if (each) each[i] = {offset, one.Alignment, one.SizeInBytes}; + total = {offset + one.SizeInBytes, std::max(total.Alignment, one.Alignment)}; + } + return failed ? kInvalidAllocation : total; + } + + // One resource's size and alignment, or kInvalidAllocation for a description D3D12 (or this device) rejects. + D3D12_RESOURCE_ALLOCATION_INFO allocation(const D3D12_RESOURCE_DESC& desc) const { + constexpr UINT64 align_4k = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT, + align_64k = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, + align_msaa_64k = D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, + align_msaa_4m = D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT; + constexpr D3D12_RESOURCE_FLAGS attachment = + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { + if (!desc.Width || desc.Width > UINT64_MAX - align_64k || desc.Height != 1 || desc.DepthOrArraySize != 1 || + desc.MipLevels != 1 || desc.Format != DXGI_FORMAT_UNKNOWN || desc.SampleDesc.Count != 1 || + desc.SampleDesc.Quality != 0 || desc.Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR || + (desc.Alignment && desc.Alignment != align_64k) || (desc.Flags & attachment)) + return kInvalidAllocation; + return {align_up(desc.Width, align_64k), align_64k}; + } + const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + if (!volume && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) { + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_UNKNOWN) + log_once("GetResourceAllocationInfo dimension not supported:", desc.Dimension); + return kInvalidAllocation; + } + const UINT samples = desc.SampleDesc.Count, depth = volume ? desc.DepthOrArraySize : 1; + const UINT64 max_extent = + volume ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION; + const UINT max_layers = + volume ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION; + if (!desc.Width || !desc.Height || !desc.DepthOrArraySize || desc.Width > max_extent || + desc.Height > max_extent || desc.DepthOrArraySize > max_layers || !samples || samples > 16 || + (samples & (samples - 1)) || desc.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR) + return kInvalidAllocation; + const UINT16 full = full_mips(desc.Width, desc.Height, depth); + D3D12_RESOURCE_DESC resolved = desc; + if (!resolved.MipLevels) resolved.MipLevels = full; + if (resolved.MipLevels > full) return kInvalidAllocation; + if (samples > 1 && + (volume || resolved.MipLevels != 1 || (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) + return kInvalidAllocation; + if (desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN) + log_once("GetResourceAllocationInfo layout as UNKNOWN:", desc.Layout); + + const Format format = state_.texture_format(desc); + if (!format.format) { + log_once("GetResourceAllocationInfo format not supported yet:", desc.Format); + return kInvalidAllocation; + } + VkMemoryRequirements need{}; + if (!state_.memory_requirements(texture_create_info(resolved, format), need)) return kInvalidAllocation; + + // D3D12's alignment: 64 KiB, or 4 MiB with MSAA, unless the description asks for a small one (4 KiB, 64 KiB + // with MSAA). 4 KiB needs the resource to fit in 64 KiB and not be a render target or depth buffer; if it + // doesn't qualify, the PC runtime calls the description invalid rather than answering with 64 KiB. The MSAA + // 64 KiB alignment has no size limit there. Both measured in d3d12_vulkan_device_test. + UINT64 alignment = 0; + if (samples > 1) { + if (desc.Alignment && desc.Alignment != align_msaa_64k && desc.Alignment != align_msaa_4m) + return kInvalidAllocation; + alignment = desc.Alignment ? desc.Alignment : align_msaa_4m; + } else { + if (desc.Alignment && desc.Alignment != align_4k && desc.Alignment != align_64k) return kInvalidAllocation; + if (desc.Alignment == align_4k && ((desc.Flags & attachment) || need.size > align_64k)) + return kInvalidAllocation; + alignment = desc.Alignment ? desc.Alignment : align_64k; + } + return {align_up(need.size, alignment), alignment}; + } + DeviceState state_; OwnedRuntime owned_; IUnknown* outer_ = nullptr; // the Xbox-ABI proxy, which owns a reference to this device diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp index dc69dcf6e..0580d2610 100644 --- a/runtime/test/d3d12_vulkan_device_test.cpp +++ b/runtime/test/d3d12_vulkan_device_test.cpp @@ -2,7 +2,8 @@ // the proxy the way the game will call it: device methods (forwarded slots), descriptor heaps from slot 14 with // start handles read in the Xbox shape (RAX), a texture from slot 76 with the Xbox layout word, committed // resources, views, command lists, a queue and a fence. Results are read back through D3D12 itself -// (CopyTextureRegion into a readback heap, then Map). GetCopyableFootprints is compared with the host PC runtime's. +// (CopyTextureRegion into a readback heap, then Map). GetCopyableFootprints and GetResourceAllocationInfo are +// compared with the host PC runtime's. // No shaders or game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation // error fails the test. #include "vk_test_device.h" @@ -115,15 +116,20 @@ D3D12_RESOURCE_BARRIER transition(ID3D12Resource* resource, D3D12_RESOURCE_STATE return barrier; } -// GetCopyableFootprints must match the PC runtime's exactly, since applications size and fill upload buffers from -// it. Returns the number of mismatches, or -1 when the host has no D3D12 device to compare with. -int compare_footprints(ID3D12Device* ours) { +// The host PC runtime's D3D12 device on the default adapter, to compare answers with; false if there is none. +bool create_host_device(Ref& host) { const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); const auto create = d3d12 ? reinterpret_cast( reinterpret_cast(GetProcAddress(d3d12, "D3D12CreateDevice"))) : nullptr; + return create && SUCCEEDED(create(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p))); +} + +// GetCopyableFootprints must match the PC runtime's exactly, since applications size and fill upload buffers from +// it. Returns the number of mismatches, or -1 when the host has no D3D12 device to compare with. +int compare_footprints(ID3D12Device* ours) { Ref host; - if (!create || FAILED(create(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) return -1; + if (!create_host_device(host)) return -1; struct Case { D3D12_RESOURCE_DESC desc; UINT subresources; @@ -180,6 +186,123 @@ int compare_footprints(ID3D12Device* ours) { return mismatches; } +// GetResourceAllocationInfo against the PC runtime. Buffer sizes, every alignment and which descriptions are invalid +// must match it exactly. A texture's size is the driver's choice on both sides, so ours is only checked to be a +// whole number of alignments and at least the texels of its top mip; both sizes are printed. Also checks the +// Device4/Device8 variants' per-resource layout. Returns the number of mismatches, or -1 without a host device. +int compare_allocation_info(ID3D12Device* ours) { + Ref host; + if (!create_host_device(host)) return -1; + const auto with = [](D3D12_RESOURCE_DESC desc, UINT64 alignment, UINT samples = 1) { + desc.Alignment = alignment; + desc.SampleDesc.Count = samples; + return desc; + }; + constexpr UINT64 k4 = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT, k64 = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + constexpr D3D12_RESOURCE_FLAGS none = D3D12_RESOURCE_FLAG_NONE, rt = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + constexpr DXGI_FORMAT rgba8 = DXGI_FORMAT_R8G8B8A8_UNORM; + struct Case { + const char* name; + D3D12_RESOURCE_DESC desc; + UINT64 top_mip_bytes; // 0: the size must match the host's exactly (buffers, invalid descriptions) + }; + D3D12_RESOURCE_DESC bad_buffer = buffer_desc(256); + bad_buffer.Height = 2; + D3D12_RESOURCE_DESC typed_buffer = buffer_desc(256); + typed_buffer.Format = DXGI_FORMAT_R8_UNORM; + D3D12_RESOURCE_DESC big_volume = volume_desc(1); + big_volume.Width = big_volume.Height = 32; + big_volume.DepthOrArraySize = 8; + const Case cases[] = { + {"buffer 300", buffer_desc(300), 0}, + {"buffer 64 KiB", buffer_desc(65536), 0}, + {"buffer 64 KiB + 1", buffer_desc(65537), 0}, + {"buffer aligned 64 KiB", with(buffer_desc(1000), k64), 0}, + {"buffer width 0", buffer_desc(0), 0}, + {"buffer height 2", bad_buffer, 0}, + {"buffer with a format", typed_buffer, 0}, + {"256x256 full chain", texture_desc(256, 256, rgba8, none, 0), 256 * 256 * 4}, + {"16x16 small", with(texture_desc(16, 16, rgba8, none), k4), 16 * 16 * 4}, + {"16x16 small render target", with(texture_desc(16, 16, rgba8, rt), k4), 16 * 16 * 4}, + {"1024x1024 small (too big)", with(texture_desc(1024, 1024, rgba8, none), k4), 1024 * 1024 * 4}, + {"64x64 BC1 small", with(texture_desc(64, 64, DXGI_FORMAT_BC1_UNORM, none, 3), k4), 16 * 16 * 8}, + {"64x64 depth", texture_desc(64, 64, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL), + 64 * 64 * 4}, + {"8x8 array of 6", texture_desc(8, 8, rgba8, none, 4, 6), 8 * 8 * 4 * 6}, + {"32x32x8 volume", big_volume, 32 * 32 * 8 * 4}, + {"64x64 4x MSAA", with(texture_desc(64, 64, rgba8, rt), 0, 4), 64 * 64 * 4 * 4}, + {"64x64 4x MSAA small", with(texture_desc(64, 64, rgba8, rt), k64, 4), 64 * 64 * 4 * 4}, + {"1024x1024 4x MSAA small", with(texture_desc(1024, 1024, rgba8, rt), k64, 4), 1024 * 1024 * 4 * 4}, + {"zero width", texture_desc(0, 16, rgba8, none), 0}, + {"alignment 12345", with(texture_desc(16, 16, rgba8, none), 12345), 0}, + {"4x MSAA with 2 mips", with(texture_desc(64, 64, rgba8, rt, 2), 0, 4), 0}, + }; + int mismatches = 0; + const auto mismatch = [&](const char* name, const D3D12_RESOURCE_ALLOCATION_INFO& a, + const D3D12_RESOURCE_ALLOCATION_INFO& b) { + if (mismatches++ < 24) + std::fprintf(stderr, "allocation info %s: ours size %llu alignment %llu, host size %llu alignment %llu\n", + name, (unsigned long long)a.SizeInBytes, (unsigned long long)a.Alignment, + (unsigned long long)b.SizeInBytes, (unsigned long long)b.Alignment); + }; + for (const Case& c : cases) { + const D3D12_RESOURCE_ALLOCATION_INFO a = ours->GetResourceAllocationInfo(0, 1, &c.desc); + const D3D12_RESOURCE_ALLOCATION_INFO b = host->GetResourceAllocationInfo(0, 1, &c.desc); + if (b.SizeInBytes == UINT64_MAX || !c.top_mip_bytes) { + if (a.SizeInBytes != b.SizeInBytes || (b.SizeInBytes != UINT64_MAX && a.Alignment != b.Alignment)) + mismatch(c.name, a, b); + continue; + } + if (a.Alignment != b.Alignment || a.SizeInBytes == UINT64_MAX || a.SizeInBytes % a.Alignment || + a.SizeInBytes < c.top_mip_bytes) + mismatch(c.name, a, b); + std::printf("allocation info %s: alignment %llu, size ours %llu host %llu\n", c.name, + (unsigned long long)a.Alignment, (unsigned long long)a.SizeInBytes, + (unsigned long long)b.SizeInBytes); + } + + // Several resources at once: each at its own alignment after the one before, the largest alignment overall. + // Buffers only for the host comparison (their sizes are fixed); the texture checks our own layout. + const D3D12_RESOURCE_DESC buffers[] = {buffer_desc(300), buffer_desc(70000), buffer_desc(1)}; + const D3D12_RESOURCE_ALLOCATION_INFO a = ours->GetResourceAllocationInfo(0, 3, buffers); + const D3D12_RESOURCE_ALLOCATION_INFO b = host->GetResourceAllocationInfo(0, 3, buffers); + if (a.SizeInBytes != b.SizeInBytes || a.Alignment != b.Alignment) mismatch("three buffers", a, b); + + Ref ours8; + if (FAILED(ours->QueryInterface(IID_PPV_ARGS(&ours8.p)))) return mismatches + 1; + const D3D12_RESOURCE_DESC mixed[] = {with(texture_desc(16, 16, rgba8, none), k4), buffer_desc(300), + with(texture_desc(64, 64, rgba8, rt), 0, 4)}; + D3D12_RESOURCE_DESC1 mixed1[3]{}; + for (int i = 0; i < 3; ++i) std::memcpy(&mixed1[i], &mixed[i], sizeof(mixed[i])); + D3D12_RESOURCE_ALLOCATION_INFO1 each[3]{}, each2[3]{}; + const D3D12_RESOURCE_ALLOCATION_INFO total = ours8->GetResourceAllocationInfo1(0, 3, mixed, each); + const D3D12_RESOURCE_ALLOCATION_INFO total2 = ours8->GetResourceAllocationInfo2(0, 3, mixed1, each2); + const auto aligned = [](UINT64 v, UINT64 to) { return (v + to - 1) / to * to; }; + bool layout_ok = total.SizeInBytes == total2.SizeInBytes && total.Alignment == total2.Alignment && + each[0].Offset == 0 && each[0].Alignment == k4 && each[1].Alignment == k64 && + each[2].Alignment == D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT && + total.Alignment == D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT && + total.SizeInBytes == each[2].Offset + each[2].SizeInBytes; + for (int i = 0; i < 3; ++i) { + const D3D12_RESOURCE_ALLOCATION_INFO single = ours->GetResourceAllocationInfo(0, 1, &mixed[i]); + layout_ok = layout_ok && each[i].SizeInBytes == single.SizeInBytes && + each[i].Alignment == single.Alignment && each[i].Offset == each2[i].Offset && + each[i].SizeInBytes == each2[i].SizeInBytes && each[i].Alignment == each2[i].Alignment && + (i == 0 || each[i].Offset == aligned(each[i - 1].Offset + each[i - 1].SizeInBytes, + each[i].Alignment)); + } + // An invalid description in the list makes the whole answer invalid. + const D3D12_RESOURCE_DESC with_bad[] = {buffer_desc(300), buffer_desc(0)}; + layout_ok = layout_ok && ours8->GetResourceAllocationInfo1(0, 2, with_bad, each).SizeInBytes == UINT64_MAX && + host->GetResourceAllocationInfo(0, 2, with_bad).SizeInBytes == UINT64_MAX; + if (!layout_ok) { + ++mismatches; + std::fprintf(stderr, "allocation info: Device4/Device8 per-resource layout wrong (total %llu/%llu)\n", + (unsigned long long)total.SizeInBytes, (unsigned long long)total.Alignment); + } + return mismatches; +} + } // namespace int main() { @@ -274,6 +397,10 @@ int main() { if (footprint_mismatches < 0) std::printf("GetCopyableFootprints: no host D3D12 device to compare with, skipped\n"); EXPECT(footprint_mismatches <= 0); + const int allocation_mismatches = compare_allocation_info(device.p); + if (allocation_mismatches < 0) + std::printf("GetResourceAllocationInfo: no host D3D12 device to compare with, skipped\n"); + EXPECT(allocation_mismatches <= 0); // Command objects; their GetDevice is the proxy, never the inner device. D3D12_COMMAND_QUEUE_DESC queue_desc{}; From eb629d41a80685a1929f59d2922694f32bb25cb9 Mon Sep 17 00:00:00 2001 From: Ayinaki Date: Sat, 21 Nov 2026 22:55:52 +0000 Subject: [PATCH 43/53] Decode BVH4 header and node pointer fields The indexer treated the pre-header wrapper words as the root and labelled the real header fields as counts. Parse the documented XboxBvh4Header fields, decode root node pointers, and document the runtime node and leaf layouts while keeping the dehydrated packed stream open. --- docs/bvh.md | 122 +++++++++++++++++++++++++++++++--------- tests/test_bvh_index.py | 42 ++++++++++++-- tools/bvh_index.py | 93 ++++++++++++++++++++++++------ 3 files changed, 208 insertions(+), 49 deletions(-) diff --git a/docs/bvh.md b/docs/bvh.md index 9439b800f..aa784ba8d 100644 --- a/docs/bvh.md +++ b/docs/bvh.md @@ -67,25 +67,88 @@ inflated bytes belong to the BVH family. The archive is not a mixed asset pack. **Verified** on 271,627 complete streams and 10 chunked streams (271,637/271,637): -* 32-bit tag `0x81020006` at offset `0x100`. -* `u32@0x104` = size of the node area in 64-byte units. -* `u32@0x20` = `0x140 + 64 * size_in_64b_units` (end of the declared node area). -* `u32@0x28` = `u32@0x20 - 0x100` (a 256-byte tail table inside the node area). -* `0x140` is the first 64-byte node; the declared node area ends at `u32@0x20`. -* `0x110` holds six floats consistent with a 3D AABB (`min xyz`, `max xyz`). In `core_bvh4.rpf` all 271,627 - complete streams are ordered (`min <= max` on every axis); in `shared_minigame000_bvh4.rpf` 1,184 of 1,237 are - ordered and 53 are not (sentinel or non-finite values). -* `0x108` is a hash-like 32-bit value; `0x10C` is a small varying word. -* `0x130`/`0x134`/`0x138` are an offset, an even byte size and a signed base. The pointed range is inside the - stream and is often a near-monotonic `u16` sequence (274/400 sampled streams non-zero; 127/400 monotonic). This - is consistent with a primitive/index remap table, not with a vertex buffer, but the exact role is **Open**. -* The 256-byte tail at `u32@0x28` contains `u32` tables, including groups of four references that begin with - `0x04000000` in the sample. The node/table encoding was not decoded. +* The 64-byte `XboxBvh4Header` begins at payload offset `0x100`. Its `flags` word is `0x81020006` in these + packs. +* `u32@0x20` = `0x140 + 64 * totalSizeIn64BNodes` (the declared end of the 64-byte node address space). +* `u32@0x28` = `u32@0x20 - 0x100`. These two words sit before the header and are not header fields. +* `0x110` holds six floats for `sceneBounds` (`min xyz`, `max xyz`). In `core_bvh4.rpf` all 271,627 complete + streams are ordered (`min <= max` on every axis); in `shared_minigame000_bvh4.rpf` 1,184 of 1,237 are ordered + and 53 are not (sentinel or non-finite values). + +The field names and offsets now match the public `XboxBvh4Header` used by the Xbox DXR traversal shaders: + +| header offset | field | sample value | +|---|---|---:| +| `0x100` | `flags` | `0x81020006` | +| `0x104` | `totalSizeIn64BNodes` | 9,943 | +| `0x108` | `crc32` | `0xeab7667e` | +| `0x10c` | `numElements` | 5,447 | +| `0x110` | `sceneBounds.min` (3 floats) | `-47.416, -25.742, -5.624` | +| `0x11c` | `sceneBounds.max` (3 floats) | `47.416, 25.742, 5.624` | +| `0x128` | `offsetToNodes` | `0x59480` | +| `0x12c` | `offsetToPrimRemap` | 0 | +| `0x130` | `rootNodePtr` | `0x136ac` | +| `0x134` | `offsetToElements` | `0x4280` | +| `0x138` | `offsetToParents` | `0xffffab40` | +| `0x13c` | `compressionParams` | `0x808c8a89` | + +The offsets are relative to the header at `0x100`, not to the start of the payload. In the sample, +`offsetToNodes` therefore addresses `0x59580` and `offsetToElements` addresses `0x4380`. The node and element +regions are not necessarily the simple `0x140` onward array that the first indexer assumed. `offsetToParents` +is a raw `u32`; its signed/relative interpretation is still **Open**. + +The `flags` word has version `6` in its low 16 bits. It also sets `0x80000000` (bottom level), `0x00020000` +(offline) and `0x01000000` (dehydrated). It does not set `0x00010000` (compressed). The sample is therefore a +bottom-level, offline, dehydrated BVH, not a ready-to-traverse runtime tree. The name "BVH4" is the builder's own: `XboxBvh4Header`, `ConstructBVH4`, `RefitBVH4`, `PT_ConstructBVH4` and `totalSizeIn64BNodes` appear in `XboxBvhBuilder.dll`. The measured field at `0x104` is a count of 64-byte units whose product plus `0x140` lands exactly on the end pointer in 271,627/271,627 complete streams. That agrees with -the builder's naming but does not prove that `0x81020006` is the builder's header tag. +the builder's naming. + +#### Node pointers and the runtime node records + +A `rootNodePtr` or child pointer packs the node type in the low three bits and a 64-byte unit index in the high +29 bits: + +``` +type = ptr & 7 +node_address = header + (ptr >> 3) * 64 +``` + +The type values are `0..3` = `TRI0..TRI3`, `4` = `BOX16`, `5` = `BOX32`, `6` = `INSTANCE`, `7` = +`AABB_GEOMETRY`. `0xffffffff` is the invalid pointer. A `BOX32` node occupies 128 bytes, so it consumes two +64-byte units; all other node records occupy 64 bytes. + +The runtime records, which are what the traversal shaders read, are: + +| record | size | layout | +|---|---:|---| +| `Node16` | 64 | four `u32` children at `+0`; four 12-byte half-float bounds at `+16` | +| `Node32` | 128 | four `u32` children at `+0`; four 24-byte float bounds at `+16`; four padding words at `+112` | +| `Leaf` | 64 | four `float3` vertices at `+0`; `GeometryIndexAndFlags` at `+48`; `BasePrimitiveIndex` at `+52`; `PrimitiveIndex2` at `+56`; `baryRemap` at `+60` | + +The `Node16` bounds are six IEEE half values packed into three `u32` words. The shader expands them with +`XdxrDecompressBox16`; the first word holds `min.x`/`min.y`, the second `min.z`/`max.x`, and the third +`max.y`/`max.z`. + +For the sample, `rootNodePtr = 0x136ac` decodes to index 9941, type `BOX16`, at payload address `0x9b640`. +That record begins `0x04000000, 0x13694, 0x1369c, 0x117b5`, so its first child is not a valid runtime +pointer. This is the dehydrated form, not a runtime `Node16`. + +#### Packed dehydrated forms + +The same public headers define the packed records used before rehydration: + +| record | size | layout | +|---|---:|---| +| `NodePacked` | 16 | four `u32` children | +| `LeafPacked` | 12 | `GeometryIndexAndFlags`, `BasePrimitiveIndex`, `PrimitiveIndex2AndBaryRemap` | +| `BVVDHeader` | 8 | `variantNodeIndex` plus a six-bit mask and two-bit child selector | + +The dehydrated stream is not a contiguous array of runtime `Node16` records. Its record order, the `BVVDHeader` +table and the exact traversal of `NodePacked`/`LeafPacked` remain **Open**. A decoder must not feed the sample +root to the runtime traversal path until that packing is understood. ### 3.2 Instance descriptor (208 bytes) @@ -184,21 +247,23 @@ into three 64 KiB/26 KiB chunks. These list the per-tile BVH packs; they are the 3. **Pair descriptor to buffer.** The 208-byte descriptor precedes its BVH chunk in stream order in 269,106/269,106 cases. The other descriptor sizes account for 2,528 more BVH buffers; 3 more are preceded by other streams. -4. **Parse the header, then stop guessing.** `0x81020006`, `n64`, end, root, AABB and the `0x130` table can be read - now. The 64-byte node encoding (child references, box encoding, leaf form) is still **Open** and must be - recovered against `XboxBvh4Header`/`ConstructBVH4` or by validation, not assumed. +4. **Parse the header, then stop guessing.** The exact header table, node pointer encoding and runtime + `Node16`/`Node32`/`Leaf` records are in section 3.1. The packed dehydrated stream (`NodePacked`, `LeafPacked`, + `BVVDHeader`) remains **Open**; do not infer a runtime child array from the `0x140` slot space. 5. **Skip fill.** Ignore all-zero nodes and the `0x81`/`0x94`/`0x29` repeated blocks; they are not primitives. 6. **Do not feed these nodes to the AMD traversal.** The translator's `image_bvh_intersect_ray` path expects the - AMD hardware node format (256-byte base units), while these payloads use the builder's 64-byte units. A - converter or a rebuild is required; see `docs/d3d12_vulkan.md` §4.8. -7. **Result format.** Any decoder should emit world-space bounds plus primitive references, and validate counts - against the header (`0x140 + 64*n == end`, ordered AABB) before use. + AMD hardware node format (256-byte base units), while these payloads use the builder's 64-byte units. The + sample is also dehydrated, so its root is not a runtime child array. A rehydrator, converter or rebuild is + required; see `docs/d3d12_vulkan.md` §4.8. +7. **Result format.** Any decoder should emit world-space bounds plus primitive references, and validate the + wrapper (`0x140 + 64*n == end`, `u32@0x28 == end - 0x100`) and ordered AABB before use. ## 7. Tooling `tools/bvh_index.py` (standard library only) scans an RPF9 archive or a directory of `.rpf`/`.bin` payloads and -writes JSON and/or CSV with offset, stored size, inflated size, kind, signature, node count, root offset, declared -bytes, bounds, descriptor key/transform and fill counts. It reads only headers and emits no payload bytes. +writes JSON and/or CSV with offset, stored size, inflated size, kind, signature, node count, tail offset, the +`XboxBvh4Header` fields, root pointer/index/type, declared bytes, bounds, descriptor key/transform and fill +counts. It reads only headers and emits no payload bytes. ```powershell python -I tools/bvh_index.py --out index.json --csv index.csv @@ -211,10 +276,11 @@ the end of the archive, stops the tool with a one-line error and exit code 2. An than its 8-byte header, has no streams. In directory mode an archive that cannot be read is reported on stderr as `skipped` and the other archives are still indexed. -The `bvh4` signature is reported only when the tag, the `0x140 + 64*n == end` formula and the `root == end - 0x100` -relation all hold; a larger payload whose declared end is past the chunk but which is a 64 KiB multiple is reported -as `bvh4-chunk`. The synthetic tests cover the tag, the formula rejection, the chunk case, the 208-byte template, -the other descriptor template, XML and XML fragments, the two-stream advance bug and CSV/JSON output. +The `bvh4` signature is reported only when `flags == 0x81020006`, the `0x140 + 64*n == end` formula and the +`u32@0x28 == end - 0x100` wrapper relation all hold; a larger payload whose declared end is past the chunk but +which is a 64 KiB multiple is reported as `bvh4-chunk`. The synthetic tests cover the tag, the formula rejection, +the exact header fields and root pointer/type, the chunk case, the 208-byte template, the other descriptor +template, XML and XML fragments, the two-stream advance bug and CSV/JSON output. Measured with the tool on `shared_minigame000_bvh4.rpf`: 2,560 streams, 59,142,787 stored, 970,044,012 inflated, 1,237 complete `bvh4`, 1,233 `instance208`, 85 descriptors, 5 XML. That matches the carver summary exactly. diff --git a/tests/test_bvh_index.py b/tests/test_bvh_index.py index c2fcd63af..099423f74 100644 --- a/tests/test_bvh_index.py +++ b/tests/test_bvh_index.py @@ -25,10 +25,15 @@ def bvh_payload(n=10, tag=bvh_index.TAG, end_delta=0): end = 0x140 + n * 64 + end_delta struct.pack_into(" [--out index.json] [--csv index.csv] @@ -38,8 +40,11 @@ HEAD = 0x140 TAG_OFF = 0x100 N_OFF = 0x104 END_OFF = 0x20 -ROOT_OFF = 0x28 +TAIL_OFF = 0x28 AABB_OFF = 0x110 +INVALID_NODE = 0xFFFFFFFF +NODE_TYPE_NAMES = {0: "tri0", 1: "tri1", 2: "tri2", 3: "tri3", + 4: "box16", 5: "box32", 6: "instance", 7: "aabb_geometry"} INSTANCE_WORDS = ((0x08, 0x50000080), (0x10, 1), (0x18, 0x500000A0), (0x20, 0x60000000), (0x28, 0x500000B0), (0x30, 0x500000C0), (0x38, 0x50000050)) FILL_BYTES = (0x00, 0x81, 0x94, 0x29) @@ -52,6 +57,49 @@ def below_normal(): k.SetPriorityClass(k.GetCurrentProcess(), 0x00004000) +def decode_node_pointer(value): + """Decode the low three type bits and the high 29-bit 64-byte node index.""" + typ = value & 7 + return {"ptr": value, "index": value >> 3, "type": typ, + "name": NODE_TYPE_NAMES.get(typ, "invalid"), "invalid": value == INVALID_NODE} + + +def parse_header(head): + """Parse the 64-byte XboxBvh4Header at payload offset 0x100. + + The field names and offsets match the public XboxBvh4Header used by the Xbox DXR traversal + shaders. The offsets in the header are relative to 0x100, the start of this header. + """ + if len(head) < HEAD or struct.unpack_from("= HEAD and len(head) >= HEAD and struct.unpack_from(" Date: Sat, 21 Nov 2026 23:57:07 +0100 Subject: [PATCH 44/53] Runtime: parse version 1.2 root signatures, and read RTS0 table ranges from their offset parse_rts0 refused D3D_ROOT_SIGNATURE_VERSION_1_2 blobs. 1.2 is 1.1 plus D3D12_STATIC_SAMPLER_DESC1::Flags: the PC serializer writes RTS0 version 3 with 14-dword static samplers (13 before). The model gains Version::V1_2 and StaticSampler::flags. The canonical codec writes the flags only for 1.2, so 1.0/1.1 encodings are byte-for-byte unchanged. Checking it against the real serializer found an older bug: a descriptor table's payload is {num_ranges, ranges_offset} with the ranges at that offset, but the parser read them inline after the count. Every table came back with a wrong range type and count. The oracle test only covered constants and a CBV, so it never saw it. root_signature_oracle_test now serializes 1.0, 1.1 and 1.2 signatures with a two-range table, a root SRV and two static samplers (1.2 with a UINT border colour, then non-normalized coordinates). Every sampler field, the ranges and the canonical round trip must match. root_signature_test adds hand-built 1.2 and table payloads and their truncation controls. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 11 ++ runtime/src/root_signature.cpp | 56 ++++---- runtime/src/root_signature.h | 12 +- runtime/test/root_signature_oracle_test.cpp | 135 ++++++++++++++++++++ runtime/test/root_signature_test.cpp | 93 ++++++++++++++ 5 files changed, 283 insertions(+), 24 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 2dc43ac00..0ec0faa0d 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -456,6 +456,17 @@ Reconciliation: `tools/root_sig_contract.py` checks a candidate root signature a the build on the first contradiction. Until the console mapping in §3.5 is confirmed by a PSO, this check — not a rendered frame — is the acceptance gate for the mapping above. +Blob format: `rt::rootsig::parse_rts0` reads the `RTS0` chunk of a serialized root signature, versions 1.0, 1.1 +and 1.2. `root_signature_oracle_test` checks it on Windows against blobs the PC `d3d12.dll` serializes. These +layouts are measured, not assumed: +- a descriptor table's payload is `{num_ranges, ranges_offset}`, with the ranges at that offset; +- ranges are 20 bytes, or 24 with the 1.1/1.2 flags dword; +- root descriptors carry a flags dword from 1.1 on; +- static samplers are 13 dwords (`D3D12_STATIC_SAMPLER_DESC` order). In 1.2 they are 14: `D3D12_STATIC_SAMPLER_DESC1` + appends `Flags`, i.e. UINT border colours and non-normalized coordinates. + +Static samplers take no user-data dwords, so 1.2 changes nothing in `pack`. + **Root-signature flag quirk.** Prior art measured Xbox root-signature descriptors carrying flags `0x03000000`; the PC serializer rejects them with `E_INVALIDARG` because its flags live in the low 16 bits. Clear the high byte on a private copy before calling the host serializer/deserializer; never modify the game's descriptor. The meaning of the diff --git a/runtime/src/root_signature.cpp b/runtime/src/root_signature.cpp index 79a633b61..bdd181f08 100644 --- a/runtime/src/root_signature.cpp +++ b/runtime/src/root_signature.cpp @@ -92,6 +92,13 @@ private: constexpr uint32_t kCanonicalMagic = 0x3153524Cu; // "LRS1" little-endian constexpr uint32_t kCanonicalVersion = 1; +// D3D_ROOT_SIGNATURE_VERSION 1 (1.0), 2 (1.1), 3 (1.2): the numbering RTS0 and the canonical codec both store. +bool known_version(uint32_t v, Version& out) { + if (v < 1 || v > 3) return false; + out = static_cast(v); + return true; +} + } // namespace std::vector encode_canonical(const RootSignature& sig) { @@ -130,6 +137,7 @@ std::vector encode_canonical(const RootSignature& sig) { put_u32(out, s.shader_register); put_u32(out, s.register_space); put_u32(out, static_cast(s.visibility)); + if (sig.version == Version::V1_2) put_u32(out, s.flags); } return out; } @@ -155,7 +163,7 @@ DecodeResult decode_canonical(const uint8_t* data, size_t size) { out.error = "truncated canonical header"; return out; } - if (ver != 1 && ver != 2) { + if (!known_version(ver, out.sig.version)) { out.error = "unknown root-signature version"; return out; } @@ -167,7 +175,6 @@ DecodeResult decode_canonical(const uint8_t* data, size_t size) { out.error = "absurd sampler count"; return out; } - out.sig.version = ver == 1 ? Version::V1_0 : Version::V1_1; out.sig.params.reserve(nparams); for (uint32_t i = 0; i < nparams; ++i) { RootParameter p; @@ -206,7 +213,8 @@ DecodeResult decode_canonical(const uint8_t* data, size_t size) { if (!r.u32(s.filter) || !r.u32(s.address_u) || !r.u32(s.address_v) || !r.u32(s.address_w) || !r.f32(s.mip_lod_bias) || !r.u32(s.max_anisotropy) || !r.u32(s.comparison_func) || !r.u32(s.border_color) || !r.f32(s.min_lod) || !r.f32(s.max_lod) || - !r.u32(s.shader_register) || !r.u32(s.register_space) || !r.u32(vis)) { + !r.u32(s.shader_register) || !r.u32(s.register_space) || !r.u32(vis) || + (out.sig.version == Version::V1_2 && !r.u32(s.flags))) { out.error = "truncated canonical sampler"; return out; } @@ -221,10 +229,12 @@ DecodeResult decode_canonical(const uint8_t* data, size_t size) { return out; } -// RTS0 payload hypothesis: u32 version (1 = 1.0, 2 = 1.1), u32 num_params, +// RTS0 payload: u32 version (1 = 1.0, 2 = 1.1, 3 = 1.2), u32 num_params, // u32 num_static_samplers, u32 flags, then per-parameter fields in d3d12.h -// order. Static samplers follow the same field order as D3D12_STATIC_SAMPLER_DESC. -// Anything else (v1.2 blobs, extra dwords, truncation) is a hard error. +// order. Static samplers follow the field order of D3D12_STATIC_SAMPLER_DESC, and +// of D3D12_STATIC_SAMPLER_DESC1 (one more dword, Flags) in 1.2. Root descriptors +// and ranges have a flags dword from 1.1 on. Anything else (unknown versions, +// truncation) is a hard error. // Payload decoder: the RTS0 chunk contents (see header for the hypothesis). static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { DecodeResult out; @@ -264,8 +274,8 @@ static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { out.error = "truncated RTS0 header"; return out; } - if (ver != 1 && ver != 2) { - out.error = "unknown RTS0 version (not 1.0/1.1)"; + if (!known_version(ver, out.sig.version)) { + out.error = "unknown RTS0 version (not 1.0/1.1/1.2)"; return out; } if (nparams > 64) { @@ -276,7 +286,7 @@ static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { out.error = "RTS0 with absurd sampler count"; return out; } - out.sig.version = ver == 1 ? Version::V1_0 : Version::V1_1; + const bool flags_v11 = ver >= 2; // descriptor and range flags (1.1 and 1.2) out.sig.flags = flags; // Parameter table at params_off: num_params x {u32 d3d_type, u32 // visibility, u32 offset}. d3d_type follows D3D12_ROOT_PARAMETER_TYPE @@ -307,7 +317,7 @@ static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { } else if (dtype == 2 || dtype == 3 || dtype == 4) { p.type = ParamType::Descriptor; uint32_t dflags = 0; - const size_t need = ver == 2 ? 12 : 8; + const size_t need = flags_v11 ? 12 : 8; if (poff > size || need > size - static_cast(poff)) { out.error = "truncated RTS0 descriptor payload"; return out; @@ -316,15 +326,17 @@ static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { out.error = "truncated RTS0 descriptor payload"; return out; } - if (ver == 2 && !u32_at(poff + 8, dflags)) { + if (flags_v11 && !u32_at(poff + 8, dflags)) { out.error = "truncated RTS0 descriptor flags"; return out; } (void)dflags; // descriptor flags do not affect the user-SGPR map } else if (dtype == 0) { p.type = ParamType::Table; - uint32_t nranges = 0; - if (!u32_at(poff, nranges)) { + // Table payload: {u32 num_ranges, u32 ranges_offset}; the ranges sit at ranges_offset (from the payload + // start), like every other table in RTS0. Measured against the PC serializer (root_signature_oracle_test). + uint32_t nranges = 0, ranges_off = 0; + if (!u32_at(poff, nranges) || !u32_at(static_cast(poff) + 4, ranges_off)) { out.error = "truncated RTS0 table payload"; return out; } @@ -332,22 +344,21 @@ static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { out.error = "absurd RTS0 range count"; return out; } - // Range record: {type, num, base_reg, space, offset} (+ flags on 1.1). - const size_t stride = ver == 2 ? 24 : 20; - if (nranges > 0 && - (poff + 4 > size || nranges > (size - (poff + 4)) / stride)) { + // Range record: {type, num, base_reg, space, offset} (+ flags on 1.1 and 1.2). + const size_t stride = flags_v11 ? 24 : 20; + if (nranges > 0 && (ranges_off > size || nranges > (size - ranges_off) / stride)) { out.error = "RTS0 ranges overrun their payload"; return out; } p.ranges.reserve(nranges); for (uint32_t j = 0; j < nranges; ++j) { - const size_t roff = static_cast(poff) + 4 + j * stride; + const size_t roff = static_cast(ranges_off) + j * stride; DescriptorRange range; uint32_t base_reg = 0, space = 0, disp_off = 0, rflags = 0; if (!u32_at(roff, range.range_type) || !u32_at(roff + 4, range.num_descriptors) || !u32_at(roff + 8, base_reg) || !u32_at(roff + 12, space) || !u32_at(roff + 16, disp_off) || - (ver == 2 && !u32_at(roff + 20, rflags))) { + (flags_v11 && !u32_at(roff + 20, rflags))) { out.error = "truncated RTS0 range"; return out; } @@ -363,8 +374,9 @@ static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { } out.sig.params.push_back(std::move(p)); } - // Sampler records mirror D3D12_STATIC_SAMPLER_DESC field order. - constexpr size_t kSamplerBytes = 13 * 4; + // Sampler records mirror D3D12_STATIC_SAMPLER_DESC field order; 1.2 appends Flags (D3D12_STATIC_SAMPLER_DESC1). + const bool sampler_flags = ver == 3; + const size_t kSamplerBytes = (sampler_flags ? 14 : 13) * 4; if (nsamplers > 0 && (samplers_off > size || nsamplers > (size - samplers_off) / kSamplerBytes)) { out.error = "RTS0 samplers overrun their payload"; @@ -381,7 +393,7 @@ static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { !u32_at(soff + 24, s.comparison_func) || !u32_at(soff + 28, s.border_color) || !f32_at(soff + 32, s.min_lod) || !f32_at(soff + 36, s.max_lod) || !u32_at(soff + 40, s.shader_register) || !u32_at(soff + 44, s.register_space) || - !u32_at(soff + 48, vis)) { + !u32_at(soff + 48, vis) || (sampler_flags && !u32_at(soff + 52, s.flags))) { out.error = "truncated RTS0 sampler"; return out; } diff --git a/runtime/src/root_signature.h b/runtime/src/root_signature.h index 4c19cf72d..d5edcf2f0 100644 --- a/runtime/src/root_signature.h +++ b/runtime/src/root_signature.h @@ -17,8 +17,8 @@ namespace rt::rootsig { -// D3D12_ROOT_SIGNATURE_VERSION subset the layer handles. -enum class Version : uint32_t { V1_0 = 1, V1_1 = 2 }; +// D3D12_ROOT_SIGNATURE_VERSION subset the layer handles. 1.2 is 1.1 plus a flags dword on each static sampler. +enum class Version : uint32_t { V1_0 = 1, V1_1 = 2, V1_2 = 3 }; // D3D12_ROOT_PARAMETER_TYPE subset (order matches D3D12 docs). enum class ParamType : uint32_t { @@ -59,6 +59,9 @@ struct StaticSampler { uint32_t shader_register = 0; uint32_t register_space = 0; Visibility visibility = Visibility::All; + // D3D12_SAMPLER_FLAGS (D3D12_STATIC_SAMPLER_DESC1, version 1.2 only): 1 UINT border colour, 2 non-normalized + // coordinates. Earlier versions have no such field; it stays 0 and the codecs neither write nor read it. + uint32_t flags = 0; }; struct RootParameter { @@ -123,6 +126,8 @@ constexpr uint32_t kMaxD3d12Cost = 64; // little-endian). This is Leonida's own layout, NOT the Microsoft RTS0 // format: it round-trips pack() inputs byte-exactly and is fully tested on // every CI leg. Never write game blobs in this format and claim otherwise. +// Static samplers carry their flags dword only in version 1.2 signatures, so +// 1.0/1.1 encodings are unchanged. [[nodiscard]] std::vector encode_canonical(const RootSignature& sig); struct DecodeResult { @@ -144,6 +149,9 @@ struct DecodeResult { // numbering). A bare payload without the DXBC header is also accepted // (unit-test path). Every deviation the oracle test finds is a hard failure // to investigate, not a quirk to absorb. +// Versions 1 (1.0), 2 (1.1) and 3 (1.2): 1.1 and 1.2 add a flags dword to +// root descriptors and ranges; 1.2 adds one to each static sampler (13 dwords +// before, 14 after), as the PC serializer writes them (root_signature_oracle_test). // Returns ok == false with a reason for unknown versions or truncation. [[nodiscard]] DecodeResult parse_rts0(const uint8_t* data, size_t size); diff --git a/runtime/test/root_signature_oracle_test.cpp b/runtime/test/root_signature_oracle_test.cpp index d60dfae3a..e2f05b1a3 100644 --- a/runtime/test/root_signature_oracle_test.cpp +++ b/runtime/test/root_signature_oracle_test.cpp @@ -5,6 +5,7 @@ // and requires rt::rootsig::parse_rts0 to recover the same model. If the // hypothesis layout in root_signature.cpp ever disagrees with the real // serializer, this fails loudly here instead of corrupting draws silently. +// Versions 1.0, 1.1 and 1.2 are each checked with static samplers. // NOT portable: runs on Windows CI only, like root_sig_test.cpp. #include #include @@ -55,6 +56,10 @@ bool parse_blob(ID3DBlob* blob, rt::rootsig::RootSignature& model) { std::printf("%02x", bytes[i]); } std::printf("\n"); + if (GetEnvironmentVariableA("LEONIDA_ORACLE_DUMP", nullptr, 0)) { // the whole blob as u32 words, for layouts + for (size_t i = 0; i + 4 <= size; i += 4) + std::printf(" +%3zu: %08x\n", i, unsigned(bytes[i] | bytes[i + 1] << 8 | bytes[i + 2] << 16 | bytes[i + 3] << 24)); + } std::fflush(stdout); const rt::rootsig::DecodeResult d = rt::rootsig::parse_rts0(bytes, size); if (!d.ok) { @@ -115,6 +120,136 @@ int main() { const PackResult packed = pack(model); check(packed.ok && packed.dword_count == 6, "oracle model packs to 6 dwords"); + // Static samplers, one signature per version: every field round-trips through the real serializer, and 1.2 + // adds D3D12_STATIC_SAMPLER_DESC1::Flags (a 14th dword) to each sampler record. Each also carries a table and a + // root descriptor, so the 1.1/1.2 descriptor and range flags sit between the samplers and the header. + D3D12_STATIC_SAMPLER_DESC1 samplers[2]{}; + samplers[0].Filter = D3D12_FILTER_ANISOTROPIC; + samplers[0].AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; + samplers[0].AddressV = D3D12_TEXTURE_ADDRESS_MODE_MIRROR; + samplers[0].AddressW = D3D12_TEXTURE_ADDRESS_MODE_BORDER; + samplers[0].MipLODBias = -1.5f; + samplers[0].MaxAnisotropy = 8; + samplers[0].ComparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL; + samplers[0].BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE; + samplers[0].MinLOD = 1.0f; + samplers[0].MaxLOD = 9.0f; + samplers[0].ShaderRegister = 4; + samplers[0].RegisterSpace = 2; + samplers[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + samplers[1].Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; + samplers[1].AddressU = samplers[1].AddressV = samplers[1].AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + samplers[1].MaxLOD = D3D12_FLOAT32_MAX; + samplers[1].ShaderRegister = 7; + samplers[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + samplers[1].BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK; + D3D12_STATIC_SAMPLER_DESC samplers0[2]{}; + for (int i = 0; i < 2; ++i) { + const D3D12_STATIC_SAMPLER_DESC1& s = samplers[i]; + samplers0[i] = {s.Filter, s.AddressU, s.AddressV, s.AddressW, s.MipLODBias, s.MaxAnisotropy, + s.ComparisonFunc, s.BorderColor, s.MinLOD, s.MaxLOD, s.ShaderRegister, s.RegisterSpace, + s.ShaderVisibility}; + } + // Two ranges, so the range stride (20 bytes in 1.0, 24 with flags) is under test too. + D3D12_DESCRIPTOR_RANGE range0[2] = { + {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 3, 1, 0, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND}, + {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 2, 0, 0, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND}}; + D3D12_DESCRIPTOR_RANGE1 range1[2] = { + {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 3, 1, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC, + D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND}, + {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 2, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, + D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND}}; + D3D12_ROOT_PARAMETER params0[2]{}; + params0[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params0[0].DescriptorTable = {2, range0}; + params0[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + params0[1].Descriptor = {5, 1}; + D3D12_ROOT_PARAMETER1 params1[2]{}; + params1[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params1[0].DescriptorTable = {2, range1}; + params1[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + params1[1].Descriptor = {5, 1, D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE}; + + const auto same_sampler = [](const StaticSampler& got, const D3D12_STATIC_SAMPLER_DESC1& want, bool flags) { + return got.filter == uint32_t(want.Filter) && got.address_u == uint32_t(want.AddressU) && + got.address_v == uint32_t(want.AddressV) && got.address_w == uint32_t(want.AddressW) && + got.mip_lod_bias == want.MipLODBias && got.max_anisotropy == want.MaxAnisotropy && + got.comparison_func == uint32_t(want.ComparisonFunc) && + got.border_color == uint32_t(want.BorderColor) && got.min_lod == want.MinLOD && + got.max_lod == want.MaxLOD && got.shader_register == want.ShaderRegister && + got.register_space == want.RegisterSpace && + got.visibility == static_cast(want.ShaderVisibility) && + got.flags == (flags ? uint32_t(want.Flags) : 0u); + }; + const auto serialize = [&](const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& d, Version version, const char* name, + bool sampler_flags) { + Blobs out; + char what[160]; + const HRESULT result = D3D12SerializeVersionedRootSignature(&d, &out.blob, &out.error); + std::snprintf(what, sizeof(what), "%s: Microsoft serializer accepts it", name); + check(result == S_OK, what); + if (result != S_OK) { + if (out.error) std::printf("serializer error: %s\n", static_cast(out.error->GetBufferPointer())); + return; + } + RootSignature got; + std::snprintf(what, sizeof(what), "%s: parses", name); + const bool parsed = parse_blob(out.blob, got); + check(parsed, what); + if (!parsed) return; + std::snprintf(what, sizeof(what), "%s: version, a two-range table, a root SRV and two samplers", name); + check(got.version == version && got.params.size() == 2 && got.params[0].type == ParamType::Table && + got.params[0].ranges.size() == 2 && got.params[0].ranges[0].range_type == 0 && + got.params[0].ranges[0].num_descriptors == 3 && got.params[0].ranges[1].range_type == 1 && + got.params[0].ranges[1].num_descriptors == 2 && + got.params[1].type == ParamType::Descriptor && got.params[1].descriptor_register == 5 && + got.params[1].descriptor_space == 1 && got.static_samplers.size() == 2, + what); + if (got.static_samplers.size() != 2) return; + std::snprintf(what, sizeof(what), "%s: every sampler field round-trips", name); + check(same_sampler(got.static_samplers[0], samplers[0], sampler_flags) && + same_sampler(got.static_samplers[1], samplers[1], sampler_flags), + what); + // The canonical cache codec keeps all of it, flags included. + const std::vector bytes = encode_canonical(got); + const DecodeResult again = decode_canonical(bytes.data(), bytes.size()); + std::snprintf(what, sizeof(what), "%s: canonical codec round-trips the parsed model", name); + check(again.ok && again.sig.version == version && again.sig.static_samplers.size() == 2 && + same_sampler(again.sig.static_samplers[0], samplers[0], sampler_flags) && + same_sampler(again.sig.static_samplers[1], samplers[1], sampler_flags), + what); + }; + + D3D12_VERSIONED_ROOT_SIGNATURE_DESC v10{}; + v10.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + v10.Desc_1_0 = {2, params0, 2, samplers0, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + serialize(v10, Version::V1_0, "1.0 with static samplers", false); + + D3D12_VERSIONED_ROOT_SIGNATURE_DESC v11{}; + v11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + v11.Desc_1_1 = {2, params1, 2, samplers0, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + serialize(v11, Version::V1_1, "1.1 with static samplers", false); + + // 1.2: a UINT border colour on one sampler, no flags on the other. + samplers[0].BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT; + samplers[0].Flags = D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC v12{}; + v12.Version = D3D_ROOT_SIGNATURE_VERSION_1_2; + v12.Desc_1_2 = {2, params1, 2, samplers, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + serialize(v12, Version::V1_2, "1.2 with sampler flags", true); + + // 1.2: non-normalized coordinates, which D3D12 allows only with point/linear filtering, no mips, no anisotropy, + // no comparison and clamp or border addressing. + samplers[0] = {}; + samplers[0].Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT; + samplers[0].AddressU = samplers[0].AddressV = samplers[0].AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + samplers[0].ShaderRegister = 4; + samplers[0].RegisterSpace = 2; + samplers[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + samplers[0].BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK; + samplers[0].Flags = D3D12_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES; + serialize(v12, Version::V1_2, "1.2 with non-normalized coordinates", true); + if (g_failures != 0) std::printf("%d FAILURES\n", g_failures); return g_failures == 0 ? 0 : 1; } diff --git a/runtime/test/root_signature_test.cpp b/runtime/test/root_signature_test.cpp index 92ef8347f..7a27aa43c 100644 --- a/runtime/test/root_signature_test.cpp +++ b/runtime/test/root_signature_test.cpp @@ -216,6 +216,99 @@ int main() { "walked RTS0 model matches payload"); } + // RTS0 descriptor tables: the payload is {num_ranges, ranges_offset} and the ranges sit at that offset, as the + // PC serializer writes them (root_signature_oracle_test); here a 1.1 table with two 24-byte ranges placed after + // a gap, so reading them inline after the count would fail. + { + std::vector p; + put_u32(p, 2); // version 1.1 + put_u32(p, 1); // 1 param + put_u32(p, 24); // params table offset + put_u32(p, 0); // 0 samplers + put_u32(p, 0); + put_u32(p, 0); // flags + put_u32(p, 0); // entry 0: descriptor table + put_u32(p, 5); // pixel + put_u32(p, 36); // table payload + put_u32(p, 2); // 2 ranges + put_u32(p, 52); // at 52 + put_u32(p, 0xdeadbeefu); // gap + put_u32(p, 0xdeadbeefu); + for (const uint32_t v : {0u, 4u, 0u, 0u, 0xffffffffu, 0u, // SRV x4 + 2u, 1u, 3u, 1u, 0xffffffffu, 0u}) // CBV x1 + put_u32(p, v); + const DecodeResult d = parse_rts0(p.data(), p.size()); + check(d.ok && d.sig.params.size() == 1 && d.sig.params[0].type == ParamType::Table && + d.sig.params[0].visibility == Visibility::Pixel && d.sig.params[0].ranges.size() == 2 && + d.sig.params[0].ranges[0].range_type == 0 && d.sig.params[0].ranges[0].num_descriptors == 4 && + d.sig.params[0].ranges[1].range_type == 2 && d.sig.params[0].ranges[1].num_descriptors == 1, + "RTS0 table ranges read from their offset"); + std::vector wild = p; + wild[40] = 0xF0; // ranges offset far past the payload + check(!parse_rts0(wild.data(), wild.size()).ok, "RTS0 ranges offset past the payload rejected"); + } + + // Version 1.2: the canonical codec carries the static-sampler flags, and only for 1.2, so 1.0/1.1 encodings are + // byte-for-byte what they were before 1.2 existed. + { + RootSignature sig; + sig.version = Version::V1_2; + sig.params = {consts(1)}; + StaticSampler s; + s.border_color = 5; // D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK_UINT + s.flags = 1; // D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR + StaticSampler plain; + plain.shader_register = 1; + sig.static_samplers = {s, plain}; + const std::vector v12 = encode_canonical(sig); + const DecodeResult d = decode_canonical(v12.data(), v12.size()); + check(d.ok && d.sig.version == Version::V1_2 && d.sig.static_samplers.size() == 2 && + d.sig.static_samplers[0].flags == 1 && d.sig.static_samplers[0].border_color == 5 && + d.sig.static_samplers[1].flags == 0 && d.sig.static_samplers[1].shader_register == 1, + "canonical 1.2 round-trips sampler flags"); + check(!decode_canonical(v12.data(), v12.size() - 4).ok, "canonical 1.2 without the last flags is truncated"); + sig.version = Version::V1_1; + const std::vector v11 = encode_canonical(sig); + check(v11.size() + 2 * 4 == v12.size(), "canonical 1.1 has no sampler flags dword"); + const DecodeResult d11 = decode_canonical(v11.data(), v11.size()); + check(d11.ok && d11.sig.static_samplers[0].flags == 0, "canonical 1.1 decodes with flags 0"); + } + + // RTS0 version 3 (1.2): 1.1-style descriptor flags, then a 14-dword sampler whose last dword is its flags. + { + std::vector p; + put_u32(p, 3); // version 1.2 + put_u32(p, 1); // 1 param + put_u32(p, 24); // params table offset + put_u32(p, 1); // 1 sampler + put_u32(p, 48); // samplers offset + put_u32(p, 0); // flags + put_u32(p, 2); // entry 0: CBV + put_u32(p, 0); + put_u32(p, 36); + put_u32(p, 9); // register + put_u32(p, 0); // space + put_u32(p, 4); // descriptor flags (DATA_STATIC_WHILE_SET_AT_EXECUTE) + const uint32_t sampler[14] = {0x15, 1, 2, 3, 0, 16, 4, 5, 0, 0x7f7fffffu, 3, 1, 5, 2}; + for (const uint32_t v : sampler) put_u32(p, v); + const DecodeResult d = parse_rts0(p.data(), p.size()); + check(d.ok, "hand-built RTS0 1.2 parses"); + check(d.ok && d.sig.version == Version::V1_2 && d.sig.params.size() == 1 && + d.sig.params[0].descriptor_register == 9 && d.sig.static_samplers.size() == 1 && + d.sig.static_samplers[0].filter == 0x15 && d.sig.static_samplers[0].max_anisotropy == 16 && + d.sig.static_samplers[0].border_color == 5 && d.sig.static_samplers[0].shader_register == 3 && + d.sig.static_samplers[0].register_space == 1 && + d.sig.static_samplers[0].visibility == Visibility::Pixel && + d.sig.static_samplers[0].flags == 2, + "RTS0 1.2 sampler fields and flags"); + std::vector cut = p; + cut.resize(cut.size() - 4); // a 13-dword (1.0/1.1-sized) sampler in a 1.2 blob + check(!parse_rts0(cut.data(), cut.size()).ok, "RTS0 1.2 sampler without flags rejected"); + std::vector v4 = p; + v4[0] = 4; + check(!parse_rts0(v4.data(), v4.size()).ok, "RTS0 version 4 rejected"); + } + if (g_failures != 0) std::printf("%d FAILURES\n", g_failures); return g_failures == 0 ? 0 : 1; } From c17cdd8b6b51be7108951ec95bfad7066a818e6d Mon Sep 17 00:00:00 2001 From: Koert Lichtendonk Date: Sat, 21 Nov 2026 23:57:45 +0100 Subject: [PATCH 45/53] Docs: point CONTRIBUTING.md and AGENTS.md at #313 for the D3D12 layer The D3D12 -> Vulkan layer is tracked in #313 (critical path, who builds what, open D3D12 methods); say so next to #156 and #166. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 3 +++ CONTRIBUTING.md | 4 +++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index bb9a75a58..8b1052725 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,6 +28,9 @@ loader that maps the game's executable and resolves its imports to shims. Nothin Check its tables and the open pull requests first. If someone has claimed the item or has a pull request for it, stop and tell the user instead of writing it a second time. - Put the item ID from #156 in the pull request, and `Depends on: #N` for every pull request yours builds on. +- For the D3D12 → Vulkan layer (`runtime/shims/d3d12_*`, `runtime/src/vulkan_*`), also read + [#313](https://github.com/ItsNotRexed/Leonida/issues/313): most of that work builds on a few open pull requests, + and it lists which D3D12 methods are still open. ## Before you guess, look diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d5a6e2a6b..e29ffeb0f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -15,7 +15,9 @@ Thanks for helping. A few rules keep the project safe to host: Claim the work in [#156](https://github.com/ItsNotRexed/Leonida/issues/156) first: check its tables and the open pull requests, post `claiming: ` there (or a one-line description for something not listed yet), and put the ID in your pull request. When two pull requests overlap anyway, the one that lands first is merged and the other is -asked to rebase or close. GPU test results go in [#166](https://github.com/ItsNotRexed/Leonida/issues/166). +asked to rebase or close. GPU test results go in [#166](https://github.com/ItsNotRexed/Leonida/issues/166). Work on +the D3D12 → Vulkan layer has its own page, [#313](https://github.com/ItsNotRexed/Leonida/issues/313): the critical +path, who builds what, and which D3D12 methods are still open. ## Working on the code From 10d6d4b876d6548b53b364cdf6f05fda36b74929 Mon Sep 17 00:00:00 2001 From: dcastell1 Date: Sat, 21 Nov 2026 23:57:59 +0100 Subject: [PATCH 46/53] test(fuzz): differential coverage for the integer and bit VALU family FUZZ-1: model the integer/bit VALU block in tools/cpu_ref.py and add those ops to the shader_diff program table: v_add_nc_u32, v_sub_nc_u32, v_subrev_nc_u32, v_mul_u32_u24, v_mul_i32_i24, v_mul_lo_u32, v_mul_hi_u32/i32, v_mad_u32_u24/i32_i24, v_min_u32/u32, v_max_i32/u32, v_bfe_u32/i32, v_bfi_b32, v_alignbit_b32, v_alignbyte_b32, v_perm_b32 and v_med3_i32/u32. Pinned known-answer tests cover the boundaries: bfe width cut and zero, perm selector ranges (bytes, sign bits, constants), align shift 0 and 24, signed mul_hi, 24-bit sign extension and mad wraparound. The generator keeps integer ops away from registers last written by a float op: Vulkan does not promise a NaN payload and the comparison accepts both-NaN, so reusing those bits as an integer would compare an unobservable payload. Unobservable as a float, not as an integer. Verified CPU-only: 28 cpu_ref tests, 6 shader_diff tests, 423 semantic tests, and 8000 seeded programs (8 seeds x 1000) with 0 mismatches and 0 skips. GPU confirmation on the 5090 is pending. --- tests/test_cpu_ref.py | 99 ++++++++++++++++++++++++++++++++++ tools/cpu_ref.py | 121 +++++++++++++++++++++++++++++++++++++++++- tools/shader_diff.py | 45 +++++++++++++++- 3 files changed, 262 insertions(+), 3 deletions(-) diff --git a/tests/test_cpu_ref.py b/tests/test_cpu_ref.py index 584abe070..9b6ea1b37 100644 --- a/tests/test_cpu_ref.py +++ b/tests/test_cpu_ref.py @@ -48,6 +48,105 @@ class CpuRefTest(unittest.TestCase): def sgpr(self, result, index): return result["registers"]["sgpr"][index] + def test_integer_add_sub_mul(self): + r = self.execute(""" + v_mov_b32 v0, 0xffffffff + v_mov_b32 v1, 2 + v_add_nc_u32 v2, v0, v1 + v_sub_nc_u32 v3, v0, v1 + v_subrev_nc_u32 v4, v0, v1 + v_mul_u32_u24 v5, v0, v1 + v_mul_i32_i24 v6, 0x800000, 2 + v_mul_lo_u32 v7, v0, v1 + s_endpgm + """) + self.assertEqual(self.vgpr(r, 2), 1) # wraps + self.assertEqual(self.vgpr(r, 3), 0xFFFFFFFD) # dst = src0 - src1 + self.assertEqual(self.vgpr(r, 4), 3) # dst = src1 - src0 + self.assertEqual(self.vgpr(r, 5), 0x1FFFFFE) # low 24 bits of each source + self.assertEqual(self.vgpr(r, 6), 0xFF000000) # -2**23 * 2 + self.assertEqual(self.vgpr(r, 7), 0xFFFFFFFE) # low 32 bits + + def test_integer_min_max_med3(self): + r = self.execute(""" + v_mov_b32 v0, 0xfffffffb + v_mov_b32 v1, 3 + v_mov_b32 v2, 0 + v_min_i32 v3, v0, v1 + v_max_i32 v4, v0, v1 + v_min_u32 v5, v0, v1 + v_max_u32 v6, v0, v1 + v_med3_i32 v7, v0, v1, v2 + v_med3_u32 v8, v0, v1, v2 + s_endpgm + """) + self.assertEqual(self.vgpr(r, 3), 0xFFFFFFFB) # -5 + self.assertEqual(self.vgpr(r, 4), 3) + self.assertEqual(self.vgpr(r, 5), 3) + self.assertEqual(self.vgpr(r, 6), 0xFFFFFFFB) + self.assertEqual(self.vgpr(r, 7), 0) # median(-5, 3, 0) + self.assertEqual(self.vgpr(r, 8), 3) # median(4294967291, 3, 0) + + def test_bitfield_extract_and_insert(self): + r = self.execute(""" + v_mov_b32 v0, 0xabcdef12 + v_bfe_u32 v1, v0, 28, 8 + v_bfe_i32 v2, v0, 28, 8 + v_bfe_u32 v3, v0, 4, 0 + v_bfe_i32 v4, v0, 0, 4 + v_mov_b32 v5, 0xff00ff00 + v_mov_b32 v6, 0x12345678 + v_mov_b32 v7, 0xaabbccdd + v_bfi_b32 v8, v5, v6, v7 + s_endpgm + """) + self.assertEqual(self.vgpr(r, 1), 0xA) # width cut to 32 - 28 + self.assertEqual(self.vgpr(r, 2), 0xFFFFFFFA) # sign-extended 0xA + self.assertEqual(self.vgpr(r, 3), 0) # a zero width extracts nothing + self.assertEqual(self.vgpr(r, 4), 2) + self.assertEqual(self.vgpr(r, 8), 0x12BB56DD) # (x & y) | (~x & z) + + def test_align_and_permute(self): + r = self.execute(""" + v_mov_b32 v0, 0x11223344 + v_mov_b32 v1, 0xaabbccdd + v_mov_b32 v2, 8 + v_alignbit_b32 v3, v0, v1, v2 + v_mov_b32 v2, 3 + v_alignbyte_b32 v4, v0, v1, v2 + v_mov_b32 v2, 0 + v_alignbit_b32 v5, v0, v1, v2 + v_mov_b32 v2, 0x0c0b0400 + v_perm_b32 v6, v0, v1, v2 + v_mov_b32 v2, 0x0d080000 + v_perm_b32 v7, v0, v1, v2 + s_endpgm + """) + self.assertEqual(self.vgpr(r, 3), 0x44AABBCC) # {v0, v1} >> 8 + self.assertEqual(self.vgpr(r, 4), 0x223344AA) # {v0, v1} >> 24 + self.assertEqual(self.vgpr(r, 5), 0xAABBCCDD) # a zero shift keeps src1 + self.assertEqual(self.vgpr(r, 6), 0x000044DD) # bytes 0, 4; sign 0; zero + self.assertEqual(self.vgpr(r, 7), 0xFFFFDDDD) # byte 0, sign of src1 half, 0xff + + def test_mul_hi_and_mad(self): + r = self.execute(""" + v_mul_hi_u32 v0, 0xffffffff, 0xffffffff + v_mul_hi_i32 v1, 0xffffffff, 1 + v_mul_hi_i32 v2, 0x40000000, 0x40000000 + v_mul_hi_i32 v3, 0x80000000, 0x40000000 + v_mad_u32_u24 v4, 0xffffff, 0xffffff, 5 + v_mad_i32_i24 v5, 0xffffff, 0xffffff, 5 + v_mad_i32_i24 v6, 0x800000, 0x800000, 1 + s_endpgm + """) + self.assertEqual(self.vgpr(r, 0), 0xFFFFFFFE) + self.assertEqual(self.vgpr(r, 1), 0xFFFFFFFF) + self.assertEqual(self.vgpr(r, 2), 0x10000000) + self.assertEqual(self.vgpr(r, 3), 0xE0000000) + self.assertEqual(self.vgpr(r, 4), 0xFE000006) # 0xffffff**2 + 5, low 32 bits + self.assertEqual(self.vgpr(r, 5), 6) + self.assertEqual(self.vgpr(r, 6), 1) # 2**46 + 1, low 32 bits + def test_mov_inline_constants_and_literals(self): r = self.execute(""" v_mov_b32 v0, 1.0 diff --git a/tools/cpu_ref.py b/tools/cpu_ref.py index 63cfb95ef..10e5f20e7 100644 --- a/tools/cpu_ref.py +++ b/tools/cpu_ref.py @@ -17,7 +17,11 @@ Model: Implemented: s_mov_b32, v_mov_b32, v_add_f32, v_sub_f32, v_mul_f32, v_fma_f32, v_cndmask_b32, v_and_b32, v_or_b32, v_xor_b32, v_lshlrev_b32, v_lshrrev_b32, v_ashrrev_i32, s_add_u32, -s_lshl_b32, s_lshr_b32, s_endpgm. Inline constants and literals for those operands are handled. +s_lshl_b32, s_lshr_b32, s_endpgm. Also the integer/bit VALU block: v_add_nc_u32, v_sub_nc_u32, +v_subrev_nc_u32, v_mul_u32_u24, v_mul_i32_i24, v_mul_lo_u32, v_mul_hi_u32/v_mul_hi_i32, +v_mad_u32_u24/v_mad_i32_i24, v_min_u32/v_max_u32, v_min_i32/v_max_i32, +v_bfe_u32/v_bfe_i32, v_bfi_b32, v_alignbit_b32, v_alignbyte_b32, v_perm_b32 and +v_med3_i32/v_med3_u32. Inline constants and literals for those operands are handled. ``clamp`` is accepted on the f32 ops (NaN -> 0). Registers not initialized by the caller read as zero, matching the translator's deterministic register arrays. @@ -81,6 +85,11 @@ SUPPORTED_OPS = { "s_mov_b32", "s_add_u32", "s_lshl_b32", "s_lshr_b32", "v_mov_b32", "v_cndmask_b32", "v_and_b32", "v_or_b32", "v_xor_b32", "v_lshlrev_b32", "v_lshrrev_b32", "v_ashrrev_i32", + "v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32", "v_mul_u32_u24", "v_mul_i32_i24", + "v_mul_lo_u32", "v_mul_hi_u32", "v_mul_hi_i32", "v_mad_u32_u24", "v_mad_i32_i24", + "v_min_u32", "v_max_u32", "v_min_i32", "v_max_i32", + "v_bfe_u32", "v_bfe_i32", "v_bfi_b32", "v_alignbit_b32", "v_alignbyte_b32", + "v_perm_b32", "v_med3_i32", "v_med3_u32", "v_add_f32", "v_sub_f32", "v_mul_f32", "v_fma_f32", "s_endpgm", } @@ -551,6 +560,116 @@ class Machine: signed = value - (1 << 32) if value & SIGN32 else value r = (signed >> shift) & MASK32 self._write_vgpr(args[0], lane, r) + elif base in ("v_add_nc_u32", "v_sub_nc_u32", "v_mul_u32_u24", "v_mul_lo_u32", + "v_min_u32", "v_max_u32", "v_min_i32", "v_max_i32"): + self._expect(ins, 3) + for lane in self._active_lanes(): + a = self._int_src(args[1], lane) + b = self._int_src(args[2], lane) + if base == "v_add_nc_u32": + r = (a + b) & MASK32 + elif base == "v_sub_nc_u32": + r = (a - b) & MASK32 + elif base == "v_mul_u32_u24": + r = ((a & 0xFFFFFF) * (b & 0xFFFFFF)) & MASK32 + elif base == "v_mul_lo_u32": + r = (a * b) & MASK32 + elif base in ("v_min_u32", "v_max_u32"): + r = (max if base == "v_max_u32" else min)(a, b) + else: + sa = a - (1 << 32) if a & SIGN32 else a + sb = b - (1 << 32) if b & SIGN32 else b + r = (max if base == "v_max_i32" else min)(sa, sb) & MASK32 + self._write_vgpr(args[0], lane, r) + elif base == "v_subrev_nc_u32": + self._expect(ins, 3) + for lane in self._active_lanes(): + a = self._int_src(args[1], lane) + b = self._int_src(args[2], lane) + self._write_vgpr(args[0], lane, (b - a) & MASK32) + elif base in ("v_mul_hi_u32", "v_mul_hi_i32"): + self._expect(ins, 3) + for lane in self._active_lanes(): + a = self._int_src(args[1], lane) + b = self._int_src(args[2], lane) + if base == "v_mul_hi_i32": + a = a - (1 << 32) if a & SIGN32 else a + b = b - (1 << 32) if b & SIGN32 else b + self._write_vgpr(args[0], lane, ((a * b) >> 32) & MASK32) + elif base in ("v_mad_u32_u24", "v_mad_i32_i24"): + self._expect(ins, 4) + for lane in self._active_lanes(): + x = self._int_src(args[1], lane) & 0xFFFFFF + y = self._int_src(args[2], lane) & 0xFFFFFF + if base == "v_mad_i32_i24": + x = x - (1 << 24) if x & 0x800000 else x + y = y - (1 << 24) if y & 0x800000 else y + z = self._int_src(args[3], lane) + self._write_vgpr(args[0], lane, (x * y + z) & MASK32) + elif base == "v_mul_i32_i24": + self._expect(ins, 3) + for lane in self._active_lanes(): + x = self._int_src(args[1], lane) & 0xFFFFFF + y = self._int_src(args[2], lane) & 0xFFFFFF + sx = x - (1 << 24) if x & 0x800000 else x + sy = y - (1 << 24) if y & 0x800000 else y + self._write_vgpr(args[0], lane, (sx * sy) & MASK32) + elif base in ("v_bfe_u32", "v_bfe_i32"): + self._expect(ins, 4) + for lane in self._active_lanes(): + value = self._int_src(args[1], lane) + off = self._int_src(args[2], lane) & 31 + width = min(self._int_src(args[3], lane) & 31, 32 - off) + if width == 0: + r = 0 + else: + r = (value >> off) & ((1 << width) - 1) + if base == "v_bfe_i32" and r & (1 << (width - 1)): + r = (r - (1 << width)) & MASK32 + self._write_vgpr(args[0], lane, r) + elif base == "v_bfi_b32": + self._expect(ins, 4) + for lane in self._active_lanes(): + x = self._int_src(args[1], lane) + y = self._int_src(args[2], lane) + z = self._int_src(args[3], lane) + self._write_vgpr(args[0], lane, (x & y) | (~x & z)) + elif base in ("v_alignbit_b32", "v_alignbyte_b32"): + self._expect(ins, 4) + for lane in self._active_lanes(): + hi = self._int_src(args[1], lane) + lo = self._int_src(args[2], lane) + shift = self._int_src(args[3], lane) + shift = (shift & 31) if base == "v_alignbit_b32" else (shift & 3) * 8 + self._write_vgpr(args[0], lane, (((hi << 32) | lo) >> shift) & MASK32) + elif base == "v_perm_b32": + self._expect(ins, 4) + for lane in self._active_lanes(): + hi = self._int_src(args[1], lane) + lo = self._int_src(args[2], lane) + sel = self._int_src(args[3], lane) + packed = (hi << 32) | lo + r = 0 + for i in range(4): + sb = (sel >> (8 * i)) & 0xFF + if sb < 8: + val = (packed >> (8 * (sb & 7))) & 0xFF + elif sb < 12: + k = sb & 3 + src = lo if k < 2 else hi + val = 0xFF if (src >> (15 + 8 * (k & 1))) & 1 else 0 + else: + val = 0 if sb == 12 else 0xFF + r |= val << (8 * i) + self._write_vgpr(args[0], lane, r) + elif base in ("v_med3_i32", "v_med3_u32"): + self._expect(ins, 4) + for lane in self._active_lanes(): + vals = [self._int_src(args[i], lane) for i in (1, 2, 3)] + if base == "v_med3_i32": + vals = [v - (1 << 32) if v & SIGN32 else v for v in vals] + x, y, z = vals + self._write_vgpr(args[0], lane, max(min(x, y), min(max(x, y), z)) & MASK32) elif base == "s_mov_b32": self._expect(ins, 2) self._write_scalar_dst(args[0], self._int_src(args[1], 0, scalar=True)) diff --git a/tools/shader_diff.py b/tools/shader_diff.py index 0dd1cfb17..e98cdb0ba 100644 --- a/tools/shader_diff.py +++ b/tools/shader_diff.py @@ -76,6 +76,28 @@ def _op_templates(): ("v_lshlrev_b32", lambda r, d, s: f"v_lshlrev_b32 v{d}, {r.randrange(0, 8)}, v{s[0]}"), ("v_lshrrev_b32", lambda r, d, s: f"v_lshrrev_b32 v{d}, {r.randrange(0, 8)}, v{s[0]}"), ("v_ashrrev_i32", lambda r, d, s: f"v_ashrrev_i32 v{d}, {r.randrange(0, 8)}, v{s[0]}"), + ("v_add_nc_u32", lambda r, d, s: f"v_add_nc_u32 v{d}, v{s[0]}, v{s[1]}"), + ("v_sub_nc_u32", lambda r, d, s: f"v_sub_nc_u32 v{d}, v{s[0]}, v{s[1]}"), + ("v_subrev_nc_u32", lambda r, d, s: f"v_subrev_nc_u32 v{d}, v{s[0]}, v{s[1]}"), + ("v_mul_u32_u24", lambda r, d, s: f"v_mul_u32_u24 v{d}, v{s[0]}, v{s[1]}"), + ("v_mul_i32_i24", lambda r, d, s: f"v_mul_i32_i24 v{d}, v{s[0]}, v{s[1]}"), + ("v_mul_lo_u32", lambda r, d, s: f"v_mul_lo_u32 v{d}, v{s[0]}, v{s[1]}"), + ("v_mul_hi_u32", lambda r, d, s: f"v_mul_hi_u32 v{d}, v{s[0]}, v{s[1]}"), + ("v_mul_hi_i32", lambda r, d, s: f"v_mul_hi_i32 v{d}, v{s[0]}, v{s[1]}"), + ("v_mad_u32_u24", lambda r, d, s: f"v_mad_u32_u24 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), + ("v_mad_i32_i24", lambda r, d, s: f"v_mad_i32_i24 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), + ("v_min_u32", lambda r, d, s: f"v_min_u32 v{d}, v{s[0]}, v{s[1]}"), + ("v_max_u32", lambda r, d, s: f"v_max_u32 v{d}, v{s[0]}, v{s[1]}"), + ("v_min_i32", lambda r, d, s: f"v_min_i32 v{d}, v{s[0]}, v{s[1]}"), + ("v_max_i32", lambda r, d, s: f"v_max_i32 v{d}, v{s[0]}, v{s[1]}"), + ("v_bfe_u32", lambda r, d, s: f"v_bfe_u32 v{d}, v{s[0]}, {r.randrange(0, 40)}, {r.randrange(0, 40)}"), + ("v_bfe_i32", lambda r, d, s: f"v_bfe_i32 v{d}, v{s[0]}, {r.randrange(0, 40)}, {r.randrange(0, 40)}"), + ("v_bfi_b32", lambda r, d, s: f"v_bfi_b32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), + ("v_alignbit_b32", lambda r, d, s: f"v_alignbit_b32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), + ("v_alignbyte_b32", lambda r, d, s: f"v_alignbyte_b32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), + ("v_perm_b32", lambda r, d, s: f"v_perm_b32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), + ("v_med3_i32", lambda r, d, s: f"v_med3_i32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), + ("v_med3_u32", lambda r, d, s: f"v_med3_u32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), ("s_add_u32", lambda r, d, s: f"s_add_u32 s{d}, s{s[0]}, s{s[1]}"), ] @@ -88,7 +110,14 @@ def _op_templates(): # mini-interp (not this runner) re-enables scalar ALU coverage. _VEC_OPS = ("v_mov_b32", "v_add_f32", "v_sub_f32", "v_mul_f32", "v_fma_f32", "v_and_b32", "v_or_b32", "v_xor_b32", "v_lshlrev_b32", - "v_lshrrev_b32", "v_ashrrev_i32") + "v_lshrrev_b32", "v_ashrrev_i32", + "v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32", "v_mul_u32_u24", + "v_mul_i32_i24", "v_mul_lo_u32", "v_mul_hi_u32", "v_mul_hi_i32", + "v_mad_u32_u24", "v_mad_i32_i24", "v_min_u32", "v_max_u32", + "v_min_i32", "v_max_i32", + "v_bfe_u32", "v_bfe_i32", "v_bfi_b32", "v_alignbit_b32", + "v_alignbyte_b32", "v_perm_b32", "v_med3_i32", "v_med3_u32") +_FLOAT_OPS = ("v_add_f32", "v_sub_f32", "v_mul_f32", "v_fma_f32") def _seed_value(rng): @@ -113,12 +142,24 @@ def generate_program(rng, n_ops): for s in s_regs: lines.append(f"s_mov_b32 s{s}, {_seed_value(rng) % 256}") vec_ops = [t for t in _op_templates() if t[0] in _VEC_OPS and t[0] != "v_mov_b32"] + # A float op may return any NaN payload (Vulkan does not promise one) and the + # comparison accepts both-NaN. If that value then fed an integer op, the two + # payloads would produce different integer results, so integer ops never read + # the destination of a float op. Every untainted register is bit-identical on + # both oracles; a later integer write clears the taint. + tainted = set() for _ in range(n_ops): name, emit = rng.choice(vec_ops) dst = rng.choice(SCRATCH) - srcs = [rng.choice(SCRATCH) for _ in range(4)] + clean = [v for v in SCRATCH if v not in tainted] + pool = SCRATCH if name in _FLOAT_OPS or not clean else clean + srcs = [rng.choice(pool) for _ in range(4)] lines.append(emit(rng, dst, srcs)) writers[dst] = (name, len(lines)) + if name in _FLOAT_OPS: + tainted.add(dst) + else: + tainted.discard(dst) # Observe one scalar through a VGPR so scalar ops are covered too. lines.append(f"v_mov_b32 v15, s{rng.choice(s_regs)}") writers[15] = ("v_mov_b32/sgpr-copy", len(lines)) From fe413a2f1c72700521500a118bca5f3fe0649484 Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:59:08 +0100 Subject: [PATCH 47/53] Cancel superseded runs and skip heavy CI on docs-only PRs --- .github/workflows/ci.yml | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d764539cb..b18a22eb5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,8 +4,42 @@ on: [push, pull_request] permissions: contents: read +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + jobs: + change-scope: + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + outputs: + docs-only: ${{ steps.paths.outputs.docs-only }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 2 + persist-credentials: false + - name: Check whether only documentation changed + id: paths + shell: pwsh + run: | + # A pull_request checkout is the test merge; its first parent is the PR base. + # Treat missing history, an empty diff, and renames out of code conservatively. + $PSNativeCommandUseErrorActionPreference = $false + $docsOnly = $false + git diff --quiet "$env:GITHUB_SHA^1" "$env:GITHUB_SHA" -- + if ($LASTEXITCODE -eq 1) { + git diff --quiet --no-renames "$env:GITHUB_SHA^1" "$env:GITHUB_SHA" -- . ` + ':(exclude,top)README.md' ':(exclude,top)CONTRIBUTING.md' ` + ':(exclude,top)AGENTS.md' ':(exclude,top)SECURITY.md' ':(exclude,top,glob)docs/**/*.md' + $docsOnly = $LASTEXITCODE -eq 0 + } + "docs-only=$($docsOnly.ToString().ToLowerInvariant())" >> $env:GITHUB_OUTPUT + exit 0 # GitHub's pwsh wrapper would otherwise forward git diff's status. + check: + needs: change-scope + if: ${{ !cancelled() && needs.change-scope.outputs.docs-only != 'true' }} runs-on: windows-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -36,6 +70,8 @@ jobs: bad=$(git ls-files | grep -iE '\.(rpf|ttpf|xvd|dxbc|fssm|spv|spvasm|dds|bk2|awc|exe|dll)$' || true) if [ -n "$bad" ]; then echo "Game or binary files tracked:"; echo "$bad"; exit 1; fi translator-tests: + needs: change-scope + if: ${{ !cancelled() && needs.change-scope.outputs.docs-only != 'true' }} runs-on: ubuntu-24.04 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -50,6 +86,8 @@ jobs: - name: Translator tests run: python -m pytest tests -q --ignore=tests/semantic semantic-tests: + needs: change-scope + if: ${{ !cancelled() && needs.change-scope.outputs.docs-only != 'true' }} runs-on: ${{ matrix.os }} strategy: matrix: @@ -63,6 +101,8 @@ jobs: run: python -m unittest discover -s tests/semantic -v viewer-tests: + needs: change-scope + if: ${{ !cancelled() && needs.change-scope.outputs.docs-only != 'true' }} runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 From 77db72f6020081f73bfa69d7b56fa639c022efdb Mon Sep 17 00:00:00 2001 From: Ewann Date: Sun, 22 Nov 2026 00:04:20 +0100 Subject: [PATCH 48/53] run_gpu_tests: find the test programs in RelWithDebInfo/Release (TEST-38) With the Visual Studio generator the test programs land in build/, and the runner only looked in the build folder itself, so --build had to point at the subfolder (#166, RX 9070 XT entry). resolve_build_dir() looks in the build folder first, then in RelWithDebInfo, Release, Debug and MinSizeRel, and takes the configuration that has all three required programs and was built last. If none has them, the folder given is kept for the error message. --- scripts/run_gpu_tests.py | 31 +++++++++++++-- tests/test_gpu_build_dir.py | 76 +++++++++++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+), 3 deletions(-) create mode 100644 tests/test_gpu_build_dir.py diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 1ce87832b..6349dd602 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -410,11 +410,35 @@ def with_draw_shaders(asm_files: list[str]) -> list[str]: return build +# Multi-config CMake generators (Visual Studio, Xcode, Ninja Multi-Config) put each program in build/. +CONFIG_DIRS = ("RelWithDebInfo", "Release", "Debug", "MinSizeRel") + + +def resolve_build_dir(build: str, programs: tuple[str, ...]) -> str: + """The folder that holds all of `programs` (file names with their extension). + + Makefile and Ninja builds leave them in `build`. With the Visual Studio generator they land in + build/RelWithDebInfo, build/Release and so on. `build` itself wins when it has them all; otherwise the + configuration folder that has them all and was built last. If none has them, `build` is returned, so the + caller's "not found" message names the folder the user gave.""" + def complete(d: str) -> bool: + return all(os.path.isfile(os.path.join(d, n)) for n in programs) + + if complete(build): + return build + found = [d for d in (os.path.join(build, c) for c in CONFIG_DIRS) if complete(d)] + if not found: + return build + return max(found, key=lambda d: max(os.path.getmtime(os.path.join(d, n)) for n in programs)) + + def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc"), help="llvm-mc path, or a whole command such as 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'") - ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build")) + ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), + help="CMake build folder; with the Visual Studio generator the RelWithDebInfo/Release/... " + "subfolder that has the test programs is found by itself") ap.add_argument("--work", default=None) ap.add_argument("--filter", default="") a = ap.parse_args() @@ -425,8 +449,9 @@ def main() -> int: a.work = os.path.abspath(a.work) ext = ".exe" if os.name == "nt" else "" - missing = [t + ext for t in ("vk_compute_test", "vk_store_test", "vk_harness") - if not os.path.isfile(os.path.join(a.build, t + ext))] + required = tuple(t + ext for t in ("vk_compute_test", "vk_store_test", "vk_harness")) + a.build = resolve_build_dir(a.build, required) + missing = [t for t in required if not os.path.isfile(os.path.join(a.build, t))] if missing: sys.exit(f"Test programs not found in {a.build}:{', '.join(missing)}\n" "Build them with cmake -S runtime -B runtime/build, then cmake --build runtime/build.\n" diff --git a/tests/test_gpu_build_dir.py b/tests/test_gpu_build_dir.py new file mode 100644 index 000000000..5e124f5e2 --- /dev/null +++ b/tests/test_gpu_build_dir.py @@ -0,0 +1,76 @@ +"""run_gpu_tests.py finds the test programs where the CMake generator put them: in the build folder (Makefiles, +Ninja) or in build/ (Visual Studio generator, TEST-38). Fake files only, so this runs on any OS.""" +from pathlib import Path +import os +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "runtime" / "test" / "shaders")) +sys.path.insert(0, str(ROOT / "scripts")) +import run_gpu_tests + +PROGRAMS = ("vk_compute_test.exe", "vk_store_test.exe", "vk_harness.exe") + + +def touch(folder: Path, names=PROGRAMS, mtime=None): + folder.mkdir(parents=True, exist_ok=True) + for n in names: + f = folder / n + f.write_bytes(b"") + if mtime is not None: + os.utime(f, (mtime, mtime)) + + +class ResolveBuildDir(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.build = Path(tmp.name) / "build" + self.build.mkdir() + + def resolve(self): + return run_gpu_tests.resolve_build_dir(str(self.build), PROGRAMS) + + def test_programs_directly_in_the_build_folder(self): + touch(self.build) + self.assertEqual(self.resolve(), str(self.build)) + + def test_visual_studio_generator_subfolder(self): + touch(self.build / "RelWithDebInfo") + self.assertEqual(self.resolve(), str(self.build / "RelWithDebInfo")) + + def test_release_subfolder(self): + touch(self.build / "Release") + self.assertEqual(self.resolve(), str(self.build / "Release")) + + def test_build_folder_wins_over_a_subfolder(self): + touch(self.build) + touch(self.build / "Release") + self.assertEqual(self.resolve(), str(self.build)) + + def test_most_recently_built_configuration_wins(self): + touch(self.build / "Debug", mtime=1_000_000) + touch(self.build / "Release", mtime=3_000_000) + touch(self.build / "RelWithDebInfo", mtime=2_000_000) + self.assertEqual(self.resolve(), str(self.build / "Release")) + + def test_a_configuration_missing_a_program_is_skipped(self): + touch(self.build / "Release", names=PROGRAMS[:2], mtime=9_000_000) # newer but incomplete + touch(self.build / "Debug", mtime=1_000_000) + self.assertEqual(self.resolve(), str(self.build / "Debug")) + + def test_nothing_found_returns_the_folder_given(self): + # so the "Test programs not found in " message names what the user passed + self.assertEqual(self.resolve(), str(self.build)) + touch(self.build / "Release", names=PROGRAMS[:1]) + self.assertEqual(self.resolve(), str(self.build)) + + def test_unknown_configuration_folder_is_not_searched(self): + touch(self.build / "Custom") + self.assertEqual(self.resolve(), str(self.build)) + + +if __name__ == "__main__": + unittest.main() From c5dc2d0330f5e20bf26571e770a374b5dd24a79a Mon Sep 17 00:00:00 2001 From: bbareth <179921368+BBareth@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:04:21 +0100 Subject: [PATCH 49/53] shader_carve.py: reject incomplete DXBC parts --- tests/test_shader_carve.py | 23 +++++++++++++++++++++++ tools/shader_carve.py | 30 +++++++++++++++++++++++------- 2 files changed, 46 insertions(+), 7 deletions(-) diff --git a/tests/test_shader_carve.py b/tests/test_shader_carve.py index 7fddd87f4..1404fdd52 100644 --- a/tests/test_shader_carve.py +++ b/tests/test_shader_carve.py @@ -437,6 +437,29 @@ class ShaderCarveCliIntegrationTest(unittest.TestCase): self.assertIsNone(index[5]["sm"]) self.assertIn("PRIV", index[5]["parts"]) + def test_carve_rejects_incomplete_parts_and_continues(self): + valid = make_dxbc([(b"PRIV", bytes(range(32)))]) + short_directory = bytearray(valid) + struct.pack_into(" dict: - n = struct.unpack_from(" len(dxbc): + raise ValueError("truncated DXBC part table") out = {} - for k in range(n): - off = struct.unpack_from(" len(dxbc): + raise ValueError("truncated DXBC part payload") + out[fourcc.decode("latin-1")] = (off + 8, size) return out def shader_model(dxbc: bytes, p: dict): if "DXIL" not in p: return None, None - off, _ = p["DXIL"] + off, size = p["DXIL"] + if size < 4: + raise ValueError("truncated DXIL version and stage") ver, kind = struct.unpack_from("> 4}.{ver & 0xF}" @@ -81,8 +93,12 @@ def main() -> int: if data[:4] != b"DXBC" or len(data) != size: bad += 1 continue - p = parts(data) - stage, sm = shader_model(data, p) + try: + p = parts(data) + stage, sm = shader_model(data, p) + except ValueError: + bad += 1 + continue fname = file_name(name, seen, used) with open(os.path.join(out, fname), "wb") as f: f.write(data) From 489258fda505ac7be0c66974583749519577e6e7 Mon Sep 17 00:00:00 2001 From: mrb-eel <323506043+mrb-eel@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:05:17 +0100 Subject: [PATCH 50/53] Resolve colour MSAA regions into destination offsets --- docs/d3d12_vulkan.md | 16 +++-- runtime/shims/d3d12_com.cpp | 11 +++ runtime/shims/d3d12_com.h | 3 + runtime/shims/d3d12_vulkan_device.cpp | 15 +++++ runtime/src/command_list.h | 18 ++++- runtime/src/vulkan_replay.h | 25 +++++-- runtime/test/d3d12_vulkan_device_test.cpp | 81 +++++++++++++++++++++++ 7 files changed, 153 insertions(+), 16 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 2dc43ac00..e889e8835 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -150,7 +150,7 @@ What is implemented (all of it testable without the game): - **IR** (`runtime/src/command_list.h`): legacy barriers (transition, UAV, aliasing; split barriers record their end half), enhanced barriers (global, buffer, texture; the half with `SyncAfter = SPLIT` is dropped and the other is replayed as a full barrier), `ClearRenderTargetView` / `ClearDepthStencilView`, whole view or rectangles, - `CopyBufferRegion` / `CopyTextureRegion` / `CopyResource`, and `ResolveSubresource`. + `CopyBufferRegion` / `CopyTextureRegion` / `CopyResource`, and colour resolves. Views and rectangles are copied while recording, so the CPU descriptor slot can be rewritten afterwards. - **Replay** (`runtime/src/vulkan_replay.h`): `prepare` resolves and checks a list without writing anything, `emit` writes it. Legacy states map through the section 4.3 table (`vulkan_access`), enhanced barriers through @@ -163,9 +163,11 @@ What is implemented (all of it testable without the game): in place in `GENERAL` when the texture is in `COMMON`: that is D3D12's implicit promotion to a copy state. A 3D mip is one subresource. Boxed volume transfers preserve the full footprint's row and slice strides. `ResolveSubresource` becomes `vkCmdResolveImage` in the same layouts as a copy: a multisampled colour - subresource into a single-sampled one of the same size and format. Depth-stencil resolves, and resolves between - two formats of one typeless family, are refused as unsupported. A multisampled texture copies only to one with - the same sample count and has no footprint. + subresource into a single-sampled one of the same size and format. `ResolveSubresourceRegion` uses the same + Vulkan operation for non-integer colour with average mode, taking a source rectangle (or the entire subresource) + and a destination offset. Depth-stencil resolves, other resolve modes, and resolves between two formats of + one typeless family remain open. A multisampled texture copies only to one with the same sample count and has + no footprint. - **Layout tracking** (`LayoutTracker`): the current Vulkan layout of every image subresource, so barriers start from the real layout instead of the application's `before`. This is how implicit promotion and decay work: a texture in `COMMON` sits in `GENERAL`, which every promotable access can use, so a later barrier naming the @@ -240,8 +242,8 @@ Two pieces of milestone M2 that the device does not use yet, built and tested on either, so the owner can wait until no command buffer that uses the set is still running. Known gaps: shader-resource, UAV and constant-buffer views, samplers, root signatures, PSOs, draws, volume attachment -views, placed and reserved resources, `GetGPUVirtualAddress` (the shared buffer arena), depth-stencil resolves and -`ResolveSubresourceRegion`, 1D textures and the swapchain; +views, placed and reserved resources, `GetGPUVirtualAddress` (the shared buffer arena), depth-stencil resolves, +1D textures and the swapchain; default-heap buffers are not zero-filled yet; a fence cannot be signalled to a lower value (Vulkan timelines only increase; such a signal is reported and dropped); enhanced-barrier access bits are not filtered against the sync scope, so a combination D3D12 accepts but Vulkan does not would show up as a validation error; the GCL8 @@ -638,7 +640,7 @@ The trace will enumerate them. images copy dimension, format, mip levels, array layers and sample count. - Copies: `CopyBufferRegion` → `vkCmdCopyBuffer` with arena offsets; `CopyTextureRegion` → `vkCmdCopyBufferToImage`/`vkCmdCopyImageToBuffer`/`vkCmdCopyImage`, using the `D3D12_PLACED_SUBRESOURCE_FOOTPRINT` - row pitch and height; `CopyResource` → a whole-subresource copy; `ResolveSubresource` → `vkCmdResolveImage`. + row pitch and height; `CopyResource` → a whole-subresource copy; colour resolves → `vkCmdResolveImage`. Partial resolve regions need a shader or a region copy. - Clears: a full-subresource clear maps to `vkCmdClearColorImage`/`vkCmdClearDepthStencilImage` (UAV buffers to `vkCmdFillBuffer`); a rect clear uses `vkCmdClearAttachments` inside the rendering scope. UAV image clears use diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 9ee34d761..0a571f217 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -166,6 +166,17 @@ public: check(list_.resolve_subresource({resource_id(dst), dst_subresource, resource_id(src), src_subresource})); } + void STDMETHODCALLTYPE ResolveSubresourceRegion(ID3D12Resource* dst, UINT dst_subresource, UINT x, UINT y, + ID3D12Resource* src, UINT src_subresource, D3D12_RECT* rect, + DXGI_FORMAT format, D3D12_RESOLVE_MODE mode) override { + if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT || mode != D3D12_RESOLVE_MODE_AVERAGE || + !color_resolve_format_matches(format, dst, src)) + return check(false); + leonida::ResolveRegion region{x, y, std::nullopt}; + if (rect) region.src_rect = leonida::Rect{rect->left, rect->top, rect->right, rect->bottom}; + check(list_.resolve_subresource({resource_id(dst), dst_subresource, resource_id(src), src_subresource, region})); + } + void STDMETHODCALLTYPE ClearRenderTargetView(D3D12_CPU_DESCRIPTOR_HANDLE view, const FLOAT color[4], UINT count, const D3D12_RECT* rects) override { if (!view.ptr || !color) return check(false); diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 472f5786f..36f4f5f5b 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -55,6 +55,9 @@ void set_device_outer(ID3D12Device* device, IUnknown* outer); // The VkImage behind a texture created by such a device, or VK_NULL_HANDLE. For tests and the swapchain. VkImage vulkan_image(ID3D12Resource* resource); +// Whether both resources use the requested typed, non-integer colour format for a regional average resolve. +bool color_resolve_format_matches(DXGI_FORMAT format, ID3D12Resource* dst, ID3D12Resource* src); + // The maxPushConstantsSize in bytes of the Vulkan physical device behind `device`, or 0 if not a Vulkan device. std::uint32_t device_max_push_constants_size(ID3D12Device* device); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e3def8865..302951622 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -782,6 +782,21 @@ VkImage vulkan_image(ID3D12Resource* resource) { return r ? r->image() : VK_NULL_HANDLE; } +bool color_resolve_format_matches(DXGI_FORMAT format, ID3D12Resource* dst, ID3D12Resource* src) { + if (!dst || !src) return false; + const Format requested = vulkan_format(format, false); + if (requested.typeless || requested.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return false; + if (format == DXGI_FORMAT_R32G32B32A32_UINT || format == DXGI_FORMAT_R8G8B8A8_UINT || + format == DXGI_FORMAT_R32_UINT) + return false; + const auto matches = [&](ID3D12Resource* resource) { + const D3D12_RESOURCE_DESC desc = resource->GetDesc(); + return vulkan_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL).format == + requested.format; + }; + return matches(dst) && matches(src); +} + std::uint32_t device_max_push_constants_size(ID3D12Device* device) { if (!device) return 0; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 83b5df40d..cded8c843 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -269,13 +270,20 @@ struct CopyResource { ResourceId src; }; -// ResolveSubresource: a multisampled subresource into a single-sampled one of the same size. The call's format is -// not kept: the resolve uses the textures' own format, which D3D12 requires to be compatible. +struct ResolveRegion { + std::uint32_t dst_x; + std::uint32_t dst_y; + std::optional src_rect; +}; + +// Without a region, both subresources have the same extent. A region with no source rectangle takes the +// entire source to the given destination offset. The resolve uses the images' own format. struct ResolveSubresource { ResourceId dst; std::uint32_t dst_subresource; ResourceId src; std::uint32_t src_subresource; + std::optional region = std::nullopt; }; // D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. @@ -363,6 +371,12 @@ public: // A resource has one sample count, so it cannot be resolved into itself. bool resolve_subresource(const ResolveSubresource& resolve) { if (!resolve.dst || !resolve.src || resolve.dst == resolve.src) return false; + if (const auto& region = resolve.region) { + if (region->dst_x > INT32_MAX || region->dst_y > INT32_MAX) return false; + if (const auto& r = region->src_rect; + r && (r->left < 0 || r->top < 0 || r->right <= r->left || r->bottom <= r->top)) + return false; + } return append(resolve); } diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 1bcee80a3..928f26ea5 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -724,9 +724,7 @@ inline ReplayResult prepare_resource_copy(Prepared& p) { return ReplayResult::success; } -// ResolveSubresource through vkCmdResolveImage: a multisampled colour subresource into a single-sampled one of -// the same size and format. Depth-stencil resolves, and resolves between two formats of a typeless family, are -// not supported yet. +// Resolve a multisampled colour image into a single-sampled image of the same format. inline ReplayResult prepare_resolve(const ResolveSubresource& resolve, Prepared& p) { VkImageSubresourceRange dst{}, src{}; if (!copy_subresource(p.binding, resolve.dst_subresource, dst) || @@ -734,13 +732,26 @@ inline ReplayResult prepare_resolve(const ResolveSubresource& resolve, Prepared& return ReplayResult::invalid_subresource; if (p.source.samples <= 1 || p.binding.samples != 1 || p.binding.volume) return ReplayResult::invalid_copy; const VkExtent2D from = mip_extent(p.source, src.baseMipLevel), to = mip_extent(p.binding, dst.baseMipLevel); - if (from.width != to.width || from.height != to.height) return ReplayResult::invalid_copy; + VkOffset3D src_offset{}, dst_offset{}; + VkExtent3D extent{from.width, from.height, 1}; + if (const auto& region = resolve.region) { + dst_offset = {std::int32_t(region->dst_x), std::int32_t(region->dst_y), 0}; + if (const auto& r = region->src_rect) { + if (std::uint32_t(r->right) > from.width || std::uint32_t(r->bottom) > from.height) + return ReplayResult::invalid_copy; + src_offset = {r->left, r->top, 0}; + extent = {std::uint32_t(r->right - r->left), std::uint32_t(r->bottom - r->top), 1}; + } + if (!within(region->dst_x, extent.width, to.width) || !within(region->dst_y, extent.height, to.height)) + return ReplayResult::invalid_copy; + } else if (from.width != to.width || from.height != to.height) { + return ReplayResult::invalid_copy; + } if (src.aspectMask != VK_IMAGE_ASPECT_COLOR_BIT || dst.aspectMask != VK_IMAGE_ASPECT_COLOR_BIT || p.source.format != p.binding.format) return ReplayResult::unsupported; - p.resolve = {{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, {0, 0, 0}, - {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, {0, 0, 0}, - {from.width, from.height, 1}}; + p.resolve = {{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, src_offset, + {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, dst_offset, extent}; p.range = dst; p.source_range = src; return ReplayResult::success; diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp index dc69dcf6e..4c6b164f6 100644 --- a/runtime/test/d3d12_vulkan_device_test.cpp +++ b/runtime/test/d3d12_vulkan_device_test.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #define EXPECT(condition) do { \ @@ -644,6 +645,86 @@ int main() { down + resolved_place.Offset + row * resolved_place.Footprint.RowPitch + col * 4, resolved_green, 4); + // Move a cropped two-colour region into a larger red texture. + constexpr UINT region_width = 10, region_height = 9; + constexpr auto region_format = DXGI_FORMAT_R8G8B8A8_UNORM; + const auto region_desc = + texture_desc(region_width, region_height, region_format, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + Ref region_target; + EXPECT(SUCCEEDED(create(default_heap, region_desc, D3D12_RESOURCE_STATE_RENDER_TARGET, region_target))); + device->CreateRenderTargetView(region_target.p, nullptr, rtv0); + cursor = 0; + const auto region_place = place(device.p, region_target.p, 0, cursor); + EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr))); + barrier = transition(msaa.p, D3D12_RESOURCE_STATE_RESOLVE_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &barrier); + const D3D12_RECT blue_patch{2, 3, 4, 5}; + list->ClearRenderTargetView(rtv1, blue, 1, &blue_patch); + list->ClearRenderTargetView(rtv0, red, 0, nullptr); + const D3D12_RESOURCE_BARRIER resolve_barriers[] = { + transition(msaa.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE), + transition(region_target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_DEST)}; + list->ResourceBarrier(2, resolve_barriers); + D3D12_RECT region{1, 2, 5, 5}; + const auto region_copy = subresource(region_target.p, 0), region_out = footprint(readback.p, region_place); + const auto resolve_and_readback = [&](UINT x, D3D12_RECT* rect, UINT64 fence_value) { + list7->ResolveSubresourceRegion(region_target.p, 0, x, 1, msaa.p, 0, rect, region_format, + D3D12_RESOLVE_MODE_AVERAGE); + const auto to_copy = transition(region_target.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + list->CopyTextureRegion(®ion_out, 0, 0, 0, ®ion_copy, nullptr); + if (list->Close() != S_OK) return false; + queue->ExecuteCommandLists(1, lists); + return rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success && + SUCCEEDED(queue->Signal(fence.p, fence_value)) && + SUCCEEDED(fence->SetEventOnCompletion(fence_value, nullptr)); + }; + EXPECT(resolve_and_readback(4, ®ion, 5)); + const std::uint8_t resolved_red[4] = {255, 0, 0, 255}, resolved_blue[4] = {0, 0, 255, 255}; + for (UINT row = 0; row < region_height; ++row) + for (UINT col = 0; col < region_width; ++col) { + const bool in_region = row >= 1 && row < 4 && col >= 4 && col < 8; + const bool in_blue = row >= 2 && row < 4 && col >= 5 && col < 7; + report("partial resolve texel", row * region_width + col, + down + region_place.Offset + row * region_place.Footprint.RowPitch + col * 4, + in_blue ? resolved_blue : in_region ? resolved_green : resolved_red, 4); + } + + // A null rectangle resolves the entire source at the destination offset. + EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr))); + const auto to_resolve = transition(region_target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RESOLVE_DEST); + list->ResourceBarrier(1, &to_resolve); + EXPECT(resolve_and_readback(1, nullptr, 6)); + for (UINT row = 0; row < region_height; ++row) + for (UINT col = 0; col < region_width; ++col) { + const bool in_source = row >= 1 && col >= 1 && col < 9; + const bool in_blue = row >= 4 && row < 6 && col >= 3 && col < 5; + report("whole source at offset", row * region_width + col, + down + region_place.Offset + row * region_place.Footprint.RowPitch + col * 4, + in_blue ? resolved_blue : in_source ? resolved_green : resolved_red, 4); + } + + D3D12_RECT out_of_source{0, 0, LONG(size + 1), 1}; + for (auto [x, rect] : {std::pair{0u, &out_of_source}, std::pair{7u, ®ion}}) { + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + list->ResourceBarrier(1, &to_resolve); + list7->ResolveSubresourceRegion(region_target.p, 0, x, 1, msaa.p, 0, rect, region_format, + D3D12_RESOLVE_MODE_AVERAGE); + EXPECT(list->Close() == S_OK); + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::invalid_copy); + } + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + list7->ResolveSubresourceRegion(region_target.p, 0, 4, 1, msaa.p, 0, ®ion, region_format, + D3D12_RESOLVE_MODE_MAX); + EXPECT(list->Close() == E_INVALIDARG); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + list7->ResolveSubresourceRegion(region_target.p, 0, 4, 1, msaa.p, 0, ®ion, + DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, D3D12_RESOLVE_MODE_AVERAGE); + EXPECT(list->Close() == E_INVALIDARG); + // A resolve of a resource into itself is refused when it is recorded, one from a single-sampled // texture when it is executed; nothing is submitted. EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); From 3eb5ad9892661ef9785ab895ea42b3da8cf92f0c Mon Sep 17 00:00:00 2001 From: ItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:14:04 -0500 Subject: [PATCH 51/53] docs: drop the open-question rows the #284 merge duplicated again Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 994d40bd3..0c1c03571 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1120,10 +1120,6 @@ Xodus is LGPL-2.1 and is cited only for its coverage number, not as a code sourc | 12 | Does the game rely on async compute or copy queues for correctness? | Trace queue creation and cross-queue fences. If only performance, serialize on one queue for boot. | | 13 | Is 144 bytes of push constants available on all target GPUs? | **Resolved / Measured** (D3D-14). Checked at device creation in `runtime/shims/d3d12_vulkan_device.cpp`. Measured across the test fleet (#166): NVIDIA (256 B), AMD (256 B), and Apple M1/MoltenVK (4096 B) satisfy 144 B natively; Intel Arc exposes only the core minimum 128 B (`maxPushConstantsSize == 128`). Below 144 B, the device logs a warning and marks `push_constants_need_fallback`, routing the 16-byte tail (dwords 32..35: heap base and code base) to a uniform-buffer fallback. | | 10 | Does the game use binning, DCC, VRS, wave MMA, stream output, tessellation, or amplification shaders? | **Shaders: answered** by `tools/feature_scan.py` over all 26,503 (1.0.2.1): no hull, domain or amplification shader (DXIL program kinds: 2,236 VS, 12,101 PS, 195 GS, 2,689 CS, 9,282 MS); no `WAVE_MMA` or `SHADING_RATE` in any SFI0, and no `v_mfma`/`v_wmma`/`v_smfmac` in the disassembly; no output-signature element on a stream other than 0 (all 195 GS write stream 0 only) and no GDS / `ds_ordered_count` / GWS instruction, so no stream-output path. Also from SFI0: 10 PS need ROVs (pixel interlock), 30 shaders `TILED_RESOURCES` (see #18), 685 `ATOMIC_INT64_ON_TYPED_RESOURCE`. Binning and DCC are not shader-visible; they stay open for the PSO/stream subobjects. | -| 10 | Does the game use binning, DCC, VRS, wave MMA, stream output, tessellation, or amplification shaders? | **Shaders: answered** by `tools/feature_scan.py` over all 26,503 (1.0.2.1): no hull, domain or amplification shader (DXIL program kinds: 2,236 VS, 12,101 PS, 195 GS, 2,689 CS, 9,282 MS); no `WAVE_MMA` or `SHADING_RATE` in any SFI0, and no `v_mfma`/`v_wmma`/`v_smfmac` in the disassembly; no output-signature element on a stream other than 0 (all 195 GS write stream 0 only) and no GDS / `ds_ordered_count` / GWS instruction, so no stream-output path. Also from SFI0: 10 PS need ROVs (pixel interlock), 30 shaders `TILED_RESOURCES` (see #18), 685 `ATOMIC_INT64_ON_TYPED_RESOURCE`. Binning and DCC are not shader-visible; they stay open for the PSO/stream subobjects. | -| 11 | What should `CheckFeatureSupport` answer for UMA, resource binding tier, mesh tier, RT tier? | **Implemented** (D3D-11). Reports truthful host architecture (discrete desktop GPU: non-UMA), ResourceBindingTier 3 (descriptor indexing / bindless support), 48-bit GPU virtual address support matching the arena, and maps `D3D12_FEATURE_FORMAT_SUPPORT` directly to `vkGetPhysicalDeviceFormatProperties`. | -| 12 | Does the game rely on async compute or copy queues for correctness? | Trace queue creation and cross-queue fences. If only performance, serialize on one queue for boot. | -| 13 | Is 144 bytes of push constants available on all target GPUs? | **Resolved / Measured** (D3D-14). Checked at device creation in `runtime/shims/d3d12_vulkan_device.cpp`. Measured across the test fleet (#166): NVIDIA (256 B), AMD (256 B), and Apple M1/MoltenVK (4096 B) satisfy 144 B natively; Intel Arc exposes only the core minimum 128 B (`maxPushConstantsSize == 128`). Below 144 B, the device logs a warning and marks `push_constants_need_fallback`, routing the 16-byte tail (dwords 32..35: heap base and code base) to a uniform-buffer fallback. | | 14 | Are there PSOs with two code-base stages? | Count from the PSO/shader hash table and the index metadata. If yes, implement per-stage code-base slots (section 5.2). **Per stage, measured** (`tools/feature_scan.py`, `s_getpc_b64` kept for data rather than a far branch): 54 VS, 93 PS, 266 MS, 263 CS, 0 GS; the translator's `uses_code_base` gives the same counts (with LLVM 23 that needs #223, without which these 1,471 shaders are rejected). So VS+PS and MS+PS pipelines with two code-base stages are possible; whether any exists depends on which shaders a PSO pairs, which is in the executable, not in `shaders.rpf`. | | 15 | Is `ExecuteIndirect` used with signatures Vulkan cannot express directly? | Trace `CreateCommandSignature` and `ExecuteIndirect`; implement simple signatures first, expand the complex ones with compute. | | 16 | Does the game use append/consume UAV counters or typed buffer formats the translator does not model? | Trace UAV descs and shader `buffer_*` ops; extend the translator/runtime together. | From d7cbc3e7cb4d031c790dddd265a83fb6a1a1a7a5 Mon Sep 17 00:00:00 2001 From: ItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:22:19 -0500 Subject: [PATCH 52/53] Translator: split a dispatch OpSwitch past SPIR-V's limits into two levels With --wave64-emulate the two ScreenProbes compute shaders reach ~37k dispatch blocks: one OpSwitch of 74k words, past the 65,535-word instruction limit (and spirv-val's 16,383-case cap). An outer switch on pc / 16000 now picks a chunk; each chunk is its own selection construct whose blocks exit to its merge. All 26,503 shaders translate and validate with --wave64-emulate. Co-Authored-By: Claude Opus 5.5 --- tools/rdna2spirv.py | 60 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 2 deletions(-) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index e5a061eaa..6a62571cb 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -5587,9 +5587,65 @@ def assemble(gen): "%live = OpLabel\n OpReturn\n OpFunctionEnd\n") else: tail = end_lock + " OpReturn\n OpFunctionEnd\n" - return no_contraction(dedupe_types( + return split_big_switch(no_contraction(dedupe_types( "\n".join(" " + l if not l.startswith("%") or " = " not in l else l for l in out) + - "\n" + "\n".join(gen.body) + "\n" + tail)) + "\n" + "\n".join(gen.body) + "\n" + tail))) + + +# SPIR-V caps an instruction at 65,535 words. The dispatch loop's OpSwitch has one (literal, label) pair per block, +# and with --wave64-emulate the two ScreenProbes compute shaders reach ~37k blocks (74k words). Past the limit the +# switch becomes two levels: an outer one on pc / SWITCH_CHUNK picks a chunk; each chunk is its own selection +# construct (inner OpSwitch on pc, merge %swm), and that chunk's blocks branch to %swm, which goes on to +# %sw_merge. Every block keeps its label and code, so only the routing changes. +SWITCH_CHUNK = 16000 # spirv-val also caps a switch at 16,383 (literal, label) pairs +_BIG_SWITCH = re.compile(r"^(\s*)OpSwitch %pcv %sw_default ((?:\d+ %\w+ ?)+)$", re.M) + + +def split_big_switch(text): + m = _BIG_SWITCH.search(text) + if not m: + return text + pairs = m.group(2).split() + cases = [(int(pairs[i]), pairs[i + 1]) for i in range(0, len(pairs), 2)] + if len(cases) <= 16383 and 3 + 2 * len(cases) <= 65535: + return text + ind = m.group(1) + chunk_of = {lbl: v // SWITCH_CHUNK for v, lbl in cases} + chunks = sorted(set(chunk_of.values())) + outer = f"{ind}OpSwitch %pcc %sw_default " + " ".join(f"{k} %swc{k}" for k in chunks) + heads = [] + for k in chunks: + inner = " ".join(f"{v} {lbl}" for v, lbl in cases if chunk_of[lbl] == k) + heads += [f"%swc{k} = OpLabel", f"{ind}OpSelectionMerge %swm{k} None", f"{ind}OpSwitch %pcv %swm{k} {inner}"] + # OpSelectionMerge must stay right before its switch, so the chunk index is computed above it + pre = text[:m.start()] + sel = pre.rfind("OpSelectionMerge %sw_merge None") + sel = pre.rfind("\n", 0, sel) + 1 + pre = pre[:sel] + f"{ind}%pcc = OpUDiv %uint %pcv %c_swchunk\n" + pre[sel:] + lines = pre.split("\n") + [outer] + heads + text[m.end():].split("\n")[1:] + # route each block's exits to its chunk's merge: a block runs from its label to the next case label + out, cur = [], None + for line in lines: + st = line.strip() + if st.endswith("= OpLabel"): + lbl = st.split(" = ")[0] + if lbl in chunk_of: + cur = chunk_of[lbl] + elif lbl in ("%sw_default", "%sw_merge") or lbl.startswith("%swc"): + cur = None + if lbl_is_sw_default(st): + out += [f"%swm{k} = OpLabel\n{ind}OpBranch %sw_merge" for k in chunks] # after every chunk's blocks + if cur is not None and st == "OpBranch %sw_merge": + line = line.replace("OpBranch %sw_merge", f"OpBranch %swm{cur}") + out.append(line) + text = "\n".join(out) + # the chunk-size constant, next to the other uint constants + first = re.search(r"^\s*%\w+ = OpConstant %uint \d+$", text, re.M) + return text[:first.start()] + f"%c_swchunk = OpConstant %uint {SWITCH_CHUNK}\n" + text[first.start():] + + +def lbl_is_sw_default(st): + return st == "%sw_default = OpLabel" _FLOAT_ARITH = re.compile(r"^\s*(%\w+) = Op(?:FMul|FAdd|FSub|FDiv|FNegate|FRem|FMod) ", re.M) From d937b7f092dbc188b59754e5c73c1a9dac553cf9 Mon Sep 17 00:00:00 2001 From: ItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:26:07 -0500 Subject: [PATCH 53/53] vk_pipeline_check: read subgroup_size null (--wave64-emulate: any size) as no required size Co-Authored-By: Claude Opus 5.5 --- runtime/test/vk_pipeline_check.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index 71a0b7ab4..aff8b85f5 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -230,7 +230,12 @@ struct JsonParser { if (error) return m; if (!consume(':')) { fail("expected ':' in shader metadata"); return m; } if (k == "stage") m.stage = parse_string(); - else if (k == "subgroup_size") m.subgroup_size = parse_u32(); + else if (k == "subgroup_size") { + // null: translated with --wave64-emulate, exact on any subgroup size, so request none (0) + ws(); + if (s.compare(i, 4, "null") == 0) { i += 4; m.subgroup_size = 0; } + else m.subgroup_size = parse_u32(); + } else if (k == "writes_depth") m.writes_depth = parse_bool(); else if (k == "needs_maintenance8") m.needs_maintenance8 = parse_bool(); else if (k == "features") m.features = parse_str_array();