diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml
index f3437a644..ddc0d36b8 100644
--- a/.github/workflows/runtime.yml
+++ b/.github/workflows/runtime.yml
@@ -186,6 +186,17 @@ jobs:
--summary "$GITHUB_STEP_SUMMARY" --label "$(wine --version)"
--require loader --require pe_loader --require loader_tls --require unimplemented_policy
--require run_tiny_game --require run_tiny_game_exit_code
+ # The general Wine runner skips tests driven by the Windows runner's cmake.
+ - name: Loaded async callbacks under Wine
+ env:
+ WINEPREFIX: ${{ runner.temp }}/wineprefix
+ WINEDLLOVERRIDES: "mscoree,mshtml="
+ WINEDEBUG: "-all"
+ run: >-
+ xvfb-run -a cmake -DRUNNER=wine
+ -DLOADER="$GITHUB_WORKSPACE/runtime/build/gta6rt.exe"
+ -DGUEST="$GITHUB_WORKSPACE/runtime/build/fixtures/game/RelWithDebInfo/tiny_async.exe"
+ -P runtime/test/check_loaded_async.cmake
# Also runs the hand-written GPU tests (runtime/test/shaders) on Mesa's llvmpipe, a software Vulkan driver, so a
# translator or harness change that breaks a test result shows up on every pull request, without a GPU.
@@ -215,7 +226,7 @@ jobs:
run: cmake --build runtime/build --parallel
- name: Check GPU tools exist
run: |
- for tool in vk_harness vk_pipeline_check vk_command_replay_test vk_compute_test vk_texture_test vk_store_test vk_bindless_test depth24_convert_test clear_color_test d3d12_state_map_test command_list_test descriptor_table_test gfx10_descriptors_test; do
+ for tool in vk_harness vk_pipeline_check vk_command_replay_test vk_predicate_capture_test vk_predicated_copy_test vk_compute_test vk_texture_test vk_store_test vk_bindless_test depth24_convert_test clear_color_test predicated_copy_test d3d12_state_map_test command_list_test descriptor_table_test gfx10_descriptors_test; do
if [ ! -f "runtime/build/$tool" ] && [ ! -f "runtime/build/$tool.exe" ]; then
echo "Missing: $tool"
exit 1
@@ -224,6 +235,14 @@ jobs:
echo "All GPU tools built"
- name: CPU runtime tests (Linux)
run: ctest --test-dir runtime/build --output-on-failure
+ - name: Predicate and byte-copy shader validation and lifetimes
+ run: |
+ python3 -c 'import re,struct; from pathlib import Path; s=Path("runtime/src/predicate_reduce_spv.h").read_text(); w=[int(x,16) for x in re.findall(r"0x([0-9a-f]{8})u",s)]; Path("runtime/build/predicate_reduce.spv").write_bytes(struct.pack("<%dI"%len(w),*w))'
+ spirv-val --target-env vulkan1.1 runtime/build/predicate_reduce.spv
+ runtime/build/vk_predicate_capture_test
+ python3 -c 'import re,struct; from pathlib import Path; s=Path("runtime/src/predicated_copy_spv.h").read_text(); w=[int(x,16) for x in re.findall(r"0x([0-9a-f]{8})u",s)]; Path("runtime/build/predicated_copy.spv").write_bytes(struct.pack("<%dI"%len(w),*w))'
+ spirv-val --target-env vulkan1.2 runtime/build/predicated_copy.spv
+ runtime/build/vk_predicated_copy_test
- name: GPU tests on llvmpipe
run: |
vulkaninfo --summary | grep -E 'deviceName.*llvmpipe' # fails the step if llvmpipe isn't there
diff --git a/README.md b/README.md
index 6c7f77a53..e369972cc 100644
--- a/README.md
+++ b/README.md
@@ -13,6 +13,7 @@
+ Other languages |
Status |
How to build |
How it works |
@@ -111,6 +112,14 @@ compute and mesh shaders 64-wide. The mode is saved next to the translated shade
again. With `auto`, a work folder that previously used emulation keeps it for later translations and retries, even if
the current GPU supports native wave64. Use `--wave64-emulate off` to translate it natively.
+Four fallback flags are forwarded to the translator the same way, saved next to the translated shaders, and changing
+them translates them again: `--no-float-controls` (drop `SignedZeroInfNanPreserve`, for devices whose pipeline check
+skips a shader without `shaderSignedZeroInfNanPreserveFloat32`; needs PR #664's translator flag), `--bary-fallback`
+(read raw barycentrics from an interpolated input, for devices without `VK_KHR_fragment_shader_barycentric`),
+`--texel-offset-fallback` (fold `image_sample*_o` offsets into the coordinate, for devices without
+`VK_KHR_maintenance8`) and `--mesh-compute` (mesh shaders as compute, for devices without `VK_EXT_mesh_shader`).
+Each is documented in [docs/design.md](docs/design.md).
+
The build records which llvm-mc command and version produced the disassembly. Changing either, or reusing a work
folder that predates this record, reruns disassembly and translation while keeping the extracted shader inputs.
@@ -137,22 +146,27 @@ cmake --build runtime/build/linux --parallel
Pass the directory containing `index.json` and the translated SPIR-V files to `vk_pipeline_check`.
`make_game.py` runs on Linux too. The `pipelines` stage uses the `vk_pipeline_check` built above
-(`runtime/build/linux`, or `runtime/build`). The `runtime` stage builds on Windows only, so on Linux it needs a
-Windows build of `runtime/`; without one it is left out of the default stages, and asking for it fails before any
-work starts.
+(`runtime/build/linux`, or `runtime/build`), and builds it there itself before any other work if it is missing.
### Running the loader on Linux
The loader is a Windows program and runs under Wine or Proton; CI runs its tests under Wine on every change to
-`runtime/` (the `wine` job of the Runtime workflow). Give the `runtime` stage a folder with `gta6rt.exe` and
-`gta6rt_tls_host.dll`, such as the `runtime-windows` artifact of that workflow's `windows` job, unzipped:
+`runtime/` (the `wine` job of the Runtime workflow). On Linux the `runtime` stage cross-builds it into
+`runtime/build/windows` with clang-cl and lld-link (LLVM 19+; plain names, or all five LLVM tools with one version
+suffix such as `clang-cl-21`) against the MSVC CRT and Windows SDK that
+[xwin](https://github.com/Jake-Shadle/xwin) lays out, in `XWIN_DIR` or `~/.local/share/xwin-sdk`
+([docs/testing.md](docs/testing.md#the-windows-runtime-on-linux-under-wine-or-proton) has the one-time `xwin`
+command). Without them the stage is left out of the default stages, and asking for it lists what is missing before
+any work starts. A Windows build made elsewhere works too, such as the `runtime-windows` artifact of that workflow's
+`windows` job, unzipped:
```sh
python3 -I make_game.py --runtime-build ~/Downloads/runtime-windows
```
-It copies both files into `--out` and writes `gta6rt.sh` next to them, which starts `gta6rt.exe` with `wine`, or
-with the Wine named by `WINE` (for Proton, its `files/bin/wine`). The same option skips the build on Windows.
+Either way it copies `gta6rt.exe` and `gta6rt_tls_host.dll` into `--out` and writes `gta6rt.sh` next to them, which
+starts `gta6rt.exe` with `wine`, or with the Wine named by `WINE` (for Proton, its `files/bin/wine`). The same option
+skips the build on Windows.
## How it works
diff --git a/docs/README.md b/docs/README.md
index 1632a7d41..fc65df604 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -28,7 +28,7 @@ method, scope and caveats. No game data is included.
| [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. Building a placed world from entity rows (`world_build.py --placements`). |
+| [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. Building a placed world from entity rows (`world_build.py --placements`): shared geometry per chunk (`EXT_mesh_gpu_instancing`), bounded memory for the whole archive, and per-tier LOD chunk sets with distance bands (`--lod-sets`). |
| [world_census.md](world_census.md) | Full `levels.rpf` pass: 23,535 maps / 1,670,442 entities, 98.32% stream coverage, sharded and exact; the SixNG 30,785-map difference reconciled map by map (interiors and entity groups). |
| [world_names.md](world_names.md) | Name resolution: `archetypeName` and map `name`/`parent` are lower-cased joaat; 64-bit keys are MurmurHash3 x64 low 64. With `rpf9_names.py` names, 99.85% of the 1,670,435 entities a whole-archive `world_index` run reads resolve (64-bit verified); 5/23,535 map names, all five confirmed by the map 64-bit key. |
| [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. |
@@ -69,4 +69,5 @@ method, scope and caveats. No game data is included.
## Other languages
-Community quickstarts (stable onboarding text only; English docs remain authoritative): [i18n/README.md](i18n/README.md) (`pt-BR`, `zh-CN`).
+Community quickstarts (stable onboarding text only; English docs remain authoritative): [i18n/README.md](i18n/README.md) (`fr`, `pt-BR`, `zh-CN`).
+Community quickstarts (stable onboarding text only; English docs remain authoritative): [i18n/README.md](i18n/README.md) (`pt-BR`, `zh-CN`, `pl-PL`).
diff --git a/docs/animation.md b/docs/animation.md
index da44e6fd5..bf625f175 100644
--- a/docs/animation.md
+++ b/docs/animation.md
@@ -376,7 +376,10 @@ In 36 roots the page map says two pages, but the next listed stream does not sta
second page is right after the first stream, but `anim_index.py` does not list it: in 28 it is a zlib stream that
inflates to 16–48 bytes (`anim_index.py` lists streams of 64 bytes or more), and in 8 it is a 16-byte raw page,
like rpf9-explorer's raw system tail. `anim_clips.py` joins such a last page only when the joined pages then parse
-as a clip dictionary; all 36 do, so no root is left unresolved. Of the joined resources, 61,505 are clip
+as a clip dictionary; all 36 do, so no root is left unresolved. That recovery runs only after the page map itself
+has been read from listed streams: a root whose page map is in such an unlisted last page stays unresolved ("page
+map not in the next stream"). No anim.rpf root has that layout. In `story000.rpf` 5 roots do, with the page map in
+a 32- or 48-byte zlib tail, and none of the 5 is a clip dictionary once that tail is joined. Of the joined resources, 61,505 are clip
dictionaries. 4 have `RIG` plus a version at +0x70 instead of a pack array (rig dictionaries, not decoded here), and
1 has some other value there. Together the dictionaries use 87,234 listed streams plus the 36 unlisted pages
(3,802,124,713 stored / 7,077,351,104 inflated bytes in the listed streams). By `anim_index.py` class those
@@ -415,9 +418,12 @@ u32; u32 count}` with `Entry {u64 key; T *value; Entry *next}`. Hashes are `joaa
| `.motion` (`+0x20` is a pointer) | `+0x18` pointer | the dictionary root (page offset 0) |
| | `+0x28` u32, `+0x2C` u32 | the clip hash (the low half of its `atMap` key) and `joaat32` of the dictionary name |
| | `+0x30` atString | `pack:/.motion` |
-| | `+0x58` u32 | 1 or 2; most likely the number of blend parameters (not verified) |
+| | `+0x58` u32 | 1 or 2; selects where the parameter node is (see `+0x120`, `+0x138`); most likely the number of blend parameters (not verified) |
| | `+0x60` array, 16-byte items | children `{u64 0; u32 clip hash; u32 dictionary hash}`: the clips it blends |
-| | `+0x70` array, 0x28-byte items | one item per child (same count); a pointer at `+8`; not decoded |
+| | `+0x70` array, 0x28-byte items | one item per child: `{f32 child duration; f32 duration in the blend; {ptr; u16 count} curve of (child time, blend time) f32 pairs; 16 zero bytes}` |
+| | `+0x120` pointer (`+0x58` = 2) | a block whose `+0x18` points at the parameter node |
+| | `+0x138` pointer (`+0x58` = 1) | the parameter node: `{u64 0; u32 type; u32 0; ...}` |
+| parameter node, type 3 | `+0x10` array of u32, `+0x20` array of 8-byte items, `+0x30`/`+0x34` f32 | one sampled axis: its name hash(es), then `{u32 sample index; f32 value}` sorted by value, then min and max |
| `.motionmatcher` (`+0x20` is a pointer) | `+0x28` 16 bytes, `+0x38` atString | an id, then `pack:/.motionmatcher`; the rest is not decoded |
| animation | `+0x24` u16 | frame count |
| | `+0x28` f32 | duration = (frames − 1) / fps |
@@ -551,8 +557,25 @@ fields are in the object table above. Measured on all 17,247 `.motion` clips:
search of every clip-dictionary-like root page in `levels`, `packs`, `story000`, `story000_script`,
`story000_restofworld`, `core_restofworld`, `core_restofworld001`, `shared_minigame000`, `data`, `common` and
`script` found none of those hashes, so this package does not resolve them.
-- `+0x70` has one 0x28-byte item per child on all 17,247. Those items, and the rest of the object from `+0x80` on, are not
- decoded.
+- **Child times (`+0x70`).** One 0x28-byte item per child on all 17,247: the child's duration, its duration in the
+ blend, and a piecewise-linear curve from child time to blend time. Of the 159,584 items, 158,991 have equal
+ durations and the two points (0, 0) and (d, d), so the child plays at its own speed. 402 have a 5–82 point curve
+ from (0, 0) to (duration, blend duration), increasing in both coordinates, so the child is time-warped. The other
+ 191 have two points, but 170 don't start at (0, 0) and 21 don't end at (d, d). For every child that names a
+ `.clip` in anim.rpf, the first float is bit-for-bit that `.clip`'s duration (`+0x78`): 111,948 of 111,948.
+- **Parameter node.** When `+0x58` is 1 the node is at `+0x138`; when it is 2, `+0x120` points at a block whose
+ `+0x18` is the node. Every `.motion` has one, and it starts `{u64 0, u32 type, u32 0}`. By type: 3 on 10,171, 1 on
+ 3,557, 4 on 2,644, 5 on 482, 6 on 295, 8 on 98. Only type 3 is decoded here.
+- **Type 3: one sampled axis.** It has one u32 name hash, then 1–16 `{u32 sample index, f32 value}` items and the
+ axis min and max. On all 10,171 (29,123 samples), the items are sorted by value, min and max are the first and
+ last values, and the sample indices are 0..n−1 in some order. They are not child indices: the sample count
+ equals the child count on 4,589 of them. The name hashes are `joaat32` of a lower-case name. 88 distinct hashes
+ occur, and a word-list search resolved 10 of them, covering 5,604 axes: `yawangle` 2,524, `rotationz` 1,691,
+ `facingdirection` 638, `speed` 284, `surfaceincline` 271, `roll` 66, `verticalheight` 58, `pitch` 25,
+ `pitchangle` 25, `height` 22. The ranges fit the names: `speed` is within [0, 1], `surfaceincline` within
+ ±0.698 rad (40°), and `roll` within ±3.14. `anim_clips.py` reports every name as `motion_axis_name:`.
+- Not decoded: parameter node types other than 3, how a type-3 sample index maps to the children, and the rest of
+ the object from `+0x80`, including the `{ptr, count}` lists at `+0x90`.
The 180 `.motionmatcher` clips sit in 142 dictionaries that hold only `.motionmatcher` clips and no local pack.
The three motion matcher streams in [Bone tables and motion matchers](#bone-tables-and-motion-matchers)
diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md
index 668ca0cf1..9b10d9be6 100644
--- a/docs/d3d12_vulkan.md
+++ b/docs/d3d12_vulkan.md
@@ -284,7 +284,18 @@ What is implemented (all of it testable without the game):
2D textures in the common render-target, depth and texture formats (typeless families become mutable-format
images), plus non-attachment 3D textures with mipmapped upload, image copy and readback, and multisampled 2D
textures (single-mip render targets or depth-stencils, in the sample counts the GPU has for the format);
- - packed `R9G9B9E5_SHAREDEXP` textures map to `VK_FORMAT_E5B9G9R9_UFLOAT_PACK32` for uploads and sampled views;
+ - packed `R9G9B9E5_SHAREDEXP` textures map to `VK_FORMAT_E5B9G9R9_UFLOAT_PACK32` for uploads and sampled views.
+ When `ALLOW_UNORDERED_ACCESS` is requested on a GPU whose `VK_FORMAT_E5B9G9R9_UFLOAT_PACK32` lacks native
+ `STORAGE_IMAGE` support (for example NVIDIA), the layer backs the texture with a mutable `VK_FORMAT_R32_UINT`
+ image (`MUTABLE_FORMAT | EXTENDED_USAGE` + `VkImageFormatListCreateInfo` `{R32_UINT, E5B9G9R9_UFLOAT_PACK32}`),
+ refusing `ALLOW_RENDER_TARGET`, `ALLOW_DEPTH_STENCIL` and `DENY_SHADER_RESOURCE`: `CheckFeatureSupport` advertises
+ `TYPED_UNORDERED_ACCESS_VIEW` and `UAV_TYPED_STORE` (plus `UAV_TYPED_LOAD` with `R32_UINT` storage atomics) while
+ keeping `RENDER_TARGET` off; SRV and UAV descriptors emit the `E5B9G9R9` T# (`FORMAT 132`, RGB1) and reject
+ incompatible casts, while set 0 creates a `VK_IMAGE_USAGE_SAMPLED_BIT` `E5B9G9R9` sampled view and a
+ `VK_IMAGE_USAGE_STORAGE_BIT` `R32_UINT` storage view (bound in `as_uint` / `r32ui`, never `as_float`);
+ `ClearUnorderedAccessViewFloat` packs RGB9E5 with round-half-up (clamping negative/NaN to 0 and +Inf/overflow to
+ 65408, bumping on 512) and `ClearUnorderedAccessViewUint` writes 0, matching WARP (`d3d12_r9g9b9e5_uav_test`,
+ `d3d12_uav_clear_test`);
- the descriptor shader samples `B5G5R5A1_UNORM` through a 2D SRV. Opaque and transparent red check bit 15,
and mixed-channel texels check the five-bit color fields;
- `R10G10B10_XR_BIAS_A2_UNORM` maps to `VK_FORMAT_A2B10G10R10_UNORM_PACK32`, the same packed 10:10:10:2
@@ -1224,6 +1235,9 @@ The trace will enumerate them.
operation group the wave intrinsics map to is present (`BASIC`, `VOTE`, `BALLOT`, `SHUFFLE`, `ARITHMETIC`),
because D3D12 promises them all behind that one bool. `WaveLaneCountMin`/`Max` are the subgroup size range
(`VkPhysicalDeviceSubgroupSizeControlProperties`, or the single `subgroupSize` without those 1.3 properties).
+ The exception is an Intel integrated GPU (D3D-121): Vulkan reports 8..32 there, Intel's D3D12 driver a fixed
+ 16..16, and the layer answers 16..16 like the host. Measured on Xe-LP: UHD 770 (32.0.101.6129) and Raptor Lake-S
+ Mobile (101.7092). Discrete Arc keeps the Vulkan range until it is measured (TEST-57).
`TotalLaneCount` has no Vulkan equivalent: D3D12 counts every lane of the device, and the layer answers one full
wave, so a game that sizes work from it plans for less parallelism than the GPU has, never more. Measured
against the host PC runtime (616.86) on an RTX 5070: `S_OK` with `WaveOps` 1, lanes 32..32 and a total of 6144,
@@ -1723,7 +1737,7 @@ Not implemented yet:
- Predication (`SetPredication`) maps to `VK_EXT_conditional_rendering` (D3D-18). Done: `GraphicsCommandList::
SetPredication` records a `Predication` command (`runtime/src/command_list.h`; offset 8-byte aligned, op
`EQUAL_ZERO` or `NOT_EQUAL_ZERO`, a null buffer turns it off). The replay (`runtime/src/vulkan_replay.h`) begins
- conditional rendering on the predicate buffer, plain for `EQUAL_ZERO` (Vulkan discards when the word is 0) and
+ conditional rendering on the captured condition, plain for `EQUAL_ZERO` (Vulkan discards when the word is 0) and
`VK_CONDITIONAL_RENDERING_INVERTED_BIT_EXT` for `NOT_EQUAL_ZERO`, ends it before a new predicate (it cannot
nest) and at the end of the list (predication does not carry over to the next list). While a predicate is set,
whole-view clears are replayed as one rectangle with `vkCmdClearAttachments`, because `vkCmdClearColorImage` and
@@ -1738,14 +1752,54 @@ Not implemented yet:
Checked by part E of `vk_command_replay_test` on an NVIDIA GeForce RTX 3070, and end to end by
`d3d12_vulkan_device_test` (an occlusion query resolved into a predicate, through legacy and enhanced barriers)
on an NVIDIA GeForce RTX 5070.
+ The 64-bit value is captured on the GPU at each `SetPredication`: an internal eight-byte copy and a
+ one-invocation compute pass OR the two dwords into a private 32-bit condition. Later writes to the source do
+ not change that snapshot. A null buffer disables predication; rebinding ends the previous conditional scope
+ before the capture, so the internal dispatch is never predicated. Bounds checks require all eight bytes.
+ Capture arenas and descriptors remain alive until their command buffer's timeline ticket completes. No
+ CPU readback or per-predicate wait is used. This helper requires a compute-capable configured queue family;
+ unsupported queues fail preparation instead of falling back to the low word. The synthetic GLSL source and
+ embedded SPIR-V are shipped together; normal builds do not need a shader compiler.
+ Capturing a new predicate inside an active pipeline-statistics query is rejected as unsupported, because the
+ helper's compute invocation would otherwise pollute the application's result; capturing before the query is
+ allowed. Virtualising that query is not part of this change.
+ Integration notes for #291 and D3D-27: the capture helper binds its own compute pipeline, descriptor set 0
+ and push constants. The compute path must restore those bindings afterward, or bind its application state
+ before each dispatch. Copies and compute dispatches cannot execute inside dynamic rendering, so render-pass
+ integration must place the capture outside the rendering scope while preserving capture at `SetPredication`.
+ These are requirements for those future integrations, not compute-dispatch or render-pass support added here.
+ `CopyBufferRegion` under a predicate instead uses a byte-granular compute dispatch inside the captured
+ conditional scope; both operations, unaligned offsets and lengths, and the full 64-bit predicate are covered.
+ Zero-byte copies are no-ops, as checked against native WARP. Unpredicated copies retain `vkCmdCopyBuffer`.
+ The compute helper requires enabled Vulkan 1.2 `storageBuffer8BitAccess` (not `shaderInt8`) and a compute queue;
+ without it, preparation rejects the predicated buffer copy rather than executing it unconditionally.
+ Descriptor windows respect storage-buffer alignment/range and dispatch limits, including arena offsets.
+ Copy descriptors are owned by command-buffer slots until the submission timeline completes. Memory dependencies order prior writes,
+ subsequent reads and successive windows. Direct and compute queues support the helper; copy queues reject
+ active predication. Preparation is serialized under the tracker lock, preserving resource -> tracker -> submit
+ lock order and the copy-then-commit tracker. Readback writes accumulate COMPUTE_SHADER for the helper and COPY
+ for ordinary copies; mixed lists accumulate both before main's queue-specific host-stage filtering.
+ This helper also binds compute pipeline/set 0/push constants, so the
+ application-state restoration requirement above applies. A predicated copy inside an active pipeline-statistics
+ query is rejected to avoid counting internal compute work.
+ Synthetic checks: `predicated_copy_test` covers preparation and rejection paths without a GPU;
+ `d3d12_predicated_copy_test` compares 180 byte-exact cases against WARP and an independent literal oracle,
+ plus 16 query-to-copy cases: real empty ordinary/binary occlusion queries resolve zero into a default-heap
+ predicate at offsets 0/16, both predicate operations govern copies, and executing overwrite copies replace zero
+ with a high-word-only value. Four paired controls verify that recapturing the same address changes exactly one
+ 13-byte destination region; without recapture, later copies keep using the captured zero. Predicate-buffer guards
+ and all untouched destination bytes are checked too. These query cases do not cover nonzero visible-draw counts;
+ `vk_predicated_copy_test` forces small windows and dispatches, arena prefixes, dependent copies, offset rebinding,
+ reset, 32 gated plus 32 reused submissions, failed-submit cleanup and host stages on all three queue kinds.
+ Binary and overlapping occlusion fixtures also verify that query results resolve under a false predicate while
+ a dedicated copy destination remains unchanged; disabling predication copies into a separate region.
+ The embedded shader is generated from `predicated_copy.comp`
+ with glslang 16.6.0 (`-V --target-env vulkan1.2 -Os`) and validated for Vulkan 1.2.
+
Open:
- - Copies and resolves. D3D12 predicates `CopyBufferRegion`, `CopyTextureRegion`, `CopyResource` and
- `ResolveSubresource`; Vulkan's conditional rendering does not cover transfer commands, so they run
- unconditionally. `PreparedList::unpredicated_copies` counts them. A fix replays a predicated copy as a compute
- dispatch, which conditional rendering does cover.
- - The 64-bit value. Vulkan reads one 32-bit word, so the low dword of D3D12's value is used: wrong only when the
- low dword is 0 and the high one is not (an occlusion count that is a non-zero multiple of 2^32). A fix is a small
- compute pass that ORs both dwords into a condition buffer.
+ - Texture copies, `CopyResource` and resolves. Vulkan's conditional rendering does not cover transfer
+ commands, so these still run unconditionally and `PreparedList::unpredicated_copies` counts them.
+
- Draws, dispatches and `ExecuteIndirect` are covered by conditional rendering as soon as they are replayed
(D3D-3, D3D-4, D3D-17); `ClearUnorderedAccessView*` and `ResolveSubresource` need the same check when added.
@@ -2378,9 +2432,13 @@ on a PC device behind the Xbox-ABI proxy). Measured:
refused on an RTX 5080 (616.92), created on an AMD Radeon and on WARP, where typed UAV writes round-trip; and on
both GPUs one allocation can serve both uses, a mutable `R32_UINT` Vulkan image with `E5B9G9R9_UFLOAT_PACK32` in
its format list, written through an `R32_UINT` storage view and sampled through an `E5B9G9R9` view.
+ **Implemented** in `d3d12_vulkan_device.cpp` and `src/uav_clear.h` (`d3d12_r9g9b9e5_uav_test`): on an RTX 3060 Ti
+ (driver 621.01, `LEONIDA_FSR_DEVICE=vulkan LEONIDA_FSR_NO_STANDIN=1`, `LEONIDA_VK_VALIDATION=1`),
+ `ffxCreateContext` and `ffxDestroyContext` both return OK without `standin_slot76` and with 0 validation errors.
Open: a float store to that format rounds differently on PC devices (@Vonsek, #864: AMD Radeon truncates the
mantissas, WARP rounds to nearest even; 609 of 794 test triples differ). Which rule the console FSR needs, and
- whether its shaders store floats to that texture at all, waits on decoding its `FSPX` shaders.
+ whether its shaders store floats to that texture at all (requiring shader-side packing into the `R32_UINT` storage
+ view), waits on decoding its `FSPX` shaders.
- With that one texture created as `R32_UINT` instead (the test's PC stand-in, `standin_slot76`), or as is on
WARP, `ffxCreateContext` and `ffxDestroyContext` both return OK. Device slots called: 14 (5), 15 (26), 18 (10),
19 (16), **27
diff --git a/docs/design.md b/docs/design.md
index c925dc4d3..976b61a84 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -105,7 +105,7 @@ add a source file, add it to `runtime\CMakeLists.txt` and to the file list in `b
| Models | **Done: 350,248 models at the `917e9b9` pin** (`levels.rpf` 314,000, `story000` 7,460, `packs` 24,034, `data` 2,581, `shared_minigame000` 1,288, `core_restofworld` 885; 0 decode failures in the re-count). The `c3708fb` export was 190,792; the new entries are **159,483 drawable-dictionary children** (levels 130,225, packs 23,720, story 4,156, data 268, shared 317, core 797) plus raw-tail/mixed-block pages. The standalone total is 190,765. Triangle totals were not re-run. 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. Character skeletons are separate: the shared 597-name `.#ft` table and its model-side bone-hash mapping are in [character_skeleton.md](character_skeleton.md). | `\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 was the hard blocker: the clean-room decoder in `tools/bcpack.py` (#312) rebuilds BC1, BC3, BC4 and BC5 blocks, which `tools/ttpf_mips.py` projects to 47,882 more complete chains; BC6H/BC7 rebuilders and the port into rpf9dump's C# `TtpfReader`, which still takes the zlib/raw path, are open ([textures.md](textures.md)). An array/volume pass resolves all 678 allocation spans exactly; tile mode 9 is validated 90/90 as six 4 KiB slices, while 588 other arrays/volumes remain layout-unresolved. 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. Clip dictionaries are system-only RAGE resources (page map at the `+0x08` pointer). `tools/anim_clips.py` decodes 191,042 of 191,042 animations in 61,505 of them to per-frame values (channel types 0–5, 7, 8 and the GTA VI type 10) and resolves 111,948 of 159,584 `.motion` children to a clip. The 2/3 packed streams are second pages of `0DRP` resources, which are not decoded. No `YCD`/`RSC7` at any stream start. The `rpf9_carve` tail overread is measured in `docs/animation.md`. | `tools\anim_index.py`, `\anim-index\` |
+| 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. Clip dictionaries are system-only RAGE resources (page map at the `+0x08` pointer). `tools/anim_clips.py` decodes 191,042 of 191,042 animations in 61,505 of them to per-frame values (channel types 0–5, 7, 8 and the GTA VI type 10) and resolves 111,948 of 159,584 `.motion` children to a clip. For each `.motion` it reads the per-child durations and time curves and, on 10,171 of 17,247, the one-axis parameter node (axis name hash, sorted sample values, range). The 2/3 packed streams are second pages of `0DRP` resources, which are not decoded. 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/per-entity id/per-archetype key/LOD fields; names and most archetypes are hash-only. Archetype and map names are lower-cased joaat, confirmed by a MurmurHash3 x64 low-64 key; see [world_names.md](world_names.md). | `tools\world_index.py`, `tools\world_census.py`, `tools\world_names.py`; [world.md](world.md), [world_census.md](world_census.md), [world_names.md](world_names.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) |
@@ -176,7 +176,8 @@ 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.
+location). MODE writes (`s_setreg`) model the f16/f64 rounding field, FP_ROUND[3:2], the only MODE field the
+corpus writes; other MODE writes are refused (see Known approximations).
### GPU tests (RTX 4060 Ti)
@@ -213,6 +214,7 @@ 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). `v_readlane_b32`/`v_writelane_b32` mask the lane select with 63 in wave64 (`S1[5:0]`) and 31 in wave32 (`S1[4:0]`); until SHADER-52 both used 63, so a wave32 select ≥ 32 pointed past a 32-wide subgroup. GPU-checked with `cs_w32_lane_wrap.asm` (lane 40 → 8). |
+| DPP | VOP1/VOP2 `_dpp` applies to src0. DPP16 controls (`quad_perm`, `row_shl/shr/ror/share/xmask/mirror/half_mirror`) and DPP8 (`dpp8` + `fi`) select the source lane, then `row_mask` (one bit per 16-lane row) and `bank_mask` (one bit per 4-lane bank) decide which destination lanes update. A lane whose row/bank is off is not written. A source lane outside the row is invalid: `bound_ctrl` 1 uses 0 as src0, otherwise the lane is not written. A source lane inactive under EXEC is used when `fi` is 1; otherwise `bound_ctrl` decides. DPP8 always writes an enabled lane: `fi` 1 reads the inactive source, `fi` 0 uses 0. DPP16/8 never leaves its 16/8-lane group, so this is exact on every subgroup at least that wide; under `--wave64-emulate` the exchange goes through the workgroup buffer like the other cross-lane ops. GPU-checked with `runtime/test/shaders/cs_dpp*.asm` on an RTX 3070 and hardware-measured on an RX 6800. Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. |
| 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. VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), **not yet GPU-verified**. |
| 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. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. |
@@ -229,7 +231,13 @@ How the generated SPIR-V expects the runtime to work:
| 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 (a location any `*_f16` interp reads is a `PerVertexKHR` array of the producer's raw words instead: see "16-bit interpolation"). A param channel carries the export's raw 32 bits either way. `exp mrtN` → location N, `exp mrtz` x → `FragDepth` when x is on and the export isn't `compr` (RGBA = Z, stencil, sample mask, alpha: Mesa `ac_get_spi_shader_z_format`; the 16-bit compressed mrtz holds stencil and sample mask and never Z, `ac_nir_lower_ps_late.c` `emit_ps_mrtz_export`). Until 2026-11-22 an mrtz export without a depth wrote one anyway (0.0, or an f16 half of the stencil word) and declared `DepthReplacing`. Checked by `tests/test_translate.py` (`test_mrtz_depth_only_from_an_enabled_x`). Stencil, sample mask and alpha exports aren't modelled. |
-| 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/subrev/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/subrev/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) and the value tests in `tests/test_f16_op_sel_values.py`. **Hardware-verified** on an AMD RX 6800 (gfx1030), the instructions run as a raw compute kernel in wave32 and in wave64 (IEEE off, DX10 clamp on, denormals kept, round to nearest; the bytes assemble identically for gfx1013 and gfx1030): **`v_med3_f16`** with all 16 `op_sel` patterns, with neg/abs on a selected high half, with `clamp`, and with the destination also a source; the **plain forms** `v_add/sub/mul/max/min_f16` (`_e32`, and `_e64` with neg/abs/`clamp`), `v_fmac_f16` (`_e32`, and `_e64` with neg/abs; the accumulator is the low half of the destination), `v_rndne/floor/ceil/trunc/fract/sqrt/rcp/rsq_f16` (`_e32` and `_e64`) and `v_cvt_f16_f32`: low halves in, low half out, high half of the destination kept. 336 words per wave size (plus `v_rsq_f16_e64` and `v_ceil_f16_e64` in a later run), all as the rule says and as the translator computes. **Vulkan** (AMD Radeon RX 6800, Windows, driver 26.11.2; the nine `ps_f16_*` fixtures also pass on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux): `ps_f16_med3_opsel`, `ps_f16_med3_mods`, `ps_f16_vop2`, `ps_f16_vop2b`, `ps_f16_vop1`, `ps_f16_vop1b`, whose expected words are the hardware ones (`tests/test_f16_hw_words.py` checks them against the rule and the translator without a GPU). **Not expressible, so not verified:** `op_sel` on the VOP2 and VOP1 ops in VOP3 encoding (`v_add/sub/mul/max/min_f16_e64`, `v_fmac_f16_e64`, the unary `_e64` forms, `v_cvt_f16_f32_e64`): llvm-mc 21 rejects the modifier for gfx1013 and gfx1030, and its disassembler prints bytes that have those bits set without it (`03 08 32 d5 01 05 02 00` comes back as `v_add_f16_e64 v3, v1, v2`). The translator's `op_sel` handling for these forms is therefore never reached from a disassembly listing and rests on the ISA field description alone; whether the hardware honours the bits there is unknown, and a blob that set them would be translated as if they were clear. Also unverified: `v_exp_f16`/`v_log_f16`, NaN and denormal operands, other rounding and IEEE modes. **Driver quirk (AMD Windows driver 26.11.1, RX 9070):** `valu_fuzz` f16 seed 3 programme 38 loses the high half of v26: `v_add_f16_e32 v26, v29, v32` then `v_sub_nc_u16_e64 v28, v32, v27 op_sel:[1,1,0]` then `v_add_f16_e64 v26, v26, v28` — the final add should keep `0xCD52` in the high half, but the GPU returns `0xEEEEEEEE` (native) / `0x00000000` (`--emulate`), all 64 threads. Bisected to the pair: the add's two sources must both have been produced by earlier partial writes; either alone, a NaN input alone, or `dst==src0` alone all pass. The emitted SPIR-V was checked with `spirv-dis` in both modes: the keep (load old v26, `AND 0xFFFF0000`, `OR` new low half, store to index 26) is present and correctly addressed, so the translator is clear and this is the driver miscompiling the pattern. Minimal reproducer: the three ops above with programme 38's inits (v26 `0xCD524000`, v28 `0xC692D243`, v29 `0xBC004200`, v32 `0xB35ABD4B`, v27 `0xB48ABA06`). Pinned by `tests/test_values.py` (`v_add_f16_e64_keep_hi`, `v_add_f16_e32_keep_hi`), which check the translator's keep, not the driver. Found and bisected by 1TrickOmen, reported on #634. |
+| 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/subrev/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/subrev/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) and the value tests in `tests/test_f16_op_sel_values.py`. **Hardware-verified** on an AMD RX 6800 (gfx1030), the instructions run as a raw compute kernel in wave32 and in wave64 (IEEE off, DX10 clamp on, denormals kept, round to nearest; the bytes assemble identically for gfx1013 and gfx1030): **`v_med3_f16`** with all 16 `op_sel` patterns, with neg/abs on a selected high half, with `clamp`, and with the destination also a source; the **plain forms** `v_add/sub/mul/max/min_f16` (`_e32`, and `_e64` with neg/abs/`clamp`), `v_fmac_f16` (`_e32`, and `_e64` with neg/abs; the accumulator is the low half of the destination), `v_rndne/floor/ceil/trunc/fract/sqrt/rcp/rsq_f16` (`_e32` and `_e64`) and `v_cvt_f16_f32`: low halves in, low half out, high half of the destination kept. 336 words per wave size (plus `v_rsq_f16_e64` and `v_ceil_f16_e64` in a later run), all as the rule says and as the translator computes. **Vulkan** (AMD Radeon RX 6800, Windows, driver 26.11.2; the nine `ps_f16_*` fixtures also pass on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux): `ps_f16_med3_opsel`, `ps_f16_med3_mods`, `ps_f16_vop2`, `ps_f16_vop2b`, `ps_f16_vop1`, `ps_f16_vop1b`, whose expected words are the hardware ones (`tests/test_f16_hw_words.py` checks them against the rule and the translator without a GPU). **Not expressible, so not verified:** `op_sel` on the VOP2 and VOP1 ops in VOP3 encoding (`v_add/sub/mul/max/min_f16_e64`, `v_fmac_f16_e64`, the unary `_e64` forms, `v_cvt_f16_f32_e64`): llvm-mc 21 rejects the modifier for gfx1013 and gfx1030, and its disassembler prints bytes that have those bits set without it (`03 08 32 d5 01 05 02 00` comes back as `v_add_f16_e64 v3, v1, v2`). The translator's `op_sel` handling for these forms is therefore never reached from a disassembly listing and rests on the ISA field description alone; whether the hardware honours the bits there is unknown, and a blob that set them would be translated as if they were clear. Also unverified: NaN and denormal operands, other rounding and IEEE modes, outside the f16 transcendentals (measured, see the f16 transcendentals row). **Driver quirk (AMD Windows driver 26.11.1, RX 9070):** `valu_fuzz` f16 seed 3 programme 38 loses the high half of v26: `v_add_f16_e32 v26, v29, v32` then `v_sub_nc_u16_e64 v28, v32, v27 op_sel:[1,1,0]` then `v_add_f16_e64 v26, v26, v28` — the final add should keep `0xCD52` in the high half, but the GPU returns `0xEEEEEEEE` (native) / `0x00000000` (`--emulate`), all 64 threads. Bisected to the pair: the add's two sources must both have been produced by earlier partial writes; either alone, a NaN input alone, or `dst==src0` alone all pass. The emitted SPIR-V was checked with `spirv-dis` in both modes: the keep (load old v26, `AND 0xFFFF0000`, `OR` new low half, store to index 26) is present and correctly addressed, so the translator is clear and this is the driver miscompiling the pattern. Minimal reproducer: the three ops above with programme 38's inits (v26 `0xCD524000`, v28 `0xC692D243`, v29 `0xBC004200`, v32 `0xB35ABD4B`, v27 `0xB48ABA06`). Pinned by `tests/test_values.py` (`v_add_f16_e64_keep_hi`, `v_add_f16_e32_keep_hi`), which check the translator's keep, not the driver. Found and bisected by 1TrickOmen, reported on #634. |
+| 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. The pair is perspective-center, the only pair this layout models; that holds for every corpus PS (row "PS interpolation modes"). 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` when x is on and the export isn't `compr` (RGBA = Z, stencil, sample mask, alpha: Mesa `ac_get_spi_shader_z_format`; the 16-bit compressed mrtz holds stencil and sample mask and never Z, `ac_nir_lower_ps_late.c` `emit_ps_mrtz_export`). Until 2026-11-22 an mrtz export without a depth wrote one anyway (0.0, or an f16 half of the stencil word) and declared `DepthReplacing`. Checked by `tests/test_translate.py` (`test_mrtz_depth_only_from_an_enabled_x`). Stencil, sample mask and alpha exports aren't modelled. |
+| 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/subrev/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/subrev/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) and the value tests in `tests/test_f16_op_sel_values.py`. **Hardware-verified** on an AMD RX 6800 (gfx1030), the instructions run as a raw compute kernel in wave32 and in wave64 (IEEE off, DX10 clamp on, denormals kept, round to nearest; the bytes assemble identically for gfx1013 and gfx1030): **`v_med3_f16`** with all 16 `op_sel` patterns, with neg/abs on a selected high half, with `clamp`, and with the destination also a source; the **plain forms** `v_add/sub/mul/max/min_f16` (`_e32`, and `_e64` with neg/abs/`clamp`), `v_fmac_f16` (`_e32`, and `_e64` with neg/abs; the accumulator is the low half of the destination), `v_rndne/floor/ceil/trunc/fract/sqrt/rcp/rsq_f16` (`_e32` and `_e64`) and `v_cvt_f16_f32`: low halves in, low half out, high half of the destination kept. 336 words per wave size (plus `v_rsq_f16_e64` and `v_ceil_f16_e64` in a later run), all as the rule says and as the translator computes. **Vulkan** (AMD Radeon RX 6800, Windows, driver 26.11.2; the nine `ps_f16_*` fixtures also pass on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux): `ps_f16_med3_opsel`, `ps_f16_med3_mods`, `ps_f16_vop2`, `ps_f16_vop2b`, `ps_f16_vop1`, `ps_f16_vop1b`, whose expected words are the hardware ones (`tests/test_f16_hw_words.py` checks them against the rule and the translator without a GPU). **Not expressible, so not verified:** `op_sel` on the VOP2 and VOP1 ops in VOP3 encoding (`v_add/sub/mul/max/min_f16_e64`, `v_fmac_f16_e64`, the unary `_e64` forms, `v_cvt_f16_f32_e64`): llvm-mc 21 rejects the modifier for gfx1013 and gfx1030, and its disassembler prints bytes that have those bits set without it (`03 08 32 d5 01 05 02 00` comes back as `v_add_f16_e64 v3, v1, v2`). The translator's `op_sel` handling for these forms is therefore never reached from a disassembly listing and rests on the ISA field description alone; whether the hardware honours the bits there is unknown, and a blob that set them would be translated as if they were clear. Also unverified: NaN and denormal operands, other rounding and IEEE modes, outside the f16 transcendentals (measured, see the f16 transcendentals row). |
+| 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. The pair is perspective-center, the only pair this layout models; that holds for every corpus PS (row "PS interpolation modes"). 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 (a location any `*_f16` interp reads is a `PerVertexKHR` array of the producer's raw words instead: see "16-bit interpolation"). A param channel carries the export's raw 32 bits either way. `exp mrtN` → location N, `exp mrtz` x → `FragDepth` when x is on and the export isn't `compr` (RGBA = Z, stencil, sample mask, alpha: Mesa `ac_get_spi_shader_z_format`; the 16-bit compressed mrtz holds stencil and sample mask and never Z, `ac_nir_lower_ps_late.c` `emit_ps_mrtz_export`). Until 2026-11-22 an mrtz export without a depth wrote one anyway (0.0, or an f16 half of the stencil word) and declared `DepthReplacing`. Checked by `tests/test_translate.py` (`test_mrtz_depth_only_from_an_enabled_x`). Stencil, sample mask and alpha exports aren't modelled. |
+| 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/subrev/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/subrev/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) and the value tests in `tests/test_f16_op_sel_values.py`. **Hardware-verified** on an AMD RX 6800 (gfx1030), the instructions run as a raw compute kernel in wave32 and in wave64 (IEEE off, DX10 clamp on, denormals kept, round to nearest; the bytes assemble identically for gfx1013 and gfx1030): **`v_med3_f16`** with all 16 `op_sel` patterns, with neg/abs on a selected high half, with `clamp`, and with the destination also a source; the **plain forms** `v_add/sub/mul/max/min_f16` (`_e32`, and `_e64` with neg/abs/`clamp`), `v_fmac_f16` (`_e32`, and `_e64` with neg/abs; the accumulator is the low half of the destination), `v_rndne/floor/ceil/trunc/fract/sqrt/rcp/rsq_f16` (`_e32` and `_e64`) and `v_cvt_f16_f32`: low halves in, low half out, high half of the destination kept. 336 words per wave size (plus `v_rsq_f16_e64` and `v_ceil_f16_e64` in a later run), all as the rule says and as the translator computes. **Vulkan** (AMD Radeon RX 6800, Windows, driver 26.11.2; the nine `ps_f16_*` fixtures also pass on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux): `ps_f16_med3_opsel`, `ps_f16_med3_mods`, `ps_f16_vop2`, `ps_f16_vop2b`, `ps_f16_vop1`, `ps_f16_vop1b`, whose expected words are the hardware ones (`tests/test_f16_hw_words.py` checks them against the rule and the translator without a GPU). **Not expressible, so not verified:** `op_sel` on the VOP2 and VOP1 ops in VOP3 encoding (`v_add/sub/mul/max/min_f16_e64`, `v_fmac_f16_e64`, the unary `_e64` forms, `v_cvt_f16_f32_e64`): llvm-mc 21 rejects the modifier for gfx1013 and gfx1030, and its disassembler prints bytes that have those bits set without it (`03 08 32 d5 01 05 02 00` comes back as `v_add_f16_e64 v3, v1, v2`). The translator's `op_sel` handling for these forms is therefore never reached from a disassembly listing and rests on the ISA field description alone; whether the hardware honours the bits there is unknown, and a blob that set them would be translated as if they were clear. Also unverified: NaN and denormal operands, other rounding and IEEE modes, outside the f16 transcendentals (measured, see the f16 transcendentals row). **Driver quirk (AMD Windows driver 26.11.1, RX 9070):** `valu_fuzz` f16 seed 3 programme 38 loses the high half of v26: `v_add_f16_e32 v26, v29, v32` then `v_sub_nc_u16_e64 v28, v32, v27 op_sel:[1,1,0]` then `v_add_f16_e64 v26, v26, v28` — the final add should keep `0xCD52` in the high half, but the GPU returns `0xEEEEEEEE` (native) / `0x00000000` (`--emulate`), all 64 threads. Bisected to the pair: the add's two sources must both have been produced by earlier partial writes; either alone, a NaN input alone, or `dst==src0` alone all pass. The emitted SPIR-V was checked with `spirv-dis` in both modes: the keep (load old v26, `AND 0xFFFF0000`, `OR` new low half, store to index 26) is present and correctly addressed, so the translator is clear and this is the driver miscompiling the pattern. Minimal reproducer: the three ops above with programme 38's inits (v26 `0xCD524000`, v28 `0xC692D243`, v29 `0xBC004200`, v32 `0xB35ABD4B`, v27 `0xB48ABA06`). Pinned by `tests/test_values.py` (`v_add_f16_e64_keep_hi`, `v_add_f16_e32_keep_hi`), which check the translator's keep, not the driver. Found and bisected by 1TrickOmen, reported on #634. |
| f16 inline constants | An inline float constant (`0.5`, `1.0`, `2.0`, `4.0`, their negatives, `0.15915494`) in an operand of a 16-bit float op is the **f16 value in the low half with a zero high half**, not f32 bits (the translator used to unpack the f32 pattern, whose low half is 0, so `v_add_f16 d, 1.0, v` added 0.0). Measured on an AMD RX 6800 (gfx1030) raw kernel, wave32 and wave64: `v_add/mul/max_f16`, `v_sub_f16_e64`, `v_fma_f16`, `v_fmac_f16`, `v_rcp_f16`, `v_med3_f16`, `v_cmp_lt_f16`, `v_cvt_f32_f16` (`0.5` gives `0x3f000000`), `v_cos_f16`, `v_pk_add_f16`/`v_pk_mul_f16` (the high result half sees 0.0), `v_pack_b32_f16`; `0.15915494` is `0x3118`; the high half `op_sel` selects from a constant reads +0.0 (`v_med3_f16`, `v_fma_f16`, `v_pack_b32_f16`, `v_pk_add_f16` with swapped halves). GPU tests `ps_f16_const`, `ps_f16_const2` and `ps_f16_pack` (Vulkan: AMD Radeon RX 6800, Windows, driver 26.11.2; all three fail without the fix). Not measured, left as they were: constants in `v_fma_mix_f32`/`v_fma_mixlo/mixhi_f16` operands. |
| `v_med3_f32` output modifiers | The translator applies `mul:2`, `mul:4` or `div:2` to the median before clamping to [0, 1], following [LLVM’s modifier order](https://llvm.org/docs/AMDGPUModifierSyntax.html#omod). The finite-input fixture `ps_med3_mods.asm` produced 4,096 exact pixels on an Apple M3 Max with MoltenVK and on Mesa llvmpipe (software Vulkan); it also passes (4,096/4,096) on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux, and on an RTX 2060 SUPER per #634. This uses the existing float MODE assumptions described above. |
| 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`). |
@@ -248,7 +256,7 @@ How the generated SPIR-V expects the runtime to work:
| 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). **On lane masks in a wave32 program** (a source is EXEC, VCC or a mask SGPR, or the result goes to EXEC) the 32-bit bitwise ops' result is the whole wave's mask, so SCC is a subgroup vote (`OpGroupNonUniformAny`), as for the `_b64` forms. Until 2026-11-22 each lane took its own bit: `s_and_b32 s0, vcc_lo, exec_lo; s_cbranch_scc0` skipped the block in lanes whose bit was 0, and a loop closed by `s_andn2_b32 exec_lo, ...; s_cbranch_scc1` let each lane leave early. Found and checked by `tools/cf_diff.py` (FUZZ-8, CPU differential against the ISA model); GPU test `runtime/test/shaders/ps_scc_mask32.asm` passes (s5 == 8 on 2,048 pixels, 192 of them with bit 0, and s5 == 7 on 2,048) on an NVIDIA RTX 4050 Laptop (Linux, driver 620.73.04, natively and under `LEONIDA_W64_EMULATE=1`) and an AMD Radeon 740M (RADV, Mesa 26.3.1), and on an RTX 2060 SUPER per #634. A 32-bit op on one half of a wave64 mask still takes the lane's bit (its SCC would be a vote of that half). |
| 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. |
| No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`) | Instruction-cache invalidate, thread-trace data, end-of-code padding and the ISA version marker have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). |
-| 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. The atomics use element 0 of the array at the aligned dword address, which also compiles on MoltenVK 1.4.0 (checked with `cs_store` on an Apple M3 Max and Mesa llvmpipe). 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. |
+| 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. The atomics use element 0 of the array at the aligned dword address, which also compiles on MoltenVK 1.4.0 (checked with `cs_store` on an Apple M3 Max and Mesa llvmpipe). 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. UNORM/SNORM stores convert NaN to zero before clamping. On native gfx1036, `buffer_store_format_d16_xyzw` into RGBA8_UNORM/SNORM matched clamp, scale by 255/127 and round to nearest even for all 63,488 finite binary16 encodings. Both infinities saturated and all 2,046 NaNs stored zero in both wave32 and wave64. The translated sweep matched all 65,536 bytes per format on RTX 5080 and Radeon Graphics. |
| `s_lshl1..4_add_u32` | D = (S0 << N) + S1. SCC = the sum taken in 64 bits is ≥ 2³², so a bit shifted out of S0 sets it as well as a carry out of the add (RDNA ISA pseudocode: `tmp = (64'U(S0) << N) + 64'U(S1)`). Checked on the CPU by `tests/semantic/test_salu_lshl_add.py`, **not yet GPU-verified**. |
| Other additions | `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at mip round(LOD) in gather order. With `d16` those four taps round to binary16 and pack low half first into two consecutive VGPRs. The packed words and the first untouched VGPR were checked with `ps_gather_wrap.asm` on RTX 5080 and Radeon Graphics. Each of the four texel coordinates goes through the S#'s own address mode, read from S# word0 (`CLAMP_X` = bits [2:0], `CLAMP_Y` = [5:3]; fields from Mesa `src/amd/registers/gfx10-rsrc.json`, values `SQ_TEX_*` in Mesa `gfx6.json`, matching RADV's `radv_tex_wrap` mapping of Vulkan address modes): 0 wrap (`c mod n`), 1 mirror (`c mod 2n`, reflected), 2 clamp to the last texel, 3 mirror-once (`-1-c` for negative `c`, then clamped), as in Vulkan's address-mode definitions. A literal S# (`s_mov_b32` earlier in the block) is decoded at translation time; otherwise the mode is read from the SGPR at run time. A literal S# with a border mode (4-7: half-border, border colour) or `FORCE_UNNORMALIZED` is `Unsupported`; a run-time S# can't be judged, so modes 4-7 act as clamp-to-edge there and `FORCE_UNNORMALIZED` (word0 bit 15) is not applied (coordinates are still scaled by the image size). Those two are the remaining approximations; the unnormalized rules (texel-unit coordinates, mip 0) weren't confirmed on hardware, so they were not guessed. GPU-checked with `runtime/test/shaders/ps_gather_wrap.asm` (`vk_texture_test`; expected values derived by hand in its header; six border cases, three literal and three run-time S#) on AMD (Radeon 880M, wave64) and NVIDIA RTX 5070. `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`). |
| Other additions | `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at mip `Floor(clamp(LOD, S# MIN_LOD, MAX_LOD) + 0.5)` (ties up, as native) in gather order. Each of the four texel coordinates goes through the S#'s own address mode, read from S# word0 (`CLAMP_X` = bits [2:0], `CLAMP_Y` = [5:3]; fields from Mesa `src/amd/registers/gfx10-rsrc.json`, values `SQ_TEX_*` in Mesa `gfx6.json`, matching RADV's `radv_tex_wrap` mapping of Vulkan address modes): 0 wrap (`c mod n`), 1 mirror (`c mod 2n`, reflected), 2 clamp to the last texel, 3 mirror-once (`-1-c` for negative `c`, then clamped), as in Vulkan's address-mode definitions. A literal S# (`s_mov_b32` earlier in the block) is decoded at translation time; otherwise the mode is read from the SGPR at run time. A literal S# with a border mode (4-7: half-border, border colour) or `FORCE_UNNORMALIZED` is `Unsupported`; a run-time S# can't be judged, so modes 4-7 act as clamp-to-edge there and `FORCE_UNNORMALIZED` (word0 bit 15) is not applied (coordinates are still scaled by the image size). Those two are the remaining approximations; the unnormalized rules (texel-unit coordinates, mip 0) weren't confirmed on hardware, so they were not guessed. GPU-checked with `runtime/test/shaders/ps_gather_wrap.asm` (`vk_texture_test`; expected values derived by hand in its header; six border cases, three literal and three run-time S#) on AMD (Radeon 880M, wave64) and NVIDIA RTX 5070. `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`). |
@@ -258,20 +266,29 @@ How the generated SPIR-V expects the runtime to work:
| 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. |
+| v_interp operand guards (SHADER-177) | The single-lane model reads the attribute's own value for `v_interp_p1/p2`, which is only right when the VGPR source really holds the barycentric coordinate that op interpolates with — **p1 reads I = v0 and p2 reads J = v1, per op** — and `v_interp_mov_f32` models only the p0 provoking vertex. A p1/p2 (f32 and f16 forms) whose source is not its own coordinate — v0 for p1, v1 for p2, each either the hardware register or a plain `v_mov_b32` copy rooted at it (the copy's single write in the whole shader, defined before the use, copy chains followed, and its source v0/v1 itself unwritten up to the copy: a copy of an already-overwritten v0/v1 carries a computed value — zeroing the source before copying renders (0,0) on hardware — while a write after the copy is fine, the copy saved the value) — is **Unsupported**, naming the register and the role, so a swapped p1(v1)/p2(v0) pair, a both-v0 pair, or a copy of an overwritten source is refused rather than silently mistranslated; `v_interp_mov_f32` with p10/p20 is **Unsupported**, naming the select. A **direct** v0/v1 read stays accepted even when the shader overwrites v0/v1 first (evaluate-at-offset/snapped barycentrics; up to 213 PS, #1218): modelling that computed value is the separate provenance follow-up. Zero corpus cost: over the 26,503-shader corpus every f32 I/J source is v0/v1 (117,001 / 116,997) except one PS whose four `v_interp_p2_f32` read J through `v_mov_b32 v14, v1` (its v1 unwritten up to the copy; the later overwrites are the saved-copy case), which the copy rule keeps translating (bit-identical .spv), every f16 source is v0/v1 (58,950 / 58,950), and all 6,926 `v_interp_mov_f32` use p0. Confirmed by `tests/semantic/test_interp_guards.py` (refusals name the operand and its role, including swapped and both-v0 pairs, a wrong-root copy, and a copy of an overwritten source; the copy, copy-chain, matching-role and saved-from-later-zero cases translate and compute; a second write or a dpp copy no longer qualifies; a mutation check that the guard consults the copy analysis) and by re-translating a 200-shader corpus slice plus that PS before and after: translated/valid counts and every .spv unchanged. |
| Pixel-shader interpolants | When a sidecar `fssm/.fssm` holds a pixel-input table (`tools/fssm_header.py`: 8-byte records from 0x138 while the first byte is 6; table position = `v_interp attr` number), every position 0..count−1 is declared as a fragment input at that Location, including positions the code never reads (the table overcounts the code's distinct `v_interp` attrs in 775 of 12,101 PS: 300 by one, 475 by two or more; only the 10 records starting with kind 7 undercount). A 32-bit `v_interp` read (`p1/p2/mov`) of a 16-bit-flagged position (flag bit 4; 11,199 such inputs corpus-wide, matching the `*_f16` interpolation opcodes in 99.7%) sees the value rounded to f16 (round to nearest, f16 denormals flushed to signed zero, back to f32) via a single `OpQuantizeToF16` (a `PackHalf2x16`/`UnpackHalf2x16` round-trip is folded to a no-op by at least one Vulkan driver, RTX 5080); reads through the `*_f16` opcodes already narrow and are unchanged (on a location an f16 op also reads, the f32 read is of the per-vertex raw word, "16-bit interpolation"; how hardware treats a 32-bit read of a packed channel is unverified), and reads past the table still declare an input (the value is undefined on hardware). Without a sidecar, or with an empty table, the output is byte-identical to the code-driven path. Confirmed by synthetic fixtures plus mini-interpreter agreement (`tests/test_rdna2spirv_pixelinput.py`: an f32 read of a flagged slot with input 1.1 yields the f16-rounded 1.099609375; unflagged and table-less controls yield exact 1.1), no GPU needed. The `index.json` entry records `ps_interpolants` (count) and `ps_fp16_interpolants` (flagged positions). |
+| Pixel-shader interpolants | When a sidecar `fssm/.fssm` holds a pixel-input table (`tools/fssm_header.py`: 8-byte records from 0x138 while the first byte is 6; table position = `v_interp attr` number), every position 0..count−1 is declared as a fragment input at that Location, including positions the code never reads (the table overcounts the code's distinct `v_interp` attrs in 775 of 12,101 PS: 300 by one, 475 by two or more; only the 10 records starting with kind 7 undercount). A 32-bit `v_interp` read (`p1/p2/mov`) of a 16-bit-flagged position (flag bit 4; 11,199 such inputs corpus-wide, matching the `*_f16` interpolation opcodes in 99.7%) sees the value rounded to f16 (round to nearest, f16 denormals flushed to signed zero, back to f32) via a single `OpQuantizeToF16` (a `PackHalf2x16`/`UnpackHalf2x16` round-trip is folded to a no-op by at least one Vulkan driver, RTX 5080); reads through the `*_f16` opcodes already narrow and are unchanged, and reads past the table still declare an input (the value is undefined on hardware). Without a sidecar, or with an empty table, the output is byte-identical to the code-driven path. Confirmed by synthetic fixtures plus mini-interpreter agreement (`tests/test_rdna2spirv_pixelinput.py`: an f32 read of a flagged slot with input 1.1 yields the f16-rounded 1.099609375; unflagged and table-less controls yield exact 1.1), no GPU needed. The `index.json` entry records `ps_interpolants` (count) and `ps_fp16_interpolants` (flagged positions). |
+| Pixel-shader interpolants | When a sidecar `fssm/.fssm` holds a pixel-input table (`tools/fssm_header.py`: 8-byte records from 0x138 while the first byte is 6; table position = `v_interp attr` number), every position 0..count−1 is declared as a fragment input at that Location, including positions the code never reads (the table overcounts the code's distinct `v_interp` attrs in 775 of 12,101 PS: 300 by one, 475 by two or more; only the 10 records starting with kind 7 undercount). A 32-bit `v_interp` read (`p1/p2/mov`) of a 16-bit-flagged position (flag bit 4; 11,199 such inputs corpus-wide, matching the `*_f16` interpolation opcodes in 99.7%) sees the value rounded to f16 (round to nearest, f16 denormals flushed to signed zero, back to f32) via a single `OpQuantizeToF16` (a `PackHalf2x16`/`UnpackHalf2x16` round-trip is folded to a no-op by at least one Vulkan driver, RTX 5080); reads through the `*_f16` opcodes already narrow and are unchanged (on a location an f16 op also reads, the f32 read is of the per-vertex raw word, "16-bit interpolation"; how hardware treats a 32-bit read of a packed channel is unverified), and reads past the table still declare an input (the value is undefined on hardware). Without a sidecar, or with an empty table, the output is byte-identical to the code-driven path. Confirmed by synthetic fixtures plus mini-interpreter agreement (`tests/test_rdna2spirv_pixelinput.py`: an f32 read of a flagged slot with input 1.1 yields the f16-rounded 1.099609375; unflagged and table-less controls yield exact 1.1), no GPU needed. The `index.json` entry records `ps_interpolants` (count) and `ps_fp16_interpolants` (flagged positions). |
+| PS interpolation modes (SHADER-181) | Every interpolated pixel input in this build is **perspective-correct at the pixel center**, and every other input is flat, so the single v0/v1 pair the code reads is `PERSP_CENTER`. The translator models exactly these two: Flat for `v_interp_mov_f32`, plain (perspective, center) inputs and `BaryCoordKHR` for `v_interp_p1/p2` and the f16 forms. Two records state the mode per input, and they agree. **FSSM:** bits 0–1 of the input record's flags byte (byte 7; `fssm_header.interpolation_modes`) are 2 (linear) in 51,191 records and 1 (flat) in 4,600; 0 and 3 never occur. In all 12,101 PS every mode-1 position the code reads is read only by `v_interp_mov_f32` (4,295 positions), every mode-2 position only by `v_interp_p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). **DXBC:** PSV0's per-element `InterpolationMode` is `linear` for 81,385 interpolated inputs (attributes plus 1,806 `SV_ClipDistance` and 2 `SV_CullDistance` rows) and `constant` for 6,333; no PS input is centroid, sample or noperspective. ISG1 has no mode field, and the DXIL part carries no bitcode. Per shader: 6,350 linear only, 4,507 linear and constant, 6 constant only, 1,238 no interpolated input. The FSSM stores no `SPI_PS_INPUT_ENA`/`SPI_PS_INPUT_ADDR` word: no header word up to the code (0xEF8 + 0x28), and none of the tail records, tracks the enabled inputs, and the register addresses (0x286CC/0x286D0, or 0xA1B3/0xA1B4 as context-register indices) appear in no PS blob. So the mode comes from the input records, and the v2.. position layout of "PS system inputs" (one enabled pair) confirms it. `rdna2spirv.check_interpolation_modes` refuses a PS whose read positions disagree with their FSSM mode, or carry mode 0 or 3, rather than reading them as perspective-center; this rejects 0 of 12,101 PS. Counted with `tools/ps_interp_census.py` (stdlib; PSV0, FSSM and disassembly in one pass) on the 1.0.2.1 corpus; tests `tests/test_ps_interp_census.py`, `tests/test_fssm_header.py` and `tests/test_rdna2spirv_pixelinput.py` (synthetic). No GPU test: no shader needs centroid or sample interpolation. **Not covered:** `SV_Position` is `noperspective_centroid` in 27 PS (11,295 plain `noperspective`); `FragCoord` stays at the pixel center, which only differs at partly covered MSAA pixels. Bit 3 (0x08) of the flags byte is set in 11,619 records (all 11,199 16-bit ones, 396 flat, 24 linear), and its meaning is not identified. The 213 PS that overwrite v0/v1 before a `v_interp` (SHADER-178) compute their own barycentrics in code; PSV0 gives them no other mode. |
+| PS interpolation modes | `tools/ps_interp_modes.py` decodes each PS input's mode from the DXBC container's PSV0 chunk (16-byte signature elements carry row, cols, semantic kind, component type and the interpolation mode; layout in the Pixel-shader inputs section) and cross-checks the FSSM sidecar. Modes are `DXIL::InterpolationMode` ("must match D3D_INTERPOLATION_MODE": 1 Constant, 2 Linear, 3 LinearCentroid, 4 LinearNoperspective, 5 LNP-Centroid, 6 LinearSample, 7 LNP-Sample) and map to the `SPI_PS_INPUT_ENA` barycentric-pair bits (Mesa `gfx103.json` register type SPI_PS_INPUT_ENA: PERSP_SAMPLE/CENTER/CENTROID = bits 0/1/2, LINEAR_SAMPLE/CENTER/CENTROID = bits 4/5/6; the same type serves `SPI_PS_INPUT_ADDR`). **No FSSM word stores ENA/ADDR**: every u16 in bytes 0x00–0x138 of all 12,101 PS was compared against the signature-reconstructed ENA and only constant coincidences matched. **Census (12,101 PS; 101,024 declared / 76,215 read inputs): every arbitrary, clip and cull input is Constant (6,333 rows, 3,652 read) or Linear = perspective-centre (81,385 rows); zero centroid, zero sample, zero noperspective generics.** SV_Position is mode 4 (11,295 rows) or mode 5 (27 rows) — noperspective by D3D rule — and is delivered through the system VGPRs ("PS system inputs") in every shader except **4**, which interpolate it through the parameter cache with the *linear* pair; front face is a system input (1,984 rows, 345 read, at most one per shader). The code reads **one** barycentric pair per shader: v0/v1 in 10,259, none in 1,841, and one shader reads J from v14 (a copy of v1) — so the perspective-centre assumption holds for every interpolated generic input; the residual surface is those 4 linear-pair position shaders, Constant rows read via `p1/p2` or `*_f16` (2,190 records at the matching table position; flat semantics in hardware, not modelled), and Linear rows read only by `v_interp_mov_f32` (3,197; already declared `Flat`). FSSM record flags are the read method, not the mode: bit 0 (0x01) `v_interp_mov_f32` (4,600 records), bit 1 (0x02) 32-bit `v_interp_p1/p2` (51,191), bit 3 (0x08) Float16-typed parameter (11,619), bit 4 (0x10) `*_f16` opcodes (11,199; 24 f16-read records lack it); the flag/usage cross-table over all 55,791 records has no contradiction. |
+| PS interpolation modes (SHADER-181) | Every interpolated pixel input in this build is **perspective-correct at the pixel center**, and every other input is flat, so the single v0/v1 pair the code reads is `PERSP_CENTER`. The translator models exactly these two: Flat for `v_interp_mov_f32`, plain (perspective, center) inputs and `BaryCoordKHR` for `v_interp_p1/p2` and the f16 forms. Two records state the mode per input, and they agree. **FSSM:** bits 0–1 of the input record's flags byte (byte 7; `fssm_header.interpolation_modes`) are 2 (linear) in 51,191 records and 1 (flat) in 4,600; 0 and 3 never occur. In all 12,101 PS every mode-1 position the code reads is read only by `v_interp_mov_f32` (4,295 positions), every mode-2 position only by `v_interp_p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). **DXBC:** PSV0's per-element `InterpolationMode` (`DXIL::InterpolationMode`, "must match D3D_INTERPOLATION_MODE": 1 Constant, 2 Linear, 3 LinearCentroid, 4 LinearNoperspective, 5 LinearNoperspectiveCentroid, 6 LinearSample, 7 LinearNoperspectiveSample; the 16-byte signature elements carry row, cols, semantic kind, component type and the mode — layout in the Pixel-shader inputs section) is `linear` for 81,385 interpolated inputs (attributes plus 1,806 `SV_ClipDistance` and 2 `SV_CullDistance` rows) and `constant` for 6,333 (3,652 read); no PS input is centroid, sample or noperspective. ISG1 has no mode field, and the DXIL part carries no bitcode. Per shader: 6,350 linear only, 4,507 linear and constant, 6 constant only, 1,238 no interpolated input. The modes map onto the `SPI_PS_INPUT_ENA` barycentric-pair bits (Mesa `gfx103.json` register type SPI_PS_INPUT_ENA: PERSP_SAMPLE/CENTER/CENTROID = bits 0/1/2, LINEAR_SAMPLE/CENTER/CENTROID = bits 4/5/6; the same register type serves `SPI_PS_INPUT_ADDR`), and the corpus uses only the PERSP_CENTER bit, or none at all for flat inputs. **No FSSM word stores ENA/ADDR**: no header word up to the code (0xEF8 + 0x28) and none of the tail records tracks the enabled inputs, the register addresses (0x286CC/0x286D0, or 0xA1B3/0xA1B4 as context-register indices) appear in no PS blob, and an independent scan of every u16 in bytes 0x00–0x138 of all 12,101 PS against the signature-reconstructed ENA matched only constant coincidences. So the mode comes from the input records, and the v2.. position layout of "PS system inputs" (one enabled pair) confirms it. The code reads **one** barycentric pair per shader: v0/v1 in 10,259, none in 1,841, and one shader reads J from v14 (a copy of v1) — so the perspective-centre assumption holds for every interpolated generic input; SV_Position is mode 4 (11,295 rows) or mode 5 (27) — noperspective by the D3D rule — and is delivered through the system VGPRs in every shader except **4**, which interpolate it through the parameter cache with the *linear* pair (`FragCoord` stays at the pixel center, which only differs at partly covered MSAA pixels); front face is a system input (1,984 rows, 345 read, at most one per shader). The residual surface is those 4 linear-pair position shaders, Constant rows read via `p1/p2` or `*_f16` (2,190 records at the matching table position; flat semantics in hardware, not modelled), and Linear rows read only by `v_interp_mov_f32` (3,197; already declared `Flat`). FSSM record flags are the read method, not the mode: bit 0 (0x01) `v_interp_mov_f32` (4,600 records), bit 1 (0x02) 32-bit `v_interp_p1/p2` (51,191), bit 3 (0x08) Float16-typed parameter (11,619), bit 4 (0x10) `*_f16` opcodes (11,199; 24 f16-read records lack it); the flag/usage cross-table over all 55,791 records has no contradiction. `rdna2spirv.check_interpolation_modes` refuses a PS whose read positions disagree with their FSSM mode, or carry mode 0 or 3, rather than reading them as perspective-center; this rejects 0 of 12,101 PS. Counted with `tools/ps_interp_census.py` (stdlib; PSV0, FSSM and disassembly in one pass) and decoded per input — the ENA bit mapping, read-method flags and per-shader pair classification — with `tools/ps_interp_modes.py` on the 1.0.2.1 corpus; tests `tests/test_ps_interp_census.py`, `tests/test_ps_interp_modes.py`, `tests/test_fssm_header.py` and `tests/test_rdna2spirv_pixelinput.py` (synthetic). No GPU test: no shader needs centroid or sample interpolation. **Not covered:** `SV_Position` is `noperspective_centroid` in 27 PS (11,295 plain `noperspective`). Bit 3 (0x08) of the flags byte is set in 11,619 records (all 11,199 16-bit ones, 396 flat, 24 linear), and its meaning is not identified. The 213 PS that overwrite v0/v1 before a `v_interp` (SHADER-178) compute their own barycentrics in code; PSV0 gives them no other mode. |
+| PS `v_interp` read methods (SHADER-181, translator side) | Bits 0–1 of the FSSM input record's flags byte (byte 7; `fssm_header.read_methods`) give the **read method** of each table position: bit 0 (0x01) = read through `v_interp_mov_f32`, bit 1 (0x02) = read through `v_interp_p1/p2` or the f16 forms. They do not give the D3D interpolation mode, which is PSV0's (row "PS interpolation modes", `tools/ps_interp_modes.py`, #1256). Exactly one bit is set in every corpus record (bit 1 in 51,191, bit 0 in 4,600). In all 12,101 PS every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 read positions), every bit-1 position only by `p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). The translator follows the read method, which is what the code does: `v_interp_mov` → `Flat`, `p1/p2` → a plain input (perspective, pixel center; `BaryCoordKHR` for raw i/j). That this one pair is perspective-center holds because PSV0 lists no centroid, sample or noperspective generic input, and the code reads one barycentric pair (#1256). Table positions don't pair one-to-one with PSV0 rows, since the table keeps only the inputs the compiled code uses, so a PSV0 row's mode and the record's read method can differ at a paired position; #1256 counts those cases. `rdna2spirv.check_read_methods` refuses a PS whose read position disagrees with its record's read method (`v_interp_mov` of a bit-1 position, `p1/p2`/f16 of a bit-0 one), or whose record has neither or both bits, instead of reading it as perspective-center. It refuses 0 of 12,101 PS, and shard 0/12 translates byte-identically to before the check. `index.json` records `ps_flat_interpolants`, the bit-0 positions. Tests: `tests/test_rdna2spirv_pixelinput.py` and `tests/test_fssm_header.py` (synthetic). GPU-checked by @Vonsek on #1246 (RTX 5080 and Radeon integrated graphics, stock `ps_flat` with a hand-built table of read methods 2 and 1): the smooth channels match a per-center perspective reference, the flat channel keeps the provoking value, and flipping either record's read method makes the translator refuse the shader. Bit 3 (0x08, 11,619 records) is a Float16-typed parameter per #1256. |
| 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`. |
| Denormal flush and special results in `v_rcp_f32`, `v_rsq_f32`, `v_sqrt_f32`, `v_log_f32`, `v_exp_f32`, `v_rcp_iflag_f32` | Measured on an RX 6800 (gfx1030, not the console's gfx1013) with raw kernels in both wave sizes and all four IEEE/DX10_CLAMP combinations: all six read a denormal input as a zero of its sign and flush a denormal result, even with MODE's denormal field set to keep them. `v_rcp_f32(±0)` = ±inf, `v_rsq_f32(-0)` = -inf, `v_sqrt_f32(-0)` = -0, `v_log_f32(±0)` = -inf, `v_rcp_f32(FLT_MAX)` = +0, `v_exp_f32(-127)` = +0, `v_exp_f32(128)` = +inf, and every invalid result (`v_sqrt_f32`/`v_rsq_f32`/`v_log_f32` of a negative, …) is `0xffc00000`. Each is within 1 ulp of correctly rounded on the values tried, and `v_rcp_iflag_f32` is bit-identical to `v_rcp_f32`. **Not modelled yet:** the translator leaves all six on Vulkan's default denormal handling, and the ±0 and negative inputs above stay undefined in the emitted SPIR-V (`OpFDiv` by zero, `Sqrt`/`Log2` of a negative), as listed in the multiply-add and output modifiers row; the `clamp`/`omod` bits on `v_cvt_f32_*` and `v_rcp_iflag_f32` are modelled there. Source: [@shelbykb2's hardware words](https://github.com/ItsNotRexed/Leonida/issues/634#issuecomment-7074348963), not the ISA text. The corpus only ever writes MODE's FP_ROUND field and carries `mul:2`/`mul:4`/`div:2` on 102,365 float instructions (a compiler does not emit one that is ignored), so the inferred f32 state, IEEE off with denormals flushed, is the one to model. Corpus count (`tools/shader_profile.py`, 26,503 shaders; the shader count of each op deduplicates its `_e32`/`_e64` forms): `v_rcp_f32` 17,393 shaders / 424,863 occurrences, `v_rsq_f32` 17,221 / 269,310, `v_sqrt_f32` 14,511 / 201,422, `v_log_f32` 8,454 / 90,199, `v_exp_f32` 8,603 / 148,846, `v_rcp_iflag_f32` 7,395 / 34,852; 20,193 shaders (76.2%) use at least one, 1,169,492 occurrences (2.6% of the corpus's 44,406,870 instructions). |
+| f16 transcendentals (`v_exp_f16`, `v_log_f16`, `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`) | Measured on an RX 6700 XT (gfx1031, not the console's gfx1013) with `tools/f16_trans_sweep.py`: all 65,536 inputs of each op, wave32 and wave64 (identical on every input), five MODEs (FUZZ-29). With f16 denormals kept (`denorm_mode_16_64 = 3`, the assembler default and what the translator assumes), `v_exp/log/rcp/rsq/sqrt_f16` are **correctly rounded on every input that is not a NaN** (0 ulp). `v_sin/v_cos_f16` take turns and reduce them exactly over the whole f16 range (no ±256 limit): compared with sin/cos(2πx), every result for |x| > 1 is bit-exact, and for |x| ≤ 1 only 14 (sin) and 4 (cos) of 30,722 are 1 ulp off. So the translator's rule (widen to f32, the GLSL.std.450 function, round to nearest even back to f16) matches the hardware as far as the driver's f32 function is accurate. For sin/cos that holds only once the angle is reduced in turns first (#594): with the f32 product 6.2831855 · x, 16,366 sin and 2,036 cos inputs are more than 1 ulp off, up to 9,944 ulp (sin of 64,640 turns: 0.0267 instead of 0). With `denorm_mode_16_64 = 0`, a denormal operand reads as a zero of its sign, and a denormal result is written as a zero of its sign. That differs from the f32 ops in the row above, which flush in both modes. The f16 field of FP_ROUND is ignored: round toward zero gives the same words as round to nearest on every input. IEEE changes only signalling NaNs. With IEEE off they pass through unchanged; with IEEE on they are quieted (bit 9 set). Payload and sign are kept either way, and quiet NaNs pass unchanged in every mode. Where SPIR-V leaves the result undefined, the hardware gives: log(±0) = -inf, rcp(±0) = ±inf, rsq(+0) = +inf, rsq(-0) = -inf, sqrt(-0) = -0, and `0xfe00` for log/rsq/sqrt of a negative (-inf included) and for sin/cos(±inf). **Not modelled yet:** `Gen.f16_bits` quiets every NaN (the hardware keeps a signalling NaN with IEEE off), and the undefined cases above are left to the driver. |
| `v_cvt_f32_f64` output modifiers | Convert to f32, apply `mul:2`, `mul:4`, or `div:2` if present, then apply `clamp` to [0, 1] if requested. [LLVM GFX10 assembler tests](https://github.com/llvm/llvm-project/blob/main/llvm/test/MC/AMDGPU/gfx10_asm_vop1.s#L3044-L3054) confirm the modifier encodings. `tests/test_f64_conversion.py` checks the resulting SPIR-V data flow. |
| `v_add_f64` output modifiers | The double sum is scaled by `mul:2`, `mul:4` or `div:2` if present, then clamped to [0, 1] if `clamp` is set, as for f32 (`clamp_mods_f64`, GLSL.std.450 `FClamp` on the double, so a NaN result and the sign of a -0 result are left to the driver, also as for f32). **Until 2026-11-22 both were ignored.** Source: LLVM AMDGPU defines it as `VOP3Inst<"v_add_f64", VOP3_Profile>` (VOP3Instructions.td), and `VOPProfile` sets `HasClamp` (f64 is a modifier type) and `HasOMod` (floating-point destination) (SIInstrInfo.td). It is the only f64 arithmetic the translator handles; `v_cvt_f32_f64` has the row above. `tests/test_f64_output_modifiers.py` checks the SPIR-V data flow; `runtime/test/shaders/ps_f64_mods.asm` is the GPU test (needs `shaderFloat64`, which `vk_harness` now enables when the fragment shader declares `Float64`), passed on an NVIDIA RTX 6000 Ada (driver 615.71.09, Linux; 4096/4096 pixels exact, and the `main` translator gives the predicted old words). |
| 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). |
| Multiply-add with a literal | `v_fmamk_f32`/`v_madmk_f32` are D = S0 × K + S1 and `v_fmaak_f32`/`v_madak_f32` are D = S0 × S1 + K, K being the 32-bit literal. LLVM prints them `vdst, src0, K, vsrc1` and `vdst, src0, vsrc1, K`, so in print order all four are a[1] × a[2] + a[3] (fused for fmamk/fmaak). **Until 2026-11-21 fmamk and madmk computed S0 × S1 + K.** Source: RDNA2 ISA (V_FMAMK_F32, V_MADMK_F32) and the operand fields of the llvm-mc encoding. Checked by `tests/semantic` and GPU-checked with `runtime/test/shaders/ps_fma_literal.asm` on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact, and 4096/4096 differ with the old translator. |
| Multiply-add and output modifiers | `v_mac_f32` is the VOP2 form of `v_mad_f32`, **not** of `v_fma_f32`: the product is rounded before the add (`OpFMul` + `OpFAdd`, both `NoContraction`). It used to emit `Fma`, one ULP off on some inputs. Source: LLVM `SIInstrInfo.cpp` `getNewFMAInst` (`V_MAC_F32` -> `V_MAD_F32_e64`, `V_FMAC_F32` -> `V_FMA_F32_e64`). VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` now apply to `v_cvt_f32_i32`/`u32`/`ubyte0..3`, `v_cvt_f32_f16` and `v_rcp_iflag_f32` (they were dropped). Source: LLVM `VOPProfileI2F` (`Ins64 = $src0, $clamp, $omod`) and the float-source profiles. Found by `tools/f32_fuzz.py` (FUZZ-3: an exact-arithmetic model against the translated SPIR-V; 0 mismatches over 10,000 seeded programs after the fix) and pinned by `runtime/test/shaders/ps_f32_mods.asm` (`tests/semantic/test_f32_valu.py`); **not yet GPU-verified**. Still open: on some inputs the ISA defines a result but the emitted SPIR-V is undefined: `v_rcp_f32(±0)` (`OpFDiv` by zero), `v_rsq_f32`/`v_log_f32` of ±0 or a negative, `v_sqrt_f32` of a negative, `v_cvt_pk_u8_f32(NaN)` (`FClamp`). |
+| Output modifiers on hardware (gfx1150) | Measured on a Radeon 880M (gfx1150, RDNA3.5; **not** RDNA2) with `tools/f32_fuzz.py --oracle hw`, 46,967 programs: `mul:2`/`mul:4`/`div:2` turn a -0 result (a flushed denormal result included) into +0, and are ignored with MODE.IEEE = 1; with f32 denormals kept they are also ignored for the ALU ops (the transcendental and cube ops still apply them). LLVM notes that omod mishandles signed zeros (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier. The translator keeps -0 (`OpFMul`), so on that evidence it likely differs from hardware; RDNA2 itself is unmeasured (see #1006). Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3; invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). |
| Float min/max/med3 with NaN, `v_fract` | Measured on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013) with the hw-oracle tool from the AnyPS5 project, 537 input rows in all four IEEE/DX10_CLAMP combinations and in wave32 and wave64, the same for every combination with quiet NaNs. `v_min_f32`/`v_max_f32`, `v_min_f16`/`v_max_f16` and each half of `v_pk_min_f16`/`v_pk_max_f16`: one NaN operand gives the other operand, bits unchanged; both NaN give src0; -0 < +0. `v_min3`/`v_max3` = f(f(s0, s1), s2) with that min/max. `v_med3_f32`/`_f16`: with any NaN operand the result is min3(s0, s1, s2), otherwise the median (-0 < +0). `v_fract_f32` rounds x − floor(x) once and returns 0x3f7fffff (the largest float below 1) where that gives 1.0, e.g. fract(-1e-10); f16 gives 0x3bff; fract(-0) = +0, fract(±inf) = NaN, a NaN passes through. The translator emits `NMin`/`NMax` for these min/max ops (before: `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `FClamp(z, NMin(x, y), NMax(x, y))`, and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead. `v_fract_f32` is `Fract` followed by `OpFOrdEqual` with 1.0 and an `OpSelect` of 0x3f7fffff, so the NaN of fract(±inf) is kept; `v_fract_f16` does the same before packing and then replaces a packed 0x3c00 with 0x3bff (not after an output multiplier, where 1.0 can be a true result). Other `FMin`/`FMax`/`FClamp` uses (the `clamp` bit, LOD and conversion clamps, `v_cvt_pk_u8_f32`, the BVH slab test) are unchanged. Not modelled: signalling NaNs under IEEE mode; NaN under the `clamp` bit (hardware gives +0 with DX10_CLAMP=1 and the NaN with DX10_CLAMP=0; the translator still emits `FClamp`); the NaN payload when both operands are NaN (`NMin` only promises a NaN); and without the `SignedZeroInfNanPreserve` execution mode Vulkan does not strictly guarantee NaN or signed-zero behaviour, so these rules hold where the driver keeps them. With an output modifier (`mul:2`, `mul:4`, `div:2`) on `v_fract_f16` the translator applies the modifier to the f32 fract before narrowing to f16; the hardware order of rounding and modifier for that case was not measured, so a result can differ by one f16 step for tiny negative inputs (e.g. x = -1e-4 with `div:2`). GPU-checked with `runtime/test/shaders/ps_fnan_med3.asm` and `ps_fnan_fract.asm` (inputs read from memory at run time) on an AMD Radeon RX 6800, Windows 11, driver 26.11.2: 4096/4096 pixels exact; on that driver the two med3 words differed before the change (0x40e00000 and 0x40600000 instead of 0x40a00000 and 0xc0200000), and so did the f16 fract word (0x3c00 instead of 0x3bff) once f16 results were narrowed with integer round-to-nearest; the f32 fract and the min/max words were already the hardware words there. `tests/semantic/test_float_nan_fract.py` runs the measured rows through the translator and the interpreter. |
| Wave64 handling | Wave size is detected per shader from the code (64-bit EXEC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64` even when the mask is an ordinary SGPR pair; mesh shaders are always wave64). Until 2026-11-21 a mask-only wave64 program with no EXEC markers was translated as wave32, so `s_bcnt1_i32_b64` counted one half (#210). GPU-checked with `runtime/test/shaders/cs_w64_mask_detect.asm` (48 set bits of `(lane & 5) != 0`) on NVIDIA GeForce RTX 5060 under `LEONIDA_W64_EMULATE=1`. 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, as `(K >> lane) & 1` (shift and mask: Intel's Windows driver evaluated `OpBitFieldUExtract` of a constant that fits in 16 bits with the lane taken mod 16, so `exec_lo = 0xffff` ran all 32 lanes; GPU-checked with `runtime/test/shaders/cs_exec_const.asm` on Intel UHD Graphics 770, driver 32.0.101.6129, and NVIDIA GeForce RTX 4080 SUPER); before, any non-zero constant turned every lane on. A register written to `exec_hi` sets lanes 32–63 only. VCC's halves follow the same rule while VCC holds a lane mask: a 32-bit write to `vcc_lo` sets lanes 0–31 of the mask and one to `vcc_hi` lanes 32–63 (until 2026-11-22 a `vcc_lo` write set all 64 lanes and a `vcc_hi` write never reached the mask that `s_cbranch_vccz`/`v_cndmask` read; CPU-checked by `tests/semantic/test_wave64_vcc_half_write.py`, not GPU-checked). 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. |
| Lane select (`v_readlane_b32` / `v_writelane_b32`) | The lane is **S1[4:0] in wave32** and S1[5:0] in wave64, from an SGPR or a constant, and EXEC is ignored (RDNA 3 ISA guide pseudocode for both opcodes; RDNA 2 has the same encoding and gives no pseudocode). **Until #488 (SHADER-52) a wave32 shader masked with 63 as well**: a lane select of 32 or more wrote no lane, and a read shuffled from a lane past the end of a 32-wide subgroup, which SPIR-V leaves undefined (NVIDIA wraps it, so reads happened to come out right there). Found by the FUZZ-7 cross-lane fuzzer: 23 of 100 random wave32 programs, each minimized to `s_mov_b32 s28, K; v_writelane_b32 vD, x, s28` with K ≥ 32. GPU-checked with `runtime/test/shaders/cs_w32_lane_wrap.asm` (25 16 777 777) on NVIDIA GeForce RTX 5060 (#488) and RTX 4090 (subgroup 32, driver 621.14); `tests/test_translate.py` checks the masks in the SPIR-V, and `tests/semantic/test_wave32_lane_select.py` runs the shader across 32 lanes, where a mask of 63 is an out-of-range shuffle. |
| 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). Fewer rounds, same results: a whole-mask read (`s_bcnt1`, `v_mbcnt_lo/hi`, ...) of the value of the same register (or EXEC) that an earlier read in the block already exchanged reuses that exchange (the value's identity is the SSA id last stored to the register, forgotten at block start and at any label); and a block that ends in a voted branch (`s_cbranch_vccz/vccnz/execz/execnz`) runs its successor in the round that reads the vote, since that segment only reads the vote and picks the next block (an inner loop in the scheduler, flag `%x_chain`). Both rules are pinned by `cs_w64x_mask_reuse` (a mask register and EXEC rewritten between reads), `cs_w64x_mask_reuse2` (EXEC read twice, a read after a buffer store, one half of a mask pair rewritten while the other is kept, a voted branch whose successor starts with a load of the other half's earlier store) and `cs_w64x_chain_barrier` (a voted branch whose successor starts with `s_barrier`, two waves): expected values from the ISA, first run on the AMD 880M with its native 64-wide subgroup, then emulated on both GPUs; `tests/test_translate.py` counts the exchanges in the SPIR-V (one per value, a new one after a rewrite of the register or EXEC), and the translator refuses (`Unsupported`) a voted branch whose segment was not started by the vote's own round. `scripts/bench_wave64.py` times `cs_bench_mix` native and emulated and checks the emulated output bytes against the native AMD run. 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` 38/39 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 40/40 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). |
-| Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one). The raw pair a PS reads ("PS system inputs": 321 PS) comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module then needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. The stage before the PS writes (1,0,0), (0,1,0), (0,0,1) at the triangle's three vertices: `tools/bary_fallback_gs.py` writes that pass-through geometry shader from the index (Position and the PS's input locations copied unchanged). Default (perspective) interpolation of those weights is the perspective-correct barycentric, the value `BaryCoordKHR` has, so `.y`/`.z` stay AMD's i/j; shaders that don't read the pair translate to the same module either way. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal, no barycentric extension; driver 560.94, Windows 10) with `LEONIDA_BARY_FALLBACK=1`: `ps_bary` 4096/4096 pixels exact, and `ps_uniform_branch` and `ps_scc_mask32` pass, through `run_gpu_tests.py` and `build.py` + `check.py`, with zero Khronos validation messages. Checked in `tests/semantic/test_bary_fallback.py`. The runtime building that GS per pipeline is the follow-up (it needs the graphics pipelines of #291). |
+| Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one). The raw pair a PS reads ("PS system inputs": 321 PS) comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module then needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. The stage before the PS writes (1,0,0), (0,1,0), (0,0,1) at the triangle's three vertices: `tools/bary_fallback_gs.py` writes that pass-through geometry shader from the index (Position and the PS's input locations copied unchanged). Default (perspective) interpolation of those weights is the perspective-correct barycentric, the value `BaryCoordKHR` has, so `.y`/`.z` stay AMD's i/j; shaders that don't read the pair translate to the same module either way. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal, no barycentric extension; driver 560.94, Windows 10) with `LEONIDA_BARY_FALLBACK=1`: `ps_bary` 4096/4096 pixels exact, and `ps_uniform_branch` and `ps_scc_mask32` pass, through `run_gpu_tests.py` and `build.py` + `check.py`, with zero Khronos validation messages. Checked in `tests/semantic/test_bary_fallback.py`. For a known VS/PS pair, `python -I tools/bary_fallback_gs.py DIR --pair VS PS` builds `PS.bary_gs.clipN.spv`. It copies the producer’s `ClipDistance[N]` at each emitted vertex, using the VS index field `clip_distance_count`. On RTX 5080 and Radeon integrated graphics, two independently shifted clip planes yielded 512, 1024, 2048 or 4096 covered pixels, matching the native barycentric path. For a cull-only VS the pair writes `PS.bary_gs.cullN.spv` from `cull_distance_count`. A two-plane synthetic draw on the same GPUs covered 0 pixels when every vertex was negative for either plane and all 4096 when each plane had a nonnegative vertex. The helper rejects mixed clip/cull arrays. The runtime building that GS per pipeline is the follow-up (it needs the graphics pipelines of #291). |
| 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, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), and input/output locations. A runtime can create every pipeline at load time from it without parsing SPIR-V. |
| Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. |
| 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. |
@@ -284,7 +301,9 @@ How the generated SPIR-V expects the runtime to work:
| LDS 2-address b64 (`ds_read2_b64`, `ds_write2_b64`, `ds_read2st64_b64`, `ds_write2st64_b64`) | Two elements at vaddr + offset0·unit and vaddr + offset1·unit, unit = 8 bytes (×64 for st64); each element is two consecutive dwords, low first. `read2_b64` fills v[d:d+3] after all four loads (a vdst overlapping vaddr is safe); `write2_b64` takes two VGPR pairs. The b32 forms share the code with unit 4. Source: RDNA2 ISA DS 2-address forms. CPU-checked by `tests/semantic/test_lds_read2_write2_b64.py` (compute listings, LDS as a Workgroup variable). **Not GPU-verified.** |
| 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). **d16 loads take the same branch** and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float view, the low 16 bits of each value from the uint/sint views (truncated). Before this, a d16 load always read the float view, so a `Texture2D` `Load` returned garbage. Checked by `tests/test_image_load_d16_typed.py` (CPU: the uint/sint reads are emitted, the SPIR-V validates) and on an RTX 5070 by `runtime/test/shaders/cs_imgload_d16.asm` (r32 uint read back with a d16 load, every texel exact). Unverified: whether AMD saturates out-of-range integers instead of truncating (Mesa sets `integer_dest_saturates`), and d16 loads on 1D, 2D-array and 3D images on a GPU. |
+| Typed image loads | `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). Before #1136, a d16 load always read the float view, so a `Texture2D` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Unverified: whether AMD saturates out-of-range integers instead of truncating (Mesa sets `integer_dest_saturates`), and d16 loads on 1D, 2D-array and 3D images on a GPU. |
+| Typed 2D gathers | `image_gather4_lz(_o)` takes one channel from four taps. The T# FORMAT selects the float, UINT or SINT sampled image at binding 0. For d16, integer taps are packed low half first, two per VGPR; float taps round to f16. | AMD RDNA 2 ISA §8.2 (MIMG D16). RTX 5080 and Radeon Graphics matched a CPU clamp-to-edge gather over all 4096 RGBA32F pixels for 8-bit UINT, SINT and UNORM, both packed and unpacked, with zero offset and with (+1,-1). Selecting red in place of green changed all 4096 pixels. Out-of-range integer narrowing has the same limitation as typed image loads below. |
+| Typed image loads | `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). Before #1136, a d16 load always read the float view, so a `Texture2D` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Its D16 form packs the selected components in ascending order, two per VGPR. An RGBA8 two-level texture was checked on RTX 5080 and Radeon Graphics: all four exported halves matched the CPU reference for UINT, SINT and UNORM, and forcing level 0 changed every pixel. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Unverified: whether AMD saturates out-of-range integers instead of truncating (Mesa sets `integer_dest_saturates`), and d16 loads on 1D, 2D-array and 3D images on a GPU. |
| 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**. In the 26,503-shader disassembled corpus (measured via `tools/feature_scan.py`), 0 of 10,500 shaders (11,930 `v_perm_b32` instructions) use selectors 8–11 or >= 13: all 11,258 immediate and 672 constant-register selectors (0 unresolved) use only bytes 0–7 (36,234) and 12 (11,486). 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`. |
| Sum of absolute differences (`v_sad_u8`, `v_sad_hi_u8`, `v_sad_u16`, `v_sad_u32`, `v_msad_u8`) | Unsigned, wrapping at 32 bits, with ABSDIFF(x, y) = `UMax − UMin`: `v_sad_u8` = S2 + the sum over the four bytes; `v_sad_hi_u8` = (that byte sum << 16) + S2; `v_sad_u16` = S2 + the sum over the two halves; `v_sad_u32` = \|S0 − S1\| + S2; `v_msad_u8` skips a byte where S1's byte is 0. `clamp` raises `Unsupported`: the ISA pseudocode doesn't say what it does to these ops. Source: RDNA2 ISA VOP3 opcodes 346–349 and 369 (pseudocode re-read for this row). CPU-checked by `tests/semantic/test_alu_sad.py` (#544): a 9×9 grid of edge words per op, 40 seeded cases, masked bytes, an SGPR source, `clamp` rejected; the PR also reports a 300-case differential run per op with 0 mismatches. None of them is in the translated corpus, and none is GPU-checked. |
@@ -292,28 +311,29 @@ How the generated SPIR-V expects the runtime to work:
| `s_sext_i32_i8`, `s_sext_i32_i16`, `s_flbit_i32` | The first two sign-extend the low byte or the low half of S0 to 32 bits (`OpBitFieldSExtract`). `s_flbit_i32` counts how many bits in a row from the MSB equal the sign bit, and gives −1 when all bits are the same (0 and −1); it is the scalar form of `v_ffbh_i32` and goes through the same code. None of the three writes SCC. Source: RDNA2 ISA SOP1 opcodes 23, 25 and 26. CPU-checked by `tests/semantic/test_salu_sext_flbit.py` (#549): edge words with SCC starting at 0 and at 1, and 30 seeded values with long runs of sign bits. Not in the translated corpus, not GPU-checked. |
| `v_lerp_u8` | Per byte i: `D.b[i] = (S0.b[i] + S1.b[i] + (S2.b[i] & 1)) >> 1`, an unsigned average where bit 0 of S2's byte decides whether 0.5 rounds up. The 9-bit sum shifted right by 1 fits back in its byte, so nothing carries between bytes. `clamp` raises `Unsupported` (the ISA doesn't define it for this op). Source: RDNA2 ISA VOP3 opcode 333. CPU-checked by `tests/semantic/test_alu_lerp_u8.py` (#577): a 9×9×5 grid of edge and rounding words, 40 seeded cases, an SGPR source with an inline S2, `clamp` rejected. Not in the translated corpus, not GPU-checked. |
| Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination, and `s_cmov_b64`, stay `Unsupported`, #210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Not measured on RDNA2.** |
-| `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact; the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. **RDNA2 is not measured**; the ISA pseudocode does not say. |
+| `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, and on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. **RDNA2 is not measured**; the ISA pseudocode does not say. |
| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Not GPU-verified.** |
| 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 6 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`). **Not GPU-verified.** |
| Vector integer additions (`v_mul_hi_u32_u24`/`v_mul_hi_i32_i24`, `v_lshrrev_b64`/`v_ashrrev_i64`, `v_qsad_pk_u16_u8`/`v_mqsad_pk_u16_u8`) | `v_mul_hi_*24`: the high 32 bits of the 48-bit product of the low 24 bits, zero-extended (u24) or sign-extended from bit 23 (i24); the high halves of `v_mul_u32_u24` / `v_mul_i32_i24`. `v_lshrrev_b64` / `v_ashrrev_i64`: the pair (or a 64-bit constant) shifted right by S0 & 63, logically or arithmetically, through the `v_lshlrev_b64` code. `v_qsad_pk_u16_u8` / `v_mqsad_pk_u16_u8`: D.u16[k] = (S2.u16[k] + byte SAD of the 32-bit window S0[8k+31:8k] against S1) & 0xFFFF; the m form skips bytes where S1's byte is 0; `clamp` raises `Unsupported`. Source: RDNA ISA pseudocode. CPU-checked by `tests/semantic/test_alu_mul_hi_24.py`, `test_alu_shift_b64.py`, `test_alu_qsad.py`; run on NVIDIA by reviewers (`v_mul_hi_*24`: RTX 5090 and RTX 5070 in #440; `v_qsad`/`v_mqsad`: 24 cases bit-exact on an RTX 3060 in #623). **Not measured on RDNA2.** |
-| Constant and ordered VOPC, `v_cmp(x)_nlg_*`, `v_cvt_off_f32_i4`, `v_pipeflush` | `v_cmp(x)_f_*` is always false, `v_cmp(x)_t_*` (integers) and `v_cmp(x)_tru_*` (floats) always true; `v_cmp(x)_o_{f32,f16}` is true when neither source is NaN, `_u_` when either is (`OpIsNan`), and `_nlg_` when `x == y` or either source is NaN (`OpFUnordEqual`, completing all 16 IEEE-754 RDNA2 float VOPC predicates; LLVM `gfx10_asm_vopc.s`); the result goes through the usual VOPC path (VCC, an SGPR mask, or EXEC for `v_cmpx`; off lanes give 0). `v_cvt_off_f32_i4`: D = sext(S0[3:0]) / 16 (the ISA's CVT_OFF_TABLE, -0.5 .. 0.4375), exact, output modifiers apply. `v_pipeflush` only flushes the VALU pipeline and is translated as nothing, like `v_nop`. Source: RDNA2 ISA VOPC and VOP1. CPU-checked by `tests/semantic/test_vopc_const_ordered.py`, `tests/semantic/test_float_compares.py` (`nlg`, **not GPU-verified**), `test_alu_cvt_off.py`, `test_valu_pipeflush.py`; the constant/ordered float compares were run on an RTX 5090 (16 draws, quiet and signalling NaNs) and the suite on RTX 4050 / Radeon 740M in #620; `v_pipeflush` on RTX 5090 / RTX 3060 in #735. |
+| Constant and ordered VOPC, `v_cmp(x)_nlg_*`, `v_cvt_off_f32_i4`, `v_pipeflush` | `v_cmp(x)_f_*` is always false, `v_cmp(x)_t_*` (integers) and `v_cmp(x)_tru_*` (floats) always true; `v_cmp(x)_o_{f32,f16}` is true when neither source is NaN, `_u_` when either is (`OpIsNan`), and `_nlg_` when `x == y` or either source is NaN (`OpFUnordEqual`, completing all 16 IEEE-754 RDNA2 float VOPC predicates; LLVM `gfx10_asm_vopc.s`); the result goes through the usual VOPC path (VCC, an SGPR mask, or EXEC for `v_cmpx`; off lanes give 0). `v_cvt_off_f32_i4`: D = sext(S0[3:0]) / 16 (the ISA's CVT_OFF_TABLE, -0.5 .. 0.4375), exact, output modifiers apply. `v_pipeflush` only flushes the VALU pipeline and is translated as nothing, like `v_nop`. Source: RDNA2 ISA VOPC and VOP1. CPU-checked by `tests/semantic/test_vopc_const_ordered.py`, `tests/semantic/test_float_compares.py` (`nlg`; GPU-checked by `ps_cmp_nlg.asm`: f32 and f16 with ±0, quiet and signalling NaN, ±inf and ignored f16 high halves, the e64 form with `abs`/`neg`, and `v_cmpx_nlg` on equal and NaN operands, Tesla V100 (NVIDIA 580.95.05, Linux)), `test_alu_cvt_off.py` (GPU-checked by `ps_cvt_off.asm`, upper bits ignored and `mul:4` with and without `clamp`), `test_valu_pipeflush.py`; the constant/ordered float compares were run on an RTX 5090 (16 draws, quiet and signalling NaNs) and the suite on RTX 4050 / Radeon 740M in #620; `v_pipeflush` on RTX 5090 / RTX 3060 in #735. |
| Relative VGPR moves (`v_movrel*`) | The VGPR file is a Function-scope uint array, so `v_movrels_b32`/`v_movreld_b32`/`v_movrelsd_b32` become dynamic array accesses at `reg + M0` (the whole of M0, as the RDNA2 ISA's opcode descriptions say). `v_movrelsd_2_b32` (VOP1 opcode 72) offsets each side by its own field: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]], other M0 bits ignored (RDNA2 ISA §12.8 opcode description and the RDNA3 ISA; the RDNA2 §6.6 summary table prints M0[7:0] for the source). The write keeps inactive lanes. Not modelled: the hardware's range check against the wave's VGPR allocation (an out-of-range source reads VGPR0, an out-of-range write is dropped). CPU-checked by `tests/semantic/test_alu_movrelsd_2.py` (including set ignored M0 bits); GPU-checked with `runtime/test/shaders/cs_movrelsd_2.asm` (the ISA's own example, v25 ← v17 with M0 = (20 << 16) \| 10) on NVIDIA RTX 4050 Laptop (Ada) and AMD Radeon 740M (RADV). |
-| d16 and f16 format narrowing | The f16 of every d16 result (image samples and gathers, the `image_sample_c_lz` compare result, typed buffer loads) and of the f16 formats a typed buffer store writes is narrowed with integer round to nearest even (`Gen.f16_bits`; #489, #711), not with `PackHalf2x16`. AMD drivers lower `PackHalf2x16` to `v_cvt_pkrtz_f16_f32`, which rounds toward zero (#489), and there about half of all unorm8, unorm16 and snorm8 values loaded with d16 came out 1 ulp low (123 of 256, 31,742 of 65,536 and 110 of 256). The memory results are packed by `pack_f16_pair_int`, never by `f16_pack2`: they come from the texture and buffer units, not the VALU whose rounding `MODE.FP_ROUND` sets (#753). Round to nearest even for these conversions is inferred, as in #489, not measured. #489's own narrower, `f32_to_f16_int`, was folded into `f16_bits` on 2026-11-22: the two gave the same bits on 30,648 inputs (every f32 exponent, ties, the subnormal and overflow edges, NaN), and `f16_bits` lost its one GLSL.std.450 instruction (`UMin`) so the packer stays free of them. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`, `test_buffer_format_f16_narrowing_avoids_packhalf2x16`), `tests/test_d16_pack.py` and `tests/semantic/test_buffer_load_format.py` (`D16NormalizedRounding`). |
+| d16 and f16 format narrowing | The f16 of every d16 result (image samples and gathers, the `image_sample_c_lz` compare result, typed buffer loads) and of the f16 formats a typed buffer store writes is narrowed with integer round to nearest even (`Gen.f16_bits`; #489, #711), not with `PackHalf2x16`. AMD drivers lower `PackHalf2x16` to `v_cvt_pkrtz_f16_f32`, which rounds toward zero (#489), and there about half of all unorm8, unorm16 and snorm8 values loaded with d16 came out 1 ulp low (123 of 256, 31,742 of 65,536 and 110 of 256). Packed `buffer_load_format_d16_x` and `_xyz` write only the low 16 bits of the final VGPR. Its upper half survives even when the load is out of bounds. Native gfx1036 wave32 and wave64 confirmed this with RGBA8_UINT and RGBA8_UNORM, two destination seeds, and both even-component loads as full-write controls. Full pairs are packed by `pack_f16_pair_int` and an odd final buffer component is narrowed with `f16_bits` for float/normalized formats. These memory conversions do not use `f16_pack2`: they come from the texture and buffer units, not the VALU whose rounding `MODE.FP_ROUND` sets (#753). Round to nearest even for these conversions is inferred, as in #489, not measured. #489's own narrower, `f32_to_f16_int`, was folded into `f16_bits` on 2026-11-22: the two gave the same bits on 30,648 inputs (every f32 exponent, ties, the subnormal and overflow edges, NaN), and `f16_bits` lost its one GLSL.std.450 instruction (`UMin`) so the packer stays free of them. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`, `test_buffer_format_f16_narrowing_avoids_packhalf2x16`), `tests/test_d16_pack.py` and `tests/semantic/test_buffer_load_format.py` (`D16NormalizedRounding`). |
| 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`. |
| `v_cvt_flr_i32_f32`, `v_cvt_rpi_i32_f32` | RDNA ISA pseudocode: `f32_to_i32(floor(S0))` and `f32_to_i32(floor(S0 + 0.5))`, the `+ 0.5` rounded in binary32 like any f32 add (so 0.49999997 gives 1, where an exact round-half-up would give 0). `f32_to_i32` saturates as in the row above: INT_MAX / INT_MIN at or past ±2³¹ and for ±inf, 0 for NaN. Source neg/abs apply first. Checked on the CPU by `tests/semantic/test_alu_cvt_flr_rpi.py`, **not yet GPU-verified**. |
-| f16 rounding (SHADER-55, SHADER-56) | **Narrowing to f16 uses integer ops, not `PackHalf2x16`.** Every f16 ALU result (`v_*_f16` VOP1/VOP2/VOP3, `v_pk_*_f16`, `v_cvt_f16_f32`, `v_interp_p2_f16`, `v_fma_mix*`) and `v_cvt_pkrtz_f16_f32` go through `Gen.f16_bits` (round to nearest even, or round toward zero for pkrtz; f16 denormals kept, f32 denormal inputs give ±0, NaN stays a quiet NaN). GLSL.std.450 leaves `PackHalf2x16`'s rounding to the implementation, and drivers fold a `PackHalf2x16` → `UnpackHalf2x16` round trip to a no-op, so the next f16 op saw the unrounded f32: #513 (RTX 6000 Ada, `--wave64-emulate`, `v_pk_add_f16` → `v_pk_mul_f16` 1 ulp off), and pkrtz giving round-to-nearest on llvmpipe. **f16 FMAs round once** (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`): x·y is exact in f32, TwoSum gives the exact error of the f32 sum, and round-to-odd at f32 then rounds correctly to f16. An RX 6700 matched a correctly rounded f16 FMA in 12,612 of 12,612 cases (#374); `Fma` then narrowing double-rounded. Checked by `tests/semantic/test_f16_int_convert.py` (edges + seeded sweep against Python's binary16), `tests/semantic/test_f16_fma_rounding.py` (exact rational reference; built near-tie cases fail on the old translation) and `tools/valu_fuzz.py --family f16` on an RTX 6000 Ada. Image/buffer d16 packing (#489) and the 16-bit interpolant quantize (#512) are separate. `v_fma_mix*` with f32 sources still uses `Fma`. |
+| f16 rounding (SHADER-55, SHADER-56) | **Narrowing to f16 uses integer ops, not `PackHalf2x16`.** Every f16 ALU result (`v_*_f16` VOP1/VOP2/VOP3, `v_pk_*_f16`, `v_cvt_f16_f32`, `v_interp_p2_f16`, `v_fma_mix*`) and `v_cvt_pkrtz_f16_f32` go through `Gen.f16_bits` (round to nearest even, or round toward zero for pkrtz; f16 denormals kept, f32 denormal inputs give ±0, NaN stays a quiet NaN). After a MODE.FP_ROUND toward-zero write the ALU results take the toward-zero form instead (`Gen.f16_res`; see Known approximations). GLSL.std.450 leaves `PackHalf2x16`'s rounding to the implementation, and drivers fold a `PackHalf2x16` → `UnpackHalf2x16` round trip to a no-op, so the next f16 op saw the unrounded f32: #513 (RTX 6000 Ada, `--wave64-emulate`, `v_pk_add_f16` → `v_pk_mul_f16` 1 ulp off), and pkrtz giving round-to-nearest on llvmpipe. **f16 FMAs round once** (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`): x·y is exact in f32, TwoSum gives the exact error of the f32 sum, and round-to-odd at f32 then rounds correctly to f16. An RX 6700 matched a correctly rounded f16 FMA in 12,612 of 12,612 cases (#374); `Fma` then narrowing double-rounded. Checked by `tests/semantic/test_f16_int_convert.py` (edges + seeded sweep against Python's binary16), `tests/semantic/test_f16_fma_rounding.py` (exact rational reference; built near-tie cases fail on the old translation) and `tools/valu_fuzz.py --family f16` on an RTX 6000 Ada. Image/buffer d16 packing (#489) and the 16-bit interpolant quantize (#512) are separate. `v_fma_mix*` with f32 sources uses `Fma` then narrows (two roundings, unmeasured) in nearest-even mode; toward zero it rounds once (see Known approximations). |
| `v_interp_p2_f16` clamp | The VOP3 `clamp` bit on `v_interp_p2_f16` clamps its f16 result to [0, 1], applied before the narrowing like the other f16 results (Mesa ACO `aco_opcodes.py` declares the op `dst(F16)`, which takes output modifiers; llvm-mc encodes `clamp` on it but no omod). Until 2026-11-22 the translator dropped it. Checked by `tests/semantic/test_interp_f16.py`: attributes 1.5 and -0.25 read with clamp give 1.0 and +0.0, and without it 1.5 and -0.25. No GPU test: `vs_ids` gives attributes in [0, 1) only. |
| 16-bit interpolation (`v_interp_p1ll_f16` / `v_interp_p2_f16`, `high`) | A 16-bit varying shares its 32-bit param channel with another: the producer packs them as low half, high half (Mesa `ac_nir_prerast_utils.c`: `nir_pack_32_2x16_split` by `io_sem.high_16bits`), the PS sets `FP16_INTERP_MODE` (plus `ATTR1_VALID` when the high half is used, RADV `radv_ps_input_type_bits`), and the `high` bit picks the half on both ops of the pair (ACO `emit_interp_instr`, `aco_isel_helpers.cpp`; llvm-mc gfx1013 sets the same bit, byte 5 bit 0, on both: p1ll `v2, v0, attr0.x high` 0x00 → 0x01, p2 `v2, v1, attr0.x, v3 high` 0x02 → 0x03). The translated VS exports the channel's raw bits, so interpolating them as one f32 gives neither half. A location any `*_f16` interp reads is therefore declared `PerVertexKHR` (`vec4[3]`, no `Flat`; it still matches a producer's vec4 output at that location); this needs `VK_KHR_fragment_shader_barycentric` (`fragmentShaderBarycentric`) for every such PS, not just the raw-barycentric ones; the index records it like any capability (`features: ["fragmentShaderBarycentric"]`), so `vk_pipeline_check` and `vk_harness` skip such a PS on a device without it. Nothing picks `--bary-fallback` from the device: it is a translation-time flag. Each f16 read decodes its half of each vertex's word (`UnpackHalf2x16` component 0 or 1) and weights them as AMD does, P0 + i(P1 − P0) + j(P2 − P0) with i, j = `BaryCoordKHR`.y/.z, then p2 clamps and narrows as before. f32 reads of such a location (`p1/p2_f32`) interpolate the raw word the same way, and `v_interp_mov_f32` takes vertex 0's. Until 2026-11-22 `high` was ignored and both halves read the smooth-f32 interpolation of the whole word; abilliontokens counted `high` in 4,776 of 12,101 PS (39.5%, 51,684 instructions, always p1ll/p2 pairs, no `p1lv`), and Pipodi found 4,731 of those 4,776 read both halves of the same channel, with p1ll and p2 always agreeing on attribute, channel and `high`. Like the f32 path, the pair's I/J operands are not read: the weights come from `BaryCoordKHR` (213 PS that compute their own barycentrics into v0/v1 first are a separate gap). Confirmed by `tests/semantic/test_interp_f16_high.py` (per-vertex halves 0.5/1.5/2.5 and −4/8/16 at weights (0.25, 0.25, 0.5) give 1.75 and 9.0; fails on the old translation) and the GPU fixture `ps_interp_f16_high` drawn with `vs_f16_pack` (u and v packed in one channel both ways, f32 control) and, through `scripts/run_gpu_tests.py`, with the mesh producer `ms_f16_pack` (mesh `exp paramN` stores the same raw words, `Gen.ms_export`): both pass on an RTX 5070 and fail on the old translation (off by 0.984). spirv-val and `vk_pipeline_check` (real pipelines against the vec4 VS stubs, RTX 5070) also accept PS mixing high, low, f32 and flat reads of one location and of several. **Unverified:** AMD hardware (whether it computes P10/P20 in f16 or rounds the p1ll intermediate differently), f16 denormal and NaN halves. **`--bary-fallback`** has no per-vertex inputs, so it keeps the old smooth-f32 read and cannot honour `high`; `check.py` skips the fixture there. |
-| `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`; **not GPU-verified**. |
-| 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 (ALU sites: see the f16 rounding row). The MODE register (`s_setreg`) is ignored, so denormal and rounding behaviour is Vulkan's default. `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). |
+| `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`, and on a GPU by `ps_fmac_f16_mods.asm`, `ps_interp_f32_mods.asm` and `ps_interp_mov_mods.asm` (the last two drawn with `vs_interp_consts.asm`, whose params are constant over the triangle; each modifier and the omod-before-clamp order change a word; Tesla V100 (NVIDIA 580.95.05, Linux)). |
+| 16-bit vector compare `op_sel` (`v_cmp(x)_*_{f16,u16,i16}`) | VOP3 `op_sel:[s0,s1]` selects bit `[15:0]` (`0`) or `[31:16]` (`1`) of each source before f16 input modifiers (`neg`/`abs`, via `Gen.f16_in`) or `u16`/`i16` zero-/sign-extension (`OpBitFieldUExtract`/`OpBitFieldSExtract` at bit offset 16 when set, 0 otherwise); VOPC writes a scalar lane mask (VCC/SGPR or EXEC for `v_cmpx`), so there is no destination `op_sel` bit. Until 2026-11-22 `Gen.compare` hardcoded the low half and ignored `mods`. Source: AMD RDNA2 ISA VOP3 `op_sel` and Mesa ACO `can_use_opsel`. Checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations across `f16` relations/ordered/unordered/NaN/`neg`/`abs`, `u16`, signed `i16`, and `v_cmpx` wave32/wave64 EXEC updates via `spirv_mini_interp` and `spirv_wave_interp`); **not GPU-verified**. |
+| 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 ALU ones follow a MODE toward-zero write (below; ALU sites: see the f16 rounding row). MODE: `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2)` (f16/f64 rounding) is tracked in a per-invocation variable, the only MODE field the corpus writes (9,417 writes in 6,333 shaders: 6,694 toward zero, 2,723 back to nearest even). While it is toward zero, every VALU f16 result except the transcendentals listed below (`v_cvt_f16_f32`, f16 arithmetic, `v_pk_*_f16`, `v_fma_mix{lo,hi}_f16`, `v_interp_p2_f16`) rounds toward zero exactly, with the integer conversion `v_cvt_pkrtz_f16_f32` uses (`f16_bits(rtz=True)`, see the f16 rounding row), and `v_add_f64` steps back one ulp when the TwoSum error shows it rounded away from zero; finite overflow gives the largest finite value. The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product (|x*y| < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `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). |
| Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` (SHADER-118) | The three have no f32 denormal support: a subnormal operand, the rounded product or the result reads as signed zero, whatever the MODE register says. `Gen.flush_f32` emits `|x| < FLT_MIN → copysign(0, x)` on the three operands, after the product rounding and after `omod`/`clamp`; inf and NaN compare false and pass through, and 0 keeps its sign. Source: LLVM AMDGPU `SIISelLowering.cpp`, `SITargetLowering::isFMADLegal` (llvm-project `1922c0c`), which forms `v_mad_f32`/`v_mac_f32` only when f32 denormals are flushed. Corpus count with `tools/shader_profile.py` over the 26,503 gfx1013 shaders: `v_mad_f32` in 7,298 shaders (139,287 occurrences), `v_mac_f32` in 5,889 (276,806: 265,901 `_e32`, 10,811 `_e64`, 94 `_dpp`), `v_mad_legacy_f32` in 6,059 (24,765); 9,297 shaders (35.1%) use at least one, 440,858 occurrences (0.99% of the corpus's 44,406,870 instructions). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, NaN/inf/zero pass-through, and a sabotaged pass-through that fails); **not GPU-verified** — a native measurement still needs an RDNA1/RDNA2 part that has these opcodes. The `omod` order is an assumption: the flush runs after `div:2`/`mul:2`/`mul:4`, so `FLT_MIN div:2` is flushed, as pinned by that test. |
| Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x | x>>1 | x>>2 | x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. |
| Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2). Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0 without a load. **The RX 6800 measurement behind RAW loads** (`buffer_load_dword`/`x2`/`x3`/`x4`, stride 0, no `idxen`, OOB_SELECT 3; the per-mode rule below covers every mode, stride and `idxen`): the byte offset O = inst_offset + soffset + (offen ? vaddr : 0) is exact (nothing truncated, and the address keeps base & 3), and dword i is data when O + 4·i + 4 ≤ num_records, else 0, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword), for x1/x2/x4 with V# word3 0x31016fac (OOB_SELECT 3) at offsets 0..63 per lane, NUM_RECORDS 17..23 and 0x1000, base & 3 = 0 and 3: a dword at 0xf with NUM_RECORDS 18 is 0 (a start-only check reads it); x4 at 3 with 18 gives three data dwords and 0 for the fourth, which starts at 15 < 18 (so neither a whole-load nor a per-dword start check), and the zero is a whole 0, not partial bytes; x4 at offset:13 with 20 gives data, 0, 0, 0; inst_offset, soffset and offen are summed before the check; base & 3 = 3 flips at the same offsets. `x3` gets the rule without a measurement. **Per-mode check (V# OOB_SELECT, word3 bits [29:28])**, for every MUBUF/MTBUF access, as measured natively on RDNA2 (gfx1036, 732 cases, `docs/buffer_bounds.md`; Mesa's GFX11 column, not its GFX10 one). `idx` = `vindex` (0 without `idxen`), `off` = inst_offset + vaddr offset (offen), `offs` = `off` + soffset. A dword at byte 4·k of the access is out of range when: **0 STRUCTURED_WITH_OFFSET** `idx >= num_records` or `off + 4k + 4 > stride`; **1 STRUCTURED** `idx >= num_records` (no `idxen`: idx 0, so only `num_records == 0`); **2 DISABLED** `num_records == 0`; **3 RAW** `offs + 4k + 4 > num_records` (`idx * stride` is in the address, not in the check). A literal word3 (`s_mov_b32` earlier in the block) folds the mode, a run-time one selects with `OpSelect`. Multi-dword accesses, measured on the Radeon 880M (gfx1150, a valid proxy: gfx1036 follows the same column and gfx1150 matched it bit-exactly): in modes 0 and 3 **`buffer_load_dwordx2..x4` and `buffer_store_dwordx2..x4` are per dword**, for loads and stores alike (x4 at off 20 of 32 in RAW loads/stores 3 dwords, at 28 one, at 32 none; mode 0 likewise at the stride); modes 1 and 2 check once and always take the whole access. **A typed element (`buffer_load_format_*`, `buffer_store_format_*`) is all or nothing and ends at its format's size** (32_32_32_32 at off 20 of 32 reads or writes nothing), and an atomic checks its dword's end like a dword access. The translator does the same: per-dword guarded loads and stores for modes 0 and 3 (a store that straddled the edge used to write past it), the element size from the instruction's format, a literal word3 or the V#. The same oracle confirmed the terms (504 `buffer_load_dword` probes, idxen/offen/inst_offset/soffset at the stride and record edges, 0 disagreements): mode 0's `off` has `inst_offset` and no soffset, mode 1 reads nothing but the index, mode 3 adds inst_offset and soffset. `s_buffer_load` (SMEM) is separate: it keeps the `num_records` bound of the Scalar/buffer row and ignores OOB_SELECT (the same pattern for 0 to 3). **Swizzle**: SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are not modelled: a literal V# with either set is `Unsupported`, a run-time V# with them is translated unswizzled, which is silently wrong (known gap). Until 2026-11-22 the translator ignored OOB_SELECT and checked by stride alone (`offset < num_records`, `index < num_records`, or `offset < num_records * stride`): a V# with word3 = 0 (mode 0, stride 0) was fully readable and is now always out of range, as on hardware, so the test harnesses' output V# is `0x31016fac` now (`vk_compute_test`, the interpreter tests, `cs_bounds.asm`, `cs_fmt_1010102.asm`, `cs_store.asm`). **How confirmed**: the native RDNA2 measurement (gfx1036) and the gfx1150 oracle (RDNA3.5, same column); GPU test `cs_oob_select.asm` (every mode, literal and run-time V#, words derived from the rules) on an NVIDIA RTX 5070 and an AMD Radeon 880M, which checks the translation, not RDNA2; `tests/semantic/test_buffer_oob_select.py` (a hand-written table of 33 cases over the four modes, loads and stores, both V# forms, plus the multi-dword stores and typed elements); `cs_oob_tail.asm` pins the end-based edge, per-dword x4 loads and stores and the all-or-nothing element, where Mesa's GFX10 column gives other words. **Unmeasured**: gfx1013/GFX10.1 itself (see `docs/buffer_bounds.md`), swizzle, unaligned addresses, and the mode 1/2 boundary of `buffer_load_dwordx2..x4` on RDNA2 hardware proper (the gfx1150 proxy shows all dwords in). Checked by `tests/semantic/test_value_semantics.py` (`RawBufferTailBounds`: the RX 6800 rows, values and the addresses loaded) and the GPU tests `runtime/test/shaders/cs_bounds.asm` (AMD Radeon RX 9070 XT, RX 6800), `cs_buf_tail.asm` (RX 6800, Vulkan, driver 26.11.2; aligned offsets only, since the translator's `Aligned 4` loads at byte-exact addresses were not checked on a Vulkan driver) `cs_oob_select.asm` and `cs_oob_tail.asm`. |
| 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. Opposite-half `s_cmp_*_u32/i32` comparisons (lo vs hi), ordering comparisons on mask halves, and `s_cmp_*_u32/i32/u64` comparing a lane mask against an arbitrary scalar or immediate reconstruct the exact 32/64-bit mask words via `wave_mask`. A compare with 0 keeps the vote, but a compare with -1 (all ones) does not: lanes that were never launched (a group smaller than the wave) don't vote, while their bits are 0 in the real mask, so until 2026-11-22 `s_cmp_eq_u32 vcc_hi, -1` read 1 in a 40-thread wave64 for `vcc_hi` = 0xff. GPU-checked with `cs_w64x_partial_scmp.asm` (40-thread wave64, native and `--wave64-emulate`) and `cs_w32_partial_scmp.asm` (20-thread wave32) on an AMD Radeon RX 7800 XT (RADV, Mesa 26.2.6): all 8 words as the headers derive, and 4 of 8 wrong in each with the old translator. 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`. |
| 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. Opposite-half `s_cmp_*_u32/i32` comparisons (lo vs hi), ordering comparisons on mask halves, and `s_cmp_*_u32/i32/u64` comparing a lane mask against an arbitrary scalar or immediate reconstruct the exact 32/64-bit mask words via `wave_mask`. 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`. |
-| VOP3 FP modifiers on constants | `tools/shader_ir.py` keeps VOP3 FP source modifiers (`neg(...)`, `|...|`, `-|...|`, `abs(...)`, and nested combinations) as `abs`/`neg` flags on `imm` and `fimm` operands so `abs` clears the sign bit first and `neg` flips it second (matching LLVM `AMDGPUInstPrinter.cpp::printOperandAndFPInputMods` and `llvm/test/MC/AMDGPU/vop3-modifiers.s`). Plain signed literals (`-1`, `-1.0`) are unchanged. Until 2026-11-22, `-|1.0|` folded `-` into the float before `FAbs` (yielding `+1.0`), `neg(0x3f800000)` / `neg(1)` applied two's-complement integer negation (`-4.0f` / `0xffffffff` NaN instead of `-1.0f` / `0x80000001`), and `|0x...|` / `-|0x...|` dropped `abs`. `tools/shader_meta.py` applies the same bit operations in `_imm_u32`. Checked on the CPU by `tests/test_shader_ir.py`, `tests/test_shader_meta.py` and `tests/semantic/test_vop3_const_mods.py` (f32, f16, `v_fma_mix_f32`, `v_cmp_class_f32`, f64 SPIR-V structure); **not GPU-verified**. |
+| VOP3 FP modifiers on constants | `tools/shader_ir.py` keeps VOP3 FP source modifiers (`neg(...)`, `|...|`, `-|...|`, `abs(...)`, and nested combinations) as `abs`/`neg` flags on `imm` and `fimm` operands so `abs` clears the sign bit first and `neg` flips it second (matching LLVM `AMDGPUInstPrinter.cpp::printOperandAndFPInputMods` and `llvm/test/MC/AMDGPU/vop3-modifiers.s`). Plain signed literals (`-1`, `-1.0`) are unchanged. Until 2026-11-22, `-|1.0|` folded `-` into the float before `FAbs` (yielding `+1.0`), `neg(0x3f800000)` / `neg(1)` applied two's-complement integer negation (`-4.0f` / `0xffffffff` NaN instead of `-1.0f` / `0x80000001`), and `|0x...|` / `-|0x...|` dropped `abs`. `tools/shader_meta.py` applies the same bit operations in `_imm_u32`. Checked on the CPU by `tests/test_shader_ir.py`, `tests/test_shader_meta.py` and `tests/semantic/test_vop3_const_mods.py` (f32, f16, `v_fma_mix_f32`, `v_cmp_class_f32`, f64 SPIR-V structure); GPU-checked for `-\|-2.0\|`, `neg(0x3f800000)`, `\|0xbf800000\|` and f16 `-\|0x3c00\|` by `ps_vop3_const_mods.asm` (Tesla V100 (NVIDIA 580.95.05, Linux)). |
| 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 = linearGroupIndex * NumThreads + LocalInvocationIndex`. 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. Fixed UNORM and SNORM loads share the exact integer quotient for each magnitude width across instructions and channels (checked against rationally rounded binary32 values on RTX 5080 and Radeon Graphics). The gfx1013 disassembler omits `format:` for the [GFX10 MTBUF default](https://llvm.org/docs/AMDGPUModifierSyntax.html#ufmt), `BUF_FMT_8_UNORM` (code 1). A few rare ops are still reported by name rather than guessed. |
+| 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. Packed `tbuffer_load_format_d16_{x,xy,xyz,xyzw}` load two 16-bit components per VGPR, with the same final partial write as MUBUF. Native gfx1036 wave32/64 confirmed all four widths for RGBA8_UINT and RGBA8_UNORM with a conflicting 32_UINT V# format. A translated vertex fetch on RTX 5080 and Radeon Graphics also followed a change to the instruction format between two draws with identical vertex records and V#. Fixed UNORM and SNORM loads share the exact integer quotient for each magnitude width across instructions and channels (checked against rationally rounded binary32 values on RTX 5080 and Radeon Graphics). The gfx1013 disassembler omits `format:` for the [GFX10 MTBUF default](https://llvm.org/docs/AMDGPUModifierSyntax.html#ufmt), `BUF_FMT_8_UNORM` (code 1). A few rare ops are still reported by name rather than guessed. |
### System values confirmed on the corpus (SHADER-4)
@@ -354,9 +374,12 @@ installs it at `/usr/lib/llvm-21/bin/llvm-mc`). The official Windows LLVM build
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++
+`%USERPROFILE%\.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.
+defaults. Keep `-Dest` out of AppData: `python` from the Python install manager (the `WindowsApps` alias) doesn't see
+folders that other programs create under `%LOCALAPPDATA%` or `%APPDATA%`, so `make_game.py` reports `llvm-mc` missing
+and the fuzzers stop with `WinError 2`, although `LLVM_MC` names the file; `py`, or the same `python.exe` started by
+its full path, sees it (measured with Python 3.14.7 on Windows 11).
```
powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1
@@ -389,7 +412,12 @@ against 201 clean and 6,560 invalid for gfx1030 and 283 clean for gfx1010–1012
`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.
+and byte 7 holds flags (bits 0–1 = interpolation mode, 1 flat and 2 linear; bit 4 = 16-bit interpolant). The
+record's position is the `v_interp attr` number. `interpolation_modes()` returns the modes by position; see the
+"PS interpolation modes (SHADER-181)" row of the contract table for the corpus counts.
+and byte 7 holds flags (bits 0–1 = read method, 0x01 `v_interp_mov` and 0x02 `v_interp_p1/p2`; bit 4 = 16-bit
+interpolant). The record's position is the `v_interp attr` number. `read_methods()` returns the read methods by
+position; see the "PS `v_interp` read methods" row of the contract table.
`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,
@@ -399,6 +427,25 @@ declare two or more, and the 10 undercounts are one family whose first record at
200-PS spot check agreed on 187/200. Flag bit 4 matches the `*_f16` interpolation opcodes in
12,067/12,101 (99.7%).
+`tools/ps_interp_modes.py` decodes the interpolation mode of each PS input from the DXBC container
+carved next to the FSSM, and runs the census. The mode is not in the FSSM: no FSSM word stores
+`SPI_PS_INPUT_ENA`/`ADDR` (every u16 in bytes 0x00–0x138 of all 12,101 PS was compared against the
+value reconstructed from the DXBC signature; only constants coincide). The PSV0 chunk
+(writer: dxc `lib/DxilContainer/DxilPipelineStateValidation.{h,cpp}`) holds, after the runtime info,
+resource bindings, string table and semantic-index table, a u32 element size (16) and then one
+16-byte input element per row: u32 semantic-name offset (0 = system value), u32 semantic-index
+offset, u8 rows, u8 start row, u8 cols[3:0] | start col[5:4] | allocated[6], u8 semantic kind
+(`DXIL::SemanticKind`: 0 Arbitrary, 3 Position, 6 ClipDistance, 7 CullDistance, 13 IsFrontFace),
+u8 component type (`DxilProgramSigCompType`: 1 UInt32, 3 Float32, 6 Float16), u8 interpolation mode,
+u8 dynamic mask | output stream, u8 reserved. The ISG1 chunk (the repo's 32-byte elements) supplies
+the read mask that marks live rows. The FSSM record flags decode as the read method — bit 0 (0x01)
+`v_interp_mov_f32`, bit 1 (0x02) 32-bit `v_interp_p1/p2`, bit 3 (0x08) Float16-typed parameter,
+bit 4 (0x10) `*_f16` opcodes — and the disassembly supplies the I/J operand of every interpolation.
+Per shader the code reads one barycentric pair (v0/v1 in 10,259 PS, none in 1,841, one v14 copy),
+and the pair's class follows the read rows: perspective-centre when a perspective generic is read,
+linear only in the 4 PS that interpolate SV_Position through the parameter cache (D3D forces
+noperspective on SV_Position), flat otherwise. Synthetic tests: `tests/test_ps_interp_modes.py`.
+
## Baseline already recorded
- `reports/manifest.json`: SHA-256 of all 108 files in `Documents\GTA6` (208.5 GiB). Run
diff --git a/docs/gamedata.md b/docs/gamedata.md
index d5bd80305..ab1448463 100644
--- a/docs/gamedata.md
+++ b/docs/gamedata.md
@@ -428,6 +428,16 @@ Measured over the 630 clouds:
`Density` within -100..100 (median 0.5) and `FogHeight` within -100..300: signed values, so these act as
offsets or overrides with a sign, not plain amounts.
+The cloud renderer's settings sit in one `STS_Config` document with 44 top-level sections: four cloud layers
+(`Nimbus`, `Cumulus`, `Stratus`, `Alto`) that share one set of 13 fields (noise weights and blends, erosion,
+density, lighting and multi-scattering density scale, shape fade, transition and altitude ranges, dilation,
+noise displacement); six media (`GlobalFog`, `LocalFog`, `Rain`, `Clouds`, `CloudsCirrus`, `CloudsHaze`) that
+share another set of 9; and 34 single-value or vector settings. Of the five cloud flags above, `Cumulus` and
+`Stratus` match a layer name, `Nimbus0`/`Nimbus1` would both fall on the one `Nimbus` layer, and
+`CirroStratus` has no layer of its own (`CloudsCirrus` is a medium, not a layer). The weather data's
+`CloudType` is fractional (14 distinct values from 0.01 to 0.67 over the 25 weathers), so it is a blend
+position rather than an index into these layers.
+
Not measured here (hypothesis): how a cloud's radius range blends with the weather's `CloudType` and cloud maps,
what a negative `Rain`/`Fog`/`Density` means (subtracting from the weather, or "unset"), and what the two
`Nimbus` flags distinguish.
@@ -687,6 +697,16 @@ entry combines up to four nested parameter groups with 12 direct scalar `value=`
| `roadPenalties`, `offRoadPenalties` | 40 / 40 each | identical 6-scalar schema: `fMaterialTractionLoss`, `fMaterialRollingDragGain`, `fMaterialSinkDragGain`, `fMaterialSurfaceDragGain`, `fWetTractionLoss`, `fWetDragGain` |
| Direct scalars (required) | 40 / 40 each | `fLoadShapeVarianceScale`, `fDamageShapeVarianceScale`, `fDamageCoefficientScale`, `fOptimumTyreTemp` (all `100.0`), `fOptimumTyreTempRange` (all `100.0`), `fGripDropOffWithTemp` (`0.01..0.05`) |
| Direct scalars (optional) | 36..39 / 40 | `fPuncturedTyreGripReduction`, `fBurstTyreGripReduction`, `fTractionStiffnessSpeedMult`, `fTractionStiffnessSpeedCap` (39 each); `fLoadStability` (37); `fLoadSensitivity` (36) |
+**Sample hours come from data.** One `time_data` document (root attributes `version` and `mode`) has exactly 13
+`sample` elements, each with `name`, `hour`, `uw_tc_mod` and `interpolation_type`, plus one `region`. The 13
+hours are integers from 0 to 22 in strictly increasing order, with gaps of 1 hour (7 times), 2 (twice), 3 (once)
+and 4 (twice); `interpolation_type` is `EASE_LINEAR_IN` on 9 samples and `EASE_QUARTIC_INOUT` on 4, and all 13
+`uw_tc_mod` values are the same name, which resolves to one of the 4,592 modifier names. The `region` name equals one of the two keyframe
+region names. So unlike GTA V, where the 13 sample times are compiled in, this build reads them (and the easing
+between them) from `time_data`; their count matches the 13 values of every keyframe variable.
+
+Not measured here (hypothesis): how the two regions are chosen at runtime, what the two plain-modifier numbers
+are (GTA V reads them as a value pair blended by strength), and how `controlValue` maps onto game state.
## Relationship to `data.rpf` and `script.rpf`
diff --git a/docs/i18n/README.md b/docs/i18n/README.md
index c351f44e6..5c31bb137 100644
--- a/docs/i18n/README.md
+++ b/docs/i18n/README.md
@@ -12,5 +12,8 @@ A language is added when a contributor volunteers to maintain it and keeps the s
| Language | File | Synced commit | Maintainer |
|---|---|---|---|
+| Français (`fr`) | [`fr/quickstart.md`](fr/quickstart.md) | `e7584c52` | `@Urban225` |
| Português (Brasil) (`pt-BR`) | [`pt-BR/quickstart.md`](pt-BR/quickstart.md) | `d3841c0c` | `@Andretuta` |
+| 简体中文 (`zh-CN`) | [`zh-CN/quickstart.md`](zh-CN/quickstart.md) | `e7584c5` | `@liang-kai-shui` |
| 简体中文 (`zh-CN`) | [`zh-CN/quickstart.md`](zh-CN/quickstart.md) | `0d61c357` | `@liang-kai-shui` |
+| Polski (Polish) (`pl-PL`) | [`pl-PL/quickstart.md`](pl-PL/quickstart.md) | `c0ac5fd6` | `@Dom-in` |
diff --git a/docs/i18n/fr/quickstart.md b/docs/i18n/fr/quickstart.md
new file mode 100644
index 000000000..80db496b7
--- /dev/null
+++ b/docs/i18n/fr/quickstart.md
@@ -0,0 +1,125 @@
+# Leonida — Guide de démarrage (`fr`)
+
+> [!NOTE]
+> La documentation en anglais ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) et
+> [`docs/README.md`](../../README.md)) **fait foi**. Ce guide ne reprend que les instructions stables d'installation
+> et de compilation (synchronisé avec le commit `e7584c52`). Pour l'état d'avancement du projet, qui change tous les
+> jours, consultez le [`README.md`](../../../README.md).
+
+## Ce qu'est Leonida
+
+Leonida est un projet de recompilation statique de Grand Theft Auto VI (version Xbox Series) pour le faire tourner
+nativement sous Windows. Il se construit **sur votre PC, à partir de votre propre copie du jeu**. Les shaders RDNA2 de
+la console sont traduits en SPIR-V (Vulkan), les ressources sont lues directement dans votre paquet et le logiciel
+système de la console est réimplémenté sous forme de shims.
+
+> [!IMPORTANT]
+> Ce dépôt **ne contient ni le jeu, ni clés, ni exécutable**, et n'explique pas comment les obtenir. Rien ici ne
+> déchiffre ni ne contourne une protection. Tout ce que la compilation produit (shaders traduits, ressources
+> extraites, dossier de travail, sauvegardes) provient de votre copie et **doit rester sur votre machine** : ne
+> joignez et ne partagez jamais ces fichiers dans une issue ou une pull request (voir
+> [`CONTRIBUTING.md`](../../../CONTRIBUTING.md)).
+
+Le projet en est à ses débuts : **le jeu ne démarre pas encore**.
+
+## Prérequis
+
+- **Votre propre copie** du paquet Xbox Series, version `1.0.2.1` : le dossier qui contient `MicrosoftGame.Config` et
+ les archives `.rpf`, sous forme de fichiers lisibles sur le disque.
+- **Windows 10/11 x64**, avec environ **350 Go libres** pour les fichiers de travail. Ils peuvent aller sur un autre
+ disque avec `--work`.
+- [Python 3.12+](https://www.python.org/downloads/) (cochez « Add python.exe to PATH » à l'installation).
+- [SDK .NET 8](https://dotnet.microsoft.com/download/dotnet/8.0).
+- [SDK Vulkan](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` et `vulkaninfo`).
+- [LLVM 21+](https://github.com/llvm/llvm-project/releases) avec la **cible AMDGPU** (`llvm-mc`) :
+ - La version officielle de LLVM pour Windows **n'inclut pas** la cible AMDGPU.
+ - Pour compiler un `llvm-mc.exe` natif avec cette cible, lancez `.\scripts\build_llvm_mc.ps1` dans PowerShell
+ depuis la racine du dépôt. Le script a besoin de `git` et des outils C++ de Visual Studio. Il définit `LLVM_MC`
+ pour votre utilisateur : ouvrez ensuite un nouveau terminal pour que la variable soit prise en compte.
+ - Avec WSL, installez `llvm-21` dans Ubuntu et donnez la commande entière à `LLVM_MC`, dans la session PowerShell
+ où vous lancerez `make_game.py` :
+
+ ```powershell
+ $env:LLVM_MC = 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'
+ ```
+
+ Voir [`docs/design.md`](../../design.md#disassembling-shaders) pour les détails.
+ - Sous Linux, un `llvm-mc` présent dans le `PATH` suffit.
+- **Visual Studio 2022** avec la charge de travail *Développement Desktop en C++* et le **SDK Windows `10.0.26100` ou
+ plus récent**, pour l'étape `runtime` (le runtime utilise les root signatures 1.2, absentes des SDK plus anciens).
+- [ffmpeg](https://ffmpeg.org/download.html) dans le `PATH` *(facultatif : décode les flux XMA2, et obligatoire avec
+ `--wav`)*.
+
+## Compiler
+
+### La méthode simple (Windows)
+
+1. Installez les prérequis ci-dessus.
+2. Clonez le dépôt **avec son sous-module** :
+ ```powershell
+ git clone --recursive https://github.com/ItsNotRexed/Leonida
+ ```
+3. Double-cliquez sur **`Build.bat`**.
+
+Le script trouve votre copie tout seul : il cherche dans Téléchargements, Bureau, Documents, Games, votre dossier
+utilisateur et à la racine de chaque disque, sur deux niveaux de dossiers. S'il trouve plusieurs copies, il demande
+laquelle utiliser ; s'il n'en trouve aucune, il vous demande de coller le chemin du dossier. Avant de commencer, il
+vérifie les prérequis et l'espace libre, et liste d'un coup tout ce qui manque. Le résultat va dans
+`Documents\Leonida`. Une compilation interrompue reprend là où elle s'était arrêtée.
+
+### Depuis un terminal (`make_game.py`)
+
+```powershell
+python -I make_game.py --find # liste les copies trouvées sur ce PC
+python -I make_game.py --check # vérifie votre copie, sans rien compiler
+python -I make_game.py --game "D:\chemin\vers\le\paquet" --out "D:\Games\Leonida" --work "E:\leonida-work"
+python -I make_game.py --stages shaders,assets # seulement certaines étapes
+python -I make_game.py --game "D:\chemin\vers\le\paquet" --wav # décode aussi l'Opus en WAV PCM (volumineux)
+python -I make_game.py --wave64-emulate off # auto (par défaut), on ou off
+```
+
+Les étapes s'exécutent dans cet ordre : `check` → `shaders` → `assets` → `runtime` → `pipelines`.
+
+- **`--wave64-emulate`** : traduit les shaders compute et mesh wave64 de façon exacte quelle que soit la taille des
+ sous-groupes du GPU. Les GPU NVIDIA et Intel ont des sous-groupes de 32 et en ont besoin. La valeur par défaut,
+ `auto`, interroge `vulkaninfo` et active l'émulation sauf si tous les GPU annoncent des sous-groupes de 64.
+- **`--work`** : choisissez un disque avec au moins 350 Go libres. La traduction des shaders est l'étape la plus
+ longue ; elle utilise par défaut la moitié des threads du processeur (réglable avec `--jobs`).
+- **`--wav`** : désactivé par défaut, car le WAV PCM 16 bits est plusieurs fois plus volumineux que l'Ogg Opus.
+- **Linux et Wine/Proton** : `make_game.py` fonctionne aussi sous Linux. Le chargeur est un programme Windows et
+ tourne sous Wine ou Proton. Pour l'étape `runtime`, vous pouvez passer `--runtime-build ` avec une
+ compilation Windows (`gta6rt.exe` et `gta6rt_tls_host.dll`) : le script écrit alors `gta6rt.sh`, qui lance
+ `gta6rt.exe` avec `wine`, ou avec le Wine désigné par la variable `WINE` (pour Proton, son `files/bin/wine`).
+
+## Problèmes courants
+
+- **Vous avez utilisé « Download ZIP » sur GitHub** : le ZIP ne contient pas le sous-module
+ `third_party/rpf9-explorer`. Utilisez `git clone --recursive`, ou lancez `git submodule update --init --recursive`
+ dans le dossier du dépôt.
+- **`llvm-mc` refuse `gfx1013` ou la cible AMDGPU** : vous utilisez probablement l'installateur officiel de LLVM pour
+ Windows. Lancez `scripts\build_llvm_mc.ps1`, ou faites pointer `LLVM_MC` vers le `llvm-mc` de WSL (`llvm-21`).
+- **CMake s'arrête sur « needs the Windows SDK 10.0.26100 or newer »**, ou MSVC signale que `Desc_1_2` n'est pas
+ membre de `D3D12_VERSIONED_ROOT_SIGNATURE_DESC` : mettez à jour le SDK Windows en `10.0.26100` ou plus récent, par
+ le Visual Studio Installer ou avec `winget install Microsoft.WindowsSDK.10.0.26100`, puis supprimez
+ `runtime/build` et relancez la configuration.
+- **Plus de place sur `C:`** : passez `--work "D:\leonida-work"` pour placer les fichiers temporaires sur un autre
+ disque.
+- **Windows refuse de lancer les programmes de test tout juste compilés** (« An Application Control policy has
+ blocked this file ») : c'est le Contrôle intelligent des applications de Windows 11. Voir
+ [`docs/testing.md`](../../testing.md#known-problems).
+
+## Contribuer et lancer les tests GPU
+
+1. Consultez les pull requests ouvertes et l'[issue de coordination][coord] pour ne pas refaire un travail en cours.
+ Réservez la tâche avec `claiming: `, ou avec une description d'une ligne s'il n'y a pas encore d'identifiant.
+2. Lancez les tests concernés, avec des entrées synthétiques. Par exemple, `python -I tests/test_manifest_verifier.py`
+ depuis la racine du dépôt.
+3. Dans la pull request, indiquez l'identifiant de la tâche, ce que vous avez testé, et le GPU et le pilote si vous
+ avez lancé des tests GPU. Précisez si vous avez été assisté par une IA. Les règles sont dans
+ [`CONTRIBUTING.md`](../../../CONTRIBUTING.md).
+
+Le [guide des tests GPU](../../testing.md) explique comment lancer les tests sans aucun fichier du jeu. Publiez vos
+résultats dans l'[issue #166](https://github.com/ItsNotRexed/Leonida/issues/166), un commentaire par GPU et par
+pilote.
+
+[coord]: https://github.com/ItsNotRexed/Leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22
diff --git a/docs/i18n/pl-PL/quickstart.md b/docs/i18n/pl-PL/quickstart.md
new file mode 100644
index 000000000..58122ffc4
--- /dev/null
+++ b/docs/i18n/pl-PL/quickstart.md
@@ -0,0 +1,102 @@
+# Leonida — Szybki start (`pl-PL`)
+
+> [!NOTE]
+> Dokumentacja w języku angielskim ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) i
+> [`docs/README.md`](../../README.md)) jest **wersją obowiązującą**. Ten przewodnik zawiera tylko stabilne instrukcje
+> konfiguracji i budowania (zsynchronizowany z commitem `c0ac5fd6`). Aktualny stan projektu znajdziesz w
+> [`README.md`](../../../README.md).
+
+## Czym jest Leonida
+
+Leonida to projekt statycznej rekompilacji Grand Theft Auto VI (Xbox Series), który uruchamia grę natywnie na
+Windowsie. Port jest budowany **na Twoim komputerze z Twojej własnej kopii gry**. Shadery RDNA2 z konsoli są
+tłumaczone na SPIR-V (Vulkan), zasoby gry są odczytywane bezpośrednio z Twojej paczki, a oprogramowanie systemowe
+konsoli jest zaimplementowane od nowa w postaci tzw. shimów.
+
+> [!IMPORTANT]
+> To repozytorium **nie zawiera gry, kluczy ani pliku wykonywalnego** i nie wyjaśnia, jak je zdobyć. Nic tutaj nie
+> odszyfrowuje danych ani nie obchodzi zabezpieczeń. Wszystko, co tworzy build (przetłumaczone shadery, wyodrębnione
+> zasoby, folder roboczy i zapisy gry), pochodzi z Twojej kopii i **musi zostać wyłącznie na Twoim komputerze** —
+> nigdy nie załączaj ani nie udostępniaj tych plików w issues ani pull requestach (zobacz
+> [`CONTRIBUTING.md`](../../../CONTRIBUTING.md)).
+
+Projekt jest na wczesnym etapie: **gra jeszcze się nie uruchamia**.
+
+## Wymagania
+
+- **Twoja własna kopia** paczki Xbox Series w wersji `1.0.2.1` (folder z plikiem `MicrosoftGame.Config` i archiwami `.rpf` czytelnymi na dysku jako zwykłe pliki).
+- **Windows 10/11 x64** z około **350 GB wolnego miejsca** na pliki robocze (mogą trafić na inny dysk dzięki `--work`).
+- [Python 3.12+](https://www.python.org/downloads/) (zaznacz *„Add python.exe to PATH”*).
+- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0).
+- [Vulkan SDK](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` i `vulkaninfo`).
+- [LLVM 21+](https://github.com/llvm/llvm-project/releases) z **targetem AMDGPU** (`llvm-mc`):
+ - Oficjalna wersja LLVM dla Windowsa **nie** zawiera targetu AMDGPU.
+ - Aby zbudować natywny `llvm-mc.exe` z AMDGPU, uruchom `.\scripts\build_llvm_mc.ps1` w PowerShellu w głównym
+ folderze repozytorium. Skrypt wymaga `git` i narzędzi C++ z Visual Studio, ustawia zmienną `LLVM_MC` dla
+ Twojego użytkownika i prosi o otwarcie nowego terminala, żeby zmienna była widoczna.
+ - Jeśli używasz WSL, zainstaluj `llvm-21` w Ubuntu i ustaw zmienną w tej samej sesji PowerShella, w której
+ uruchamiasz `make_game.py`:
+
+ ```powershell
+ $env:LLVM_MC = 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'
+ ```
+
+ Więcej szczegółów w [`docs/design.md`](../../design.md#disassembling-shaders).
+ - Na Linuksie wystarczy `llvm-mc` w `PATH`.
+- **Visual Studio 2022** z pakietem *Programowanie aplikacji klasycznych w języku C++* i **Windows SDK `10.0.26100` lub nowszym** (potrzebne do etapu `runtime`, który używa root signatures w wersji 1.2).
+- [ffmpeg](https://ffmpeg.org/download.html) w `PATH` *(opcjonalnie: dekoduje strumienie XMA2 i jest wymagany przy `--wav`)*.
+
+## Jak zbudować
+
+### Prosty sposób (Windows)
+
+1. Zainstaluj powyższe wymagania.
+2. Sklonuj repozytorium **razem z submodułem**:
+ ```powershell
+ git clone --recursive https://github.com/ItsNotRexed/Leonida
+ ```
+3. Kliknij dwukrotnie **`Build.bat`**.
+
+Skrypt sam znajdzie Twoją kopię gry (Pobrane, Pulpit, Dokumenty, Games, folder użytkownika i główne foldery
+wszystkich dysków, do dwóch poziomów w głąb). Rozpoznaje wersję po rozmiarach kilku plików, bez czytania dużych
+danych. Jeśli znajdzie kilka kopii, zapyta, której użyć, a jeśli żadnej — poprosi o wklejenie ścieżki do folderu.
+Przed startem sprawdza wymagania i wolne miejsce, a wynik zapisuje w `Documents\Leonida`. Przerwany build można
+uruchomić ponownie — będzie kontynuowany od miejsca, w którym się zatrzymał.
+
+### Z terminala (`make_game.py`)
+
+```powershell
+python -I make_game.py --find # lista kopii gry znalezionych na tym komputerze
+python -I make_game.py --check # sprawdza Twoją kopię, niczego nie buduje
+python -I make_game.py --game "D:\sciezka\do\paczki" --out "D:\Games\Leonida" --work "E:\leonida-work"
+python -I make_game.py --stages shaders,assets # tylko wybrane etapy
+python -I make_game.py --game "D:\sciezka\do\paczki" --wav # dodatkowo dekoduje Ogg Opus do PCM WAV (duże pliki)
+python -I make_game.py --wave64-emulate auto # auto (domyślnie), on lub off
+```
+
+Etapy wykonują się w tej kolejności: `check` → `shaders` → `assets` → `runtime` → `pipelines`.
+
+- **`--wave64-emulate`**: emuluje shadery compute/mesh wave64 na kartach z podgrupami 32-wątkowymi (NVIDIA i Intel). Domyślny tryb `auto` pyta `vulkaninfo` i sam włącza emulację, gdy jest potrzebna.
+- **`--work`**: najlepiej wskazać dysk z co najmniej 350 GB wolnego miejsca. Etap `shaders` trwa najdłużej i domyślnie używa połowy wątków procesora (można to zmienić przez `--jobs`).
+- **Linux i Wine/Proton**: `make_game.py` działa też na Linuksie. Aby wykonać etap `runtime` poza Windowsem, podaj `--runtime-build ` z buildem dla Windowsa (`gta6rt.exe` i `gta6rt_tls_host.dll`). Skrypt utworzy wtedy `gta6rt.sh`, który uruchamia program przez `wine` (albo przez Wine wskazane zmienną `WINE`, np. z Protona).
+
+## Częste problemy
+
+- **Pobrałeś repozytorium przyciskiem „Download ZIP” na GitHubie**: archiwum ZIP nie zawiera submodułu `third_party/rpf9-explorer`. Użyj `git clone --recursive` albo uruchom `git submodule update --init --recursive` w folderze repozytorium.
+- **`llvm-mc` odrzuca `gfx1013` / AMDGPU**: najpewniej masz oficjalny instalator LLVM dla Windowsa. Użyj `scripts\build_llvm_mc.ps1` albo ustaw `LLVM_MC` na `llvm-mc` z WSL (`llvm-21`).
+- **Błąd `D3D12_ROOT_SIGNATURE_DESC2` przy budowaniu runtime**: zaktualizuj Windows SDK do `10.0.26100` lub nowszego przez Visual Studio Installer albo `winget install Microsoft.WindowsSDK.10.0.26100`, usuń folder builda i skonfiguruj go ponownie.
+- **Brak miejsca na dysku `C:`**: podaj `--work "D:\leonida-work"`, aby przenieść pliki robocze na inną partycję.
+
+## Jak pomóc i uruchomić testy GPU
+
+1. Przejrzyj otwarte PR-y i [issue koordynacyjne][coord], żeby nie dublować pracy. Zarezerwuj zadanie wpisem
+ `claiming: ` albo jednym zdaniem opisu, jeśli zadanie nie ma jeszcze ID.
+2. Uruchom odpowiednie testy na syntetycznych danych wejściowych. Na przykład weryfikator manifestów testujesz
+ poleceniem `python -I tests/test_manifest_verifier.py` w głównym folderze repozytorium.
+3. W PR podaj ID zadania, opisz, co przetestowałeś, a jeśli uruchamiałeś testy GPU — podaj kartę i wersję
+ sterownika. Zaznacz, czy korzystałeś z pomocy AI. Zasady znajdziesz w [`CONTRIBUTING.md`](../../../CONTRIBUTING.md).
+
+[Przewodnik po testach GPU](../../testing.md) pokazuje, jak uruchomić testy bez plików gry.
+Wyniki testów GPU publikuj w [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166).
+
+[coord]: https://github.com/ItsNotRexed/Leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22
diff --git a/docs/i18n/zh-CN/quickstart.md b/docs/i18n/zh-CN/quickstart.md
index a62fb93bb..c316e65da 100644
--- a/docs/i18n/zh-CN/quickstart.md
+++ b/docs/i18n/zh-CN/quickstart.md
@@ -2,7 +2,7 @@
> [!NOTE]
> 英文文档([`README.md`](../../../README.md)、[`CONTRIBUTING.md`](../../../CONTRIBUTING.md) 和
-> [`docs/README.md`](../../README.md))是**权威版本**。本文只汇总稳定的安装与构建说明(与 commit `0d61c357` 同步)。
+> [`docs/README.md`](../../README.md))是**权威版本**。本文只汇总稳定的安装与构建说明(与 commit `e7584c5` 同步)。
> 项目每日进展请查看 [`README.md`](../../../README.md)。
## Leonida 是什么
@@ -67,9 +67,15 @@ python -I make_game.py --wave64-emulate auto # auto(默认)、o
- **`--wave64-emulate`**:在 32 lane 子组的 GPU(NVIDIA、Intel)上模拟 compute/mesh 的 wave64。
默认 `auto` 会询问 `vulkaninfo`,需要时自动启用。
- **`--work`**:建议指向至少有 350 GB 空闲的磁盘;`shaders` 阶段最慢,默认使用一半 CPU 线程(`--jobs` 可调)。
-- **Linux 与 Wine/Proton**:`make_game.py` 也能在 Linux 上运行。非 Windows 的 `runtime` 阶段需要传入
- `--runtime-build <目录>`(含 Windows 构建的 `gta6rt.exe` 和 `gta6rt_tls_host.dll`),脚本会生成
- `gta6rt.sh`,用 `wine`(或 `WINE` 指定的 Proton)启动。
+- **Linux 与 Wine/Proton**:`make_game.py` 也能在 Linux 上运行。`runtime` 阶段会在 Linux 上用 clang-cl 和
+ lld-link(LLVM 19+)把 loader 交叉编译到 `runtime/build/windows`,依赖 `XWIN_DIR` 或
+ `~/.local/share/xwin-sdk` 里的 MSVC CRT 和 Windows SDK
+ ([docs/testing.md](../../testing.md#the-windows-runtime-on-linux-under-wine-or-proton) 有一次性 `xwin` 命令);
+ 缺少这些时该阶段不参与默认 stages,显式请求会先列出缺什么。
+ 也可以使用别处构建好的 Windows 版本,例如 Runtime workflow 的 `runtime-windows` artifact:
+ `python3 -I make_game.py --runtime-build ~/Downloads/runtime-windows`。
+ 两种方式都会把 `gta6rt.exe` 和 `gta6rt_tls_host.dll` 复制到 `--out`,并在旁边生成 `gta6rt.sh`,
+ 用 `wine`(或 `WINE` 指定的 Proton)启动。
## 常见问题
diff --git a/docs/restofworld.md b/docs/restofworld.md
index e90fa58ec..53a45ef29 100644
--- a/docs/restofworld.md
+++ b/docs/restofworld.md
@@ -408,9 +408,51 @@ bindings are reported as unresolved.
python -I tools/meshlet_page.py --draw-system --drawable-offset
```
+**Component types (full corpus).** `tools/vertex_types.py` (at `1aef69e`, with the running-sum fix to
+`group_edges`) was run over the seven archives that hold target blocks: `data`, `packs`, `levels`, `story000`,
+`core_restofworld`, `shared_minigame000` and `story000_restofworld`. It measures a block only when the
+following meshlet group covers it densely, so it uses **60,442 blocks** (138,929,728 vertices,
+282,704,362 triangle edges) out of the 309,007 target streams; the rest are skipped as "no group" (225,795)
+or "not dense" (22,769), plus one single-stream block. The run before that fix gave the same block and vertex counts and 3,300 fewer
+edges, so none of the conclusions below depend on it.
+
+| Measure | Result |
+|---|---|
+| `+0x5C` flags word | `0x200` in all 60,442 |
+| `+0x7C` float | 4.0 in all 60,442 |
+| `+0x6C` axis word | 2: 30,017, 1: 16,718, 0: 13,707 |
+| Position header (bias, scale) finite, scale >= 0 | 60,442 / 60,442 |
+| Every triangle edge no longer than the block extent | 48,150 / 60,442 |
+
+Slot usage (block counts): slot 0 tag `0x42` in all 60,442; slot 2 `0x21` in 57,925; slot 1 `0x26` in
+57,873; slot 3 `0x28` in 49,294 and slot 4 `0x28` in 29,379; then slot 12 `0x26` (25,239), slot 6 `0x26`
+(24,876), slot 8 `0x25` (21,519), slot 13 `0x26` (17,928), slot 11 `0x27` (11,120) and 21 rarer slot/tag
+pairs, including `0x84` and `0x4b` in slot 17 (5,452 and 3,714).
+
+**Tag `0x28` is two signed 16-bit values.** Over the triangle edges of the slot 3 stream, a difference of more
+than 0x8000 between neighbouring vertices occurs 1,597,530 times when the values are read as unsigned and
+18,791 times when they are read as signed (85 times fewer); slot 4 gives 1,680,055 against 5,570. Read as
+half floats, 1,391,311 slot 3 values are NaN or infinite. So the stream is a pair of `int16`s, continuous across
+the surface, which fits the `x / 32767 * f32@0x7C` texture-coordinate reading.
+
+**Tag `0x26` (slot 1) is four bytes with an alpha-like byte 3.** Byte 3 is 255 on 62.4% of the 137.9 million
+vertices and 0 on 17.2%; each of bytes 0-2 is constant within a block in 36,544 to 38,854 blocks. The bytes
+change smoothly over edges (block-weighted median edge/random difference ratio 0.18 to 0.27), as a colour or
+blend weight would. As a packed normal it scores no better than random directions (below).
+
+**Tag `0x21` (slot 2) is still unsolved.** For each block the tool reads 256 sampled triangles and counts the
+vertices whose decoded vector is within `|cos| > 0.8` of the face normal; random directions score 0.2. Of the
+19 candidate decodings (snorm8/unorm8 xyz, snorm10/unorm10 10:10:10, six octahedral 8- and 16-bit variants,
+and each column of a quaternion tangent frame in three packings), the best block-weighted medians are unorm10 xyz at 0.479
+(per archive 0.318 to 0.667) and octahedral unorm8 bytes 0-1 at 0.331. Every other candidate is between 0.13
+and 0.31. Only 12.1% of vertices are unit length as snorm10 and 7.7% as snorm8. The stream is smooth over
+edges (block-weighted medians 0.46 to 0.71 for bytes 0-2), so it varies with the surface, but none of these
+encodings is a plain per-vertex normal.
+
Opaque: the encrypted RPF9 tables of contents, the Bink 2 bodies, the `LSNS` payloads, the bodies of the
`RSC8` headers, the nested RPF9 payloads, and the whole `appdata0` data area. Across the 971
-core graphics blocks, component types and final-slot widths remain unresolved. The stride check
+core graphics blocks, final-slot widths remain unresolved, and of the component types only `0x21`
+(see above). The stride check
also leaves 436 blocks unclassified, including 18 with a validated following meshlet group.
"Unread" in the tables above is not a claim that those bytes are empty: in
`story000_restofworld` the 9.33 MB unread gap contains nine `RSC8` headers and nested RPF9 headers, and
diff --git a/docs/shader_validation.md b/docs/shader_validation.md
index a368b6475..68936e28c 100644
--- a/docs/shader_validation.md
+++ b/docs/shader_validation.md
@@ -128,11 +128,17 @@ The scalar ALU has its own differential fuzzer (FUZZ-4), `tools/salu_diff.py`: a
SOP1/SOP2/SOPC/SOPK opcodes with SCC kept explicit, seeded programs, the translated SPIR-V run in
`tests/semantic/spirv_mini_interp.py`, and failing programs shrunk to the instructions that matter.
64-bit mask ops are left out by default (the translator models them as wave masks), and `s_bfe_*` control
-words stay inside offset + width <= 32 unless `--bfe-any`. Until SHADER-46 (#349) lands, a default run on
-main reports `s_ff0_i32_b32` with a constant source; its docstring lists the known divergences.
+words stay inside offset + width <= 32 unless `--bfe-any`. Its docstring lists the known divergences.
+
+`--branches` puts SCC into control flow, one lane: after an SCC producer comes either a chain of 1..3 consumers
+(`s_cselect_b32`, `s_addc_u32`, `s_subb_u32`) or `s_cbranch_scc0`/`scc1` forward over the next 1..3 scalar
+instructions (no loops or nesting), and half the instructions are SCC producers. The listing carries
+`; encoding:` placeholders of each instruction's size, which places the branch targets. It is a flag so that the
+default seeds keep their programs; translator oracle only.
```
python -I tools/salu_diff.py --programs 2000 --seed 1
+python -I tools/salu_diff.py --branches --programs 2000 --seed 1
python -I tests/test_salu_diff.py
```
@@ -158,12 +164,44 @@ Setup on Windows, about 800 MB and no admin rights:
`py -m venv .venv` then `.venv\Scripts\python -m pip install --index-url https://stable.repo.amd.com/rocm/whl-next/ "rocm-sdk-core==10.0.0"`;
`clang.exe` ends up in `.venv\Lib\site-packages\_rocm_sdk_core\lib\llvm\bin`. A `.venv` in the working
directory or repository is found by itself; otherwise set `LEONIDA_AMD_CLANG` to that `clang.exe`.
-- **Linux/ROCm is not supported yet:** `hw_oracle.c` is Windows-only (it loads the driver's DLL).
-- **Host C compiler.** MinGW gcc (on PATH, or `LEONIDA_HOST_CC`) builds `tools/hw_oracle/hw_oracle.c` once into the
- temp folder. By hand: `gcc -O1 tools/hw_oracle/hw_oracle.c -o hw_oracle.exe`.
+- **Linux** has a launcher of its own, without ROCm: see the next list. `hw_oracle.c` is the Windows one (it loads
+ the driver's DLL).
+- **Host C compiler.** `tools/hw_oracle/hw_oracle.c` is built once into the temp folder by MinGW gcc (on PATH or in
+ `C:\msys64`), else by MSVC: a `cl` on PATH (a Developer shell), else the Visual Studio that `vswhere` finds, through
+ its `vcvars64.bat`. The Visual Studio the runtime needs is therefore enough. `LEONIDA_HOST_CC` overrides the choice
+ (gcc or `cl.exe`). By hand: `gcc -O1 tools/hw_oracle/hw_oracle.c -o hw_oracle.exe` or `cl /O1 tools\hw_oracle\hw_oracle.c`.
- `LEONIDA_HW_ARCH` overrides the detected architecture (`amdgpu-arch`, else `gfx1150`). GFX10 spellings
(`s_load_dwordx2`, `global_store_dwordx4`) are used for `gfx10xx`, so the same kernels assemble for an RDNA2 card
- (checked by assembling for gfx1030 with clang and gfx1013 with `llvm-mc`; not run on one).
+ (checked by assembling for gfx1030 with clang and gfx1013 with `llvm-mc`, and run on gfx1036 on Linux).
+ `gfx12xx` (RDNA4) uses the GFX11 spellings. An architecture outside gfx10, gfx11 and gfx12 is `unavailable`
+ (exit 77), like a missing tool.
+
+Setup on Linux, without ROCm. `tools/hw_oracle/hw_oracle_drm.c` submits each kernel as a raw compute dispatch
+through the kernel driver (`libdrm_amdgpu`), so nothing sits between the instructions and the GPU:
+
+- **GPU.** GFX10 only, which is RDNA1 and RDNA2 (compute engine version 10); the launcher answers anything else
+ with exit 77. Name the render node, for example `LEONIDA_HW_DRM_NODE=/dev/dri/renderD129`
+ (`ls -l /dev/dri/by-path` shows which node is which PCI device). There is no default device, so a raw command
+ stream never goes to a GPU by accident.
+- **Not the GPU you are looking at.** A raw stream bypasses the Vulkan driver, and a kernel that hangs makes the
+ kernel driver reset that GPU. A node with a display connected is refused unless
+ `LEONIDA_HW_DRM_ALLOW_DISPLAY=1`. An integrated GPU next to a discrete card is the convenient case.
+- **Tools.** `clang` with the amdgcn target (the distribution's LLVM has it; `LEONIDA_AMD_CLANG` overrides), `gcc`
+ and the libdrm headers. The launcher is built once into the temp folder. By hand:
+ `gcc -O1 tools/hw_oracle/hw_oracle_drm.c -o hw_oracle_drm $(pkg-config --cflags --libs libdrm_amdgpu)`.
+- **Access.** Your user must be able to open the render node (the `render` or `video` group on most
+ distributions).
+- **The command stream** is libdrm's own compute dispatch test for GFX10 (`amdgpu_test_dispatch_memset`), with what
+ belongs to the kernel put in: its entry point, its group size, and what its kernel descriptor says.
+ - `COMPUTE_PGM_RSRC1`, `COMPUTE_PGM_RSRC2` and the wave size are read out of the descriptor in the assembled
+ object, so the `.amdhsa_*` directives take effect as they do under the HIP runtime: register counts, float
+ rounding and denormal modes, IEEE mode, DX10 clamp. A test checks that an f32 rounding mode set there changes
+ a sum on the hardware.
+ - A descriptor that asks for something the launcher does not provide (LDS, scratch memory, more than the
+ kernarg pointer in the user SGPRs) is refused instead of being run differently.
+ - Every submission gets command memory of its own. While one buffer was rewritten in place, the second kernel of
+ a process ran the first one's commands, every time; `tests/test_hw_oracle.py` runs 300 distinct kernels to
+ catch that.
How it works: each program becomes one kernel (`tools/hw_oracle/asm.py`: load the output pointer, run the program,
store `v[8:11]`), 500 kernels per code object. The code object needs an `.amdgpu_metadata` block; without it the HIP
@@ -180,6 +218,9 @@ What it can and cannot say:
find-first-zero), and programs with two different 32-bit literals in one instruction (not encodable). Renamed
opcodes (`s_andn2_*` to `s_and_not1_*`, `s_ff1_*` to `s_ctz_*`, `s_flbit_i32_b32` to `s_clz_i32_u32`, ...) are
accepted by LLVM under their old names with the same behaviour and are run.
+- Skipped on gfx12 as well: the twelve SOPK compares `s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32}`, which AMD clang
+ assembles for gfx1150 and rejects for gfx1201. They are about a third of the programs there (seed 1: 870 of 2000
+ skipped in all, 1130 run).
- Only the scalar unit is observed, on one lane with EXEC = 1; nothing about wave64 or the other stages.
Result of the first runs (Radeon 880M, driver 26.11.2, AMD clang 23.0.0git): about 40,000 seeded programs
@@ -190,7 +231,24 @@ the hardware stops the field at bit 31 (`width = min(width, 32 - offset)`) and s
control words, including bits 23 to 31 of the control word (ignored), fit that rule exactly. The translator already
did this (0 of 600 differ), so the reference was the one that was wrong, and it now follows the measured rule. The
rule rests on that gfx1150 measurement (4000 control words). LLVM's `constantFoldBFE` does the same for the VOP3
-`v_bfe` nodes, but with a 5-bit width, so it is only analogous; RDNA2 is unmeasured.
+`v_bfe` nodes, but with a 5-bit width, so it is only analogous.
+
+Result on RDNA2 (the integrated GPU of a Ryzen 9 7950X3D, Raphael, gfx1036; the Linux launcher, Linux 7.3.5,
+libdrm 2.4.134, clang 23.1.5 from the distribution): 70,000 seeded programs, 0 mismatches.
+
+| Run | Programs | Match | Mismatch | Skipped (two literals) |
+|---|---|---|---|---|
+| seeds 1 to 8 | 40,000 | 39,439 | 0 | 561 |
+| seeds 1 to 4, `--bfe-any` | 20,000 | 19,727 | 0 | 273 |
+| seeds 1 and 2, `--inline64` | 10,000 | 9,855 | 0 | 145 |
+
+So the reference, the `s_bfe_i32` rule above included, holds on RDNA2 as measured, and GFX10's `s_ff0_i32_b32` and
+`s_ff0_i32_b64`, which gfx1150 cannot run, are covered. As a control, a reference whose `s_min_i32` sets SCC for
+equal operands too (`<=` for `<`) gave 2 mismatches in 5,000 programs, minimized to that instruction.
+
+RDNA4 (Radeon RX 9070, gfx1201, driver 26.11.2, `rocm-sdk-core` 10.0.0 clang): 10,000 programs (seeds 1, 2, 3 and
+500, 2000 each, and seed 500 with `--bfe-any`) gave 0 mismatches, so gfx1201 follows the same `s_bfe` rule. With
+`--oracle translator,hw`, 200 of 200 programs matched (seed 1).
Two assembler facts matter when writing edge cases:
@@ -336,7 +394,8 @@ python -m pytest tests/test_image_fuzz.py
```
Covered: 2D `image_load`, `R8G8B8A8_UNORM`, `R16G16B16A16_SFLOAT`, `R32G32B32A32_SFLOAT`, `R32_SFLOAT`,
-and `R8G8B8A8_UINT`/`SINT` storage images. The shader converts the loaded 8-bit integer values to float for
+and `R8G8B8A8_UINT`/`SINT`, all as sampled images, as the runtime binds a read-only texture (integer formats are
+read through the translator's uint/sint aliases of the sampled array). The shader converts the loaded 8-bit integer values to float for
readback; every such value is exactly representable, including signed negatives. Wider integers are not covered.
Texture sizes divide the 64x64 draw (8/16/32/64), so every texel is read at least once. The nonzero masks cycle from
`0xf` through `0x1`–`0xe`; 90 programs cover all 15 masks for each of the six default formats. Selected channels
@@ -345,10 +404,11 @@ The packing model follows the image VGPR usage description in AMD's
[RDNA 1.0 ISA guide](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna-shader-instruction-set-architecture.pdf);
the Vulkan test compares translated shaders on the host GPU, not native RDNA2 execution.
-Devices: the harness needs `fragmentStoresAndAtomics` and both without-format storage-image features, because the
-translated `image_load` declares the uint/sint storage path even when the case reads a float format (the choice is
-made from the T# FORMAT at run time). An Intel UHD 770 (Xe-LP) lacks `shaderStorageImageReadWithoutFormat` and
-skips every case; the harness names the missing feature. Not covered yet: wider UINT/SINT formats, mips, 1D/2D-array/3D/cube,
+Devices: the harness needs `fragmentStoresAndAtomics`, and no without-format storage-image feature: a translated
+`image_load` fetches every format from the sampled arrays, UINT/SINT ones through integer aliases (SHADER-151, the
+"Typed image loads" row of `docs/design.md`). Until then it declared the uint/sint storage path even when the case
+read a float format, so an Intel UHD 770 (Xe-LP), which lacks `shaderStorageImageReadWithoutFormat`, skipped every
+case. Not covered yet: wider UINT/SINT formats, mips, 1D/2D-array/3D/cube,
`image_sample`/`gather` with filters and borders, and texel offsets with `VK_KHR_maintenance8`.
### 16-bit and memory ops on the GPU (`tools/valu_fuzz.py`, FUZZ-2, FUZZ-5)
@@ -432,8 +492,13 @@ every scalar. `vk_compute_test` reads them back with `VKC_OUT_WORDS` / `VKC_DUMP
only on both (the generator never uses the `_e64` form, whose GFX10 SDST the assembler no longer takes either);
`v_mbcnt_*` is VOP3-only on both; `s_ff1_i32_*` is the GFX10 name of GFX11's `s_ctz_i32_*` (an accepted alias);
`v_readlane_b32` with a lane select of 32 and up in wave32 uses select bits [4:0] on gfx1150 too. Nothing
- needed a skip, so `hw_skip_reason` returns none and the only skips are assembler rejections (none seen). It is
- still gfx1150, not RDNA2.
+ needed a skip, so `hw_skip_reason` returns none and the only skips are assembler rejections (none seen). That
+ was gfx1150.
+ On RDNA2 (gfx1036, through the Linux launcher of the FUZZ-4 section): 24,000 programs (seeds 1 to 6) match in
+ both wave sizes, 12,000 each, 6,586 of them `hyp_permlane`; with `--dpp` (seeds 1 and 2) 8,000 more match,
+ 972 of them `hyp_dpp`. As a control, `--permlane-fetch-inactive` there mismatches in 239 of 1,000 programs. A
+ GFX10 assembler has no `global_store_b32`, so `asm.raw_kernel_text` puts the GFX10 name (`global_store_dword`)
+ back for `gfx10xx`; nothing else the generator emits needed a change.
First results (Radeon 880M, driver 26.11.2): 24,000 programs on the hardware, half wave32 and half native
wave64, seeds 11 to 16 (4,000 programs each), with and without `--dpp`, 12 to 60 ops, with and without
`--no-maskdata` and `--no-hw-guard`: match 24,000, mismatch 0, hyp_only 0, rejected 0. 7,652 of them contained
@@ -458,6 +523,188 @@ First results on an RTX 4090 (subgroup 32, driver 621.14):
- **Everything else matches.** On `main`, 1,000 programs (`--seed 8 --ops 28 --no-maskdata --no-w32-hi-lanes`, 500 wave32 native and 500 wave64 emulated) give 0 mismatches. 297 of them are `hyp_only` (permlane with FI = 0 and an inactive source), and with `--permlane-fetch-inactive` all 1,000 match. Native wave64 on the 32-wide card mismatches as documented: `s_bcnt1` of EXEC counts one half, and a `v_readlane` from the other half wraps.
- **Closed question (#374):** what hardware does for permlane with FI = 0 was measured on RDNA2 and RDNA3.5 (see above).
+### 32-bit float VALU on the GPU (`tools/f32_fuzz.py`, FUZZ-3)
+
+`--oracle hw` (or `translator,hw`) runs the same seeded VOP1/VOP2/VOP3 f32 programs natively on the AMD GPU and judges
+the hardware's `v8` and VCC against `F32Model` bit for bit (NaN matches any NaN; an f16 NaN in a `v_cvt_f16_f32` /
+`v_cvt_pkrtz_f16_f32` half too). Setup is the one in "Hardware oracle" above; without it the run prints
+`hardware oracle unavailable: ...` and exits 77. It tests the **model**, on wave32 with one lane; with `translator,hw`
+a hardware mismatch also prints what the translated SPIR-V did.
+
+```
+python -I tools/f32_fuzz.py --oracle hw --programs 5000 --seed 1 # table + informational hardware tables
+python -I tools/f32_fuzz.py --oracle hw --negative-control # wrong models must be caught
+python -I tools/f32_fuzz.py --oracle hw --perturb mul_rtz --programs 500 # one wrong model, mismatches must appear
+```
+
+- **Float MODE.** An assembled kernel's descriptor starts with IEEE 1, DX10_CLAMP 1, f32 denormals flushed
+ (`.amdhsa_float_denorm_mode_32 0`), f16/f64 denormals kept (3), round to nearest (MODE `0x3c0`, read back with
+ `s_getreg_b32`). The primary mode, `flush`, is the state inferred for the game's shaders (IEEE off, f32 denormals
+ flushed, DX10_CLAMP on: MODE `0x1c0`). Three more are run for what the model does not judge: `keep` (f32 denormals
+ kept, `0x1f0`), `no_dx10` (`0x0c0`), `ieee` (`0x3c0`). The run reads MODE back in a kernel for each and fails if a
+ directive did not take. Rounding is always to nearest even.
+- **GFX11 against GFX10, handled explicitly** (`tools/hw_oracle/asm.py`, checked by assembling every opcode for gfx1013,
+ gfx1010, gfx1030, gfx1100, gfx1150 and gfx1200):
+ - *Skipped, never substituted:* `v_mad_f32`, `v_mac_f32`, `v_madak_f32` and `v_mad_legacy_f32` exist on GFX10.1 only
+ (gfx1010/1011/1013, the console's family); gfx1030 and every GFX11 part reject them. The fused replacements
+ (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fma_dx9_zero_f32`) round once, so they are different instructions. The
+ unfused mad semantics (and SHADER-118's flush) therefore stay unmeasured: no RDNA2 desktop part and no GFX11 part has
+ them. Also not generated: `v_madmk_f32` (GFX10.1 only, like the mad opcodes), `v_min_legacy_f32` (in no GFX10 or GFX11
+ part: llvm-mc rejects it for gfx1010, gfx1013, gfx1030 and gfx1150), `v_fma_legacy_f32`/`v_fmac_legacy_f32` (new in
+ GFX10.3, not in gfx1013).
+ - *Renamed, run:* `v_mul_legacy_f32` is `v_mul_dx9_zero_f32` in GFX11 (the DX9 rule `0 * x = 0`, inf and NaN included,
+ held in every program) and `v_cvt_pkrtz_f16_f32` is `v_cvt_pk_rtz_f16_f32`; the assembler takes the old spelling.
+ - *Same, with a syntax change:* GFX11's assembler wants `clamp` before `mul:N`/`div:2`; the native kernels print them in
+ that order (the same bits). Opcode numbers differ between the families (`v_cmp_class_f32_e32` is `7d10` on gfx1013 and
+ `7cfc` on gfx1150); only mnemonics are shared. omod and clamp exist in VOP3 on both; no op_sel is used for f32.
+ The transcendental unit is separate on GFX11, so a `s_nop 7` follows the instruction in the native kernel
+ (`--no-hw-guard` leaves it out).
+ - *Not covered:* wave64 (the f32 ALU does not depend on it), `v_fma_mix*`, f16 and f64 arithmetic.
+- **Programs.** The seeded random ones, plus `--probes N` (default 12) per op and kind: denormal operand, denormal
+ result, NaN payloads, clamp of NaN/-0, invalid operations (inf - inf, 0 * inf, ...), and `cancel` (`z = -round(x * y)`,
+ which separates fused from unfused). `v_min/max/min3/max3/med3_f32` are in the table for the hardware only, with the
+ RDNA2 rules measured in #634.
+- **Judged / not judged.** A program is *match* or *mismatch* where the model has an answer. Where it declines (denormal
+ operand or result, clamp of NaN or -0, cube of NaN) the hardware still runs and is recorded in the informational tables,
+ also under the other three modes. A *known deviation* is hardware behaviour already analysed and written down as a model
+ alternative (`KNOWN_DEVIATIONS`); the hardware words must equal the alternative exactly, anything else is a mismatch.
+
+Results (Radeon 880M, gfx1150, driver 26.11.2, AMD clang 23.0.0git), seeds 1 to 6, 5,000 random programs + 24 probes per
+op and kind each, 46,967 programs in all: **30,577 match, 0 mismatch, 57 known deviation**, 5,417 skipped for GFX11,
+5,903 denormal, 5,013 other not judged (clamp of NaN or -0, cube of NaN). "Match" accepts any NaN for any NaN: payload, sign and quiet bit are in the informational tables, not judged. Seed 1 by family:
+
+| Family | Programs | Match | Mismatch | Known dev | GFX11 skip | Denormal | Other |
+|---|---|---|---|---|---|---|---|
+| add / sub / mul | 921 | 631 | 0 | 0 | 0 | 176 | 114 |
+| DX9 legacy mul / mad | 453 | 133 | 0 | 0 | 239 | 51 | 30 |
+| mad / mac / madak | 698 | 0 | 0 | 0 | 698 | 0 | 0 |
+| fma / fmac / fmaak | 700 | 509 | 0 | 0 | 0 | 132 | 59 |
+| int to f32 convert | 708 | 708 | 0 | 0 | 0 | 0 | 0 |
+| f16 convert | 478 | 383 | 0 | 0 | 0 | 90 | 5 |
+| `v_cvt_pk_u8_f32` | 183 | 130 | 0 | 0 | 0 | 53 | 0 |
+| floor / ceil / trunc / rndne | 795 | 582 | 0 | 5 | 0 | 96 | 112 |
+| rcp / rsq / sqrt / exp / log | 956 | 704 | 0 | 0 | 0 | 119 | 133 |
+| cube | 786 | 435 | 0 | 1 | 0 | 104 | 246 |
+| `v_cmp_class_f32` | 171 | 147 | 0 | 0 | 0 | 24 | 0 |
+| min / max / med3 (hardware only) | 989 | 732 | 0 | 1 | 0 | 128 | 128 |
+
+Negative control: `--negative-control` re-judges the same hardware words with a deliberately wrong model for six ops
+(`v_add_f32` low bit flipped, `v_mul_f32` rounding toward zero, `v_fma_f32` unfused, `v_mul_legacy_f32` as IEEE multiply,
+`v_rndne_f32` as floor, `v_min_f32` NaN rule changed); every one produced mismatches (1 to 112 per run; the `v_fma_f32` one only after the `cancel` probes were added, a plain random sweep missed it in seed 2;
+the legacy multiply is the weakest, 1 to 4 in seeds 1 to 6, because `0 * inf` is rare in random programs; the `zero_inf` probes (a zero against inf, NaN or a normal number, DX9 multiply) were added afterwards and catch it at small sizes). The `cancel` probes (seeds 2, 7, 8) give 72 of 72 fused-FMA matches. Seeds 1 to 6 ran without them.
+
+On RDNA2 (gfx1036, through the Linux launcher of the FUZZ-4 section, the same seeds 1 to 6): 38,858 programs,
+**28,671 match, 0 mismatch, 56 known deviation**, 4,224 skipped (the four mad opcodes are GFX10.1-only), 3,097
+denormal, 2,810 other not judged. The four MODE settings read back in the kernels as `0x1c0`, `0x1f0`, `0xc0` and
+`0x3c0`, so the float mode of the kernel descriptor reaches the hardware through that launcher as well.
+`--negative-control` catches all six wrong models there (3 to 25 mismatches each).
+
+What the hardware answered where the model does not judge (gfx1150; the RDNA2 run above agrees where it is cited):
+
+- **No model error found.** The model was right wherever it had an answer, in 30,577 programs; the min/max/med3
+ rules measured on RDNA2 in #634 (one NaN gives the other operand, both NaN give src0, -0 < +0, med3 with a NaN is min3)
+ also hold on gfx1150 for quiet and signalling NaNs with IEEE off.
+- **On gfx1150 output modifiers turn a -0 result into +0** (`mul:2`, `mul:4`, `div:2`; 57 programs, every seed; a flushed
+ denormal result, which is a -0, too). RDNA2 does the same: 56 programs in the same seeds on gfx1036. LLVM notes that omod mishandles signed zeros
+ (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier, which points the same way. The
+ model and the translator both keep -0, so on that evidence the translator likely differs from the hardware
+ (`translator,hw`: all 6 deviations of 2,000 programs are "matches the model, so it shares the model's answer"). Not
+ fixed in this change; the finding is posted in the coordination issue (see #1006). A deviation is only accepted where
+ the omod was active (not with IEEE on, not for ALU ops with f32 denormals kept).
+- **omod only acts with MODE.IEEE = 0**, and for the ALU ops only with f32 denormals flushed: with `keep` the omod of
+ add/mul/fma/min/max/cvt/rounding ops is ignored; the transcendental ops and the cube ops still apply it. LLVM says the
+ same for both conditions (`SIFoldOperands.cpp`: "omod is ignored by hardware if IEEE bit is enabled"; "If output
+ denormals are enabled, omod is ignored"). This supports
+ the corpus inference (omod on 102,365 float instructions, so IEEE off and f32 denormals flushed in the game's shaders).
+- **f32 denormals (SHADER-35's MODE question).** With `denorm_mode_32 = 0` a denormal operand is read as a zero of its sign
+ and a denormal result is written as a zero of its sign, for add/sub/mul/fma/fmac/fmaak, min/max/med3, rounding ops and
+ DX9 mul; with `3` they are exact. `v_rcp/rsq/sqrt/exp/log_f32` flush in both modes (as #634 measured on RDNA2).
+ `v_cmp_class_f32` classifies a denormal as a denormal in both. `v_cubesc/cubetc` pass a denormal operand through.
+- **clamp.** With DX10_CLAMP 1, clamp of a NaN gives +0; with 0 the NaN passes through. clamp of -0 gives +0 in every mode.
+ The model still declines both.
+- **NaN payloads.** With IEEE off a signalling NaN passes through add/mul/fma/rounding/transcendental ops unchanged
+ (payload and sign); with IEEE on it is quieted (bit 22 set). With several NaN operands the first (lowest source) wins
+ in add/mul/fma/fmaak/fmac; for min/max the rule above applies. `v_sub_f32` returns the NaN of src1 with its sign flipped
+ (it computes src0 + -src1). Invalid operations (inf - inf, 0 * inf, sqrt/rsq/log of a negative) give `0xffc00000` in every
+ mode and op, never `0x7fc00000`. `v_cvt_f16_f32` and `v_cvt_pkrtz_f16_f32` turn a NaN into an f16 NaN with the top 10
+ payload bits and the quiet bit set (not the canonical `0x7e00` the model writes; payload not judged, quietness is).
+ `v_cvt_f32_f16` keeps the f16 payload shifted left by 13 and does not quiet it (the model agrees).
+
+
+### f16 transcendentals on the hardware (`tools/f16_trans_sweep.py`, FUZZ-29)
+
+The `16-bit results` row of `docs/design.md` listed `v_exp_f16`/`v_log_f16` and the NaN and denormal operands as
+unverified. f16 has only 65,536 bit patterns, so instead of sampling, this tool runs every one of them through
+`v_exp_f16`, `v_log_f16`, `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16` and `v_cos_f16` on the hardware
+oracle (setup above; exit 77 without it). Each op is 8 raw kernels of 1,024 threads. Each thread computes 8 inputs
+and stores them packed two to a dword, which is 4,096 words per kernel, the launcher's limit. The op runs in wave32
+and wave64 and under five MODEs, and MODE is read back with `s_getreg_b32` first:
+
+| Mode | IEEE | f16 denormals | f16 rounding |
+|---|---|---|---|
+| `keep16` | 0 | kept (3) | nearest |
+| `flush16` | 0 | flushed (0) | nearest |
+| `ieee_keep16` | 1 | kept | nearest |
+| `ieee_flush16` | 1 | flushed | nearest |
+| `keep16_rtz` | 0 | kept | toward zero |
+
+All modes have DX10_CLAMP 1 and f32 denormals flushed.
+
+```
+python -I tools/f16_trans_sweep.py # all ops and modes, about 5 minutes
+python -I tools/f16_trans_sweep.py --ops v_exp_f16 --modes keep16 --json out.json
+python -I tools/f16_trans_sweep.py --self-test # the reference, no GPU
+```
+
+The reference is the exact result correctly rounded to f16, computed with `decimal` at 60 digits: for sin/cos that is
+sin/cos(2πx), reduced in turns. That reference is the translator's rule (widen, the GLSL.std.450 function in f32,
+round to nearest even) with an exact f32 function, the best a driver can do. Inputs where the translated SPIR-V is
+undefined are tabulated, not judged. For each mode the tool counts:
+- bit-exact results, 1 ulp and more than 1 ulp;
+- denormal operands that give the hardware's own word for a zero of the same sign, and denormal results written as zero;
+- NaN results, with signalling NaNs kept, quieted or changed.
+
+It also counts the inputs on which each mode differs from `keep16`, and lists the word for 23 special inputs. For
+sin/cos a second table compares the hardware with Sin/Cos of the f32 product 6.2831855 · x, by |x| band.
+
+Result on an RX 6700 XT (gfx1031, Navi 22; the Linux launcher from #1265, Linux 7.3.5, amdgpu, clang 23.1.5).
+wave32 and wave64 gave the same word for every input of every op in every mode. There was no GPU fault, timeout or
+reset in the kernel log.
+
+| Op (`keep16`) | Inputs that are not NaN | Bit-exact | 1 ulp | Undefined in SPIR-V |
+|---|---|---|---|---|
+| `v_exp_f16` | 63,490 | 63,490 | 0 | 0 |
+| `v_log_f16` | 63,490 | 31,744 | 0 | 31,746 (≤ 0) |
+| `v_rcp_f16` | 63,490 | 63,488 | 0 | 2 (±0) |
+| `v_rsq_f16` | 63,490 | 31,744 | 0 | 31,746 (≤ 0) |
+| `v_sqrt_f16` | 63,490 | 31,746 | 0 | 31,744 (< 0, -0 excluded) |
+| `v_sin_f16` | 63,490 | 63,474 | 14 | 2 (±inf) |
+| `v_cos_f16` | 63,490 | 63,484 | 4 | 2 (±inf) |
+
+- **Correctly rounded.** The five non-trigonometric ops never differ from the correctly rounded result. sin/cos differ
+ by 1 ulp on 14 and 4 inputs, all with |x| ≤ 1. For |x| > 1 every result is bit-exact, up to 65,504 turns: the f16
+ ops have no ±256 domain limit.
+- **The f32 product loses the turn.** Against Sin/Cos(f32 6.2831855 · x), which is what the translator computes before
+ #594 is fixed, 16,366 sin and 2,036 cos inputs are more than 1 ulp off, up to 9,944 ulp. Nearly all of them have
+ |x| > 1 (sin: 1,010 inputs at 1 < |x| ≤ 256 and 15,354 above 256). Reducing in turns first, as #1283 and #616
+ propose, is what the hardware does; for f16 the reduction must not stop at ±256.
+- **f16 denormals follow `denorm_mode_16_64`, for operands and results alike.** With 0, a denormal operand gives the
+ word of a zero of its sign (`v_log_f16` -inf, `v_rcp_f16` and `v_rsq_f16` ±inf, `v_sqrt_f16` and `v_sin_f16` ±0).
+ Denormal results become ±0 (831 for `v_exp_f16`, 4,094 for `v_rcp_f16`). With 3, both are kept. The f32
+ transcendentals behave differently: they flush in both modes.
+- **The f16 field of FP_ROUND is ignored.** Under round toward zero every op gives the same word as under round to
+ nearest, on all 65,536 inputs.
+- **IEEE only changes signalling NaNs.** With IEEE 0, all 1,022 f16 signalling NaNs pass through unchanged. With IEEE 1
+ they are quieted (bit 9 set) with payload and sign kept. Quiet NaNs pass through unchanged in every mode. This is the
+ f32 behaviour of the previous section.
+- **Undefined in SPIR-V, defined on the hardware.** log(±0) = -inf; rcp(±0) = ±inf; rsq(+0) = +inf; rsq(-0) = -inf;
+ sqrt(-0) = -0. log, rsq and sqrt of a negative (-inf included), and sin/cos(±inf), give `0xfe00`, the negative quiet
+ NaN (`0xffc00000` in f32).
+- **Controls.** `keep16_rtz` also judges against a round-toward-zero reference, so it shows what a wrong rounding
+ model produces: about half the results 1 ulp off. The kernel layout is checked without a GPU: each of the 65,536
+ inputs is computed once and stored in its own half (`tests/test_f16_trans_sweep.py`). On a GPU the test checks
+ exp2 of integers and wave32 = wave64.
+
## Coverage plan and cost
Start with straight-line scalar/vector ALU because it is deterministic, needs no descriptors and
diff --git a/docs/testing.md b/docs/testing.md
index fa79d9b15..92e815705 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -55,6 +55,12 @@ cmake --build runtime/build/linux --parallel
On macOS, add `-DVulkan_INCLUDE_DIR=/opt/homebrew/include` to the first command.
+The test programs and `scripts/run_gpu_tests.py` should come from the same commit. Some checks tolerate an older
+binary (`unpinned_subgroup_skip`), but mixing them can report false failures in the compute tests: 28 `cs_*`
+failures on both an RTX 5070 Ti Laptop and a Radeon 610M with the `426023a` script and `48ad23f` binaries, where
+either matching pair is clean. If you cannot build locally, the `runtime-windows` artifact of the Runtime workflow
+belongs to the commit that built it; check that commit out as well.
+
## Run them
The whole suite, assembled, translated and run in one go:
@@ -90,7 +96,8 @@ WINEPREFIX="$HOME/.local/share/leonida-wine" ctest --test-dir runtime/build/wind
```
The build type defaults to `RelWithDebInfo`: xwin leaves out the debug CRT, so `Debug` needs `--include-debug-libs`.
-`make_game.py --runtime-build runtime/build/windows` takes this folder like a Windows build. CMake packages are
+`make_game.py`'s `runtime` stage makes this same build on Linux when the tools and the SDK are there (`--runtime-build
+runtime/build/windows` takes a folder made by hand like a Windows build). CMake packages are
looked up only inside the SDK folder, so a Windows SDL3 for the GameInput shim is passed as `-DSDL3_DIR=` (`CMAKE_PREFIX_PATH` is not searched here).
@@ -148,8 +155,7 @@ differences.
`ps_bary`, `ps_uniform_branch` and `ps_scc_mask32` read raw barycentrics, which need
`VK_KHR_fragment_shader_barycentric`; so do `ps_interp_f16_high` and `ms_f16_pack` (16-bit interpolants are
-`PerVertexKHR` inputs, and `--bary-fallback` cannot express them, so they skip under it). Where the device lacks it they're skipped; that's expected, not a failure. To
-`VK_KHR_fragment_shader_barycentric`. NVIDIA has it from Turing on; Volta (V100, Titan V) and older lack it, as do
+`PerVertexKHR` inputs, and `--bary-fallback` cannot express them, so they skip under it). NVIDIA has it from Turing on; Volta (V100, Titan V) and older lack it, as do
llvmpipe and some other drivers. Where the device lacks it they're skipped; that's expected, not a failure. To
test the fallback that runs them anyway, set `LEONIDA_BARY_FALLBACK=1`, **for both `build.py` and `check.py`** (or
for `run_gpu_tests.py`). The shaders are then translated with `--bary-fallback` and drawn through a pass-through
diff --git a/docs/textures.md b/docs/textures.md
index 2ce0ea6c1..129bf51ed 100644
--- a/docs/textures.md
+++ b/docs/textures.md
@@ -28,8 +28,10 @@ for all six active modes (BC1, BC3, BC4, BC5, BC6H and BC7 — 100% of BCPack co
corpus). Strict confirmed-history mode is the default; `--allow-provisional` enables the
provisional and last-resort history entries, and `--history ` supplies locally
calibrated BC6H/BC7 initial history JSON tables at run time (no fitted BC6H/BC7 history
-data is embedded in the repository). `rpf9dump`'s C# `TtpfReader` still uses the baseline
-zlib/raw path until ported.
+data is embedded in the repository). `rpf9dump`'s C# `TtpfReader` (submodule pin `e293917`,
+`breadbbbb/rpf9-explorer#7`) now decodes compact 2D mip tails, multi-slice layouts, DXGI 11,
+and BCPack BC1, BC3, BC4 and BC5 chunks in strict mode; BC6H, BC7 and provisional-history
+chunks remain skipped by `rpf9dump` and can be completed by `tools/ttpf_assets.py`.
The compact layout rule moves 206,661 2D textures into complete exports and 1,218 more into
partial exports (`305,264` complete, `16,419` partial, `35,432` skipped under zlib/raw).
@@ -861,11 +863,12 @@ via `bcpack.decode_with_info`).
## Next step
-1. **Port the BCPack decoder to `TtpfReader` (`rpf9-explorer` / `tools/rpf9dump`; ASSET-44).**
- The compact layout rule and multi-slice layouts are already upstream in `rpf9-explorer`
- (carried by the `917e9b9` submodule pin); what remains is wiring BCPack behind
- `TtpfReader.DecodeChunk`. Keep the lower-mip zlib/raw fallback for any chunk refused in
- strict mode.
+1. **Port BC6H/BC7 BCPack decoders to `TtpfReader` (`rpf9-explorer` / `tools/rpf9dump`).**
+ Compact 2D mip tails, multi-slice layouts, DXGI 11, and strict BCPack BC1/BC3/BC4/BC5
+ decoding are now live in `rpf9-explorer` (carried by the `e293917` submodule pin,
+ `breadbbbb/rpf9-explorer#7`; `ASSET-44`). Remaining C# follow-ups are BC6H/BC7 block
+ rebuilders (plus optional external history tables) and preserving lower-mip zlib/raw
+ fallback when a higher mip is refused in strict mode.
2. **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.
diff --git a/docs/textures_arrays.md b/docs/textures_arrays.md
index 48a7cac11..400f30f57 100644
--- a/docs/textures_arrays.md
+++ b/docs/textures_arrays.md
@@ -217,8 +217,8 @@ With 2D compact layouts plus 2D arrays, cubemaps, and 3D volumes enabled in
`tools/ttpf_mips.py` exports DX10 DDS for 2D arrays (`Texture2DArray`), cubemaps
(`TextureCube`), and validated float16 3D volumes (`Texture3D`). Upstream C# `TtpfReader` parity
-has landed in `breadbbbb/rpf9-explorer` PRs #5 and #6 and is carried by the `917e9b9` submodule
-pin.
+has landed in `breadbbbb/rpf9-explorer` PRs #5, #6, and #7 (compact layouts, multi-slice shapes,
+and BCPack BC1/BC3/BC4/BC5) and is carried by the `e293917` submodule pin.
## Reproduce
diff --git a/docs/world.md b/docs/world.md
index c206eae0b..954c4aba8 100644
--- a/docs/world.md
+++ b/docs/world.md
@@ -298,6 +298,27 @@ Hash-only or opaque:
this package are the loose RDS5 pools under `data/ttdb` plus `textures.rpf`, so placement records do not
carry texture names, only material/asset keys in the model resources.
+## Location, interior, river and road names (`GameShape__Data__LocationNameLoopkup`)
+
+The place names shown to the player come from one `GameShape__Data__LocationNameLoopkup` XML document in
+`common.rpf` (the root name keeps its `Loopkup` spelling). Counts only; no names or keys.
+
+| Section | Items | Content |
+|---|---:|---|
+| `LocationNames/Item key=...` | 2,318 | `Name` (empty in 382); 46 items also name a `TextureDictionary` (2 distinct) and a `Texture` (46 distinct) |
+| `InteriorNames/Item key=...` | 1,358 | 2,280 inner `Item`s, each `Name` (empty in 434) and `Pos` (`x y z`); 1 position in 1,192 interiors, 2 or more in the other 166 |
+| `RiverNames/Item key=...` | 66 | the name as item text |
+| `RoadNames/Item key=...` | 409 | `Name` |
+
+- Keys are plain text, distinct within each section, and no key is shared between the location, river and road
+ sections.
+- **All 2,280 interior positions lie inside the world rectangle** shared by the `PAMH` heightmap and the region
+ tint map (x -13,312..5,120, y -9,728..11,264); none is at the origin. Heights run from -78 to 821 (median 5).
+- None of the keys is an archive entry name or the joaat of a model archetype name in the local catalog, the two
+ texture-dictionary names match archive entries but not `.ytd` ones, so the keys are their own namespace (probably shape
+ or zone ids resolved elsewhere at runtime; not measured). The 46 textures match no texture-dictionary item
+ in the catalog either.
+
## What a runtime needs
1. **RPF9 page reader.** Read the `9FPR` header; the data area starts at the u32 at +0x04. Streams start on a
@@ -380,7 +401,8 @@ reported with fewer entities or as `meta` rather than guessed.
## Building a placed world
`tools/world_build.py --placements` builds the viewer's chunks from map placements instead of each model's own
-coordinates. It covers points 3 and 4 of *What a runtime needs*; point 5 (HD/LOD switching) is not done.
+coordinates. It covers points 3 and 4 of *What a runtime needs*, and approximates point 5 with `--lod-sets`
+(below).
1. `world_index.py --entities-out \world\entities.jsonl` writes one row per complete entity.
2. rpf9dump exports the models (`models/manifest.json` + OBJ).
@@ -389,45 +411,130 @@ coordinates. It covers points 3 and 4 of *What a runtime needs*; point 5 (HD/LOD
entity row carries the +0x20 key, the model's Murmur3-64 must equal it, as in `world_names.py`; a 32-bit-only
match is a `key_mismatch` and is not placed. The model is scaled by (`scaleXY`, `scaleXY`, `scaleZ`), rotated
by the **conjugate** of the stored quaternion, translated to `position`, and converted from RAGE Z-up to
- glTF Y-up `(x, z, -y)`. Normals use the inverse-transpose; a negative scale product flips the winding.
+ glTF Y-up `(x, z, -y)`.
`--lod-levels` picks the `lodLevel` values to place (default `0,5`: HD and ORPHAN_HD) and `--region
MINX,MINY,MAXX,MAXY` bounds the RAGE world X/Y. `world.json` then has `"layout": "placements"` and a
`stats.placements` block: `rows`, `malformed`, `other_lod_level`, `outside_region`, `selected`, `placed`,
`placed_unverified` (no key in the row), `key_mismatch`, `unresolved_archetype` (no exported model has that name),
-`model_not_loadable` and `distinct_models`.
+`model_not_loadable`, `degenerate_scale`, `mirrored` and `distinct_models`.
-Measured on the 1.0.2.1 package:
+### Shared geometry (`--instancing`)
+
+A city has 1.55 M HD placements of about 120 k models, and most models are placed many times. By default
+(`--instancing gpu`) each model's OBJ is parsed once into a packed cache file, each chunk stores every model it uses
+once, and the placements in the chunk are instance transforms (`EXT_mesh_gpu_instancing`: one node per model with
+`TRANSLATION`/`ROTATION`/`SCALE` accessors; listed in `extensionsRequired`). three.js's `GLTFLoader`, which the
+viewer uses, turns each such node into `InstancedMesh`es. `--instancing nodes` writes one plain glTF node per
+placement instead, for loaders without the extension (a draw call per placement). `--instancing bake` keeps the
+first version's output, where every placement is a transformed copy of the geometry.
+
+Each chunk is written as soon as it is built, so memory holds about 100 bytes per placement plus the models of
+the chunks being written, not the whole map. `--jobs N` packs models and writes chunks in N processes.
+
+Every instance transform has a positive determinant, so the winding is right in any loader:
+- the TRS is the baked transform split into node form (checked against it on random rotations and scales);
+- a negative `scaleXY` is a 180° turn about the model's Z axis and is folded into the rotation;
+- a negative `scaleZ` mirrors. Those placements draw a mirrored copy of the mesh (glTF Y negated, winding
+ reversed) with a positive scale, counted as `mirrored`;
+- a zero scale cannot be inverted for normals; those rows are counted as `degenerate_scale` and not placed.
+
+Chunk records add `distinct_models` (meshes stored) and `stored_triangles`; `triangles` stays the drawn count
+(each mesh's triangles times its placements). `world.json` adds `instancing`, `stats.stored_triangles`,
+`stats.chunk_bytes` and `stats.max_chunk_bytes`.
+
+### LOD sets (`--lod-sets`)
+
+`--lod-sets` places every `lodLevel` (unless `--lod-levels` narrows it) and builds one chunk set per tier, ids
+`c___` with tiers `hd`, `lod`, `slod1`, `slod2`, `slod3`, `slod4` and `orphan_hd`. Each chunk record
+names its `lod` tier and its grid `cell` (`[minx, minz, maxx, maxz]`, glTF metres). `world.json` gets
+`lod_bands`: for each tier, the camera distance band in which it is drawn, from the selected entities:
+
+- a tier starts at its own median `childLodDist` (the distance inside which a parent hands over to its children);
+ HD starts at 0;
+- it ends where the next coarser tier present starts; the coarsest tier ends at its median `lodDist`;
+- ORPHAN_HD has no parent and runs from 0 to its median `lodDist`.
+
+`stats.lod_tiers` records the medians and each tier's chunk and placement counts. The viewer loads a tiered chunk
+while the horizontal distance from the camera to its cell is inside the band, and keeps it up to 32 m past the
+band, so each cell shows one tier. Worlds without `lod_bands` stream as before.
+
+Tier medians over all 1,670,435 entities (`lodDist` ≤ 0 means "use the archetype's default" and is left out):
+
+| Tier | Entities | Median `childLodDist` | Median `lodDist` | Band |
+|---|---:|---:|---:|---|
+| HD | 1,153,122 | — | 124 (97,625 set) | 0–130 |
+| LOD | 100,953 | 130 | 450 | 130–450 |
+| SLOD1 | 16,828 | 450 | 1,000 | 450–1,000 |
+| SLOD2 | 1,708 | 1,000 | 2,000 | 1,000–1,976 |
+| SLOD3 | 601 | 1,976 | 4,000 | 1,976–6,043.5 |
+| SLOD4 | 352 | 6,043.5 | 20,000 | 6,043.5–20,000 |
+| ORPHAN_HD | 396,871 | — | 1,000 | 0–1,000 |
+
+From HD to SLOD2, each tier's median `lodDist` is within 5% of the next tier's median `childLodDist` (124/130,
+450/450, 1,000/1,000, 2,000/1,976), so the two fields agree on the bands. For SLOD3 they differ (4,000 and
+6,043.5), and the band follows `childLodDist`.
+
+This is an approximation of point 5, per cell and per tier. Per-entity `lodDist` overrides and the
+`parentIndex`/`numChildren` links are not used: an entity row doesn't say which map file it came from, and
+`parentIndex` is an index into that file's entity table.
+
+### Measured
+
+On the 1.0.2.1 package, `levels.rpf`, Linux, 88 cores, `--no-textures`, 256 m chunks. Models were exported with
+rpf9-explorer at Leonida's pin (917e9b9) and with breadbbbb/rpf9-explorer#8 and #10 applied. Each placement was
+counted against the first export and built from the second.
| Step | Result |
|---|---|
-| `--entities-out` over the whole data area (24 parallel `--start/--limit` windows) | 1,670,435 rows, about 1 min |
+| `--entities-out` over the whole data area (24 parallel `--start/--limit` windows) | 1,670,435 rows, 66 s |
| `lodLevel` split | 0: 1,153,122 · 5: 396,871 · 1: 100,953 · 2: 16,828 · 3: 1,708 · 4: 601 · 6: 352 |
-| one 700 m × 700 m downtown box, HD + ORPHAN_HD | 29,258 entities, 3,995 distinct archetypes |
-| placed with models recovered by the pinned rpf9-explorer (917e9b9) | 10,729 (36.7%); 18,529 `unresolved_archetype`, 0 `key_mismatch` |
-| same box, models recovered with breadbbbb/rpf9-explorer#8 and #10 applied | 29,229 of 29,258 entities have a model (3,992 of 3,995 archetypes) |
-| build of the 10,729 placed instances (`--no-textures --jobs 8`, 256 m chunks) | 16 chunks, 29.3M triangles, 1.17 GB of GLB, median chunk 104 MB, max 164 MB; 5 min, 22 GB peak RSS |
+| HD + ORPHAN_HD placements with a recovered model (joaat + Murmur3-64) | 640,080 of 1,549,993 (41.3%) at the pin; 1,549,347 (99.96%) with #8/#10, from 121,411 resources |
+| 700 m × 700 m downtown box, 10,729 placements, `--jobs 16` | `bake` (#1183): 5 min, 22 GB peak RSS. `gpu`: 35 s; 0.43 GB in the largest process, 1.93 GB for all 17 processes; same 16 chunks and 29,331,138 triangles |
+| **whole city**, HD + ORPHAN_HD, `gpu`, `--jobs 40` | 1,549,343 placed (646 `unresolved_archetype`, 4 `model_not_loadable`, 0 `key_mismatch`, 0 `mirrored`), 121,407 distinct models → 2,940 chunks; 7.31 G triangles drawn, 3.34 G stored; 125 GB of GLB, median chunk 17 MB, largest 926 MB; 21 min; 3.4 GB in the largest process, 38 GB for all 41 processes |
+| **whole city, all tiers, `--lod-sets`, `gpu`, `--jobs 24`** | 1,669,771 placed (660 `unresolved_archetype`, 4 `model_not_loadable`), 228,566 distinct models → 12,340 chunks: HD 2,911 (median 16.9 MB), LOD 2,836 (0.6 MB), SLOD1 2,811, SLOD2 1,222, SLOD3 501, SLOD4 284 (all ≤ 0.1 MB median), ORPHAN_HD 1,775 (3.0 MB); bands as in the table above; 33 min; 2.6 GB in the largest process, 30 GB for all 25 |
+| what the viewer loads at the densest HD cell (camera at street level in its centre) | with `lod_bands`: 577 chunks, 180 M triangles, 3.1 GB of GLB (5 HD, 69 ORPHAN_HD, the rest LOD/SLOD); the same city without LOD sets at the viewer's 1,400 m radius: 119 chunks, 1,060 M triangles, 16.3 GB |
-The unresolved share in that box is a model-recovery gap, not a naming gap. All 1,800 archetypes that #8/#10 add
-in that box are `.#ft` fragments (18,500 of the entities). The pinned `LooksLikeFragment` rejects their headers
-(breadbbbb/rpf9-explorer#8).
-
-Checks on the same box:
-- The conjugate of every stored rotation equals SixNG's independently derived world rotation:
+Checks:
+- Every chunk of the whole-city build passes a structural check: accessors inside their bufferViews, indices
+ below the vertex count, POSITION `min`/`max` equal to the data, the instancing attributes' counts equal, unit
+ rotations, and positive finite scales. Recomputed from the GLBs, the chunk bounds, placement counts (1,549,343)
+ and drawn triangles (7,311,221,858) equal `world.json`.
+- three r160's `GLTFLoader` (the viewer's loader), run under Node, parses 65 of the city chunks: 60 random and the
+ 5 largest, including the 926 MB one. It builds `InstancedMesh`es whose drawn triangles equal `world.json`, with
+ bounds inside the chunk's bounds. It also parses all 16 chunks of the box and 35 chunks of the LOD-set build
+ (4 random and the largest per tier).
+- The LOD-set build's 12,340 chunks pass the same structural check; 1,669,771 placements and 7,527,211,045 drawn
+ triangles equal `world.json`.
+- On the downtown box, the conjugate of every stored rotation equals SixNG's independently derived world rotation:
|dot| ≥ 0.9999 on 29,124 of 29,125 entities matched by position and archetype, and the minimum is 0.99894.
- Scales are equal on all 29,125.
-- Every placed instance's position lies inside its chunk's bounds (10,620 of 10,620 distinct
- position/archetype pairs).
+ Scales are equal on all 29,125. The instance TRS equals that transform (see the tests).
-**Not verified:** the result has not been looked at in a browser. Instances are baked into the chunk geometry,
-not shared, so a dense box makes 100 MB+ chunks; a smaller `--chunk-size` keeps them small. Building a whole
-city needs glTF instancing and LOD switching, which are next steps.
+The pin's 41.3% is a model-recovery gap, not a naming gap: almost every archetype name resolves (99.85%, see
+*What is readable* above), but only recovered models can be placed. The archetypes that #8/#10 add are `.#ft`
+fragments, whose headers the pinned `LooksLikeFragment` rejects (breadbbbb/rpf9-explorer#8).
+
+**Not verified or limited:**
+- Nothing here was looked at in a browser. The checks above are structural and numeric.
+- Memory grows with `--jobs` (each worker holds the models of one chunk), not with the map: 38 GB at 40 jobs, 30
+ GB at 24 jobs for a bigger build, 1.9 GB at 16 jobs for the box.
+- With LOD sets, most of what is still loaded near the centre is ORPHAN_HD: it has no parent tier, so its band is
+ 0 to 1,000 m.
+- Chunk sizes follow model detail. A few dense downtown cells exceed 100 MB, and the largest stores 24 M
+ triangles of 2,204 distinct models, so a smaller `--chunk-size` there helps a browser.
+- No placement in this package has a negative `scaleZ`, so the mirrored path is checked by the synthetic tests
+ only.
+- Textures were not part of these runs (`--no-textures`).
```powershell
python -I tools\world_index.py --out work\world\index.json --entities-out work\world\entities.jsonl
-python -I tools\world_build.py work\assets --out work\world\placed --no-textures `
- --placements work\world\entities.jsonl --region=-900,500,-200,1200
+python -I tools\world_build.py work\assets --out work\world\placed --no-textures --jobs 16 `
+ --placements work\world\entities.jsonl
+python -I tools\world_build.py work\assets --out work\world\lod --no-textures --jobs 16 `
+ --placements work\world\entities.jsonl --lod-sets
python -I tests\test_world_place.py
+python -I tests\test_world_instancing.py
+node --test tests\test_viewer_streaming.cjs
```
The entity rows and the placed chunks come from your own copy of the game; keep them in the local work folder.
diff --git a/make_game.py b/make_game.py
index 430c8c5d1..ec199a954 100644
--- a/make_game.py
+++ b/make_game.py
@@ -18,16 +18,18 @@ Stages, in order (each skips work that is already done, so a stopped build conti
shaders carve shaders.rpf, unpack the native RDNA2 code, disassemble, translate to SPIR-V
assets models (OBJ), texture dictionaries and texture pools (DDS), audio banks (AWC; --wav adds PCM WAV)
BCPack uses strict decoding by default. For local calibration use /bcpack-calibration.json.
- runtime build the loader (needs the game's executable to run, not to build). Off Windows, or to skip the
- build, --runtime-build DIR takes a Windows build of runtime/ instead (the runtime-windows artifact of
- the Runtime workflow, or your own) and, off Windows, writes gta6rt.sh to start it with Wine
+ runtime build the loader (needs the game's executable to run, not to build). On Linux it is cross-built with
+ clang-cl and an xwin SDK (docs/testing.md) and gta6rt.sh starts it with Wine; --runtime-build DIR
+ takes a Windows build of runtime/ instead (the runtime-windows artifact of the Runtime workflow)
pipelines create every translated shader on your GPU's driver (and every compute pipeline), report anything
the driver rejects, and save the pipeline cache next to the port so the first boot doesn't compile
"""
import argparse
import functools
+import glob
import hashlib
import json
+import ntpath
import os
import re
import shutil
@@ -43,7 +45,11 @@ from mc_command import mc_command # noqa: E402
VERSIONS = os.path.join(ROOT, "game")
STAGES = ["check", "shaders", "assets", "runtime", "pipelines"]
-WINDOWS_ONLY = ("runtime",) # off Windows only with --runtime-build
+WINDOWS_ONLY = ("runtime",) # off Windows: the clang-cl + xwin cross-build, or --runtime-build
+CROSS_TOOLS = ("clang-cl", "lld-link", "llvm-lib", "llvm-rc", "llvm-mt")
+CROSS_VARS = {"C_COMPILER": "clang-cl", "CXX_COMPILER": "clang-cl", "LINKER": "lld-link", "AR": "llvm-lib",
+ "RC_COMPILER": "llvm-rc", "MT": "llvm-mt"} # the toolchain's CMAKE_ defaults
+XWIN_DEFAULT = os.path.join("~", ".local", "share", "xwin-sdk")
RUNTIME_FILES = ("gta6rt.exe", "gta6rt_tls_host.dll")
# Archives scanned for models and texture dictionaries, small to large.
MODEL_ARCHIVES = [
@@ -77,11 +83,11 @@ def below_normal() -> None:
k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00004000)
-def run(args: list, **kw) -> None:
+def run(args: list, hint: str = "", **kw) -> None:
log(" " + " ".join(os.path.basename(str(a)) if i == 0 else str(a) for i, a in enumerate(args)))
r = subprocess.run([str(a) for a in args], **kw)
if r.returncode != 0:
- fail(f"{os.path.basename(str(args[0]))} exited with {r.returncode}")
+ fail(f"{os.path.basename(str(args[0]))} exited with {r.returncode}" + (f". {hint}" if hint else ""))
def py(tool: str, *args) -> None:
@@ -97,6 +103,25 @@ def tool_available(cmd: str) -> bool:
return bool(head and (shutil.which(head) or os.path.isfile(head)))
+def appdata_hint(cmd: str) -> str:
+ """Why a tool under AppData may look missing on Windows, or "".
+
+ `python` from the Python install manager (the app execution alias in WindowsApps) doesn't see folders that other
+ programs create under %LOCALAPPDATA% or %APPDATA%; `py`, or the same python.exe started by its full path, does.
+ scripts\\build_llvm_mc.ps1 used to install llvm-mc.exe to %LOCALAPPDATA%\\Leonida\\llvm-mc."""
+ if os.name != "nt":
+ return ""
+ path = ntpath.normcase(cmd.strip().strip('"'))
+ for var in ("LOCALAPPDATA", "APPDATA"):
+ base = os.environ.get(var, "").strip()
+ if base and path.startswith(ntpath.normcase(ntpath.join(base, ""))):
+ return (f" LLVM_MC points into %{var}%, which `python` from the Python install manager can't see: copy "
+ "llvm-mc.exe out of AppData (scripts\\build_llvm_mc.ps1 now installs it to "
+ "%USERPROFILE%\\.leonida\\llvm-mc), set LLVM_MC to the new path and reopen the terminal, or start "
+ "make_game.py with `py`.")
+ return ""
+
+
def need(exe: str, hint: str) -> str:
if not tool_available(exe):
fail(f"'{exe}' was not found on PATH. {hint}")
@@ -277,14 +302,9 @@ def pipeline_check_prerequisite(runtime_selected: bool = False) -> str:
def preflight(stages: list, work: str, wav: bool = False, runtime_build: str | None = None, *,
- emulate: bool = False, keep_emulated: bool = False) -> None:
+ emulate: bool = False, keep_emulated: bool = False,
+ fallbacks: tuple[str, ...] = (), jobs: int = 1) -> None:
"""Find every missing prerequisite before a long build starts, and list them all at once."""
- if os.name != "nt" and not runtime_build:
- asked = [s for s in stages if s in WINDOWS_ONLY]
- if asked:
- fail(f"The {', '.join(asked)} stage builds on Windows only for now. Pass --runtime-build with a Windows "
- "build of runtime/ (README.md, \"Running the loader on Linux\"), or leave it out of --stages; "
- "without --stages it is left out on this system.")
if "runtime" in stages and runtime_build:
absent = [n for n in RUNTIME_FILES if not os.path.isfile(os.path.join(runtime_build, n))]
if absent:
@@ -295,12 +315,13 @@ def preflight(stages: list, work: str, wav: bool = False, runtime_build: str | N
if sys.version_info < (3, 12):
missing.append("Python 3.12 or newer: https://www.python.org/downloads/")
if "shaders" in stages:
- if not tool_available(mc_command()[0]):
+ mc = mc_command()[0]
+ if not tool_available(mc):
missing.append(
"llvm-mc (LLVM 21+ with the AMDGPU target). The official Windows LLVM build has no AMDGPU "
"target: build a native one with scripts\\build_llvm_mc.ps1, or install llvm-21 in WSL and set "
"LLVM_MC to the whole command, e.g. "
- "LLVM_MC=\"wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc\" (docs/design.md)")
+ "LLVM_MC=\"wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc\" (docs/design.md)." + appdata_hint(mc))
for t in ("spirv-as", "spirv-val"):
if not shutil.which(t):
missing.append(f"{t}: install the Vulkan SDK, https://vulkan.lunarg.com/ (then reopen the terminal)")
@@ -309,14 +330,21 @@ def preflight(stages: list, work: str, wav: bool = False, runtime_build: str | N
missing.append(".NET 8 SDK (the .NET runtime alone can't build rpf9dump): "
"https://dotnet.microsoft.com/download/dotnet/8.0")
ensure_submodule()
- if "runtime" in stages and not runtime_build and not visual_cpp_tools_ok():
+ if os.name == "nt" and "runtime" in stages and not runtime_build and not visual_cpp_tools_ok():
missing.append("Visual Studio 2022 with 'Desktop development with C++'")
+ if os.name != "nt" and not runtime_build and any(s in WINDOWS_ONLY for s in stages):
+ missing.extend(f"{s} (for the runtime stage, or pass --runtime-build)" for s in cross_build_missing())
# The pipelines stage needs a checker the runtime stage builds (on Windows only with VULKAN_SDK set).
# Without this check a build with shaders and pipelines spends hours before failing at the very end.
if "pipelines" in stages and not pipeline_check_exe():
- runtime_building = "runtime" in stages and os.name == "nt" and not runtime_build
- if not runtime_building or not os.environ.get("VULKAN_SDK"):
- missing.append(pipeline_check_prerequisite(runtime_building))
+ if os.name != "nt":
+ if not shutil.which("cmake"):
+ missing.append("CMake 3.24 or newer, a C++20 compiler and the Vulkan headers, to build "
+ "vk_pipeline_check for the pipelines stage")
+ else:
+ runtime_building = "runtime" in stages and not runtime_build
+ if not runtime_building or not os.environ.get("VULKAN_SDK"):
+ missing.append(pipeline_check_prerequisite(runtime_building))
if missing:
fail("Install these first, then run the build again:\n - " + "\n - ".join(dict.fromkeys(missing)))
need = {s: MIN_FREE_GB.get(s, 0) for s in stages}
@@ -328,12 +356,20 @@ def preflight(stages: list, work: str, wav: bool = False, runtime_build: str | N
os.makedirs(work, exist_ok=True)
free_gb = shutil.disk_usage(work).free / 2**30
need_gb = sum(need.values())
- if free_gb < need_gb and need.get("shaders") and shader_outputs_reusable(work, emulate, keep_emulated):
+ if free_gb < need_gb and need.get("shaders") and shader_outputs_reusable(work, emulate, keep_emulated, fallbacks):
log(f"preflight: the shaders in {work} can be reused; not counting their {need['shaders']} GB")
need_gb -= need["shaders"]
if free_gb < need_gb:
fail(f"{free_gb:.0f} GB free on the drive of {work}, about {need_gb} GB is needed. "
"Free some space or choose another drive with --work.")
+ if os.name != "nt" and not runtime_build and any(s in WINDOWS_ONLY for s in stages):
+ cross_configure()
+ if "pipelines" in stages and os.name != "nt" and not pipeline_check_exe():
+ build_pipeline_check(jobs)
+ if not pipeline_check_exe():
+ fail("vk_pipeline_check built, but not as runtime/build/linux/vk_pipeline_check (a multi-config "
+ "generator puts it in a subfolder): unset CMAKE_GENERATOR if it names one, delete "
+ "runtime/build/linux and run the build again.")
def visual_cpp_tools_ok() -> bool:
@@ -351,6 +387,82 @@ def visual_cpp_tools_ok() -> bool:
return result.returncode == 0 and bool(result.stdout.strip())
+def xwin_dir() -> "str | None":
+ """The xwin /winsysroot splat for the cross-build: XWIN_DIR, else the folder docs/testing.md uses."""
+ d = os.path.expanduser(os.environ.get("XWIN_DIR") or XWIN_DEFAULT)
+ sdk = glob.glob(os.path.join(glob.escape(d), "Windows Kits", "10", "Lib", "*", "um", "x64"))
+ return d if os.path.isdir(os.path.join(d, "VC", "Tools", "MSVC")) and sdk else None
+
+
+CROSS_SUFFIXES = ("", *(f"-{n}" for n in range(40, 18, -1)))
+
+
+def cross_tool_suffix() -> "str | None":
+ """"" for the plain LLVM tool names, "-N" for a set named like clang-cl-21: the first complete set whose
+ clang-cl is 19 or newer, plain names first. None if there is none."""
+ for suffix in CROSS_SUFFIXES:
+ if all(shutil.which(t + suffix) for t in CROSS_TOOLS):
+ major = clang_cl_major("clang-cl" + suffix)
+ if major is None or major >= 19:
+ return suffix
+ return None
+
+
+def cross_build_dir() -> str:
+ return os.path.join(ROOT, "runtime", "build", "windows")
+
+
+def configured_cross_tools() -> dict:
+ """The LLVM tools an existing runtime/build/windows was configured with, from CMake's compiler files."""
+ found = {}
+ pattern = os.path.join(glob.escape(cross_build_dir()), "CMakeFiles", "*", "CMake*Compiler.cmake")
+ for path in sorted(glob.glob(pattern), key=os.path.getmtime):
+ try:
+ with open(path, encoding="utf-8", errors="replace") as f:
+ text = f.read()
+ except OSError:
+ continue
+ for m in re.finditer(r'^set\((CMAKE_(?:CXX_COMPILER|LINKER|AR|MT|RC_COMPILER)) "([^"]+)"\)', text, re.M):
+ found[m.group(1)] = m.group(2)
+ return found
+
+
+def clang_cl_major(exe: str = "clang-cl") -> "int | None":
+ try:
+ r = subprocess.run([exe, "--version"], capture_output=True, text=True, errors="replace", timeout=60)
+ except (OSError, subprocess.SubprocessError):
+ return None
+ m = re.search(r"clang version (\d+)", r.stdout)
+ return int(m.group(1)) if m else None
+
+
+def cross_build_missing() -> list:
+ """What the clang-cl + xwin cross-build of runtime/ (runtime/cmake/clang-cl-xwin.cmake) lacks here."""
+ missing = []
+ if not shutil.which("cmake"):
+ missing.append("CMake 3.24 or newer")
+ configured = configured_cross_tools()
+ if configured:
+ gone = sorted({t for t in configured.values() if not shutil.which(t)})
+ if gone:
+ missing.append(f"{', '.join(gone)}, which runtime/build/windows was configured with: put it back on "
+ "PATH, or delete runtime/build/windows to configure it with the tools on PATH now")
+ elif cross_tool_suffix() is None:
+ major = clang_cl_major() if all(shutil.which(t) for t in CROSS_TOOLS) else None
+ partial = next((s for s in CROSS_SUFFIXES[1:] if shutil.which("clang-cl" + s)), "")
+ absent = [t + partial for t in CROSS_TOOLS if not shutil.which(t + partial)]
+ if major is not None and not absent:
+ missing.append(f"clang-cl 19 or newer (this one is {major}; the MSVC STL from xwin rejects older Clang)")
+ else:
+ missing.append(f"{', '.join(absent)}: LLVM 19 or newer (clang, lld and llvm), all five by their plain "
+ "names or with one version suffix such as clang-cl-21")
+ if not xwin_dir():
+ missing.append("an xwin splat made with `xwin splat --use-winsysroot-style --preserve-ms-arch-notation` "
+ "(VC/Tools/MSVC and Windows Kits/10/Lib//um/x64) in XWIN_DIR or "
+ "~/.local/share/xwin-sdk, see docs/testing.md, \"The Windows runtime on Linux\"")
+ return missing
+
+
def dotnet_sdk_ok() -> bool:
"""True if a .NET SDK 8 or newer is installed. `dotnet` is also on PATH with only a runtime, and then
`dotnet build` fails with "No .NET SDKs were found"."""
@@ -414,6 +526,11 @@ def requested_shader_mode(had: str, emulate: bool, keep_emulated: bool) -> str:
return "on" if emulate or (had == "on" and keep_emulated) else "off"
+def translator_flags_setting(fallbacks: tuple[str, ...]) -> str:
+ """The recorded form of the translator fallback flags in spirv/translator_flags.txt (empty means none)."""
+ return " ".join(fallbacks)
+
+
def llvm_mc_signature() -> str:
command = mc_command()
command[0] = shutil.which(command[0]) or command[0]
@@ -434,7 +551,8 @@ def disassembly_matches(dxbc: str, signature: str) -> bool:
and read_shader_setting(os.path.join(dxbc, "disasm.done")) == signature)
-def shader_outputs_reusable(work: str, emulate: bool, keep_emulated: bool) -> bool:
+def shader_outputs_reusable(work: str, emulate: bool, keep_emulated: bool,
+ fallbacks: tuple[str, ...] = ()) -> bool:
"""Check whether the shader stage can resume without carving, unpacking or translating again."""
sh = os.path.join(work, "shaders")
dxbc = os.path.join(sh, "dxbc")
@@ -445,6 +563,7 @@ def shader_outputs_reusable(work: str, emulate: bool, keep_emulated: bool) -> bo
return False
had = read_shader_setting(os.path.join(spirv, "wave64_emulate.txt"), default="off")
return (had == requested_shader_mode(had, emulate, keep_emulated)
+ and read_shader_setting(os.path.join(spirv, "translator_flags.txt")) == translator_flags_setting(fallbacks)
and read_shader_setting(os.path.join(spirv, "translation_sources.sha256")) == translation_sources_digest()
and os.path.isfile(os.path.join(dxbc, "disasm.done"))
and disassembly_matches(dxbc, llvm_mc_signature()))
@@ -462,7 +581,8 @@ def clear_shader_disassembly(work: str, disasm: str) -> None:
os.unlink(entry.path)
-def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulated: bool = False) -> None:
+def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulated: bool = False,
+ fallbacks: tuple[str, ...] = ()) -> None:
src = os.path.join(game, "shaders.rpf")
sh = os.path.join(work, "shaders")
dxbc = os.path.join(sh, "dxbc")
@@ -519,6 +639,16 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate
log(f"shaders: wave64 emulation is now {want} (the shaders were translated with it {had}): "
"translating again")
drop(translated)
+ # The translation also depends on the fallback flags (--no-float-controls, --bary-fallback,
+ # --texel-offset-fallback, --mesh-compute), so they are kept beside it like the wave64 mode. A folder from
+ # before the file existed was translated without them.
+ flags_file = os.path.join(spirv, "translator_flags.txt")
+ want_flags = translator_flags_setting(fallbacks)
+ had_flags = read_shader_setting(flags_file)
+ if had_flags != want_flags and os.path.isfile(translated):
+ log(f"shaders: the fallback flags are now {want_flags or 'none'} (the shaders were translated with "
+ f"{had_flags or 'none'}): translating again")
+ drop(translated)
if not os.path.isfile(translated):
need("spirv-as", "Install the Vulkan SDK (it includes spirv-as and spirv-val) and reopen the terminal.")
need("spirv-val", "Install the Vulkan SDK and reopen the terminal.")
@@ -529,14 +659,25 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate
os.makedirs(spirv, exist_ok=True)
with open(mode_file, "w", encoding="utf-8") as f:
f.write(want + "\n")
+ with open(flags_file, "w", encoding="utf-8") as f:
+ f.write(want_flags + "\n")
with open(sources_file, "w", encoding="utf-8") as f:
f.write(sources + "\n")
- translate(disasm, spirv, jobs, emulate=emulate)
+ translate(disasm, spirv, jobs, emulate=emulate, fallbacks=fallbacks)
log("shaders: done")
WAVE64_MODES = ("auto", "on", "off")
+# The translator's fallback flags make_game.py can forward, and the argparse attribute each one reads.
+FALLBACK_FLAGS = (("--no-float-controls", "no_float_controls"), ("--bary-fallback", "bary_fallback"),
+ ("--texel-offset-fallback", "texel_offset_fallback"), ("--mesh-compute", "mesh_compute"))
+
+
+def fallback_flags(a) -> tuple[str, ...]:
+ """The fallback flags the parsed arguments ask for, in a stable order (the order they are recorded in)."""
+ return tuple(flag for flag, attr in FALLBACK_FLAGS if getattr(a, attr, False))
+
def smallest_max_subgroup(vulkaninfo_text: str):
"""The smallest maxSubgroupSize vulkaninfo reports over all devices (text or --json output), or None."""
@@ -639,23 +780,26 @@ def translator_digest() -> str:
return h.hexdigest()
-def translate(disasm: str, spirv: str, jobs: int, emulate: bool = False) -> None:
+def translate(disasm: str, spirv: str, jobs: int, emulate: bool = False,
+ fallbacks: tuple[str, ...] = ()) -> None:
"""rdna2spirv.py runs on one core: start one --shard per job side by side, then merge their index parts.
A shard renames its index.part.json into place last, so a part on disk is a finished shard. A run stopped
- part-way, or during the merge, keeps those parts when it resumes with the same --jobs, wave64 mode and translator
- source, and starts only the shards that have none. shaders() drops the plan whenever an earlier step reruns."""
+ part-way, or during the merge, keeps those parts when it resumes with the same --jobs, wave64 mode, fallback
+ flags and translator source, and starts only the shards that have none. shaders() drops the plan whenever an
+ earlier step reruns."""
os.makedirs(spirv, exist_ok=True)
plan_path = os.path.join(spirv, SHARD_PLAN)
- plan = {"jobs": jobs, "wave64_emulate": bool(emulate), "translator": translator_digest()}
+ plan = {"jobs": jobs, "wave64_emulate": bool(emulate), "fallbacks": list(fallbacks),
+ "translator": translator_digest()}
try:
with open(plan_path, encoding="utf-8") as f:
same = json.load(f) == plan
except (OSError, ValueError):
same = False
if not same:
- # Parts from another --jobs would be merged in too, and parts from another mode or translator are wrong.
- # They go before the new plan is written: a stop in between must not leave old parts under a new plan.
+ # Parts from another --jobs would be merged in too, and parts from another mode, flags or translator are
+ # wrong. They go before the new plan is written: a stop in between must not leave old parts under a new plan.
for f in os.listdir(spirv):
if f.startswith("index.part") and f.endswith(".json"):
os.remove(os.path.join(spirv, f))
@@ -666,6 +810,7 @@ def translate(disasm: str, spirv: str, jobs: int, emulate: bool = False) -> None
log(f" keeping {jobs - len(todo)} of {jobs} shards finished by the run before")
tool = os.path.join(TOOLS, "rdna2spirv.py")
extra = ["--wave64-emulate"] if emulate else []
+ extra.extend(fallbacks)
if todo:
which = f"0..{jobs - 1}" if len(todo) == jobs else ",".join(str(i) for i in todo)
log(f" rdna2spirv.py {disasm} --out {spirv} --shard {which}/{jobs}" + "".join(" " + e for e in extra))
@@ -838,12 +983,56 @@ exec "${WINE:-wine}" "$here/gta6rt.exe" "$@"
"""
-def runtime(game: str, out: str, v: dict, runtime_build: str | None = None) -> None:
+def cmake_configure(build: str, *config: str, hint: str = "") -> None:
+ """Configure runtime/ in build; the generator and build type are chosen only for a new build folder."""
+ fresh = [] if os.path.isfile(os.path.join(build, "CMakeCache.txt")) else [
+ *(["-G", "Ninja"] if shutil.which("ninja") else []), "-DCMAKE_BUILD_TYPE=RelWithDebInfo"]
+ run(["cmake", "-S", os.path.join(ROOT, "runtime"), "-B", build, *fresh, *config], hint=hint)
+
+
+def cmake_build(build: str, targets: list, jobs: int, hint: str) -> None:
+ run(["cmake", "--build", build, "--parallel", str(jobs), "--target", *targets], hint=hint)
+
+
+def cross_configure() -> str:
+ xwin = xwin_dir()
+ if not xwin:
+ fail("runtime: no xwin SDK in XWIN_DIR or ~/.local/share/xwin-sdk (docs/testing.md, "
+ "\"The Windows runtime on Linux\"), and no --runtime-build.")
+ build = cross_build_dir()
+ suffix = "" if configured_cross_tools() else cross_tool_suffix() or ""
+ tools = [f"-DCMAKE_{var}={shutil.which(name + suffix) or name + suffix}" for var, name in CROSS_VARS.items()
+ ] if suffix else []
+ cmake_configure(build, "--toolchain", os.path.join(ROOT, "runtime", "cmake", "clang-cl-xwin.cmake"),
+ f"-DXWIN_DIR={xwin}", *tools, hint="CMake's error above says what the cross-build lacks "
+ "(docs/testing.md, \"The Windows runtime on Linux\"). Or pass --runtime-build, or drop "
+ "runtime from --stages (the default without it: check,shaders,assets,pipelines).")
+ return build
+
+
+def cross_build_runtime(jobs: int) -> str:
+ log("runtime: cross-building with clang-cl and xwin")
+ build = cross_configure()
+ cmake_build(build, ["gta6rt", "gta6rt_tls_host"], jobs,
+ "See the compiler output above; docs/testing.md has the cross-build's requirements.")
+ return build
+
+
+def build_pipeline_check(jobs: int) -> None:
+ build = os.path.join(ROOT, "runtime", "build", "linux")
+ log("pipelines: building vk_pipeline_check")
+ cmake_configure(build)
+ cmake_build(build, ["vk_pipeline_check"], jobs,
+ "It needs a C++20 compiler and the Vulkan headers (your distribution's Vulkan headers package, "
+ "or VULKAN_SDK); the CMake output above says which is missing.")
+
+
+def runtime(game: str, out: str, v: dict, runtime_build: str | None = None, jobs: int = 1) -> None:
if runtime_build:
log(f"runtime: using the build in {runtime_build}")
build = runtime_build
elif os.name != "nt":
- fail("The runtime builds on Windows only for now: pass --runtime-build with a Windows build of runtime/.")
+ build = cross_build_runtime(jobs)
else:
log("runtime: building")
run(["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File",
@@ -924,11 +1113,24 @@ def main() -> int:
ap.add_argument("--find", action="store_true", help="only list the game copies found on this PC")
ap.add_argument("--runtime-build", metavar="DIR",
help="a Windows build of runtime/ (gta6rt.exe and gta6rt_tls_host.dll) for the runtime stage "
- "instead of building it; off Windows the stage needs it and adds gta6rt.sh for Wine")
+ "instead of building it (off Windows: instead of the clang-cl + xwin cross-build)")
ap.add_argument("--wave64-emulate", choices=WAVE64_MODES, default="auto",
help="translate wave64 compute and mesh shaders to be exact on any subgroup size (needed on "
"32-wide GPUs: NVIDIA, Intel). auto (default) turns it on unless vulkaninfo shows that "
"every GPU has 64-wide subgroups")
+ ap.add_argument("--no-float-controls", action="store_true",
+ help="translate without SignedZeroInfNanPreserve (Depends on: #664), for devices whose "
+ "vk_pipeline_check skips a shader without shaderSignedZeroInfNanPreserveFloat32")
+ ap.add_argument("--bary-fallback", action="store_true",
+ help="translate raw barycentric reads from an interpolated vec3 input (with a pass-through "
+ "geometry shader the runtime draws), for devices without "
+ "VK_KHR_fragment_shader_barycentric")
+ ap.add_argument("--texel-offset-fallback", action="store_true",
+ help="fold the run-time texel offset of image_sample*_o into the coordinate, for devices "
+ "without VK_KHR_maintenance8")
+ ap.add_argument("--mesh-compute", action="store_true",
+ help="translate mesh shaders to compute shaders writing an output buffer, for devices "
+ "without VK_EXT_mesh_shader")
a = ap.parse_args()
stages = STAGES
if a.stages is not None:
@@ -982,19 +1184,24 @@ def main() -> int:
fail("--out and --work must be outside the game folder.")
runtime_build = os.path.abspath(a.runtime_build) if a.runtime_build else None
if a.stages is None and os.name != "nt" and not runtime_build:
- stages = [s for s in stages if s not in WINDOWS_ONLY]
- log(f"{', '.join(WINDOWS_ONLY)}: left out, it builds on Windows only for now (or pass --runtime-build)")
+ lacking = cross_build_missing()
+ if lacking:
+ stages = [s for s in stages if s not in WINDOWS_ONLY]
+ log(f"{', '.join(WINDOWS_ONLY)}: left out, the cross-build needs {'; '.join(lacking)} "
+ "(or pass --runtime-build)")
emulate = "shaders" in stages and wave64_emulate(a.wave64_emulate)
keep_emulated = a.wave64_emulate == "auto"
- preflight(stages, work, a.wav, runtime_build, emulate=emulate, keep_emulated=keep_emulated)
+ fallbacks = fallback_flags(a) if "shaders" in stages else ()
+ preflight(stages, work, a.wav, runtime_build, emulate=emulate, keep_emulated=keep_emulated,
+ fallbacks=fallbacks, jobs=a.jobs)
log(f"building into {out} (work files in {work})")
t0 = time.time()
if "shaders" in stages:
- shaders(game, work, a.jobs, emulate=emulate, keep_emulated=keep_emulated)
+ shaders(game, work, a.jobs, emulate=emulate, keep_emulated=keep_emulated, fallbacks=fallbacks)
if "assets" in stages:
assets(game, work, a.wav, a.jobs)
if "runtime" in stages:
- runtime(game, out, v, runtime_build)
+ runtime(game, out, v, runtime_build, a.jobs)
if "pipelines" in stages:
pipelines(work, out, a.jobs)
log(f"finished in {(time.time() - t0) / 60:.0f} min")
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index d6c98048e..66803a5b7 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -341,7 +341,8 @@ if(BUILD_TESTING)
# `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)
+ add_library(xgameruntime_stub SHARED test/fixtures/xgameruntime_stub.cpp test/fixtures/xgameruntime_stub.def)
+ target_include_directories(xgameruntime_stub PUBLIC ${XTASKQUEUE_DIR}/Include)
target_compile_definitions(xgameruntime_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
set_target_properties(xgameruntime_stub PROPERTIES
OUTPUT_NAME xgameruntime
@@ -349,6 +350,11 @@ if(BUILD_TESTING)
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$"
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$"
)
+ add_executable(tiny_async test/fixtures/tiny_async.cpp)
+ target_link_libraries(tiny_async PRIVATE xgameruntime_stub)
+ set_target_properties(tiny_async PROPERTIES
+ RUNTIME_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 _CRT_SECURE_NO_WARNINGS) # plain fopen, as games use
@@ -530,6 +536,9 @@ if(BUILD_TESTING)
set_tests_properties(gameinput PROPERTIES DISABLED TRUE)
endif()
if(WIN32 AND TARGET gta6rt AND TARGET tiny_game)
+ add_test(NAME run_tiny_async COMMAND ${CMAKE_COMMAND}
+ "-DLOADER=$" "-DGUEST=$"
+ "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_async.cmake")
# 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)
@@ -604,13 +613,17 @@ if(NOT TARGET Vulkan::Headers)
endif()
if(TARGET Vulkan::Headers)
foreach(tool vk_harness vk_texture_test vk_compute_test vk_store_test vk_pipeline_check vk_command_replay_test
- vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test)
+ vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test)
add_executable(${tool} test/${tool}.cpp)
target_link_libraries(${tool} PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
if(WIN32)
target_compile_definitions(${tool} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
endif()
endforeach()
+ if(BUILD_TESTING)
+ add_test(NAME depth24_convert COMMAND depth24_convert_test)
+ set_tests_properties(depth24_convert PROPERTIES SKIP_RETURN_CODE 77)
+ endif()
if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE)
find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin")
endif()
@@ -754,6 +767,29 @@ if(TARGET Vulkan::Headers)
add_test(NAME d3d12_uav_clear COMMAND d3d12_uav_clear_test)
set_tests_properties(d3d12_uav_clear PROPERTIES SKIP_RETURN_CODE 77)
+ # Emulation of R9G9B9E5_SHAREDEXP UAV textures as mutable R32_UINT on GPUs without E5B9G9R9 storage:
+ # format support, 1D/2D/3D/reserved creation, SRV/UAV T#s, WARP differential UAV clears, cross-backing copies,
+ # and set-0 storage write -> E5B9G9R9 sampled HDR round-trip.
+ add_executable(d3d12_r9g9b9e5_uav_test test/d3d12_r9g9b9e5_uav_test.cpp)
+ target_link_libraries(d3d12_r9g9b9e5_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
+ target_compile_definitions(d3d12_r9g9b9e5_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
+ target_compile_options(d3d12_r9g9b9e5_uav_test PRIVATE /W4 /permissive- /utf-8)
+ add_test(NAME d3d12_r9g9b9e5_uav COMMAND d3d12_r9g9b9e5_uav_test)
+ set_tests_properties(d3d12_r9g9b9e5_uav PROPERTIES SKIP_RETURN_CODE 77)
+ if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE)
+ set(LEONIDA_TEST_CS_R9G9B9E5_UAV ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_r9g9b9e5_uav.spv)
+ add_custom_command(
+ OUTPUT ${LEONIDA_TEST_CS_R9G9B9E5_UAV}
+ COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_CS_R9G9B9E5_UAV}
+ ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_r9g9b9e5_uav.comp
+ DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_r9g9b9e5_uav.comp
+ COMMENT "Compiling cs_r9g9b9e5_uav.comp"
+ VERBATIM)
+ target_sources(d3d12_r9g9b9e5_uav_test PRIVATE ${LEONIDA_TEST_CS_R9G9B9E5_UAV})
+ target_compile_definitions(d3d12_r9g9b9e5_uav_test PRIVATE
+ LEONIDA_TEST_CS_R9G9B9E5_UAV_SPV="${LEONIDA_TEST_CS_R9G9B9E5_UAV}")
+ endif()
+
# Debug markers as VK_EXT_debug_utils labels, and private data on every object (D3D-24).
add_executable(d3d12_debug_markers_test test/d3d12_debug_markers_test.cpp)
target_link_libraries(d3d12_debug_markers_test PRIVATE gta6rt_d3d12_com)
@@ -826,6 +862,13 @@ if(TARGET Vulkan::Headers)
message(STATUS "glslangValidator not found: d3d12_descriptor_test skips its shader")
endif()
+ add_executable(d3d12_predicated_copy_test test/d3d12_predicated_copy_test.cpp)
+ target_link_libraries(d3d12_predicated_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
+ target_compile_definitions(d3d12_predicated_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
+ target_compile_options(d3d12_predicated_copy_test PRIVATE /W4 /permissive- /utf-8)
+ add_test(NAME d3d12_predicated_copy COMMAND d3d12_predicated_copy_test)
+ set_tests_properties(d3d12_predicated_copy PROPERTIES SKIP_RETURN_CODE 77)
+
# Differential regression: run explicitly (requires Vulkan hardware and Windows WARP).
add_executable(d3d12_clear_test test/d3d12_clear_test.cpp)
target_link_libraries(d3d12_clear_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
@@ -929,6 +972,8 @@ if(TARGET Vulkan::Headers)
LEONIDA_TEST_FS_SOLID_SPV="${LEONIDA_TEST_FS_SOLID}"
LEONIDA_TEST_CS_RAYQUERY_SPV="${LEONIDA_TEST_CS_RAYQUERY}")
endif()
+ add_test(NAME d3d12_indirect_rt COMMAND d3d12_indirect_rt_test)
+ set_tests_properties(d3d12_indirect_rt PROPERTIES SKIP_RETURN_CODE 77)
# Milestone M0: a window, 60 cleared frames presented through the proxy on Vulkan.
add_executable(d3d12_present_test test/d3d12_present_test.cpp)
@@ -992,6 +1037,11 @@ if(TARGET Vulkan::Headers)
target_link_libraries(bvh_builder_test PRIVATE gta6rt_d3d12_com)
target_compile_definitions(bvh_builder_test PRIVATE LEONIDA_VULKAN_DEVICE)
endif()
+ # fsr_dispatch_test can put the package's FidelityFX DLL on this device too (LEONIDA_FSR_DEVICE=vulkan).
+ if(TARGET fsr_dispatch_test)
+ target_link_libraries(fsr_dispatch_test PRIVATE gta6rt_d3d12_com)
+ target_compile_definitions(fsr_dispatch_test PRIVATE LEONIDA_VULKAN_DEVICE)
+ endif()
else()
message(STATUS "Python 3, Windows or d3d12.h missing: the D3D12 COM objects and d3d12_com_test are not built")
endif()
@@ -1007,6 +1057,12 @@ if(TARGET Vulkan::Headers)
add_executable(pipeline_cache_snapshot_test test/pipeline_cache_snapshot_test.cpp)
target_link_libraries(pipeline_cache_snapshot_test PRIVATE Vulkan::Headers)
add_test(NAME pipeline_cache_snapshot COMMAND pipeline_cache_snapshot_test)
+ add_executable(predicated_copy_test test/predicated_copy_test.cpp)
+ target_link_libraries(predicated_copy_test PRIVATE Vulkan::Headers)
+ if(WIN32)
+ target_compile_definitions(predicated_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
+ endif()
+ add_test(NAME predicated_copy COMMAND predicated_copy_test)
add_executable(clear_color_test test/clear_color_test.cpp)
target_link_libraries(clear_color_test PRIVATE Vulkan::Headers)
if(WIN32)
diff --git a/runtime/README.md b/runtime/README.md
index 5e1ad9d2f..fcd151733 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -292,3 +292,7 @@ every sample of a pixel one value, so the modes over differing samples are not c
$env:LEONIDA_VK_VALIDATION = '1'
.\runtime\build\RelWithDebInfo\d3d12_depth_resolve_test.exe
```
+
+### Predicate capture lifetime
+
+`vk_predicate_capture_test` checks full-width predicate snapshots, offset rebinding and reset with 32 gated submissions, then reuses completed command-buffer slots. Run explicitly on a Vulkan GPU with conditional rendering; it uses only synthetic data.
diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp
index 9b5550166..998c1b1a4 100644
--- a/runtime/shims/d3d12_com.cpp
+++ b/runtime/shims/d3d12_com.cpp
@@ -1050,10 +1050,17 @@ public:
domains[0].timeDomain = VK_TIME_DOMAIN_DEVICE_KHR;
domains[1].timeDomain = VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_KHR;
std::uint64_t stamps[2]{}, deviation = 0;
+ LARGE_INTEGER before{}, after{};
+ QueryPerformanceCounter(&before);
if (clock_.calibrated(context_.device(), 2, domains, stamps, &deviation) == VK_SUCCESS) {
- *gpu = stamps[0];
- *cpu = stamps[1];
- return S_OK;
+ QueryPerformanceCounter(&after);
+ // Wine can expose a host monotonic clock that differs from its Win32 QPC clock.
+ // Keep the GPU and CPU samples paired by taking a fresh GPU sample on fallback.
+ if (stamps[1] >= UINT64(before.QuadPart) && stamps[1] <= UINT64(after.QuadPart)) {
+ *gpu = stamps[0];
+ *cpu = stamps[1];
+ return S_OK;
+ }
}
}
return submitted_calibration(*gpu, *cpu);
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h
index e6170411f..815289f5e 100644
--- a/runtime/shims/d3d12_com.h
+++ b/runtime/shims/d3d12_com.h
@@ -85,6 +85,7 @@ struct VulkanDeviceInfo {
// buffers are created with VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT. Without it a predicated list is
// rejected at ExecuteCommandLists.
bool conditional_rendering = false;
+ bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled: byte-granular predicated buffer copies.
// VK_EXT_host_image_copy and its hostImageCopy feature are enabled on `device`: WriteToSubresource and
// ReadFromSubresource on textures in CPU-visible heaps copy on the CPU instead of through a staging submit.
bool host_image_copy = false;
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index 0fa6f819c..ea52813d4 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -72,6 +72,7 @@ struct Format {
bool typeless = false; // created with MUTABLE_FORMAT so typed views can reinterpret it
bool d24_as_float = false; // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (no D24 on the GPU)
bool d24 = false; // a D24_UNORM_S8_UINT family format, native or stored as D32
+ bool r9g9b9e5_as_r32_uint = false; // R9G9B9E5_SHAREDEXP UAV stored as mutable R32_UINT (no E5B9G9R9 storage)
};
// DXGI -> Vulkan for the formats render targets, depth buffers and common textures use. Typeless depth families
@@ -208,33 +209,49 @@ leonida::TargetView volume_rtv(leonida::ResourceId id, const D3D12_RESOURCE_DESC
// The VkImage a texture description becomes, with its mip count already resolved (MipLevels != 0). Shared by
// texture creation and GetResourceAllocationInfo, so the sizes reported are the sizes later allocated.
+// Keeps the optional VkImageFormatListCreateInfo alongside VkImageCreateInfo so info.pNext stays valid.
// attachment_usable: the GPU can render to `format`. A UAV texture then also gets COLOR_ATTACHMENT usage, because
// ClearUnorderedAccessView* with rectangles clears through an attachment (vkCmdClearAttachments).
-VkImageCreateInfo texture_create_info(const D3D12_RESOURCE_DESC& desc, const Format& format, bool attachment_usable) {
- const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D;
- const bool one_d = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D;
+struct TextureCreateInfo {
VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
- info.flags = format.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0;
- if (volume && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET))
- info.flags |= VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT;
- info.imageType = volume ? VK_IMAGE_TYPE_3D : one_d ? VK_IMAGE_TYPE_1D : VK_IMAGE_TYPE_2D;
- info.format = format.format;
- info.extent = {std::uint32_t(desc.Width), one_d ? 1u : desc.Height,
- volume ? UINT(desc.DepthOrArraySize) : 1u};
- info.mipLevels = desc.MipLevels;
- 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 (!volume && info.samples == VK_SAMPLE_COUNT_1_BIT && attachment_usable)
- info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
+ VkImageFormatListCreateInfo format_list{VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO};
+ std::array view_formats{};
+
+ TextureCreateInfo(const D3D12_RESOURCE_DESC& desc, const Format& format, bool attachment_usable) {
+ const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D;
+ const bool one_d = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D;
+ info.flags = format.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0;
+ if (volume && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET))
+ info.flags |= VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT;
+ info.imageType = volume ? VK_IMAGE_TYPE_3D : one_d ? VK_IMAGE_TYPE_1D : VK_IMAGE_TYPE_2D;
+ info.format = format.format;
+ info.extent = {std::uint32_t(desc.Width), one_d ? 1u : desc.Height,
+ volume ? UINT(desc.DepthOrArraySize) : 1u};
+ info.mipLevels = desc.MipLevels;
+ 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 (!volume && info.samples == VK_SAMPLE_COUNT_1_BIT && attachment_usable)
+ info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
+ }
+ if (!(desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
+ if (format.r9g9b9e5_as_r32_uint) {
+ // R32_UINT owns storage and attachment usages; E5B9G9R9 views restrict usage to SAMPLED_BIT.
+ info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_EXTENDED_USAGE_BIT;
+ view_formats = {VK_FORMAT_R32_UINT, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32};
+ format_list.viewFormatCount = 2;
+ format_list.pViewFormats = view_formats.data();
+ info.pNext = &format_list;
+ }
}
- if (!(desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
- return info;
-}
+
+ TextureCreateInfo(const TextureCreateInfo&) = delete;
+ TextureCreateInfo& operator=(const TextureCreateInfo&) = delete;
+};
// What a device's children need from it, kept apart from the COM class so children can hold a plain pointer.
struct DeviceState {
@@ -255,13 +272,18 @@ struct DeviceState {
bool subgroups_read = false;
PFN_vkGetPhysicalDeviceFormatProperties format_properties = nullptr;
PFN_vkGetPhysicalDeviceImageFormatProperties image_format_properties = nullptr;
+ PFN_vkGetPhysicalDeviceImageFormatProperties2 image_format_properties2 = nullptr;
PFN_vkGetDeviceImageMemoryRequirements image_requirements = nullptr; // Vulkan 1.3 or VK_KHR_maintenance4
LUID luid{}; // VkPhysicalDeviceIDProperties::deviceLUID; zero when the driver reports none
QueueClock clock; // what every queue's GetClockCalibration uses
PFN_vkGetPhysicalDeviceFormatProperties2 format_properties2 = nullptr;
+ // True when VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 lacks native STORAGE_IMAGE but mutable R32_UINT+{R32_UINT,E5B9G9R9}
+ // is supported, so R9G9B9E5_SHAREDEXP UAV textures are backed by R32_UINT with separate storage/sampled views.
+ bool r9g9b9e5_uav_emulated = false;
// Cached physical-device no-attachment sample counts for D3D12_OPTIONS19.
UINT no_output_sample_counts = 0;
+ float max_sampler_lod_bias = 0;
// VkPhysicalDeviceDepthStencilResolveProperties: the modes a depth or stencil ResolveSubresourceRegion can use.
VkResolveModeFlags depth_resolve_modes = 0;
VkResolveModeFlags stencil_resolve_modes = 0;
@@ -360,14 +382,61 @@ struct DeviceState {
bool color_attachment_usable(VkFormat format) const {
VkFormatProperties properties{};
format_properties(info.physical, format, &properties);
- return properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT;
+ return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0;
}
- // The limits apply to this exact combination of format, type, tiling, usage and create flags.
+ bool storage_usable(VkFormat format) const {
+ VkFormatProperties properties{};
+ format_properties(info.physical, format, &properties);
+ return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) != 0;
+ }
+
+ bool sampled_usable(VkFormat format) const {
+ VkFormatProperties properties{};
+ format_properties(info.physical, format, &properties);
+ return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) != 0;
+ }
+
+ // Whether the GPU needs and supports backing R9G9B9E5_SHAREDEXP UAV textures with a mutable R32_UINT image.
+ bool probe_r9g9b9e5_uav_emulation() const {
+ if (storage_usable(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32)) return false;
+ if (!image_format_properties2 || !storage_usable(VK_FORMAT_R32_UINT) ||
+ !sampled_usable(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32))
+ return false;
+ constexpr VkFormat view_formats[2] = {VK_FORMAT_R32_UINT, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32};
+ VkImageFormatListCreateInfo list{VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO};
+ list.viewFormatCount = 2;
+ list.pViewFormats = view_formats;
+ VkPhysicalDeviceImageFormatInfo2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2, &list};
+ query.format = VK_FORMAT_R32_UINT;
+ query.type = VK_IMAGE_TYPE_2D;
+ query.tiling = VK_IMAGE_TILING_OPTIMAL;
+ query.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
+ VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
+ query.flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_EXTENDED_USAGE_BIT;
+ VkImageFormatProperties2 props{VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2};
+ return image_format_properties2(info.physical, &query, &props) == VK_SUCCESS;
+ }
+
+ // The limits apply to this exact combination of format, type, tiling, usage, create flags and pNext format list.
HRESULT check_image_support(const VkImageCreateInfo& create) const {
VkImageFormatProperties limits{};
- const VkResult result = image_format_properties(info.physical, create.format, create.imageType, create.tiling,
- create.usage, create.flags, &limits);
+ VkResult result = VK_ERROR_FORMAT_NOT_SUPPORTED;
+ if (image_format_properties2) {
+ VkPhysicalDeviceImageFormatInfo2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2};
+ query.pNext = create.pNext;
+ query.format = create.format;
+ query.type = create.imageType;
+ query.tiling = create.tiling;
+ query.usage = create.usage;
+ query.flags = create.flags;
+ VkImageFormatProperties2 props{VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2};
+ result = image_format_properties2(info.physical, &query, &props);
+ limits = props.imageFormatProperties;
+ } else {
+ result = image_format_properties(info.physical, create.format, create.imageType, create.tiling,
+ create.usage, create.flags, &limits);
+ }
if (result == VK_ERROR_FORMAT_NOT_SUPPORTED) return E_INVALIDARG;
if (result == VK_ERROR_OUT_OF_HOST_MEMORY || result == VK_ERROR_OUT_OF_DEVICE_MEMORY) return E_OUTOFMEMORY;
if (result != VK_SUCCESS) return E_FAIL;
@@ -402,6 +471,15 @@ struct DeviceState {
subgroups.lane_min = size_control.minSubgroupSize ? size_control.minSubgroupSize : subgroup.subgroupSize;
subgroups.lane_max = size_control.maxSubgroupSize ? size_control.maxSubgroupSize : subgroups.lane_min;
if (subgroups.lane_max < subgroups.lane_min) subgroups.lane_max = subgroups.lane_min;
+ // D3D-121: Intel's D3D12 driver answers a fixed 16..16 on its integrated GPUs, where Vulkan reports the
+ // compiler's whole 8..32 choice. Measured on Xe-LP: UHD 770 (32.0.101.6129) and Raptor Lake-S Mobile
+ // (101.7092). Discrete Arc is not measured yet (TEST-57), so it keeps the Vulkan range.
+ constexpr uint32_t kIntelVendorId = 0x8086;
+ constexpr UINT kIntelD3D12Lanes = 16;
+ if (properties.properties.vendorID == kIntelVendorId &&
+ properties.properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU &&
+ subgroups.lane_min <= kIntelD3D12Lanes && kIntelD3D12Lanes <= subgroups.lane_max)
+ subgroups.lane_min = subgroups.lane_max = kIntelD3D12Lanes;
return subgroups;
}
@@ -418,7 +496,7 @@ struct DeviceState {
return VK_SAMPLE_COUNT_1_BIT;
}
- // The format a texture description is created with, D24S8's fallback included.
+ // The format a texture description is created with, D24S8 and R9G9B9E5 UAV fallbacks included.
Format texture_format(const D3D12_RESOURCE_DESC& desc) const {
if (!xr_bias_compatible(desc)) return {};
if (desc.Format == DXGI_FORMAT_A8_UNORM &&
@@ -426,7 +504,16 @@ struct DeviceState {
(desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL |
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))))
return {};
- if (!xr_bias_compatible(desc)) return {};
+ if (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) {
+ if (desc.SampleDesc.Count != 1 ||
+ (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL |
+ D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)))
+ return {};
+ if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && r9g9b9e5_uav_emulated) {
+ log_once("R9G9B9E5_SHAREDEXP UAV unavailable natively, using mutable R32_UINT; format", desc.Format);
+ return {VK_FORMAT_R32_UINT, VK_IMAGE_ASPECT_COLOR_BIT, false, false, false, true};
+ }
+ }
Format format = texture_storage_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL);
format.d24 = format.format == VK_FORMAT_D24_UNORM_S8_UINT; // native or not: clears are quantised
if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !depth_usable(format.format)) {
@@ -516,7 +603,8 @@ struct DeviceState {
// write through it too (an unordered-access view), so it also goes into the storage arrays, which are
// shorter. False when set 0 cannot show the image; the descriptor then finds the fallback at index 0.
bool bind_image(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image,
- VkFormat image_format, VkImageAspectFlags aspects, bool storage) {
+ VkFormat image_format, VkImageAspectFlags aspects, bool storage,
+ bool r9g9b9e5_as_r32_uint = false) {
namespace g = leonida::gfx10;
std::lock_guard lock(descriptor_mutex);
if (!bindless) return false;
@@ -540,7 +628,8 @@ struct DeviceState {
// views it in the image's own format with the stencil aspect, and returns the value in R, as a T# whose
// format is 8_UINT reads it from X.
const bool stencil = (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) && image.format == g::stencil_format;
- const VkFormat view_format = stencil ? image_format : g::vulkan_view_format(image_format, image.format);
+ const VkFormat logical_format = r9g9b9e5_as_r32_uint ? VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 : image_format;
+ const VkFormat view_format = stencil ? image_format : g::vulkan_view_format(logical_format, image.format);
if (view_format == VK_FORMAT_UNDEFINED) {
log_once("no Vulkan view format for the GFX10 format of a view:", int(image.format));
return false;
@@ -555,6 +644,11 @@ struct DeviceState {
view_info.image = vk_image;
view_info.viewType = g::vulkan_view_type(image.type);
view_info.format = view_format;
+ VkImageViewUsageCreateInfo sampled_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO};
+ if (r9g9b9e5_as_r32_uint) {
+ sampled_usage.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
+ view_info.pNext = &sampled_usage;
+ }
auto swizzle = image.swizzle;
VkImageViewMinLodCreateInfoEXT clamp{VK_STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT};
const bool color_2d = (image.type == g::ImageType::image_2d || image.type == g::ImageType::image_2d_array || image.type == g::ImageType::cube) &&
@@ -571,6 +665,7 @@ struct DeviceState {
log_once("2D SRV requires VK_EXT_image_view_min_lod; first mip", int(image.first_mip));
return false;
}
+ clamp.pNext = view_info.pNext;
view_info.pNext = &clamp;
}
}
@@ -585,14 +680,22 @@ struct DeviceState {
if (vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled) != VK_SUCCESS) return false;
leonida::StorageViews views{};
if (storage) {
- view_info.components = {};
- if (vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.storage) != VK_SUCCESS) {
+ VkImageViewCreateInfo storage_info = view_info;
+ storage_info.components = {};
+ VkImageViewUsageCreateInfo storage_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO};
+ const VkFormat storage_format = r9g9b9e5_as_r32_uint ? VK_FORMAT_R32_UINT : view_format;
+ if (r9g9b9e5_as_r32_uint) {
+ storage_info.format = storage_format;
+ storage_usage.usage = VK_IMAGE_USAGE_STORAGE_BIT;
+ storage_info.pNext = &storage_usage;
+ }
+ if (vk.vkCreateImageView(info.device, &storage_info, nullptr, &entry.storage) != VK_SUCCESS) {
vk.vkDestroyImageView(info.device, entry.sampled, nullptr);
return false;
}
- const int numeric = numeric_class(view_format);
+ const int numeric = numeric_class(storage_format);
(numeric == 1 ? views.as_uint : numeric == 2 ? views.as_sint : views.as_float) = entry.storage;
- if (view_format == VK_FORMAT_R32_UINT) views.r32ui = entry.storage;
+ if (storage_format == VK_FORMAT_R32_UINT) views.r32ui = entry.storage;
}
// Every state a shader can read or write the texture in is GENERAL (ResourceBinding::sampled_in_general).
entry.index = bindless->add_image(dimension, entry.sampled, VK_IMAGE_LAYOUT_GENERAL, views, sampled_class);
@@ -640,7 +743,7 @@ struct DeviceState {
const leonida::DescriptorKey key = leonida::make_ssharp_key(words.data());
if (sampler_entries.count(key)) return true;
const g::Sampler sampler = g::decode(words);
- VkSamplerCreateInfo sampler_info = g::vulkan_sampler(sampler);
+ VkSamplerCreateInfo sampler_info = g::vulkan_sampler(sampler, max_sampler_lod_bias);
// What vulkan_sampler leaves to its caller, and features this device may not have enabled.
if (sampler_info.anisotropyEnable && !info.sampler_anisotropy) {
log_once("anisotropic sampler without samplerAnisotropy; anisotropy", int(sampler.max_anisotropy));
@@ -792,6 +895,7 @@ public:
VkBuffer buffer() const { return buffer_; }
const D3D12_RESOURCE_DESC& desc() const { return desc_; }
VkFormat format() const { return format_; } // of the image
+ bool r9g9b9e5_as_r32_uint() const { return r9g9b9e5_as_r32_uint_; }
VkImageAspectFlags aspects() const { return aspects_; }
std::uint64_t image_address() const { return image_address_; } // what a T# names the texture by
VkMemoryPropertyFlags memory_flags() const { return memory_flags_; } // of the memory type behind it
@@ -903,8 +1007,8 @@ public:
const UINT depth = volume ? desc_.DepthOrArraySize : 1;
const bool one_d = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D;
if (desc_.MipLevels == 0) desc_.MipLevels = full_mips(desc_.Width, desc_.Height, depth);
- VkImageCreateInfo info =
- texture_create_info(desc_, format, device_.color_attachment_usable(format.format));
+ TextureCreateInfo create(desc_, format, device_.color_attachment_usable(format.format));
+ VkImageCreateInfo& info = create.info;
const std::uint32_t samples = info.samples;
// Textures the CPU reads and writes (WriteToSubresource/ReadFromSubresource) copy on the host when they can.
// (A D24 texture stored as D32 goes through the staged copy: the host copy would not convert.)
@@ -944,6 +1048,7 @@ public:
// With the bindless set, a view's descriptor has one layout for as long as it lives (bind_image).
binding.sampled_in_general = device_.bindless != nullptr;
format_ = format.format;
+ r9g9b9e5_as_r32_uint_ = format.r9g9b9e5_as_r32_uint;
aspects_ = format.aspects;
image_address_ = device_.next_image_address.fetch_add(256);
binding_ = binding;
@@ -1259,6 +1364,7 @@ private:
VkAccelerationStructureKHR accel_ = VK_NULL_HANDLE;
void* mapped_ = nullptr;
VkFormat format_ = VK_FORMAT_UNDEFINED;
+ bool r9g9b9e5_as_r32_uint_ = false;
VkImageAspectFlags aspects_ = 0;
std::uint64_t image_address_ = 0;
bool reserved_ = false;
@@ -2011,7 +2117,9 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida
return false;
}
}
- VkFormat named = resource.format();
+ const VkFormat resource_format =
+ resource.r9g9b9e5_as_r32_uint() ? VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 : resource.format();
+ VkFormat named = resource_format;
if (volume) {
const bool compatible = vulkan_format(desc.Format, false).typeless
? desc.Format == DXGI_FORMAT_R8G8B8A8_TYPELESS &&
@@ -2038,11 +2146,15 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida
log_once("incompatible typed A8 view format:", int(view.format));
return false;
}
+ if ((view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) != (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP)) {
+ log_once("incompatible R9G9B9E5 view format:", int(view.format));
+ return false;
+ }
named = texture_storage_format(view.format, false).format;
}
const std::uint32_t code = stencil ? g::stencil_format : g::format_from_vulkan(named);
const VkFormat view_format = stencil ? resource.format()
- : code ? g::vulkan_view_format(resource.format(), code)
+ : code ? g::vulkan_view_format(resource_format, code)
: VK_FORMAT_UNDEFINED;
if (view_format == VK_FORMAT_UNDEFINED) {
log_once("view format not supported for this texture:", int(view.format));
@@ -2244,6 +2356,12 @@ public:
info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties"));
state_.image_format_properties = reinterpret_cast(
info.get_instance_proc(info.instance, "vkGetPhysicalDeviceImageFormatProperties"));
+ state_.image_format_properties2 = reinterpret_cast(
+ info.get_instance_proc(info.instance, "vkGetPhysicalDeviceImageFormatProperties2"));
+ if (!state_.image_format_properties2) {
+ state_.image_format_properties2 = reinterpret_cast(
+ info.get_instance_proc(info.instance, "vkGetPhysicalDeviceImageFormatProperties2KHR"));
+ }
const auto memory_properties = reinterpret_cast(
info.get_instance_proc(info.instance, "vkGetPhysicalDeviceMemoryProperties"));
const auto device_properties = reinterpret_cast(
@@ -2253,6 +2371,7 @@ public:
if (!get_device || !state_.format_properties || !state_.image_format_properties || !memory_properties ||
!device_properties || !queue_families)
return;
+ state_.r9g9b9e5_uav_emulated = state_.probe_r9g9b9e5_uav_emulation();
memory_properties(info.physical, &state_.memory);
{
char text[4] = {};
@@ -2305,26 +2424,48 @@ public:
info.conditional_rendering, info.ray_tracing);
if (info.buffer_device_address && state_.context->loaded() && !create_arena())
std::fprintf(stderr, "[rt] d3d12: the GPU address arena could not be created\n");
- if (info.host_image_copy) load_host_image_copy(get_device);
- // The copies of a D24 texture stored as D32 convert on the GPU (vulkan_depth24.h).
- std::uint64_t max_storage_range = 1u << 27; // the least Vulkan allows, if the limit cannot be read
- if (info.physical && info.get_instance_proc) {
- if (const auto get_props = reinterpret_cast(
- info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) {
- VkPhysicalDeviceProperties props{};
- get_props(info.physical, &props);
- max_storage_range = props.limits.maxStorageBufferRange;
+ if (info.conditional_rendering) {
+ const auto properties = reinterpret_cast(
+ info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"));
+ const auto families = reinterpret_cast(
+ info.get_instance_proc(info.instance, "vkGetPhysicalDeviceQueueFamilyProperties"));
+ if (properties && families) {
+ VkPhysicalDeviceProperties limits{};
+ properties(info.physical, &limits);
+ std::uint32_t count = 0;
+ families(info.physical, &count, nullptr);
+ std::vector queues(count);
+ families(info.physical, &count, queues.data());
+ if (info.queue_family < count && (queues[info.queue_family].queueFlags & VK_QUEUE_COMPUTE_BIT)) {
+ state_.context->configure_predication(get_device, state_.memory, limits.limits.maxStorageBufferRange, info.queue_family);
+ if (info.storage_buffer_8bit) state_.context->configure_predicated_copy(get_device, limits.limits);
+ }
}
}
- state_.context->enable_depth24(get_device, [this](const VkMemoryRequirements& requirements) {
- return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
- }, max_storage_range);
+ if (info.host_image_copy) load_host_image_copy(get_device);
+ // The copies of a D24 texture stored as D32 convert on the GPU (vulkan_depth24.h).
+ // Only enable the converter when the GPU lacks native D24_UNORM_S8_UINT support.
+ if (!state_.depth_usable(VK_FORMAT_D24_UNORM_S8_UINT)) {
+ std::uint64_t max_storage_range = 1u << 27; // the least Vulkan allows, if the limit cannot be read
+ if (info.physical && info.get_instance_proc) {
+ if (const auto get_props = reinterpret_cast(
+ info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) {
+ VkPhysicalDeviceProperties props{};
+ get_props(info.physical, &props);
+ max_storage_range = props.limits.maxStorageBufferRange;
+ }
+ }
+ state_.context->enable_depth24(get_device, [this](const VkMemoryRequirements& requirements) {
+ return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
+ }, max_storage_range);
+ }
if (info.bindless && state_.context->loaded() && !create_bindless(get_device))
std::fprintf(stderr, "[rt] d3d12: the bindless set 0 could not be created\n");
query_luid_and_clock(get_device);
// Timestamps: what the one VkQueue every D3D12 queue submits to can write.
VkPhysicalDeviceProperties properties{};
device_properties(info.physical, &properties);
+ state_.max_sampler_lod_bias = properties.limits.maxSamplerLodBias;
std::uint32_t family_count = 0;
queue_families(info.physical, &family_count, nullptr);
std::vector families(family_count);
@@ -2896,7 +3037,9 @@ public:
const bool typeless_rgba8 = rd.Format == DXGI_FORMAT_R8G8B8A8_TYPELESS;
const bool typed_rgba8 = rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM ||
rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB || rd.Format == DXGI_FORMAT_R8G8B8A8_UINT;
- if (rd.Format == DXGI_FORMAT_A8_UNORM || (desc && desc->Format == DXGI_FORMAT_A8_UNORM)) {
+ if (rd.Format == DXGI_FORMAT_A8_UNORM || (desc && desc->Format == DXGI_FORMAT_A8_UNORM) ||
+ rd.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP ||
+ (desc && desc->Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP)) {
view = {};
} else if (typeless_rgba8 || typed_rgba8) {
const DXGI_FORMAT requested = desc && desc->Format != DXGI_FORMAT_UNKNOWN ? desc->Format : rd.Format;
@@ -3868,6 +4011,15 @@ public:
s2 |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD;
}
}
+ if (fs->Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && state_.r9g9b9e5_uav_emulated) {
+ s1 |= D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW;
+ s2 |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE;
+ VkFormatProperties r32{};
+ state_.format_properties(state_.info.physical, VK_FORMAT_R32_UINT, &r32);
+ if (r32.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT) {
+ s2 |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD;
+ }
+ }
fs->Support1 = s1;
fs->Support2 = s2;
return d3d12_trace::result(method, S_OK);
@@ -4029,8 +4181,8 @@ private:
return kInvalidAllocation;
}
VkMemoryRequirements need{};
- const VkImageCreateInfo image = texture_create_info(resolved, format, state_.color_attachment_usable(format.format));
- if (!state_.memory_requirements(image, need)) return kInvalidAllocation;
+ const TextureCreateInfo create(resolved, format, state_.color_attachment_usable(format.format));
+ if (!state_.memory_requirements(create.info, 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 top mip of one array slice to fit in 16 tiles of 4 KiB and the resource not to
@@ -4076,7 +4228,7 @@ private:
if (!image_descriptor(resource, view, image)) return;
const leonida::gfx10::ImageWords words = leonida::gfx10::encode(image);
const bool registered = state_.bind_image(words, image, resource.image(), resource.format(),
- resource.aspects(), storage);
+ resource.aspects(), storage, resource.r9g9b9e5_as_r32_uint());
if (leonida::gfx10::multisampled(image.type) && !registered) return;
std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words));
}
@@ -4699,6 +4851,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
enable12.separateDepthStencilLayouts = VK_TRUE;
info.buffer_device_address = chosen12.bufferDeviceAddress == VK_TRUE;
enable12.bufferDeviceAddress = info.buffer_device_address ? VK_TRUE : VK_FALSE;
+ info.storage_buffer_8bit = chosen12.storageBuffer8BitAccess == VK_TRUE;
+ enable12.storageBuffer8BitAccess = info.storage_buffer_8bit;
// Where the GPU has them: what the bindless set 0 needs (VulkanDeviceInfo::bindless), and the sampler features
// D3D12 samplers can ask for.
info.bindless = chosen12.runtimeDescriptorArray && chosen_features.shaderSampledImageArrayDynamicIndexing &&
diff --git a/runtime/shims/dxgi_com.cpp b/runtime/shims/dxgi_com.cpp
index a86c7c419..72b6ef5e8 100644
--- a/runtime/shims/dxgi_com.cpp
+++ b/runtime/shims/dxgi_com.cpp
@@ -4,9 +4,12 @@
#include
#include
#include
+#include